]> git.r.bdr.sh - rbdr/captura/blob - Captura/CapturaApp.swift
2136d72f9be0ed6d699d6b9629cf3f6814e57697
[rbdr/captura] / Captura / CapturaApp.swift
1 import SwiftUI
2 import SwiftData
3 import Cocoa
4 import Combine
5 import AVFoundation
6
7 @main
8 struct CapturaApp: App {
9
10 @NSApplicationDelegateAdaptor(CapturaAppDelegate.self) var appDelegate
11
12 var body: some Scene {
13 WindowGroup {
14 PreferencesScreen()
15 .handlesExternalEvents(preferring: Set(arrayLiteral: "PreferencesScreen"), allowing: Set(arrayLiteral: "*"))
16 .frame(width: 650, height: 450)
17 }
18 .handlesExternalEvents(matching: Set(arrayLiteral: "PreferencesScreen"))
19 //.modelContainer(for: CapturaRemoteFile.self)
20 }
21 }
22
23 @objc(CapturaAppDelegate) class CapturaAppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
24
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
32 var helpShown = false
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()
41
42 @objc dynamic var scriptedPreferences: ScriptedPreferences = ScriptedPreferences()
43
44 func applicationDidFinishLaunching(_ notification: Notification) {
45 setupStatusBar()
46 NotificationCenter.default.addObserver(
47 self,
48 selector: #selector(self.didReceiveNotification(_:)),
49 name: nil,
50 object: nil)
51 closeWindow()
52 fetchRemoteItems()
53 }
54
55 // MARK: - Setup Functions
56
57
58 private func setupStatusBar() {
59 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
60
61 if let button = statusItem.button {
62 button.image = NSImage(systemSymbolName: "rectangle.dashed.badge.record", accessibilityDescription: "Captura")
63 }
64
65 statusItem.isVisible = true
66 statusItem.menu = NSMenu()
67 statusItem.menu?.delegate = self
68
69 // Create the Popover
70 popover = NSPopover()
71 popover?.contentViewController = HelpPopoverViewController()
72 popover?.behavior = .transient
73
74 setupMenu()
75 }
76
77 private func setupMenu() {
78
79 statusItem.menu?.removeAllItems()
80
81 statusItem.menu?.addItem(NSMenuItem(title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording), keyEquivalent: ""))
82 if (remoteFiles.count > 0) {
83 statusItem.menu?.addItem(NSMenuItem.separator())
84 for remoteFile in remoteFiles {
85 let remoteFileItem = NSMenuItem(title: remoteFile.name, action: #selector(CapturaAppDelegate.onClickRemoteFile), keyEquivalent: "")
86 remoteFileItem.representedObject = remoteFile
87 statusItem.menu?.addItem(remoteFileItem)
88 }
89 }
90 statusItem.menu?.addItem(NSMenuItem.separator())
91 statusItem.menu?.addItem(NSMenuItem(title: "Open Local Folder", action: #selector(CapturaAppDelegate.onOpenFolder), keyEquivalent: ""))
92 statusItem.menu?.addItem(NSMenuItem.separator())
93 statusItem.menu?.addItem(NSMenuItem(title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences), keyEquivalent: ""))
94 statusItem.menu?.addItem(NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: ""))
95 }
96
97 private func closeWindow() {
98 if let window = NSApplication.shared.windows.first {
99 window.close()
100 }
101 }
102
103 // MARK: - URL Event Handler
104
105 func application(_ application: NSApplication, open urls: [URL]) {
106 if (CapturaSettings.shouldAllowURLAutomation) {
107 for url in urls {
108 if let action = CapturaURLDecoder.decodeParams(url: url) {
109 switch action {
110 case let .configure(config):
111 NotificationCenter.default.post(name: .setConfiguration, object: nil, userInfo: [
112 "config": config
113 ])
114 case let .record(config):
115 NotificationCenter.default.post(name: .setCaptureSessionConfiguration, object: nil, userInfo: [
116 "config": config
117 ])
118 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
119 }
120 }
121 }
122 } else {
123 let alert = NSAlert()
124 alert.messageText = "URL Automation Prevented"
125 alert.informativeText = "A website or application attempted to record your screen using URL Automation. If you want to allow this, enable it in Preferences."
126 alert.alertStyle = .warning
127 alert.addButton(withTitle: "OK")
128 alert.runModal()
129 }
130 }
131
132 // MARK: - UI Event Handlers
133
134 func menuWillOpen(_ menu: NSMenu) {
135 if captureState != .idle {
136 menu.cancelTracking()
137 if captureState == .recording {
138 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
139 }
140 }
141 }
142
143 @objc private func onClickStartRecording() {
144 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
145 }
146
147 @objc private func onOpenPreferences() {
148 NSApp.activate(ignoringOtherApps: true)
149 if preferencesWindow == nil {
150 preferencesWindow = PreferencesWindow()
151 } else {
152 preferencesWindow?.makeKeyAndOrderFront(nil)
153 preferencesWindow?.orderFrontRegardless()
154 }
155 }
156
157 @objc private func onOpenFolder() {
158 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?.appendingPathComponent("captura") {
159 NSWorkspace.shared.open(directory)
160 }
161 }
162
163 @objc private func onClickRemoteFile(_ sender: NSMenuItem) {
164 if let remoteFile = sender.representedObject as? CapturaRemoteFile {
165 if let urlString = remoteFile.url {
166 if let url = URL(string: urlString) {
167 NSWorkspace.shared.open(url)
168 }
169 }
170 }
171 }
172
173 @objc private func onQuit() {
174 NSApplication.shared.terminate(self)
175 }
176
177 // MARK: - App State Event Listeners
178
179 @objc func didReceiveNotification(_ notification: Notification) {
180 switch(notification.name) {
181 case .startAreaSelection:
182 startAreaSelection()
183 case .startRecording:
184 startRecording()
185 case .stopRecording:
186 stopRecording()
187 case .finalizeRecording:
188 DispatchQueue.main.async {
189 self.finalizeRecording()
190 }
191 case .reset:
192 reset()
193 case .failedToStart:
194 DispatchQueue.main.async {
195 self.failed(true)
196 }
197 case .failedtoUpload:
198 DispatchQueue.main.async {
199 self.failed()
200 }
201 case .receivedFrame:
202 if let frame = notification.userInfo?["frame"] {
203 receivedFrame(frame as! CVImageBuffer)
204 }
205 case .setConfiguration:
206 DispatchQueue.main.async {
207 if let userInfo = notification.userInfo {
208 if let config = userInfo["config"] as? ConfigureAction {
209 self.setConfiguration(config)
210 }
211 }
212 }
213 case .reloadConfiguration:
214 reloadConfiguration()
215 case .setCaptureSessionConfiguration:
216 if let userInfo = notification.userInfo {
217 if let config = userInfo["config"] as? RecordAction {
218 setCaptureSessionConfiguration(config)
219 }
220 }
221 case .NSManagedObjectContextObjectsDidChange:
222 DispatchQueue.main.async {
223 self.fetchRemoteItems()
224 self.setupMenu()
225 }
226 default:
227 return
228 }
229 }
230
231
232 func startAreaSelection() {
233 helpShown = false
234 if captureState != .selectingArea {
235 captureState = .selectingArea
236 if let button = statusItem.button {
237 let rectInWindow = button.convert(button.bounds, to: nil)
238 let rectInScreen = button.window?.convertToScreen(rectInWindow)
239 NSApp.activate(ignoringOtherApps: true)
240 recordingWindow = RecordingWindow(captureSessionConfiguration, rectInScreen)
241 recordingWindow?.makeKeyAndOrderFront(nil)
242 recordingWindow?.orderFrontRegardless()
243 boxListener = recordingWindow?.recordingContentView.$box
244 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
245 .sink { newValue in
246 if newValue != nil {
247 self.updateImage()
248 if !self.helpShown {
249 self.helpShown = true
250 self.showPopoverWithMessage("Click here when you're ready to record.")
251 }
252 }
253 }
254 }
255 }
256 }
257
258 func startRecording() {
259 captureState = .recording
260 updateImage()
261 outputFile = nil
262 images = [];
263 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
264 recordingWindow?.recordingContentView.startRecording()
265 if let box = recordingWindow?.recordingContentView.box {
266 if let screen = recordingWindow?.screen {
267 captureSession = CapturaCaptureSession(screen, box: box)
268
269 if let captureSession {
270
271 stopTimer = DispatchWorkItem {
272 self.stopRecording()
273 }
274 DispatchQueue.main.asyncAfter(deadline: .now() + Double(captureSessionConfiguration.maxLength), execute: stopTimer!)
275
276 outputFile = CapturaFile()
277 if captureSessionConfiguration.shouldSaveMp4 {
278 captureSession.startRecording(to: outputFile!.mp4URL)
279 } else {
280 captureSession.startRunning()
281 }
282 return
283 }
284 }
285 }
286 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
287 }
288
289 func stopRecording() {
290 captureState = .uploading
291 updateImage()
292 stop()
293
294 Task.detached {
295 if self.captureSessionConfiguration.shouldSaveGif {
296 if let outputFile = self.outputFile {
297 await GifRenderer.render(self.images, at: self.captureSessionConfiguration.frameRate, to: outputFile.gifURL)
298 }
299 }
300 let wasSuccessful = await self.uploadOrCopy()
301 if wasSuccessful {
302 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
303 } else {
304 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
305 }
306 }
307 }
308
309 func finalizeRecording() {
310 captureState = .uploaded
311 updateImage()
312 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
313 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
314 }
315 }
316
317 func reset() {
318 captureState = .idle
319 updateImage()
320 captureSessionConfiguration = CaptureSessionConfiguration()
321 stop()
322 }
323
324 func receivedFrame(_ frame: CVImageBuffer) {
325 let now = ContinuousClock.now
326
327 if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate)) {
328 gifCallbackTimer = now
329 DispatchQueue.main.async {
330 if let cgImage = frame.cgImage?.resize(by: self.pixelDensity) {
331 self.images.append(cgImage)
332 }
333 }
334 }
335 }
336
337 func failed(_ requestPermission: Bool = false) {
338 captureState = .error
339 updateImage()
340 if requestPermission {
341 requestPermissionToRecord()
342 }
343 stop()
344 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
345 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
346 }
347 }
348
349 func setConfiguration(_ config: ConfigureAction) {
350 CapturaSettings.apply(config)
351 }
352
353 func reloadConfiguration() {
354 self.captureSessionConfiguration = CaptureSessionConfiguration()
355 }
356
357 func setCaptureSessionConfiguration(_ config: RecordAction) {
358 self.captureSessionConfiguration = CaptureSessionConfiguration(from: config)
359 }
360
361 // MARK: - CoreData
362
363 private func fetchRemoteItems() {
364 let viewContext = PersistenceController.shared.container.viewContext
365 let fetchRequest = NSFetchRequest<CapturaRemoteFile>(entityName: "CapturaRemoteFile")
366 fetchRequest.fetchLimit = 5
367 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
368
369 let results = try? viewContext.fetch(fetchRequest)
370 remoteFiles = results ?? []
371 }
372
373 // MARK: - Presentation Helpers
374
375
376 private func requestPermissionToRecord() {
377 showPopoverWithMessage("Please grant Captura permission to record")
378 if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording") {
379 NSWorkspace.shared.open(url)
380 }
381 }
382
383 private func showPopoverWithMessage(_ message: String) {
384 if let button = statusItem.button {
385 (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message)
386 self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
387 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
388 self.popover?.performClose(nil)
389 }
390 }
391 }
392
393 private func updateImage() {
394 if let button = statusItem.button {
395 let image: String = switch captureState {
396 case .idle:
397 "rectangle.dashed.badge.record"
398 case .selectingArea:
399 "circle.rectangle.dashed"
400 case .recording:
401 "checkmark.rectangle"
402 case .uploading:
403 "dock.arrow.up.rectangle"
404 case .uploaded:
405 "checkmark.rectangle.fill"
406 case .error:
407 "xmark.rectangle.fill"
408 }
409 button.image = NSImage(systemSymbolName: image, accessibilityDescription: "Captura")
410 }
411 }
412
413 private func stop() {
414 stopTimer?.cancel()
415 captureSession?.stopRunning()
416 captureSession = nil
417 boxListener?.cancel()
418 recordingWindow?.close()
419 recordingWindow = nil
420 }
421
422 private func uploadOrCopy() async -> Bool {
423 if captureSessionConfiguration.shouldUseBackend {
424 let result = await uploadToBackend()
425 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
426 deleteLocalFiles()
427 }
428 return result
429 } else {
430 copyLocalToClipboard()
431 return true
432 }
433 }
434
435 private func copyLocalToClipboard() {
436 let fileType: NSPasteboard.PasteboardType = .init(rawValue: captureSessionConfiguration.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
437 if let url = captureSessionConfiguration.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL {
438 if let data = try? Data(contentsOf: url) {
439 let pasteboard = NSPasteboard.general
440 pasteboard.declareTypes([fileType], owner: nil)
441 pasteboard.setData(data, forType: fileType)
442 }
443 }
444 }
445
446 private func uploadToBackend() async -> Bool {
447 let contentType = captureSessionConfiguration.shouldUploadGif ? "image/gif" : "video/mp4"
448 if let url = captureSessionConfiguration.shouldUploadGif ? outputFile?.gifURL : outputFile?.mp4URL {
449 if let data = try? Data(contentsOf: url) {
450 if let remoteUrl = captureSessionConfiguration.backend {
451 var request = URLRequest(url: remoteUrl)
452 request.httpMethod = "POST"
453 request.httpBody = data
454 request.setValue(contentType, forHTTPHeaderField: "Content-Type")
455 request.setValue("Captura/1.0", forHTTPHeaderField: "User-Agent")
456
457 do {
458 let (data, response) = try await URLSession.shared.data(for: request)
459
460 if let httpResponse = response as? HTTPURLResponse {
461 if httpResponse.statusCode == 201 {
462 let answer = try JSONDecoder().decode(BackendResponse.self, from: data)
463 createRemoteFile(answer.url)
464 return true
465 }
466 }
467 } catch {}
468 }
469 }
470 }
471 return false
472 }
473
474 private func createRemoteFile(_ url: URL) {
475 let viewContext = PersistenceController.shared.container.viewContext
476 let remoteFile = CapturaRemoteFile(context: viewContext)
477 remoteFile.url = url.absoluteString
478 remoteFile.timestamp = Date()
479 try? viewContext.save()
480 let pasteboard = NSPasteboard.general
481 pasteboard.declareTypes([.URL], owner: nil)
482 pasteboard.setString(url.absoluteString, forType: .string)
483 }
484
485 private func deleteLocalFiles() {
486 if captureSessionConfiguration.shouldSaveGif {
487 if let url = outputFile?.gifURL {
488 try? FileManager.default.removeItem(at: url)
489 }
490 }
491 if captureSessionConfiguration.shouldSaveMp4 {
492 if let url = outputFile?.mp4URL {
493 try? FileManager.default.removeItem(at: url)
494 }
495 }
496 }
497 }