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 NotificationCenter.default.post(name: .setConfiguration, object: nil, userInfo: [
114 case let .record(config):
115 NotificationCenter.default.post(name: .setCaptureSessionConfiguration, object: nil, userInfo: [
118 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
123 let alert = NSAlert()
124 alert.messageText = "URL Automation Prevented"
125 alert.informativeText = "A website or application attempted to record your screen using URL Automation. If you want to allow this, enable it in Preferences."
126 alert.alertStyle = .warning
127 alert.addButton(withTitle: "OK")
132 // MARK: - UI Event Handlers
134 func menuWillOpen(_ menu: NSMenu) {
135 if captureState != .idle {
136 menu.cancelTracking()
137 if captureState == .recording {
138 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
143 @objc private func onClickStartRecording() {
144 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
147 @objc private func onOpenPreferences() {
148 NSApp.activate(ignoringOtherApps: true)
149 if preferencesWindow == nil {
150 preferencesWindow = PreferencesWindow()
152 preferencesWindow?.makeKeyAndOrderFront(nil)
153 preferencesWindow?.orderFrontRegardless()
157 @objc private func onOpenFolder() {
158 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?.appendingPathComponent("captura") {
159 NSWorkspace.shared.open(directory)
163 @objc private func onClickRemoteFile(_ sender: NSMenuItem) {
164 if let remoteFile = sender.representedObject as? CapturaRemoteFile {
165 if let urlString = remoteFile.url {
166 if let url = URL(string: urlString) {
167 NSWorkspace.shared.open(url)
173 @objc private func onQuit() {
174 NSApplication.shared.terminate(self)
177 // MARK: - App State Event Listeners
179 @objc func didReceiveNotification(_ notification: Notification) {
180 switch(notification.name) {
181 case .startAreaSelection:
183 case .startRecording:
187 case .finalizeRecording:
188 DispatchQueue.main.async {
189 self.finalizeRecording()
194 DispatchQueue.main.async {
197 case .failedtoUpload:
198 DispatchQueue.main.async {
202 if let frame = notification.userInfo?["frame"] {
203 receivedFrame(frame as! CVImageBuffer)
205 case .setConfiguration:
206 DispatchQueue.main.async {
207 if let userInfo = notification.userInfo {
208 if let config = userInfo["config"] as? ConfigureAction {
209 self.setConfiguration(config)
213 case .reloadConfiguration:
214 reloadConfiguration()
215 case .setCaptureSessionConfiguration:
216 if let userInfo = notification.userInfo {
217 if let config = userInfo["config"] as? RecordAction {
218 setCaptureSessionConfiguration(config)
221 case .NSManagedObjectContextObjectsDidChange:
222 DispatchQueue.main.async {
223 self.fetchRemoteItems()
232 func startAreaSelection() {
234 if captureState != .selectingArea {
235 captureState = .selectingArea
236 if let button = statusItem.button {
237 let rectInWindow = button.convert(button.bounds, to: nil)
238 let rectInScreen = button.window?.convertToScreen(rectInWindow)
239 NSApp.activate(ignoringOtherApps: true)
240 recordingWindow = RecordingWindow(captureSessionConfiguration, rectInScreen)
241 recordingWindow?.makeKeyAndOrderFront(nil)
242 recordingWindow?.orderFrontRegardless()
243 boxListener = recordingWindow?.recordingContentView.$box
244 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
249 self.helpShown = true
250 self.showPopoverWithMessage("Click here when you're ready to record.")
258 func startRecording() {
259 captureState = .recording
263 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
264 recordingWindow?.recordingContentView.startRecording()
265 if let box = recordingWindow?.recordingContentView.box {
266 if let screen = recordingWindow?.screen {
267 captureSession = CapturaCaptureSession(screen, box: box)
269 if let captureSession {
271 stopTimer = DispatchWorkItem {
274 DispatchQueue.main.asyncAfter(deadline: .now() + Double(captureSessionConfiguration.maxLength), execute: stopTimer!)
276 outputFile = CapturaFile()
277 if captureSessionConfiguration.shouldSaveMp4 {
278 captureSession.startRecording(to: outputFile!.mp4URL)
280 captureSession.startRunning()
286 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
289 func stopRecording() {
290 captureState = .uploading
295 if self.captureSessionConfiguration.shouldSaveGif {
296 if let outputFile = self.outputFile {
297 await GifRenderer.render(self.images, at: self.captureSessionConfiguration.frameRate, to: outputFile.gifURL)
300 let wasSuccessful = await self.uploadOrCopy()
302 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
304 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
309 func finalizeRecording() {
310 captureState = .uploaded
312 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
313 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
320 captureSessionConfiguration = CaptureSessionConfiguration()
324 func receivedFrame(_ frame: CVImageBuffer) {
325 let now = ContinuousClock.now
327 if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate)) {
328 gifCallbackTimer = now
329 DispatchQueue.main.async {
330 if let cgImage = frame.cgImage?.resize(by: self.pixelDensity) {
331 self.images.append(cgImage)
337 func failed(_ requestPermission: Bool = false) {
338 captureState = .error
340 if requestPermission {
341 requestPermissionToRecord()
344 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
345 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
349 func setConfiguration(_ config: ConfigureAction) {
350 CapturaSettings.apply(config)
353 func reloadConfiguration() {
354 self.captureSessionConfiguration = CaptureSessionConfiguration()
357 func setCaptureSessionConfiguration(_ config: RecordAction) {
358 self.captureSessionConfiguration = CaptureSessionConfiguration(from: config)
363 private func fetchRemoteItems() {
364 let viewContext = PersistenceController.shared.container.viewContext
365 let fetchRequest = NSFetchRequest<CapturaRemoteFile>(entityName: "CapturaRemoteFile")
366 fetchRequest.fetchLimit = 5
367 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
369 let results = try? viewContext.fetch(fetchRequest)
370 remoteFiles = results ?? []
373 // MARK: - Presentation Helpers
376 private func requestPermissionToRecord() {
377 showPopoverWithMessage("Please grant Captura permission to record")
378 if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording") {
379 NSWorkspace.shared.open(url)
383 private func showPopoverWithMessage(_ message: String) {
384 if let button = statusItem.button {
385 (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message)
386 self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
387 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
388 self.popover?.performClose(nil)
393 private func updateImage() {
394 if let button = statusItem.button {
395 let image: String = switch captureState {
397 "rectangle.dashed.badge.record"
399 "circle.rectangle.dashed"
401 "checkmark.rectangle"
403 "dock.arrow.up.rectangle"
405 "checkmark.rectangle.fill"
407 "xmark.rectangle.fill"
409 button.image = NSImage(systemSymbolName: image, accessibilityDescription: "Captura")
413 private func stop() {
415 captureSession?.stopRunning()
417 boxListener?.cancel()
418 recordingWindow?.close()
419 recordingWindow = nil
422 private func uploadOrCopy() async -> Bool {
423 if captureSessionConfiguration.shouldUseBackend {
424 let result = await uploadToBackend()
425 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
430 copyLocalToClipboard()
435 private func copyLocalToClipboard() {
436 let fileType: NSPasteboard.PasteboardType = .init(rawValue: captureSessionConfiguration.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
437 if let url = captureSessionConfiguration.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL {
438 if let data = try? Data(contentsOf: url) {
439 let pasteboard = NSPasteboard.general
440 pasteboard.declareTypes([fileType], owner: nil)
441 pasteboard.setData(data, forType: fileType)
446 private func uploadToBackend() async -> Bool {
447 let contentType = captureSessionConfiguration.shouldUploadGif ? "image/gif" : "video/mp4"
448 if let url = captureSessionConfiguration.shouldUploadGif ? outputFile?.gifURL : outputFile?.mp4URL {
449 if let data = try? Data(contentsOf: url) {
450 if let remoteUrl = captureSessionConfiguration.backend {
451 var request = URLRequest(url: remoteUrl)
452 request.httpMethod = "POST"
453 request.httpBody = data
454 request.setValue(contentType, forHTTPHeaderField: "Content-Type")
455 request.setValue("Captura/1.0", forHTTPHeaderField: "User-Agent")
458 let (data, response) = try await URLSession.shared.data(for: request)
460 if let httpResponse = response as? HTTPURLResponse {
461 if httpResponse.statusCode == 201 {
462 let answer = try JSONDecoder().decode(BackendResponse.self, from: data)
463 createRemoteFile(answer.url)
474 private func createRemoteFile(_ url: URL) {
475 let viewContext = PersistenceController.shared.container.viewContext
476 let remoteFile = CapturaRemoteFile(context: viewContext)
477 remoteFile.url = url.absoluteString
478 remoteFile.timestamp = Date()
479 try? viewContext.save()
480 let pasteboard = NSPasteboard.general
481 pasteboard.declareTypes([.URL], owner: nil)
482 pasteboard.setString(url.absoluteString, forType: .string)
485 private func deleteLocalFiles() {
486 if captureSessionConfiguration.shouldSaveGif {
487 if let url = outputFile?.gifURL {
488 try? FileManager.default.removeItem(at: url)
491 if captureSessionConfiguration.shouldSaveMp4 {
492 if let url = outputFile?.mp4URL {
493 try? FileManager.default.removeItem(at: url)