-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathwindows.rs
More file actions
2378 lines (2087 loc) · 91.3 KB
/
windows.rs
File metadata and controls
2378 lines (2087 loc) · 91.3 KB
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(unused_mut)]
#![allow(unused_imports)]
use anyhow::anyhow;
use futures::pin_mut;
use scap_targets::{Display, DisplayId};
use serde::Deserialize;
use specta::Type;
use std::{
ops::Deref,
path::PathBuf,
str::FromStr,
sync::{Arc, Mutex, atomic::AtomicU32},
time::Duration,
};
use tauri::{
AppHandle, LogicalPosition, Manager, Monitor, PhysicalPosition, PhysicalSize, WebviewUrl,
WebviewWindow, WebviewWindowBuilder, Wry,
};
use tauri_specta::Event;
use tokio::sync::RwLock;
use tracing::{debug, error, instrument, warn};
#[cfg(target_os = "macos")]
use crate::panel_manager::{PanelManager, PanelState, PanelWindowType};
use crate::{
App, ArcLock, CameraWindowCloseGate, CameraWindowPositionGuard, RequestScreenCapturePrewarm,
RequestSetTargetMode,
editor_window::PendingEditorInstances,
fake_window,
general_settings::{self, AppTheme, GeneralSettingsStore},
permissions,
recording_settings::RecordingTargetMode,
target_select_overlay::WindowFocusManager,
window_exclusion::WindowExclusion,
};
use cap_recording::feeds;
#[cfg(target_os = "macos")]
const DEFAULT_TRAFFIC_LIGHTS_INSET: LogicalPosition<f64> = LogicalPosition::new(12.0, 12.0);
const DEFAULT_FALLBACK_DISPLAY_WIDTH: f64 = 1920.0;
const DEFAULT_FALLBACK_DISPLAY_HEIGHT: f64 = 1080.0;
#[cfg(target_os = "macos")]
fn is_system_dark_mode() -> bool {
use cocoa::base::{id, nil};
use cocoa::foundation::NSString;
use objc::{class, msg_send, sel, sel_impl};
unsafe {
let app: id = msg_send![class!(NSApplication), sharedApplication];
let appearance: id = msg_send![app, effectiveAppearance];
if appearance == nil {
return false;
}
let name: id = msg_send![appearance, name];
if name == nil {
return false;
}
let dark_appearance = NSString::alloc(nil).init_str("NSAppearanceNameDarkAqua");
let vibrant_dark = NSString::alloc(nil).init_str("NSAppearanceNameVibrantDark");
let is_dark: bool = msg_send![name, isEqualToString: dark_appearance];
let is_vibrant_dark: bool = msg_send![name, isEqualToString: vibrant_dark];
is_dark || is_vibrant_dark
}
}
#[cfg(target_os = "windows")]
fn is_system_dark_mode() -> bool {
use winreg::RegKey;
use winreg::enums::HKEY_CURRENT_USER;
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
if let Ok(key) =
hkcu.open_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize")
&& let Ok(value) = key.get_value::<u32, _>("AppsUseLightTheme")
{
return value == 0;
}
false
}
#[cfg(target_os = "linux")]
fn is_system_dark_mode() -> bool {
if let Ok(output) = std::process::Command::new("gsettings")
.args(["get", "org.gnome.desktop.interface", "gtk-theme"])
.output()
{
let theme = String::from_utf8_lossy(&output.stdout);
return theme.to_lowercase().contains("dark");
}
false
}
fn hide_recording_windows(app: &AppHandle) {
for (label, window) in app.webview_windows() {
if let Ok(id) = CapWindowId::from_str(&label)
&& matches!(
id,
CapWindowId::TargetSelectOverlay { .. } | CapWindowId::Main | CapWindowId::Camera
)
{
let _ = window.hide();
}
}
}
async fn cleanup_camera_window(
app: &AppHandle,
window: Option<&WebviewWindow>,
#[allow(unused_variables)] reset_panel: bool,
wait_for_removal: bool,
) -> bool {
use crate::CameraWindowCloseGate;
#[cfg(target_os = "macos")]
if reset_panel {
let panel_manager = app.state::<PanelManager>();
panel_manager.force_reset(PanelWindowType::Camera).await;
}
app.state::<CameraWindowCloseGate>().set_allow_close(true);
#[cfg(target_os = "macos")]
{
let (panel_close_tx, panel_close_rx) = tokio::sync::oneshot::channel();
let app_for_close = app.clone();
app.run_on_main_thread(move || {
use tauri_nspanel::ManagerExt;
let label = CapWindowId::Camera.label();
if let Ok(panel) = app_for_close.get_webview_panel(&label) {
panel.released_when_closed(false);
panel.close();
}
let _ = panel_close_tx.send(());
})
.ok();
let _ = tokio::time::timeout(std::time::Duration::from_millis(500), panel_close_rx).await;
}
if let Some(window) = window {
let (destroy_tx, destroy_rx) = tokio::sync::oneshot::channel();
app.run_on_main_thread({
let window = window.clone();
move || {
let _ = window.destroy();
let _ = destroy_tx.send(());
}
})
.ok();
let _ = tokio::time::timeout(std::time::Duration::from_millis(500), destroy_rx).await;
} else if let Some(stale) = CapWindowId::Camera.get(app) {
let (destroy_tx, destroy_rx) = tokio::sync::oneshot::channel();
app.run_on_main_thread({
let stale = stale.clone();
move || {
let _ = stale.destroy();
let _ = destroy_tx.send(());
}
})
.ok();
let _ = tokio::time::timeout(std::time::Duration::from_millis(500), destroy_rx).await;
}
if wait_for_removal {
let start = std::time::Instant::now();
let timeout = std::time::Duration::from_millis(2000);
while start.elapsed() < timeout && CapWindowId::Camera.get(app).is_some() {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
let still_exists = CapWindowId::Camera.get(app).is_some();
app.state::<CameraWindowCloseGate>().set_allow_close(false);
!still_exists
}
struct CursorMonitorInfo {
x: f64,
y: f64,
width: f64,
height: f64,
}
impl CursorMonitorInfo {
fn get() -> Self {
let display = Display::get_containing_cursor().unwrap_or_else(Display::primary);
let bounds = display.raw_handle().logical_bounds();
let (x, y, width, height) = bounds
.map(|b| {
(
b.position().x(),
b.position().y(),
b.size().width(),
b.size().height(),
)
})
.unwrap_or((
0.0,
0.0,
DEFAULT_FALLBACK_DISPLAY_WIDTH,
DEFAULT_FALLBACK_DISPLAY_HEIGHT,
));
Self {
x,
y,
width,
height,
}
}
fn center_position(&self, window_width: f64, window_height: f64) -> (f64, f64) {
let pos_x = self.x + (self.width - window_width) / 2.0;
let pos_y = self.y + (self.height - window_height) / 2.0;
(pos_x, pos_y)
}
fn bottom_center_position(
&self,
window_width: f64,
window_height: f64,
offset_y: f64,
) -> (f64, f64) {
let pos_x = self.x + (self.width - window_width) / 2.0;
let pos_y = self.y + self.height - window_height - offset_y;
(pos_x, pos_y)
}
fn from_window(window: &tauri::WebviewWindow) -> Self {
let window_pos = window
.outer_position()
.ok()
.map(|p| (p.x as f64, p.y as f64))
.unwrap_or((0.0, 0.0));
for display in Display::list() {
if let Some(bounds) = display.raw_handle().logical_bounds() {
let (x, y, width, height) = (
bounds.position().x(),
bounds.position().y(),
bounds.size().width(),
bounds.size().height(),
);
if window_pos.0 >= x
&& window_pos.0 < x + width
&& window_pos.1 >= y
&& window_pos.1 < y + height
{
return Self {
x,
y,
width,
height,
};
}
}
}
Self::get()
}
}
fn center_camera_window(app: &AppHandle, window: &WebviewWindow) {
let state = app.state::<ArcLock<crate::App>>();
let camera_state = if let Ok(guard) = state.try_read() {
guard.camera_preview.get_state().ok().unwrap_or_default()
} else {
crate::camera::CameraPreviewState::default()
};
let toolbar_height = 56.0;
let size = camera_state.size as f64;
let is_full = camera_state.shape == crate::camera::CameraPreviewShape::Full;
let aspect_ratio = 16.0 / 9.0;
let window_width = if is_full { size * aspect_ratio } else { size };
let window_height = size + toolbar_height;
let monitor_info = CursorMonitorInfo::get();
let (pos_x, pos_y) = monitor_info.center_position(window_width, window_height);
let _ = window.set_size(tauri::LogicalSize::new(window_width, window_height));
app.state::<CameraWindowPositionGuard>().ignore_for(1000);
let _ = window.set_position(tauri::LogicalPosition::new(pos_x, pos_y));
}
fn is_position_on_display(display_id: &DisplayId, pos_x: f64, pos_y: f64) -> bool {
Display::from_id(display_id)
.and_then(|display| display.raw_handle().logical_bounds())
.map(|bounds| {
let (x, y, width, height) = (
bounds.position().x(),
bounds.position().y(),
bounds.size().width(),
bounds.size().height(),
);
pos_x >= x && pos_x < x + width && pos_y >= y && pos_y < y + height
})
.unwrap_or(false)
}
fn display_name_for_position(pos_x: f64, pos_y: f64) -> Option<String> {
Display::list().into_iter().find_map(|display| {
let bounds = display.raw_handle().logical_bounds()?;
let (x, y, width, height) = (
bounds.position().x(),
bounds.position().y(),
bounds.size().width(),
bounds.size().height(),
);
if pos_x >= x && pos_x < x + width && pos_y >= y && pos_y < y + height {
display.name().filter(|name| !name.trim().is_empty())
} else {
None
}
})
}
fn is_position_on_monitor_name(monitor_name: &str, pos_x: f64, pos_y: f64) -> bool {
Display::list().into_iter().any(|display| {
if display.name().as_deref() != Some(monitor_name) {
return false;
}
display
.raw_handle()
.logical_bounds()
.map(|bounds| {
let (x, y, width, height) = (
bounds.position().x(),
bounds.position().y(),
bounds.size().width(),
bounds.size().height(),
);
pos_x >= x && pos_x < x + width && pos_y >= y && pos_y < y + height
})
.unwrap_or(false)
})
}
fn is_position_on_any_screen(pos_x: f64, pos_y: f64) -> bool {
for display in Display::list() {
if let Some(bounds) = display.raw_handle().logical_bounds() {
let (x, y, width, height) = (
bounds.position().x(),
bounds.position().y(),
bounds.size().width(),
bounds.size().height(),
);
if pos_x >= x && pos_x < x + width && pos_y >= y && pos_y < y + height {
return true;
}
}
}
false
}
#[derive(Clone, Deserialize, Type)]
pub enum CapWindowId {
// Contains onboarding + permissions
Setup,
Main,
Settings,
Editor { id: u32 },
RecordingsOverlay,
WindowCaptureOccluder { screen_id: DisplayId },
TargetSelectOverlay { display_id: DisplayId },
CaptureArea,
Camera,
RecordingControls,
Upgrade,
ModeSelect,
Debug,
ScreenshotEditor { id: u32 },
}
impl FromStr for CapWindowId {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"setup" => Self::Setup,
"main" => Self::Main,
"settings" => Self::Settings,
"camera" => Self::Camera,
"capture-area" => Self::CaptureArea,
// legacy identifier
"in-progress-recording" => Self::RecordingControls,
"recordings-overlay" => Self::RecordingsOverlay,
"upgrade" => Self::Upgrade,
"mode-select" => Self::ModeSelect,
"debug" => Self::Debug,
s if s.starts_with("editor-") => Self::Editor {
id: s
.replace("editor-", "")
.parse::<u32>()
.map_err(|e| e.to_string())?,
},
s if s.starts_with("screenshot-editor-") => Self::ScreenshotEditor {
id: s
.replace("screenshot-editor-", "")
.parse::<u32>()
.map_err(|e| e.to_string())?,
},
s if s.starts_with("window-capture-occluder-") => Self::WindowCaptureOccluder {
screen_id: s
.replace("window-capture-occluder-", "")
.parse::<DisplayId>()
.map_err(|e| e.to_string())?,
},
s if s.starts_with("target-select-overlay-") => Self::TargetSelectOverlay {
display_id: s
.replace("target-select-overlay-", "")
.parse::<DisplayId>()
.map_err(|e| e.to_string())?,
},
_ => return Err(format!("unknown window label: {s}")),
})
}
}
impl std::fmt::Display for CapWindowId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Setup => write!(f, "setup"),
Self::Main => write!(f, "main"),
Self::Settings => write!(f, "settings"),
Self::Camera => write!(f, "camera"),
Self::WindowCaptureOccluder { screen_id } => {
write!(f, "window-capture-occluder-{screen_id}")
}
Self::CaptureArea => write!(f, "capture-area"),
Self::TargetSelectOverlay { display_id } => {
write!(f, "target-select-overlay-{display_id}")
}
Self::RecordingControls => write!(f, "in-progress-recording"), // legacy identifier
Self::RecordingsOverlay => write!(f, "recordings-overlay"),
Self::Upgrade => write!(f, "upgrade"),
Self::ModeSelect => write!(f, "mode-select"),
Self::Editor { id } => write!(f, "editor-{id}"),
Self::Debug => write!(f, "debug"),
Self::ScreenshotEditor { id } => write!(f, "screenshot-editor-{id}"),
}
}
}
impl CapWindowId {
pub fn label(&self) -> String {
self.to_string()
}
pub fn title(&self) -> String {
match self {
Self::Setup => "Cap Setup".to_string(),
Self::Settings => "Cap Settings".to_string(),
Self::WindowCaptureOccluder { .. } => "Cap Window Capture Occluder".to_string(),
Self::CaptureArea => "Cap Capture Area".to_string(),
Self::RecordingControls => "Cap Recording Controls".to_string(),
Self::Editor { .. } => "Cap Editor".to_string(),
Self::ScreenshotEditor { .. } => "Cap Screenshot Editor".to_string(),
Self::ModeSelect => "Cap Mode Selection".to_string(),
Self::Camera => "Cap Camera".to_string(),
Self::RecordingsOverlay => "Cap Recordings Overlay".to_string(),
Self::TargetSelectOverlay { .. } => "Cap Target Select".to_string(),
_ => "Cap".to_string(),
}
}
pub fn activates_dock(&self) -> bool {
matches!(
self,
Self::Setup
| Self::Main
| Self::Editor { .. }
| Self::ScreenshotEditor { .. }
| Self::Settings
| Self::Upgrade
| Self::ModeSelect
)
}
pub fn is_transparent(&self) -> bool {
matches!(
self,
Self::Main
| Self::Camera
| Self::WindowCaptureOccluder { .. }
| Self::CaptureArea
| Self::RecordingControls
| Self::RecordingsOverlay
| Self::TargetSelectOverlay { .. }
)
}
pub fn get(&self, app: &AppHandle<Wry>) -> Option<WebviewWindow> {
let label = self.label();
app.get_webview_window(&label)
}
#[cfg(target_os = "macos")]
pub fn traffic_lights_position(&self) -> Option<Option<LogicalPosition<f64>>> {
match self {
Self::Editor { .. } | Self::ScreenshotEditor { .. } => {
Some(Some(LogicalPosition::new(20.0, 32.0)))
}
Self::Camera
| Self::Main
| Self::WindowCaptureOccluder { .. }
| Self::CaptureArea
| Self::RecordingsOverlay
| Self::RecordingControls
| Self::TargetSelectOverlay { .. } => None,
_ => Some(None),
}
}
pub fn min_size(&self) -> Option<(f64, f64)> {
Some(match self {
Self::Setup => (600.0, 600.0),
Self::Main => (330.0, 395.0),
Self::Editor { .. } => (1275.0, 800.0),
Self::ScreenshotEditor { .. } => (800.0, 600.0),
Self::Settings => (700.0, 540.0),
Self::Camera => (200.0, 200.0),
Self::Upgrade => (950.0, 850.0),
Self::ModeSelect => (580.0, 340.0),
_ => return None,
})
}
}
#[derive(Debug, Clone, Type, Deserialize)]
pub enum ShowCapWindow {
Setup,
Main {
init_target_mode: Option<RecordingTargetMode>,
},
Settings {
page: Option<String>,
},
Editor {
project_path: PathBuf,
},
RecordingsOverlay,
WindowCaptureOccluder {
screen_id: DisplayId,
},
TargetSelectOverlay {
display_id: DisplayId,
target_mode: Option<RecordingTargetMode>,
},
CaptureArea {
screen_id: DisplayId,
},
Camera {
centered: bool,
},
InProgressRecording {
countdown: Option<u32>,
},
Upgrade,
ModeSelect,
ScreenshotEditor {
path: PathBuf,
},
}
impl ShowCapWindow {
pub async fn show(&self, app: &AppHandle<Wry>) -> tauri::Result<WebviewWindow> {
if let Self::Editor { project_path } = &self {
let state = app.state::<EditorWindowIds>();
let window_id = {
let mut s = state.ids.lock().unwrap();
if !s.iter().any(|(path, _)| path == project_path) {
let id = state
.counter
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
s.push((project_path.clone(), id));
id
} else {
s.iter().find(|(path, _)| path == project_path).unwrap().1
}
};
let window_label = CapWindowId::Editor { id: window_id }.label();
PendingEditorInstances::start_prewarm(app, window_label, project_path.clone()).await;
}
if let Self::ScreenshotEditor { path } = &self {
let state = app.state::<ScreenshotEditorWindowIds>();
let mut s = state.ids.lock().unwrap();
if !s.iter().any(|(p, _)| p == path) {
s.push((
path.clone(),
state
.counter
.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
));
}
}
if let Self::Camera { centered } = self {
#[cfg(target_os = "macos")]
{
let panel_manager = app.state::<PanelManager>();
let mut panel_state = panel_manager.get_state(PanelWindowType::Camera).await;
if panel_state == PanelState::Destroying {
debug!("Camera window is being destroyed, waiting...");
let wait_result = panel_manager
.wait_for_state(
PanelWindowType::Camera,
&[PanelState::None],
std::time::Duration::from_millis(500),
)
.await;
if !wait_result {
warn!("Camera destroy wait timed out, force resetting state");
panel_manager.force_reset(PanelWindowType::Camera).await;
}
panel_state = panel_manager.get_state(PanelWindowType::Camera).await;
}
if panel_state == PanelState::Creating {
debug!("Camera window is being created, waiting...");
panel_manager
.wait_for_state(
PanelWindowType::Camera,
&[PanelState::Ready],
std::time::Duration::from_millis(500),
)
.await;
}
}
if let Some(window) = self.id(app).get(app) {
#[cfg(target_os = "macos")]
{
use crate::panel_manager::is_window_handle_valid;
let handle_valid = is_window_handle_valid(&window);
if !handle_valid {
warn!(
"Camera window exists but handle is invalid, destroying and recreating..."
);
let cleanup_success =
cleanup_camera_window(app, Some(&window), true, true).await;
if !cleanup_success {
warn!(
"Camera window still in registry after cleanup attempts, will retry later"
);
return Err(tauri::Error::WindowNotFound);
}
debug!("Camera window successfully removed from registry");
} else {
let panel_manager = app.state::<PanelManager>();
let mut panel_state =
panel_manager.get_state(PanelWindowType::Camera).await;
if panel_state == PanelState::Creating {
debug!(
"Camera window valid but state is Creating, waiting for completion"
);
panel_manager
.wait_for_state(
PanelWindowType::Camera,
&[PanelState::Ready, PanelState::None],
std::time::Duration::from_millis(1000),
)
.await;
panel_state = panel_manager.get_state(PanelWindowType::Camera).await;
}
if panel_state != PanelState::Ready {
debug!(
"Camera window exists but panel state is {:?}, updating to Ready",
panel_state
);
panel_manager.force_reset(PanelWindowType::Camera).await;
panel_manager.mark_ready(PanelWindowType::Camera, 0).await;
}
let state = app.state::<ArcLock<App>>();
let mut app_state = state.write().await;
let enable_native_camera_preview = GeneralSettingsStore::get(app)
.ok()
.and_then(|v| v.map(|v| v.enable_native_camera_preview))
.unwrap_or_default();
let shutdown_preview = if !enable_native_camera_preview {
app_state.camera_preview.begin_shutdown()
} else {
None
};
if enable_native_camera_preview {
let camera_feed = app_state.camera_feed.clone();
if let Err(err) = app_state
.camera_preview
.init_window(window.clone(), camera_feed)
.await
{
error!(
"Error reinitializing camera preview for existing window: {err}"
);
}
}
drop(app_state);
if let Some(rx) = shutdown_preview {
let _ = tokio::time::timeout(Duration::from_millis(500), rx).await;
}
let (show_tx, show_rx) = tokio::sync::oneshot::channel();
app.run_on_main_thread({
let window = window.clone();
move || {
use crate::panel_manager::try_to_panel;
// IMPORTANT: We intentionally use window.show() + set_focus() here
// instead of panel.order_front_regardless().
//
// order_front_regardless() was found to cause a crash after ~4-5
// camera toggle cycles due to macOS internal state accumulation.
// The crash manifested as a hard crash in the Metal/CAMetalLayer
// subsystem, not in our Rust code.
//
// Using standard Tauri window APIs avoids this macOS-specific issue
// while still properly showing and focusing the camera preview window.
let _ = window.show();
let _ = window.set_focus();
let _ = show_tx.send(true);
}
})
.ok();
let show_result = show_rx.await.unwrap_or(false);
if show_result {
if *centered {
center_camera_window(app, &window);
}
return Ok(window);
} else {
warn!("Camera panel show failed, will recreate window");
let cleanup_success =
cleanup_camera_window(app, Some(&window), true, true).await;
if !cleanup_success {
warn!(
"Camera window still in registry after show failure, will retry later"
);
return Err(tauri::Error::WindowNotFound);
}
debug!("Camera window successfully removed after show failure");
}
}
}
#[cfg(not(target_os = "macos"))]
{
let state = app.state::<ArcLock<App>>();
let mut app_state = state.write().await;
let enable_native_camera_preview = GeneralSettingsStore::get(app)
.ok()
.and_then(|v| v.map(|v| v.enable_native_camera_preview))
.unwrap_or_default();
let shutdown_preview = if !enable_native_camera_preview {
app_state.camera_preview.begin_shutdown()
} else {
None
};
if enable_native_camera_preview && !app_state.camera_preview.is_initialized() {
let camera_feed = app_state.camera_feed.clone();
if let Err(err) = app_state
.camera_preview
.init_window(window.clone(), camera_feed)
.await
{
error!(
"Error reinitializing camera preview for existing window: {err}"
);
}
}
drop(app_state);
if let Some(rx) = shutdown_preview {
let _ = tokio::time::timeout(Duration::from_millis(500), rx).await;
}
if *centered {
center_camera_window(app, &window);
}
window.show().ok();
window.set_focus().ok();
return Ok(window);
}
}
}
#[cfg(target_os = "macos")]
if let Self::InProgressRecording { .. } = self
&& let Some(window) = self.id(app).get(app)
{
use crate::panel_manager::is_window_handle_valid;
if is_window_handle_valid(&window) {
debug!("InProgressRecording: reusing existing window");
let width = 320.0;
let height = 150.0;
let recording_monitor = CursorMonitorInfo::get();
let (pos_x, pos_y) = recording_monitor.bottom_center_position(width, height, 120.0);
let _ = window.set_position(tauri::LogicalPosition::new(pos_x, pos_y));
let label = window.label().to_string();
app.run_on_main_thread({
let app = app.clone();
move || {
use tauri_nspanel::ManagerExt;
if let Ok(panel) = app.get_webview_panel(&label) {
panel.order_front_regardless();
panel.show();
}
}
})
.ok();
return Ok(window);
} else {
warn!("InProgressRecording window handle invalid, destroying and recreating...");
let _ = window.destroy();
let window_id = self.id(app);
let max_wait = std::time::Duration::from_millis(500);
let poll_interval = std::time::Duration::from_millis(25);
let start = std::time::Instant::now();
while start.elapsed() < max_wait {
if window_id.get(app).is_none() {
debug!(
"InProgressRecording window removed from registry after {:?}",
start.elapsed()
);
break;
}
tokio::time::sleep(poll_interval).await;
}
if window_id.get(app).is_some() {
error!("InProgressRecording window STILL in registry, cannot recreate");
return Err(tauri::Error::WindowNotFound);
}
debug!("InProgressRecording window cleaned up, will recreate");
}
}
#[cfg(not(target_os = "macos"))]
if let Self::InProgressRecording { .. } = self
&& let Some(window) = self.id(app).get(app)
{
let width = 320.0;
let height = 150.0;
let recording_monitor = CursorMonitorInfo::get();
let (pos_x, pos_y) = recording_monitor.bottom_center_position(width, height, 120.0);
let _ = window.set_position(tauri::LogicalPosition::new(pos_x, pos_y));
#[cfg(target_os = "linux")]
if let Err(error) = window.set_ignore_cursor_events(false) {
warn!(
%error,
"Failed to make reused recording controls interactive on linux"
);
}
window.show().ok();
window.set_focus().ok();
return Ok(window);
}
if !matches!(self, Self::Camera { .. } | Self::InProgressRecording { .. })
&& let Some(window) = self.id(app).get(app)
{
let cursor_display_id = if let Self::Main { init_target_mode } = self {
if init_target_mode.is_some() {
Display::get_containing_cursor()
.map(|d| d.id().to_string())
.or_else(|| Some(Display::primary().id().to_string()))
} else {
None
}
} else {
None
};
if let Self::Main {
init_target_mode: Some(target_mode),
} = self
{
window.hide().ok();
let _ = RequestSetTargetMode {
target_mode: Some(*target_mode),
display_id: cursor_display_id,
}
.emit(app);
} else {
window.show().ok();
window.unminimize().ok();
window.set_focus().ok();
if let Self::Main { init_target_mode } = self {
let _ = RequestSetTargetMode {
target_mode: *init_target_mode,
display_id: cursor_display_id,
}
.emit(app);
}
}
return Ok(window);
}
let _id = self.id(app);
let cursor_monitor = CursorMonitorInfo::get();
let window = match self {
Self::Setup => {
let window = self
.window_builder(app, "/setup")
.inner_size(600.0, 600.0)
.min_inner_size(600.0, 600.0)
.resizable(false)
.maximized(false)
.focused(true)
.maximizable(false)
.shadow(true)
.build()?;
let (pos_x, pos_y) = cursor_monitor.center_position(600.0, 600.0);
let _ = window.set_position(tauri::LogicalPosition::new(pos_x, pos_y));
#[cfg(windows)]
{
use tauri::LogicalSize;
if let Err(e) = window.set_size(LogicalSize::new(600.0, 600.0)) {
warn!("Failed to set Setup window size on Windows: {}", e);
}
if let Err(e) = window.set_position(tauri::LogicalPosition::new(pos_x, pos_y)) {
warn!("Failed to position Setup window on Windows: {}", e);
}
}
window
}
Self::Main { init_target_mode } => {
if !permissions::do_permissions_check(false).necessary_granted() {
return Box::pin(Self::Setup.show(app)).await;
}
let title = CapWindowId::Main.title();
let should_protect = should_protect_window(app, &title);
#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Accessory)
.ok();
let window = self
.window_builder(app, "/")
.resizable(false)
.maximized(false)
.maximizable(false)
.minimizable(false)
.always_on_top(true)
.visible_on_all_workspaces(true)
.content_protected(should_protect)
.transparent(true)
.visible(false)
.initialization_script(format!(
"
window.__CAP__ = window.__CAP__ ?? {{}};
window.__CAP__.initialTargetMode = {}
",
serde_json::to_string(init_target_mode)
.expect("Failed to serialize initial target mode")
))
.build()?;
let saved_position = GeneralSettingsStore::get(app)
.ok()