Skip to content

Open source CapCut alternative.

TypeScript

feat(app): a recording keeps the pointer's path beside the movie [rebuild]

David Le046050f65311
diff --git a/apps/Donkey/Sources/Donkey/RecordingControlBarController.swift b/apps/Donkey/Sources/Donkey/RecordingControlBarController.swift
index 7bca88b1..0ca6023b 100644
--- a/apps/Donkey/Sources/Donkey/RecordingControlBarController.swift
+++ b/apps/Donkey/Sources/Donkey/RecordingControlBarController.swift
@@ -71,7 +71,9 @@ final class RecordingControlBarController {
private func frame(for size: CGSize, on screen: NSScreen) -> CGRect {
let x = screen.frame.midX - size.width / 2
- let y = screen.visibleFrame.minY + 24
+ // The panel drops by the hint lane it carries above the bar, so the bar itself sits the
+ // same 24pt off the bottom of the screen whether or not a hint is showing.
+ let y = screen.visibleFrame.minY + 24 - RecordingControlBarView.hintLaneHeight
return CGRect(x: x, y: y, width: size.width, height: size.height)
}
}
diff --git a/apps/Donkey/Sources/Donkey/ScreenRecordingController.swift b/apps/Donkey/Sources/Donkey/ScreenRecordingController.swift
index c82b540d..20ac1f85 100644
--- a/apps/Donkey/Sources/Donkey/ScreenRecordingController.swift
+++ b/apps/Donkey/Sources/Donkey/ScreenRecordingController.swift
@@ -30,6 +30,9 @@ final class ScreenRecordingController {
private let recordingDim = RecordingRegionDimOverlayController()
private var recorder: (any ScreenRecording)?
+ /// The pointer's path through the recording. The video never draws a cursor, so this is the only
+ /// record of where it went — an editor draws its own, or zooms to follow it.
+ private let cursorTrack = CursorTrackRecorder()
private var phase: Phase = .idle
private var armScreen: NSScreen?
private var selectedRegion: (rect: CGRect, displayID: CGDirectDisplayID)?
@@ -213,6 +216,7 @@ final class ScreenRecordingController {
do {
try await recorder.start(configuration)
+ cursorTrack.start(captureRect: Self.captureRectProvider(for: target))
phase = .recording
recordingStart = Date()
model.isRecording = true
@@ -238,8 +242,10 @@ final class ScreenRecordingController {
Task {
defer { finishAfterRecording() }
+ let track = cursorTrack.finish()
do {
let url = try await recorder.stop()
+ Self.writeCursorTrack(track, beside: url)
NSWorkspace.shared.activateFileViewerSelecting([url])
} catch {
model.statusMessage = "Recording failed to finalize."
@@ -249,6 +255,7 @@ final class ScreenRecordingController {
private func handleUnexpectedStop() {
stopTimer()
+ _ = cursorTrack.finish()
recorder = nil
recordingDim.close()
phase = .idle
@@ -284,6 +291,38 @@ final class ScreenRecordingController {
}
}
+ // MARK: - Cursor track
+
+ /// The rect the pointer is measured against, in CoreGraphics global points. It is read on every
+ /// sample, so a window dragged mid-recording keeps yielding positions in its own frame.
+ private static func captureRectProvider(for target: ScreenCaptureTarget) -> @MainActor () -> CGRect? {
+ switch target {
+ case .display(let displayID, let region):
+ let bounds = CGDisplayBounds(displayID)
+ let rect = region.map { $0.offsetBy(dx: bounds.minX, dy: bounds.minY) } ?? bounds
+ return { rect }
+ case .window(let windowID):
+ return { windowFrame(windowID) }
+ }
+ }
+
+ /// A window's frame right now, straight from the window server.
+ private static func windowFrame(_ windowID: CGWindowID) -> CGRect? {
+ guard let list = CGWindowListCopyWindowInfo([.optionIncludingWindow], windowID) as? [[String: Any]],
+ let bounds = list.first?[kCGWindowBounds as String] as? [String: CGFloat],
+ let rect = CGRect(dictionaryRepresentation: bounds as CFDictionary) else {
+ return nil
+ }
+ return rect
+ }
+
+ private static func writeCursorTrack(_ track: CursorTrack, beside movieURL: URL) {
+ guard !track.samples.isEmpty else { return }
+ let encoder = JSONEncoder()
+ guard let data = try? encoder.encode(track) else { return }
+ try? data.write(to: ScreenRecordingDestination.cursorTrackURL(for: movieURL))
+ }
+
// MARK: - Audio inputs
/// The audio sources offered by the input picker: system output (the default), every available
diff --git a/apps/Donkey/Sources/Donkey/WindowPickerOverlayController.swift b/apps/Donkey/Sources/Donkey/WindowPickerOverlayController.swift
index 513457b5..3fe889dc 100644
--- a/apps/Donkey/Sources/Donkey/WindowPickerOverlayController.swift
+++ b/apps/Donkey/Sources/Donkey/WindowPickerOverlayController.swift
@@ -75,12 +75,15 @@ final class WindowPickerOverlayController {
panels.first?.makeKey()
}
- /// The frontmost pickable window containing the cursor. ScreenCaptureKit returns windows
- /// front-to-back, so the first hit is the topmost.
+ /// The window the cursor is actually over: the first hit walking the list front-to-back, so a
+ /// window buried under another one is never offered where the one on top covers it.
private func window(atGlobalCGPoint point: CGPoint) -> PickWindowInfo? {
windows.first { $0.cgFrame.contains(point) }
}
+ /// Pickable windows, front-to-back. ScreenCaptureKit says which windows can be captured and
+ /// where they are; the window server's on-screen list says which one is in front of which, and
+ /// that order is what makes the hit test pick the window the cursor is looking at.
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.
@@ -92,15 +95,27 @@ final class WindowPickerOverlayController {
return []
}
let ownPID = ProcessInfo.processInfo.processIdentifier
- return content.windows.compactMap { window in
+ var capturable: [CGWindowID: CGRect] = [:]
+ for window in content.windows {
guard window.isOnScreen,
window.windowLayer == 0,
window.frame.width >= 40,
window.frame.height >= 40,
window.owningApplication?.processID != ownPID else {
+ continue
+ }
+ capturable[window.windowID] = window.frame
+ }
+ let ordered = CGWindowListCopyWindowInfo(
+ [.optionOnScreenOnly, .excludeDesktopElements],
+ kCGNullWindowID
+ ) as? [[String: Any]] ?? []
+ return ordered.compactMap { entry in
+ guard let id = entry[kCGWindowNumber as String] as? CGWindowID,
+ let frame = capturable[id] else {
return nil
}
- return PickWindowInfo(windowID: window.windowID, cgFrame: window.frame)
+ return PickWindowInfo(windowID: id, cgFrame: frame)
}
}
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/CursorTrack.swift b/apps/Donkey/Sources/DonkeyRuntime/CursorTrack.swift
new file mode 100644
index 00000000..4737add7
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/CursorTrack.swift
@@ -0,0 +1,137 @@
+import CoreGraphics
+import Foundation
+
+/// One reading of the pointer during a recording: where it sat in the recorded frame and whether a
+/// button was down. Positions are fractions of the frame (0…1) from its top-left corner, so a track
+/// survives any scale the video is exported at.
+public struct CursorSample: Codable, Equatable, Sendable {
+ /// Seconds from the moment capture started.
+ public let t: Double
+ public let x: Double
+ public let y: Double
+ /// Any mouse button held at this reading — the beat an auto-zoom wants to land on.
+ public let pressed: Bool
+ /// Whether the pointer was inside the recorded frame. `x`/`y` stay unclamped when it is not, so a
+ /// consumer can tell "just off the left edge" from "parked at the left edge".
+ public let inside: Bool
+
+ public init(t: Double, x: Double, y: Double, pressed: Bool, inside: Bool) {
+ self.t = t
+ self.x = x
+ self.y = y
+ self.pressed = pressed
+ self.inside = inside
+ }
+}
+
+/// The pointer's path through a recording, written beside the `.mov`. The video itself never draws a
+/// cursor: the path rides as data so an editor can draw its own pointer, follow it with a zoom, or
+/// ignore it.
+public struct CursorTrack: Codable, Equatable, Sendable {
+ public static let version = 1
+
+ public let version: Int
+ /// Readings per second the recorder aimed for. Samples are dropped while nothing moves, so the
+ /// gaps between them are uneven; hold the last reading across a gap.
+ public let sampleRate: Int
+ /// The recorded frame in points, the rect the fractions are measured against.
+ public let frameWidth: Double
+ public let frameHeight: Double
+ public let samples: [CursorSample]
+
+ public init(sampleRate: Int, frameSize: CGSize, samples: [CursorSample]) {
+ self.version = Self.version
+ self.sampleRate = sampleRate
+ self.frameWidth = Double(frameSize.width)
+ self.frameHeight = Double(frameSize.height)
+ self.samples = samples
+ }
+}
+
+/// Samples the pointer for the length of a recording. The capture rect is asked for on every reading
+/// rather than captured once, so a window that gets dragged mid-recording still yields positions in
+/// its own frame.
+@MainActor
+public final class CursorTrackRecorder {
+ private let sampleRate: Int
+ private var captureRect: (@MainActor () -> CGRect?)?
+ private var timer: Timer?
+ private var startedAt: Date?
+ private var samples: [CursorSample] = []
+ private var frameSize: CGSize = .zero
+ private var last: (x: Double, y: Double, pressed: Bool, inside: Bool)?
+
+ public init(sampleRate: Int = 60) {
+ self.sampleRate = max(1, sampleRate)
+ }
+
+ /// Begin sampling. `captureRect` answers in CoreGraphics global points (top-left origin) — the
+ /// space `SCWindow.frame` and `CGDisplayBounds` report.
+ public func start(captureRect: @escaping @MainActor () -> CGRect?) {
+ stopTimer()
+ self.captureRect = captureRect
+ samples = []
+ last = nil
+ frameSize = captureRect()?.size ?? .zero
+ startedAt = Date()
+ sample()
+ let timer = Timer(timeInterval: 1.0 / Double(sampleRate), repeats: true) { [weak self] _ in
+ Task { @MainActor in self?.sample() }
+ }
+ RunLoop.main.add(timer, forMode: .common)
+ self.timer = timer
+ }
+
+ /// Stop sampling and hand back what was recorded.
+ public func finish() -> CursorTrack {
+ stopTimer()
+ let track = CursorTrack(sampleRate: sampleRate, frameSize: frameSize, samples: samples)
+ captureRect = nil
+ startedAt = nil
+ samples = []
+ last = nil
+ return track
+ }
+
+ private func sample() {
+ guard let startedAt, let rect = captureRect?(), rect.width > 0, rect.height > 0 else { return }
+ frameSize = rect.size
+ let point = Self.cursorLocation()
+ let x = Double((point.x - rect.minX) / rect.width)
+ let y = Double((point.y - rect.minY) / rect.height)
+ let pressed = Self.anyButtonDown()
+ let inside = (0...1).contains(x) && (0...1).contains(y)
+ let reading = (x: round(x), y: round(y), pressed: pressed, inside: inside)
+ // A still pointer writes nothing: the track keeps its turns, not its idle time.
+ if let last, last == reading { return }
+ last = reading
+ samples.append(CursorSample(
+ t: Date().timeIntervalSince(startedAt),
+ x: reading.x,
+ y: reading.y,
+ pressed: pressed,
+ inside: inside
+ ))
+ }
+
+ /// Fractions to five places — a pixel on an 8K frame, and it keeps the sidecar small.
+ private func round(_ value: Double) -> Double {
+ (value * 100_000).rounded() / 100_000
+ }
+
+ private func stopTimer() {
+ timer?.invalidate()
+ timer = nil
+ }
+
+ /// The pointer in CoreGraphics global points (top-left origin) — the space the capture rects
+ /// come in, straight from the event system with no AppKit in the way.
+ private static func cursorLocation() -> CGPoint {
+ CGEvent(source: nil)?.location ?? .zero
+ }
+
+ private static func anyButtonDown() -> Bool {
+ let buttons: [CGMouseButton] = [.left, .right, .center]
+ return buttons.contains { CGEventSource.buttonState(.combinedSessionState, button: $0) }
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ScreenRecorder.swift b/apps/Donkey/Sources/DonkeyRuntime/ScreenRecorder.swift
index e06fe015..aea5ca41 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ScreenRecorder.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ScreenRecorder.swift
@@ -17,6 +17,8 @@ public struct ScreenRecordingConfiguration: Sendable {
public var capturesMicrophone: Bool
/// The microphone device to capture, when `capturesMicrophone` is set. `nil` uses the system default.
public var microphoneDeviceID: String?
+ /// Whether the pointer is burned into the video. Off: the recording carries the cursor as a
+ /// `CursorTrack` sidecar instead, so an editor can draw it, follow it, or leave it out.
public var showsCursor: Bool
public var frameRate: Int
/// Window IDs to keep out of the capture — our own control bar, so it never appears in the file.
@@ -28,7 +30,7 @@ public struct ScreenRecordingConfiguration: Sendable {
capturesSystemAudio: Bool = true,
capturesMicrophone: Bool = false,
microphoneDeviceID: String? = nil,
- showsCursor: Bool = true,
+ showsCursor: Bool = false,
frameRate: Int = 30,
excludedWindowIDs: [CGWindowID] = [],
outputURL: URL
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ScreenRecordingDestination.swift b/apps/Donkey/Sources/DonkeyRuntime/ScreenRecordingDestination.swift
index f85ac8c4..3c135da4 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ScreenRecordingDestination.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ScreenRecordingDestination.swift
@@ -30,6 +30,12 @@ public enum ScreenRecordingDestination {
return candidate
}
+ /// Where a recording's cursor track goes: the movie's name with a `.cursor.json` tail, so the
+ /// pair travels together and an importer can find one from the other.
+ public static func cursorTrackURL(for movieURL: URL) -> URL {
+ movieURL.deletingPathExtension().appendingPathExtension("cursor.json")
+ }
+
/// The concrete output URL for a recording starting now, on the real Desktop.
public static func makeOutputURL(now: Date = Date()) -> URL {
let fileManager = FileManager.default
diff --git a/apps/Donkey/Sources/DonkeyUI/RecordingControlBarView.swift b/apps/Donkey/Sources/DonkeyUI/RecordingControlBarView.swift
index 1683555c..4da65d69 100644
--- a/apps/Donkey/Sources/DonkeyUI/RecordingControlBarView.swift
+++ b/apps/Donkey/Sources/DonkeyUI/RecordingControlBarView.swift
@@ -1,3 +1,4 @@
+import AppKit
import SwiftUI
/// The three things a screen recording can capture, as the control bar presents them.
@@ -84,9 +85,14 @@ public final class RecordingControlBarModel: ObservableObject {
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)
+ public static let contentSize = CGSize(width: 500, height: 96)
+
+ /// The lane above the bar that holds the hovered control's name, plus the stack spacing under
+ /// it. The controller drops the panel by this much so the bar itself stays put.
+ public static let hintLaneHeight: CGFloat = 24
@ObservedObject private var model: RecordingControlBarModel
+ @State private var hint: String?
public init(model: RecordingControlBarModel) {
self.model = model
@@ -94,6 +100,7 @@ public struct RecordingControlBarView: View {
public var body: some View {
VStack(spacing: 6) {
+ hintLabel
bar
if let statusMessage = model.statusMessage {
Text(statusMessage)
@@ -105,6 +112,21 @@ public struct RecordingControlBarView: View {
.frame(width: Self.contentSize.width, height: Self.contentSize.height, alignment: .top)
}
+ /// The hovered control's name, above the bar. The bar floats over whatever is being recorded
+ /// while Donkey sits inactive in the menu bar, and AppKit holds its own tooltips back for an
+ /// inactive app — so the bar carries its own.
+ private var hintLabel: some View {
+ Text(hint ?? " ")
+ .font(.system(size: 11, weight: .medium))
+ .lineLimit(1)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 2)
+ .background(Capsule().fill(.ultraThinMaterial))
+ .overlay(Capsule().strokeBorder(Color.white.opacity(0.08), lineWidth: 1))
+ .opacity(hint == nil ? 0 : 1)
+ .frame(height: 18)
+ }
+
private var bar: some View {
HStack(spacing: 10) {
iconButton(symbol: "xmark", help: "Close") { model.onClose?() }
@@ -132,7 +154,6 @@ public struct RecordingControlBarView: View {
.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 {
@@ -160,7 +181,7 @@ public struct RecordingControlBarView: View {
.foregroundStyle(isActive ? Color.white : Color.primary)
}
.buttonStyle(.plain)
- .help(mode.tooltip)
+ .hoverHint(mode.tooltip, into: $hint)
}
/// The audio input selector: a sound icon, the current input's name, and a chevron opening the
@@ -196,7 +217,7 @@ public struct RecordingControlBarView: View {
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.fixedSize()
- .help("Audio Input")
+ .hoverHint("Audio Input", into: $hint)
}
private var recordButton: some View {
@@ -219,7 +240,7 @@ public struct RecordingControlBarView: View {
.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")
+ .hoverHint(model.isRecording ? "Stop Recording" : "Start Recording", into: $hint)
}
private func iconButton(symbol: String, help: String, action: @escaping () -> Void) -> some View {
@@ -230,6 +251,58 @@ public struct RecordingControlBarView: View {
.foregroundStyle(Color.primary)
}
.buttonStyle(.plain)
- .help(help)
+ .hoverHint(help, into: $hint)
+ }
+}
+
+private extension View {
+ /// Name this control in the bar's hint lane while the pointer is on it.
+ func hoverHint(_ text: String, into hint: Binding<String?>) -> some View {
+ overlay(
+ HoverTracker { inside in
+ if inside {
+ hint.wrappedValue = text
+ } else if hint.wrappedValue == text {
+ hint.wrappedValue = nil
+ }
+ }
+ )
+ }
+}
+
+/// Pointer enter/exit that fires with Donkey inactive. SwiftUI's `onHover` and AppKit's tooltips
+/// both wait on the active app; the tracking area asks for `.activeAlways` instead. The view hands
+/// every click straight through, so it reports on top of a button without taking its taps.
+private struct HoverTracker: NSViewRepresentable {
+ let onChange: (Bool) -> Void
+
+ func makeNSView(context: Context) -> TrackingView {
+ let view = TrackingView()
+ view.onChange = onChange
+ return view
+ }
+
+ func updateNSView(_ view: TrackingView, context: Context) {
+ view.onChange = onChange
+ }
+
+ final class TrackingView: NSView {
+ var onChange: ((Bool) -> Void)?
+
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for area in trackingAreas { removeTrackingArea(area) }
+ addTrackingArea(NSTrackingArea(
+ rect: bounds,
+ options: [.activeAlways, .mouseEnteredAndExited, .inVisibleRect],
+ owner: self,
+ userInfo: nil
+ ))
+ }
+
+ override func mouseEntered(with event: NSEvent) { onChange?(true) }
+ override func mouseExited(with event: NSEvent) { onChange?(false) }
}
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/CursorTrackTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/CursorTrackTests.swift
new file mode 100644
index 00000000..c19251c1
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/CursorTrackTests.swift
@@ -0,0 +1,34 @@
+@testable import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct CursorTrackTests {
+ @Test
+ func cursorTrackSitsBesideTheMovie() {
+ let movie = URL(fileURLWithPath: "/Users/x/Desktop/Screen Recording 2026-07-21 at 15.24.05.mov")
+
+ let sidecar = ScreenRecordingDestination.cursorTrackURL(for: movie)
+
+ #expect(sidecar.lastPathComponent == "Screen Recording 2026-07-21 at 15.24.05.cursor.json")
+ #expect(sidecar.deletingLastPathComponent() == movie.deletingLastPathComponent())
+ }
+
+ @Test
+ func trackRoundTripsThroughJSON() throws {
+ let track = CursorTrack(
+ sampleRate: 60,
+ frameSize: CGSize(width: 1512, height: 982),
+ samples: [
+ CursorSample(t: 0, x: 0.5, y: 0.25, pressed: false, inside: true),
+ CursorSample(t: 0.5, x: 1.2, y: 0.25, pressed: true, inside: false)
+ ]
+ )
+
+ let decoded = try JSONDecoder().decode(CursorTrack.self, from: JSONEncoder().encode(track))
+
+ #expect(decoded == track)
+ #expect(decoded.version == CursorTrack.version)
+ #expect(decoded.frameWidth == 1512)
+ }
+}
diff --git a/docs/guides/swift-mvc.md b/docs/guides/swift-mvc.md
index f7b0b590..d9c975c3 100644
--- a/docs/guides/swift-mvc.md
+++ b/docs/guides/swift-mvc.md
@@ -39,7 +39,9 @@ Screen recording follows this split: `ScreenRecorder` and its destination types
hold the capture state; `RecordingControlBarView` renders it; the controllers own
AppKit-only work such as the control bar panel, the region and window pickers, and
screen positioning; `DonkeyAppDelegate` bootstraps the feature and the menu bar
-without owning product behavior.
+without owning product behavior. The pointer is captured as data: the stream draws
+no cursor, and `CursorTrackRecorder` samples where it went into a `.cursor.json`
+beside the movie for an editor to draw or follow.
## Review Checklist