-
-
Notifications
You must be signed in to change notification settings - Fork 315
/
Copy pathlib.rs
2181 lines (1992 loc) · 81.8 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 2020-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! <p align="center"><img height="100" src="https://raw.githubusercontent.com/tauri-apps/wry/refs/heads/dev/.github/splash.png" alt="WRY Webview Rendering library" /></p>
//!
//! [](https://crates.io/crates/wry) [](https://docs.rs/wry/)
//! [](https://opencollective.com/tauri)
//! [](https://discord.gg/SpmNs4S)
//! [](https://tauri.app)
//! [](https://good-labs.github.io/greater-good-affirmation)
//! [](https://opencollective.com/tauri)
//!
//! Wry is a Cross-platform WebView rendering library.
//!
//! The webview requires a running event loop and a window type that implements [`HasWindowHandle`],
//! or a gtk container widget if you need to support X11 and Wayland.
//! You can use a windowing library like [`tao`] or [`winit`].
//!
//! ## Examples
//!
//! This example leverages the [`HasWindowHandle`] and supports Windows, macOS, iOS, Android and Linux (X11 Only).
//! See the following example using [`winit`]:
//!
//! ```no_run
//! # use wry::{WebViewBuilder, raw_window_handle};
//! # use winit::{application::ApplicationHandler, event::WindowEvent, event_loop::{ActiveEventLoop, EventLoop}, window::{Window, WindowId}};
//! #[derive(Default)]
//! struct App {
//! window: Option<Window>,
//! webview: Option<wry::WebView>,
//! }
//!
//! impl ApplicationHandler for App {
//! fn resumed(&mut self, event_loop: &ActiveEventLoop) {
//! let window = event_loop.create_window(Window::default_attributes()).unwrap();
//! let webview = WebViewBuilder::new()
//! .with_url("https://tauri.app")
//! .build(&window)
//! .unwrap();
//!
//! self.window = Some(window);
//! self.webview = Some(webview);
//! }
//!
//! fn window_event(&mut self, _event_loop: &ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {}
//! }
//!
//! let event_loop = EventLoop::new().unwrap();
//! let mut app = App::default();
//! event_loop.run_app(&mut app).unwrap();
//! ```
//!
//! If you also want to support Wayland too, then we recommend you use [`WebViewBuilderExtUnix::new_gtk`] on Linux.
//! See the following example using [`tao`]:
//!
//! ```no_run
//! # use wry::WebViewBuilder;
//! # use tao::{window::WindowBuilder, event_loop::EventLoop};
//! # #[cfg(target_os = "linux")]
//! # use tao::platform::unix::WindowExtUnix;
//! # #[cfg(target_os = "linux")]
//! # use wry::WebViewBuilderExtUnix;
//! let event_loop = EventLoop::new();
//! let window = WindowBuilder::new().build(&event_loop).unwrap();
//!
//! let builder = WebViewBuilder::new().with_url("https://tauri.app");
//!
//! #[cfg(not(target_os = "linux"))]
//! let webview = builder.build(&window).unwrap();
//! #[cfg(target_os = "linux")]
//! let webview = builder.build_gtk(window.gtk_window()).unwrap();
//! ```
//!
//! ## Child webviews
//!
//! You can use [`WebView::new_as_child`] or [`WebViewBuilder::new_as_child`] to create the webview as a child inside another window. This is supported on
//! macOS, Windows and Linux (X11 Only).
//!
//! ```no_run
//! # use wry::{WebViewBuilder, raw_window_handle, Rect, dpi::*};
//! # use winit::{application::ApplicationHandler, event::WindowEvent, event_loop::{ActiveEventLoop, EventLoop}, window::{Window, WindowId}};
//! #[derive(Default)]
//! struct App {
//! window: Option<Window>,
//! webview: Option<wry::WebView>,
//! }
//!
//! impl ApplicationHandler for App {
//! fn resumed(&mut self, event_loop: &ActiveEventLoop) {
//! let window = event_loop.create_window(Window::default_attributes()).unwrap();
//! let webview = WebViewBuilder::new()
//! .with_url("https://tauri.app")
//! .with_bounds(Rect {
//! position: LogicalPosition::new(100, 100).into(),
//! size: LogicalSize::new(200, 200).into(),
//! })
//! .build_as_child(&window)
//! .unwrap();
//!
//! self.window = Some(window);
//! self.webview = Some(webview);
//! }
//!
//! fn window_event(&mut self, _event_loop: &ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {}
//! }
//!
//! let event_loop = EventLoop::new().unwrap();
//! let mut app = App::default();
//! event_loop.run_app(&mut app).unwrap();
//! ```
//!
//! If you want to support X11 and Wayland at the same time, we recommend using
//! [`WebViewExtUnix::new_gtk`] or [`WebViewBuilderExtUnix::new_gtk`] with [`gtk::Fixed`].
//!
//! ```no_run
//! # use wry::{WebViewBuilder, raw_window_handle, Rect, dpi::*};
//! # use tao::{window::WindowBuilder, event_loop::EventLoop};
//! # #[cfg(target_os = "linux")]
//! # use wry::WebViewBuilderExtUnix;
//! # #[cfg(target_os = "linux")]
//! # use tao::platform::unix::WindowExtUnix;
//! let event_loop = EventLoop::new();
//! let window = WindowBuilder::new().build(&event_loop).unwrap();
//!
//! let builder = WebViewBuilder::new()
//! .with_url("https://tauri.app")
//! .with_bounds(Rect {
//! position: LogicalPosition::new(100, 100).into(),
//! size: LogicalSize::new(200, 200).into(),
//! });
//!
//! #[cfg(not(target_os = "linux"))]
//! let webview = builder.build_as_child(&window).unwrap();
//! #[cfg(target_os = "linux")]
//! let webview = {
//! # use gtk::prelude::*;
//! let vbox = window.default_vbox().unwrap(); // tao adds a gtk::Box by default
//! let fixed = gtk::Fixed::new();
//! fixed.show_all();
//! vbox.pack_start(&fixed, true, true, 0);
//! builder.build_gtk(&fixed).unwrap()
//! };
//! ```
//!
//! ## Platform Considerations
//!
//! Here is the underlying web engine each platform uses, and some dependencies you might need to install.
//!
//! ### Linux
//!
//! [WebKitGTK](https://webkitgtk.org/) is used to provide webviews on Linux which requires GTK,
//! so if the windowing library doesn't support GTK (as in [`winit`])
//! you'll need to call [`gtk::init`] before creating the webview and then call [`gtk::main_iteration_do`] alongside
//! your windowing library event loop.
//!
//! ```no_run
//! # use wry::{WebView, WebViewBuilder};
//! # use winit::{application::ApplicationHandler, event::WindowEvent, event_loop::{ActiveEventLoop, EventLoop}, window::{Window, WindowId}};
//! #[derive(Default)]
//! struct App {
//! webview_window: Option<(Window, WebView)>,
//! }
//!
//! impl ApplicationHandler for App {
//! fn resumed(&mut self, event_loop: &ActiveEventLoop) {
//! let window = event_loop.create_window(Window::default_attributes()).unwrap();
//! let webview = WebViewBuilder::new()
//! .with_url("https://tauri.app")
//! .build(&window)
//! .unwrap();
//!
//! self.webview_window = Some((window, webview));
//! }
//!
//! fn window_event(&mut self, _event_loop: &ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {}
//!
//! // Advance GTK event loop <!----- IMPORTANT
//! fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
//! #[cfg(target_os = "linux")]
//! while gtk::events_pending() {
//! gtk::main_iteration_do(false);
//! }
//! }
//! }
//!
//! let event_loop = EventLoop::new().unwrap();
//! let mut app = App::default();
//! event_loop.run_app(&mut app).unwrap();
//! ```
//!
//! #### Linux Dependencies
//!
//! ##### Arch Linux / Manjaro:
//!
//! ```bash
//! sudo pacman -S webkit2gtk-4.1
//! ```
//!
//! ##### Debian / Ubuntu:
//!
//! ```bash
//! sudo apt install libwebkit2gtk-4.1-dev
//! ```
//!
//! ##### Fedora
//!
//! ```bash
//! sudo dnf install gtk3-devel webkit2gtk4.1-devel
//! ```
//!
//! ##### Nix & NixOS
//!
//! ```nix
//! # shell.nix
//!
//! let
//! # Unstable Channel | Rolling Release
//! pkgs = import (fetchTarball("channel:nixpkgs-unstable")) { };
//! packages = with pkgs; [
//! pkg-config
//! webkitgtk_4_1
//! ];
//! in
//! pkgs.mkShell {
//! buildInputs = packages;
//! }
//! ```
//!
//! ```sh
//! nix-shell shell.nix
//! ```
//!
//! ##### GUIX
//!
//! ```scheme
//! ;; manifest.scm
//!
//! (specifications->manifest
//! '("pkg-config" ; Helper tool used when compiling
//! "webkitgtk" ; Web content engine fot GTK+
//! ))
//! ```
//!
//! ```bash
//! guix shell -m manifest.scm
//! ```
//!
//! ### macOS
//!
//! WebKit is native on macOS so everything should be fine.
//!
//! If you are cross-compiling for macOS using [osxcross](https://github.com/tpoechtrager/osxcross) and encounter a runtime panic like `Class with name WKWebViewConfiguration could not be found` it's possible that `WebKit.framework` has not been linked correctly, to fix this set the `RUSTFLAGS` environment variable:
//!
//! ```bash
//! RUSTFLAGS="-l framework=WebKit" cargo build --target=x86_64-apple-darwin --release
//! ```
//! ### Windows
//!
//! WebView2 provided by Microsoft Edge Chromium is used. So wry supports Windows 7, 8, 10 and 11.
//!
//! ### Android
//!
//! In order for `wry` to be able to create webviews on Android, there is a few requirements that your application needs to uphold:
//! 1. You need to set a few environment variables that will be used to generate the necessary kotlin
//! files that you need to include in your Android application for wry to function properly.
//! - `WRY_ANDROID_PACKAGE`: which is the reversed domain name of your android project and the app name in snake_case, for example, `com.wry.example.wry_app`
//! - `WRY_ANDROID_LIBRARY`: for example, if your cargo project has a lib name `wry_app`, it will generate `libwry_app.so` so you se this env var to `wry_app`
//! - `WRY_ANDROID_KOTLIN_FILES_OUT_DIR`: for example, `path/to/app/src/main/kotlin/com/wry/example`
//! 2. Your main Android Activity needs to inherit `AppCompatActivity`, preferably it should use the generated `WryActivity` or inherit it.
//! 3. Your Rust app needs to call `wry::android_setup` function to setup the necessary logic to be able to create webviews later on.
//! 4. Your Rust app needs to call `wry::android_binding!` macro to setup the JNI functions that will be called by `WryActivity` and various other places.
//!
//! It is recommended to use [`tao`](https://docs.rs/tao/latest/tao/) crate as it provides maximum compatibility with `wry`
//!
//! ```
//! #[cfg(target_os = "android")]
//! {
//! tao::android_binding!(
//! com_example,
//! wry_app,
//! WryActivity,
//! wry::android_setup, // pass the wry::android_setup function to tao which will invoke when the event loop is created
//! _start_app
//! );
//! wry::android_binding!(com_example, ttt);
//! }
//! ```
//!
//! If this feels overwhelming, you can just use the preconfigured template from [`cargo-mobile2`](https://github.com/tauri-apps/cargo-mobile2).
//!
//! For more inforamtion, checkout [MOBILE.md](https://github.com/tauri-apps/wry/blob/dev/MOBILE.md).
//!
//! ## Feature flags
//!
//! Wry uses a set of feature flags to toggle several advanced features.
//!
//! - `os-webview` (default): Enables the default WebView framework on the platform. This must be enabled
//! for the crate to work. This feature was added in preparation of other ports like cef and servo.
//! - `protocol` (default): Enables [`WebViewBuilder::with_custom_protocol`] to define custom URL scheme for handling tasks like
//! loading assets.
//! - `drag-drop` (default): Enables [`WebViewBuilder::with_drag_drop_handler`] to control the behaviour when there are files
//! interacting with the window.
//! - `devtools`: Enables devtools on release builds. Devtools are always enabled in debug builds.
//! On **macOS**, enabling devtools, requires calling private apis so you should not enable this flag in release
//! build if your app needs to publish to App Store.
//! - `transparent`: Transparent background on **macOS** requires calling private functions.
//! Avoid this in release build if your app needs to publish to App Store.
//! - `fullscreen`: Fullscreen video and other media on **macOS** requires calling private functions.
//! Avoid this in release build if your app needs to publish to App Store.
//! libraries and prevent from building documentation on doc.rs fails.
//! - `linux-body`: Enables body support of custom protocol request on Linux. Requires
//! webkit2gtk v2.40 or above.
//! - `tracing`: enables [`tracing`] for `evaluate_script`, `ipc_handler` and `custom_protocols.
//!
//! ## Partners
//!
//! <table>
//! <tbody>
//! <tr>
//! <td align="center" valign="middle">
//! <a href="https://crabnebula.dev" target="_blank">
//! <img src=".github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
//! </a>
//! </td>
//! </tr>
//! </tbody>
//! </table>
//!
//! For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
//!
//! ## License
//!
//! Apache-2.0/MIT
//!
//! [`tao`]: https://docs.rs/tao
//! [`winit`]: https://docs.rs/winit
//! [`tracing`]: https://docs.rs/tracing
#![allow(clippy::new_without_default)]
#![allow(clippy::default_constructed_unit_structs)]
#![allow(clippy::type_complexity)]
#![cfg_attr(docsrs, feature(doc_cfg))]
// #[cfg(any(target_os = "macos", target_os = "ios"))]
// #[macro_use]
// extern crate objc;
mod error;
mod proxy;
#[cfg(any(target_os = "macos", target_os = "android", target_os = "ios"))]
mod util;
mod web_context;
#[cfg(target_os = "android")]
pub(crate) mod android;
#[cfg(target_os = "android")]
pub use crate::android::android_setup;
#[cfg(target_os = "android")]
pub mod prelude {
pub use crate::android::{binding::*, dispatch, find_class, Context};
pub use tao_macros::{android_fn, generate_package_name};
}
#[cfg(target_os = "android")]
pub use android::JniHandle;
#[cfg(target_os = "android")]
use android::*;
#[cfg(gtk)]
pub(crate) mod webkitgtk;
/// Re-exported [raw-window-handle](https://docs.rs/raw-window-handle/latest/raw_window_handle/) crate.
pub use raw_window_handle;
use raw_window_handle::HasWindowHandle;
#[cfg(gtk)]
use webkitgtk::*;
#[cfg(any(target_os = "macos", target_os = "ios"))]
use objc2::rc::Retained;
#[cfg(target_os = "macos")]
use objc2_app_kit::NSWindow;
#[cfg(any(target_os = "macos", target_os = "ios"))]
use objc2_web_kit::WKUserContentController;
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) mod wkwebview;
#[cfg(any(target_os = "macos", target_os = "ios"))]
use wkwebview::*;
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub use wkwebview::{PrintMargin, PrintOptions, WryWebView};
#[cfg(target_os = "windows")]
pub(crate) mod webview2;
#[cfg(target_os = "windows")]
pub use self::webview2::ScrollBarStyle;
#[cfg(target_os = "windows")]
use self::webview2::*;
#[cfg(target_os = "windows")]
use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Controller;
use std::{borrow::Cow, collections::HashMap, path::PathBuf, rc::Rc};
use http::{Request, Response};
pub use cookie;
pub use dpi;
pub use error::*;
pub use http;
pub use proxy::{ProxyConfig, ProxyEndpoint};
pub use web_context::WebContext;
/// A rectangular region.
#[derive(Clone, Copy, Debug)]
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(),
}
}
}
/// Resolves a custom protocol [`Request`] asynchronously.
///
/// See [`WebViewBuilder::with_asynchronous_custom_protocol`] for more information.
pub struct RequestAsyncResponder {
pub(crate) responder: Box<dyn FnOnce(Response<Cow<'static, [u8]>>)>,
}
// 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 for a webview
pub type WebViewId<'a> = &'a str;
pub struct WebViewAttributes<'a> {
/// An id that will be passed when this webview makes requests in certain callbacks.
pub id: Option<WebViewId<'a>>,
/// Web context to be shared with this webview.
pub context: Option<&'a mut WebContext>,
/// Whether the WebView should have a custom user-agent.
pub user_agent: Option<String>,
/// Whether the WebView window should be visible.
pub visible: bool,
/// Whether the WebView should be transparent.
///
/// ## Platform-specific:
///
/// **Windows 7**: Not supported.
pub transparent: bool,
/// Specify the webview background color. This will be ignored if `transparent` is set to `true`.
///
/// The color uses the RGBA format.
///
/// ## Platform-specific:
///
/// - **macOS / iOS**: Not implemented.
/// - **Windows**:
/// - On Windows 7, transparency is not supported and the alpha value will be ignored.
/// - On Windows higher than 7: translucent colors are not supported so any alpha value other than `0` will be replaced by `255`
pub background_color: Option<RGBA>,
/// Whether load the provided URL to [`WebView`].
///
/// ## Note
///
/// Data URLs are not supported, use [`html`](Self::html) option instead.
pub url: Option<String>,
/// Headers used when loading the requested [`url`](Self::url).
pub headers: Option<http::HeaderMap>,
/// Whether page zooming by hotkeys is enabled
///
/// ## Platform-specific
///
/// **macOS / Linux / Android / iOS**: Unsupported
pub zoom_hotkeys_enabled: bool,
/// Whether load the provided html string to [`WebView`].
/// This will be ignored if the `url` is provided.
///
/// # Warning
///
/// The Page loaded from html string will have `null` origin.
///
/// ## PLatform-specific:
///
/// - **Windows:** the string can not be larger than 2 MB (2 * 1024 * 1024 bytes) in total size
pub html: Option<String>,
/// A list of initialization javascript scripts to run when loading new pages.
/// When webview load a new page, this initialization code will be executed.
/// It is guaranteed that code is executed before `window.onload`.
///
/// Second parameter represents if script should be added to main frame only or sub frames also.
/// `true` for main frame only, `false` for sub frames.
///
/// ## Platform-specific
///
/// - **Android:** The Android WebView does not provide an API for initialization scripts,
/// so we prepend them to each HTML head. They are only implemented on custom protocol URLs.
pub initialization_scripts: Vec<(String, bool)>,
/// A list of custom loading protocols with pairs of scheme uri string and a handling
/// closure.
///
/// The closure takes an Id ([WebViewId]), [Request] and [RequestAsyncResponder] as arguments and returns a [Response].
///
/// # Note
///
/// If using a shared [WebContext], make sure custom protocols were not already registered on that web context on Linux.
///
/// # Warning
///
/// Pages loaded from custom protocol will have different Origin on different platforms. And
/// servers which enforce CORS will need to add exact same Origin header in `Access-Control-Allow-Origin`
/// if you wish to send requests with native `fetch` and `XmlHttpRequest` APIs. Here are the
/// different Origin headers across platforms:
///
/// - macOS, iOS and Linux: `<scheme_name>://<path>` (so it will be `wry://path/to/page/`).
/// - Windows and Android: `http://<scheme_name>.<path>` by default (so it will be `http://wry.path/to/page). To use `https` instead of `http`, use [`WebViewBuilderExtWindows::with_https_scheme`] and [`WebViewBuilderExtAndroid::with_https_scheme`].
///
/// # Reading assets on mobile
///
/// - Android: Android has `assets` and `resource` path finder to
/// locate your files in those directories. For more information, see [Loading in-app content](https://developer.android.com/guide/webapps/load-local-content) page.
/// - iOS: To get the path of your assets, you can call [`CFBundle::resources_path`](https://docs.rs/core-foundation/latest/core_foundation/bundle/struct.CFBundle.html#method.resources_path). So url like `wry://assets/index.html` could get the html file in assets directory.
pub custom_protocols:
HashMap<String, Box<dyn Fn(WebViewId, Request<Vec<u8>>, RequestAsyncResponder)>>,
/// The IPC handler to receive the message from Javascript on webview
/// using `window.ipc.postMessage("insert_message_here")` to host Rust code.
pub ipc_handler: Option<Box<dyn Fn(Request<String>)>>,
/// A handler closure to process incoming [`DragDropEvent`] of the webview.
///
/// # Blocking OS Default Behavior
/// Return `true` in the callback to block the OS' default behavior.
///
/// Note, that if you do block this behavior, it won't be possible to drop files on `<input type="file">` forms.
/// Also note, that it's not possible to manually set the value of a `<input type="file">` via JavaScript for security reasons.
#[cfg(feature = "drag-drop")]
#[cfg_attr(docsrs, doc(cfg(feature = "drag-drop")))]
pub drag_drop_handler: Option<Box<dyn Fn(DragDropEvent) -> bool>>,
#[cfg(not(feature = "drag-drop"))]
drag_drop_handler: Option<Box<dyn Fn(DragDropEvent) -> bool>>,
/// A navigation handler to decide if incoming url is allowed to navigate.
///
/// The closure take a `String` parameter as url and returns a `bool` to determine whether the navigation should happen.
/// `true` allows to navigate and `false` does not.
pub navigation_handler: Option<Box<dyn Fn(String) -> bool>>,
/// A download started handler to manage incoming downloads.
///
/// The closure takes two parameters, the first is a `String` representing the url being downloaded from and and the
/// second is a mutable `PathBuf` reference that (possibly) represents where the file will be downloaded to. The latter
/// parameter can be used to set the download location by assigning a new path to it, the assigned path _must_ be
/// absolute. The closure returns a `bool` to allow or deny the download.
pub download_started_handler: Option<Box<dyn FnMut(String, &mut PathBuf) -> bool + 'static>>,
/// A download completion handler to manage downloads that have finished.
///
/// The closure is fired when the download completes, whether it was successful or not.
/// The closure takes a `String` representing the URL of the original download request, an `Option<PathBuf>`
/// potentially representing the filesystem path the file was downloaded to, and a `bool` indicating if the download
/// succeeded. A value of `None` being passed instead of a `PathBuf` does not necessarily indicate that the download
/// did not succeed, and may instead indicate some other failure, always check the third parameter if you need to
/// know if the download succeeded.
///
/// ## Platform-specific:
///
/// - **macOS**: The second parameter indicating the path the file was saved to, is always empty,
/// due to API limitations.
pub download_completed_handler: Option<Rc<dyn Fn(String, Option<PathBuf>, bool) + 'static>>,
/// A new window handler to decide if incoming url is allowed to open in a new window.
///
/// The closure take a `String` parameter as url and return `bool` to determine whether the window should open.
/// `true` allows to open and `false` does not.
pub new_window_req_handler: Option<Box<dyn Fn(String) -> bool>>,
/// Enables clipboard access for the page rendered on **Linux** and **Windows**.
///
/// macOS doesn't provide such method and is always enabled by default. But your app will still need to add menu
/// item accelerators to use the clipboard shortcuts.
pub clipboard: bool,
/// Enable web inspector which is usually called browser devtools.
///
/// Note this only enables devtools to the webview. To open it, you can call
/// [`WebView::open_devtools`], or right click the page and open it from the context menu.
///
/// ## Platform-specific
///
/// - macOS: This will call private functions on **macOS**. It is enabled in **debug** builds,
/// but requires `devtools` feature flag to actually enable it in **release** builds.
/// - Android: Open `chrome://inspect/#devices` in Chrome to get the devtools window. Wry's `WebView` devtools API isn't supported on Android.
/// - iOS: Open Safari > Develop > [Your Device Name] > [Your WebView] to get the devtools window.
pub devtools: bool,
/// Whether clicking an inactive window also clicks through to the webview. Default is `false`.
///
/// ## Platform-specific
///
/// This configuration only impacts macOS.
pub accept_first_mouse: bool,
/// Indicates whether horizontal swipe gestures trigger backward and forward page navigation.
///
/// ## Platform-specific:
///
/// - Windows: Setting to `false` does nothing on WebView2 Runtime version before 92.0.902.0,
/// see https://learn.microsoft.com/en-us/microsoft-edge/webview2/release-notes/archive?tabs=dotnetcsharp#10902-prerelease
///
/// - **Android / iOS:** Unsupported.
pub back_forward_navigation_gestures: bool,
/// Set a handler closure to process the change of the webview's document title.
pub document_title_changed_handler: Option<Box<dyn Fn(String)>>,
/// Run the WebView with incognito mode. Note that WebContext will be ingored if incognito is
/// enabled.
///
/// ## Platform-specific:
///
/// - Windows: Requires WebView2 Runtime version 101.0.1210.39 or higher, does nothing on older versions,
/// see https://learn.microsoft.com/en-us/microsoft-edge/webview2/release-notes/archive?tabs=dotnetcsharp#10121039
/// - **Android:** Unsupported yet.
pub incognito: bool,
/// Whether all media can be played without user interaction.
pub autoplay: bool,
/// Set a handler closure to process page load events.
pub on_page_load_handler: Option<Box<dyn Fn(PageLoadEvent, String)>>,
/// Set a proxy configuration for the webview. Supports HTTP CONNECT and SOCKSv5 proxies
///
/// - **macOS**: Requires macOS 14.0+ and the `mac-proxy` feature flag to be enabled.
/// - **Android / iOS:** Not supported.
pub proxy_config: Option<ProxyConfig>,
/// Whether the webview should be focused when created.
///
/// ## Platform-specific:
///
/// - **macOS / Android / iOS:** Unsupported.
pub focused: bool,
/// The webview bounds. Defaults to `x: 0, y: 0, width: 200, height: 200`.
/// This is only effective if the webview was created by [`WebView::new_as_child`] or [`WebViewBuilder::new_as_child`]
/// or on Linux, if was created by [`WebViewExtUnix::new_gtk`] or [`WebViewBuilderExtUnix::new_gtk`] with [`gtk::Fixed`].
pub bounds: Option<Rect>,
/// Whether background throttling should be disabled.
///
/// By default, browsers throttle timers and even unload the whole tab (view) to free resources after roughly 5 minutes when
/// a view became minimized or hidden. This will permanently suspend all tasks until the documents visibility state
/// changes back from hidden to visible by bringing the view back to the foreground.
///
/// ## Platform-specific
///
/// - **Linux / Windows / Android**: Unsupported. Workarounds like a pending WebLock transaction might suffice.
/// - **iOS**: Supported since version 17.0+.
/// - **macOS**: Supported since version 14.0+.
///
/// see https://github.com/tauri-apps/tauri/issues/5250#issuecomment-2569380578
pub background_throttling: Option<BackgroundThrottlingPolicy>,
}
impl Default for WebViewAttributes<'_> {
fn default() -> Self {
Self {
id: Default::default(),
context: None,
user_agent: None,
visible: true,
transparent: false,
background_color: None,
url: None,
headers: None,
html: None,
initialization_scripts: Default::default(),
custom_protocols: Default::default(),
ipc_handler: None,
drag_drop_handler: None,
navigation_handler: None,
download_started_handler: None,
download_completed_handler: None,
new_window_req_handler: None,
clipboard: false,
#[cfg(debug_assertions)]
devtools: true,
#[cfg(not(debug_assertions))]
devtools: false,
zoom_hotkeys_enabled: false,
accept_first_mouse: false,
back_forward_navigation_gestures: false,
document_title_changed_handler: None,
incognito: false,
autoplay: true,
on_page_load_handler: None,
proxy_config: None,
focused: true,
bounds: Some(Rect {
position: dpi::LogicalPosition::new(0, 0).into(),
size: dpi::LogicalSize::new(200, 200).into(),
}),
background_throttling: None,
}
}
}
struct WebviewBuilderParts<'a> {
attrs: WebViewAttributes<'a>,
platform_specific: PlatformSpecificWebViewAttributes,
}
/// Builder type of [`WebView`].
///
/// [`WebViewBuilder`] / [`WebView`] are the basic building blocks to construct WebView contents and
/// scripts for those who prefer to control fine grained window creation and event handling.
/// [`WebViewBuilder`] provides ability to setup initialization before web engine starts.
pub struct WebViewBuilder<'a> {
inner: Result<WebviewBuilderParts<'a>>,
}
impl<'a> WebViewBuilder<'a> {
/// Create a new [`WebViewBuilder`].
pub fn new() -> Self {
Self {
inner: Ok(WebviewBuilderParts {
attrs: WebViewAttributes::default(),
#[allow(clippy::default_constructed_unit_structs)]
platform_specific: PlatformSpecificWebViewAttributes::default(),
}),
}
}
/// Create a new [`WebViewBuilder`] with a web context that can be shared with multiple [`WebView`]s.
pub fn with_web_context(web_context: &'a mut WebContext) -> Self {
let mut attrs = WebViewAttributes::default();
attrs.context = Some(web_context);
Self {
inner: Ok(WebviewBuilderParts {
attrs,
#[allow(clippy::default_constructed_unit_structs)]
platform_specific: PlatformSpecificWebViewAttributes::default(),
}),
}
}
/// Create a new [`WebViewBuilder`] with the given [`WebViewAttributes`]
pub fn with_attributes(attrs: WebViewAttributes<'a>) -> Self {
Self {
inner: Ok(WebviewBuilderParts {
attrs,
#[allow(clippy::default_constructed_unit_structs)]
platform_specific: PlatformSpecificWebViewAttributes::default(),
}),
}
}
fn and_then<F>(self, func: F) -> Self
where
F: FnOnce(WebviewBuilderParts<'a>) -> Result<WebviewBuilderParts<'a>>,
{
Self {
inner: self.inner.and_then(func),
}
}
/// Set an id that will be passed when this webview makes requests in certain callbacks.
pub fn with_id(self, id: WebViewId<'a>) -> Self {
self.and_then(|mut b| {
b.attrs.id = Some(id);
Ok(b)
})
}
/// Indicates whether horizontal swipe gestures trigger backward and forward page navigation.
///
/// ## Platform-specific:
///
/// - **Android / iOS:** Unsupported.
pub fn with_back_forward_navigation_gestures(self, gesture: bool) -> Self {
self.and_then(|mut b| {
b.attrs.back_forward_navigation_gestures = gesture;
Ok(b)
})
}
/// Sets whether the WebView should be transparent.
///
/// ## Platform-specific:
///
/// **Windows 7**: Not supported.
pub fn with_transparent(self, transparent: bool) -> Self {
self.and_then(|mut b| {
b.attrs.transparent = transparent;
Ok(b)
})
}
/// Specify the webview background color. This will be ignored if `transparent` is set to `true`.
///
/// The color uses the RGBA format.
///
/// ## Platfrom-specific:
///
/// - **macOS / iOS**: Not implemented.
/// - **Windows**:
/// - on Windows 7, transparency is not supported and the alpha value will be ignored.
/// - on Windows higher than 7: translucent colors are not supported so any alpha value other than `0` will be replaced by `255`
pub fn with_background_color(self, background_color: RGBA) -> Self {
self.and_then(|mut b| {
b.attrs.background_color = Some(background_color);
Ok(b)
})
}
/// Sets whether the WebView should be visible or not.
pub fn with_visible(self, visible: bool) -> Self {
self.and_then(|mut b| {
b.attrs.visible = visible;
Ok(b)
})
}
/// Sets whether all media can be played without user interaction.
pub fn with_autoplay(self, autoplay: bool) -> Self {
self.and_then(|mut b| {
b.attrs.autoplay = autoplay;
Ok(b)
})
}
/// Initialize javascript code when loading new pages. When webview load a new page, this
/// initialization code will be executed. It is guaranteed that code is executed before
/// `window.onload`.
///
/// ## Example
/// ```ignore
/// let webview = WebViewBuilder::new()
/// .with_initialization_script("console.log('Running inside main frame only')")
/// .with_url("https://tauri.app")
/// .build(&window)
/// .unwrap();
/// ```
///
/// ## Platform-specific
///
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend them to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
/// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
pub fn with_initialization_script(self, js: &str) -> Self {
self.with_initialization_script_for_main_only(js, true)
}
/// Same as [`with_initialization_script`](Self::with_initialization_script) but with option to inject into main frame only or sub frames.
///
/// ## Example
/// ```ignore
/// let webview = WebViewBuilder::new()
/// .with_initialization_script_for_main_only("console.log('Running inside main frame only')", true)
/// .with_initialization_script_for_main_only("console.log('Running main frame and sub frames')", false)
/// .with_url("https://tauri.app")
/// .build(&window)
/// .unwrap();
/// ```
pub fn with_initialization_script_for_main_only(self, js: &str, main_only: bool) -> Self {
self.and_then(|mut b| {
if !js.is_empty() {
b.attrs
.initialization_scripts
.push((js.to_string(), main_only));
}
Ok(b)
})
}
/// Register custom loading protocols with pairs of scheme uri string and a handling
/// closure.
///
/// The closure takes a [Request] and returns a [Response]
///
/// When registering a custom protocol with the same name, only the last regisered one will be used.
///
/// # Warning
///
/// Pages loaded from custom protocol will have different Origin on different platforms. And
/// servers which enforce CORS will need to add exact same Origin header in `Access-Control-Allow-Origin`
/// if you wish to send requests with native `fetch` and `XmlHttpRequest` APIs. Here are the
/// different Origin headers across platforms:
///
/// - macOS, iOS and Linux: `<scheme_name>://<path>` (so it will be `wry://path/to/page).
/// - Windows and Android: `http://<scheme_name>.<path>` by default (so it will be `http://wry.path/to/page`). To use `https` instead of `http`, use [`WebViewBuilderExtWindows::with_https_scheme`] and [`WebViewBuilderExtAndroid::with_https_scheme`].
///
/// # Reading assets on mobile
///
/// - Android: For loading content from the `assets` folder (which is copied to the Andorid apk) please
/// use the function [`with_asset_loader`] from [`WebViewBuilderExtAndroid`] instead.
/// This function on Android can only be used to serve assets you can embed in the binary or are
/// elsewhere in Android (provided the app has appropriate access), but not from the `assets`
/// folder which lives within the apk. For the cases where this can be used, it works the same as in macOS and Linux.
/// - iOS: To get the path of your assets, you can call [`CFBundle::resources_path`](https://docs.rs/core-foundation/latest/core_foundation/bundle/struct.CFBundle.html#method.resources_path). So url like `wry://assets/index.html` could get the html file in assets directory.
#[cfg(feature = "protocol")]
pub fn with_custom_protocol<F>(self, name: String, handler: F) -> Self
where
F: Fn(WebViewId, Request<Vec<u8>>) -> Response<Cow<'static, [u8]>> + 'static,
{
self.and_then(|mut b| {
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
if let Some(context) = &mut b.attrs.context {
context.register_custom_protocol(name.clone())?;
}
if b.attrs.custom_protocols.iter().any(|(n, _)| n == &name) {
return Err(Error::DuplicateCustomProtocol(name));
}
b.attrs.custom_protocols.insert(
name,
Box::new(move |id, request, responder| {
let http_response = handler(id, request);
responder.respond(http_response);
}),
);
Ok(b)
})
}
/// Same as [`Self::with_custom_protocol`] but with an asynchronous responder.
///
/// When registering a custom protocol with the same name, only the last regisered one will be used.
///
/// # Examples
///
/// ```no_run
/// use wry::{WebViewBuilder, raw_window_handle};
/// WebViewBuilder::new()
/// .with_asynchronous_custom_protocol("wry".into(), |_webview_id, request, responder| {
/// // here you can use a tokio task, thread pool or anything
/// // to do heavy computation to resolve your request
/// // e.g. downloading files, opening the camera...
/// std::thread::spawn(move || {
/// std::thread::sleep(std::time::Duration::from_secs(2));
/// responder.respond(http::Response::builder().body(Vec::new()).unwrap());
/// });
/// });
/// ```
#[cfg(feature = "protocol")]
pub fn with_asynchronous_custom_protocol<F>(self, name: String, handler: F) -> Self
where
F: Fn(WebViewId, Request<Vec<u8>>, RequestAsyncResponder) + 'static,
{
self.and_then(|mut b| {
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
if let Some(context) = &mut b.attrs.context {
context.register_custom_protocol(name.clone())?;
}