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