Open source CapCut alternative.
TypeScript
feat(app): add menu-bar screen recording controls and pickers [rebuild]
David Le938351c387a7
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swiftindex 3430a096..be1880f4 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift@@ -30,6 +30,9 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {/// Runs the Donkey Cut engine (the local server behind cut.donkeyuse.com) for the app's/// lifetime. Cut is free and standalone, so this starts regardless of sign-in state.private var cutEngineSupervisor: DonkeyCutEngineSupervisor?+ /// The QuickTime-style screen recorder: a menu bar toggle, a center-bottom control bar, and the+ /// region/window pickers. Free and standalone like Cut, so it installs regardless of sign-in.+ private var screenRecordingController: ScreenRecordingController?func applicationDidFinishLaunching(_ notification: Notification) {if ManualCaptureDebugLaunchHandler.shouldHandle(arguments: CommandLine.arguments) {@@ -56,6 +59,8 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {self?.onboardingWindowController?.close()}registerAuthCallbackHandler()+ // Build the recorder before the status item so its menu can drive the "Record Screen" item.+ self.screenRecordingController = ScreenRecordingController()installMainMenu()installStatusItem()startUpdateChecker()@@ -174,6 +179,12 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {},installUpdate: { [weak self] inself?.updateChecker?.installAvailableUpdate()+ },+ screenRecordingMenuItem: { [weak self] in+ self?.screenRecordingController?.menuItem+ },+ toggleScreenRecording: { [weak self] in+ self?.screenRecordingController?.handleMenuItemClicked()})}diff --git a/apps/Donkey/Sources/Donkey/DonkeyOverlayWindowLevels.swift b/apps/Donkey/Sources/Donkey/DonkeyOverlayWindowLevels.swiftindex c4bd1826..e33c6036 100644--- a/apps/Donkey/Sources/Donkey/DonkeyOverlayWindowLevels.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyOverlayWindowLevels.swift@@ -3,4 +3,10 @@ import AppKitenum DonkeyOverlayWindowLevel {static let debugInspection = NSWindow.Level(rawValue: NSWindow.Level.statusBar.rawValue - 1)static let userQuery: NSWindow.Level = .statusBar+ /// The screen-recording region/window picker: a full-screen dim + selection, floating at the+ /// status-bar tier so it paints over app windows while arming a recording.+ static let regionSelection: NSWindow.Level = .statusBar+ /// The recording control bar, one tier above the picker so its buttons stay visible and clickable+ /// over the dim while a region or window is being chosen.+ static let recordingControlBar = NSWindow.Level(rawValue: NSWindow.Level.statusBar.rawValue + 1)}diff --git a/apps/Donkey/Sources/Donkey/DonkeyStatusItemController.swift b/apps/Donkey/Sources/Donkey/DonkeyStatusItemController.swiftindex 773aee37..1b0a2693 100644--- a/apps/Donkey/Sources/Donkey/DonkeyStatusItemController.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyStatusItemController.swift@@ -14,6 +14,11 @@ final class DonkeyStatusItemController: NSObject, NSMenuDelegate {private let statusItem: NSStatusItemprivate let checkForUpdates: () -> Voidprivate let installUpdate: () -> Void+ /// The "Record Screen" menu item's title and glyph, or `nil` to omit it (pre-macOS 15). Read on+ /// each menu open so the item reflects whether a recording is in progress.+ private let screenRecordingMenuItem: () -> (title: String, symbolName: String)?+ /// Opens the recording control bar, or stops an in-progress recording.+ private let toggleScreenRecording: () -> Void/// Latest update-checker state; drives the update section of the menu. Setting it while the menu/// is open refreshes the update row in place, so a user-triggered check spins and resolves without@@ -28,10 +33,14 @@ final class DonkeyStatusItemController: NSObject, NSMenuDelegate {init(checkForUpdates: @escaping () -> Void,- installUpdate: @escaping () -> Void+ installUpdate: @escaping () -> Void,+ screenRecordingMenuItem: @escaping () -> (title: String, symbolName: String)? = { nil },+ toggleScreenRecording: @escaping () -> Void = {}) {self.checkForUpdates = checkForUpdatesself.installUpdate = installUpdate+ self.screenRecordingMenuItem = screenRecordingMenuItem+ self.toggleScreenRecording = toggleScreenRecordingstatusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)super.init()@@ -55,7 +64,15 @@ final class DonkeyStatusItemController: NSObject, NSMenuDelegate {/// The shared item set — Go to App, the update section, and Quit. The status-item menu is/// exactly this; the app main menu appends it after About.func populateMenuItems(in menu: NSMenu) {- menu.addItem(makeItem(title: "Go to App", action: #selector(goToAppAction)))+ menu.addItem(makeItem(title: "Go to App", action: #selector(goToAppAction), image: Self.donkeyMenuIcon()))++ if let recording = screenRecordingMenuItem() {+ menu.addItem(makeItem(+ title: recording.title,+ action: #selector(recordScreenAction),+ image: Self.recordMenuIcon(symbolName: recording.symbolName)+ ))+ }menu.addItem(.separator())menu.addItem(updateItem())@@ -64,12 +81,36 @@ final class DonkeyStatusItemController: NSObject, NSMenuDelegate {menu.addItem(makeItem(title: "Quit Donkey", action: #selector(quitAction), keyEquivalent: "q"))}- private func makeItem(title: String, action: Selector, keyEquivalent: String = "") -> NSMenuItem {+ private func makeItem(+ title: String,+ action: Selector,+ keyEquivalent: String = "",+ image: NSImage? = nil+ ) -> NSMenuItem {let item = NSMenuItem(title: title, action: action, keyEquivalent: keyEquivalent)item.target = self+ item.image = imagereturn item}+ /// The donkey glyph sized for a menu row, as a template so the menu recolors it for light/dark.+ private static func donkeyMenuIcon() -> NSImage {+ let glyph = loadGlyph()+ glyph.size = NSSize(width: 16, height: 16)+ glyph.isTemplate = true+ return glyph+ }++ /// A red record/stop SF Symbol for the "Record Screen" row. Not a template, so the red shows.+ private static func recordMenuIcon(symbolName: String) -> NSImage? {+ let configuration = NSImage.SymbolConfiguration(pointSize: 13, weight: .regular)+ .applying(NSImage.SymbolConfiguration(paletteColors: [.systemRed]))+ let image = NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)?+ .withSymbolConfiguration(configuration)+ image?.isTemplate = false+ return image+ }+/// The update section's single item, following the checker state: "Check for Updates" at rest,/// a spinning progress line while checking or installing, and "Update App" once a check has an/// update waiting — choosing it downloads, installs, quits, and relaunches automatically.@@ -127,6 +168,10 @@ final class DonkeyStatusItemController: NSObject, NSMenuDelegate {}}+ @objc private func recordScreenAction(_ sender: Any?) {+ toggleScreenRecording()+ }+@objc private func goToAppAction(_ sender: Any?) {NSWorkspace.shared.open(Self.appURL)}diff --git a/apps/Donkey/Sources/Donkey/RecordingControlBarController.swift b/apps/Donkey/Sources/Donkey/RecordingControlBarController.swiftnew file mode 100644index 00000000..7bca88b1--- /dev/null+++ b/apps/Donkey/Sources/Donkey/RecordingControlBarController.swift@@ -0,0 +1,77 @@+import AppKit+import DonkeyUI+import SwiftUI++/// The floating QuickTime-style control bar, pinned center-bottom of a screen. A borderless,+/// non-activating panel so its buttons click without stealing focus from the app being recorded. The+/// controller owns framing (`hostingView.sizingOptions = []`) to avoid the SwiftUI layout re-entrancy+/// crash the other overlays document.+@MainActor+final class RecordingControlBarController {+ let model: RecordingControlBarModel+ private var panel: NSPanel?+ private var hostingView: NSHostingView<RecordingControlBarView>?++ init(model: RecordingControlBarModel) {+ self.model = model+ }++ /// The bar's window number, so the recorder can exclude it from the captured video.+ var windowNumber: Int? { panel?.windowNumber }++ func show(on screen: NSScreen) {+ guard panel == nil else {+ reposition(on: screen)+ return+ }+ let size = RecordingControlBarView.contentSize+ let hostingView = NSHostingView(rootView: RecordingControlBarView(model: model))+ hostingView.sizingOptions = []+ hostingView.frame = CGRect(origin: .zero, size: size)+ hostingView.autoresizingMask = [.width, .height]+ hostingView.wantsLayer = true+ hostingView.layer?.backgroundColor = NSColor.clear.cgColor++ let panel = NSPanel(+ contentRect: frame(for: size, on: screen),+ styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered,+ defer: false+ )+ panel.title = "Screen Recording Controls"+ panel.contentView = hostingView+ panel.backgroundColor = .clear+ panel.isOpaque = false+ panel.hasShadow = false+ panel.hidesOnDeactivate = false+ panel.isReleasedWhenClosed = false+ panel.ignoresMouseEvents = false+ panel.level = DonkeyOverlayWindowLevel.recordingControlBar+ panel.collectionBehavior = [+ .canJoinAllSpaces,+ .fullScreenAuxiliary,+ .ignoresCycle,+ .stationary+ ]+ panel.orderFrontRegardless()+ self.panel = panel+ self.hostingView = hostingView+ }++ func reposition(on screen: NSScreen) {+ guard let panel else { return }+ panel.setFrame(frame(for: panel.frame.size, on: screen), display: true)+ }++ func close() {+ panel?.close()+ panel = nil+ hostingView = nil+ }++ private func frame(for size: CGSize, on screen: NSScreen) -> CGRect {+ let x = screen.frame.midX - size.width / 2+ let y = screen.visibleFrame.minY + 24+ return CGRect(x: x, y: y, width: size.width, height: size.height)+ }+}diff --git a/apps/Donkey/Sources/Donkey/RegionSelectionOverlayController.swift b/apps/Donkey/Sources/Donkey/RegionSelectionOverlayController.swiftnew file mode 100644index 00000000..d3f0b4e5--- /dev/null+++ b/apps/Donkey/Sources/Donkey/RegionSelectionOverlayController.swift@@ -0,0 +1,187 @@+import AppKit+import Carbon.HIToolbox+import CoreGraphics++extension NSScreen {+ /// The CoreGraphics display ID backing this screen, for matching against `SCDisplay`/`SCStream`.+ var donkeyDisplayID: CGDirectDisplayID? {+ deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? CGDirectDisplayID+ }+}++/// The drag-to-select region picker. Puts a dimmed, key-capable panel over every display; the user+/// drags a rectangle on one of them and the controller reports it in display-local, top-left points —+/// the coordinate space `SCStreamConfiguration.sourceRect` expects. Escape cancels. v1 keeps a+/// selection within the single display it started on.+@MainActor+final class RegionSelectionOverlayController {+ /// `(region in display-local top-left points, the display it belongs to)`.+ var onSelect: ((CGRect, CGDirectDisplayID) -> Void)?+ var onCancel: (() -> Void)?++ private var panels: [NSPanel] = []++ func begin() {+ close()+ for screen in NSScreen.screens {+ guard let displayID = screen.donkeyDisplayID else { continue }+ let view = RegionSelectionView()+ view.onComplete = { [weak self] rectInView in+ self?.handleComplete(rectInView: rectInView, screenHeight: screen.frame.height, displayID: displayID)+ }+ view.onCancel = { [weak self] in self?.handleCancel() }++ let panel = RegionSelectionPanel(+ contentRect: screen.frame,+ styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered,+ defer: false+ )+ panel.escapeHandler = { [weak self] in self?.handleCancel() }+ panel.contentView = view+ panel.backgroundColor = .clear+ panel.isOpaque = false+ panel.hasShadow = false+ panel.hidesOnDeactivate = false+ panel.isReleasedWhenClosed = false+ panel.ignoresMouseEvents = false+ panel.level = DonkeyOverlayWindowLevel.regionSelection+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .ignoresCycle, .stationary]+ panel.orderFrontRegardless()+ panels.append(panel)+ }+ // Become active so the picker receives mouse + Escape even when another app was frontmost.+ NSApp.activate(ignoringOtherApps: true)+ panels.first?.makeKey()+ }++ func close() {+ for panel in panels { panel.close() }+ panels.removeAll()+ }++ private func handleComplete(rectInView: CGRect, screenHeight: CGFloat, displayID: CGDirectDisplayID) {+ // View coords are bottom-left; flip to display-local top-left for SCStreamConfiguration.sourceRect.+ let region = CGRect(+ x: rectInView.minX,+ y: screenHeight - rectInView.maxY,+ width: rectInView.width,+ height: rectInView.height+ )+ onSelect?(region, displayID)+ }++ private func handleCancel() {+ onCancel?()+ }+}++/// A borderless panel that can become key (so it receives `keyDown`) and routes Escape to a handler,+/// mirroring the `UserQueryPanel` pattern used elsewhere.+private final class RegionSelectionPanel: NSPanel {+ var escapeHandler: (() -> Void)?++ override var canBecomeKey: Bool { true }+ override var canBecomeMain: Bool { true }++ override func sendEvent(_ event: NSEvent) {+ if event.type == .keyDown, event.keyCode == UInt16(kVK_Escape) {+ escapeHandler?()+ return+ }+ super.sendEvent(event)+ }+}++/// Dims its display and tracks a single drag into a selection rectangle, painting the clear cut-out,+/// a 1px frame, and a live pixel readout. Reports the rect (view coords, bottom-left) on mouse-up.+private final class RegionSelectionView: NSView {+ var onComplete: ((CGRect) -> Void)?+ var onCancel: (() -> Void)?++ private var anchor: CGPoint?+ private var selection: CGRect?++ override var acceptsFirstResponder: Bool { true }+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }+ override var isFlipped: Bool { false }++ override func mouseDown(with event: NSEvent) {+ anchor = convert(event.locationInWindow, from: nil)+ selection = nil+ needsDisplay = true+ }++ override func mouseDragged(with event: NSEvent) {+ guard let anchor else { return }+ let current = convert(event.locationInWindow, from: nil)+ selection = CGRect(+ x: min(anchor.x, current.x),+ y: min(anchor.y, current.y),+ width: abs(current.x - anchor.x),+ height: abs(current.y - anchor.y)+ ).intersection(bounds)+ needsDisplay = true+ }++ override func mouseUp(with event: NSEvent) {+ defer { anchor = nil }+ guard let selection, selection.width >= 16, selection.height >= 16 else {+ self.selection = nil+ needsDisplay = true+ return+ }+ onComplete?(selection)+ }++ override func keyDown(with event: NSEvent) {+ if event.keyCode == UInt16(kVK_Escape) {+ onCancel?()+ } else {+ super.keyDown(with: event)+ }+ }++ override func draw(_ dirtyRect: NSRect) {+ NSColor.black.withAlphaComponent(0.35).setFill()+ bounds.fill()++ guard let selection, selection.width > 0, selection.height > 0 else { return }++ // Punch the selection back out of the dim, then frame it.+ NSColor.clear.set()+ selection.fill(using: .copy)+ NSColor.white.withAlphaComponent(0.9).setStroke()+ let framePath = NSBezierPath(rect: selection.insetBy(dx: 0.5, dy: 0.5))+ framePath.lineWidth = 1+ framePath.stroke()++ drawReadout(for: selection)+ }++ private func drawReadout(for rect: CGRect) {+ let scale = window?.backingScaleFactor ?? 2+ let widthPx = Int((rect.width * scale).rounded())+ let heightPx = Int((rect.height * scale).rounded())+ let text = "\(widthPx) × \(heightPx)"+ let attributes: [NSAttributedString.Key: Any] = [+ .font: NSFont.systemFont(ofSize: 12, weight: .medium),+ .foregroundColor: NSColor.white+ ]+ let size = (text as NSString).size(withAttributes: attributes)+ let padding: CGFloat = 6+ let boxWidth = size.width + padding * 2+ let boxHeight = size.height + padding+ var boxX = rect.midX - boxWidth / 2+ var boxY = rect.minY - boxHeight - 6+ boxX = max(4, min(boxX, bounds.width - boxWidth - 4))+ if boxY < 4 { boxY = rect.maxY + 6 }+ let box = CGRect(x: boxX, y: boxY, width: boxWidth, height: boxHeight)+ NSColor.black.withAlphaComponent(0.65).setFill()+ NSBezierPath(roundedRect: box, xRadius: 5, yRadius: 5).fill()+ (text as NSString).draw(+ at: CGPoint(x: box.minX + padding, y: box.minY + padding / 2),+ withAttributes: attributes+ )+ }+}diff --git a/apps/Donkey/Sources/Donkey/ScreenRecordingController.swift b/apps/Donkey/Sources/Donkey/ScreenRecordingController.swiftnew file mode 100644index 00000000..f77f9183--- /dev/null+++ b/apps/Donkey/Sources/Donkey/ScreenRecordingController.swift@@ -0,0 +1,355 @@+import AppKit+import AVFoundation+import DonkeyRuntime+import DonkeyUI+import ScreenCaptureKit++/// Coordinates the whole screen-recording flow: the menu bar toggle, the center-bottom control bar,+/// the region/window pickers, and the recorder. It is the single source of truth — the menu bar glyph+/// and the control bar both render from this controller's state, so a click on either surface routes+/// here and every transition re-renders both.+///+/// ```+/// idle ──click──▶ armed ──Record──▶ recording ──Stop/click──▶ finalizing ──▶ idle (reveal .mov)+/// ▲ │ ▲ pick region / window+/// └── click / ✕ / Esc ┘+/// ```+@MainActor+final class ScreenRecordingController {+ private enum Phase {+ case idle+ case armed+ case recording+ case finalizing+ }++ private let model = RecordingControlBarModel()+ private lazy var controlBar = RecordingControlBarController(model: model)+ private let regionOverlay = RegionSelectionOverlayController()+ private let windowPicker = WindowPickerOverlayController()++ private var recorder: (any ScreenRecording)?+ private var phase: Phase = .idle+ private var armScreen: NSScreen?+ private var selectedRegion: (rect: CGRect, displayID: CGDirectDisplayID)?+ private var selectedWindowID: CGWindowID?+ private var recordingStart: Date?+ private var timer: Timer?++ init() {+ model.onSelectMode = { [weak self] mode in self?.selectMode(mode) }+ model.onSelectAudioInput = { [weak self] id in self?.model.selectedAudioInputID = id }+ model.selectedAudioInputID = "system"+ model.onRecord = { [weak self] in self?.startRecording() }+ model.onStop = { [weak self] in self?.stopRecording() }+ model.onClose = { [weak self] in self?.cancel() }++ regionOverlay.onSelect = { [weak self] rect, displayID in self?.handleRegionSelected(rect, displayID) }+ regionOverlay.onCancel = { [weak self] in self?.handlePickerCancel() }+ windowPicker.onSelect = { [weak self] windowID in self?.handleWindowSelected(windowID) }+ windowPicker.onCancel = { [weak self] in self?.handlePickerCancel() }+ }++ // MARK: - Menu bar routing++ /// The "Record Screen" item's title and matching record/stop glyph for the Donkey menu, or `nil`+ /// to hide it (pre-macOS 15). Reflects state so the same item stops an in-progress recording. Read+ /// fresh each time the menu opens, so it always matches the current phase.+ var menuItem: (title: String, symbolName: String)? {+ guard #available(macOS 15.0, *) else { return nil }+ switch phase {+ case .idle, .armed: return ("Record Screen", "record.circle")+ case .recording, .finalizing: return ("Stop Recording", "stop.circle.fill")+ }+ }++ /// Routes a click on the Donkey menu's "Record Screen" item: open the control bar, or stop a+ /// running recording. The control bar's ✕ is what dismisses an armed-but-not-recording session.+ func handleMenuItemClicked() {+ switch phase {+ case .idle:+ arm()+ case .armed:+ if let screen = armScreen ?? NSScreen.main ?? NSScreen.screens.first {+ controlBar.show(on: screen)+ }+ case .recording:+ stopRecording()+ case .finalizing:+ break+ }+ }++ // MARK: - Arm / cancel++ private func arm() {+ phase = .armed+ selectedRegion = nil+ selectedWindowID = nil+ model.mode = .fullScreen+ model.isRecording = false+ model.isBusy = false+ model.statusMessage = nil+ model.audioInputs = makeAudioInputs()+ if !model.audioInputs.contains(where: { $0.id == model.selectedAudioInputID }) {+ model.selectedAudioInputID = "system"+ }+ armScreen = NSScreen.main ?? NSScreen.screens.first+ refreshCanRecord()+ if let armScreen {+ controlBar.show(on: armScreen)+ }+ // Warm ScreenCaptureKit so the first Record starts without the slow first-call latency.+ prewarmShareableContent()+ }++ private func cancel() {+ teardownOverlays()+ controlBar.close()+ phase = .idle+ selectedRegion = nil+ selectedWindowID = nil+ }++ // MARK: - Mode selection++ private func selectMode(_ mode: RecordingCaptureMode) {+ model.mode = mode+ model.statusMessage = nil+ teardownOverlays()+ switch mode {+ case .fullScreen:+ break+ case .region:+ selectedRegion = nil+ regionOverlay.begin()+ case .window:+ selectedWindowID = nil+ windowPicker.begin()+ }+ refreshCanRecord()+ }++ private func handleRegionSelected(_ rect: CGRect, _ displayID: CGDirectDisplayID) {+ selectedRegion = (rect, displayID)+ refreshCanRecord()+ }++ private func handleWindowSelected(_ windowID: CGWindowID) {+ selectedWindowID = windowID+ windowPicker.close()+ refreshCanRecord()+ }++ /// Escape / dismiss from a picker returns to full-screen, keeping the control bar up.+ private func handlePickerCancel() {+ teardownOverlays()+ model.mode = .fullScreen+ selectedRegion = nil+ selectedWindowID = nil+ refreshCanRecord()+ }++ private func refreshCanRecord() {+ switch model.mode {+ case .fullScreen: model.canRecord = true+ case .region: model.canRecord = selectedRegion != nil+ case .window: model.canRecord = selectedWindowID != nil+ }+ }++ // MARK: - Recording++ private func startRecording() {+ guard phase == .armed else { return }+ guard #available(macOS 15.0, *) else {+ model.statusMessage = "Screen recording requires macOS 15 or later."+ return+ }+ guard let target = resolveTarget() else { return }++ Task { await beginCapture(target: target) }+ }++ @available(macOS 15.0, *)+ private func beginCapture(target: ScreenCaptureTarget) async {+ guard await ensurePermission(.screenRecording, hint: "Allow Screen Recording in System Settings, then try again.") else {+ openScreenRecordingSettings()+ return+ }+ let audio = resolveAudioSelection()+ if audio.capturesMicrophone {+ guard await ensurePermission(.microphone, hint: "Allow Microphone access to include your voice.") else {+ return+ }+ }++ let configuration = ScreenRecordingConfiguration(+ target: target,+ capturesSystemAudio: audio.capturesSystemAudio,+ capturesMicrophone: audio.capturesMicrophone,+ microphoneDeviceID: audio.microphoneDeviceID,+ excludedWindowIDs: controlBar.windowNumber.map { [CGWindowID($0)] } ?? [],+ outputURL: ScreenRecordingDestination.makeOutputURL()+ )++ // The pickers are gone once recording starts; only the (excluded) control bar remains.+ teardownOverlays()++ let recorder = SCRecordingScreenRecorder()+ recorder.onUnexpectedStop = { [weak self] _ in self?.handleUnexpectedStop() }+ self.recorder = recorder++ do {+ try await recorder.start(configuration)+ phase = .recording+ recordingStart = Date()+ model.isRecording = true+ model.statusMessage = nil+ startTimer()+ } catch ScreenRecordingError.screenRecordingPermissionDenied {+ self.recorder = nil+ model.statusMessage = "Allow Screen Recording in System Settings, then try again."+ openScreenRecordingSettings()+ } catch {+ self.recorder = nil+ model.statusMessage = "Couldn't start recording."+ }+ }++ private func stopRecording() {+ guard phase == .recording, let recorder else { return }+ phase = .finalizing+ model.isBusy = true+ stopTimer()++ Task {+ defer { finishAfterRecording() }+ do {+ let url = try await recorder.stop()+ NSWorkspace.shared.activateFileViewerSelecting([url])+ } catch {+ model.statusMessage = "Recording failed to finalize."+ }+ }+ }++ private func handleUnexpectedStop() {+ stopTimer()+ recorder = nil+ phase = .idle+ controlBar.close()+ }++ private func finishAfterRecording() {+ recorder = nil+ recordingStart = nil+ phase = .idle+ model.isRecording = false+ model.isBusy = false+ controlBar.close()+ }++ // MARK: - Target resolution++ private func resolveTarget() -> ScreenCaptureTarget? {+ switch model.mode {+ case .fullScreen:+ guard let displayID = (armScreen ?? NSScreen.main)?.donkeyDisplayID else {+ model.statusMessage = "Couldn't find a display to record."+ return nil+ }+ return .display(displayID: displayID, region: nil)+ case .region:+ guard let selectedRegion else { return nil }+ return .display(displayID: selectedRegion.displayID, region: selectedRegion.rect)+ case .window:+ guard let selectedWindowID else { return nil }+ return .window(windowID: selectedWindowID)+ }+ }++ // MARK: - Audio inputs++ /// The audio sources offered by the input picker: system output (the default), every available+ /// microphone by name, and None.+ private func makeAudioInputs() -> [RecordingAudioInput] {+ var inputs: [RecordingAudioInput] = [+ RecordingAudioInput(id: "system", kind: .systemAudio, label: "System Audio")+ ]+ let discovery = AVCaptureDevice.DiscoverySession(+ deviceTypes: [.microphone, .external],+ mediaType: .audio,+ position: .unspecified+ )+ for device in discovery.devices {+ inputs.append(RecordingAudioInput(+ id: device.uniqueID,+ kind: .microphone(deviceID: device.uniqueID),+ label: device.localizedName+ ))+ }+ inputs.append(RecordingAudioInput(id: "none", kind: .none, label: "None"))+ return inputs+ }++ private func resolveAudioSelection() -> (capturesSystemAudio: Bool, capturesMicrophone: Bool, microphoneDeviceID: String?) {+ let selected = model.audioInputs.first { $0.id == model.selectedAudioInputID }+ guard let kind = selected?.kind else { return (false, false, nil) }+ switch kind {+ case .none: return (false, false, nil)+ case .systemAudio: return (true, false, nil)+ case .microphone(let deviceID): return (false, true, deviceID)+ }+ }++ // MARK: - Permission helpers++ private func ensurePermission(_ permission: SystemPermission, hint: String) async -> Bool {+ if SystemPermissionCoordinator.status(permission) == .granted { return true }+ let granted = await SystemPermissionCoordinator.request(permission)+ if !granted {+ model.statusMessage = hint+ }+ return granted+ }++ private func openScreenRecordingSettings() {+ guard let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture") else {+ return+ }+ NSWorkspace.shared.open(url)+ }++ private func prewarmShareableContent() {+ Task { _ = try? await SCShareableContent.current }+ }++ // MARK: - Timer++ private func startTimer() {+ stopTimer()+ updateElapsed()+ let timer = Timer(timeInterval: 1, repeats: true) { [weak self] _ in+ Task { @MainActor in self?.updateElapsed() }+ }+ RunLoop.main.add(timer, forMode: .common)+ self.timer = timer+ }++ private func stopTimer() {+ timer?.invalidate()+ timer = nil+ }++ private func updateElapsed() {+ guard let recordingStart else { return }+ let seconds = Int(Date().timeIntervalSince(recordingStart))+ model.elapsedText = String(format: "%d:%02d", seconds / 60, seconds % 60)+ }++ private func teardownOverlays() {+ regionOverlay.close()+ windowPicker.close()+ }+}diff --git a/apps/Donkey/Sources/Donkey/WindowPickerOverlayController.swift b/apps/Donkey/Sources/Donkey/WindowPickerOverlayController.swiftnew file mode 100644index 00000000..513457b5--- /dev/null+++ b/apps/Donkey/Sources/Donkey/WindowPickerOverlayController.swift@@ -0,0 +1,208 @@+import AppKit+import Carbon.HIToolbox+import CoreGraphics+import ScreenCaptureKit++/// One selectable on-screen window, in CoreGraphics global coordinates (points, top-left origin) —+/// the space `SCWindow.frame` reports.+private struct PickWindowInfo {+ let windowID: CGWindowID+ let cgFrame: CGRect+}++/// The "record a window" picker. Dims every display, highlights the window under the cursor, and+/// selects it on click — the Cmd+Shift+5 window mode. Windows come from ScreenCaptureKit so the chosen+/// `windowID` matches what the recorder captures. Escape cancels.+@MainActor+final class WindowPickerOverlayController {+ var onSelect: ((CGWindowID) -> Void)?+ var onCancel: (() -> Void)?++ private var panels: [NSPanel] = []+ private var windows: [PickWindowInfo] = []+ /// Height of the primary display, the anchor for flipping between Cocoa (bottom-left) and+ /// CoreGraphics (top-left) global coordinates.+ private var primaryHeight: CGFloat = 0++ func begin() {+ close()+ Task { [weak self] in+ guard let self else { return }+ let windows = await Self.pickableWindows()+ self.presentOverlays(windows: windows)+ }+ }++ func close() {+ for panel in panels { panel.close() }+ panels.removeAll()+ windows = []+ }++ private func presentOverlays(windows: [PickWindowInfo]) {+ self.windows = windows+ primaryHeight = (NSScreen.screens.first { $0.frame.origin == .zero } ?? NSScreen.screens.first)?.frame.height ?? 0++ for screen in NSScreen.screens {+ let view = WindowPickerView()+ view.screenFrame = screen.frame+ view.primaryHeight = primaryHeight+ view.windowProvider = { [weak self] cgCursor in self?.window(atGlobalCGPoint: cgCursor) }+ view.onSelect = { [weak self] windowID in self?.onSelect?(windowID) }+ view.onCancel = { [weak self] in self?.onCancel?() }++ let panel = WindowPickerPanel(+ contentRect: screen.frame,+ styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered,+ defer: false+ )+ panel.escapeHandler = { [weak self] in self?.onCancel?() }+ panel.contentView = view+ panel.backgroundColor = .clear+ panel.isOpaque = false+ panel.hasShadow = false+ panel.hidesOnDeactivate = false+ panel.isReleasedWhenClosed = false+ panel.ignoresMouseEvents = false+ panel.acceptsMouseMovedEvents = true+ panel.level = DonkeyOverlayWindowLevel.regionSelection+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .ignoresCycle, .stationary]+ panel.orderFrontRegardless()+ panels.append(panel)+ }+ NSApp.activate(ignoringOtherApps: true)+ panels.first?.makeKey()+ }++ /// The frontmost pickable window containing the cursor. ScreenCaptureKit returns windows+ /// front-to-back, so the first hit is the topmost.+ private func window(atGlobalCGPoint point: CGPoint) -> PickWindowInfo? {+ windows.first { $0.cgFrame.contains(point) }+ }++ private static func pickableWindows() async -> [PickWindowInfo] {+ // Only visible windows: ask ScreenCaptureKit for on-screen, non-desktop windows, then keep+ // normal app windows (layer 0) that aren't our own and are large enough to aim at.+ guard CGPreflightScreenCaptureAccess(),+ let content = try? await SCShareableContent.excludingDesktopWindows(+ true,+ onScreenWindowsOnly: true+ ) else {+ return []+ }+ let ownPID = ProcessInfo.processInfo.processIdentifier+ return content.windows.compactMap { window in+ guard window.isOnScreen,+ window.windowLayer == 0,+ window.frame.width >= 40,+ window.frame.height >= 40,+ window.owningApplication?.processID != ownPID else {+ return nil+ }+ return PickWindowInfo(windowID: window.windowID, cgFrame: window.frame)+ }+ }+}++private final class WindowPickerPanel: NSPanel {+ var escapeHandler: (() -> Void)?++ override var canBecomeKey: Bool { true }+ override var canBecomeMain: Bool { true }++ override func sendEvent(_ event: NSEvent) {+ if event.type == .keyDown, event.keyCode == UInt16(kVK_Escape) {+ escapeHandler?()+ return+ }+ super.sendEvent(event)+ }+}++/// Dims one display and highlights the hovered window. The controller resolves the window under the+/// cursor from the shared window list; this view only converts coordinates and paints.+private final class WindowPickerView: NSView {+ var screenFrame: CGRect = .zero+ var primaryHeight: CGFloat = 0+ var windowProvider: ((CGPoint) -> PickWindowInfo?)?+ var onSelect: ((CGWindowID) -> Void)?+ var onCancel: (() -> Void)?++ private var highlightRect: CGRect?+ private var hoveredWindowID: CGWindowID?++ override var acceptsFirstResponder: Bool { true }+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }+ override var isFlipped: Bool { false }++ override func updateTrackingAreas() {+ super.updateTrackingAreas()+ for area in trackingAreas { removeTrackingArea(area) }+ addTrackingArea(NSTrackingArea(+ rect: bounds,+ options: [.activeAlways, .mouseMoved, .inVisibleRect],+ owner: self,+ userInfo: nil+ ))+ }++ override func mouseMoved(with event: NSEvent) {+ updateHover()+ }++ override func mouseDown(with event: NSEvent) {+ updateHover()+ if let hoveredWindowID {+ onSelect?(hoveredWindowID)+ }+ }++ override func keyDown(with event: NSEvent) {+ if event.keyCode == UInt16(kVK_Escape) {+ onCancel?()+ } else {+ super.keyDown(with: event)+ }+ }++ private func updateHover() {+ let cursorCocoa = NSEvent.mouseLocation+ let cursorCG = CGPoint(x: cursorCocoa.x, y: primaryHeight - cursorCocoa.y)+ if let window = windowProvider?(cursorCG) {+ hoveredWindowID = window.windowID+ highlightRect = localRect(forGlobalCG: window.cgFrame)+ } else {+ hoveredWindowID = nil+ highlightRect = nil+ }+ needsDisplay = true+ }++ /// CG global (top-left) rect → this view's local coords (bottom-left), via Cocoa global.+ private func localRect(forGlobalCG cgFrame: CGRect) -> CGRect {+ let cocoaGlobalY = primaryHeight - cgFrame.maxY+ return CGRect(+ x: cgFrame.minX - screenFrame.minX,+ y: cocoaGlobalY - screenFrame.minY,+ width: cgFrame.width,+ height: cgFrame.height+ )+ }++ override func draw(_ dirtyRect: NSRect) {+ NSColor.black.withAlphaComponent(0.35).setFill()+ bounds.fill()++ guard let highlightRect else { return }+ let clipped = highlightRect.intersection(bounds)+ guard !clipped.isNull, clipped.width > 0, clipped.height > 0 else { return }++ NSColor.clear.set()+ clipped.fill(using: .copy)+ NSColor.controlAccentColor.setStroke()+ let path = NSBezierPath(rect: clipped.insetBy(dx: 1, dy: 1))+ path.lineWidth = 2+ path.stroke()+ }+}diff --git a/apps/Donkey/Sources/DonkeyUI/RecordingControlBarView.swift b/apps/Donkey/Sources/DonkeyUI/RecordingControlBarView.swiftnew file mode 100644index 00000000..1683555c--- /dev/null+++ b/apps/Donkey/Sources/DonkeyUI/RecordingControlBarView.swift@@ -0,0 +1,235 @@+import SwiftUI++/// The three things a screen recording can capture, as the control bar presents them.+public enum RecordingCaptureMode: String, CaseIterable, Sendable {+ case fullScreen+ case window+ case region++ var symbolName: String {+ switch self {+ case .fullScreen: return "rectangle.inset.filled"+ case .window: return "macwindow"+ case .region: return "rectangle.dashed"+ }+ }++ var tooltip: String {+ switch self {+ case .fullScreen: return "Record Entire Screen"+ case .window: return "Record Window"+ case .region: return "Record Selected Portion"+ }+ }+}++/// One selectable audio source for the input picker: system output, a specific microphone, or none.+public struct RecordingAudioInput: Identifiable, Equatable, Sendable {+ public enum Kind: Equatable, Sendable {+ case none+ case systemAudio+ case microphone(deviceID: String)+ }++ public let id: String+ public let kind: Kind+ public let label: String++ public init(id: String, kind: Kind, label: String) {+ self.id = id+ self.kind = kind+ self.label = label+ }+}++/// State + callbacks the control bar renders from. The controller owns the truth and mutates these;+/// the view is a pure projection and routes taps back through the closures.+@MainActor+public final class RecordingControlBarModel: ObservableObject {+ @Published public var mode: RecordingCaptureMode = .fullScreen+ @Published public var audioInputs: [RecordingAudioInput] = []+ @Published public var selectedAudioInputID = ""+ @Published public var isRecording = false+ @Published public var isBusy = false+ @Published public var elapsedText = "0:00"+ @Published public var canRecord = true+ /// An inline hint under the bar (e.g. a permission prompt); `nil` hides it.+ @Published public var statusMessage: String?++ public var onSelectMode: ((RecordingCaptureMode) -> Void)?+ public var onSelectAudioInput: ((String) -> Void)?+ public var onRecord: (() -> Void)?+ public var onStop: (() -> Void)?+ public var onClose: (() -> Void)?++ public init() {}++ var selectedAudioInput: RecordingAudioInput? {+ audioInputs.first { $0.id == selectedAudioInputID }+ }++ var selectedAudioInputLabel: String {+ selectedAudioInput?.label ?? "None"+ }++ var audioIconName: String {+ guard let kind = selectedAudioInput?.kind else { return "speaker.slash.fill" }+ switch kind {+ case .none: return "speaker.slash.fill"+ case .systemAudio, .microphone: return "speaker.wave.2.fill"+ }+ }+}++public struct RecordingControlBarView: View {+ /// Fixed panel size — the controller owns framing (`hostingView.sizingOptions = []`), so the bar+ /// paints to a known rect rather than pushing its content size back to the window.+ public static let contentSize = CGSize(width: 500, height: 72)++ @ObservedObject private var model: RecordingControlBarModel++ public init(model: RecordingControlBarModel) {+ self.model = model+ }++ public var body: some View {+ VStack(spacing: 6) {+ bar+ if let statusMessage = model.statusMessage {+ Text(statusMessage)+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ .lineLimit(1)+ }+ }+ .frame(width: Self.contentSize.width, height: Self.contentSize.height, alignment: .top)+ }++ private var bar: some View {+ HStack(spacing: 10) {+ iconButton(symbol: "xmark", help: "Close") { model.onClose?() }++ Divider().frame(height: 22)++ if model.isRecording {+ recordingStatus+ } else {+ ForEach(RecordingCaptureMode.allCases, id: \.self) { mode in+ modeButton(mode)+ }+ Divider().frame(height: 22)+ audioInputPicker+ }++ Spacer(minLength: 4)+ recordButton+ }+ .padding(.horizontal, 14)+ .frame(height: 48)+ .background(+ Capsule().fill(.ultraThinMaterial)+ )+ .overlay(+ Capsule().strokeBorder(Color.white.opacity(0.08), lineWidth: 1)+ )+ .shadow(color: .black.opacity(0.35), radius: 12, y: 4)+ }++ private var recordingStatus: some View {+ HStack(spacing: 8) {+ Circle()+ .fill(Color.red)+ .frame(width: 8, height: 8)+ Text(model.elapsedText)+ .font(.system(size: 14, weight: .medium).monospacedDigit())+ }+ }++ private func modeButton(_ mode: RecordingCaptureMode) -> some View {+ let isActive = model.mode == mode+ return Button {+ model.onSelectMode?(mode)+ } label: {+ Image(systemName: mode.symbolName)+ .font(.system(size: 15, weight: .medium))+ .frame(width: 34, height: 30)+ .background(+ RoundedRectangle(cornerRadius: 8)+ .fill(isActive ? Color.accentColor.opacity(0.85) : Color.clear)+ )+ .foregroundStyle(isActive ? Color.white : Color.primary)+ }+ .buttonStyle(.plain)+ .help(mode.tooltip)+ }++ /// The audio input selector: a sound icon, the current input's name, and a chevron opening the+ /// list of sources (System Audio, each microphone, None).+ private var audioInputPicker: some View {+ Menu {+ ForEach(model.audioInputs) { input in+ Button {+ model.onSelectAudioInput?(input.id)+ } label: {+ if input.id == model.selectedAudioInputID {+ Label(input.label, systemImage: "checkmark")+ } else {+ Text(input.label)+ }+ }+ }+ } label: {+ HStack(spacing: 5) {+ Image(systemName: model.audioIconName)+ .font(.system(size: 13, weight: .medium))+ Text(model.selectedAudioInputLabel)+ .font(.system(size: 13))+ .lineLimit(1)+ .truncationMode(.tail)+ .frame(maxWidth: 130, alignment: .leading)+ .fixedSize(horizontal: true, vertical: false)+ Image(systemName: "chevron.down")+ .font(.system(size: 9, weight: .semibold))+ .foregroundStyle(.secondary)+ }+ }+ .menuStyle(.borderlessButton)+ .menuIndicator(.hidden)+ .fixedSize()+ .help("Audio Input")+ }++ private var recordButton: some View {+ Button {+ if model.isRecording { model.onStop?() } else { model.onRecord?() }+ } label: {+ HStack(spacing: 7) {+ RoundedRectangle(cornerRadius: model.isRecording ? 3 : 8)+ .fill(Color.red)+ .frame(width: 16, height: 16)+ Text(model.isRecording ? "Stop" : "Record")+ .font(.system(size: 14, weight: .regular))+ }+ .padding(.horizontal, 14)+ .frame(height: 34)+ .background(+ Capsule().fill(Color.primary.opacity(0.08))+ )+ }+ .buttonStyle(.plain)+ .disabled(model.isBusy || (!model.isRecording && !model.canRecord))+ .opacity(model.isBusy || (!model.isRecording && !model.canRecord) ? 0.5 : 1)+ .help(model.isRecording ? "Stop Recording" : "Start Recording")+ }++ private func iconButton(symbol: String, help: String, action: @escaping () -> Void) -> some View {+ Button(action: action) {+ Image(systemName: symbol)+ .font(.system(size: 14, weight: .medium))+ .frame(width: 30, height: 30)+ .foregroundStyle(Color.primary)+ }+ .buttonStyle(.plain)+ .help(help)+ }+}