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?
40 var remoteFiles: [CapturaRemoteFile] = []
42 func applicationDidFinishLaunching(_ notification: Notification) {
44 NotificationCenter.default.addObserver(
46 selector: #selector(self.didReceiveNotification(_:)),
53 // MARK: - Setup Functions
56 private func setupStatusBar() {
57 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
59 if let button = statusItem.button {
60 button.image = NSImage(systemSymbolName: "rectangle.dashed.badge.record", accessibilityDescription: "Captura")
63 statusItem.isVisible = true
64 statusItem.menu = NSMenu()
65 statusItem.menu?.delegate = self
69 popover?.contentViewController = HelpPopoverViewController()
70 popover?.behavior = .transient
75 private func setupMenu() {
77 statusItem.menu?.removeAllItems()
79 statusItem.menu?.addItem(NSMenuItem(title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording), keyEquivalent: ""))
80 if (remoteFiles.count > 0) {
81 statusItem.menu?.addItem(NSMenuItem.separator())
82 for remoteFile in remoteFiles {
83 let remoteFileItem = NSMenuItem(title: remoteFile.name, action: #selector(CapturaAppDelegate.onClickRemoteFile), keyEquivalent: "")
84 remoteFileItem.representedObject = remoteFile
85 statusItem.menu?.addItem(remoteFileItem)
88 statusItem.menu?.addItem(NSMenuItem.separator())
89 statusItem.menu?.addItem(NSMenuItem(title: "Open Local Folder", action: #selector(CapturaAppDelegate.onOpenFolder), keyEquivalent: ""))
90 statusItem.menu?.addItem(NSMenuItem.separator())
91 statusItem.menu?.addItem(NSMenuItem(title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences), keyEquivalent: ""))
92 statusItem.menu?.addItem(NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: ""))
95 private func closeWindow() {
96 if let window = NSApplication.shared.windows.first {
101 // MARK: - UI Event Handlers
103 func menuWillOpen(_ menu: NSMenu) {
104 if captureState != .idle {
105 menu.cancelTracking()
106 if captureState == .recording {
107 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
112 @objc private func onClickStartRecording() {
113 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
116 @objc private func onOpenPreferences() {
117 NSApp.activate(ignoringOtherApps: true)
118 if preferencesWindow == nil {
119 preferencesWindow = PreferencesWindow()
121 preferencesWindow?.makeKeyAndOrderFront(nil)
122 preferencesWindow?.orderFrontRegardless()
126 @objc private func onOpenFolder() {
127 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?.appendingPathComponent("captura") {
128 NSWorkspace.shared.open(directory)
132 @objc private func onClickRemoteFile(_ sender: NSMenuItem) {
133 if let remoteFile = sender.representedObject as? CapturaRemoteFile {
134 if let urlString = remoteFile.url {
135 if let url = URL(string: urlString) {
136 NSWorkspace.shared.open(url)
142 @objc private func onQuit() {
143 NSApplication.shared.terminate(self)
146 // MARK: - App State Event Listeners
148 @objc func didReceiveNotification(_ notification: Notification) {
149 switch(notification.name) {
150 case .startAreaSelection:
152 case .startRecording:
156 case .finalizeRecording:
157 DispatchQueue.main.async {
158 self.finalizeRecording()
163 DispatchQueue.main.async {
166 case .failedtoUpload:
167 DispatchQueue.main.async {
171 if let frame = notification.userInfo?["frame"] {
172 receivedFrame(frame as! CVImageBuffer)
174 case .NSManagedObjectContextObjectsDidChange:
175 DispatchQueue.main.async {
176 self.fetchRemoteItems()
185 func startAreaSelection() {
187 if captureState != .selectingArea {
188 captureState = .selectingArea
189 if let button = statusItem.button {
190 let rectInWindow = button.convert(button.bounds, to: nil)
191 let rectInScreen = button.window?.convertToScreen(rectInWindow)
192 NSApp.activate(ignoringOtherApps: true)
193 recordingWindow = RecordingWindow(rectInScreen)
194 recordingWindow?.makeKeyAndOrderFront(nil)
195 recordingWindow?.orderFrontRegardless()
196 boxListener = recordingWindow?.recordingContentView.$box
197 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
202 self.helpShown = true
203 self.showPopoverWithMessage("Click here when you're ready to record.")
211 func startRecording() {
212 captureState = .recording
214 fps = CapturaSettings.frameRate
217 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
218 recordingWindow?.recordingContentView.startRecording()
219 if let box = recordingWindow?.recordingContentView.box {
220 if let screen = recordingWindow?.screen {
221 captureSession = CapturaCaptureSession(screen, box: box)
223 if let captureSession {
225 stopTimer = DispatchWorkItem {
228 DispatchQueue.main.asyncAfter(deadline: .now() + 300, execute: stopTimer!)
230 outputFile = CapturaFile()
231 if CapturaSettings.shouldSaveMp4 {
232 captureSession.startRecording(to: outputFile!.mp4URL)
234 captureSession.startRunning()
240 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
243 func stopRecording() {
244 captureState = .uploading
249 if CapturaSettings.shouldSaveGif {
250 if let outputFile = self.outputFile {
251 await GifRenderer.render(self.images, at: self.fps, to: outputFile.gifURL)
254 let wasSuccessful = await self.uploadOrCopy()
256 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
258 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
263 func finalizeRecording() {
264 captureState = .uploaded
266 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
267 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
277 func receivedFrame(_ frame: CVImageBuffer) {
278 let now = ContinuousClock.now
280 if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(fps)) {
281 gifCallbackTimer = now
282 DispatchQueue.main.async {
283 if let cgImage = frame.cgImage?.resize(by: self.pixelDensity) {
284 self.images.append(cgImage)
290 func failed(_ requestPermission: Bool = false) {
291 captureState = .error
293 if requestPermission {
294 requestPermissionToRecord()
297 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
298 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
304 private func fetchRemoteItems() {
305 let viewContext = PersistenceController.shared.container.viewContext
306 let fetchRequest = NSFetchRequest<CapturaRemoteFile>(entityName: "CapturaRemoteFile")
307 fetchRequest.fetchLimit = 5
308 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
310 let results = try? viewContext.fetch(fetchRequest)
311 remoteFiles = results ?? []
314 // MARK: - Presentation Helpers
317 private func requestPermissionToRecord() {
318 showPopoverWithMessage("Please grant Captura permission to record")
319 if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording") {
320 NSWorkspace.shared.open(url)
324 private func showPopoverWithMessage(_ message: String) {
325 if let button = statusItem.button {
326 (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message)
327 self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
328 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
329 self.popover?.performClose(nil)
334 private func updateImage() {
335 if let button = statusItem.button {
336 let image: String = switch captureState {
338 "rectangle.dashed.badge.record"
340 "circle.rectangle.dashed"
342 "checkmark.rectangle"
344 "dock.arrow.up.rectangle"
346 "checkmark.rectangle.fill"
348 "xmark.rectangle.fill"
350 button.image = NSImage(systemSymbolName: image, accessibilityDescription: "Captura")
354 private func stop() {
356 captureSession?.stopRunning()
358 boxListener?.cancel()
359 recordingWindow?.close()
360 recordingWindow = nil
363 private func uploadOrCopy() async -> Bool {
364 if CapturaSettings.shouldUseBackend {
365 let result = await uploadToBackend()
366 if result && !CapturaSettings.shouldKeepLocalFiles {
371 copyLocalToClipboard()
376 private func copyLocalToClipboard() {
377 let fileType: NSPasteboard.PasteboardType = .init(rawValue: CapturaSettings.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
378 if let url = CapturaSettings.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL {
379 if let data = try? Data(contentsOf: url) {
380 let pasteboard = NSPasteboard.general
381 pasteboard.declareTypes([fileType], owner: nil)
382 pasteboard.setData(data, forType: fileType)
387 private func uploadToBackend() async -> Bool {
388 let contentType = CapturaSettings.shouldUploadGif ? "image/gif" : "video/mp4"
389 if let url = CapturaSettings.shouldUploadGif ? outputFile?.gifURL : outputFile?.mp4URL {
390 if let data = try? Data(contentsOf: url) {
391 if let remoteUrl = CapturaSettings.backend {
392 var request = URLRequest(url: remoteUrl)
393 request.httpMethod = "POST"
394 request.httpBody = data
395 request.setValue(contentType, forHTTPHeaderField: "Content-Type")
396 request.setValue("Captura/1.0", forHTTPHeaderField: "User-Agent")
399 let (data, response) = try await URLSession.shared.data(for: request)
401 if let httpResponse = response as? HTTPURLResponse {
402 if httpResponse.statusCode == 201 {
403 let answer = try JSONDecoder().decode(BackendResponse.self, from: data)
404 createRemoteFile(answer.url)
415 private func createRemoteFile(_ url: URL) {
416 let viewContext = PersistenceController.shared.container.viewContext
417 let remoteFile = CapturaRemoteFile(context: viewContext)
418 remoteFile.url = url.absoluteString
419 remoteFile.timestamp = Date()
420 try? viewContext.save()
421 let pasteboard = NSPasteboard.general
422 pasteboard.declareTypes([.URL], owner: nil)
423 pasteboard.setString(url.absoluteString, forType: .string)
426 private func deleteLocalFiles() {
427 if CapturaSettings.shouldSaveGif {
428 if let url = outputFile?.gifURL {
429 try? FileManager.default.removeItem(at: url)
432 if CapturaSettings.shouldSaveMp4 {
433 if let url = outputFile?.mp4URL {
434 try? FileManager.default.removeItem(at: url)