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 @objc(CapturaAppDelegate) 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 dynamic var scriptedPreferences: ScriptedPreferences = ScriptedPreferences()
44 func applicationDidFinishLaunching(_ notification: Notification) {
46 NotificationCenter.default.addObserver(
48 selector: #selector(self.didReceiveNotification(_:)),
55 // MARK: - Setup Functions
58 private func setupStatusBar() {
59 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
61 if let button = statusItem.button {
62 button.image = NSImage(systemSymbolName: "rectangle.dashed.badge.record", accessibilityDescription: "Captura")
65 statusItem.isVisible = true
66 statusItem.menu = NSMenu()
67 statusItem.menu?.delegate = self
71 popover?.contentViewController = HelpPopoverViewController()
72 popover?.behavior = .transient
77 private func setupMenu() {
79 statusItem.menu?.removeAllItems()
81 statusItem.menu?.addItem(NSMenuItem(title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording), keyEquivalent: ""))
82 if (remoteFiles.count > 0) {
83 statusItem.menu?.addItem(NSMenuItem.separator())
84 for remoteFile in remoteFiles {
85 let remoteFileItem = NSMenuItem(title: remoteFile.name, action: #selector(CapturaAppDelegate.onClickRemoteFile), keyEquivalent: "")
86 remoteFileItem.representedObject = remoteFile
87 statusItem.menu?.addItem(remoteFileItem)
90 statusItem.menu?.addItem(NSMenuItem.separator())
91 statusItem.menu?.addItem(NSMenuItem(title: "Open Local Folder", action: #selector(CapturaAppDelegate.onOpenFolder), keyEquivalent: ""))
92 statusItem.menu?.addItem(NSMenuItem.separator())
93 statusItem.menu?.addItem(NSMenuItem(title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences), keyEquivalent: ""))
94 statusItem.menu?.addItem(NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: ""))
97 private func closeWindow() {
98 if let window = NSApplication.shared.windows.first {
103 // MARK: - URL Event Handler
105 func application(_ application: NSApplication, open urls: [URL]) {
106 if (CapturaSettings.shouldAllowURLAutomation) {
108 if let action = CapturaURLDecoder.decodeParams(url: url) {
110 case let .configure(config):
111 CapturaSettings.apply(config)
112 case let .record(config):
113 NotificationCenter.default.post(name: .setCaptureSessionConfiguration, object: nil, userInfo: [
116 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
121 let alert = NSAlert()
122 alert.messageText = "URL Automation Prevented"
123 alert.informativeText = "A website or application attempted to record your screen using URL Automation. If you want to allow this, enable it in Preferences."
124 alert.alertStyle = .warning
125 alert.addButton(withTitle: "OK")
130 // MARK: - UI Event Handlers
132 func menuWillOpen(_ menu: NSMenu) {
133 if captureState != .idle {
134 menu.cancelTracking()
135 if captureState == .recording {
136 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
141 @objc private func onClickStartRecording() {
142 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
145 @objc private func onOpenPreferences() {
146 NSApp.activate(ignoringOtherApps: true)
147 if preferencesWindow == nil {
148 preferencesWindow = PreferencesWindow()
150 preferencesWindow?.makeKeyAndOrderFront(nil)
151 preferencesWindow?.orderFrontRegardless()
155 @objc private func onOpenFolder() {
156 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?.appendingPathComponent("captura") {
157 NSWorkspace.shared.open(directory)
161 @objc private func onClickRemoteFile(_ sender: NSMenuItem) {
162 if let remoteFile = sender.representedObject as? CapturaRemoteFile {
163 if let urlString = remoteFile.url {
164 if let url = URL(string: urlString) {
165 NSWorkspace.shared.open(url)
171 @objc private func onQuit() {
172 NSApplication.shared.terminate(self)
175 // MARK: - App State Event Listeners
177 @objc func didReceiveNotification(_ notification: Notification) {
178 switch(notification.name) {
179 case .startAreaSelection:
181 case .startRecording:
185 case .finalizeRecording:
186 DispatchQueue.main.async {
187 self.finalizeRecording()
192 DispatchQueue.main.async {
195 case .failedtoUpload:
196 DispatchQueue.main.async {
200 if let frame = notification.userInfo?["frame"] {
201 receivedFrame(frame as! CVImageBuffer)
203 case .reloadConfiguration:
204 reloadConfiguration()
205 case .setCaptureSessionConfiguration:
206 if let userInfo = notification.userInfo {
207 if let config = userInfo["config"] as? RecordAction {
208 setCaptureSessionConfiguration(config)
211 case .NSManagedObjectContextObjectsDidChange:
212 DispatchQueue.main.async {
213 self.fetchRemoteItems()
222 func startAreaSelection() {
224 if captureState != .selectingArea {
225 captureState = .selectingArea
226 if let button = statusItem.button {
227 let rectInWindow = button.convert(button.bounds, to: nil)
228 let rectInScreen = button.window?.convertToScreen(rectInWindow)
229 NSApp.activate(ignoringOtherApps: true)
230 recordingWindow = RecordingWindow(captureSessionConfiguration, rectInScreen)
231 recordingWindow?.makeKeyAndOrderFront(nil)
232 recordingWindow?.orderFrontRegardless()
233 boxListener = recordingWindow?.recordingContentView.$box
234 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
239 self.helpShown = true
240 self.showPopoverWithMessage("Click here when you're ready to record.")
248 func startRecording() {
249 captureState = .recording
253 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
254 recordingWindow?.recordingContentView.startRecording()
255 if let box = recordingWindow?.recordingContentView.box {
256 if let screen = recordingWindow?.screen {
257 captureSession = CapturaCaptureSession(screen, box: box)
259 if let captureSession {
261 stopTimer = DispatchWorkItem {
264 DispatchQueue.main.asyncAfter(deadline: .now() + Double(captureSessionConfiguration.maxLength), execute: stopTimer!)
266 outputFile = CapturaFile()
267 if captureSessionConfiguration.shouldSaveMp4 {
268 captureSession.startRecording(to: outputFile!.mp4URL)
270 captureSession.startRunning()
276 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
279 func stopRecording() {
280 captureState = .uploading
285 if self.captureSessionConfiguration.shouldSaveGif {
286 if let outputFile = self.outputFile {
287 await GifRenderer.render(self.images, at: self.captureSessionConfiguration.frameRate, to: outputFile.gifURL)
290 let wasSuccessful = await self.uploadOrCopy()
292 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
294 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
299 func finalizeRecording() {
300 captureState = .uploaded
302 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
303 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
310 captureSessionConfiguration = CaptureSessionConfiguration()
314 func receivedFrame(_ frame: CVImageBuffer) {
315 let now = ContinuousClock.now
317 if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate)) {
318 gifCallbackTimer = now
319 DispatchQueue.main.async {
320 if let cgImage = frame.cgImage?.resize(by: self.pixelDensity) {
321 self.images.append(cgImage)
327 func failed(_ requestPermission: Bool = false) {
328 captureState = .error
330 if requestPermission {
331 requestPermissionToRecord()
334 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
335 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
339 func reloadConfiguration() {
340 self.captureSessionConfiguration = CaptureSessionConfiguration()
343 func setCaptureSessionConfiguration(_ config: RecordAction) {
344 self.captureSessionConfiguration = CaptureSessionConfiguration(from: config)
349 private func fetchRemoteItems() {
350 let viewContext = PersistenceController.shared.container.viewContext
351 let fetchRequest = NSFetchRequest<CapturaRemoteFile>(entityName: "CapturaRemoteFile")
352 fetchRequest.fetchLimit = 5
353 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
355 let results = try? viewContext.fetch(fetchRequest)
356 remoteFiles = results ?? []
359 // MARK: - Presentation Helpers
362 private func requestPermissionToRecord() {
363 showPopoverWithMessage("Please grant Captura permission to record")
364 if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording") {
365 NSWorkspace.shared.open(url)
369 private func showPopoverWithMessage(_ message: String) {
370 if let button = statusItem.button {
371 (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message)
372 self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
373 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
374 self.popover?.performClose(nil)
379 private func updateImage() {
380 if let button = statusItem.button {
381 let image: String = switch captureState {
383 "rectangle.dashed.badge.record"
385 "circle.rectangle.dashed"
387 "checkmark.rectangle"
389 "dock.arrow.up.rectangle"
391 "checkmark.rectangle.fill"
393 "xmark.rectangle.fill"
395 button.image = NSImage(systemSymbolName: image, accessibilityDescription: "Captura")
399 private func stop() {
401 captureSession?.stopRunning()
403 boxListener?.cancel()
404 recordingWindow?.close()
405 recordingWindow = nil
408 private func uploadOrCopy() async -> Bool {
409 if captureSessionConfiguration.shouldUseBackend {
410 let result = await uploadToBackend()
411 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
416 copyLocalToClipboard()
421 private func copyLocalToClipboard() {
422 let fileType: NSPasteboard.PasteboardType = .init(rawValue: captureSessionConfiguration.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
423 if let url = captureSessionConfiguration.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL {
424 if let data = try? Data(contentsOf: url) {
425 let pasteboard = NSPasteboard.general
426 pasteboard.declareTypes([fileType], owner: nil)
427 pasteboard.setData(data, forType: fileType)
432 private func uploadToBackend() async -> Bool {
433 let contentType = captureSessionConfiguration.shouldUploadGif ? "image/gif" : "video/mp4"
434 if let url = captureSessionConfiguration.shouldUploadGif ? outputFile?.gifURL : outputFile?.mp4URL {
435 if let data = try? Data(contentsOf: url) {
436 if let remoteUrl = captureSessionConfiguration.backend {
437 var request = URLRequest(url: remoteUrl)
438 request.httpMethod = "POST"
439 request.httpBody = data
440 request.setValue(contentType, forHTTPHeaderField: "Content-Type")
441 request.setValue("Captura/1.0", forHTTPHeaderField: "User-Agent")
444 let (data, response) = try await URLSession.shared.data(for: request)
446 if let httpResponse = response as? HTTPURLResponse {
447 if httpResponse.statusCode == 201 {
448 let answer = try JSONDecoder().decode(BackendResponse.self, from: data)
449 createRemoteFile(answer.url)
460 private func createRemoteFile(_ url: URL) {
461 let viewContext = PersistenceController.shared.container.viewContext
462 let remoteFile = CapturaRemoteFile(context: viewContext)
463 remoteFile.url = url.absoluteString
464 remoteFile.timestamp = Date()
465 try? viewContext.save()
466 let pasteboard = NSPasteboard.general
467 pasteboard.declareTypes([.URL], owner: nil)
468 pasteboard.setString(url.absoluteString, forType: .string)
471 private func deleteLocalFiles() {
472 if captureSessionConfiguration.shouldSaveGif {
473 if let url = outputFile?.gifURL {
474 try? FileManager.default.removeItem(at: url)
477 if captureSessionConfiguration.shouldSaveMp4 {
478 if let url = outputFile?.mp4URL {
479 try? FileManager.default.removeItem(at: url)