]> git.r.bdr.sh - rbdr/captura/blame_incremental - Captura/CapturaApp.swift
Add clipboard
[rbdr/captura] / Captura / CapturaApp.swift
... / ...
CommitLineData
1import SwiftUI
2import SwiftData
3import Cocoa
4import Combine
5import AVFoundation
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"))
19 .modelContainer(for: CapturaRemoteFile.self)
20 }
21}
22
23class 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
41 func applicationDidFinishLaunching(_ notification: Notification) {
42 setupMenu()
43 NotificationCenter.default.addObserver(
44 self,
45 selector: #selector(self.didReceiveNotification(_:)),
46 name: nil,
47 object: nil)
48 closeWindow()
49 }
50
51 // MARK: - Setup Functions
52
53
54 private func setupMenu() {
55 statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
56
57 if let button = statusItem.button {
58 button.image = NSImage(systemSymbolName: "rectangle.dashed.badge.record", accessibilityDescription: "Captura")
59 }
60
61 statusItem.isVisible = true
62 statusItem.menu = NSMenu()
63 statusItem.menu?.delegate = self
64
65 // Create the Popover
66 popover = NSPopover()
67 popover?.contentViewController = HelpPopoverViewController()
68 popover?.behavior = .transient
69
70
71 let recordItem = NSMenuItem(title: "Record", action: #selector(CapturaAppDelegate.onClickStartRecording), keyEquivalent: "6")
72 recordItem.keyEquivalentModifierMask = [.command, .shift]
73 statusItem.menu?.addItem(recordItem)
74 statusItem.menu?.addItem(NSMenuItem.separator())
75
76 let preferencesItem = NSMenuItem(title: "Preferences", action: #selector(CapturaAppDelegate.onOpenPreferences), keyEquivalent: "")
77 statusItem.menu?.addItem(preferencesItem)
78
79 let quitItem = NSMenuItem(title: "Quit", action: #selector(CapturaAppDelegate.onQuit), keyEquivalent: "")
80 statusItem.menu?.addItem(quitItem)
81 }
82
83 private func closeWindow() {
84 if let window = NSApplication.shared.windows.first {
85 window.close()
86 }
87 }
88
89 // MARK: - UI Event Handlers
90
91 func menuWillOpen(_ menu: NSMenu) {
92 if captureState != .idle {
93 menu.cancelTracking()
94 if captureState == .recording {
95 NotificationCenter.default.post(name: .stopRecording, object: nil, userInfo: nil)
96 }
97 }
98 }
99
100 @objc private func onClickStartRecording() {
101 NotificationCenter.default.post(name: .startAreaSelection, object: nil, userInfo: nil)
102 }
103
104 @objc private func onOpenPreferences() {
105 NSApp.activate(ignoringOtherApps: true)
106 if preferencesWindow == nil {
107 preferencesWindow = PreferencesWindow()
108 } else {
109 preferencesWindow?.makeKeyAndOrderFront(nil)
110 }
111 }
112
113 @objc private func onQuit() {
114 NSApplication.shared.terminate(self)
115 }
116
117 // MARK: - App State Event Listeners
118
119 @objc func didReceiveNotification(_ notification: Notification) {
120 switch(notification.name) {
121 case .startAreaSelection:
122 startAreaSelection()
123 case .startRecording:
124 startRecording()
125 case .stopRecording:
126 stopRecording()
127 case .finalizeRecording:
128 DispatchQueue.main.async {
129 self.finalizeRecording()
130 }
131 case .reset:
132 reset()
133 case .failedToStart:
134 failedToStart()
135 case .receivedFrame:
136 if let frame = notification.userInfo?["frame"] {
137 receivedFrame(frame as! CVImageBuffer)
138 }
139 default:
140 return
141 }
142 }
143
144
145 func startAreaSelection() {
146 helpShown = false
147 NSApp.activate(ignoringOtherApps: true)
148 if captureState != .selectingArea {
149 captureState = .selectingArea
150 if let button = statusItem.button {
151 let rectInWindow = button.convert(button.bounds, to: nil)
152 let rectInScreen = button.window?.convertToScreen(rectInWindow)
153 recordingWindow = RecordingWindow(rectInScreen)
154 boxListener = recordingWindow?.recordingContentView.$box
155 .debounce(for: .seconds(0.3), scheduler: RunLoop.main)
156 .sink { newValue in
157 if newValue != nil {
158 self.updateImage()
159 if !self.helpShown {
160 self.helpShown = true
161 self.showPopoverWithMessage("Click here when you're ready to record.")
162 }
163 }
164 }
165 }
166 }
167 }
168
169 func startRecording() {
170 captureState = .recording
171 updateImage()
172 fps = CapturaSettings.frameRate
173 outputFile = nil
174 images = [];
175 pixelDensity = recordingWindow?.pixelDensity ?? 1.0
176 recordingWindow?.recordingContentView.startRecording()
177 if let box = recordingWindow?.recordingContentView.box {
178 if let screen = recordingWindow?.screen {
179 captureSession = CapturaCaptureSession(screen, box: box)
180
181 if let captureSession {
182
183 stopTimer = DispatchWorkItem {
184 self.stopRecording()
185 }
186 DispatchQueue.main.asyncAfter(deadline: .now() + 300, execute: stopTimer!)
187
188 outputFile = CapturaFile()
189 if CapturaSettings.shouldSaveMp4 {
190 captureSession.startRecording(to: outputFile!.mp4URL)
191 } else {
192 captureSession.startRunning()
193 }
194 return
195 }
196 }
197 }
198 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
199 }
200
201 func stopRecording() {
202 captureState = .uploading
203 updateImage()
204 stop()
205
206 if !CapturaSettings.shouldSaveMp4 {
207 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
208 return
209 }
210
211 Task.detached {
212 if let outputFile = self.outputFile {
213 await GifRenderer.render(self.images, at: self.fps, to: outputFile.gifURL)
214 NotificationCenter.default.post(name: .finalizeRecording, object: nil, userInfo: nil)
215 }
216 }
217 }
218
219 func finalizeRecording() {
220 captureState = .uploaded
221 copyToClipboard()
222 updateImage()
223 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
224 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
225 }
226 }
227
228 func reset() {
229 captureState = .idle
230 updateImage()
231 stop()
232 }
233
234 func receivedFrame(_ frame: CVImageBuffer) {
235 let now = ContinuousClock.now
236
237 if now - gifCallbackTimer > .nanoseconds(1_000_000_000 / UInt64(fps)) {
238 gifCallbackTimer = now
239 DispatchQueue.main.async {
240 if let cgImage = frame.cgImage?.resize(by: self.pixelDensity) {
241 self.images.append(cgImage)
242 }
243 }
244 }
245 }
246
247 func failedToStart() {
248 captureState = .error
249 updateImage()
250 requestPermissionToRecord()
251 stop()
252 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
253 NotificationCenter.default.post(name: .reset, object: nil, userInfo: nil)
254 }
255 }
256
257 // MARK: - Presentation Helpers
258
259
260 private func requestPermissionToRecord() {
261 showPopoverWithMessage("Please grant Captura permission to record")
262 if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenRecording") {
263 NSWorkspace.shared.open(url)
264 }
265 }
266
267 private func showPopoverWithMessage(_ message: String) {
268 if let button = statusItem.button {
269 (self.popover?.contentViewController as? HelpPopoverViewController)?.updateLabel(message)
270 self.popover?.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
271 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
272 self.popover?.performClose(nil)
273 }
274 }
275 }
276
277 private func updateImage() {
278 if let button = statusItem.button {
279 let image: String = switch captureState {
280 case .idle:
281 "rectangle.dashed.badge.record"
282 case .selectingArea:
283 "circle.rectangle.dashed"
284 case .recording:
285 "checkmark.rectangle"
286 case .uploading:
287 "dock.arrow.up.rectangle"
288 case .uploaded:
289 "checkmark.rectangle.fill"
290 case .error:
291 "xmark.rectangle.fill"
292 }
293 button.image = NSImage(systemSymbolName: image, accessibilityDescription: "Captura")
294 }
295 }
296
297 private func stop() {
298 stopTimer?.cancel()
299 captureSession?.stopRunning()
300 captureSession = nil
301 boxListener?.cancel()
302 recordingWindow?.close()
303 recordingWindow = nil
304 }
305
306 private func copyToClipboard() {
307 let fileType: NSPasteboard.PasteboardType = .init(rawValue: CapturaSettings.shouldSaveGif ? "com.compuserve.gif" : "public.mpeg-4")
308 if let url = CapturaSettings.shouldSaveGif ? outputFile?.gifURL : outputFile?.mp4URL {
309 if let data = try? Data(contentsOf: url) {
310 let pasteboard = NSPasteboard.general
311 pasteboard.declareTypes([fileType], owner: nil)
312 pasteboard.setData(data, forType: fileType)
313 }
314 }
315 }
316}