]> git.r.bdr.sh - rbdr/captura/blame - Captura/CapturaApp.swift
Format the code
[rbdr/captura] / Captura / CapturaApp.swift
CommitLineData
505c1e62
RBR
1import AVFoundation
2import Cocoa
3import Combine
4import Sparkle
5802c153
RBR
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 */
a4e80427 21import SwiftUI
a4e80427
RBR
22
23@main
24struct CapturaApp: App {
153f3309 25
505c1e62 26 @NSApplicationDelegateAdaptor(CapturaAppDelegate.self) var appDelegate
a4e80427 27
505c1e62
RBR
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 }
a4e80427
RBR
39}
40
505c1e62
RBR
41@objc(CapturaAppDelegate) class CapturaAppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate
42{
43
a4e80427
RBR
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
c9b9e1d6 52 var captureSession: CapturaCaptureSession? = nil
a4e80427 53 var images: [CGImage] = []
f5d16c1c 54 var outputFile: CapturaFile? = nil
a4e80427 55 var gifCallbackTimer = ContinuousClock.now
a4e80427
RBR
56 var pixelDensity: CGFloat = 1.0
57 var stopTimer: DispatchWorkItem?
533cd932 58 var remoteFiles: [CapturaRemoteFile] = []
ba17de89 59 var captureSessionConfiguration: CaptureSessionConfiguration = CaptureSessionConfiguration()
505c1e62 60
578c4751
RBR
61 // Sparkle Configuration
62 @IBOutlet var checkForUpdatesMenuItem: NSMenuItem!
505c1e62
RBR
63 let updaterController: SPUStandardUpdaterController = SPUStandardUpdaterController(
64 startingUpdater: true, updaterDelegate: nil, userDriverDelegate: nil)
65
153f3309 66 @objc dynamic var scriptedPreferences: ScriptedPreferences = ScriptedPreferences()
505c1e62 67
a4e80427 68 func applicationDidFinishLaunching(_ notification: Notification) {
533cd932 69 setupStatusBar()
a4e80427
RBR
70 NotificationCenter.default.addObserver(
71 self,
72 selector: #selector(self.didReceiveNotification(_:)),
73 name: nil,
74 object: nil)
75 closeWindow()
533cd932 76 fetchRemoteItems()
a4e80427 77 }
505c1e62 78
a4e80427 79 // MARK: - Setup Functions
505c1e62 80
533cd932 81 private func setupStatusBar() {
a4e80427 82 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
505c1e62 83
a4e80427 84 if let button = statusItem.button {
3472041d 85 button.image = NSImage(named: "Idle")
a4e80427 86 }
505c1e62 87
a4e80427
RBR
88 statusItem.isVisible = true
89 statusItem.menu = NSMenu()
90 statusItem.menu?.delegate = self
505c1e62 91
a4e80427
RBR
92 // Create the Popover
93 popover = NSPopover()
94 popover?.contentViewController = HelpPopoverViewController()
95 popover?.behavior = .transient
505c1e62 96
533cd932
RBR
97 setupMenu()
98 }
505c1e62 99
533cd932 100 private func setupMenu() {
505c1e62 101
533cd932 102 statusItem.menu?.removeAllItems()
505c1e62
RBR
103
104 statusItem.menu?.addItem(
105 NSMenuItem(
106 title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording),
107 keyEquivalent: ""))
108 if remoteFiles.count > 0 {
533cd932
RBR
109 statusItem.menu?.addItem(NSMenuItem.separator())
110 for remoteFile in remoteFiles {
505c1e62
RBR
111 let remoteFileItem = NSMenuItem(
112 title: remoteFile.name, action: #selector(CapturaAppDelegate.onClickRemoteFile),
113 keyEquivalent: "")
533cd932
RBR
114 remoteFileItem.representedObject = remoteFile
115 statusItem.menu?.addItem(remoteFileItem)
116 }
117 }
118 statusItem.menu?.addItem(NSMenuItem.separator())
505c1e62
RBR
119 statusItem.menu?.addItem(
120 NSMenuItem(
121 title: "Open Local Folder", action: #selector(CapturaAppDelegate.onOpenFolder),
122 keyEquivalent: ""))
533cd932 123 statusItem.menu?.addItem(NSMenuItem.separator())
505c1e62
RBR
124
125 checkForUpdatesMenuItem = NSMenuItem(
126 title: "Check for Updates",
127 action: #selector(SPUStandardUpdaterController.checkForUpdates(_:)), keyEquivalent: "")
578c4751
RBR
128 checkForUpdatesMenuItem.target = updaterController
129 statusItem.menu?.addItem(checkForUpdatesMenuItem)
505c1e62
RBR
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: ""))
a4e80427 137 }
505c1e62 138
a4e80427
RBR
139 private func closeWindow() {
140 if let window = NSApplication.shared.windows.first {
141 window.close()
142 }
143 }
153f3309 144
ba17de89 145 // MARK: - URL Event Handler
505c1e62 146
ba17de89 147 func application(_ application: NSApplication, open urls: [URL]) {
505c1e62 148 if CapturaSettings.shouldAllowURLAutomation {
ba17de89
RBR
149 for url in urls {
150 if let action = CapturaURLDecoder.decodeParams(url: url) {
151 switch action {
505c1e62
RBR
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 ])
153f3309 164 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
ba17de89
RBR
165 }
166 }
167 }
168 } else {
169 let alert = NSAlert()
170 alert.messageText = "URL Automation Prevented"
505c1e62
RBR
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()
ba17de89
RBR
176 }
177 }
505c1e62 178
a4e80427 179 // MARK: - UI Event Handlers
505c1e62 180
a4e80427
RBR
181 func menuWillOpen(_ menu: NSMenu) {
182 if captureState != .idle {
082b61f3
RBR
183 menu.cancelTrackingWithoutAnimation()
184 if captureState == .selectingArea {
185 NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
186 return
187 }
a4e80427 188 if captureState == .recording {
f5d16c1c 189 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
082b61f3 190 return
a4e80427
RBR
191 }
192 }
193 }
505c1e62 194
a4e80427
RBR
195 @objc private func onClickStartRecording() {
196 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
197 }
505c1e62 198
a4e80427
RBR
199 @objc private func onOpenPreferences() {
200 NSApp.activate(ignoringOtherApps: true)
201 if preferencesWindow == nil {
505c1e62 202 preferencesWindow = PreferencesWindow()
a4e80427
RBR
203 } else {
204 preferencesWindow?.makeKeyAndOrderFront(nil)
533cd932
RBR
205 preferencesWindow?.orderFrontRegardless()
206 }
207 }
505c1e62 208
533cd932 209 @objc private func onOpenFolder() {
505c1e62
RBR
210 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?
211 .appendingPathComponent("captura")
212 {
533cd932
RBR
213 NSWorkspace.shared.open(directory)
214 }
215 }
505c1e62 216
533cd932
RBR
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 }
a4e80427
RBR
224 }
225 }
505c1e62 226
a4e80427
RBR
227 @objc private func onQuit() {
228 NSApplication.shared.terminate(self)
229 }
505c1e62 230
a4e80427 231 // MARK: - App State Event Listeners
505c1e62 232
a4e80427 233 @objc func didReceiveNotification(_ notification: Notification) {
505c1e62 234 switch notification.name {
a4e80427
RBR
235 case .startAreaSelection:
236 startAreaSelection()
237 case .startRecording:
238 startRecording()
239 case .stopRecording:
240 stopRecording()
241 case .finalizeRecording:
f5d16c1c
RBR
242 DispatchQueue.main.async {
243 self.finalizeRecording()
244 }
a4e80427
RBR
245 case .reset:
246 reset()
c9b9e1d6 247 case .failedToStart:
533cd932
RBR
248 DispatchQueue.main.async {
249 self.failed(true)
250 }
251 case .failedtoUpload:
252 DispatchQueue.main.async {
253 self.failed()
254 }
c9b9e1d6
RBR
255 case .receivedFrame:
256 if let frame = notification.userInfo?["frame"] {
257 receivedFrame(frame as! CVImageBuffer)
258 }
e42019cd
RBR
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 }
377442f2 267 case .reloadConfiguration:
505c1e62 268 reloadConfiguration()
377442f2
RBR
269 case .setCaptureSessionConfiguration:
270 if let userInfo = notification.userInfo {
271 if let config = userInfo["config"] as? RecordAction {
272 setCaptureSessionConfiguration(config)
273 }
274 }
533cd932
RBR
275 case .NSManagedObjectContextObjectsDidChange:
276 DispatchQueue.main.async {
277 self.fetchRemoteItems()
278 self.setupMenu()
279 }
a4e80427
RBR
280 default:
281 return
282 }
a4e80427 283 }
505c1e62 284
c9b9e1d6 285 func startAreaSelection() {
a4e80427 286 helpShown = false
a4e80427
RBR
287 if captureState != .selectingArea {
288 captureState = .selectingArea
3472041d 289 updateImage()
a4e80427
RBR
290 if let button = statusItem.button {
291 let rectInWindow = button.convert(button.bounds, to: nil)
292 let rectInScreen = button.window?.convertToScreen(rectInWindow)
533cd932 293 NSApp.activate(ignoringOtherApps: true)
8e932130 294 recordingWindow = RecordingWindow(captureSessionConfiguration, rectInScreen)
533cd932
RBR
295 recordingWindow?.makeKeyAndOrderFront(nil)
296 recordingWindow?.orderFrontRegardless()
c9b9e1d6
RBR
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.")
a4e80427
RBR
305 }
306 }
c9b9e1d6 307 }
a4e80427
RBR
308 }
309 }
310 }
505c1e62 311
a4e80427
RBR
312 func startRecording() {
313 captureState = .recording
c9b9e1d6 314 updateImage()
f5d16c1c 315 outputFile = nil
505c1e62 316 images = []
a4e80427 317 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
c9b9e1d6
RBR
318 recordingWindow?.recordingContentView.startRecording()
319 if let box = recordingWindow?.recordingContentView.box {
320 if let screen = recordingWindow?.screen {
321 captureSession = CapturaCaptureSession(screen, box: box)
505c1e62 322
c9b9e1d6
RBR
323 if let captureSession {
324
325 stopTimer = DispatchWorkItem {
326 self.stopRecording()
327 }
505c1e62
RBR
328 DispatchQueue.main.asyncAfter(
329 deadline: .now() + Double(captureSessionConfiguration.maxLength), execute: stopTimer!)
330
c9b9e1d6 331 outputFile = CapturaFile()
ba17de89 332 if captureSessionConfiguration.shouldSaveMp4 {
c9b9e1d6
RBR
333 captureSession.startRecording(to: outputFile!.mp4URL)
334 } else {
a4e80427 335 captureSession.startRunning()
a4e80427 336 }
c9b9e1d6 337 return
a4e80427
RBR
338 }
339 }
340 }
c9b9e1d6 341 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
a4e80427 342 }
505c1e62 343
a4e80427 344 func stopRecording() {
a4e80427 345 captureState = .uploading
c9b9e1d6
RBR
346 updateImage()
347 stop()
505c1e62 348
a4e80427 349 Task.detached {
ba17de89 350 if self.captureSessionConfiguration.shouldSaveGif {
533cd932 351 if let outputFile = self.outputFile {
505c1e62
RBR
352 await GifRenderer.render(
353 self.images, at: self.captureSessionConfiguration.frameRate, to: outputFile.gifURL)
533cd932
RBR
354 }
355 }
356 let wasSuccessful = await self.uploadOrCopy()
357 if wasSuccessful {
f5d16c1c 358 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
533cd932
RBR
359 } else {
360 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
a4e80427
RBR
361 }
362 }
a4e80427 363 }
505c1e62 364
a4e80427
RBR
365 func finalizeRecording() {
366 captureState = .uploaded
c9b9e1d6 367 updateImage()
f5d16c1c 368 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
c9b9e1d6 369 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
f5d16c1c 370 }
a4e80427 371 }
505c1e62 372
a4e80427 373 func reset() {
a4e80427 374 captureState = .idle
c9b9e1d6 375 updateImage()
8e932130 376 captureSessionConfiguration = CaptureSessionConfiguration()
c9b9e1d6 377 stop()
a4e80427 378 }
505c1e62 379
c9b9e1d6 380 func receivedFrame(_ frame: CVImageBuffer) {
a4e80427 381 let now = ContinuousClock.now
505c1e62
RBR
382
383 if now - gifCallbackTimer
384 > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate))
385 {
a4e80427
RBR
386 gifCallbackTimer = now
387 DispatchQueue.main.async {
9431168d
RBR
388 if var cgImage = frame.cgImage {
389 if self.pixelDensity > 1 {
390 cgImage = cgImage.resize(by: self.pixelDensity) ?? cgImage
391 }
c9b9e1d6 392 self.images.append(cgImage)
a4e80427
RBR
393 }
394 }
395 }
396 }
505c1e62 397
533cd932 398 func failed(_ requestPermission: Bool = false) {
c9b9e1d6
RBR
399 captureState = .error
400 updateImage()
533cd932
RBR
401 if requestPermission {
402 requestPermissionToRecord()
403 }
c9b9e1d6
RBR
404 stop()
405 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
406 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
407 }
408 }
505c1e62 409
e42019cd
RBR
410 func setConfiguration(_ config: ConfigureAction) {
411 CapturaSettings.apply(config)
412 }
505c1e62 413
377442f2
RBR
414 func reloadConfiguration() {
415 self.captureSessionConfiguration = CaptureSessionConfiguration()
416 }
505c1e62 417
377442f2
RBR
418 func setCaptureSessionConfiguration(_ config: RecordAction) {
419 self.captureSessionConfiguration = CaptureSessionConfiguration(from: config)
420 }
505c1e62 421
533cd932 422 // MARK: - CoreData
505c1e62 423
533cd932
RBR
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)]
505c1e62 429
533cd932
RBR
430 let results = try? viewContext.fetch(fetchRequest)
431 remoteFiles = results ?? []
432 }
505c1e62 433
c9b9e1d6 434 // MARK: - Presentation Helpers
505c1e62 435
c9b9e1d6
RBR
436 private func requestPermissionToRecord() {
437 showPopoverWithMessage("Please grant Captura permission to record")
505c1e62
RBR
438 if let url = URL(
439 string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording")
440 {
c9b9e1d6
RBR
441 NSWorkspace.shared.open(url)
442 }
443 }
505c1e62 444
a4e80427
RBR
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 }
505c1e62 454
c9b9e1d6
RBR
455 private func updateImage() {
456 if let button = statusItem.button {
505c1e62
RBR
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"
3472041d 475 }
3472041d 476 button.image = NSImage(named: image)
c9b9e1d6
RBR
477 }
478 }
505c1e62 479
c9b9e1d6
RBR
480 private func stop() {
481 stopTimer?.cancel()
482 captureSession?.stopRunning()
483 captureSession = nil
484 boxListener?.cancel()
485 recordingWindow?.close()
486 recordingWindow = nil
487 }
505c1e62 488
533cd932 489 private func uploadOrCopy() async -> Bool {
ba17de89 490 if captureSessionConfiguration.shouldUseBackend {
533cd932 491 let result = await uploadToBackend()
ba17de89 492 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
533cd932
RBR
493 deleteLocalFiles()
494 }
495 return result
496 } else {
497 copyLocalToClipboard()
498 return true
499 }
500 }
505c1e62 501
533cd932 502 private func copyLocalToClipboard() {
505c1e62
RBR
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 {
c9b9e1d6
RBR
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 }
505c1e62 514
533cd932 515 private func uploadToBackend() async -> Bool {
ba17de89 516 let contentType = captureSessionConfiguration.shouldUploadGif ? "image/gif" : "video/mp4"
505c1e62
RBR
517 if let url = captureSessionConfiguration.shouldUploadGif
518 ? outputFile?.gifURL : outputFile?.mp4URL
519 {
533cd932 520 if let data = try? Data(contentsOf: url) {
ba17de89 521 if let remoteUrl = captureSessionConfiguration.backend {
533cd932
RBR
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")
505c1e62 527
533cd932
RBR
528 do {
529 let (data, response) = try await URLSession.shared.data(for: request)
505c1e62 530
533cd932
RBR
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 }
505c1e62 544
533cd932
RBR
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 }
505c1e62 555
533cd932 556 private func deleteLocalFiles() {
ba17de89 557 if captureSessionConfiguration.shouldSaveGif {
533cd932 558 if let url = outputFile?.gifURL {
505c1e62 559 try? FileManager.default.removeItem(at: url)
533cd932
RBR
560 }
561 }
ba17de89 562 if captureSessionConfiguration.shouldSaveMp4 {
533cd932
RBR
563 if let url = outputFile?.mp4URL {
564 try? FileManager.default.removeItem(at: url)
565 }
566 }
567 }
a4e80427 568}