-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
lib.rs
4360 lines (3910 loc) · 128 KB
/
lib.rs
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
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [![](https://github.com/tauri-apps/tauri/raw/dev/.github/splash.png)](https://tauri.app)
//!
//! The [`wry`] Tauri [`Runtime`].
//!
//! None of the exposed API of this crate is stable, and it may break semver
//! compatibility in the future. The major version only signifies the intended Tauri version.
#![doc(
html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png",
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png"
)]
use http::Request;
use raw_window_handle::{DisplayHandle, HasDisplayHandle, HasWindowHandle};
use tauri_runtime::{
dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size},
monitor::Monitor,
webview::{DetachedWebview, DownloadEvent, PendingWebview, WebviewIpcHandler},
window::{
CursorIcon, DetachedWindow, DragDropEvent, PendingWindow, RawWindow, WebviewEvent,
WindowBuilder, WindowBuilderBase, WindowEvent, WindowId, WindowSizeConstraints,
},
DeviceEventFilter, Error, EventLoopProxy, ExitRequestedEventAction, Icon, ProgressBarState,
ProgressBarStatus, Result, RunEvent, Runtime, RuntimeHandle, RuntimeInitArgs, UserAttentionType,
UserEvent, WebviewDispatch, WebviewEventId, WindowDispatch, WindowEventId,
};
#[cfg(target_os = "macos")]
use tao::platform::macos::{EventLoopWindowTargetExtMacOS, WindowBuilderExtMacOS};
#[cfg(target_os = "linux")]
use tao::platform::unix::{WindowBuilderExtUnix, WindowExtUnix};
#[cfg(windows)]
use tao::platform::windows::{WindowBuilderExtWindows, WindowExtWindows};
#[cfg(windows)]
use webview2_com::FocusChangedEventHandler;
#[cfg(windows)]
use windows::Win32::{Foundation::HWND, System::WinRT::EventRegistrationToken};
#[cfg(windows)]
use wry::WebViewBuilderExtWindows;
use tao::{
dpi::{
LogicalPosition as TaoLogicalPosition, LogicalSize as TaoLogicalSize,
PhysicalPosition as TaoPhysicalPosition, PhysicalSize as TaoPhysicalSize,
Position as TaoPosition, Size as TaoSize,
},
event::{Event, StartCause, WindowEvent as TaoWindowEvent},
event_loop::{
ControlFlow, DeviceEventFilter as TaoDeviceEventFilter, EventLoop, EventLoopBuilder,
EventLoopProxy as TaoEventLoopProxy, EventLoopWindowTarget,
},
monitor::MonitorHandle,
window::{
CursorIcon as TaoCursorIcon, Fullscreen, Icon as TaoWindowIcon,
ProgressBarState as TaoProgressBarState, ProgressState as TaoProgressState, Theme as TaoTheme,
UserAttentionType as TaoUserAttentionType,
},
};
#[cfg(target_os = "macos")]
use tauri_utils::TitleBarStyle;
use tauri_utils::{config::WindowConfig, Theme};
use url::Url;
use wry::{
DragDropEvent as WryDragDropEvent, ProxyConfig, ProxyEndpoint, WebContext as WryWebContext,
WebView, WebViewBuilder,
};
pub use tao;
pub use tao::window::{Window, WindowBuilder as TaoWindowBuilder, WindowId as TaoWindowId};
pub use wry;
pub use wry::webview_version;
#[cfg(windows)]
use wry::WebViewExtWindows;
#[cfg(target_os = "android")]
use wry::{
prelude::{dispatch, find_class},
WebViewBuilderExtAndroid, WebViewExtAndroid,
};
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
target_os = "android"
)))]
use wry::{WebViewBuilderExtUnix, WebViewExtUnix};
#[cfg(target_os = "macos")]
pub use tao::platform::macos::{
ActivationPolicy as TaoActivationPolicy, EventLoopExtMacOS, WindowExtMacOS,
};
#[cfg(target_os = "macos")]
use tauri_runtime::ActivationPolicy;
use std::{
cell::RefCell,
collections::{
hash_map::Entry::{Occupied, Vacant},
BTreeMap, HashMap, HashSet,
},
fmt,
ops::Deref,
path::PathBuf,
rc::Rc,
sync::{
atomic::{AtomicBool, AtomicU32, Ordering},
mpsc::{channel, Sender},
Arc, Mutex, Weak,
},
thread::{current as current_thread, ThreadId},
};
pub type WebviewId = u32;
type IpcHandler = dyn Fn(Request<String>) + 'static;
#[cfg(any(
windows,
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
mod undecorated_resizing;
mod webview;
pub use webview::Webview;
#[derive(Debug)]
pub struct WebContext {
pub inner: WryWebContext,
pub referenced_by_webviews: HashSet<String>,
// on Linux the custom protocols are associated with the context
// and you cannot register a URI scheme more than once
pub registered_custom_protocols: HashSet<String>,
}
pub type WebContextStore = Arc<Mutex<HashMap<Option<PathBuf>, WebContext>>>;
// window
pub type WindowEventHandler = Box<dyn Fn(&WindowEvent) + Send>;
pub type WindowEventListeners = Arc<Mutex<HashMap<WindowEventId, WindowEventHandler>>>;
pub type WebviewEventHandler = Box<dyn Fn(&WebviewEvent) + Send>;
pub type WebviewEventListeners = Arc<Mutex<HashMap<WebviewEventId, WebviewEventHandler>>>;
#[derive(Debug, Clone, Default)]
pub struct WindowIdStore(Arc<Mutex<HashMap<TaoWindowId, WindowId>>>);
impl WindowIdStore {
pub fn insert(&self, w: TaoWindowId, id: WindowId) {
self.0.lock().unwrap().insert(w, id);
}
fn get(&self, w: &TaoWindowId) -> Option<WindowId> {
self.0.lock().unwrap().get(w).copied()
}
}
#[macro_export]
macro_rules! getter {
($self: ident, $rx: expr, $message: expr) => {{
$crate::send_user_message(&$self.context, $message)?;
$rx
.recv()
.map_err(|_| $crate::Error::FailedToReceiveMessage)
}};
}
macro_rules! window_getter {
($self: ident, $message: expr) => {{
let (tx, rx) = channel();
getter!($self, rx, Message::Window($self.window_id, $message(tx)))
}};
}
macro_rules! webview_getter {
($self: ident, $message: expr) => {{
let (tx, rx) = channel();
getter!(
$self,
rx,
Message::Webview(
*$self.window_id.lock().unwrap(),
$self.webview_id,
$message(tx)
)
)
}};
}
pub(crate) fn send_user_message<T: UserEvent>(
context: &Context<T>,
message: Message<T>,
) -> Result<()> {
if current_thread().id() == context.main_thread_id {
handle_user_message(
&context.main_thread.window_target,
message,
UserMessageContext {
window_id_map: context.window_id_map.clone(),
windows: context.main_thread.windows.clone(),
},
);
Ok(())
} else {
context
.proxy
.send_event(message)
.map_err(|_| Error::FailedToSendMessage)
}
}
#[derive(Clone)]
pub struct Context<T: UserEvent> {
pub window_id_map: WindowIdStore,
main_thread_id: ThreadId,
pub proxy: TaoEventLoopProxy<Message<T>>,
main_thread: DispatcherMainThreadContext<T>,
plugins: Arc<Mutex<Vec<Box<dyn Plugin<T> + Send>>>>,
next_window_id: Arc<AtomicU32>,
next_webview_id: Arc<AtomicU32>,
next_window_event_id: Arc<AtomicU32>,
next_webview_event_id: Arc<AtomicU32>,
}
impl<T: UserEvent> Context<T> {
pub fn run_threaded<R, F>(&self, f: F) -> R
where
F: FnOnce(Option<&DispatcherMainThreadContext<T>>) -> R,
{
f(if current_thread().id() == self.main_thread_id {
Some(&self.main_thread)
} else {
None
})
}
fn next_window_id(&self) -> WindowId {
self.next_window_id.fetch_add(1, Ordering::Relaxed).into()
}
fn next_webview_id(&self) -> WebviewId {
self.next_webview_id.fetch_add(1, Ordering::Relaxed)
}
fn next_window_event_id(&self) -> u32 {
self.next_window_event_id.fetch_add(1, Ordering::Relaxed)
}
fn next_webview_event_id(&self) -> u32 {
self.next_webview_event_id.fetch_add(1, Ordering::Relaxed)
}
}
impl<T: UserEvent> Context<T> {
fn create_window<F: Fn(RawWindow) + Send + 'static>(
&self,
pending: PendingWindow<T, Wry<T>>,
after_window_creation: Option<F>,
) -> Result<DetachedWindow<T, Wry<T>>> {
let label = pending.label.clone();
let context = self.clone();
let window_id = self.next_window_id();
let webview_id = pending.webview.as_ref().map(|_| context.next_webview_id());
send_user_message(
self,
Message::CreateWindow(
window_id,
Box::new(move |event_loop| {
create_window(
window_id,
webview_id.unwrap_or_default(),
event_loop,
&context,
pending,
after_window_creation,
)
}),
),
)?;
let dispatcher = WryWindowDispatcher {
window_id,
context: self.clone(),
};
let detached_webview = webview_id.map(|id| DetachedWebview {
label: label.clone(),
dispatcher: WryWebviewDispatcher {
window_id: Arc::new(Mutex::new(window_id)),
webview_id: id,
context: self.clone(),
},
});
Ok(DetachedWindow {
id: window_id,
label,
dispatcher,
webview: detached_webview,
})
}
fn create_webview(
&self,
window_id: WindowId,
pending: PendingWebview<T, Wry<T>>,
) -> Result<DetachedWebview<T, Wry<T>>> {
let label = pending.label.clone();
let context = self.clone();
let webview_id = self.next_webview_id();
let window_id_wrapper = Arc::new(Mutex::new(window_id));
let window_id_wrapper_ = window_id_wrapper.clone();
send_user_message(
self,
Message::CreateWebview(
window_id,
Box::new(move |window| {
create_webview(
WebviewKind::WindowChild,
window,
window_id_wrapper_,
webview_id,
&context,
pending,
)
}),
),
)?;
let dispatcher = WryWebviewDispatcher {
window_id: window_id_wrapper,
webview_id,
context: self.clone(),
};
Ok(DetachedWebview { label, dispatcher })
}
}
#[cfg(feature = "tracing")]
#[derive(Debug, Clone, Default)]
pub struct ActiveTraceSpanStore(Rc<RefCell<Vec<ActiveTracingSpan>>>);
#[cfg(feature = "tracing")]
impl ActiveTraceSpanStore {
pub fn remove_window_draw(&self) {
self
.0
.borrow_mut()
.retain(|t| !matches!(t, ActiveTracingSpan::WindowDraw { id: _, span: _ }));
}
}
#[cfg(feature = "tracing")]
#[derive(Debug)]
pub enum ActiveTracingSpan {
WindowDraw {
id: TaoWindowId,
span: tracing::span::EnteredSpan,
},
}
#[derive(Debug)]
pub struct WindowsStore(RefCell<BTreeMap<WindowId, WindowWrapper>>);
// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for WindowsStore {}
// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Sync for WindowsStore {}
#[derive(Debug, Clone)]
pub struct DispatcherMainThreadContext<T: UserEvent> {
pub window_target: EventLoopWindowTarget<Message<T>>,
pub web_context: WebContextStore,
// changing this to an Rc will cause frequent app crashes.
pub windows: Arc<WindowsStore>,
#[cfg(feature = "tracing")]
pub active_tracing_spans: ActiveTraceSpanStore,
}
// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl<T: UserEvent> Send for DispatcherMainThreadContext<T> {}
// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl<T: UserEvent> Sync for DispatcherMainThreadContext<T> {}
impl<T: UserEvent> fmt::Debug for Context<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Context")
.field("main_thread_id", &self.main_thread_id)
.field("proxy", &self.proxy)
.field("main_thread", &self.main_thread)
.finish()
}
}
pub struct DeviceEventFilterWrapper(pub TaoDeviceEventFilter);
impl From<DeviceEventFilter> for DeviceEventFilterWrapper {
fn from(item: DeviceEventFilter) -> Self {
match item {
DeviceEventFilter::Always => Self(TaoDeviceEventFilter::Always),
DeviceEventFilter::Never => Self(TaoDeviceEventFilter::Never),
DeviceEventFilter::Unfocused => Self(TaoDeviceEventFilter::Unfocused),
}
}
}
pub struct RectWrapper(pub wry::Rect);
impl From<tauri_runtime::Rect> for RectWrapper {
fn from(value: tauri_runtime::Rect) -> Self {
RectWrapper(wry::Rect {
position: value.position,
size: value.size,
})
}
}
/// Wrapper around a [`tao::window::Icon`] that can be created from an [`Icon`].
pub struct TaoIcon(pub TaoWindowIcon);
impl TryFrom<Icon<'_>> for TaoIcon {
type Error = Error;
fn try_from(icon: Icon<'_>) -> std::result::Result<Self, Self::Error> {
TaoWindowIcon::from_rgba(icon.rgba.to_vec(), icon.width, icon.height)
.map(Self)
.map_err(|e| Error::InvalidIcon(Box::new(e)))
}
}
pub struct WindowEventWrapper(pub Option<WindowEvent>);
impl WindowEventWrapper {
fn parse(window: &WindowWrapper, event: &TaoWindowEvent<'_>) -> Self {
match event {
// resized event from tao doesn't include a reliable size on macOS
// because wry replaces the NSView
TaoWindowEvent::Resized(_) => {
if let Some(w) = &window.inner {
let size = inner_size(
w,
&window.webviews,
window.has_children.load(Ordering::Relaxed),
);
Self(Some(WindowEvent::Resized(PhysicalSizeWrapper(size).into())))
} else {
Self(None)
}
}
e => e.into(),
}
}
}
pub fn map_theme(theme: &TaoTheme) -> Theme {
match theme {
TaoTheme::Light => Theme::Light,
TaoTheme::Dark => Theme::Dark,
_ => Theme::Light,
}
}
#[cfg(target_os = "macos")]
fn tao_activation_policy(activation_policy: ActivationPolicy) -> TaoActivationPolicy {
match activation_policy {
ActivationPolicy::Regular => TaoActivationPolicy::Regular,
ActivationPolicy::Accessory => TaoActivationPolicy::Accessory,
ActivationPolicy::Prohibited => TaoActivationPolicy::Prohibited,
_ => unimplemented!(),
}
}
impl<'a> From<&TaoWindowEvent<'a>> for WindowEventWrapper {
fn from(event: &TaoWindowEvent<'a>) -> Self {
let event = match event {
TaoWindowEvent::Resized(size) => WindowEvent::Resized(PhysicalSizeWrapper(*size).into()),
TaoWindowEvent::Moved(position) => {
WindowEvent::Moved(PhysicalPositionWrapper(*position).into())
}
TaoWindowEvent::Destroyed => WindowEvent::Destroyed,
TaoWindowEvent::ScaleFactorChanged {
scale_factor,
new_inner_size,
} => WindowEvent::ScaleFactorChanged {
scale_factor: *scale_factor,
new_inner_size: PhysicalSizeWrapper(**new_inner_size).into(),
},
#[cfg(any(target_os = "linux", target_os = "macos"))]
TaoWindowEvent::Focused(focused) => WindowEvent::Focused(*focused),
TaoWindowEvent::ThemeChanged(theme) => WindowEvent::ThemeChanged(map_theme(theme)),
_ => return Self(None),
};
Self(Some(event))
}
}
pub struct MonitorHandleWrapper(pub MonitorHandle);
impl From<MonitorHandleWrapper> for Monitor {
fn from(monitor: MonitorHandleWrapper) -> Monitor {
Self {
name: monitor.0.name(),
position: PhysicalPositionWrapper(monitor.0.position()).into(),
size: PhysicalSizeWrapper(monitor.0.size()).into(),
scale_factor: monitor.0.scale_factor(),
}
}
}
pub struct PhysicalPositionWrapper<T>(pub TaoPhysicalPosition<T>);
impl<T> From<PhysicalPositionWrapper<T>> for PhysicalPosition<T> {
fn from(position: PhysicalPositionWrapper<T>) -> Self {
Self {
x: position.0.x,
y: position.0.y,
}
}
}
impl<T> From<PhysicalPosition<T>> for PhysicalPositionWrapper<T> {
fn from(position: PhysicalPosition<T>) -> Self {
Self(TaoPhysicalPosition {
x: position.x,
y: position.y,
})
}
}
struct LogicalPositionWrapper<T>(TaoLogicalPosition<T>);
impl<T> From<LogicalPosition<T>> for LogicalPositionWrapper<T> {
fn from(position: LogicalPosition<T>) -> Self {
Self(TaoLogicalPosition {
x: position.x,
y: position.y,
})
}
}
pub struct PhysicalSizeWrapper<T>(pub TaoPhysicalSize<T>);
impl<T> From<PhysicalSizeWrapper<T>> for PhysicalSize<T> {
fn from(size: PhysicalSizeWrapper<T>) -> Self {
Self {
width: size.0.width,
height: size.0.height,
}
}
}
impl<T> From<PhysicalSize<T>> for PhysicalSizeWrapper<T> {
fn from(size: PhysicalSize<T>) -> Self {
Self(TaoPhysicalSize {
width: size.width,
height: size.height,
})
}
}
struct LogicalSizeWrapper<T>(TaoLogicalSize<T>);
impl<T> From<LogicalSize<T>> for LogicalSizeWrapper<T> {
fn from(size: LogicalSize<T>) -> Self {
Self(TaoLogicalSize {
width: size.width,
height: size.height,
})
}
}
pub struct SizeWrapper(pub TaoSize);
impl From<Size> for SizeWrapper {
fn from(size: Size) -> Self {
match size {
Size::Logical(s) => Self(TaoSize::Logical(LogicalSizeWrapper::from(s).0)),
Size::Physical(s) => Self(TaoSize::Physical(PhysicalSizeWrapper::from(s).0)),
}
}
}
pub struct PositionWrapper(pub TaoPosition);
impl From<Position> for PositionWrapper {
fn from(position: Position) -> Self {
match position {
Position::Logical(s) => Self(TaoPosition::Logical(LogicalPositionWrapper::from(s).0)),
Position::Physical(s) => Self(TaoPosition::Physical(PhysicalPositionWrapper::from(s).0)),
}
}
}
#[derive(Debug, Clone)]
pub struct UserAttentionTypeWrapper(pub TaoUserAttentionType);
impl From<UserAttentionType> for UserAttentionTypeWrapper {
fn from(request_type: UserAttentionType) -> Self {
let o = match request_type {
UserAttentionType::Critical => TaoUserAttentionType::Critical,
UserAttentionType::Informational => TaoUserAttentionType::Informational,
};
Self(o)
}
}
#[derive(Debug)]
pub struct CursorIconWrapper(pub TaoCursorIcon);
impl From<CursorIcon> for CursorIconWrapper {
fn from(icon: CursorIcon) -> Self {
use CursorIcon::*;
let i = match icon {
Default => TaoCursorIcon::Default,
Crosshair => TaoCursorIcon::Crosshair,
Hand => TaoCursorIcon::Hand,
Arrow => TaoCursorIcon::Arrow,
Move => TaoCursorIcon::Move,
Text => TaoCursorIcon::Text,
Wait => TaoCursorIcon::Wait,
Help => TaoCursorIcon::Help,
Progress => TaoCursorIcon::Progress,
NotAllowed => TaoCursorIcon::NotAllowed,
ContextMenu => TaoCursorIcon::ContextMenu,
Cell => TaoCursorIcon::Cell,
VerticalText => TaoCursorIcon::VerticalText,
Alias => TaoCursorIcon::Alias,
Copy => TaoCursorIcon::Copy,
NoDrop => TaoCursorIcon::NoDrop,
Grab => TaoCursorIcon::Grab,
Grabbing => TaoCursorIcon::Grabbing,
AllScroll => TaoCursorIcon::AllScroll,
ZoomIn => TaoCursorIcon::ZoomIn,
ZoomOut => TaoCursorIcon::ZoomOut,
EResize => TaoCursorIcon::EResize,
NResize => TaoCursorIcon::NResize,
NeResize => TaoCursorIcon::NeResize,
NwResize => TaoCursorIcon::NwResize,
SResize => TaoCursorIcon::SResize,
SeResize => TaoCursorIcon::SeResize,
SwResize => TaoCursorIcon::SwResize,
WResize => TaoCursorIcon::WResize,
EwResize => TaoCursorIcon::EwResize,
NsResize => TaoCursorIcon::NsResize,
NeswResize => TaoCursorIcon::NeswResize,
NwseResize => TaoCursorIcon::NwseResize,
ColResize => TaoCursorIcon::ColResize,
RowResize => TaoCursorIcon::RowResize,
_ => TaoCursorIcon::Default,
};
Self(i)
}
}
pub struct ProgressStateWrapper(pub TaoProgressState);
impl From<ProgressBarStatus> for ProgressStateWrapper {
fn from(status: ProgressBarStatus) -> Self {
let state = match status {
ProgressBarStatus::None => TaoProgressState::None,
ProgressBarStatus::Normal => TaoProgressState::Normal,
ProgressBarStatus::Indeterminate => TaoProgressState::Indeterminate,
ProgressBarStatus::Paused => TaoProgressState::Paused,
ProgressBarStatus::Error => TaoProgressState::Error,
};
Self(state)
}
}
pub struct ProgressBarStateWrapper(pub TaoProgressBarState);
impl From<ProgressBarState> for ProgressBarStateWrapper {
fn from(progress_state: ProgressBarState) -> Self {
Self(TaoProgressBarState {
progress: progress_state.progress,
state: progress_state
.status
.map(|state| ProgressStateWrapper::from(state).0),
desktop_filename: progress_state.desktop_filename,
})
}
}
#[derive(Clone, Default)]
pub struct WindowBuilderWrapper {
inner: TaoWindowBuilder,
center: bool,
#[cfg(target_os = "macos")]
tabbing_identifier: Option<String>,
}
impl std::fmt::Debug for WindowBuilderWrapper {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = f.debug_struct("WindowBuilderWrapper");
s.field("inner", &self.inner).field("center", &self.center);
#[cfg(target_os = "macos")]
{
s.field("tabbing_identifier", &self.tabbing_identifier);
}
s.finish()
}
}
// SAFETY: this type is `Send` since `menu_items` are read only here
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for WindowBuilderWrapper {}
impl WindowBuilderBase for WindowBuilderWrapper {}
impl WindowBuilder for WindowBuilderWrapper {
fn new() -> Self {
#[allow(unused_mut)]
let mut builder = Self::default().focused(true);
#[cfg(target_os = "macos")]
{
// TODO: find a proper way to prevent webview being pushed out of the window.
// Workround for issue: https://github.com/tauri-apps/tauri/issues/10225
// The window requies `NSFullSizeContentViewWindowMask` flag to prevent devtools
// pushing the content view out of the window.
// By setting the default style to `TitleBarStyle::Visible` should fix the issue for most of the users.
builder = builder.title_bar_style(TitleBarStyle::Visible);
}
builder
}
fn with_config(config: &WindowConfig) -> Self {
let mut window = WindowBuilderWrapper::new();
#[cfg(target_os = "macos")]
{
window = window
.hidden_title(config.hidden_title)
.title_bar_style(config.title_bar_style);
if let Some(identifier) = &config.tabbing_identifier {
window = window.tabbing_identifier(identifier);
}
}
#[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
{
window = window.transparent(config.transparent);
}
#[cfg(all(
target_os = "macos",
not(feature = "macos-private-api"),
debug_assertions
))]
if config.transparent {
eprintln!(
"The window is set to be transparent but the `macos-private-api` is not enabled.
This can be enabled via the `tauri.macOSPrivateApi` configuration property <https://tauri.app/docs/api/config#tauri.macOSPrivateApi>
");
}
#[cfg(target_os = "linux")]
{
// Mouse event is disabled on Linux since sudden event bursts could block event loop.
window.inner = window.inner.with_cursor_moved_event(false);
}
#[cfg(desktop)]
{
window = window
.title(config.title.to_string())
.inner_size(config.width, config.height)
.visible(config.visible)
.resizable(config.resizable)
.fullscreen(config.fullscreen)
.decorations(config.decorations)
.maximized(config.maximized)
.always_on_bottom(config.always_on_bottom)
.always_on_top(config.always_on_top)
.visible_on_all_workspaces(config.visible_on_all_workspaces)
.content_protected(config.content_protected)
.skip_taskbar(config.skip_taskbar)
.theme(config.theme)
.closable(config.closable)
.maximizable(config.maximizable)
.minimizable(config.minimizable)
.shadow(config.shadow);
let mut constraints = WindowSizeConstraints::default();
if let Some(min_width) = config.min_width {
constraints.min_width = Some(tao::dpi::LogicalUnit::new(min_width).into());
}
if let Some(min_height) = config.min_height {
constraints.min_height = Some(tao::dpi::LogicalUnit::new(min_height).into());
}
if let Some(max_width) = config.max_width {
constraints.max_width = Some(tao::dpi::LogicalUnit::new(max_width).into());
}
if let Some(max_height) = config.max_height {
constraints.max_height = Some(tao::dpi::LogicalUnit::new(max_height).into());
}
window = window.inner_size_constraints(constraints);
if let (Some(x), Some(y)) = (config.x, config.y) {
window = window.position(x, y);
}
if config.center {
window = window.center();
}
}
window
}
fn center(mut self) -> Self {
self.center = true;
self
}
fn position(mut self, x: f64, y: f64) -> Self {
self.inner = self.inner.with_position(TaoLogicalPosition::new(x, y));
self
}
fn inner_size(mut self, width: f64, height: f64) -> Self {
self.inner = self
.inner
.with_inner_size(TaoLogicalSize::new(width, height));
self
}
fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
self.inner = self
.inner
.with_min_inner_size(TaoLogicalSize::new(min_width, min_height));
self
}
fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
self.inner = self
.inner
.with_max_inner_size(TaoLogicalSize::new(max_width, max_height));
self
}
fn inner_size_constraints(mut self, constraints: WindowSizeConstraints) -> Self {
self.inner.window.inner_size_constraints = tao::window::WindowSizeConstraints {
min_width: constraints.min_width,
min_height: constraints.min_height,
max_width: constraints.max_width,
max_height: constraints.max_height,
};
self
}
fn resizable(mut self, resizable: bool) -> Self {
self.inner = self.inner.with_resizable(resizable);
self
}
fn maximizable(mut self, maximizable: bool) -> Self {
self.inner = self.inner.with_maximizable(maximizable);
self
}
fn minimizable(mut self, minimizable: bool) -> Self {
self.inner = self.inner.with_minimizable(minimizable);
self
}
fn closable(mut self, closable: bool) -> Self {
self.inner = self.inner.with_closable(closable);
self
}
fn title<S: Into<String>>(mut self, title: S) -> Self {
self.inner = self.inner.with_title(title.into());
self
}
fn fullscreen(mut self, fullscreen: bool) -> Self {
self.inner = if fullscreen {
self
.inner
.with_fullscreen(Some(Fullscreen::Borderless(None)))
} else {
self.inner.with_fullscreen(None)
};
self
}
fn focused(mut self, focused: bool) -> Self {
self.inner = self.inner.with_focused(focused);
self
}
fn maximized(mut self, maximized: bool) -> Self {
self.inner = self.inner.with_maximized(maximized);
self
}
fn visible(mut self, visible: bool) -> Self {
self.inner = self.inner.with_visible(visible);
self
}
#[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
fn transparent(mut self, transparent: bool) -> Self {
self.inner = self.inner.with_transparent(transparent);
self
}
fn decorations(mut self, decorations: bool) -> Self {
self.inner = self.inner.with_decorations(decorations);
self
}
fn always_on_bottom(mut self, always_on_bottom: bool) -> Self {
self.inner = self.inner.with_always_on_bottom(always_on_bottom);
self
}
fn always_on_top(mut self, always_on_top: bool) -> Self {
self.inner = self.inner.with_always_on_top(always_on_top);
self
}
fn visible_on_all_workspaces(mut self, visible_on_all_workspaces: bool) -> Self {
self.inner = self
.inner
.with_visible_on_all_workspaces(visible_on_all_workspaces);
self
}
fn content_protected(mut self, protected: bool) -> Self {
self.inner = self.inner.with_content_protection(protected);
self
}
fn shadow(#[allow(unused_mut)] mut self, _enable: bool) -> Self {
#[cfg(windows)]
{
self.inner = self.inner.with_undecorated_shadow(_enable);
}
#[cfg(target_os = "macos")]
{
self.inner = self.inner.with_has_shadow(_enable);
}
self
}
#[cfg(windows)]
fn owner(mut self, owner: HWND) -> Self {
self.inner = self.inner.with_owner_window(owner.0 as _);
self
}
#[cfg(windows)]
fn parent(mut self, parent: HWND) -> Self {
self.inner = self.inner.with_parent_window(parent.0 as _);
self
}
#[cfg(target_os = "macos")]
fn parent(mut self, parent: *mut std::ffi::c_void) -> Self {
self.inner = self.inner.with_parent_window(parent);
self
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
fn transient_for(mut self, parent: &impl gtk::glib::IsA<gtk::Window>) -> Self {
self.inner = self.inner.with_transient_for(parent);
self
}
#[cfg(windows)]
fn drag_and_drop(mut self, enabled: bool) -> Self {
self.inner = self.inner.with_drag_and_drop(enabled);
self
}
#[cfg(target_os = "macos")]
fn title_bar_style(mut self, style: TitleBarStyle) -> Self {
match style {