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