-
Notifications
You must be signed in to change notification settings - Fork 63
/
remApp.swift
725 lines (611 loc) · 28.3 KB
/
remApp.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//
// remApp.swift
// rem
//
// Created by Jason McGhee on 12/16/23.
//
import AppKit
import CoreGraphics
import os
import ScreenCaptureKit
import ScriptingBridge
import SwiftUI
import Vision
import VisionKit
final class MainWindow: NSWindow {
override var canBecomeKey: Bool {
return true
}
}
enum CaptureState {
case recording
case stopped
case paused
}
@main
struct remApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
// Empty scene, as we are controlling everything through the AppDelegate
Settings { SettingsView(settingsManager: appDelegate.settingsManager) }
}
}
class AppDelegate: NSObject, NSApplicationDelegate {
private let logger = Logger(
subsystem: Bundle.main.bundleIdentifier!,
category: String(describing: AppDelegate.self)
)
var imageAnalyzer = ImageAnalyzer()
var timelineViewWindow: NSWindow?
var timelineView: TimelineView?
var settingsManager = SettingsManager()
var settingsViewWindow: NSWindow?
var statusBarItem: NSStatusItem!
var popover: NSPopover!
var searchViewWindow: NSWindow?
var searchView: SearchView?
var lastCaptureTime = Date()
var screenCaptureSession: SCStream?
var captureOutputURL: URL?
var lastVideoEncodingTime = Date()
let idleStatusImage = NSImage(named: "StatusIdle")
let recordingStatusImage = NSImage(named: "StatusRecording")
let idleStatusImageDark = NSImage(named: "StatusIdleDark")
let recordingStatusImageDark = NSImage(named: "StatusRecordingDark")
let ocrQueue = DispatchQueue(label: "today.jason.ocrQueue", attributes: .concurrent)
var imageBufferQueue = DispatchQueue(label: "today.jason.imageBufferQueue", attributes: .concurrent)
var imageDataBuffer = [Data]()
var ffmpegTimer: Timer?
var screenshotTimer: Timer?
private let frameThreshold = 30 // Number of frames after which FFmpeg processing is triggered
private var ffmpegProcess: Process?
private var ffmpegInputPipe: Pipe?
private var pendingScreenshotURLs = [URL]()
private var isCapturing: CaptureState = .stopped
private let screenshotQueue = DispatchQueue(label: "today.jason.screenshotQueue")
private var wasRecordingBeforeSleep: Bool = false
private var wasRecordingBeforeTimelineView: Bool = false
private var wasRecordingBeforeSearchView: Bool = false
private var lastImageData: Data? = nil
private var lastActiveApplication: String? = nil
func applicationDidFinishLaunching(_ notification: Notification) {
let _ = DatabaseManager.shared
// Initialize the popover
popover = NSPopover()
popover.contentSize = NSSize(width: 360, height: 360)
popover.behavior = .transient
popover.contentViewController = NSHostingController(rootView: ContentView())
// Create the status bar item
statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
// Setup Menu
setupMenu()
// Monitor for scroll events
NSEvent.addGlobalMonitorForEvents(matching: .scrollWheel) { [weak self] event in
self?.handleGlobalScrollEvent(event)
}
NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { [weak self] event in
if (self?.searchViewWindow?.isVisible ?? false) && event.keyCode == 53 {
DispatchQueue.main.async { [weak self] in
self?.closeSearchView()
}
}
if (self?.isTimelineOpen() ?? false) && event.keyCode == 53 {
DispatchQueue.main.async { [weak self] in
self?.closeTimelineView()
}
}
}
NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
if event.modifierFlags.contains([.command, .shift]) && event.keyCode == 3 {
DispatchQueue.main.async { [weak self] in
self?.closeTimelineView()
self?.showSearchView()
}
}
if (self?.searchViewWindow?.isVisible ?? false) && event.keyCode == 53 {
DispatchQueue.main.async { [weak self] in
self?.closeSearchView()
}
}
if (self?.isTimelineOpen() ?? false) && event.keyCode == 53 {
DispatchQueue.main.async { [weak self] in
self?.closeTimelineView()
}
}
return event
}
NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { [weak self] event in
if self?.isTimelineOpen() ?? false {
if !event.modifierFlags.contains(.command) && event.scrollingDeltaX != 0 {
self?.timelineView?.viewModel.updateIndex(withDelta: event.scrollingDeltaX)
}
if event.modifierFlags.contains(.command) && event.scrollingDeltaY > 0 && (self?.isTimelineOpen() ?? false) { // Check if scroll up
DispatchQueue.main.async { [weak self] in
self?.closeTimelineView()
}
}
}
return event
}
// Initialize the search view
searchView = SearchView(onThumbnailClick: openFullView)
observeSystemNotifications()
}
func drawStatusBarIcon(rect: CGRect) -> Bool {
// More robust dark mode detection
let isDarkMode = self.statusBarItem.button?.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
let icon = self.isCapturing == .recording ? (
isDarkMode ? self.recordingStatusImageDark : self.recordingStatusImage
) : (
isDarkMode ? self.idleStatusImageDark : self.idleStatusImage
)
icon?.draw(in: rect)
return true
}
func setupMenu() {
DispatchQueue.main.async {
if let button = self.statusBarItem.button {
button.image = NSImage(size: NSSize(width: 16, height: 16), flipped: false) { [weak self] rect in
return self?.drawStatusBarIcon(rect: rect) ?? false
}
button.action = #selector(self.togglePopover(_:))
}
let menu = NSMenu()
let recordingTitle = self.isCapturing == .recording ? "Stop Remembering" : "Start Remembering"
let recordingSelector = self.isCapturing == .recording ? #selector(self.disableRecording) : #selector(self.enableRecording)
menu.addItem(NSMenuItem(title: recordingTitle, action: recordingSelector, keyEquivalent: ""))
menu.addItem(NSMenuItem(title: "Toggle Timeline", action: #selector(self.toggleTimeline), keyEquivalent: ""))
menu.addItem(NSMenuItem(title: "Search", action: #selector(self.showSearchView), keyEquivalent: ""))
menu.addItem(NSMenuItem(title: "Copy Recent Context", action: #selector(self.copyRecentContext), keyEquivalent: ""))
menu.addItem(NSMenuItem.separator()) // Separator
menu.addItem(NSMenuItem(title: "Show Me My Data", action: #selector(self.showMeMyData), keyEquivalent: ""))
menu.addItem(NSMenuItem(title: "⚠️ Purge All Data ⚠️", action: #selector(self.confirmPurgeAllData), keyEquivalent: ""))
menu.addItem(NSMenuItem.separator()) // Separator
menu.addItem(
withTitle: "Settings",
action: #selector(self.openSettings),
keyEquivalent: ","
)
menu.addItem(NSMenuItem(title: "Quit", action: #selector(self.quitApp), keyEquivalent: "q"))
self.statusBarItem.menu = menu
}
}
@objc func showMeMyData() {
if let saveDir = RemFileManager.shared.getSaveDir() {
NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: saveDir.path)
}
}
@objc func toggleTimeline() {
if isTimelineOpen() {
closeTimelineView()
} else {
let frame = DatabaseManager.shared.getMaxFrame()
showTimelineView(with: frame)
}
}
@objc func openSettings() {
if settingsViewWindow == nil {
let settingsView = SettingsView(settingsManager: settingsManager)
settingsViewWindow = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 400, height: 300),
styleMask: [.titled, .closable],
backing: .buffered,
defer: false
)
settingsViewWindow?.isReleasedWhenClosed = false
settingsViewWindow?.center()
settingsViewWindow?.contentView = NSHostingView(rootView: settingsView)
settingsViewWindow?.makeKeyAndOrderFront(nil)
DispatchQueue.main.async {
self.settingsViewWindow?.orderFrontRegardless() // Ensure it comes to the front
}
} else if !(settingsViewWindow?.isVisible ?? false) {
settingsViewWindow?.makeKeyAndOrderFront(nil)
DispatchQueue.main.async {
self.settingsViewWindow?.orderFrontRegardless() // Ensure it comes to the front
}
}
}
@objc func confirmPurgeAllData() {
let alert = NSAlert()
alert.messageText = "Purge all data?"
alert.informativeText = "This is a permanent action and will delete everything rem has every seen."
alert.alertStyle = .warning
alert.addButton(withTitle: "Yes, delete everything")
alert.addButton(withTitle: "Cancel")
let response = alert.runModal()
if response == .alertFirstButtonReturn {
alert.window.close()
forgetEverything()
} else {
alert.window.close()
}
}
private func handleGlobalScrollEvent(_ event: NSEvent) {
guard settingsManager.settings.enableCmdScrollShortcut else { return }
guard event.modifierFlags.contains(.command) else { return }
if event.scrollingDeltaY < 0 && !isTimelineOpen() { // Check if scroll up
DispatchQueue.main.async { [weak self] in
self?.showTimelineView(with: DatabaseManager.shared.getMaxFrame())
}
}
}
@objc func togglePopover(_ sender: AnyObject?) {
if let button = statusBarItem.button {
if popover.isShown {
popover.performClose(sender)
} else {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
}
}
private func observeSystemNotifications() {
let workspaceNotificationCenter = NSWorkspace.shared.notificationCenter
workspaceNotificationCenter.addObserver(self, selector: #selector(systemWillSleep), name: NSWorkspace.willSleepNotification, object: nil)
workspaceNotificationCenter.addObserver(self, selector: #selector(systemDidWake), name: NSWorkspace.didWakeNotification, object: nil)
}
@objc private func systemWillSleep() {
logger.info("Detected sleep!")
// Logic to handle system going to sleep
wasRecordingBeforeSleep = (isCapturing == .recording)
if wasRecordingBeforeSleep {
pauseRecording()
}
}
@objc private func systemDidWake() {
logger.info("Detected wake!")
// Logic to handle system wake up
if wasRecordingBeforeSleep {
enableRecording()
}
}
func startScreenCapture() async {
do {
let shareableContent = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: false)
setupMenu()
screenshotQueue.async { [weak self] in
self?.scheduleScreenshot(shareableContent: shareableContent)
}
} catch {
logger.error("Error starting screen capture: \(error.localizedDescription)")
}
}
@objc private func copyRecentContext() {
let texts = DatabaseManager.shared.getRecentTextContext()
let text = TextMerger.shared.mergeTexts(texts: texts)
ClipboardManager.shared.replaceClipboardContents(with: text)
}
private func displayImageChangedFromLast(imageData: Data) -> Bool {
if let prevImage = lastImageData {
return prevImage.withUnsafeBytes { ptr1 in
imageData.withUnsafeBytes { ptr2 in
memcmp(ptr1.baseAddress, ptr2.baseAddress, imageData.count) != 0
}
}
}
return false
}
private func scheduleScreenshot(shareableContent: SCShareableContent) {
Task {
do {
guard isCapturing == .recording else { return }
var displayID: CGDirectDisplayID? = nil
if let screenID = NSScreen.main?.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber {
displayID = CGDirectDisplayID(screenID.uint32Value)
}
guard displayID != nil else { return }
guard let display = shareableContent.displays.first(where: { $0.displayID == displayID }) else { return }
let activeApplicationName = NSWorkspace.shared.frontmostApplication?.localizedName
logger.debug("Active Application: \(activeApplicationName ?? "<undefined>")")
// Do we want to record the timeline being searched?
guard let image = CGDisplayCreateImage(display.displayID, rect: display.frame) else { return }
let bitmapRep = NSBitmapImageRep(cgImage: image)
guard let imageData = bitmapRep.representation(using: .png, properties: [:]) else { return }
// Might as well only check if the applications are the same, otherwise obviously different
if activeApplicationName != lastActiveApplication || displayImageChangedFromLast(imageData: imageData) {
lastImageData = imageData;
lastActiveApplication = activeApplicationName;
let frameId = DatabaseManager.shared.insertFrame(activeApplicationName: activeApplicationName)
if settingsManager.settings.onlyOCRFrontmostWindow {
// User wants to perform OCR on only active window.
// We need to determine the scale factor for cropping. CGImage is
// measured in pixels, display sizes are measured in points.
let scale = max(CGFloat(image.width) / CGFloat(display.width), CGFloat(image.height) / CGFloat(display.height))
if
let window = shareableContent.windows.first(where: { $0.isOnScreen && $0.owningApplication?.processID == NSWorkspace.shared.frontmostApplication?.processIdentifier }),
let cropped = ImageHelper.cropImage(image: image, frame: window.frame, scale: scale)
{
self.performOCR(frameId: frameId, on: cropped)
}
} else {
// default: User wants to perform OCR on full display.
self.performOCR(frameId: frameId, on: image)
}
await processScreenshot(frameId: frameId, imageData: imageData, frame: display.frame)
} else {
logger.info("Screen didn't change! Not processing frame.")
}
} catch {
logger.error("Error taking screenshot: \(error)")
}
screenshotQueue.asyncAfter(deadline: .now() + 2) { [weak self] in
self?.scheduleScreenshot(shareableContent: shareableContent)
}
}
}
@objc func forgetEverything() {
if let savedir = RemFileManager.shared.getSaveDir() {
if FileManager.default.fileExists(atPath: savedir.path) {
do {
try FileManager.default.subpathsOfDirectory(atPath: savedir.path).forEach { path in
if !path.hasSuffix(".sqlite3") {
let fileToDelete = savedir.appendingPathComponent(path)
try FileManager.default.removeItem(at: fileToDelete)
}
}
} catch {
logger.error("Error deleting folder: \(error)")
}
} else {
logger.error("Error finding folder.")
}
}
DatabaseManager.shared.purge()
}
func stopScreenCapture() {
isCapturing = .stopped
logger.info("Screen capture stopped")
}
func pauseScreenCapture() {
isCapturing = .paused
logger.info("Screen capture paused")
}
// // Old method
// func takeScreenshot(filter: SCContentFilter, configuration: SCStreamConfiguration, frame: CGRect) async {
// do {
// let image = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: configuration)
// await processScreenshot(image: image, frame: frame)
// } catch {
// print("Error taking screenshot: \(error.localizedDescription)")
// }
// }
private func processScreenshot(frameId: Int64, imageData: Data, frame: CGRect) async {
imageBufferQueue.async(flags: .barrier) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.imageDataBuffer.append(imageData)
// Quickly move the images to a temporary buffer if the threshold is reached
var tempBuffer: [Data] = []
if strongSelf.imageDataBuffer.count >= strongSelf.frameThreshold {
tempBuffer = Array(strongSelf.imageDataBuffer.prefix(strongSelf.frameThreshold))
strongSelf.imageDataBuffer.removeFirst(strongSelf.frameThreshold)
}
// Process the images outside of the critical section
if !tempBuffer.isEmpty {
strongSelf.processChunk(tempBuffer)
}
}
}
private func processChunk(_ chunk: [Data]) {
// Create a unique output file for each chunk
if let savedir = RemFileManager.shared.getSaveDir() {
let outputPath = savedir.appendingPathComponent("output-\(Date().timeIntervalSince1970).mp4").path
let _ = DatabaseManager.shared.startNewVideoChunk(filePath: outputPath)
// Setup the FFmpeg process for the chunk
let ffmpegProcess = Process()
let bundleURL = Bundle.main.bundleURL
ffmpegProcess.executableURL = bundleURL.appendingPathComponent("Contents/MacOS/ffmpeg")
ffmpegProcess.arguments = [
"-f", "image2pipe",
"-vcodec", "png",
"-i", "-",
"-power_efficient", "1",
"-color_trc", "iec61966_2_1", // Set transfer characteristics for sRGB (approximates 2.2 gamma)
"-c:v", "h264_videotoolbox",
"-q:v", "25",
outputPath
]
let ffmpegInputPipe = Pipe()
ffmpegProcess.standardInput = ffmpegInputPipe
// Ignore SIGPIPE
signal(SIGPIPE, SIG_IGN)
// Setup logging for FFmpeg's output
let ffmpegOutputPipe = Pipe()
let ffmpegErrorPipe = Pipe()
ffmpegProcess.standardOutput = ffmpegOutputPipe
ffmpegProcess.standardError = ffmpegErrorPipe
// Start the FFmpeg process
do {
try ffmpegProcess.run()
} catch {
logger.error("Failed to start FFmpeg process for chunk: \(error)")
return
}
// Write the chunk data to the FFmpeg process
for (_, data) in chunk.enumerated() {
do {
try ffmpegInputPipe.fileHandleForWriting.write(contentsOf: data)
} catch {
logger.error("Error writing to FFmpeg process: \(error)")
break
}
}
// Close the pipe and handle the process completion
ffmpegInputPipe.fileHandleForWriting.closeFile()
// Read FFmpeg's output and error
let outputData = ffmpegOutputPipe.fileHandleForReading.readDataToEndOfFile()
let errorData = ffmpegErrorPipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: outputData, encoding: .utf8) {
logger.info("FFmpeg (stdout pipe): \(output)")
}
// Not differentiating as ffmpeg is outputting standard output on error pipe?
if let errorOutput = String(data: errorData, encoding: .utf8) {
logger.info("FFmpeg (stderror pipe): \(errorOutput)")
}
} else {
logger.error("Failed to save ffmpeg video")
}
}
@objc func enableRecording() {
isCapturing = .recording
Task {
await startScreenCapture()
}
}
@objc func pauseRecording() {
isCapturing = .paused
logger.info("Screen capture paused")
}
@objc func disableRecording() {
if isCapturing != .recording {
return
}
// Stop screen capture
stopScreenCapture()
// Process any remaining frames in the buffer
imageBufferQueue.sync { [weak self] in
guard let strongSelf = self else { return }
// Move the images to a temporary buffer if the threshold is reached
let tempBuffer: [Data] = Array(strongSelf.imageDataBuffer.prefix(strongSelf.frameThreshold))
strongSelf.imageDataBuffer.removeAll()
// Process the images outside of the critical section
if !tempBuffer.isEmpty {
strongSelf.processChunk(tempBuffer)
}
}
timelineView?.viewModel.setIndexToLatest()
setupMenu()
}
@objc func quitApp() {
NSApplication.shared.terminate(self)
}
private func performOCR(frameId: Int64, on image: CGImage) {
ocrQueue.async {
Task {
let request = VNRecognizeTextRequest { request, error in
guard let observations = request.results as? [VNRecognizedTextObservation], error == nil else {
print("OCR error: \(error?.localizedDescription ?? "Unknown error")")
return
}
let topK = 1
let recognizedStrings = observations.compactMap { observation in
observation.topCandidates(topK).first?.string
// observation.topCandidates(1).first?.boundingBox(for: str.startIndex..<str.endIndex)
}.joined(separator: "\n")
var texts = [recognizedStrings]
if self.settingsManager.settings.saveEverythingCopiedToClipboard {
let newClipboardText = ClipboardManager.shared.getClipboardIfChanged() ?? ""
texts.append(newClipboardText)
}
let cleanText = TextMerger.shared.mergeTexts(texts: texts)
DatabaseManager.shared.insertTextForFrame(frameId: frameId, text: cleanText)
}
if self.settingsManager.settings.fastOCR {
request.recognitionLevel = .fast
} else {
request.recognitionLevel = .accurate
}
let requestHandler = VNImageRequestHandler(cgImage: image, options: [:])
do {
try requestHandler.perform([request])
} catch {
print("Failed to perform OCR: \(error.localizedDescription)")
}
}
}
}
private func analyzeImage(frameId: Int64, image: CGImage) {}
private func processImageDataBuffer() {
// Temporarily store the buffered data and clear the buffer
let tempBuffer = imageDataBuffer
imageDataBuffer.removeAll()
// Write the buffered data to the FFmpeg process
tempBuffer.forEach {
ffmpegInputPipe?.fileHandleForWriting.write($0)
}
}
@objc func showTimelineView(with index: Int64) {
wasRecordingBeforeTimelineView = (isCapturing == .recording)
disableRecording()
closeSearchView()
if timelineViewWindow == nil {
let screenRect = NSScreen.main?.frame ?? NSRect.zero
timelineViewWindow = MainWindow(
contentRect: screenRect,
styleMask: [.borderless, .fullSizeContentView],
backing: .buffered,
defer: false
)
timelineViewWindow?.hasShadow = false
timelineViewWindow?.level = .normal
timelineViewWindow?.collectionBehavior = [.fullScreenAuxiliary, .canJoinAllSpaces, .participatesInCycle]
timelineViewWindow?.ignoresMouseEvents = false
timelineView = TimelineView(viewModel: TimelineViewModel(), settingsManager: settingsManager, onClose: {
DispatchQueue.main.async { [weak self] in
self?.closeTimelineView()
}
})
timelineView?.viewModel.updateIndex(withIndex: index)
timelineViewWindow?.contentView = NSHostingView(rootView: timelineView)
timelineView?.viewModel.setIsOpen(isOpen: true)
timelineViewWindow?.makeKeyAndOrderFront(nil)
DispatchQueue.main.async {
self.timelineViewWindow?.orderFrontRegardless() // Ensure it comes to the front
}
} else if !isTimelineOpen() {
timelineView?.viewModel.updateIndex(withIndex: index)
timelineView?.viewModel.setIsOpen(isOpen: true)
timelineViewWindow?.makeKeyAndOrderFront(nil)
DispatchQueue.main.async {
self.timelineViewWindow?.orderFrontRegardless() // Ensure it comes to the front
}
}
}
private func isTimelineOpen() -> Bool {
return timelineViewWindow?.isVisible ?? false
}
func openFullView(atIndex index: Int64) {
showTimelineView(with: index)
}
func closeSearchView() {
searchViewWindow?.isReleasedWhenClosed = false
searchViewWindow?.close()
if wasRecordingBeforeSearchView {
enableRecording()
}
}
func closeTimelineView() {
timelineViewWindow?.isReleasedWhenClosed = false
timelineViewWindow?.close()
timelineView?.viewModel.setIsOpen(isOpen: false)
if wasRecordingBeforeTimelineView {
enableRecording()
}
}
@objc func showSearchView() {
wasRecordingBeforeSearchView = (isCapturing == .recording)
disableRecording()
closeTimelineView()
// Ensure that the search view window is created and shown
if searchViewWindow == nil {
let screenRect = NSScreen.main?.frame ?? NSRect.zero
searchViewWindow = MainWindow(
contentRect: screenRect,
styleMask: [.borderless, .fullSizeContentView],
backing: .buffered, defer: false
)
searchViewWindow?.hasShadow = false
searchViewWindow?.ignoresMouseEvents = false
searchViewWindow?.center()
searchViewWindow?.contentView = NSHostingView(rootView: searchView)
searchViewWindow?.makeKeyAndOrderFront(nil)
DispatchQueue.main.async {
self.searchViewWindow?.orderFrontRegardless() // Ensure it comes to the front
}
} else if !(searchViewWindow?.isVisible ?? false) {
searchViewWindow?.makeKeyAndOrderFront(nil)
DispatchQueue.main.async {
self.searchViewWindow?.orderFrontRegardless() // Ensure it comes to the front
}
}
}
}