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 if let image = NSImage(named: "MenuBar/Idle") {
86 image.isTemplate = true
87 image.size = NSSize(width: 18, height: 18)
92 statusItem.isVisible = true
93 statusItem.menu = NSMenu()
94 statusItem.menu?.delegate = self
98 popover?.contentViewController = HelpPopoverViewController()
99 popover?.behavior = .transient
104 private func setupMenu() {
106 statusItem.menu?.removeAllItems()
108 statusItem.menu?.addItem(
110 title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording),
112 if remoteFiles.count > 0 {
113 statusItem.menu?.addItem(NSMenuItem.separator())
114 for remoteFile in remoteFiles {
115 let remoteFileItem = NSMenuItem(
116 title: remoteFile.name, action: #selector(CapturaAppDelegate.onClickRemoteFile),
118 remoteFileItem.representedObject = remoteFile
119 statusItem.menu?.addItem(remoteFileItem)
122 statusItem.menu?.addItem(NSMenuItem.separator())
123 statusItem.menu?.addItem(
125 title: "Open Local Folder", action: #selector(CapturaAppDelegate.onOpenFolder),
127 statusItem.menu?.addItem(NSMenuItem.separator())
129 checkForUpdatesMenuItem = NSMenuItem(
130 title: "Check for Updates",
131 action: #selector(SPUStandardUpdaterController.checkForUpdates(_:)), keyEquivalent: "")
132 checkForUpdatesMenuItem.target = updaterController
133 statusItem.menu?.addItem(checkForUpdatesMenuItem)
135 statusItem.menu?.addItem(
137 title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences),
139 statusItem.menu?.addItem(
140 NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: ""))
143 private func closeWindow() {
144 if let window = NSApplication.shared.windows.first {
149 // MARK: - URL Event Handler
151 func application(_ application: NSApplication, open urls: [URL]) {
152 if CapturaSettings.shouldAllowURLAutomation {
154 if let action = CapturaURLDecoder.decodeParams(url: url) {
156 case let .configure(config):
157 NotificationCenter.default.post(
158 name: .setConfiguration, object: nil,
162 case let .record(config):
163 NotificationCenter.default.post(
164 name: .setCaptureSessionConfiguration, object: nil,
168 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
173 let alert = NSAlert()
174 alert.messageText = "URL Automation Prevented"
175 alert.informativeText =
176 "A website or application attempted to record your screen using URL Automation. If you want to allow this, enable it in Preferences."
177 alert.alertStyle = .warning
178 alert.addButton(withTitle: "OK")
183 // MARK: - UI Event Handlers
185 func menuWillOpen(_ menu: NSMenu) {
186 if captureState != .idle {
187 menu.cancelTrackingWithoutAnimation()
188 if captureState == .selectingArea {
189 NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
192 if captureState == .recording {
193 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
199 @objc private func onClickStartRecording() {
200 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
203 @objc private func onOpenPreferences() {
204 NSApp.activate(ignoringOtherApps: true)
205 if preferencesWindow == nil {
206 preferencesWindow = PreferencesWindow()
208 preferencesWindow?.makeKeyAndOrderFront(nil)
209 preferencesWindow?.orderFrontRegardless()
213 @objc private func onOpenFolder() {
214 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?
215 .appendingPathComponent("captura")
217 NSWorkspace.shared.open(directory)
221 @objc private func onClickRemoteFile(_ sender: NSMenuItem) {
222 if let remoteFile = sender.representedObject as? CapturaRemoteFile {
223 if let urlString = remoteFile.url {
224 if let url = URL(string: urlString) {
225 NSWorkspace.shared.open(url)
231 @objc private func onQuit() {
232 NSApplication.shared.terminate(self)
235 // MARK: - App State Event Listeners
237 @objc func didReceiveNotification(_ notification: Notification) {
238 switch notification.name {
239 case .startAreaSelection:
241 case .startRecording:
245 case .finalizeRecording:
246 DispatchQueue.main.async {
247 self.finalizeRecording()
252 DispatchQueue.main.async {
255 case .failedtoUpload:
256 DispatchQueue.main.async {
260 if let frame = notification.userInfo?["frame"] {
261 receivedFrame(frame as! CVImageBuffer)
263 case .setConfiguration:
264 DispatchQueue.main.async {
265 if let userInfo = notification.userInfo {
266 if let config = userInfo["config"] as? ConfigureAction {
267 self.setConfiguration(config)
271 case .reloadConfiguration:
272 reloadConfiguration()
273 case .setCaptureSessionConfiguration:
274 if let userInfo = notification.userInfo {
275 if let config = userInfo["config"] as? RecordAction {
276 setCaptureSessionConfiguration(config)
279 case .NSManagedObjectContextObjectsDidChange:
280 DispatchQueue.main.async {
281 self.fetchRemoteItems()
289 func startAreaSelection() {
291 if captureState != .selectingArea {
292 captureState = .selectingArea
294 if let button = statusItem.button {
295 let rectInWindow = button.convert(button.bounds, to: nil)
296 let rectInScreen = button.window?.convertToScreen(rectInWindow)
297 NSApp.activate(ignoringOtherApps: true)
298 recordingWindow = RecordingWindow(captureSessionConfiguration, rectInScreen)
299 recordingWindow?.makeKeyAndOrderFront(nil)
300 recordingWindow?.orderFrontRegardless()
301 boxListener = recordingWindow?.recordingContentView.$box
302 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
307 self.helpShown = true
308 self.showPopoverWithMessage("Click here when you're ready to record.")
316 func startRecording() {
317 captureState = .recording
321 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
322 recordingWindow?.recordingContentView.startRecording()
323 if let box = recordingWindow?.recordingContentView.box {
324 if let screen = recordingWindow?.screen {
325 captureSession = CapturaCaptureSession(screen, box: box)
327 if let captureSession {
329 stopTimer = DispatchWorkItem {
332 DispatchQueue.main.asyncAfter(
333 deadline: .now() + Double(captureSessionConfiguration.maxLength), execute: stopTimer!)
335 outputFile = CapturaFile()
336 if captureSessionConfiguration.shouldSaveMp4 {
337 captureSession.startRecording(to: outputFile!.mp4URL)
339 captureSession.startRunning()
345 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
348 func stopRecording() {
349 captureState = .uploading
354 if self.captureSessionConfiguration.shouldSaveGif {
355 if let outputFile = self.outputFile {
356 await GifRenderer.render(
357 self.images, at: self.captureSessionConfiguration.frameRate, to: outputFile.gifURL)
360 let wasSuccessful = await self.uploadOrCopy()
362 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
364 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
369 func finalizeRecording() {
370 captureState = .uploaded
372 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
373 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
380 captureSessionConfiguration = CaptureSessionConfiguration()
384 func receivedFrame(_ frame: CVImageBuffer) {
385 let now = ContinuousClock.now
387 if now - gifCallbackTimer
388 > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate))
390 gifCallbackTimer = now
391 DispatchQueue.main.async {
392 if var cgImage = frame.cgImage {
393 if self.pixelDensity > 1 {
394 cgImage = cgImage.resize(by: self.pixelDensity) ?? cgImage
396 self.images.append(cgImage)
402 func failed(_ requestPermission: Bool = false) {
403 captureState = .error
405 if requestPermission {
406 requestPermissionToRecord()
409 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
410 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
414 func setConfiguration(_ config: ConfigureAction) {
415 CapturaSettings.apply(config)
418 func reloadConfiguration() {
419 self.captureSessionConfiguration = CaptureSessionConfiguration()
422 func setCaptureSessionConfiguration(_ config: RecordAction) {
423 self.captureSessionConfiguration = CaptureSessionConfiguration(from: config)
428 private func fetchRemoteItems() {
429 let viewContext = PersistenceController.shared.container.viewContext
430 let fetchRequest = NSFetchRequest<CapturaRemoteFile>(entityName: "CapturaRemoteFile")
431 fetchRequest.fetchLimit = 5
432 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
434 let results = try? viewContext.fetch(fetchRequest)
435 remoteFiles = results ?? []
438 // MARK: - Presentation Helpers
440 private func requestPermissionToRecord() {
441 showPopoverWithMessage("Please grant Captura permission to record")
443 string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording")
445 NSWorkspace.shared.open(url)
449 private func showPopoverWithMessage(_ message: String) {
450 if let button = statusItem.button {
451 (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message)
452 self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
453 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
454 self.popover?.performClose(nil)
459 private func updateImage() {
460 if let button = statusItem.button {
462 switch captureState {
466 if recordingWindow?.recordingContentView.box != nil {
467 "MenuBar/Ready to Record"
472 "MenuBar/Stop Frame 1"
474 "MenuBar/Upload Frame 1"
480 if let image = NSImage(named: image) {
481 image.isTemplate = true
482 image.size = NSSize(width: 18, height: 18)
488 private func stop() {
490 captureSession?.stopRunning()
492 boxListener?.cancel()
493 recordingWindow?.close()
494 recordingWindow = nil
497 private func uploadOrCopy() async -> Bool {
498 if captureSessionConfiguration.shouldUseBackend {
499 let result = await uploadToBackend()
500 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
505 copyLocalToClipboard()
510 private func copyLocalToClipboard() {
511 let fileType: NSPasteboard.PasteboardType = .init(
512 rawValue: captureSessionConfiguration.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
513 if let url = captureSessionConfiguration.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL
515 if let data = try? Data(contentsOf: url) {
516 let pasteboard = NSPasteboard.general
517 pasteboard.declareTypes([fileType], owner: nil)
518 pasteboard.setData(data, forType: fileType)
523 private func uploadToBackend() async -> Bool {
524 let contentType = captureSessionConfiguration.shouldUploadGif ? "image/gif" : "video/mp4"
525 if let url = captureSessionConfiguration.shouldUploadGif
526 ? outputFile?.gifURL : outputFile?.mp4URL
528 if let data = try? Data(contentsOf: url) {
529 if let remoteUrl = captureSessionConfiguration.backend {
530 var request = URLRequest(url: remoteUrl)
531 request.httpMethod = "POST"
532 request.httpBody = data
533 request.setValue(contentType, forHTTPHeaderField: "Content-Type")
534 request.setValue("Captura/1.0", forHTTPHeaderField: "User-Agent")
537 let (data, response) = try await URLSession.shared.data(for: request)
539 if let httpResponse = response as? HTTPURLResponse {
540 if httpResponse.statusCode == 201 {
541 let answer = try JSONDecoder().decode(BackendResponse.self, from: data)
542 createRemoteFile(answer.url)
553 private func createRemoteFile(_ url: URL) {
554 let viewContext = PersistenceController.shared.container.viewContext
555 let remoteFile = CapturaRemoteFile(context: viewContext)
556 remoteFile.url = url.absoluteString
557 remoteFile.timestamp = Date()
558 try? viewContext.save()
559 let pasteboard = NSPasteboard.general
560 pasteboard.declareTypes([.URL], owner: nil)
561 pasteboard.setString(url.absoluteString, forType: .string)
564 private func deleteLocalFiles() {
565 if captureSessionConfiguration.shouldSaveGif {
566 if let url = outputFile?.gifURL {
567 try? FileManager.default.removeItem(at: url)
570 if captureSessionConfiguration.shouldSaveMp4 {
571 if let url = outputFile?.mp4URL {
572 try? FileManager.default.removeItem(at: url)