]> git.r.bdr.sh - rbdr/captura/blob - Captura/CapturaApp.swift
deb1e0775da472cb25c6d464d4380769ad00fa9f
[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 if let image = NSImage(named: "MenuBar/Idle") {
86 image.isTemplate = true
87 image.size = NSSize(width: 18, height: 18)
88 button.image = image
89 }
90 }
91
92 statusItem.isVisible = true
93 statusItem.menu = NSMenu()
94 statusItem.menu?.delegate = self
95
96 // Create the Popover
97 popover = NSPopover()
98 popover?.contentViewController = HelpPopoverViewController()
99 popover?.behavior = .transient
100
101 setupMenu()
102 }
103
104 private func setupMenu() {
105
106 statusItem.menu?.removeAllItems()
107
108 statusItem.menu?.addItem(
109 NSMenuItem(
110 title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording),
111 keyEquivalent: ""))
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),
117 keyEquivalent: "")
118 remoteFileItem.representedObject = remoteFile
119 statusItem.menu?.addItem(remoteFileItem)
120 }
121 }
122 statusItem.menu?.addItem(NSMenuItem.separator())
123 statusItem.menu?.addItem(
124 NSMenuItem(
125 title: "Open Local Folder", action: #selector(CapturaAppDelegate.onOpenFolder),
126 keyEquivalent: ""))
127 statusItem.menu?.addItem(NSMenuItem.separator())
128
129 checkForUpdatesMenuItem = NSMenuItem(
130 title: "Check for Updates",
131 action: #selector(SPUStandardUpdaterController.checkForUpdates(_:)), keyEquivalent: "")
132 checkForUpdatesMenuItem.target = updaterController
133 statusItem.menu?.addItem(checkForUpdatesMenuItem)
134
135 statusItem.menu?.addItem(
136 NSMenuItem(
137 title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences),
138 keyEquivalent: ""))
139 statusItem.menu?.addItem(
140 NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: ""))
141 }
142
143 private func closeWindow() {
144 if let window = NSApplication.shared.windows.first {
145 window.close()
146 }
147 }
148
149 // MARK: - URL Event Handler
150
151 func application(_ application: NSApplication, open urls: [URL]) {
152 if CapturaSettings.shouldAllowURLAutomation {
153 for url in urls {
154 if let action = CapturaURLDecoder.decodeParams(url: url) {
155 switch action {
156 case let .configure(config):
157 NotificationCenter.default.post(
158 name: .setConfiguration, object: nil,
159 userInfo: [
160 "config": config
161 ])
162 case let .record(config):
163 NotificationCenter.default.post(
164 name: .setCaptureSessionConfiguration, object: nil,
165 userInfo: [
166 "config": config
167 ])
168 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
169 }
170 }
171 }
172 } else {
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")
179 alert.runModal()
180 }
181 }
182
183 // MARK: - UI Event Handlers
184
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)
190 return
191 }
192 if captureState == .recording {
193 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
194 return
195 }
196 }
197 }
198
199 @objc private func onClickStartRecording() {
200 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
201 }
202
203 @objc private func onOpenPreferences() {
204 NSApp.activate(ignoringOtherApps: true)
205 if preferencesWindow == nil {
206 preferencesWindow = PreferencesWindow()
207 } else {
208 preferencesWindow?.makeKeyAndOrderFront(nil)
209 preferencesWindow?.orderFrontRegardless()
210 }
211 }
212
213 @objc private func onOpenFolder() {
214 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?
215 .appendingPathComponent("captura")
216 {
217 NSWorkspace.shared.open(directory)
218 }
219 }
220
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)
226 }
227 }
228 }
229 }
230
231 @objc private func onQuit() {
232 NSApplication.shared.terminate(self)
233 }
234
235 // MARK: - App State Event Listeners
236
237 @objc func didReceiveNotification(_ notification: Notification) {
238 switch notification.name {
239 case .startAreaSelection:
240 startAreaSelection()
241 case .startRecording:
242 startRecording()
243 case .stopRecording:
244 stopRecording()
245 case .finalizeRecording:
246 DispatchQueue.main.async {
247 self.finalizeRecording()
248 }
249 case .reset:
250 reset()
251 case .failedToStart:
252 DispatchQueue.main.async {
253 self.failed(true)
254 }
255 case .failedtoUpload:
256 DispatchQueue.main.async {
257 self.failed()
258 }
259 case .receivedFrame:
260 if let frame = notification.userInfo?["frame"] {
261 receivedFrame(frame as! CVImageBuffer)
262 }
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)
268 }
269 }
270 }
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)
277 }
278 }
279 case .NSManagedObjectContextObjectsDidChange:
280 DispatchQueue.main.async {
281 self.fetchRemoteItems()
282 self.setupMenu()
283 }
284 default:
285 return
286 }
287 }
288
289 func startAreaSelection() {
290 helpShown = false
291 if captureState != .selectingArea {
292 captureState = .selectingArea
293 updateImage()
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)
303 .sink { newValue in
304 if newValue != nil {
305 self.updateImage()
306 if !self.helpShown {
307 self.helpShown = true
308 self.showPopoverWithMessage("Click here when you're ready to record.")
309 }
310 }
311 }
312 }
313 }
314 }
315
316 func startRecording() {
317 captureState = .recording
318 updateImage()
319 outputFile = nil
320 images = []
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)
326
327 if let captureSession {
328
329 stopTimer = DispatchWorkItem {
330 self.stopRecording()
331 }
332 DispatchQueue.main.asyncAfter(
333 deadline: .now() + Double(captureSessionConfiguration.maxLength), execute: stopTimer!)
334
335 outputFile = CapturaFile()
336 if captureSessionConfiguration.shouldSaveMp4 {
337 captureSession.startRecording(to: outputFile!.mp4URL)
338 } else {
339 captureSession.startRunning()
340 }
341 return
342 }
343 }
344 }
345 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
346 }
347
348 func stopRecording() {
349 captureState = .uploading
350 updateImage()
351 stop()
352
353 Task.detached {
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)
358 }
359 }
360 let wasSuccessful = await self.uploadOrCopy()
361 if wasSuccessful {
362 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
363 } else {
364 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
365 }
366 }
367 }
368
369 func finalizeRecording() {
370 captureState = .uploaded
371 updateImage()
372 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
373 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
374 }
375 }
376
377 func reset() {
378 captureState = .idle
379 updateImage()
380 captureSessionConfiguration = CaptureSessionConfiguration()
381 stop()
382 }
383
384 func receivedFrame(_ frame: CVImageBuffer) {
385 let now = ContinuousClock.now
386
387 if now - gifCallbackTimer
388 > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate))
389 {
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
395 }
396 self.images.append(cgImage)
397 }
398 }
399 }
400 }
401
402 func failed(_ requestPermission: Bool = false) {
403 captureState = .error
404 updateImage()
405 if requestPermission {
406 requestPermissionToRecord()
407 }
408 stop()
409 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
410 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
411 }
412 }
413
414 func setConfiguration(_ config: ConfigureAction) {
415 CapturaSettings.apply(config)
416 }
417
418 func reloadConfiguration() {
419 self.captureSessionConfiguration = CaptureSessionConfiguration()
420 }
421
422 func setCaptureSessionConfiguration(_ config: RecordAction) {
423 self.captureSessionConfiguration = CaptureSessionConfiguration(from: config)
424 }
425
426 // MARK: - CoreData
427
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)]
433
434 let results = try? viewContext.fetch(fetchRequest)
435 remoteFiles = results ?? []
436 }
437
438 // MARK: - Presentation Helpers
439
440 private func requestPermissionToRecord() {
441 showPopoverWithMessage("Please grant Captura permission to record")
442 if let url = URL(
443 string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording")
444 {
445 NSWorkspace.shared.open(url)
446 }
447 }
448
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)
455 }
456 }
457 }
458
459 private func updateImage() {
460 if let button = statusItem.button {
461 let image: String =
462 switch captureState {
463 case .idle:
464 "MenuBar/Idle"
465 case .selectingArea:
466 if recordingWindow?.recordingContentView.box != nil {
467 "MenuBar/Ready to Record"
468 } else {
469 "MenuBar/Selecting"
470 }
471 case .recording:
472 "MenuBar/Stop Frame 1"
473 case .uploading:
474 "MenuBar/Upload Frame 1"
475 case .uploaded:
476 "MenuBar/OK"
477 case .error:
478 "MenuBar/ERR"
479 }
480 if let image = NSImage(named: image) {
481 image.isTemplate = true
482 image.size = NSSize(width: 18, height: 18)
483 button.image = image
484 }
485 }
486 }
487
488 private func stop() {
489 stopTimer?.cancel()
490 captureSession?.stopRunning()
491 captureSession = nil
492 boxListener?.cancel()
493 recordingWindow?.close()
494 recordingWindow = nil
495 }
496
497 private func uploadOrCopy() async -> Bool {
498 if captureSessionConfiguration.shouldUseBackend {
499 let result = await uploadToBackend()
500 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
501 deleteLocalFiles()
502 }
503 return result
504 } else {
505 copyLocalToClipboard()
506 return true
507 }
508 }
509
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
514 {
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)
519 }
520 }
521 }
522
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
527 {
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")
535
536 do {
537 let (data, response) = try await URLSession.shared.data(for: request)
538
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)
543 return true
544 }
545 }
546 } catch {}
547 }
548 }
549 }
550 return false
551 }
552
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)
562 }
563
564 private func deleteLocalFiles() {
565 if captureSessionConfiguration.shouldSaveGif {
566 if let url = outputFile?.gifURL {
567 try? FileManager.default.removeItem(at: url)
568 }
569 }
570 if captureSessionConfiguration.shouldSaveMp4 {
571 if let url = outputFile?.mp4URL {
572 try? FileManager.default.removeItem(at: url)
573 }
574 }
575 }
576 }