]>
Commit | Line | Data |
---|---|---|
a4e80427 RBR |
1 | import SwiftUI |
2 | import SwiftData | |
3 | import Cocoa | |
4 | import Combine | |
c9b9e1d6 | 5 | import AVFoundation |
a4e80427 RBR |
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")) | |
533cd932 | 19 | //.modelContainer(for: CapturaRemoteFile.self) |
a4e80427 RBR |
20 | } |
21 | } | |
22 | ||
c9b9e1d6 | 23 | 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 |
c9b9e1d6 | 37 | var fps = CapturaSettings.frameRate |
a4e80427 RBR |
38 | var pixelDensity: CGFloat = 1.0 |
39 | var stopTimer: DispatchWorkItem? | |
533cd932 | 40 | var remoteFiles: [CapturaRemoteFile] = [] |
a4e80427 RBR |
41 | |
42 | func applicationDidFinishLaunching(_ notification: Notification) { | |
533cd932 | 43 | setupStatusBar() |
a4e80427 RBR |
44 | NotificationCenter.default.addObserver( |
45 | self, | |
46 | selector: #selector(self.didReceiveNotification(_:)), | |
47 | name: nil, | |
48 | object: nil) | |
49 | closeWindow() | |
533cd932 | 50 | fetchRemoteItems() |
a4e80427 RBR |
51 | } |
52 | ||
53 | // MARK: - Setup Functions | |
54 | ||
55 | ||
533cd932 | 56 | private func setupStatusBar() { |
a4e80427 RBR |
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 | ||
533cd932 RBR |
72 | setupMenu() |
73 | } | |
74 | ||
75 | private func setupMenu() { | |
a4e80427 | 76 | |
533cd932 | 77 | statusItem.menu?.removeAllItems() |
a4e80427 | 78 | |
533cd932 RBR |
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: "")) | |
a4e80427 RBR |
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 { | |
f5d16c1c | 107 | NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil) |
a4e80427 RBR |
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) | |
533cd932 RBR |
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 | } | |
a4e80427 RBR |
139 | } |
140 | } | |
141 | ||
142 | @objc private func onQuit() { | |
143 | NSApplication.shared.terminate(self) | |
144 | } | |
145 | ||
a4e80427 RBR |
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: | |
f5d16c1c RBR |
157 | DispatchQueue.main.async { |
158 | self.finalizeRecording() | |
159 | } | |
a4e80427 RBR |
160 | case .reset: |
161 | reset() | |
c9b9e1d6 | 162 | case .failedToStart: |
533cd932 RBR |
163 | DispatchQueue.main.async { |
164 | self.failed(true) | |
165 | } | |
166 | case .failedtoUpload: | |
167 | DispatchQueue.main.async { | |
168 | self.failed() | |
169 | } | |
c9b9e1d6 RBR |
170 | case .receivedFrame: |
171 | if let frame = notification.userInfo?["frame"] { | |
172 | receivedFrame(frame as! CVImageBuffer) | |
173 | } | |
533cd932 RBR |
174 | case .NSManagedObjectContextObjectsDidChange: |
175 | DispatchQueue.main.async { | |
176 | self.fetchRemoteItems() | |
177 | self.setupMenu() | |
178 | } | |
a4e80427 RBR |
179 | default: |
180 | return | |
181 | } | |
a4e80427 RBR |
182 | } |
183 | ||
184 | ||
c9b9e1d6 | 185 | func startAreaSelection() { |
a4e80427 | 186 | helpShown = false |
a4e80427 RBR |
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) | |
533cd932 | 192 | NSApp.activate(ignoringOtherApps: true) |
a4e80427 | 193 | recordingWindow = RecordingWindow(rectInScreen) |
533cd932 RBR |
194 | recordingWindow?.makeKeyAndOrderFront(nil) |
195 | recordingWindow?.orderFrontRegardless() | |
c9b9e1d6 RBR |
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.") | |
a4e80427 RBR |
204 | } |
205 | } | |
c9b9e1d6 | 206 | } |
a4e80427 RBR |
207 | } |
208 | } | |
209 | } | |
210 | ||
211 | func startRecording() { | |
212 | captureState = .recording | |
c9b9e1d6 RBR |
213 | updateImage() |
214 | fps = CapturaSettings.frameRate | |
f5d16c1c | 215 | outputFile = nil |
a4e80427 RBR |
216 | images = []; |
217 | pixelDensity = recordingWindow?.pixelDensity ?? 1.0 | |
c9b9e1d6 RBR |
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!) | |
a4e80427 | 229 | |
c9b9e1d6 RBR |
230 | outputFile = CapturaFile() |
231 | if CapturaSettings.shouldSaveMp4 { | |
232 | captureSession.startRecording(to: outputFile!.mp4URL) | |
233 | } else { | |
a4e80427 | 234 | captureSession.startRunning() |
a4e80427 | 235 | } |
c9b9e1d6 | 236 | return |
a4e80427 RBR |
237 | } |
238 | } | |
239 | } | |
c9b9e1d6 | 240 | NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil) |
a4e80427 RBR |
241 | } |
242 | ||
243 | func stopRecording() { | |
a4e80427 | 244 | captureState = .uploading |
c9b9e1d6 RBR |
245 | updateImage() |
246 | stop() | |
f5d16c1c | 247 | |
a4e80427 | 248 | Task.detached { |
533cd932 RBR |
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 { | |
f5d16c1c | 256 | NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil) |
533cd932 RBR |
257 | } else { |
258 | NotificationCenter.default.post(name: .failedtoUpload, object: nil, userInfo: nil) | |
a4e80427 RBR |
259 | } |
260 | } | |
a4e80427 RBR |
261 | } |
262 | ||
263 | func finalizeRecording() { | |
264 | captureState = .uploaded | |
c9b9e1d6 | 265 | updateImage() |
f5d16c1c | 266 | DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { |
c9b9e1d6 | 267 | NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil) |
f5d16c1c | 268 | } |
a4e80427 RBR |
269 | } |
270 | ||
271 | func reset() { | |
a4e80427 | 272 | captureState = .idle |
c9b9e1d6 RBR |
273 | updateImage() |
274 | stop() | |
a4e80427 RBR |
275 | } |
276 | ||
c9b9e1d6 | 277 | func receivedFrame(_ frame: CVImageBuffer) { |
a4e80427 RBR |
278 | let now = ContinuousClock.now |
279 | ||
280 | if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(fps)) { | |
281 | gifCallbackTimer = now | |
282 | DispatchQueue.main.async { | |
c9b9e1d6 RBR |
283 | if let cgImage = frame.cgImage?.resize(by: self.pixelDensity) { |
284 | self.images.append(cgImage) | |
a4e80427 RBR |
285 | } |
286 | } | |
287 | } | |
288 | } | |
289 | ||
533cd932 | 290 | func failed(_ requestPermission: Bool = false) { |
c9b9e1d6 RBR |
291 | captureState = .error |
292 | updateImage() | |
533cd932 RBR |
293 | if requestPermission { |
294 | requestPermissionToRecord() | |
295 | } | |
c9b9e1d6 RBR |
296 | stop() |
297 | DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { | |
298 | NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil) | |
299 | } | |
300 | } | |
301 | ||
533cd932 RBR |
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 | ||
c9b9e1d6 RBR |
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 | ||
a4e80427 RBR |
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 | ||
c9b9e1d6 RBR |
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 | } | |
a4e80427 | 362 | |
533cd932 RBR |
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() { | |
c9b9e1d6 RBR |
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 | } | |
533cd932 RBR |
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 | } | |
a4e80427 | 438 | } |