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