Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
5064 lines (4532 loc) · 150 KB
/
Copy pathlib.rs
File metadata and controls
5064 lines (4532 loc) · 150 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
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The Servo 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"
)]
#[cfg(not(desktop))]
compile_error!("the experimental Servo backend is only supported on desktop targets");
use self::monitor::MonitorExt;
use http::{Request, Response};
use raw_window_handle::{DisplayHandle, HasDisplayHandle, HasWindowHandle};
use std::borrow::Cow;
use tauri_runtime::{
dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size},
monitor::Monitor,
webview::{DetachedWebview, DownloadEvent, PendingWebview, WebviewIpcHandler},
window::{
CursorIcon, DetachedWindow, DetachedWindowWebview, DragDropEvent, PendingWindow, RawWindow,
WebviewEvent, WindowBuilder, WindowBuilderBase, WindowEvent, WindowId, WindowSizeConstraints,
},
Cookie, DeviceEventFilter, Error, EventLoopProxy, ExitRequestedEventAction, Icon,
ProgressBarState, ProgressBarStatus, Result, RunEvent, Runtime, RuntimeHandle, RuntimeInitArgs,
UserAttentionType, UserEvent, WebviewDispatch, WebviewEventId, WindowDispatch, WindowEventId,
};
pub use tao;
#[cfg(target_os = "android")]
use tao::platform::android::{WindowBuilderExtAndroid, WindowExtAndroid};
#[cfg(target_os = "macos")]
use tao::platform::macos::{EventLoopWindowTargetExtMacOS, WindowBuilderExtMacOS};
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
use tao::platform::unix::{WindowBuilderExtUnix, WindowExtUnix};
#[cfg(windows)]
use tao::platform::windows::{WindowBuilderExtWindows, WindowExtWindows};
pub use tao::window::{Window, WindowBuilder as TaoWindowBuilder, WindowId as TaoWindowId};
use tao::{
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,
},
};
use tauri_utils::config::PreventOverflowConfig;
#[cfg(target_os = "macos")]
use tauri_utils::TitleBarStyle;
use tauri_utils::{
config::{Color, WindowConfig},
Theme,
};
use url::Url;
#[cfg(windows)]
use windows::Win32::Foundation::HWND;
pub use crate::servo::{WebViewBuilderExtServo, WebViewExtServo};
#[cfg(target_os = "ios")]
pub use tao::platform::ios::{WindowBuilderExtIOS, WindowExtIOS};
#[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::{BTreeMap, HashMap},
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;
mod monitor;
pub mod servo;
#[cfg(windows)]
mod undecorated_resizing;
mod util;
mod webview;
mod window;
pub use webview::Webview;
use window::WindowExt as _;
pub mod error;
pub use error::{Error as ServoError, Result as ServoResult};
pub use cookie;
pub use http;
/// JavaScript that replaces Tauri's default invoke system with one compatible
/// with Servo's IPC bridge.
///
/// Servo does not expose custom protocol request bodies to embedders, so the
/// default invoke system's custom protocol path cannot carry invoke payloads.
/// Pass this script to `tauri::Builder::invoke_system` when using this
/// runtime:
///
/// ```ignore
/// tauri::Builder::<tauri_runtime_servo::Servo<tauri::EventLoopMessage>>::new()
/// .invoke_system(tauri_runtime_servo::INVOKE_SYSTEM_SCRIPT)
/// .run(tauri::generate_context!())
/// .unwrap();
/// ```
pub const INVOKE_SYSTEM_SCRIPT: &str = include_str!("./invoke-system-initialization-script.js");
pub use url;
/// Type alias for a color in the RGBA format.
///
/// Each value can be 0..255 inclusive.
pub type RGBA = (u8, u8, u8, u8);
/// A rectangular region.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rect {
/// Rect position.
pub position: dpi::Position,
/// Rect size.
pub size: dpi::Size,
}
impl Default for Rect {
fn default() -> Self {
Self {
position: dpi::LogicalPosition::new(0, 0).into(),
size: dpi::LogicalSize::new(0, 0).into(),
}
}
}
/// Type of page loading event.
pub enum PageLoadEvent {
/// Indicates that the content of the page has started loading.
Started,
/// Indicates that the page content has finished loading.
Finished,
}
/// An initialization script.
#[derive(Debug, Clone)]
pub struct InitializationScript {
/// The script to run.
pub script: String,
/// Whether the script should be injected to main frame only.
///
/// Servo injects scripts into every frame; this flag is kept for API parity.
pub for_main_frame_only: bool,
}
/// Resolves a custom protocol [`Request`] asynchronously.
///
/// See [`WebViewBuilder::with_asynchronous_custom_protocol`] for more information.
pub struct RequestAsyncResponder {
pub(crate) responder: AsyncResponderFn,
}
/// Boxed closure resolving an asynchronous custom protocol request.
pub(crate) type AsyncResponderFn = Box<dyn FnOnce(Response<Cow<'static, [u8]>>)>;
/// Boxed handler for a custom protocol request.
type CustomProtocolHandler =
Box<dyn Fn(WebViewId, Request<Vec<u8>>, RequestAsyncResponder) + Send + Sync>;
/// Boxed handler deciding whether a download may start (may rewrite the path).
type DownloadStartedHandler = Box<dyn FnMut(String, &mut PathBuf) -> bool>;
/// Boxed handler observing a finished (or failed) download.
type DownloadCompletedHandler = Box<dyn Fn(String, Option<PathBuf>, bool)>;
// SAFETY: even though the webview bindings do not indicate the responder is Send,
// it actually is and we need it in order to let the user do the protocol computation
// on a separate thread or async task.
unsafe impl Send for RequestAsyncResponder {}
impl RequestAsyncResponder {
/// Resolves the request with the given response.
pub fn respond<T: Into<Cow<'static, [u8]>>>(self, response: Response<T>) {
let (parts, body) = response.into_parts();
(self.responder)(Response::from_parts(parts, body.into()))
}
}
/// An id that will be passed when this webview makes requests in certain callbacks.
pub type WebViewId<'a> = &'a str;
// WebViewAttributes is not stable enough to be pub.
struct WebViewAttributes<'a> {
pub id: Option<WebViewId<'a>>,
pub visible: bool,
pub transparent: bool,
pub background_color: Option<RGBA>,
pub url: Option<String>,
pub headers: Option<http::HeaderMap>,
pub html: Option<String>,
pub bounds: Option<Rect>,
pub initialization_scripts: Vec<InitializationScript>,
pub custom_protocols: HashMap<String, CustomProtocolHandler>,
pub ipc_handler: Option<Box<dyn Fn(Request<String>)>>,
pub navigation_handler: Option<Box<dyn Fn(String) -> bool>>,
pub document_title_changed_handler: Option<Box<dyn Fn(String)>>,
pub on_page_load_handler: Option<Box<dyn Fn(PageLoadEvent, String)>>,
pub download_started_handler: Option<DownloadStartedHandler>,
pub download_completed_handler: Option<DownloadCompletedHandler>,
pub javascript_disabled: bool,
pub user_agent: Option<String>,
pub proxy_config: Option<ProxyConfig>,
}
impl Default for WebViewAttributes<'_> {
fn default() -> Self {
Self {
id: None,
visible: true,
transparent: false,
background_color: None,
url: None,
headers: None,
html: None,
bounds: None,
initialization_scripts: Vec::new(),
custom_protocols: HashMap::new(),
ipc_handler: None,
navigation_handler: None,
document_title_changed_handler: None,
on_page_load_handler: None,
download_started_handler: None,
download_completed_handler: None,
javascript_disabled: false,
user_agent: None,
proxy_config: None,
}
}
}
/// The fundamental type to present a [`WebView`].
///
/// [`WebViewBuilder`] / [`WebView`] are the basic building blocks to construct WebView contents.
pub struct WebView {
pub(crate) webview: servo::InnerWebView,
}
impl std::ops::Deref for WebView {
type Target = servo::InnerWebView;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.webview
}
}
impl WebView {
/// Returns the id of this webview.
pub fn id(&self) -> WebViewId<'_> {
self.webview.id()
}
/// Returns a reference to the underlying Servo embedder.
pub fn servo(&self) -> &servo::embedder::Embedder {
self.webview.embedder()
}
}
/// Webview builder that is used to create a [`WebView`].
pub struct WebViewBuilder<'a> {
pub(crate) attrs: WebViewAttributes<'a>,
/// Records errors before the [`WebViewBuilder::build_servo`] is called.
pub(crate) error: crate::ServoResult<()>,
}
impl<'a> WebViewBuilder<'a> {
/// Create a new [`WebViewBuilder`].
pub fn new() -> Self {
Self {
attrs: WebViewAttributes::default(),
error: Ok(()),
}
}
/// Set an id that will be passed when this webview makes requests in certain callbacks.
pub fn with_id(mut self, id: WebViewId<'a>) -> Self {
self.attrs.id = Some(id);
self
}
/// Sets whether the WebView should be visible.
pub fn with_visible(mut self, visible: bool) -> Self {
self.attrs.visible = visible;
self
}
/// Sets whether the WebView should be transparent.
pub fn with_transparent(mut self, transparent: bool) -> Self {
self.attrs.transparent = transparent;
self
}
/// Specify the webview background color. This will be ignored if `transparent` is set to `true`.
pub fn with_background_color(mut self, background_color: RGBA) -> Self {
self.attrs.background_color = Some(background_color);
self
}
/// Disables JavaScript.
pub fn with_javascript_disabled(mut self) -> Self {
self.attrs.javascript_disabled = true;
self
}
/// Add an initialization script to run on every page load.
pub fn with_initialization_script<S: Into<String>>(self, js: S) -> Self {
self.with_initialization_script_for_main_only(js, true)
}
/// Add an initialization script to run on every page load in the main frame.
pub fn with_initialization_script_for_main_only<S: Into<String>>(
mut self,
js: S,
for_main_frame_only: bool,
) -> Self {
self
.attrs
.initialization_scripts
.push(InitializationScript {
script: js.into(),
for_main_frame_only,
});
self
}
/// Register an asynchronous custom protocol.
pub fn with_asynchronous_custom_protocol<F>(mut self, name: String, handler: F) -> Self
where
F: Fn(WebViewId, Request<Vec<u8>>, RequestAsyncResponder) + Send + Sync + 'static,
{
self.attrs.custom_protocols.insert(name, Box::new(handler));
self
}
/// Set the ipc handler.
pub fn with_ipc_handler<F>(mut self, handler: F) -> Self
where
F: Fn(Request<String>) + 'static,
{
self.attrs.ipc_handler = Some(Box::new(handler));
self
}
/// Set the navigation handler.
pub fn with_navigation_handler<F>(mut self, callback: F) -> Self
where
F: Fn(String) -> bool + 'static,
{
self.attrs.navigation_handler = Some(Box::new(callback));
self
}
/// Set the document title changed handler.
pub fn with_document_title_changed_handler<F>(mut self, callback: F) -> Self
where
F: Fn(String) + 'static,
{
self.attrs.document_title_changed_handler = Some(Box::new(callback));
self
}
/// Set the page load handler.
pub fn with_on_page_load_handler<F>(mut self, callback: F) -> Self
where
F: Fn(PageLoadEvent, String) + 'static,
{
self.attrs.on_page_load_handler = Some(Box::new(callback));
self
}
/// Set the download started handler.
pub fn with_download_started_handler<F>(mut self, callback: F) -> Self
where
F: FnMut(String, &mut PathBuf) -> bool + 'static,
{
self.attrs.download_started_handler = Some(Box::new(callback));
self
}
/// Set the download completed handler.
pub fn with_download_completed_handler<F>(mut self, callback: F) -> Self
where
F: Fn(String, Option<PathBuf>, bool) + 'static,
{
self.attrs.download_completed_handler = Some(Box::new(callback));
self
}
/// Set the url to be loaded.
pub fn with_url(mut self, url: impl Into<String>) -> Self {
self.attrs.url = Some(url.into());
self
}
/// Set the bounds of the webview.
pub fn with_bounds(mut self, bounds: Rect) -> Self {
self.attrs.bounds = Some(bounds);
self
}
/// Set the user agent.
pub fn with_user_agent(mut self, user_agent: &str) -> Self {
self.attrs.user_agent = Some(user_agent.into());
self
}
/// Set the proxy configuration.
pub fn with_proxy_config(mut self, config: ProxyConfig) -> Self {
self.attrs.proxy_config = Some(config);
self
}
}
impl Default for WebViewBuilder<'_> {
fn default() -> Self {
Self::new()
}
}
/// The configuration of a proxy server.
#[derive(Debug, Clone)]
pub enum ProxyConfig {
/// A HTTP proxy.
Http(ProxyEndpoint),
/// A SOCKS5 proxy.
Socks5(ProxyEndpoint),
}
/// An endpoint (host and port) of a proxy server.
#[derive(Debug, Clone)]
pub struct ProxyEndpoint {
/// The host of the proxy server.
pub host: String,
/// The port of the proxy server.
pub port: u16,
}
// 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);
}
pub 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! event_loop_window_getter {
($self: ident, $message: expr) => {{
let (tx, rx) = channel();
getter!($self, rx, Message::EventLoopWindowTarget($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,
windows: &context.main_thread.windows,
},
);
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>,
next_window_id: Arc<AtomicU32>,
next_webview_id: Arc<AtomicU32>,
next_window_event_id: Arc<AtomicU32>,
next_webview_event_id: Arc<AtomicU32>,
}
unsafe impl<T: UserEvent> Send for Context<T> {}
unsafe impl<T: UserEvent> Sync for Context<T> {}
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, Servo<T>>,
after_window_creation: Option<F>,
) -> Result<DetachedWindow<T, Servo<T>>> {
let label = pending.label.clone();
let context = self.clone();
let window_id = self.next_window_id();
let (webview_id, use_https_scheme) = pending
.webview
.as_ref()
.map(|w| {
(
Some(context.next_webview_id()),
w.webview_attributes.use_https_scheme,
)
})
.unwrap_or((None, false));
let (tx, rx) = channel();
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,
)
}),
tx,
),
)?;
rx.recv()
.map_err(|_| crate::Error::FailedToReceiveMessage)??;
let dispatcher = ServoWindowDispatcher {
window_id,
context: self.clone(),
};
let detached_webview = webview_id.map(|id| {
let webview = DetachedWebview {
label: label.clone(),
dispatcher: ServoWebviewDispatcher {
window_id: Arc::new(Mutex::new(window_id)),
webview_id: id,
context: self.clone(),
},
};
DetachedWindowWebview {
webview,
use_https_scheme,
}
});
Ok(DetachedWindow {
id: window_id,
label,
dispatcher,
webview: detached_webview,
})
}
fn create_webview(
&self,
window_id: WindowId,
pending: PendingWebview<T, Servo<T>>,
) -> Result<DetachedWebview<T, Servo<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();
let (tx, rx) = channel();
send_user_message(
self,
Message::CreateWebview(
window_id,
Box::new(move |window, options| {
create_webview(
WebviewKind::WindowChild,
window,
window_id_wrapper_,
webview_id,
&context,
pending,
options.focused_webview,
)
}),
tx,
),
)?;
rx.recv()
.map_err(|_| crate::Error::FailedToReceiveMessage)??;
let dispatcher = ServoWebviewDispatcher {
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(pub RefCell<BTreeMap<WindowId, WindowWrapper>>);
#[derive(Debug, Clone)]
pub struct DispatcherMainThreadContext<T: UserEvent> {
pub window_target: EventLoopWindowTarget<Message<T>>,
// changing this to an Rc will cause frequent app crashes.
pub windows: Arc<WindowsStore>,
#[cfg(feature = "tracing")]
pub active_tracing_spans: ActiveTraceSpanStore,
}
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 Rect);
impl From<tauri_runtime::dpi::Rect> for RectWrapper {
fn from(value: tauri_runtime::dpi::Rect) -> Self {
RectWrapper(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 map_from_tao(event: &TaoWindowEvent<'_>, #[cfg(windows)] window: &WindowWrapper) -> Self {
let event = match event {
TaoWindowEvent::Resized(size) => WindowEvent::Resized(*size),
TaoWindowEvent::Moved(position) => WindowEvent::Moved(*position),
TaoWindowEvent::Destroyed => WindowEvent::Destroyed,
TaoWindowEvent::ScaleFactorChanged {
scale_factor,
new_inner_size,
} => WindowEvent::ScaleFactorChanged {
scale_factor: *scale_factor,
new_inner_size: **new_inner_size,
},
TaoWindowEvent::Focused(focused) => {
#[cfg(not(windows))]
return Self(Some(WindowEvent::Focused(*focused)));
// on multiwebview mode, if there's no focused webview, it means we're receiving a direct window focus change
// (without receiving a webview focus, such as when clicking the taskbar app icon or using Alt + Tab)
// in this case we must send the focus change event here
#[cfg(windows)]
if window.has_children.load(Ordering::Relaxed) {
if !*focused {
// Blur events are handled in the webview side (add_LostFocus)
return Self(None);
}
let mut focused_webview = window.focused_webview.lock().unwrap();
if let FocusState::Blured {
last_focused_webview_label,
} = &*focused_webview
{
let should_focus_webview =
last_focused_webview_label
.as_deref()
.and_then(|last_focused_webview_label| {
window
.webviews
.iter()
.find(|w| w.label == last_focused_webview_label)
});
*focused_webview = FocusState::WindowFocused;
if let Some(should_focus_webview) = should_focus_webview {
drop(focused_webview);
let _ = should_focus_webview.focus();
}
WindowEvent::Focused(true)
} else {
// Already focused
return Self(None);
}
} else if window.webviews.is_empty() {
// Raw tao window without webviews, forward the event
WindowEvent::Focused(*focused)
} else {
// when not on multiwebview mode, focus changes are handled on the webview
return Self(None);
}
}
TaoWindowEvent::ThemeChanged(theme) => WindowEvent::ThemeChanged(map_theme(theme)),
#[cfg(mobile)]
TaoWindowEvent::Suspended => WindowEvent::Suspended,
#[cfg(mobile)]
TaoWindowEvent::Resumed => WindowEvent::Resumed,
_ => return Self(None),
};
Self(Some(event))
}
fn parse(window: &WindowWrapper, event: &TaoWindowEvent<'_>) -> Self {
match event {
// resized event from tao doesn't include a reliable size on macOS
// because the webview 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(size)))
} else {
Self(None)
}
}
e => Self::map_from_tao(
e,
#[cfg(windows)]
window,
),
}
}
}
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!(),
}
}
pub struct MonitorHandleWrapper(pub MonitorHandle);
impl From<MonitorHandleWrapper> for Monitor {
fn from(monitor: MonitorHandleWrapper) -> Monitor {
Self {
name: monitor.0.name(),
position: monitor.0.position(),
size: monitor.0.size(),
work_area: monitor.0.work_area(),
scale_factor: monitor.0.scale_factor(),
}
}
}
#[cfg(desktop)]
fn find_monitor_for_position(
monitors: impl Iterator<Item = MonitorHandle>,
window_position: Position,
) -> Option<MonitorHandle> {
monitors.into_iter().find(|m| {
let monitor_pos = m.position();
let monitor_size = m.size();
// type annotations required for 32bit targets.
let window_position = window_position.to_physical::<i32>(m.scale_factor());
monitor_pos.x <= window_position.x
&& window_position.x < monitor_pos.x + monitor_size.width as i32
&& monitor_pos.y <= window_position.y
&& window_position.y < monitor_pos.y + monitor_size.height as i32
})
}
#[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 {