/
window.rs
1834 lines (1667 loc) · 56.4 KB
/
window.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-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The Tauri window types and functions.
pub(crate) mod menu;
pub use menu::{MenuEvent, MenuHandle};
use url::Url;
#[cfg(target_os = "macos")]
use crate::TitleBarStyle;
use crate::{
app::AppHandle,
command::{CommandArg, CommandItem},
event::{Event, EventHandler},
hooks::{InvokePayload, InvokeResponder},
manager::WindowManager,
runtime::{
http::{Request as HttpRequest, Response as HttpResponse},
monitor::Monitor as RuntimeMonitor,
webview::{WebviewAttributes, WindowBuilder as _},
window::{
dpi::{PhysicalPosition, PhysicalSize},
DetachedWindow, JsEventListenerKey, PendingWindow,
},
Dispatch, RuntimeHandle,
},
sealed::ManagerBase,
sealed::RuntimeOrDispatch,
utils::config::{WindowConfig, WindowUrl},
EventLoopMessage, Invoke, InvokeError, InvokeMessage, InvokeResolver, Manager, PageLoadPayload,
Runtime, Theme, WindowEvent,
};
#[cfg(desktop)]
use crate::{
runtime::{
menu::Menu,
window::dpi::{Position, Size},
UserAttentionType,
},
CursorIcon, Icon,
};
use serde::Serialize;
#[cfg(windows)]
use windows::Win32::Foundation::HWND;
use tauri_macros::default_runtime;
use std::{
fmt,
hash::{Hash, Hasher},
path::PathBuf,
sync::Arc,
};
pub(crate) type WebResourceRequestHandler = dyn Fn(&HttpRequest, &mut HttpResponse) + Send + Sync;
pub(crate) type NavigationHandler = dyn Fn(Url) -> bool + Send;
#[derive(Clone, Serialize)]
struct WindowCreatedEvent {
label: String,
}
/// Monitor descriptor.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Monitor {
pub(crate) name: Option<String>,
pub(crate) size: PhysicalSize<u32>,
pub(crate) position: PhysicalPosition<i32>,
pub(crate) scale_factor: f64,
}
impl From<RuntimeMonitor> for Monitor {
fn from(monitor: RuntimeMonitor) -> Self {
Self {
name: monitor.name,
size: monitor.size,
position: monitor.position,
scale_factor: monitor.scale_factor,
}
}
}
impl Monitor {
/// Returns a human-readable name of the monitor.
/// Returns None if the monitor doesn't exist anymore.
pub fn name(&self) -> Option<&String> {
self.name.as_ref()
}
/// Returns the monitor's resolution.
pub fn size(&self) -> &PhysicalSize<u32> {
&self.size
}
/// Returns the top-left corner position of the monitor relative to the larger full screen area.
pub fn position(&self) -> &PhysicalPosition<i32> {
&self.position
}
/// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
pub fn scale_factor(&self) -> f64 {
self.scale_factor
}
}
/// A builder for a webview window managed by Tauri.
#[default_runtime(crate::Wry, wry)]
pub struct WindowBuilder<'a, R: Runtime> {
manager: WindowManager<R>,
runtime: RuntimeOrDispatch<'a, R>,
app_handle: AppHandle<R>,
label: String,
pub(crate) window_builder: <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder,
pub(crate) webview_attributes: WebviewAttributes,
web_resource_request_handler: Option<Box<WebResourceRequestHandler>>,
navigation_handler: Option<Box<NavigationHandler>>,
}
impl<'a, R: Runtime> fmt::Debug for WindowBuilder<'a, R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WindowBuilder")
.field("manager", &self.manager)
.field("app_handle", &self.app_handle)
.field("label", &self.label)
.field("window_builder", &self.window_builder)
.field("webview_attributes", &self.webview_attributes)
.finish()
}
}
impl<'a, R: Runtime> WindowBuilder<'a, R> {
/// Initializes a webview window builder with the given window label and URL to load on the webview.
///
/// # Known issues
///
/// On Windows, this function deadlocks when used in a synchronous command, see [the Webview2 issue].
/// You should use `async` commands when creating windows.
///
/// # Examples
///
/// - Create a window in the setup hook:
///
/// ```
/// tauri::Builder::default()
/// .setup(|app| {
/// let window = tauri::WindowBuilder::new(app, "label", tauri::WindowUrl::App("index.html".into()))
/// .build()?;
/// Ok(())
/// });
/// ```
///
/// - Create a window in a separate thread:
///
/// ```
/// tauri::Builder::default()
/// .setup(|app| {
/// let handle = app.handle();
/// std::thread::spawn(move || {
/// let window = tauri::WindowBuilder::new(&handle, "label", tauri::WindowUrl::App("index.html".into()))
/// .build()
/// .unwrap();
/// });
/// Ok(())
/// });
/// ```
///
/// - Create a window in a command:
///
/// ```
/// #[tauri::command]
/// async fn create_window(app: tauri::AppHandle) {
/// let window = tauri::WindowBuilder::new(&app, "label", tauri::WindowUrl::External("https://tauri.app/".parse().unwrap()))
/// .build()
/// .unwrap();
/// }
/// ```
///
/// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
pub fn new<M: Manager<R>, L: Into<String>>(manager: &'a M, label: L, url: WindowUrl) -> Self {
let runtime = manager.runtime();
let app_handle = manager.app_handle();
Self {
manager: manager.manager().clone(),
runtime,
app_handle,
label: label.into(),
window_builder: <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder::new(),
webview_attributes: WebviewAttributes::new(url),
web_resource_request_handler: None,
navigation_handler: None,
}
}
/// Initializes a webview window builder from a window config from tauri.conf.json.
/// Keep in mind that you can't create 2 windows with the same `label` so make sure
/// that the initial window was closed or change the label of the new `WindowBuilder`.
///
/// # Known issues
///
/// On Windows, this function deadlocks when used in a synchronous command, see [the Webview2 issue].
/// You should use `async` commands when creating windows.
///
/// # Examples
///
/// - Create a window in a command:
///
/// ```
/// #[tauri::command]
/// async fn reopen_window(app: tauri::AppHandle) {
/// let window = tauri::WindowBuilder::from_config(&app, app.config().tauri.windows.get(0).unwrap().clone())
/// .build()
/// .unwrap();
/// }
/// ```
///
/// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
pub fn from_config<M: Manager<R>>(manager: &'a M, config: WindowConfig) -> Self {
let runtime = manager.runtime();
let app_handle = manager.app_handle();
let url = config.url.clone();
let file_drop_enabled = config.file_drop_enabled;
let mut builder = Self {
manager: manager.manager().clone(),
runtime,
app_handle,
label: config.label.clone(),
window_builder: <R::Dispatcher as Dispatch<EventLoopMessage>>::WindowBuilder::with_config(
config,
),
webview_attributes: WebviewAttributes::new(url),
web_resource_request_handler: None,
navigation_handler: None,
};
if !file_drop_enabled {
builder = builder.disable_file_drop_handler();
}
builder
}
/// Defines a closure to be executed when the webview makes an HTTP request for a web resource, allowing you to modify the response.
///
/// Currently only implemented for the `tauri` URI protocol.
///
/// **NOTE:** Currently this is **not** executed when using external URLs such as a development server,
/// but it might be implemented in the future. **Always** check the request URL.
///
/// # Examples
///
/// ```rust,no_run
/// use tauri::{
/// utils::config::{Csp, CspDirectiveSources, WindowUrl},
/// http::header::HeaderValue,
/// window::WindowBuilder,
/// };
/// use std::collections::HashMap;
/// tauri::Builder::default()
/// .setup(|app| {
/// WindowBuilder::new(app, "core", WindowUrl::App("index.html".into()))
/// .on_web_resource_request(|request, response| {
/// if request.uri().starts_with("tauri://") {
/// // if we have a CSP header, Tauri is loading an HTML file
/// // for this example, let's dynamically change the CSP
/// if let Some(csp) = response.headers_mut().get_mut("Content-Security-Policy") {
/// // use the tauri helper to parse the CSP policy to a map
/// let mut csp_map: HashMap<String, CspDirectiveSources> = Csp::Policy(csp.to_str().unwrap().to_string()).into();
/// csp_map.entry("script-src".to_string()).or_insert_with(Default::default).push("'unsafe-inline'");
/// // use the tauri helper to get a CSP string from the map
/// let csp_string = Csp::from(csp_map).to_string();
/// *csp = HeaderValue::from_str(&csp_string).unwrap();
/// }
/// }
/// })
/// .build()?;
/// Ok(())
/// });
/// ```
pub fn on_web_resource_request<F: Fn(&HttpRequest, &mut HttpResponse) + Send + Sync + 'static>(
mut self,
f: F,
) -> Self {
self.web_resource_request_handler.replace(Box::new(f));
self
}
/// Defines a closure to be executed when the webview navigates to a URL. Returning `false` cancels the navigation.
///
/// # Examples
///
/// ```rust,no_run
/// use tauri::{
/// utils::config::{Csp, CspDirectiveSources, WindowUrl},
/// http::header::HeaderValue,
/// window::WindowBuilder,
/// };
/// use std::collections::HashMap;
/// tauri::Builder::default()
/// .setup(|app| {
/// WindowBuilder::new(app, "core", WindowUrl::App("index.html".into()))
/// .on_navigation(|url| {
/// // allow the production URL or localhost on dev
/// url.scheme() == "tauri" || (cfg!(dev) && url.host_str() == Some("localhost"))
/// })
/// .build()?;
/// Ok(())
/// });
/// ```
pub fn on_navigation<F: Fn(Url) -> bool + Send + 'static>(mut self, f: F) -> Self {
self.navigation_handler.replace(Box::new(f));
self
}
/// Creates a new webview window.
pub fn build(mut self) -> crate::Result<Window<R>> {
let web_resource_request_handler = self.web_resource_request_handler.take();
let pending = PendingWindow::new(
self.window_builder.clone(),
self.webview_attributes.clone(),
self.label.clone(),
)?;
let labels = self.manager.labels().into_iter().collect::<Vec<_>>();
let mut pending = self.manager.prepare_window(
self.app_handle.clone(),
pending,
&labels,
web_resource_request_handler,
)?;
pending.navigation_handler = self.navigation_handler.take();
let window = match &mut self.runtime {
RuntimeOrDispatch::Runtime(runtime) => runtime.create_window(pending),
RuntimeOrDispatch::RuntimeHandle(handle) => handle.create_window(pending),
RuntimeOrDispatch::Dispatch(dispatcher) => dispatcher.create_window(pending),
}
.map(|window| self.manager.attach_window(self.app_handle.clone(), window))?;
self.manager.eval_script_all(format!(
"window.__TAURI_METADATA__.__windows = {window_labels_array}.map(function (label) {{ return {{ label: label }} }})",
window_labels_array = serde_json::to_string(&self.manager.labels())?,
))?;
self.manager.emit_filter(
"tauri://window-created",
None,
Some(WindowCreatedEvent {
label: window.label().into(),
}),
|w| w != &window,
)?;
Ok(window)
}
}
/// Desktop APIs.
#[cfg(desktop)]
impl<'a, R: Runtime> WindowBuilder<'a, R> {
/// Sets the menu for the window.
#[must_use]
pub fn menu(mut self, menu: Menu) -> Self {
self.window_builder = self.window_builder.menu(menu);
self
}
/// Show window in the center of the screen.
#[must_use]
pub fn center(mut self) -> Self {
self.window_builder = self.window_builder.center();
self
}
/// The initial position of the window's.
#[must_use]
pub fn position(mut self, x: f64, y: f64) -> Self {
self.window_builder = self.window_builder.position(x, y);
self
}
/// Window size.
#[must_use]
pub fn inner_size(mut self, width: f64, height: f64) -> Self {
self.window_builder = self.window_builder.inner_size(width, height);
self
}
/// Window min inner size.
#[must_use]
pub fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
self.window_builder = self.window_builder.min_inner_size(min_width, min_height);
self
}
/// Window max inner size.
#[must_use]
pub fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
self.window_builder = self.window_builder.max_inner_size(max_width, max_height);
self
}
/// Whether the window is resizable or not.
#[must_use]
pub fn resizable(mut self, resizable: bool) -> Self {
self.window_builder = self.window_builder.resizable(resizable);
self
}
/// The title of the window in the title bar.
#[must_use]
pub fn title<S: Into<String>>(mut self, title: S) -> Self {
self.window_builder = self.window_builder.title(title);
self
}
/// Whether to start the window in fullscreen or not.
#[must_use]
pub fn fullscreen(mut self, fullscreen: bool) -> Self {
self.window_builder = self.window_builder.fullscreen(fullscreen);
self
}
/// Sets the window to be initially focused.
#[must_use]
#[deprecated(
since = "1.2.0",
note = "The window is automatically focused by default. This function Will be removed in 2.0.0. Use `focused` instead."
)]
pub fn focus(mut self) -> Self {
self.window_builder = self.window_builder.focused(true);
self
}
/// Whether the window will be initially focused or not.
#[must_use]
pub fn focused(mut self, focused: bool) -> Self {
self.window_builder = self.window_builder.focused(focused);
self
}
/// Whether the window should be maximized upon creation.
#[must_use]
pub fn maximized(mut self, maximized: bool) -> Self {
self.window_builder = self.window_builder.maximized(maximized);
self
}
/// Whether the window should be immediately visible upon creation.
#[must_use]
pub fn visible(mut self, visible: bool) -> Self {
self.window_builder = self.window_builder.visible(visible);
self
}
/// Forces a theme or uses the system settings if None was provided.
///
/// ## Platform-specific
///
/// - **macOS**: Only supported on macOS 10.14+.
#[must_use]
pub fn theme(mut self, theme: Option<Theme>) -> Self {
self.window_builder = self.window_builder.theme(theme);
self
}
/// Whether the window should be transparent. If this is true, writing colors
/// with alpha values different than `1.0` will produce a transparent window.
#[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
#[cfg_attr(
doc_cfg,
doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
)]
#[must_use]
pub fn transparent(mut self, transparent: bool) -> Self {
self.window_builder = self.window_builder.transparent(transparent);
self
}
/// Whether the window should have borders and bars.
#[must_use]
pub fn decorations(mut self, decorations: bool) -> Self {
self.window_builder = self.window_builder.decorations(decorations);
self
}
/// Whether the window should always be on top of other windows.
#[must_use]
pub fn always_on_top(mut self, always_on_top: bool) -> Self {
self.window_builder = self.window_builder.always_on_top(always_on_top);
self
}
/// Whether the window should always be on top of other windows.
#[must_use]
pub fn content_protected(mut self, protected: bool) -> Self {
self.window_builder = self.window_builder.content_protected(protected);
self
}
/// Sets the window icon.
pub fn icon(mut self, icon: Icon) -> crate::Result<Self> {
self.window_builder = self.window_builder.icon(icon.try_into()?)?;
Ok(self)
}
/// Sets whether or not the window icon should be hidden from the taskbar.
///
/// ## Platform-specific
///
/// - **macOS**: Unsupported.
#[must_use]
pub fn skip_taskbar(mut self, skip: bool) -> Self {
self.window_builder = self.window_builder.skip_taskbar(skip);
self
}
/// Sets whether or not the window has shadow.
///
/// ## Platform-specific
///
/// - **Windows:**
/// - `false` has no effect on decorated window, shadows are always ON.
/// - `true` will make ndecorated window have a 1px white border,
/// and on Windows 11, it will have a rounded corners.
/// - **Linux:** Unsupported.
#[must_use]
pub fn shadow(mut self, enable: bool) -> Self {
self.window_builder = self.window_builder.shadow(enable);
self
}
/// Sets a parent to the window to be created.
///
/// A child window has the WS_CHILD style and is confined to the client area of its parent window.
///
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
#[cfg(windows)]
#[must_use]
pub fn parent_window(mut self, parent: HWND) -> Self {
self.window_builder = self.window_builder.parent_window(parent);
self
}
/// Sets a parent to the window to be created.
#[cfg(target_os = "macos")]
#[must_use]
pub fn parent_window(mut self, parent: *mut std::ffi::c_void) -> Self {
self.window_builder = self.window_builder.parent_window(parent);
self
}
/// Set an owner to the window to be created.
///
/// From MSDN:
/// - An owned window is always above its owner in the z-order.
/// - The system automatically destroys an owned window when its owner is destroyed.
/// - An owned window is hidden when its owner is minimized.
///
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
#[cfg(windows)]
#[must_use]
pub fn owner_window(mut self, owner: HWND) -> Self {
self.window_builder = self.window_builder.owner_window(owner);
self
}
/// Sets the [`TitleBarStyle`].
#[cfg(target_os = "macos")]
#[must_use]
pub fn title_bar_style(mut self, style: TitleBarStyle) -> Self {
self.window_builder = self.window_builder.title_bar_style(style);
self
}
/// Hide the window title.
#[cfg(target_os = "macos")]
#[must_use]
pub fn hidden_title(mut self, hidden: bool) -> Self {
self.window_builder = self.window_builder.hidden_title(hidden);
self
}
/// Defines the window [tabbing identifier] for macOS.
///
/// Windows with matching tabbing identifiers will be grouped together.
/// If the tabbing identifier is not set, automatic tabbing will be disabled.
///
/// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
#[cfg(target_os = "macos")]
#[must_use]
pub fn tabbing_identifier(mut self, identifier: &str) -> Self {
self.window_builder = self.window_builder.tabbing_identifier(identifier);
self
}
/// Sets whether clicking an inactive window also clicks through to the webview.
#[must_use]
pub fn accept_first_mouse(mut self, accept: bool) -> Self {
self.webview_attributes.accept_first_mouse = accept;
self
}
}
/// Webview attributes.
impl<'a, R: Runtime> WindowBuilder<'a, R> {
/// Adds the provided JavaScript to a list of scripts that should be run after the global object has been created,
/// but before the HTML document has been parsed and before any other script included by the HTML document is run.
///
/// Since it runs on all top-level document and child frame page navigations,
/// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
///
/// # Examples
///
/// ```rust
/// use tauri::{WindowBuilder, Runtime};
///
/// const INIT_SCRIPT: &str = r#"
/// if (window.location.origin === 'https://tauri.app') {
/// console.log("hello world from js init script");
///
/// window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
/// }
/// "#;
///
/// fn main() {
/// tauri::Builder::default()
/// .setup(|app| {
/// let window = tauri::WindowBuilder::new(app, "label", tauri::WindowUrl::App("index.html".into()))
/// .initialization_script(INIT_SCRIPT)
/// .build()?;
/// Ok(())
/// });
/// }
/// ```
#[must_use]
pub fn initialization_script(mut self, script: &str) -> Self {
self
.webview_attributes
.initialization_scripts
.push(script.to_string());
self
}
/// Set the user agent for the webview
#[must_use]
pub fn user_agent(mut self, user_agent: &str) -> Self {
self.webview_attributes.user_agent = Some(user_agent.to_string());
self
}
/// Set additional arguments for the webview.
///
/// ## Platform-specific
///
/// - **macOS / Linux / Android / iOS**: Unsupported.
///
/// ## Warning
///
/// By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`
/// so if you use this method, you also need to disable these components by yourself if you want.
#[must_use]
pub fn additional_browser_args(mut self, additional_args: &str) -> Self {
self.webview_attributes.additional_browser_args = Some(additional_args.to_string());
self
}
/// Data directory for the webview.
#[must_use]
pub fn data_directory(mut self, data_directory: PathBuf) -> Self {
self
.webview_attributes
.data_directory
.replace(data_directory);
self
}
/// Disables the file drop handler. This is required to use drag and drop APIs on the front end on Windows.
#[must_use]
pub fn disable_file_drop_handler(mut self) -> Self {
self.webview_attributes.file_drop_handler_enabled = false;
self
}
/// Enables clipboard access for the page rendered on **Linux** and **Windows**.
///
/// **macOS** doesn't provide such method and is always enabled by default,
/// but you still need to add menu item accelerators to use shortcuts.
#[must_use]
pub fn enable_clipboard_access(mut self) -> Self {
self.webview_attributes.clipboard = true;
self
}
}
// TODO: expand these docs since this is a pretty important type
/// A webview window managed by Tauri.
///
/// This type also implements [`Manager`] which allows you to manage other windows attached to
/// the same application.
#[default_runtime(crate::Wry, wry)]
#[derive(Debug)]
pub struct Window<R: Runtime> {
/// The webview window created by the runtime.
window: DetachedWindow<EventLoopMessage, R>,
/// The manager to associate this webview window with.
manager: WindowManager<R>,
pub(crate) app_handle: AppHandle<R>,
}
unsafe impl<R: Runtime> raw_window_handle::HasRawWindowHandle for Window<R> {
fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle {
self.window.dispatcher.raw_window_handle().unwrap()
}
}
impl<R: Runtime> Clone for Window<R> {
fn clone(&self) -> Self {
Self {
window: self.window.clone(),
manager: self.manager.clone(),
app_handle: self.app_handle.clone(),
}
}
}
impl<R: Runtime> Hash for Window<R> {
/// Only use the [`Window`]'s label to represent its hash.
fn hash<H: Hasher>(&self, state: &mut H) {
self.window.label.hash(state)
}
}
impl<R: Runtime> Eq for Window<R> {}
impl<R: Runtime> PartialEq for Window<R> {
/// Only use the [`Window`]'s label to compare equality.
fn eq(&self, other: &Self) -> bool {
self.window.label.eq(&other.window.label)
}
}
impl<R: Runtime> Manager<R> for Window<R> {
fn emit_to<S: Serialize + Clone>(
&self,
label: &str,
event: &str,
payload: S,
) -> crate::Result<()> {
self
.manager()
.emit_filter(event, Some(self.label()), payload, |w| label == w.label())
}
fn emit_all<S: Serialize + Clone>(&self, event: &str, payload: S) -> crate::Result<()> {
self
.manager()
.emit_filter(event, Some(self.label()), payload, |_| true)
}
}
impl<R: Runtime> ManagerBase<R> for Window<R> {
fn manager(&self) -> &WindowManager<R> {
&self.manager
}
fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
RuntimeOrDispatch::Dispatch(self.dispatcher())
}
fn managed_app_handle(&self) -> AppHandle<R> {
self.app_handle.clone()
}
}
impl<'de, R: Runtime> CommandArg<'de, R> for Window<R> {
/// Grabs the [`Window`] from the [`CommandItem`]. This will never fail.
fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
Ok(command.message.window())
}
}
/// The platform webview handle. Accessed with [`Window#method.with_webview`];
#[cfg(feature = "wry")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "wry")))]
pub struct PlatformWebview(tauri_runtime_wry::Webview);
#[cfg(feature = "wry")]
impl PlatformWebview {
/// Returns [`webkit2gtk::WebView`] handle.
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
#[cfg_attr(
doc_cfg,
doc(cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))
)]
pub fn inner(&self) -> std::rc::Rc<webkit2gtk::WebView> {
self.0.clone()
}
/// Returns the WebView2 controller.
#[cfg(windows)]
#[cfg_attr(doc_cfg, doc(cfg(windows)))]
pub fn controller(
&self,
) -> webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Controller {
self.0.controller.clone()
}
/// Returns the [WKWebView] handle.
///
/// [WKWebView]: https://developer.apple.com/documentation/webkit/wkwebview
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[cfg_attr(doc_cfg, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
pub fn inner(&self) -> cocoa::base::id {
self.0.webview
}
/// Returns WKWebView [controller] handle.
///
/// [controller]: https://developer.apple.com/documentation/webkit/wkusercontentcontroller
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[cfg_attr(doc_cfg, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
pub fn controller(&self) -> cocoa::base::id {
self.0.manager
}
/// Returns [NSWindow] associated with the WKWebView webview.
///
/// [NSWindow]: https://developer.apple.com/documentation/appkit/nswindow
#[cfg(target_os = "macos")]
#[cfg_attr(doc_cfg, doc(cfg(target_os = "macos")))]
pub fn ns_window(&self) -> cocoa::base::id {
self.0.ns_window
}
/// Returns [UIViewController] used by the WKWebView webview NSWindow.
///
/// [UIViewController]: https://developer.apple.com/documentation/uikit/uiviewcontroller
#[cfg(target_os = "ios")]
#[cfg_attr(doc_cfg, doc(cfg(target_os = "ios")))]
pub fn view_controller(&self) -> cocoa::base::id {
self.0.view_controller
}
/// Returns handle for JNI execution.
#[cfg(target_os = "android")]
pub fn jni_handle(&self) -> tauri_runtime_wry::wry::webview::JniHandle {
self.0
}
}
/// Base window functions.
impl<R: Runtime> Window<R> {
/// Create a new window that is attached to the manager.
pub(crate) fn new(
manager: WindowManager<R>,
window: DetachedWindow<EventLoopMessage, R>,
app_handle: AppHandle<R>,
) -> Self {
Self {
window,
manager,
app_handle,
}
}
/// Initializes a webview window builder with the given window label and URL to load on the webview.
///
/// Data URLs are only supported with the `window-data-url` feature flag.
pub fn builder<'a, M: Manager<R>, L: Into<String>>(
manager: &'a M,
label: L,
url: WindowUrl,
) -> WindowBuilder<'a, R> {
WindowBuilder::<'a, R>::new(manager, label.into(), url)
}
pub(crate) fn invoke_responder(&self) -> Arc<InvokeResponder<R>> {
self.manager.invoke_responder()
}
/// The current window's dispatcher.
pub(crate) fn dispatcher(&self) -> R::Dispatcher {
self.window.dispatcher.clone()
}
/// Runs the given closure on the main thread.
pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
self
.window
.dispatcher
.run_on_main_thread(f)
.map_err(Into::into)
}
/// The label of this window.
pub fn label(&self) -> &str {
&self.window.label
}
/// Registers a window event listener.
pub fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) {
self
.window
.dispatcher
.on_window_event(move |event| f(&event.clone().into()));
}
/// Registers a menu event listener.
pub fn on_menu_event<F: Fn(MenuEvent) + Send + 'static>(&self, f: F) -> uuid::Uuid {
let menu_ids = self.window.menu_ids.clone();
self.window.dispatcher.on_menu_event(move |event| {
let id = menu_ids
.lock()
.unwrap()
.get(&event.menu_item_id)
.unwrap()
.clone();
f(MenuEvent { menu_item_id: id })
})
}
/// Executes a closure, providing it with the webview handle that is specific to the current platform.
///
/// The closure is executed on the main thread.
///
/// # Examples
///
/// ```rust,no_run
/// #[cfg(target_os = "macos")]
/// #[macro_use]
/// extern crate objc;
/// use tauri::Manager;
///
/// fn main() {
/// tauri::Builder::default()
/// .setup(|app| {
/// let main_window = app.get_window("main").unwrap();
/// main_window.with_webview(|webview| {
/// #[cfg(target_os = "linux")]
/// {
/// // see https://docs.rs/webkit2gtk/0.18.2/webkit2gtk/struct.WebView.html
/// // and https://docs.rs/webkit2gtk/0.18.2/webkit2gtk/trait.WebViewExt.html
/// use webkit2gtk::traits::WebViewExt;
/// webview.inner().set_zoom_level(4.);
/// }
///
/// #[cfg(windows)]
/// unsafe {
/// // see https://docs.rs/webview2-com/0.19.1/webview2_com/Microsoft/Web/WebView2/Win32/struct.ICoreWebView2Controller.html
/// webview.controller().SetZoomFactor(4.).unwrap();
/// }
///
/// #[cfg(target_os = "macos")]
/// unsafe {
/// let () = msg_send![webview.inner(), setPageZoom: 4.];
/// let () = msg_send![webview.controller(), removeAllUserScripts];
/// let bg_color: cocoa::base::id = msg_send![class!(NSColor), colorWithDeviceRed:0.5 green:0.2 blue:0.4 alpha:1.];
/// let () = msg_send![webview.ns_window(), setBackgroundColor: bg_color];
/// }
///
/// #[cfg(target_os = "android")]
/// {
/// use jni::objects::JValue;
/// webview.jni_handle().exec(|env, _, webview| {
/// env.call_method(webview, "zoomBy", "(F)V", &[JValue::Float(4.)]).unwrap();
/// })
/// }
/// });
/// Ok(())
/// });
/// }
/// ```
#[cfg(all(feature = "wry"))]
#[cfg_attr(doc_cfg, doc(all(feature = "wry")))]
pub fn with_webview<F: FnOnce(PlatformWebview) + Send + 'static>(
&self,
f: F,
) -> crate::Result<()> {
self
.window
.dispatcher
.with_webview(|w| f(PlatformWebview(*w.downcast().unwrap())))
.map_err(Into::into)
}
}
/// Window getters.