]> git.r.bdr.sh - rbdr/captura/blame_incremental - Captura/CapturaApp.swift
Allow URL configuration
[rbdr/captura] / Captura / CapturaApp.swift
... / ...
CommitLineData
1import SwiftUI
2import SwiftData
3import Cocoa
4import Combine
5import AVFoundation
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"))
19 //.modelContainer(for: CapturaRemoteFile.self)
20 }
21}
22
23class CapturaAppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
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
33 var captureSession: CapturaCaptureSession? = nil
34 var images: [CGImage] = []
35 var outputFile: CapturaFile? = nil
36 var gifCallbackTimer = ContinuousClock.now
37 var pixelDensity: CGFloat = 1.0
38 var stopTimer: DispatchWorkItem?
39 var remoteFiles: [CapturaRemoteFile] = []
40 var captureSessionConfiguration: CaptureSessionConfiguration = CaptureSessionConfiguration()
41
42 func applicationDidFinishLaunching(_ notification: Notification) {
43 setupStatusBar()
44 NotificationCenter.default.addObserver(
45 self,
46 selector: #selector(self.didReceiveNotification(_:)),
47 name: nil,
48 object: nil)
49 closeWindow()
50 fetchRemoteItems()
51 }
52
53 // MARK: - Setup Functions
54
55
56 private func setupStatusBar() {
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
72 setupMenu()
73 }
74
75 private func setupMenu() {
76
77 statusItem.menu?.removeAllItems()
78
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: ""))
93 }
94
95 private func closeWindow() {
96 if let window = NSApplication.shared.windows.first {
97 window.close()
98 }
99 }
100
101 // MARK: - URL Event Handler
102
103 func application(_ application: NSApplication, open urls: [URL]) {
104 print("AAAH OPENING")
105 if (CapturaSettings.shouldAllowURLAutomation) {
106 for url in urls {
107 if let action = CapturaURLDecoder.decodeParams(url: url) {
108 switch action {
109 case let .configure(config):
110 print("AAAH CONFIGURING \(config)")
111 CapturaSettings.apply(config)
112 case let .record(config):
113 print(config)
114 }
115 }
116 }
117 } else {
118 let alert = NSAlert()
119 alert.messageText = "URL Automation Prevented"
120 alert.informativeText = "A website or application attempted to record your screen using URL Automation. If you want to allow this, enable it in Preferences."
121 alert.alertStyle = .warning
122 alert.addButton(withTitle: "OK")
123 alert.runModal()
124 }
125 }
126
127 // MARK: - UI Event Handlers
128
129 func menuWillOpen(_ menu: NSMenu) {
130 if captureState != .idle {
131 menu.cancelTracking()
132 if captureState == .recording {
133 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
134 }
135 }
136 }
137
138 @objc private func onClickStartRecording() {
139 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
140 }
141
142 @objc private func onOpenPreferences() {
143 NSApp.activate(ignoringOtherApps: true)
144 if preferencesWindow == nil {
145 preferencesWindow = PreferencesWindow()
146 } else {
147 preferencesWindow?.makeKeyAndOrderFront(nil)
148 preferencesWindow?.orderFrontRegardless()
149 }
150 }
151
152 @objc private func onOpenFolder() {
153 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?.appendingPathComponent("captura") {
154 NSWorkspace.shared.open(directory)
155 }
156 }
157
158 @objc private func onClickRemoteFile(_ sender: NSMenuItem) {
159 if let remoteFile = sender.representedObject as? CapturaRemoteFile {
160 if let urlString = remoteFile.url {
161 if let url = URL(string: urlString) {
162 NSWorkspace.shared.open(url)
163 }
164 }
165 }
166 }
167
168 @objc private func onQuit() {
169 NSApplication.shared.terminate(self)
170 }
171
172 // MARK: - App State Event Listeners
173
174 @objc func didReceiveNotification(_ notification: Notification) {
175 switch(notification.name) {
176 case .startAreaSelection:
177 startAreaSelection()
178 case .startRecording:
179 startRecording()
180 case .stopRecording:
181 stopRecording()
182 case .finalizeRecording:
183 DispatchQueue.main.async {
184 self.finalizeRecording()
185 }
186 case .reset:
187 reset()
188 case .failedToStart:
189 DispatchQueue.main.async {
190 self.failed(true)
191 }
192 case .failedtoUpload:
193 DispatchQueue.main.async {
194 self.failed()
195 }
196 case .receivedFrame:
197 if let frame = notification.userInfo?["frame"] {
198 receivedFrame(frame as! CVImageBuffer)
199 }
200 case .NSManagedObjectContextObjectsDidChange:
201 DispatchQueue.main.async {
202 self.fetchRemoteItems()
203 self.setupMenu()
204 }
205 default:
206 return
207 }
208 }
209
210
211 func startAreaSelection() {
212 helpShown = false
213 if captureState != .selectingArea {
214 captureState = .selectingArea
215 if let button = statusItem.button {
216 let rectInWindow = button.convert(button.bounds, to: nil)
217 let rectInScreen = button.window?.convertToScreen(rectInWindow)
218 NSApp.activate(ignoringOtherApps: true)
219 recordingWindow = RecordingWindow(rectInScreen)
220 recordingWindow?.makeKeyAndOrderFront(nil)
221 recordingWindow?.orderFrontRegardless()
222 boxListener = recordingWindow?.recordingContentView.$box
223 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
224 .sink { newValue in
225 if newValue != nil {
226 self.updateImage()
227 if !self.helpShown {
228 self.helpShown = true
229 self.showPopoverWithMessage("Click here when you're ready to record.")
230 }
231 }
232 }
233 }
234 }
235 }
236
237 func startRecording() {
238 captureState = .recording
239 updateImage()
240 outputFile = nil
241 images = [];
242 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
243 recordingWindow?.recordingContentView.startRecording()
244 if let box = recordingWindow?.recordingContentView.box {
245 if let screen = recordingWindow?.screen {
246 captureSession = CapturaCaptureSession(screen, box: box)
247
248 if let captureSession {
249
250 stopTimer = DispatchWorkItem {
251 self.stopRecording()
252 }
253 DispatchQueue.main.asyncAfter(deadline: .now() + 300, execute: stopTimer!)
254
255 outputFile = CapturaFile()
256 if captureSessionConfiguration.shouldSaveMp4 {
257 captureSession.startRecording(to: outputFile!.mp4URL)
258 } else {
259 captureSession.startRunning()
260 }
261 return
262 }
263 }
264 }
265 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
266 }
267
268 func stopRecording() {
269 captureState = .uploading
270 updateImage()
271 stop()
272
273 Task.detached {
274 if self.captureSessionConfiguration.shouldSaveGif {
275 if let outputFile = self.outputFile {
276 await GifRenderer.render(self.images, at: self.captureSessionConfiguration.frameRate, to: outputFile.gifURL)
277 }
278 }
279 let wasSuccessful = await self.uploadOrCopy()
280 if wasSuccessful {
281 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
282 } else {
283 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
284 }
285 }
286 }
287
288 func finalizeRecording() {
289 captureState = .uploaded
290 updateImage()
291 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
292 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
293 }
294 }
295
296 func reset() {
297 captureState = .idle
298 updateImage()
299 stop()
300 }
301
302 func receivedFrame(_ frame: CVImageBuffer) {
303 let now = ContinuousClock.now
304
305 if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(captureSessionConfiguration.frameRate)) {
306 gifCallbackTimer = now
307 DispatchQueue.main.async {
308 if let cgImage = frame.cgImage?.resize(by: self.pixelDensity) {
309 self.images.append(cgImage)
310 }
311 }
312 }
313 }
314
315 func failed(_ requestPermission: Bool = false) {
316 captureState = .error
317 updateImage()
318 if requestPermission {
319 requestPermissionToRecord()
320 }
321 stop()
322 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
323 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
324 }
325 }
326
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
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
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
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 captureSessionConfiguration = CaptureSessionConfiguration()
387 }
388
389 private func uploadOrCopy() async -> Bool {
390 if captureSessionConfiguration.shouldUseBackend {
391 let result = await uploadToBackend()
392 if result && !captureSessionConfiguration.shouldKeepLocalFiles {
393 deleteLocalFiles()
394 }
395 return result
396 } else {
397 copyLocalToClipboard()
398 return true
399 }
400 }
401
402 private func copyLocalToClipboard() {
403 let fileType: NSPasteboard.PasteboardType = .init(rawValue: captureSessionConfiguration.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
404 if let url = captureSessionConfiguration.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL {
405 if let data = try? Data(contentsOf: url) {
406 let pasteboard = NSPasteboard.general
407 pasteboard.declareTypes([fileType], owner: nil)
408 pasteboard.setData(data, forType: fileType)
409 }
410 }
411 }
412
413 private func uploadToBackend() async -> Bool {
414 let contentType = captureSessionConfiguration.shouldUploadGif ? "image/gif" : "video/mp4"
415 if let url = captureSessionConfiguration.shouldUploadGif ? outputFile?.gifURL : outputFile?.mp4URL {
416 if let data = try? Data(contentsOf: url) {
417 if let remoteUrl = captureSessionConfiguration.backend {
418 var request = URLRequest(url: remoteUrl)
419 request.httpMethod = "POST"
420 request.httpBody = data
421 request.setValue(contentType, forHTTPHeaderField: "Content-Type")
422 request.setValue("Captura/1.0", forHTTPHeaderField: "User-Agent")
423
424 do {
425 let (data, response) = try await URLSession.shared.data(for: request)
426
427 if let httpResponse = response as? HTTPURLResponse {
428 if httpResponse.statusCode == 201 {
429 let answer = try JSONDecoder().decode(BackendResponse.self, from: data)
430 createRemoteFile(answer.url)
431 return true
432 }
433 }
434 } catch {}
435 }
436 }
437 }
438 return false
439 }
440
441 private func createRemoteFile(_ url: URL) {
442 let viewContext = PersistenceController.shared.container.viewContext
443 let remoteFile = CapturaRemoteFile(context: viewContext)
444 remoteFile.url = url.absoluteString
445 remoteFile.timestamp = Date()
446 try? viewContext.save()
447 let pasteboard = NSPasteboard.general
448 pasteboard.declareTypes([.URL], owner: nil)
449 pasteboard.setString(url.absoluteString, forType: .string)
450 }
451
452 private func deleteLocalFiles() {
453 if captureSessionConfiguration.shouldSaveGif {
454 if let url = outputFile?.gifURL {
455 try? FileManager.default.removeItem(at: url)
456 }
457 }
458 if captureSessionConfiguration.shouldSaveMp4 {
459 if let url = outputFile?.mp4URL {
460 try? FileManager.default.removeItem(at: url)
461 }
462 }
463 }
464}