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 // Sparkle Configuration
43 @IBOutlet var checkForUpdatesMenuItem: NSMenuItem!
44 let updaterController: SPUStandardUpdaterController = SPUStandardUpdaterController(startingUpdater: true, updaterDelegate: nil, userDriverDelegate: nil)
46 @objc dynamic var scriptedPreferences: ScriptedPreferences = ScriptedPreferences()
48 func applicationDidFinishLaunching(_ notification: Notification) {
50 NotificationCenter.default.addObserver(
52 selector: #selector(self.didReceiveNotification(_:)),
59 // MARK: - Setup Functions
62 private func setupStatusBar() {
63 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
65 if let button = statusItem.button {
66 button.image = NSImage(named: "Idle")
69 statusItem.isVisible = true
70 statusItem.menu = NSMenu()
71 statusItem.menu?.delegate = self
75 popover?.contentViewController = HelpPopoverViewController()
76 popover?.behavior = .transient
81 private func setupMenu() {
83 statusItem.menu?.removeAllItems()
85 statusItem.menu?.addItem(NSMenuItem(title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording), keyEquivalent: ""))
86 if (remoteFiles.count > 0) {
87 statusItem.menu?.addItem(NSMenuItem.separator())
88 for remoteFile in remoteFiles {
89 let remoteFileItem = NSMenuItem(title: remoteFile.name, action: #selector(CapturaAppDelegate.onClickRemoteFile), keyEquivalent: "")
90 remoteFileItem.representedObject = remoteFile
91 statusItem.menu?.addItem(remoteFileItem)
94 statusItem.menu?.addItem(NSMenuItem.separator())
95 statusItem.menu?.addItem(NSMenuItem(title: "Open Local Folder", action: #selector(CapturaAppDelegate.onOpenFolder), keyEquivalent: ""))
96 statusItem.menu?.addItem(NSMenuItem.separator())
98 checkForUpdatesMenuItem = NSMenuItem(title: "Check for Updates", action: #selector(SPUStandardUpdaterController.checkForUpdates(_:)), keyEquivalent: "")
99 checkForUpdatesMenuItem.target = updaterController
100 statusItem.menu?.addItem(checkForUpdatesMenuItem)
102 statusItem.menu?.addItem(NSMenuItem(title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences), keyEquivalent: ""))
103 statusItem.menu?.addItem(NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: ""))
106 private func closeWindow() {
107 if let window = NSApplication.shared.windows.first {
112 // MARK: - URL Event Handler
114 func application(_ application: NSApplication, open urls: [URL]) {
115 if (CapturaSettings.shouldAllowURLAutomation) {
117 if let action = CapturaURLDecoder.decodeParams(url: url) {
119 case let .configure(config):
120 NotificationCenter.default.post(name: .setConfiguration, object: nil, userInfo: [
123 case let .record(config):
124 NotificationCenter.default.post(name: .setCaptureSessionConfiguration, object: nil, userInfo: [
127 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
132 let alert = NSAlert()
133 alert.messageText = "URL Automation Prevented"
134 alert.informativeText = "A website or application attempted to record your screen using URL Automation. If you want to allow this, enable it in Preferences."
135 alert.alertStyle = .warning
136 alert.addButton(withTitle: "OK")
141 // MARK: - UI Event Handlers
143 func menuWillOpen(_ menu: NSMenu) {
144 if captureState != .idle {
145 menu.cancelTrackingWithoutAnimation()
146 if captureState == .selectingArea {
147 NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
150 if captureState == .recording {
151 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
157 @objc private func onClickStartRecording() {
158 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
161 @objc private func onOpenPreferences() {
162 NSApp.activate(ignoringOtherApps: true)
163 if preferencesWindow == nil {
164 preferencesWindow = PreferencesWindow()
166 preferencesWindow?.makeKeyAndOrderFront(nil)
167 preferencesWindow?.orderFrontRegardless()
171 @objc private func onOpenFolder() {
172 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?.appendingPathComponent("captura") {
173 NSWorkspace.shared.open(directory)
177 @objc private func onClickRemoteFile(_ sender: NSMenuItem) {
178 if let remoteFile = sender.representedObject as? CapturaRemoteFile {
179 if let urlString = remoteFile.url {
180 if let url = URL(string: urlString) {
181 NSWorkspace.shared.open(url)
187 @objc private func onQuit() {
188 NSApplication.shared.terminate(self)
191 // MARK: - App State Event Listeners
193 @objc func didReceiveNotification(_ notification: Notification) {
194 switch(notification.name) {
195 case .startAreaSelection:
197 case .startRecording:
201 case .finalizeRecording:
202 DispatchQueue.main.async {
203 self.finalizeRecording()
208 DispatchQueue.main.async {
211 case .failedtoUpload:
212 DispatchQueue.main.async {
216 if let frame = notification.userInfo?["frame"] {
217 receivedFrame(frame as! CVImageBuffer)
219 case .setConfiguration:
220 DispatchQueue.main.async {
221 if let userInfo = notification.userInfo {
222 if let config = userInfo["config"] as? ConfigureAction {
223 self.setConfiguration(config)
227 case .reloadConfiguration:
228 reloadConfiguration()
229 case .setCaptureSessionConfiguration:
230 if let userInfo = notification.userInfo {
231 if let config = userInfo["config"] as? RecordAction {
232 setCaptureSessionConfiguration(config)
235 case .NSManagedObjectContextObjectsDidChange:
236 DispatchQueue.main.async {
237 self.fetchRemoteItems()
246 func startAreaSelection() {
248 if captureState != .selectingArea {
249 captureState = .selectingArea
251 if let button = statusItem.button {
252 let rectInWindow = button.convert(button.bounds, to: nil)
253 let rectInScreen = button.window?.convertToScreen(rectInWindow)
254 NSApp.activate(ignoringOtherApps: true)
255 recordingWindow = RecordingWindow(captureSessionConfiguration, rectInScreen)
256 recordingWindow?.makeKeyAndOrderFront(nil)
257 recordingWindow?.orderFrontRegardless()
258 boxListener = recordingWindow?.recordingContentView.$box
259 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
264 self.helpShown = true
265 self.showPopoverWithMessage("Click here when you're ready to record.")
273 func startRecording() {
274 captureState = .recording
278 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
279 recordingWindow?.recordingContentView.startRecording()
280 if let box = recordingWindow?.recordingContentView.box {
281 if let screen = recordingWindow?.screen {
282 captureSession = CapturaCaptureSession(screen, box: box)
284 if let captureSession {
286 stopTimer = DispatchWorkItem {
289 DispatchQueue.main.asyncAfter(deadline: .now() + Double(captureSessionConfiguration.maxLength), execute: stopTimer!)
291 outputFile = CapturaFile()
292 if captureSessionConfiguration.shouldSaveMp4 {
293 captureSession.startRecording(to: outputFile!.mp4URL)
295 captureSession.startRunning()
301 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
304 func stopRecording() {
305 captureState = .uploading
310 if self.captureSessionConfiguration.shouldSaveGif {
311 if let outputFile = self.outputFile {
312 await GifRenderer.render(self.images, at: self.captureSessionConfiguration.frameRate, to: outputFile.gifURL)
315 let wasSuccessful = await self.uploadOrCopy()
317 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
319 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
324 func finalizeRecording() {
325 captureState = .uploaded
327 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
328 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
335 captureSessionConfiguration = CaptureSessionConfiguration()
339 func receivedFrame(_ frame: CVImageBuffer) {
340 let now = ContinuousClock.now
342 if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate)) {
343 gifCallbackTimer = now
344 DispatchQueue.main.async {
345 if var cgImage = frame.cgImage {
346 if self.pixelDensity > 1 {
347 cgImage = cgImage.resize(by: self.pixelDensity) ?? cgImage
349 self.images.append(cgImage)
355 func failed(_ requestPermission: Bool = false) {
356 captureState = .error
358 if requestPermission {
359 requestPermissionToRecord()
362 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
363 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
367 func setConfiguration(_ config: ConfigureAction) {
368 CapturaSettings.apply(config)
371 func reloadConfiguration() {
372 self.captureSessionConfiguration = CaptureSessionConfiguration()
375 func setCaptureSessionConfiguration(_ config: RecordAction) {
376 self.captureSessionConfiguration = CaptureSessionConfiguration(from: config)
381 private func fetchRemoteItems() {
382 let viewContext = PersistenceController.shared.container.viewContext
383 let fetchRequest = NSFetchRequest<CapturaRemoteFile>(entityName: "CapturaRemoteFile")
384 fetchRequest.fetchLimit = 5
385 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
387 let results = try? viewContext.fetch(fetchRequest)
388 remoteFiles = results ?? []
391 // MARK: - Presentation Helpers
394 private func requestPermissionToRecord() {
395 showPopoverWithMessage("Please grant Captura permission to record")
396 if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording") {
397 NSWorkspace.shared.open(url)
401 private func showPopoverWithMessage(_ message: String) {
402 if let button = statusItem.button {
403 (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message)
404 self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
405 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
406 self.popover?.performClose(nil)
411 private func updateImage() {
412 if let button = statusItem.button {
413 let image: String = switch captureState {
417 if recordingWindow?.recordingContentView.box != nil {
431 button.image = NSImage(named: image)
435 private func stop() {
437 captureSession?.stopRunning()
439 boxListener?.cancel()
440 recordingWindow?.close()
441 recordingWindow = nil
444 private func uploadOrCopy() async -> Bool {
445 if captureSessionConfiguration.shouldUseBackend {
446 let result = await uploadToBackend()
447 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
452 copyLocalToClipboard()
457 private func copyLocalToClipboard() {
458 let fileType: NSPasteboard.PasteboardType = .init(rawValue: captureSessionConfiguration.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
459 if let url = captureSessionConfiguration.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL {
460 if let data = try? Data(contentsOf: url) {
461 let pasteboard = NSPasteboard.general
462 pasteboard.declareTypes([fileType], owner: nil)
463 pasteboard.setData(data, forType: fileType)
468 private func uploadToBackend() async -> Bool {
469 let contentType = captureSessionConfiguration.shouldUploadGif ? "image/gif" : "video/mp4"
470 if let url = captureSessionConfiguration.shouldUploadGif ? outputFile?.gifURL : outputFile?.mp4URL {
471 if let data = try? Data(contentsOf: url) {
472 if let remoteUrl = captureSessionConfiguration.backend {
473 var request = URLRequest(url: remoteUrl)
474 request.httpMethod = "POST"
475 request.httpBody = data
476 request.setValue(contentType, forHTTPHeaderField: "Content-Type")
477 request.setValue("Captura/1.0", forHTTPHeaderField: "User-Agent")
480 let (data, response) = try await URLSession.shared.data(for: request)
482 if let httpResponse = response as? HTTPURLResponse {
483 if httpResponse.statusCode == 201 {
484 let answer = try JSONDecoder().decode(BackendResponse.self, from: data)
485 createRemoteFile(answer.url)
496 private func createRemoteFile(_ url: URL) {
497 let viewContext = PersistenceController.shared.container.viewContext
498 let remoteFile = CapturaRemoteFile(context: viewContext)
499 remoteFile.url = url.absoluteString
500 remoteFile.timestamp = Date()
501 try? viewContext.save()
502 let pasteboard = NSPasteboard.general
503 pasteboard.declareTypes([.URL], owner: nil)
504 pasteboard.setString(url.absoluteString, forType: .string)
507 private func deleteLocalFiles() {
508 if captureSessionConfiguration.shouldSaveGif {
509 if let url = outputFile?.gifURL {
510 try? FileManager.default.removeItem(at: url)
513 if captureSessionConfiguration.shouldSaveMp4 {
514 if let url = outputFile?.mp4URL {
515 try? FileManager.default.removeItem(at: url)