]> git.r.bdr.sh - rbdr/captura/blob - Captura/CapturaApp.swift
Format the code
[rbdr/captura] / Captura / CapturaApp.swift
1 import AVFoundation
2 import Cocoa
3 import Combine
4 import Sparkle
5 /*
6 Copyright (C) 2024 Rubén Beltrán del Río
7
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.
12
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.
17
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.
20 */
21 import SwiftUI
22
23 @main
24 struct CapturaApp: App {
25
26 @NSApplicationDelegateAdaptor(CapturaAppDelegate.self) var appDelegate
27
28 var body: some Scene {
29 WindowGroup {
30 PreferencesScreen()
31 .handlesExternalEvents(
32 preferring: Set(arrayLiteral: "PreferencesScreen"), allowing: Set(arrayLiteral: "*")
33 )
34 .frame(width: 650, height: 450)
35 }
36 .handlesExternalEvents(matching: Set(arrayLiteral: "PreferencesScreen"))
37 //.modelContainer(for: CapturaRemoteFile.self)
38 }
39 }
40
41 @objc(CapturaAppDelegate) class CapturaAppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate
42 {
43
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
51 var helpShown = false
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()
60
61 // Sparkle Configuration
62 @IBOutlet var checkForUpdatesMenuItem: NSMenuItem!
63 let updaterController: SPUStandardUpdaterController = SPUStandardUpdaterController(
64 startingUpdater: true, updaterDelegate: nil, userDriverDelegate: nil)
65
66 @objc dynamic var scriptedPreferences: ScriptedPreferences = ScriptedPreferences()
67
68 func applicationDidFinishLaunching(_ notification: Notification) {
69 setupStatusBar()
70 NotificationCenter.default.addObserver(
71 self,
72 selector: #selector(self.didReceiveNotification(_:)),
73 name: nil,
74 object: nil)
75 closeWindow()
76 fetchRemoteItems()
77 }
78
79 // MARK: - Setup Functions
80
81 private func setupStatusBar() {
82 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
83
84 if let button = statusItem.button {
85 button.image = NSImage(named: "Idle")
86 }
87
88 statusItem.isVisible = true
89 statusItem.menu = NSMenu()
90 statusItem.menu?.delegate = self
91
92 // Create the Popover
93 popover = NSPopover()
94 popover?.contentViewController = HelpPopoverViewController()
95 popover?.behavior = .transient
96
97 setupMenu()
98 }
99
100 private func setupMenu() {
101
102 statusItem.menu?.removeAllItems()
103
104 statusItem.menu?.addItem(
105 NSMenuItem(
106 title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording),
107 keyEquivalent: ""))
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),
113 keyEquivalent: "")
114 remoteFileItem.representedObject = remoteFile
115 statusItem.menu?.addItem(remoteFileItem)
116 }
117 }
118 statusItem.menu?.addItem(NSMenuItem.separator())
119 statusItem.menu?.addItem(
120 NSMenuItem(
121 title: "Open Local Folder", action: #selector(CapturaAppDelegate.onOpenFolder),
122 keyEquivalent: ""))
123 statusItem.menu?.addItem(NSMenuItem.separator())
124
125 checkForUpdatesMenuItem = NSMenuItem(
126 title: "Check for Updates",
127 action: #selector(SPUStandardUpdaterController.checkForUpdates(_:)), keyEquivalent: "")
128 checkForUpdatesMenuItem.target = updaterController
129 statusItem.menu?.addItem(checkForUpdatesMenuItem)
130
131 statusItem.menu?.addItem(
132 NSMenuItem(
133 title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences),
134 keyEquivalent: ""))
135 statusItem.menu?.addItem(
136 NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: ""))
137 }
138
139 private func closeWindow() {
140 if let window = NSApplication.shared.windows.first {
141 window.close()
142 }
143 }
144
145 // MARK: - URL Event Handler
146
147 func application(_ application: NSApplication, open urls: [URL]) {
148 if CapturaSettings.shouldAllowURLAutomation {
149 for url in urls {
150 if let action = CapturaURLDecoder.decodeParams(url: url) {
151 switch action {
152 case let .configure(config):
153 NotificationCenter.default.post(
154 name: .setConfiguration, object: nil,
155 userInfo: [
156 "config": config
157 ])
158 case let .record(config):
159 NotificationCenter.default.post(
160 name: .setCaptureSessionConfiguration, object: nil,
161 userInfo: [
162 "config": config
163 ])
164 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
165 }
166 }
167 }
168 } else {
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")
175 alert.runModal()
176 }
177 }
178
179 // MARK: - UI Event Handlers
180
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)
186 return
187 }
188 if captureState == .recording {
189 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
190 return
191 }
192 }
193 }
194
195 @objc private func onClickStartRecording() {
196 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
197 }
198
199 @objc private func onOpenPreferences() {
200 NSApp.activate(ignoringOtherApps: true)
201 if preferencesWindow == nil {
202 preferencesWindow = PreferencesWindow()
203 } else {
204 preferencesWindow?.makeKeyAndOrderFront(nil)
205 preferencesWindow?.orderFrontRegardless()
206 }
207 }
208
209 @objc private func onOpenFolder() {
210 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?
211 .appendingPathComponent("captura")
212 {
213 NSWorkspace.shared.open(directory)
214 }
215 }
216
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)
222 }
223 }
224 }
225 }
226
227 @objc private func onQuit() {
228 NSApplication.shared.terminate(self)
229 }
230
231 // MARK: - App State Event Listeners
232
233 @objc func didReceiveNotification(_ notification: Notification) {
234 switch notification.name {
235 case .startAreaSelection:
236 startAreaSelection()
237 case .startRecording:
238 startRecording()
239 case .stopRecording:
240 stopRecording()
241 case .finalizeRecording:
242 DispatchQueue.main.async {
243 self.finalizeRecording()
244 }
245 case .reset:
246 reset()
247 case .failedToStart:
248 DispatchQueue.main.async {
249 self.failed(true)
250 }
251 case .failedtoUpload:
252 DispatchQueue.main.async {
253 self.failed()
254 }
255 case .receivedFrame:
256 if let frame = notification.userInfo?["frame"] {
257 receivedFrame(frame as! CVImageBuffer)
258 }
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)
264 }
265 }
266 }
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)
273 }
274 }
275 case .NSManagedObjectContextObjectsDidChange:
276 DispatchQueue.main.async {
277 self.fetchRemoteItems()
278 self.setupMenu()
279 }
280 default:
281 return
282 }
283 }
284
285 func startAreaSelection() {
286 helpShown = false
287 if captureState != .selectingArea {
288 captureState = .selectingArea
289 updateImage()
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)
299 .sink { newValue in
300 if newValue != nil {
301 self.updateImage()
302 if !self.helpShown {
303 self.helpShown = true
304 self.showPopoverWithMessage("Click here when you're ready to record.")
305 }
306 }
307 }
308 }
309 }
310 }
311
312 func startRecording() {
313 captureState = .recording
314 updateImage()
315 outputFile = nil
316 images = []
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)
322
323 if let captureSession {
324
325 stopTimer = DispatchWorkItem {
326 self.stopRecording()
327 }
328 DispatchQueue.main.asyncAfter(
329 deadline: .now() + Double(captureSessionConfiguration.maxLength), execute: stopTimer!)
330
331 outputFile = CapturaFile()
332 if captureSessionConfiguration.shouldSaveMp4 {
333 captureSession.startRecording(to: outputFile!.mp4URL)
334 } else {
335 captureSession.startRunning()
336 }
337 return
338 }
339 }
340 }
341 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
342 }
343
344 func stopRecording() {
345 captureState = .uploading
346 updateImage()
347 stop()
348
349 Task.detached {
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)
354 }
355 }
356 let wasSuccessful = await self.uploadOrCopy()
357 if wasSuccessful {
358 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
359 } else {
360 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
361 }
362 }
363 }
364
365 func finalizeRecording() {
366 captureState = .uploaded
367 updateImage()
368 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
369 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
370 }
371 }
372
373 func reset() {
374 captureState = .idle
375 updateImage()
376 captureSessionConfiguration = CaptureSessionConfiguration()
377 stop()
378 }
379
380 func receivedFrame(_ frame: CVImageBuffer) {
381 let now = ContinuousClock.now
382
383 if now - gifCallbackTimer
384 > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate))
385 {
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
391 }
392 self.images.append(cgImage)
393 }
394 }
395 }
396 }
397
398 func failed(_ requestPermission: Bool = false) {
399 captureState = .error
400 updateImage()
401 if requestPermission {
402 requestPermissionToRecord()
403 }
404 stop()
405 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
406 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
407 }
408 }
409
410 func setConfiguration(_ config: ConfigureAction) {
411 CapturaSettings.apply(config)
412 }
413
414 func reloadConfiguration() {
415 self.captureSessionConfiguration = CaptureSessionConfiguration()
416 }
417
418 func setCaptureSessionConfiguration(_ config: RecordAction) {
419 self.captureSessionConfiguration = CaptureSessionConfiguration(from: config)
420 }
421
422 // MARK: - CoreData
423
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)]
429
430 let results = try? viewContext.fetch(fetchRequest)
431 remoteFiles = results ?? []
432 }
433
434 // MARK: - Presentation Helpers
435
436 private func requestPermissionToRecord() {
437 showPopoverWithMessage("Please grant Captura permission to record")
438 if let url = URL(
439 string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording")
440 {
441 NSWorkspace.shared.open(url)
442 }
443 }
444
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)
451 }
452 }
453 }
454
455 private func updateImage() {
456 if let button = statusItem.button {
457 let image: String =
458 switch captureState {
459 case .idle:
460 "Idle"
461 case .selectingArea:
462 if recordingWindow?.recordingContentView.box != nil {
463 "Ready to Record"
464 } else {
465 "Selecting"
466 }
467 case .recording:
468 "Stop Frame 1"
469 case .uploading:
470 "Upload Frame 1"
471 case .uploaded:
472 "OK"
473 case .error:
474 "ERR"
475 }
476 button.image = NSImage(named: image)
477 }
478 }
479
480 private func stop() {
481 stopTimer?.cancel()
482 captureSession?.stopRunning()
483 captureSession = nil
484 boxListener?.cancel()
485 recordingWindow?.close()
486 recordingWindow = nil
487 }
488
489 private func uploadOrCopy() async -> Bool {
490 if captureSessionConfiguration.shouldUseBackend {
491 let result = await uploadToBackend()
492 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
493 deleteLocalFiles()
494 }
495 return result
496 } else {
497 copyLocalToClipboard()
498 return true
499 }
500 }
501
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
506 {
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)
511 }
512 }
513 }
514
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
519 {
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")
527
528 do {
529 let (data, response) = try await URLSession.shared.data(for: request)
530
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)
535 return true
536 }
537 }
538 } catch {}
539 }
540 }
541 }
542 return false
543 }
544
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)
554 }
555
556 private func deleteLocalFiles() {
557 if captureSessionConfiguration.shouldSaveGif {
558 if let url = outputFile?.gifURL {
559 try? FileManager.default.removeItem(at: url)
560 }
561 }
562 if captureSessionConfiguration.shouldSaveMp4 {
563 if let url = outputFile?.mp4URL {
564 try? FileManager.default.removeItem(at: url)
565 }
566 }
567 }
568 }