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 pixelDensity: CGFloat = 1.0
38 var stopTimer: DispatchWorkItem?
39 var remoteFiles: [CapturaRemoteFile] = []
40 var captureSessionConfiguration: CaptureSessionConfiguration = CaptureSessionConfiguration()
42 @objc var scriptedPreferences: ScriptedPreferences?
44 func applicationDidFinishLaunching(_ notification: Notification) {
46 NotificationCenter.default.addObserver(
48 selector: #selector(self.didReceiveNotification(_:)),
54 scriptedPreferences = ScriptedPreferences()
57 // MARK: - Setup Functions
60 private func setupStatusBar() {
61 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
63 if let button = statusItem.button {
64 button.image = NSImage(systemSymbolName: "rectangle.dashed.badge.record", accessibilityDescription: "Captura")
67 statusItem.isVisible = true
68 statusItem.menu = NSMenu()
69 statusItem.menu?.delegate = self
73 popover?.contentViewController = HelpPopoverViewController()
74 popover?.behavior = .transient
79 private func setupMenu() {
81 statusItem.menu?.removeAllItems()
83 statusItem.menu?.addItem(NSMenuItem(title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording), keyEquivalent: ""))
84 if (remoteFiles.count > 0) {
85 statusItem.menu?.addItem(NSMenuItem.separator())
86 for remoteFile in remoteFiles {
87 let remoteFileItem = NSMenuItem(title: remoteFile.name, action: #selector(CapturaAppDelegate.onClickRemoteFile), keyEquivalent: "")
88 remoteFileItem.representedObject = remoteFile
89 statusItem.menu?.addItem(remoteFileItem)
92 statusItem.menu?.addItem(NSMenuItem.separator())
93 statusItem.menu?.addItem(NSMenuItem(title: "Open Local Folder", action: #selector(CapturaAppDelegate.onOpenFolder), keyEquivalent: ""))
94 statusItem.menu?.addItem(NSMenuItem.separator())
95 statusItem.menu?.addItem(NSMenuItem(title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences), keyEquivalent: ""))
96 statusItem.menu?.addItem(NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: ""))
99 private func closeWindow() {
100 if let window = NSApplication.shared.windows.first {
105 // MARK: - URL Event Handler
107 func application(_ application: NSApplication, open urls: [URL]) {
108 if (CapturaSettings.shouldAllowURLAutomation) {
110 if let action = CapturaURLDecoder.decodeParams(url: url) {
112 case let .configure(config):
113 CapturaSettings.apply(config)
114 case let .record(config):
115 let config = CaptureSessionConfiguration(from: config)
116 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: [
119 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
124 let alert = NSAlert()
125 alert.messageText = "URL Automation Prevented"
126 alert.informativeText = "A website or application attempted to record your screen using URL Automation. If you want to allow this, enable it in Preferences."
127 alert.alertStyle = .warning
128 alert.addButton(withTitle: "OK")
133 // MARK: - UI Event Handlers
135 func menuWillOpen(_ menu: NSMenu) {
136 if captureState != .idle {
137 menu.cancelTracking()
138 if captureState == .recording {
139 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
144 @objc private func onClickStartRecording() {
145 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
148 @objc private func onOpenPreferences() {
149 NSApp.activate(ignoringOtherApps: true)
150 if preferencesWindow == nil {
151 preferencesWindow = PreferencesWindow()
153 preferencesWindow?.makeKeyAndOrderFront(nil)
154 preferencesWindow?.orderFrontRegardless()
158 @objc private func onOpenFolder() {
159 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?.appendingPathComponent("captura") {
160 NSWorkspace.shared.open(directory)
164 @objc private func onClickRemoteFile(_ sender: NSMenuItem) {
165 if let remoteFile = sender.representedObject as? CapturaRemoteFile {
166 if let urlString = remoteFile.url {
167 if let url = URL(string: urlString) {
168 NSWorkspace.shared.open(url)
174 @objc private func onQuit() {
175 NSApplication.shared.terminate(self)
178 // MARK: - App State Event Listeners
180 @objc func didReceiveNotification(_ notification: Notification) {
181 switch(notification.name) {
182 case .startAreaSelection:
184 case .startRecording:
188 case .finalizeRecording:
189 DispatchQueue.main.async {
190 self.finalizeRecording()
195 DispatchQueue.main.async {
198 case .failedtoUpload:
199 DispatchQueue.main.async {
203 if let frame = notification.userInfo?["frame"] {
204 receivedFrame(frame as! CVImageBuffer)
206 case .reloadConfiguration:
207 reloadConfiguration()
208 case .setCaptureSessionConfiguration:
209 if let userInfo = notification.userInfo {
210 if let config = userInfo["config"] as? RecordAction {
211 setCaptureSessionConfiguration(config)
214 case .NSManagedObjectContextObjectsDidChange:
215 DispatchQueue.main.async {
216 self.fetchRemoteItems()
225 func startAreaSelection() {
227 if captureState != .selectingArea {
228 captureState = .selectingArea
229 if let button = statusItem.button {
230 let rectInWindow = button.convert(button.bounds, to: nil)
231 let rectInScreen = button.window?.convertToScreen(rectInWindow)
232 NSApp.activate(ignoringOtherApps: true)
233 recordingWindow = RecordingWindow(captureSessionConfiguration, rectInScreen)
234 recordingWindow?.makeKeyAndOrderFront(nil)
235 recordingWindow?.orderFrontRegardless()
236 boxListener = recordingWindow?.recordingContentView.$box
237 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
242 self.helpShown = true
243 self.showPopoverWithMessage("Click here when you're ready to record.")
251 func startRecording() {
252 captureState = .recording
256 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
257 recordingWindow?.recordingContentView.startRecording()
258 if let box = recordingWindow?.recordingContentView.box {
259 if let screen = recordingWindow?.screen {
260 captureSession = CapturaCaptureSession(screen, box: box)
262 if let captureSession {
264 stopTimer = DispatchWorkItem {
267 DispatchQueue.main.asyncAfter(deadline: .now() + Double(captureSessionConfiguration.maxLength), execute: stopTimer!)
269 outputFile = CapturaFile()
270 if captureSessionConfiguration.shouldSaveMp4 {
271 captureSession.startRecording(to: outputFile!.mp4URL)
273 captureSession.startRunning()
279 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
282 func stopRecording() {
283 captureState = .uploading
288 if self.captureSessionConfiguration.shouldSaveGif {
289 if let outputFile = self.outputFile {
290 await GifRenderer.render(self.images, at: self.captureSessionConfiguration.frameRate, to: outputFile.gifURL)
293 let wasSuccessful = await self.uploadOrCopy()
295 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
297 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
302 func finalizeRecording() {
303 captureState = .uploaded
305 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
306 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
313 captureSessionConfiguration = CaptureSessionConfiguration()
317 func receivedFrame(_ frame: CVImageBuffer) {
318 let now = ContinuousClock.now
320 if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate)) {
321 gifCallbackTimer = now
322 DispatchQueue.main.async {
323 if let cgImage = frame.cgImage?.resize(by: self.pixelDensity) {
324 self.images.append(cgImage)
330 func failed(_ requestPermission: Bool = false) {
331 captureState = .error
333 if requestPermission {
334 requestPermissionToRecord()
337 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
338 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
342 func reloadConfiguration() {
343 self.captureSessionConfiguration = CaptureSessionConfiguration()
346 func setCaptureSessionConfiguration(_ config: RecordAction) {
347 self.captureSessionConfiguration = CaptureSessionConfiguration(from: config)
352 private func fetchRemoteItems() {
353 let viewContext = PersistenceController.shared.container.viewContext
354 let fetchRequest = NSFetchRequest<CapturaRemoteFile>(entityName: "CapturaRemoteFile")
355 fetchRequest.fetchLimit = 5
356 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
358 let results = try? viewContext.fetch(fetchRequest)
359 remoteFiles = results ?? []
362 // MARK: - Presentation Helpers
365 private func requestPermissionToRecord() {
366 showPopoverWithMessage("Please grant Captura permission to record")
367 if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording") {
368 NSWorkspace.shared.open(url)
372 private func showPopoverWithMessage(_ message: String) {
373 if let button = statusItem.button {
374 (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message)
375 self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
376 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
377 self.popover?.performClose(nil)
382 private func updateImage() {
383 if let button = statusItem.button {
384 let image: String = switch captureState {
386 "rectangle.dashed.badge.record"
388 "circle.rectangle.dashed"
390 "checkmark.rectangle"
392 "dock.arrow.up.rectangle"
394 "checkmark.rectangle.fill"
396 "xmark.rectangle.fill"
398 button.image = NSImage(systemSymbolName: image, accessibilityDescription: "Captura")
402 private func stop() {
404 captureSession?.stopRunning()
406 boxListener?.cancel()
407 recordingWindow?.close()
408 recordingWindow = nil
411 private func uploadOrCopy() async -> Bool {
412 if captureSessionConfiguration.shouldUseBackend {
413 let result = await uploadToBackend()
414 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
419 copyLocalToClipboard()
424 private func copyLocalToClipboard() {
425 let fileType: NSPasteboard.PasteboardType = .init(rawValue: captureSessionConfiguration.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
426 if let url = captureSessionConfiguration.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL {
427 if let data = try? Data(contentsOf: url) {
428 let pasteboard = NSPasteboard.general
429 pasteboard.declareTypes([fileType], owner: nil)
430 pasteboard.setData(data, forType: fileType)
435 private func uploadToBackend() async -> Bool {
436 let contentType = captureSessionConfiguration.shouldUploadGif ? "image/gif" : "video/mp4"
437 if let url = captureSessionConfiguration.shouldUploadGif ? outputFile?.gifURL : outputFile?.mp4URL {
438 if let data = try? Data(contentsOf: url) {
439 if let remoteUrl = captureSessionConfiguration.backend {
440 var request = URLRequest(url: remoteUrl)
441 request.httpMethod = "POST"
442 request.httpBody = data
443 request.setValue(contentType, forHTTPHeaderField: "Content-Type")
444 request.setValue("Captura/1.0", forHTTPHeaderField: "User-Agent")
447 let (data, response) = try await URLSession.shared.data(for: request)
449 if let httpResponse = response as? HTTPURLResponse {
450 if httpResponse.statusCode == 201 {
451 let answer = try JSONDecoder().decode(BackendResponse.self, from: data)
452 createRemoteFile(answer.url)
463 private func createRemoteFile(_ url: URL) {
464 let viewContext = PersistenceController.shared.container.viewContext
465 let remoteFile = CapturaRemoteFile(context: viewContext)
466 remoteFile.url = url.absoluteString
467 remoteFile.timestamp = Date()
468 try? viewContext.save()
469 let pasteboard = NSPasteboard.general
470 pasteboard.declareTypes([.URL], owner: nil)
471 pasteboard.setString(url.absoluteString, forType: .string)
474 private func deleteLocalFiles() {
475 if captureSessionConfiguration.shouldSaveGif {
476 if let url = outputFile?.gifURL {
477 try? FileManager.default.removeItem(at: url)
480 if captureSessionConfiguration.shouldSaveMp4 {
481 if let url = outputFile?.mp4URL {
482 try? FileManager.default.removeItem(at: url)