]> git.r.bdr.sh - rbdr/captura/blame - Captura/CapturaApp.swift
Add license and contributing
[rbdr/captura] / Captura / CapturaApp.swift
CommitLineData
5802c153
RBR
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 */
a4e80427 17import SwiftUI
a4e80427
RBR
18import Cocoa
19import Combine
c9b9e1d6 20import AVFoundation
578c4751 21import Sparkle
a4e80427
RBR
22
23@main
24struct CapturaApp: App {
153f3309 25
a4e80427
RBR
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"))
533cd932 35 //.modelContainer(for: CapturaRemoteFile.self)
a4e80427
RBR
36 }
37}
38
153f3309 39@objc(CapturaAppDelegate) class CapturaAppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
a4e80427
RBR
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
c9b9e1d6 49 var captureSession: CapturaCaptureSession? = nil
a4e80427 50 var images: [CGImage] = []
f5d16c1c 51 var outputFile: CapturaFile? = nil
a4e80427 52 var gifCallbackTimer = ContinuousClock.now
a4e80427
RBR
53 var pixelDensity: CGFloat = 1.0
54 var stopTimer: DispatchWorkItem?
533cd932 55 var remoteFiles: [CapturaRemoteFile] = []
ba17de89 56 var captureSessionConfiguration: CaptureSessionConfiguration = CaptureSessionConfiguration()
a4e80427 57
578c4751
RBR
58 // Sparkle Configuration
59 @IBOutlet var checkForUpdatesMenuItem: NSMenuItem!
60 let updaterController: SPUStandardUpdaterController = SPUStandardUpdaterController(startingUpdater: true, updaterDelegate: nil, userDriverDelegate: nil)
61
153f3309 62 @objc dynamic var scriptedPreferences: ScriptedPreferences = ScriptedPreferences()
377442f2 63
a4e80427 64 func applicationDidFinishLaunching(_ notification: Notification) {
533cd932 65 setupStatusBar()
a4e80427
RBR
66 NotificationCenter.default.addObserver(
67 self,
68 selector: #selector(self.didReceiveNotification(_:)),
69 name: nil,
70 object: nil)
71 closeWindow()
533cd932 72 fetchRemoteItems()
a4e80427
RBR
73 }
74
75 // MARK: - Setup Functions
76
77
533cd932 78 private func setupStatusBar() {
a4e80427
RBR
79 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
80
81 if let button = statusItem.button {
3472041d 82 button.image = NSImage(named: "Idle")
a4e80427
RBR
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
533cd932
RBR
94 setupMenu()
95 }
96
97 private func setupMenu() {
a4e80427 98
533cd932 99 statusItem.menu?.removeAllItems()
a4e80427 100
533cd932
RBR
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())
578c4751
RBR
113
114 checkForUpdatesMenuItem = NSMenuItem(title: "Check for Updates", action: #selector(SPUStandardUpdaterController.checkForUpdates(_:)), keyEquivalent: "")
115 checkForUpdatesMenuItem.target = updaterController
116 statusItem.menu?.addItem(checkForUpdatesMenuItem)
117
533cd932
RBR
118 statusItem.menu?.addItem(NSMenuItem(title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences), keyEquivalent: ""))
119 statusItem.menu?.addItem(NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: ""))
a4e80427
RBR
120 }
121
122 private func closeWindow() {
123 if let window = NSApplication.shared.windows.first {
124 window.close()
125 }
126 }
153f3309 127
ba17de89
RBR
128 // MARK: - URL Event Handler
129
130 func application(_ application: NSApplication, open urls: [URL]) {
ba17de89
RBR
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):
e42019cd
RBR
136 NotificationCenter.default.post(name: .setConfiguration, object: nil, userInfo: [
137 "config": config
138 ])
ba17de89 139 case let .record(config):
153f3309 140 NotificationCenter.default.post(name: .setCaptureSessionConfiguration, object: nil, userInfo: [
377442f2
RBR
141 "config": config
142 ])
153f3309 143 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
ba17de89
RBR
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
a4e80427
RBR
157 // MARK: - UI Event Handlers
158
159 func menuWillOpen(_ menu: NSMenu) {
160 if captureState != .idle {
082b61f3
RBR
161 menu.cancelTrackingWithoutAnimation()
162 if captureState == .selectingArea {
163 NotificationCenter.default.post(name: .startRecording, object: nil, userInfo: nil)
164 return
165 }
a4e80427 166 if captureState == .recording {
f5d16c1c 167 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
082b61f3 168 return
a4e80427
RBR
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)
533cd932
RBR
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 }
a4e80427
RBR
200 }
201 }
202
203 @objc private func onQuit() {
204 NSApplication.shared.terminate(self)
205 }
206
a4e80427
RBR
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:
f5d16c1c
RBR
218 DispatchQueue.main.async {
219 self.finalizeRecording()
220 }
a4e80427
RBR
221 case .reset:
222 reset()
c9b9e1d6 223 case .failedToStart:
533cd932
RBR
224 DispatchQueue.main.async {
225 self.failed(true)
226 }
227 case .failedtoUpload:
228 DispatchQueue.main.async {
229 self.failed()
230 }
c9b9e1d6
RBR
231 case .receivedFrame:
232 if let frame = notification.userInfo?["frame"] {
233 receivedFrame(frame as! CVImageBuffer)
234 }
e42019cd
RBR
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 }
377442f2 243 case .reloadConfiguration:
e42019cd 244 reloadConfiguration()
377442f2
RBR
245 case .setCaptureSessionConfiguration:
246 if let userInfo = notification.userInfo {
247 if let config = userInfo["config"] as? RecordAction {
248 setCaptureSessionConfiguration(config)
249 }
250 }
533cd932
RBR
251 case .NSManagedObjectContextObjectsDidChange:
252 DispatchQueue.main.async {
253 self.fetchRemoteItems()
254 self.setupMenu()
255 }
a4e80427
RBR
256 default:
257 return
258 }
a4e80427
RBR
259 }
260
261
c9b9e1d6 262 func startAreaSelection() {
a4e80427 263 helpShown = false
a4e80427
RBR
264 if captureState != .selectingArea {
265 captureState = .selectingArea
3472041d 266 updateImage()
a4e80427
RBR
267 if let button = statusItem.button {
268 let rectInWindow = button.convert(button.bounds, to: nil)
269 let rectInScreen = button.window?.convertToScreen(rectInWindow)
533cd932 270 NSApp.activate(ignoringOtherApps: true)
8e932130 271 recordingWindow = RecordingWindow(captureSessionConfiguration, rectInScreen)
533cd932
RBR
272 recordingWindow?.makeKeyAndOrderFront(nil)
273 recordingWindow?.orderFrontRegardless()
c9b9e1d6
RBR
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.")
a4e80427
RBR
282 }
283 }
c9b9e1d6 284 }
a4e80427
RBR
285 }
286 }
287 }
288
289 func startRecording() {
290 captureState = .recording
c9b9e1d6 291 updateImage()
f5d16c1c 292 outputFile = nil
a4e80427
RBR
293 images = [];
294 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
c9b9e1d6
RBR
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 }
8e932130 305 DispatchQueue.main.asyncAfter(deadline: .now() + Double(captureSessionConfiguration.maxLength), execute: stopTimer!)
a4e80427 306
c9b9e1d6 307 outputFile = CapturaFile()
ba17de89 308 if captureSessionConfiguration.shouldSaveMp4 {
c9b9e1d6
RBR
309 captureSession.startRecording(to: outputFile!.mp4URL)
310 } else {
a4e80427 311 captureSession.startRunning()
a4e80427 312 }
c9b9e1d6 313 return
a4e80427
RBR
314 }
315 }
316 }
c9b9e1d6 317 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
a4e80427
RBR
318 }
319
320 func stopRecording() {
a4e80427 321 captureState = .uploading
c9b9e1d6
RBR
322 updateImage()
323 stop()
f5d16c1c 324
a4e80427 325 Task.detached {
ba17de89 326 if self.captureSessionConfiguration.shouldSaveGif {
533cd932 327 if let outputFile = self.outputFile {
ba17de89 328 await GifRenderer.render(self.images, at: self.captureSessionConfiguration.frameRate, to: outputFile.gifURL)
533cd932
RBR
329 }
330 }
331 let wasSuccessful = await self.uploadOrCopy()
332 if wasSuccessful {
f5d16c1c 333 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
533cd932
RBR
334 } else {
335 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
a4e80427
RBR
336 }
337 }
a4e80427
RBR
338 }
339
340 func finalizeRecording() {
341 captureState = .uploaded
c9b9e1d6 342 updateImage()
f5d16c1c 343 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
c9b9e1d6 344 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
f5d16c1c 345 }
a4e80427
RBR
346 }
347
348 func reset() {
a4e80427 349 captureState = .idle
c9b9e1d6 350 updateImage()
8e932130 351 captureSessionConfiguration = CaptureSessionConfiguration()
c9b9e1d6 352 stop()
a4e80427
RBR
353 }
354
c9b9e1d6 355 func receivedFrame(_ frame: CVImageBuffer) {
a4e80427
RBR
356 let now = ContinuousClock.now
357
ba17de89 358 if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate)) {
a4e80427
RBR
359 gifCallbackTimer = now
360 DispatchQueue.main.async {
9431168d
RBR
361 if var cgImage = frame.cgImage {
362 if self.pixelDensity > 1 {
363 cgImage = cgImage.resize(by: self.pixelDensity) ?? cgImage
364 }
c9b9e1d6 365 self.images.append(cgImage)
a4e80427
RBR
366 }
367 }
368 }
369 }
370
533cd932 371 func failed(_ requestPermission: Bool = false) {
c9b9e1d6
RBR
372 captureState = .error
373 updateImage()
533cd932
RBR
374 if requestPermission {
375 requestPermissionToRecord()
376 }
c9b9e1d6
RBR
377 stop()
378 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
379 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
380 }
381 }
382
e42019cd
RBR
383 func setConfiguration(_ config: ConfigureAction) {
384 CapturaSettings.apply(config)
385 }
386
377442f2
RBR
387 func reloadConfiguration() {
388 self.captureSessionConfiguration = CaptureSessionConfiguration()
389 }
390
391 func setCaptureSessionConfiguration(_ config: RecordAction) {
392 self.captureSessionConfiguration = CaptureSessionConfiguration(from: config)
393 }
394
533cd932
RBR
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
c9b9e1d6
RBR
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
a4e80427
RBR
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
c9b9e1d6
RBR
427 private func updateImage() {
428 if let button = statusItem.button {
429 let image: String = switch captureState {
430 case .idle:
3472041d 431 "Idle"
c9b9e1d6 432 case .selectingArea:
3472041d
RBR
433 if recordingWindow?.recordingContentView.box != nil {
434 "Ready to Record"
435 } else {
436 "Selecting"
437 }
c9b9e1d6 438 case .recording:
3472041d 439 "Stop Frame 1"
c9b9e1d6 440 case .uploading:
3472041d 441 "Upload Frame 1"
c9b9e1d6 442 case .uploaded:
3472041d 443 "OK"
c9b9e1d6 444 case .error:
3472041d 445 "ERR"
c9b9e1d6 446 }
3472041d 447 button.image = NSImage(named: image)
c9b9e1d6
RBR
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 }
a4e80427 459
533cd932 460 private func uploadOrCopy() async -> Bool {
ba17de89 461 if captureSessionConfiguration.shouldUseBackend {
533cd932 462 let result = await uploadToBackend()
ba17de89 463 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
533cd932
RBR
464 deleteLocalFiles()
465 }
466 return result
467 } else {
468 copyLocalToClipboard()
469 return true
470 }
471 }
472
473 private func copyLocalToClipboard() {
ba17de89
RBR
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 {
c9b9e1d6
RBR
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 }
533cd932
RBR
483
484 private func uploadToBackend() async -> Bool {
ba17de89
RBR
485 let contentType = captureSessionConfiguration.shouldUploadGif ? "image/gif" : "video/mp4"
486 if let url = captureSessionConfiguration.shouldUploadGif ? outputFile?.gifURL : outputFile?.mp4URL {
533cd932 487 if let data = try? Data(contentsOf: url) {
ba17de89 488 if let remoteUrl = captureSessionConfiguration.backend {
533cd932
RBR
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() {
ba17de89 524 if captureSessionConfiguration.shouldSaveGif {
533cd932
RBR
525 if let url = outputFile?.gifURL {
526 try? FileManager.default.removeItem(at: url)
527 }
528 }
ba17de89 529 if captureSessionConfiguration.shouldSaveMp4 {
533cd932
RBR
530 if let url = outputFile?.mp4URL {
531 try? FileManager.default.removeItem(at: url)
532 }
533 }
534 }
a4e80427 535}