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