8 struct CapturaApp: App {
10 @NSApplicationDelegateAdaptor(CapturaAppDelegate.self) var appDelegate
12 var body: some Scene {
15 .handlesExternalEvents(preferring: Set(arrayLiteral: "PreferencesScreen"), allowing: Set(arrayLiteral: "*"))
16 .frame(width: 650, height: 450)
18 .handlesExternalEvents(matching: Set(arrayLiteral: "PreferencesScreen"))
19 .modelContainer(for: CapturaRemoteFile.self)
23 class CapturaAppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
25 @Environment(\.openURL) var openURL
26 var statusItem: NSStatusItem!
27 var captureState: CaptureState = .idle
28 var recordingWindow: RecordingWindow? = nil
29 var preferencesWindow: PreferencesWindow? = nil
30 var boxListener: AnyCancellable? = nil
31 var popover: NSPopover? = nil
33 var captureSession: CapturaCaptureSession? = nil
34 var images: [CGImage] = []
35 var outputFile: CapturaFile? = nil
36 var gifCallbackTimer = ContinuousClock.now
37 var fps = CapturaSettings.frameRate
38 var pixelDensity: CGFloat = 1.0
39 var stopTimer: DispatchWorkItem?
41 func applicationDidFinishLaunching(_ notification: Notification) {
43 NotificationCenter.default.addObserver(
45 selector: #selector(self.didReceiveNotification(_:)),
51 // MARK: - Setup Functions
54 private func setupMenu() {
55 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
57 if let button = statusItem.button {
58 button.image = NSImage(systemSymbolName: "rectangle.dashed.badge.record", accessibilityDescription: "Captura")
61 statusItem.isVisible = true
62 statusItem.menu = NSMenu()
63 statusItem.menu?.delegate = self
67 popover?.contentViewController = HelpPopoverViewController()
68 popover?.behavior = .transient
71 let recordItem = NSMenuItem(title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording), keyEquivalent: "6")
72 recordItem.keyEquivalentModifierMask = [.command, .shift]
73 statusItem.menu?.addItem(recordItem)
74 statusItem.menu?.addItem(NSMenuItem.separator())
76 let preferencesItem = NSMenuItem(title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences), keyEquivalent: "")
77 statusItem.menu?.addItem(preferencesItem)
79 let quitItem = NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: "")
80 statusItem.menu?.addItem(quitItem)
83 private func closeWindow() {
84 if let window = NSApplication.shared.windows.first {
89 // MARK: - UI Event Handlers
91 func menuWillOpen(_ menu: NSMenu) {
92 if captureState != .idle {
94 if captureState == .recording {
95 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
100 @objc private func onClickStartRecording() {
101 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
104 @objc private func onOpenPreferences() {
105 NSApp.activate(ignoringOtherApps: true)
106 if preferencesWindow == nil {
107 preferencesWindow = PreferencesWindow()
109 preferencesWindow?.makeKeyAndOrderFront(nil)
113 @objc private func onQuit() {
114 NSApplication.shared.terminate(self)
117 // MARK: - App State Event Listeners
119 @objc func didReceiveNotification(_ notification: Notification) {
120 switch(notification.name) {
121 case .startAreaSelection:
123 case .startRecording:
127 case .finalizeRecording:
128 DispatchQueue.main.async {
129 self.finalizeRecording()
136 if let frame = notification.userInfo?["frame"] {
137 receivedFrame(frame as! CVImageBuffer)
145 func startAreaSelection() {
147 NSApp.activate(ignoringOtherApps: true)
148 if captureState != .selectingArea {
149 captureState = .selectingArea
150 if let button = statusItem.button {
151 let rectInWindow = button.convert(button.bounds, to: nil)
152 let rectInScreen = button.window?.convertToScreen(rectInWindow)
153 recordingWindow = RecordingWindow(rectInScreen)
154 boxListener = recordingWindow?.recordingContentView.$box
155 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
160 self.helpShown = true
161 self.showPopoverWithMessage("Click here when you're ready to record.")
169 func startRecording() {
170 captureState = .recording
172 fps = CapturaSettings.frameRate
175 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
176 recordingWindow?.recordingContentView.startRecording()
177 if let box = recordingWindow?.recordingContentView.box {
178 if let screen = recordingWindow?.screen {
179 captureSession = CapturaCaptureSession(screen, box: box)
181 if let captureSession {
183 stopTimer = DispatchWorkItem {
186 DispatchQueue.main.asyncAfter(deadline: .now() + 300, execute: stopTimer!)
188 outputFile = CapturaFile()
189 if CapturaSettings.shouldSaveMp4 {
190 captureSession.startRecording(to: outputFile!.mp4URL)
192 captureSession.startRunning()
198 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
201 func stopRecording() {
202 captureState = .uploading
206 if !CapturaSettings.shouldSaveMp4 {
207 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
212 if let outputFile = self.outputFile {
213 await GifRenderer.render(self.images, at: self.fps, to: outputFile.gifURL)
214 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
219 func finalizeRecording() {
220 captureState = .uploaded
223 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
224 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
234 func receivedFrame(_ frame: CVImageBuffer) {
235 let now = ContinuousClock.now
237 if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(fps)) {
238 gifCallbackTimer = now
239 DispatchQueue.main.async {
240 if let cgImage = frame.cgImage?.resize(by: self.pixelDensity) {
241 self.images.append(cgImage)
247 func failedToStart() {
248 captureState = .error
250 requestPermissionToRecord()
252 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
253 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
257 // MARK: - Presentation Helpers
260 private func requestPermissionToRecord() {
261 showPopoverWithMessage("Please grant Captura permission to record")
262 if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording") {
263 NSWorkspace.shared.open(url)
267 private func showPopoverWithMessage(_ message: String) {
268 if let button = statusItem.button {
269 (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message)
270 self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
271 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
272 self.popover?.performClose(nil)
277 private func updateImage() {
278 if let button = statusItem.button {
279 let image: String = switch captureState {
281 "rectangle.dashed.badge.record"
283 "circle.rectangle.dashed"
285 "checkmark.rectangle"
287 "dock.arrow.up.rectangle"
289 "checkmark.rectangle.fill"
291 "xmark.rectangle.fill"
293 button.image = NSImage(systemSymbolName: image, accessibilityDescription: "Captura")
297 private func stop() {
299 captureSession?.stopRunning()
301 boxListener?.cancel()
302 recordingWindow?.close()
303 recordingWindow = nil
306 private func copyToClipboard() {
307 let fileType: NSPasteboard.PasteboardType = .init(rawValue: CapturaSettings.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
308 if let url = CapturaSettings.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL {
309 if let data = try? Data(contentsOf: url) {
310 let pasteboard = NSPasteboard.general
311 pasteboard.declareTypes([fileType], owner: nil)
312 pasteboard.setData(data, forType: fileType)