6 Copyright (C) 2024 Rubén Beltrán del Río
8 This program is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see https://captura.tranquil.systems.
24 struct CapturaApp: App {
26 @NSApplicationDelegateAdaptor(CapturaAppDelegate.self) var appDelegate
28 var body: some Scene {
31 .handlesExternalEvents(
32 preferring: Set(arrayLiteral: "PreferencesScreen"), allowing: Set(arrayLiteral: "*")
34 .frame(width: 650, height: 450)
36 .handlesExternalEvents(matching: Set(arrayLiteral: "PreferencesScreen"))
37 //.modelContainer(for: CapturaRemoteFile.self)
41 @objc(CapturaAppDelegate) class CapturaAppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate
44 @Environment(\.openURL) var openURL
45 var statusItem: NSStatusItem!
46 var captureState: CaptureState = .idle
47 var recordingWindow: RecordingWindow? = nil
48 var preferencesWindow: PreferencesWindow? = nil
49 var boxListener: AnyCancellable? = nil
50 var popover: NSPopover? = nil
52 var captureSession: CapturaCaptureSession? = nil
53 var images: [CGImage] = []
54 var outputFile: CapturaFile? = nil
55 var gifCallbackTimer = ContinuousClock.now
56 var pixelDensity: CGFloat = 1.0
57 var stopTimer: DispatchWorkItem?
58 var remoteFiles: [CapturaRemoteFile] = []
59 var captureSessionConfiguration: CaptureSessionConfiguration = CaptureSessionConfiguration()
61 // Sparkle Configuration
62 @IBOutlet var checkForUpdatesMenuItem: NSMenuItem!
63 let updaterController: SPUStandardUpdaterController = SPUStandardUpdaterController(
64 startingUpdater: true, updaterDelegate: nil, userDriverDelegate: nil)
66 @objc dynamic var scriptedPreferences: ScriptedPreferences = ScriptedPreferences()
68 func applicationDidFinishLaunching(_ notification: Notification) {
70 NotificationCenter.default.addObserver(
72 selector: #selector(self.didReceiveNotification(_:)),
79 // MARK: - Setup Functions
81 private func setupStatusBar() {
82 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
84 if let button = statusItem.button {
85 button.image = NSImage(named: "Idle")
88 statusItem.isVisible = true
89 statusItem.menu = NSMenu()
90 statusItem.menu?.delegate = self
94 popover?.contentViewController = HelpPopoverViewController()
95 popover?.behavior = .transient
100 private func setupMenu() {
102 statusItem.menu?.removeAllItems()
104 statusItem.menu?.addItem(
106 title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording),
108 if remoteFiles.count > 0 {
109 statusItem.menu?.addItem(NSMenuItem.separator())
110 for remoteFile in remoteFiles {
111 let remoteFileItem = NSMenuItem(
112 title: remoteFile.name, action: #selector(CapturaAppDelegate.onClickRemoteFile),
114 remoteFileItem.representedObject = remoteFile
115 statusItem.menu?.addItem(remoteFileItem)
118 statusItem.menu?.addItem(NSMenuItem.separator())
119 statusItem.menu?.addItem(
121 title: "Open Local Folder", action: #selector(CapturaAppDelegate.onOpenFolder),
123 statusItem.menu?.addItem(NSMenuItem.separator())
125 checkForUpdatesMenuItem = NSMenuItem(
126 title: "Check for Updates",
127 action: #selector(SPUStandardUpdaterController.checkForUpdates(_:)), keyEquivalent: "")
128 checkForUpdatesMenuItem.target = updaterController
129 statusItem.menu?.addItem(checkForUpdatesMenuItem)
131 statusItem.menu?.addItem(
133 title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences),
135 statusItem.menu?.addItem(
136 NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: ""))
139 private func closeWindow() {
140 if let window = NSApplication.shared.windows.first {
145 // MARK: - URL Event Handler
147 func application(_ application: NSApplication, open urls: [URL]) {
148 if CapturaSettings.shouldAllowURLAutomation {
150 if let action = CapturaURLDecoder.decodeParams(url: url) {
152 case let .configure(config):
153 NotificationCenter.default.post(
154 name: .setConfiguration, object: nil,
158 case let .record(config):
159 NotificationCenter.default.post(
160 name: .setCaptureSessionConfiguration, object: nil,
164 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
169 let alert = NSAlert()
170 alert.messageText = "URL Automation Prevented"
171 alert.informativeText =
172 "A website or application attempted to record your screen using URL Automation. If you want to allow this, enable it in Preferences."
173 alert.alertStyle = .warning
174 alert.addButton(withTitle: "OK")
179 // MARK: - UI Event Handlers
181 func menuWillOpen(_ menu: NSMenu) {
182 if captureState != .idle {
183 menu.cancelTrackingWithoutAnimation()
184 if captureState == .selectingArea {
185 NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
188 if captureState == .recording {
189 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
195 @objc private func onClickStartRecording() {
196 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
199 @objc private func onOpenPreferences() {
200 NSApp.activate(ignoringOtherApps: true)
201 if preferencesWindow == nil {
202 preferencesWindow = PreferencesWindow()
204 preferencesWindow?.makeKeyAndOrderFront(nil)
205 preferencesWindow?.orderFrontRegardless()
209 @objc private func onOpenFolder() {
210 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?
211 .appendingPathComponent("captura")
213 NSWorkspace.shared.open(directory)
217 @objc private func onClickRemoteFile(_ sender: NSMenuItem) {
218 if let remoteFile = sender.representedObject as? CapturaRemoteFile {
219 if let urlString = remoteFile.url {
220 if let url = URL(string: urlString) {
221 NSWorkspace.shared.open(url)
227 @objc private func onQuit() {
228 NSApplication.shared.terminate(self)
231 // MARK: - App State Event Listeners
233 @objc func didReceiveNotification(_ notification: Notification) {
234 switch notification.name {
235 case .startAreaSelection:
237 case .startRecording:
241 case .finalizeRecording:
242 DispatchQueue.main.async {
243 self.finalizeRecording()
248 DispatchQueue.main.async {
251 case .failedtoUpload:
252 DispatchQueue.main.async {
256 if let frame = notification.userInfo?["frame"] {
257 receivedFrame(frame as! CVImageBuffer)
259 case .setConfiguration:
260 DispatchQueue.main.async {
261 if let userInfo = notification.userInfo {
262 if let config = userInfo["config"] as? ConfigureAction {
263 self.setConfiguration(config)
267 case .reloadConfiguration:
268 reloadConfiguration()
269 case .setCaptureSessionConfiguration:
270 if let userInfo = notification.userInfo {
271 if let config = userInfo["config"] as? RecordAction {
272 setCaptureSessionConfiguration(config)
275 case .NSManagedObjectContextObjectsDidChange:
276 DispatchQueue.main.async {
277 self.fetchRemoteItems()
285 func startAreaSelection() {
287 if captureState != .selectingArea {
288 captureState = .selectingArea
290 if let button = statusItem.button {
291 let rectInWindow = button.convert(button.bounds, to: nil)
292 let rectInScreen = button.window?.convertToScreen(rectInWindow)
293 NSApp.activate(ignoringOtherApps: true)
294 recordingWindow = RecordingWindow(captureSessionConfiguration, rectInScreen)
295 recordingWindow?.makeKeyAndOrderFront(nil)
296 recordingWindow?.orderFrontRegardless()
297 boxListener = recordingWindow?.recordingContentView.$box
298 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
303 self.helpShown = true
304 self.showPopoverWithMessage("Click here when you're ready to record.")
312 func startRecording() {
313 captureState = .recording
317 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
318 recordingWindow?.recordingContentView.startRecording()
319 if let box = recordingWindow?.recordingContentView.box {
320 if let screen = recordingWindow?.screen {
321 captureSession = CapturaCaptureSession(screen, box: box)
323 if let captureSession {
325 stopTimer = DispatchWorkItem {
328 DispatchQueue.main.asyncAfter(
329 deadline: .now() + Double(captureSessionConfiguration.maxLength), execute: stopTimer!)
331 outputFile = CapturaFile()
332 if captureSessionConfiguration.shouldSaveMp4 {
333 captureSession.startRecording(to: outputFile!.mp4URL)
335 captureSession.startRunning()
341 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
344 func stopRecording() {
345 captureState = .uploading
350 if self.captureSessionConfiguration.shouldSaveGif {
351 if let outputFile = self.outputFile {
352 await GifRenderer.render(
353 self.images, at: self.captureSessionConfiguration.frameRate, to: outputFile.gifURL)
356 let wasSuccessful = await self.uploadOrCopy()
358 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
360 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
365 func finalizeRecording() {
366 captureState = .uploaded
368 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
369 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
376 captureSessionConfiguration = CaptureSessionConfiguration()
380 func receivedFrame(_ frame: CVImageBuffer) {
381 let now = ContinuousClock.now
383 if now - gifCallbackTimer
384 > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate))
386 gifCallbackTimer = now
387 DispatchQueue.main.async {
388 if var cgImage = frame.cgImage {
389 if self.pixelDensity > 1 {
390 cgImage = cgImage.resize(by: self.pixelDensity) ?? cgImage
392 self.images.append(cgImage)
398 func failed(_ requestPermission: Bool = false) {
399 captureState = .error
401 if requestPermission {
402 requestPermissionToRecord()
405 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
406 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
410 func setConfiguration(_ config: ConfigureAction) {
411 CapturaSettings.apply(config)
414 func reloadConfiguration() {
415 self.captureSessionConfiguration = CaptureSessionConfiguration()
418 func setCaptureSessionConfiguration(_ config: RecordAction) {
419 self.captureSessionConfiguration = CaptureSessionConfiguration(from: config)
424 private func fetchRemoteItems() {
425 let viewContext = PersistenceController.shared.container.viewContext
426 let fetchRequest = NSFetchRequest<CapturaRemoteFile>(entityName: "CapturaRemoteFile")
427 fetchRequest.fetchLimit = 5
428 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
430 let results = try? viewContext.fetch(fetchRequest)
431 remoteFiles = results ?? []
434 // MARK: - Presentation Helpers
436 private func requestPermissionToRecord() {
437 showPopoverWithMessage("Please grant Captura permission to record")
439 string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording")
441 NSWorkspace.shared.open(url)
445 private func showPopoverWithMessage(_ message: String) {
446 if let button = statusItem.button {
447 (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message)
448 self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
449 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
450 self.popover?.performClose(nil)
455 private func updateImage() {
456 if let button = statusItem.button {
458 switch captureState {
462 if recordingWindow?.recordingContentView.box != nil {
476 button.image = NSImage(named: image)
480 private func stop() {
482 captureSession?.stopRunning()
484 boxListener?.cancel()
485 recordingWindow?.close()
486 recordingWindow = nil
489 private func uploadOrCopy() async -> Bool {
490 if captureSessionConfiguration.shouldUseBackend {
491 let result = await uploadToBackend()
492 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
497 copyLocalToClipboard()
502 private func copyLocalToClipboard() {
503 let fileType: NSPasteboard.PasteboardType = .init(
504 rawValue: captureSessionConfiguration.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
505 if let url = captureSessionConfiguration.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL
507 if let data = try? Data(contentsOf: url) {
508 let pasteboard = NSPasteboard.general
509 pasteboard.declareTypes([fileType], owner: nil)
510 pasteboard.setData(data, forType: fileType)
515 private func uploadToBackend() async -> Bool {
516 let contentType = captureSessionConfiguration.shouldUploadGif ? "image/gif" : "video/mp4"
517 if let url = captureSessionConfiguration.shouldUploadGif
518 ? outputFile?.gifURL : outputFile?.mp4URL
520 if let data = try? Data(contentsOf: url) {
521 if let remoteUrl = captureSessionConfiguration.backend {
522 var request = URLRequest(url: remoteUrl)
523 request.httpMethod = "POST"
524 request.httpBody = data
525 request.setValue(contentType, forHTTPHeaderField: "Content-Type")
526 request.setValue("Captura/1.0", forHTTPHeaderField: "User-Agent")
529 let (data, response) = try await URLSession.shared.data(for: request)
531 if let httpResponse = response as? HTTPURLResponse {
532 if httpResponse.statusCode == 201 {
533 let answer = try JSONDecoder().decode(BackendResponse.self, from: data)
534 createRemoteFile(answer.url)
545 private func createRemoteFile(_ url: URL) {
546 let viewContext = PersistenceController.shared.container.viewContext
547 let remoteFile = CapturaRemoteFile(context: viewContext)
548 remoteFile.url = url.absoluteString
549 remoteFile.timestamp = Date()
550 try? viewContext.save()
551 let pasteboard = NSPasteboard.general
552 pasteboard.declareTypes([.URL], owner: nil)
553 pasteboard.setString(url.absoluteString, forType: .string)
556 private func deleteLocalFiles() {
557 if captureSessionConfiguration.shouldSaveGif {
558 if let url = outputFile?.gifURL {
559 try? FileManager.default.removeItem(at: url)
562 if captureSessionConfiguration.shouldSaveMp4 {
563 if let url = outputFile?.mp4URL {
564 try? FileManager.default.removeItem(at: url)