]> git.r.bdr.sh - rbdr/captura/blob - Captura/CapturaApp.swift
Complete initial release
[rbdr/captura] / Captura / CapturaApp.swift
1 import SwiftUI
2 import SwiftData
3 import Cocoa
4 import Combine
5 import AVFoundation
6
7 @main
8 struct 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
23 class 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 fps = CapturaSettings.frameRate
38 var pixelDensity: CGFloat = 1.0
39 var stopTimer: DispatchWorkItem?
40 var remoteFiles: [CapturaRemoteFile] = []
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: - UI Event Handlers
102
103 func menuWillOpen(_ menu: NSMenu) {
104 if captureState != .idle {
105 menu.cancelTracking()
106 if captureState == .recording {
107 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
108 }
109 }
110 }
111
112 @objc private func onClickStartRecording() {
113 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
114 }
115
116 @objc private func onOpenPreferences() {
117 NSApp.activate(ignoringOtherApps: true)
118 if preferencesWindow == nil {
119 preferencesWindow = PreferencesWindow()
120 } else {
121 preferencesWindow?.makeKeyAndOrderFront(nil)
122 preferencesWindow?.orderFrontRegardless()
123 }
124 }
125
126 @objc private func onOpenFolder() {
127 if let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first?.appendingPathComponent("captura") {
128 NSWorkspace.shared.open(directory)
129 }
130 }
131
132 @objc private func onClickRemoteFile(_ sender: NSMenuItem) {
133 if let remoteFile = sender.representedObject as? CapturaRemoteFile {
134 if let urlString = remoteFile.url {
135 if let url = URL(string: urlString) {
136 NSWorkspace.shared.open(url)
137 }
138 }
139 }
140 }
141
142 @objc private func onQuit() {
143 NSApplication.shared.terminate(self)
144 }
145
146 // MARK: - App State Event Listeners
147
148 @objc func didReceiveNotification(_ notification: Notification) {
149 switch(notification.name) {
150 case .startAreaSelection:
151 startAreaSelection()
152 case .startRecording:
153 startRecording()
154 case .stopRecording:
155 stopRecording()
156 case .finalizeRecording:
157 DispatchQueue.main.async {
158 self.finalizeRecording()
159 }
160 case .reset:
161 reset()
162 case .failedToStart:
163 DispatchQueue.main.async {
164 self.failed(true)
165 }
166 case .failedtoUpload:
167 DispatchQueue.main.async {
168 self.failed()
169 }
170 case .receivedFrame:
171 if let frame = notification.userInfo?["frame"] {
172 receivedFrame(frame as! CVImageBuffer)
173 }
174 case .NSManagedObjectContextObjectsDidChange:
175 DispatchQueue.main.async {
176 self.fetchRemoteItems()
177 self.setupMenu()
178 }
179 default:
180 return
181 }
182 }
183
184
185 func startAreaSelection() {
186 helpShown = false
187 if captureState != .selectingArea {
188 captureState = .selectingArea
189 if let button = statusItem.button {
190 let rectInWindow = button.convert(button.bounds, to: nil)
191 let rectInScreen = button.window?.convertToScreen(rectInWindow)
192 NSApp.activate(ignoringOtherApps: true)
193 recordingWindow = RecordingWindow(rectInScreen)
194 recordingWindow?.makeKeyAndOrderFront(nil)
195 recordingWindow?.orderFrontRegardless()
196 boxListener = recordingWindow?.recordingContentView.$box
197 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
198 .sink { newValue in
199 if newValue != nil {
200 self.updateImage()
201 if !self.helpShown {
202 self.helpShown = true
203 self.showPopoverWithMessage("Click here when you're ready to record.")
204 }
205 }
206 }
207 }
208 }
209 }
210
211 func startRecording() {
212 captureState = .recording
213 updateImage()
214 fps = CapturaSettings.frameRate
215 outputFile = nil
216 images = [];
217 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
218 recordingWindow?.recordingContentView.startRecording()
219 if let box = recordingWindow?.recordingContentView.box {
220 if let screen = recordingWindow?.screen {
221 captureSession = CapturaCaptureSession(screen, box: box)
222
223 if let captureSession {
224
225 stopTimer = DispatchWorkItem {
226 self.stopRecording()
227 }
228 DispatchQueue.main.asyncAfter(deadline: .now() + 300, execute: stopTimer!)
229
230 outputFile = CapturaFile()
231 if CapturaSettings.shouldSaveMp4 {
232 captureSession.startRecording(to: outputFile!.mp4URL)
233 } else {
234 captureSession.startRunning()
235 }
236 return
237 }
238 }
239 }
240 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
241 }
242
243 func stopRecording() {
244 captureState = .uploading
245 updateImage()
246 stop()
247
248 Task.detached {
249 if CapturaSettings.shouldSaveGif {
250 if let outputFile = self.outputFile {
251 await GifRenderer.render(self.images, at: self.fps, to: outputFile.gifURL)
252 }
253 }
254 let wasSuccessful = await self.uploadOrCopy()
255 if wasSuccessful {
256 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
257 } else {
258 NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil)
259 }
260 }
261 }
262
263 func finalizeRecording() {
264 captureState = .uploaded
265 updateImage()
266 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
267 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
268 }
269 }
270
271 func reset() {
272 captureState = .idle
273 updateImage()
274 stop()
275 }
276
277 func receivedFrame(_ frame: CVImageBuffer) {
278 let now = ContinuousClock.now
279
280 if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(fps)) {
281 gifCallbackTimer = now
282 DispatchQueue.main.async {
283 if let cgImage = frame.cgImage?.resize(by: self.pixelDensity) {
284 self.images.append(cgImage)
285 }
286 }
287 }
288 }
289
290 func failed(_ requestPermission: Bool = false) {
291 captureState = .error
292 updateImage()
293 if requestPermission {
294 requestPermissionToRecord()
295 }
296 stop()
297 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
298 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
299 }
300 }
301
302 // MARK: - CoreData
303
304 private func fetchRemoteItems() {
305 let viewContext = PersistenceController.shared.container.viewContext
306 let fetchRequest = NSFetchRequest<CapturaRemoteFile>(entityName: "CapturaRemoteFile")
307 fetchRequest.fetchLimit = 5
308 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
309
310 let results = try? viewContext.fetch(fetchRequest)
311 remoteFiles = results ?? []
312 }
313
314 // MARK: - Presentation Helpers
315
316
317 private func requestPermissionToRecord() {
318 showPopoverWithMessage("Please grant Captura permission to record")
319 if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording") {
320 NSWorkspace.shared.open(url)
321 }
322 }
323
324 private func showPopoverWithMessage(_ message: String) {
325 if let button = statusItem.button {
326 (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message)
327 self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
328 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
329 self.popover?.performClose(nil)
330 }
331 }
332 }
333
334 private func updateImage() {
335 if let button = statusItem.button {
336 let image: String = switch captureState {
337 case .idle:
338 "rectangle.dashed.badge.record"
339 case .selectingArea:
340 "circle.rectangle.dashed"
341 case .recording:
342 "checkmark.rectangle"
343 case .uploading:
344 "dock.arrow.up.rectangle"
345 case .uploaded:
346 "checkmark.rectangle.fill"
347 case .error:
348 "xmark.rectangle.fill"
349 }
350 button.image = NSImage(systemSymbolName: image, accessibilityDescription: "Captura")
351 }
352 }
353
354 private func stop() {
355 stopTimer?.cancel()
356 captureSession?.stopRunning()
357 captureSession = nil
358 boxListener?.cancel()
359 recordingWindow?.close()
360 recordingWindow = nil
361 }
362
363 private func uploadOrCopy() async -> Bool {
364 if CapturaSettings.shouldUseBackend {
365 let result = await uploadToBackend()
366 if result && !CapturaSettings.shouldKeepLocalFiles {
367 deleteLocalFiles()
368 }
369 return result
370 } else {
371 copyLocalToClipboard()
372 return true
373 }
374 }
375
376 private func copyLocalToClipboard() {
377 let fileType: NSPasteboard.PasteboardType = .init(rawValue: CapturaSettings.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
378 if let url = CapturaSettings.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL {
379 if let data = try? Data(contentsOf: url) {
380 let pasteboard = NSPasteboard.general
381 pasteboard.declareTypes([fileType], owner: nil)
382 pasteboard.setData(data, forType: fileType)
383 }
384 }
385 }
386
387 private func uploadToBackend() async -> Bool {
388 let contentType = CapturaSettings.shouldUploadGif ? "image/gif" : "video/mp4"
389 if let url = CapturaSettings.shouldUploadGif ? outputFile?.gifURL : outputFile?.mp4URL {
390 if let data = try? Data(contentsOf: url) {
391 if let remoteUrl = CapturaSettings.backend {
392 var request = URLRequest(url: remoteUrl)
393 request.httpMethod = "POST"
394 request.httpBody = data
395 request.setValue(contentType, forHTTPHeaderField: "Content-Type")
396 request.setValue("Captura/1.0", forHTTPHeaderField: "User-Agent")
397
398 do {
399 let (data, response) = try await URLSession.shared.data(for: request)
400
401 if let httpResponse = response as? HTTPURLResponse {
402 if httpResponse.statusCode == 201 {
403 let answer = try JSONDecoder().decode(BackendResponse.self, from: data)
404 createRemoteFile(answer.url)
405 return true
406 }
407 }
408 } catch {}
409 }
410 }
411 }
412 return false
413 }
414
415 private func createRemoteFile(_ url: URL) {
416 let viewContext = PersistenceController.shared.container.viewContext
417 let remoteFile = CapturaRemoteFile(context: viewContext)
418 remoteFile.url = url.absoluteString
419 remoteFile.timestamp = Date()
420 try? viewContext.save()
421 let pasteboard = NSPasteboard.general
422 pasteboard.declareTypes([.URL], owner: nil)
423 pasteboard.setString(url.absoluteString, forType: .string)
424 }
425
426 private func deleteLocalFiles() {
427 if CapturaSettings.shouldSaveGif {
428 if let url = outputFile?.gifURL {
429 try? FileManager.default.removeItem(at: url)
430 }
431 }
432 if CapturaSettings.shouldSaveMp4 {
433 if let url = outputFile?.mp4URL {
434 try? FileManager.default.removeItem(at: url)
435 }
436 }
437 }
438 }