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