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