forked from CapSoftware/Cap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindows.rs
More file actions
3703 lines (3267 loc) · 143 KB
/
Copy pathwindows.rs
File metadata and controls
3703 lines (3267 loc) · 143 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, AtomicU64, Ordering},
},
time::Duration,
};
use tauri::{
AppHandle, LogicalPosition, LogicalSize, Manager, Monitor, PhysicalPosition, PhysicalSize,
WebviewUrl, WebviewWindow, WebviewWindowBuilder, Wry,
};
use tauri_specta::Event;
use tokio::sync::RwLock;
use tracing::{debug, error, info, instrument, warn};
#[cfg(target_os = "macos")]
use crate::panel_manager::{PanelManager, PanelState, PanelWindowType, is_window_handle_valid};
use crate::{
App, ArcLock, CameraWindowCloseGate, CameraWindowPositionGuard, MainWindowReadyState,
NewNotification, RequestSetTargetMode, camera_preview_error_message,
editor_window::PendingEditorInstances,
emit_camera_preview_clear, emit_camera_preview_error, fake_window,
general_settings::{self, AppTheme, GeneralSettingsStore},
permissions,
recording::{RecordingEvent, RecordingInputKind},
recording_settings::RecordingTargetMode,
screenshot_editor::PendingScreenshotEditorInstances,
target_select_overlay::WindowFocusManager,
window_exclusion::WindowExclusion,
};
use cap_recording::{feeds, sources::screen_capture::ScreenCaptureTarget};
#[cfg(target_os = "macos")]
const DEFAULT_TRAFFIC_LIGHTS_INSET: LogicalPosition<f64> = LogicalPosition::new(12.0, 12.0);
#[cfg(target_os = "macos")]
const MAIN_PANEL_LEVEL: i32 = 100;
#[cfg(target_os = "macos")]
const TELEPROMPTER_PANEL_LEVEL: objc2_app_kit::NSWindowLevel = MAIN_PANEL_LEVEL as isize + 1;
const DEFAULT_FALLBACK_DISPLAY_WIDTH: f64 = 1920.0;
const DEFAULT_FALLBACK_DISPLAY_HEIGHT: f64 = 1080.0;
#[cfg(windows)]
const WINDOWS_WEBVIEW2_BROWSER_ARGS: &str = "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --autoplay-policy=no-user-gesture-required --disable-vulkan --use-angle=d3d11";
#[cfg(windows)]
fn windows_webview2_browser_args() -> String {
let mut args = WINDOWS_WEBVIEW2_BROWSER_ARGS.to_string();
if cap_rendering::force_software_wgpu_adapter()
|| std::env::args_os().any(|arg| arg.to_str() == Some("--disable-gpu"))
{
args.push_str(" --disable-gpu");
}
args
}
#[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 {
let output = std::process::Command::new("gsettings")
.args(["get", "org.gnome.desktop.interface", "color-scheme"])
.output();
if let Ok(output) = output
&& output.status.success()
{
return String::from_utf8_lossy(&output.stdout).contains("dark");
}
false
}
pub fn hide_overlay(window: &WebviewWindow) {
let _ = window.set_ignore_cursor_events(true);
let _ = window.hide();
}
pub fn show_overlay(window: &WebviewWindow) {
let _ = window.set_ignore_cursor_events(false);
let _ = window.show();
}
fn emit_app_event<E>(app: &AppHandle, event: E)
where
E: Event + serde::Serialize + Clone,
{
let event_name = std::any::type_name::<E>();
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| event.emit(app))) {
Ok(Ok(())) => {}
Ok(Err(error)) => warn!(event = event_name, %error, "Failed to emit app event"),
Err(panic) => {
let message = crate::panic_payload_message(&panic);
error!(event = event_name, panic = %message, "Suppressed panic while emitting app event");
}
}
}
fn hide_recording_windows(app: &AppHandle, restore_target_select_overlays: bool) {
let focus_manager = app.try_state::<WindowFocusManager>();
for (label, window) in app.webview_windows() {
if let Ok(id) = CapWindowId::from_str(&label)
&& matches!(
id,
CapWindowId::TargetSelectOverlay { .. } | CapWindowId::Main | CapWindowId::Camera
)
{
if matches!(id, CapWindowId::TargetSelectOverlay { .. }) {
if restore_target_select_overlays
&& window.is_visible().unwrap_or(false)
&& let Some(focus_manager) = focus_manager.as_ref()
{
focus_manager.remember_overlay_for_restore(label);
}
hide_overlay(&window);
} else if matches!(id, CapWindowId::Main) {
crate::hide_main_window(app);
} else {
let _ = window.hide();
}
}
}
}
/// Release the live camera preview feed after `hide_recording_windows` when a
/// foreground window (Settings, an editor) takes over. Hiding the camera window
/// alone leaves the capture session running, so the OS camera-in-use indicator
/// stays lit while the user is in the editor. `restore_main_window_inputs`
/// re-attaches the feed when the main window comes back.
fn release_camera_preview_if_idle(app: &AppHandle) {
let is_recording = app
.try_state::<ArcLock<App>>()
.and_then(|state| {
state
.try_read()
.ok()
.map(|state| state.is_recording_active_or_pending())
})
.unwrap_or(true);
if is_recording {
return;
}
let app = app.clone();
tokio::spawn(async move {
if let Some(state) = app.try_state::<ArcLock<App>>() {
let app_state = &mut *state.write().await;
app_state.camera_preview.pause();
let _ = app_state.camera_feed.ask(feeds::camera::RemoveInput).await;
app_state.camera_in_use = false;
} else {
warn!("App state unavailable while pausing camera preview");
}
});
}
fn bump_camera_window_session(app: &AppHandle) -> u64 {
app.state::<Arc<AtomicU64>>().fetch_add(1, Ordering::AcqRel) + 1
}
fn camera_window_label_for_session(session_id: u64) -> String {
format!("camera-{session_id}")
}
fn is_camera_window_label(label: &str) -> bool {
label == "camera"
|| label
.strip_prefix("camera-")
.is_some_and(|suffix| suffix.parse::<u64>().is_ok())
}
fn camera_window_rank(label: &str) -> u64 {
if label == "camera" {
return 0;
}
label
.strip_prefix("camera-")
.and_then(|suffix| suffix.parse::<u64>().ok())
.unwrap_or(0)
}
#[cfg(target_os = "macos")]
fn camera_window_labels(app: &AppHandle<Wry>) -> Vec<String> {
app.webview_windows()
.into_keys()
.filter(|label| is_camera_window_label(label))
.collect()
}
fn camera_webview_window_entries(app: &AppHandle<Wry>) -> Vec<(String, WebviewWindow)> {
app.webview_windows()
.into_iter()
.filter(|(label, _)| is_camera_window_label(label))
.collect()
}
fn camera_webview_windows(app: &AppHandle<Wry>) -> Vec<WebviewWindow> {
camera_webview_window_entries(app)
.into_iter()
.map(|(_, window)| window)
.collect()
}
fn current_camera_window(app: &AppHandle<Wry>) -> Option<WebviewWindow> {
#[cfg(target_os = "macos")]
{
camera_webview_window_entries(app)
.into_iter()
.filter(|(_, window)| is_window_handle_valid(window))
.max_by_key(|(label, _)| camera_window_rank(label))
.map(|(_, window)| window)
}
#[cfg(not(target_os = "macos"))]
{
camera_webview_window_entries(app)
.into_iter()
.max_by_key(|(label, _)| camera_window_rank(label))
.map(|(_, window)| window)
}
}
fn destroy_camera_window_handle(
app: &AppHandle<Wry>,
window: WebviewWindow,
) -> tokio::sync::oneshot::Receiver<()> {
let (destroy_tx, destroy_rx) = tokio::sync::oneshot::channel();
let _ = window.as_ref().close();
app.run_on_main_thread({
let window = window.clone();
move || {
let _ = window.destroy();
let _ = destroy_tx.send(());
}
})
.ok();
destroy_rx
}
async fn init_native_camera_preview(
app_state: &mut App,
window: WebviewWindow,
) -> Result<(), String> {
let camera_feed = app_state.camera_feed.clone();
let init_result = app_state
.camera_preview
.init_window(window, camera_feed.clone())
.await;
match init_result {
Ok(()) => {
#[allow(deprecated)]
let camera_ws_sender = app_state.camera_ws_sender.clone();
#[allow(deprecated)]
if let Err(err) = camera_feed
.ask(feeds::camera::RemoveSender(camera_ws_sender))
.await
{
warn!(error = %err, "Failed to remove legacy camera preview sender");
}
Ok(())
}
Err(err) => {
#[allow(deprecated)]
let camera_ws_sender = app_state.camera_ws_sender.clone();
#[allow(deprecated)]
if let Err(add_err) = camera_feed
.ask(feeds::camera::AddSender(camera_ws_sender))
.await
{
warn!(error = %add_err, "Failed to restore legacy camera preview sender");
}
Err(err.to_string())
}
}
}
pub(crate) async fn ensure_camera_input_active(app_state: &mut App) {
if let Some(id) = app_state.selected_camera_id.clone()
&& !app_state.camera_in_use
{
let settings = crate::recording_settings::RecordingSettingsStore::camera_settings_for(
&app_state.handle,
&id,
);
match app_state
.camera_feed
.ask(feeds::camera::SetInput { id, settings })
.await
{
Ok(ready_future) => {
if let Err(err) = ready_future.await {
error!("Camera failed to initialize: {err}");
return;
}
}
Err(err) => {
error!("Failed to send SetInput to camera feed: {err}");
return;
}
}
app_state.camera_in_use = true;
app_state.camera_cleanup_done = false;
}
}
pub(crate) async fn restore_main_window_inputs(app: &AppHandle) {
let Some(state) = app.try_state::<ArcLock<App>>() else {
warn!("App state unavailable while restoring main window inputs");
return;
};
let should_restore = state
.try_read()
.map(|state| !state.is_recording_active_or_pending())
.unwrap_or(false);
if !should_restore {
return;
}
let settings = crate::recording_settings::RecordingSettingsStore::get(app)
.ok()
.flatten()
.unwrap_or_default();
let stored_camera_id = settings.camera_id.clone();
if let Err(err) = crate::set_mic_input(state.clone(), settings.mic_name).await {
warn!("Failed to restore microphone input for main window: {err}");
}
let Some(operation_lock) = app.try_state::<crate::CameraWindowOperationLock>() else {
warn!("CameraWindowOperationLock unavailable while restoring main window inputs");
return;
};
let operation_guard = operation_lock.lock().await;
let camera_to_restore = state
.try_read()
.map(|s| {
if !s.camera_cleanup_done && !s.camera_in_use {
s.selected_camera_id
.clone()
.or_else(|| stored_camera_id.clone())
} else {
None
}
})
.unwrap_or(None)
// A remembered camera that isn't connected must not run the init/retry
// loop below: it would flash the preview window and toast an error on
// every main-window reveal while the device is away.
.filter(crate::is_camera_available);
if let Some(camera_id) = camera_to_restore {
emit_camera_preview_clear(app);
let settings =
crate::recording_settings::RecordingSettingsStore::camera_settings_for(app, &camera_id);
let (camera_feed, camera_ws_sender, native_sender) = {
let app_state = &mut *state.write().await;
app_state.selected_camera_id = Some(camera_id.clone());
app_state.camera_in_use = true;
app_state.camera_cleanup_done = false;
#[allow(deprecated)]
(
app_state.camera_feed.clone(),
app_state.camera_ws_sender.clone(),
app_state.camera_preview.sender(),
)
};
if let Some(sender) = native_sender {
#[allow(deprecated)]
let _ = camera_feed
.ask(feeds::camera::RemoveSender(camera_ws_sender))
.await;
if let Err(err) = sender.attach(&camera_feed).await {
warn!(error = %err, "Failed to add native preview camera sender");
}
} else {
#[allow(deprecated)]
let _ = camera_feed
.ask(feeds::camera::AddSender(camera_ws_sender))
.await;
}
let mut showed_camera_window = false;
let mut attempts = 0;
let init_result: Result<(), String> = loop {
attempts += 1;
let request = camera_feed
.ask(feeds::camera::SetInput {
id: camera_id.clone(),
settings,
})
.await
.map_err(|e| e.to_string());
if !showed_camera_window {
showed_camera_window = true;
crate::show_camera_window_unlocked(app);
}
match request {
Ok(future) => match future.await {
Ok(_) => {
emit_camera_preview_clear(app);
break Ok(());
}
Err(e) => {
if attempts == 1 {
emit_camera_preview_error(
app,
camera_preview_error_message(&e.to_string()),
);
}
if attempts >= 3 {
break Err(format!(
"Failed to restore camera after {attempts} attempts: {e}"
));
}
warn!("Camera restore attempt {attempts} failed: {e}. Retrying...");
tokio::time::sleep(Duration::from_millis(500)).await;
}
},
Err(e) => {
if attempts >= 3 {
break Err(e);
}
warn!("Camera restore attempt {attempts} failed: {e}. Retrying...");
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
};
drop(operation_guard);
match init_result {
Ok(()) => crate::restore_camera_window(app),
Err(error) => {
let message = camera_preview_error_message(&error);
warn!("Failed to restore camera input for main window: {error}");
let _ = camera_feed.ask(feeds::camera::RemoveInput).await;
let emit_input_lost = {
let app_state = &mut *state.write().await;
app_state.selected_camera_id = None;
app_state.camera_in_use = false;
app_state
.disconnected_inputs
.insert(RecordingInputKind::Camera)
};
crate::show_camera_window_unlocked(app);
if emit_input_lost {
let _ = RecordingEvent::InputLost {
input: RecordingInputKind::Camera,
}
.emit(app);
}
emit_camera_preview_error(app, message.clone());
let _ = NewNotification {
title: "Camera unavailable".to_string(),
body: message,
is_error: true,
}
.emit(app);
}
}
}
}
pub(crate) 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_labels = window
.map(|window| vec![window.label().to_string()])
.unwrap_or_else(|| camera_window_labels(app));
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;
for label in panel_labels {
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;
}
let windows = window
.cloned()
.map(|window| vec![window])
.unwrap_or_else(|| camera_webview_windows(app));
for window in windows {
let destroy_rx = destroy_camera_window_handle(app, window);
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 && !camera_webview_windows(app).is_empty() {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
let still_exists = !camera_webview_windows(app).is_empty();
app.state::<CameraWindowCloseGate>().set_allow_close(false);
!still_exists
}
struct CursorMonitorInfo {
x: f64,
y: f64,
width: f64,
height: f64,
// On Windows each monitor's "logical" rect is its physical rect divided by
// its own scale, so logical rects of mixed-DPI monitors overlap and tao's
// LogicalPosition conversion (which uses whatever monitor the window
// currently occupies) can land a window on the wrong monitor. Positioning
// must go through this monitor's own scale, as a physical position.
#[cfg(windows)]
scale: f64,
}
impl CursorMonitorInfo {
fn get() -> Self {
Self::from_display(&Display::get_containing_cursor().unwrap_or_else(Display::primary))
}
fn from_display(display: &Display) -> Self {
let bounds = display.raw_handle().logical_bounds();
#[cfg(windows)]
let scale = bounds
.as_ref()
.map(|b| b.size().width())
.filter(|width| *width > 0.0)
.and_then(|logical_width| {
display
.physical_size()
.map(|physical| physical.width() / logical_width)
})
.filter(|scale| scale.is_finite() && *scale > 0.0)
.unwrap_or(1.0);
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,
#[cfg(windows)]
scale,
}
}
/// Converts a global-logical point on this monitor into a `Position` that
/// lands exactly there regardless of which monitor the window currently
/// occupies. Logical on macOS/Linux (a true global space there), physical
/// on Windows.
fn position(&self, x: f64, y: f64) -> tauri::Position {
#[cfg(windows)]
return tauri::Position::Physical(tauri::PhysicalPosition::new(
(x * self.scale).round() as i32,
(y * self.scale).round() as i32,
));
#[cfg(not(windows))]
tauri::Position::Logical(tauri::LogicalPosition::new(x, y))
}
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 Ok(window_pos) = window.outer_position() else {
return Self::get();
};
// outer_position is physical. On Windows, resolve the display in
// physical space (per-monitor logical rects overlap in mixed-DPI
// layouts). On macOS, convert to logical points, a true global space.
// On Linux scap reports logical bounds in unscaled physical units, so
// the raw position compares directly.
#[cfg(windows)]
{
let (pos_x, pos_y) = (window_pos.x as f64, window_pos.y as f64);
for display in Display::list() {
if let Some(bounds) = display.raw_handle().physical_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 Self::from_display(&display);
}
}
}
Self::get()
}
#[cfg(target_os = "macos")]
{
let scale = window.scale_factor().unwrap_or(1.0);
let pos = window_pos.to_logical::<f64>(scale);
for display in Display::list() {
if display_contains_logical(&display, pos.x, pos.y) {
return Self::from_display(&display);
}
}
Self::get()
}
#[cfg(target_os = "linux")]
{
let (pos_x, pos_y) = (window_pos.x as f64, window_pos.y as f64);
for display in Display::list() {
if display_contains_logical(&display, pos_x, pos_y) {
return Self::from_display(&display);
}
}
Self::get()
}
}
}
fn display_contains_logical(display: &Display, pos_x: f64, pos_y: f64) -> bool {
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_containing_logical(pos_x: f64, pos_y: f64) -> Option<Display> {
Display::list()
.into_iter()
.find(|display| display_contains_logical(display, pos_x, pos_y))
}
/// Resolves the display a persisted window position belongs to, preferring the
/// display it was saved on. On Windows the saved logical coordinates are only
/// meaningful relative to that display (mixed-DPI logical rects overlap), so
/// restores must convert through its scale rather than the window's current one.
fn display_for_saved_position(
pos_x: f64,
pos_y: f64,
display_id: Option<&DisplayId>,
) -> Option<Display> {
display_id
.and_then(Display::from_id)
.filter(|display| display_contains_logical(display, pos_x, pos_y))
.or_else(|| display_containing_logical(pos_x, pos_y))
}
/// Converts a global-logical point into a `Position` that lands exactly there,
/// resolving the owning display by containment when the caller doesn't know it.
/// Falls back to a plain logical position when no display contains the point.
pub fn logical_point_position(pos_x: f64, pos_y: f64) -> tauri::Position {
#[cfg(windows)]
if let Some(display) = display_containing_logical(pos_x, pos_y) {
return CursorMonitorInfo::from_display(&display).position(pos_x, pos_y);
}
tauri::Position::Logical(tauri::LogicalPosition::new(pos_x, pos_y))
}
fn center_camera_window(app: &AppHandle, window: &WebviewWindow) {
let camera_state = match app.try_state::<ArcLock<crate::App>>() {
Some(state) => state
.try_read()
.ok()
.and_then(|guard| guard.camera_preview.get_state().ok())
.unwrap_or_default(),
None => 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 = crate::camera::WIDE_CAMERA_ASPECT_RATIO as f64;
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));
if let Some(guard) = app.try_state::<CameraWindowPositionGuard>() {
guard.ignore_for(1000);
}
let _ = window.set_position(monitor_info.position(pos_x, pos_y));
if let Some(state) = app.try_state::<ArcLock<crate::App>>()
&& let Ok(guard) = state.try_read()
{
guard
.camera_preview
.notify_window_resized(window_width as u32, window_height as u32);
}
}
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
}
// Recovers a window that ended up entirely off every connected display (e.g. the
// monitor it was on got disconnected), which otherwise leaves it open but unreachable.
fn recenter_window_if_offscreen(window: &WebviewWindow) {
let Ok(position) = window.outer_position() else {
return;
};
let Ok(size) = window.outer_size() else {
return;
};
let scale = window.scale_factor().unwrap_or(1.0);
let on_screen = Display::list()
.iter()
.any(|display| display.intersects(position, size, scale));
if on_screen {
return;
}
let monitor = CursorMonitorInfo::get();
let (pos_x, pos_y) =
monitor.center_position(size.width as f64 / scale, size.height as f64 / scale);
let _ = window.set_position(monitor.position(pos_x, pos_y));
}
fn ensure_settings_window_bounds(window: &WebviewWindow) {
const MIN_W: f64 = 780.0;
const MIN_H: f64 = 560.0;
let _ = window.set_min_size(Some(LogicalSize::new(MIN_W, MIN_H)));
if let (Ok(physical), Ok(scale)) = (window.inner_size(), window.scale_factor()) {
let width = physical.width as f64 / scale;
let height = physical.height as f64 / scale;
if width < MIN_W || height < MIN_H {
let _ = window.set_size(LogicalSize::new(width.max(MIN_W), height.max(MIN_H)));
}
}
}
#[derive(Clone, Deserialize, Type)]
pub enum CapWindowId {
Main,
Settings,
Editor { id: u32 },
RecordingsOverlay,
WindowCaptureOccluder { screen_id: DisplayId },
TargetSelectOverlay { display_id: DisplayId },
CaptureArea,
Camera,
RecordingControls,
Upgrade,
ModeSelect,
Debug,
ScreenshotEditor { id: u32 },
Onboarding,
Teleprompter,
}
impl FromStr for CapWindowId {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"main" => Self::Main,
"settings" => Self::Settings,
s if is_camera_window_label(s) => 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,
"onboarding" => Self::Onboarding,
"teleprompter" => Self::Teleprompter,
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}")),
})
}
}