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