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