1#[cfg(feature = "dom")]
16mod browser;
17
18use std::cell::{Cell, RefCell};
19use std::collections::HashMap;
20use std::future::Future;
21use std::pin::Pin;
22use std::rc::Rc;
23use std::sync::Arc;
24use std::task::Poll;
25
26use day_core::{BuildCx, Flex, Piece, RNode};
27use day_pieces::{Decorated, IntoReactive, IntoText, Reactive};
28use day_reactive::{AnyBinding, Binding, Signal, Trigger, bind_seeded, watch};
29use day_spec::Event;
30
31mod browsing;
32mod content;
33pub mod renderer;
34mod resources;
35pub use browsing::{
36 AuthRequest, AuthResponder, BrowseProps, DialogKind, DialogRequest, DialogResponder,
37 DownloadEvent, DownloadRequest, DownloadResponder, LoadError, LoadErrorKind, RendererGone,
38 UserAgent, cancel_download, download_support, host_trusted, open_download, present_dialog,
39 remove_download, sanitize_file_name, trust_host, unused_path,
40};
41pub use content::{
42 BlockedLoad, ContentRuleList, ContentRulesError, Frames, InjectAt, MediaRequest, PageContent,
43 RequestDecision, RequestFilter, RequestHooks, RequestInfo, ResourceKind, ScriptMessage,
44 UserScript, blocked_report_support, content_rules_support, request_filter_support,
45 script_message_support, user_script_support,
46};
47pub use resources::{ResourceProvider, ResourceRequest, ResourceResponse};
48
49#[cfg(all(
50 any(target_os = "macos", target_os = "ios"),
51 any(feature = "appkit", feature = "uikit", feature = "gtk")
52))]
53mod resources_apple;
54
55#[cfg(all(feature = "arkui", target_env = "ohos"))]
56mod resources_arkui;
57
58#[cfg(any(test, all(feature = "arkui", target_env = "ohos")))]
59mod resource_content_type;
60
61#[cfg(any(
64 test,
65 all(
66 any(target_os = "macos", target_os = "ios"),
67 any(feature = "appkit", feature = "uikit", feature = "gtk")
68 )
69))]
70fn external_document_link(
71 current: Option<&str>,
72 target: &str,
73 activated: bool,
74 new_window: bool,
75 subframe: bool,
76) -> bool {
77 if subframe || target.is_empty() || target == "about:blank" || !(activated || new_window) {
78 return false;
79 }
80 let without_fragment = |url: &str| url.split('#').next().unwrap_or("").to_owned();
81 current.is_none_or(|url| without_fragment(url) != without_fragment(target))
82}
83
84pub const KIND: &str = "day.piece.webview";
85
86#[derive(Clone, Debug, Default, PartialEq, Eq)]
90#[must_use]
91pub struct WebProfile {
92 pub name: String,
93 pub directory: Option<String>,
94 pub private: bool,
95}
96impl WebProfile {
97 pub fn persistent(name: impl Into<String>) -> Self {
98 Self {
99 name: name.into(),
100 ..Self::default()
101 }
102 }
103 pub fn private(name: impl Into<String>) -> Self {
104 Self {
105 name: name.into(),
106 private: true,
107 directory: None,
108 }
109 }
110 pub fn directory(mut self, path: impl Into<String>) -> Self {
111 self.directory = Some(path.into());
112 self
113 }
114 pub fn storage_key(&self) -> String {
116 let text = format!("{}:{:?}:{}", self.name, self.directory, self.private);
117 let hash = text.bytes().fold(14_695_981_039_346_656_037_u64, |h, b| {
118 (h ^ u64::from(b)).wrapping_mul(1_099_511_628_211)
119 });
120 format!("day-{hash:016x}")
121 }
122}
123pub fn private_browsing_support() -> day_spec::Support {
126 if cfg!(any(
127 all(feature = "material", target_os = "android"),
128 all(feature = "dom", target_arch = "wasm32")
129 )) {
130 day_spec::Support::Unsupported
131 } else {
132 support()
133 }
134}
135#[allow(
137 dead_code,
138 reason = "the Apple cookie store (storage_apple.rs) is its only caller"
139)]
140pub(crate) fn cookie_matches(url: &str, domain: &str, path: &str, secure: bool) -> bool {
141 let Ok(url) = url::Url::parse(url) else {
142 return false;
143 };
144 if !matches!(url.scheme(), "http" | "https") || (secure && url.scheme() != "https") {
145 return false;
146 }
147 let host = url.host_str().unwrap_or_default().to_ascii_lowercase();
148 let domain = domain.to_ascii_lowercase();
149 let bare = domain.trim_start_matches('.');
150 let domain_match =
151 host == bare || (domain.starts_with('.') && host.ends_with(&format!(".{bare}")));
152 let path = if path.is_empty() { "/" } else { path };
153 domain_match
154 && (url.path() == path
155 || (url.path().starts_with(path)
156 && (path.ends_with('/') || url.path().as_bytes().get(path.len()) == Some(&b'/'))))
157}
158fn cookie_source_valid(source: &str, header: &str) -> bool {
160 if header.contains(['\r', '\n']) {
161 return false;
162 }
163 let Ok(url) = url::Url::parse(source) else {
164 return false;
165 };
166 if !matches!(url.scheme(), "http" | "https") {
167 return false;
168 }
169 let host = url.host_str().unwrap_or_default().to_ascii_lowercase();
170 let mut fields = header.split(';');
171 let Some((name, _)) = fields.next().and_then(|field| field.trim().split_once('=')) else {
172 return false;
173 };
174 let mut secure = false;
175 let mut domain_set = false;
176 let mut root_path = false;
177 for field in fields {
178 let (key, value) = field.trim().split_once('=').unwrap_or((field.trim(), ""));
179 if key.eq_ignore_ascii_case("domain") {
180 domain_set = true;
181 let domain = value.trim().trim_start_matches('.').to_ascii_lowercase();
182 if psl::suffix(domain.as_bytes())
183 .is_some_and(|suffix| suffix.is_known() && suffix.as_bytes() == domain.as_bytes())
184 {
185 return false;
186 }
187 if domain.is_empty()
188 || !(host == domain
189 || (url::Host::parse(&host).is_ok_and(|h| matches!(h, url::Host::Domain(_)))
190 && host.ends_with(&format!(".{domain}"))))
191 {
192 return false;
193 }
194 } else if key.eq_ignore_ascii_case("secure") {
195 secure = true;
196 } else if key.eq_ignore_ascii_case("path") {
197 root_path = value.trim() == "/";
198 }
199 }
200 if secure && url.scheme() != "https" {
201 return false;
202 }
203 if name.starts_with("__Secure-") && !secure {
204 return false;
205 }
206 if name.starts_with("__Host-") && (!secure || domain_set || !root_path) {
207 return false;
208 }
209 true
210}
211#[cfg(any(
212 all(any(feature = "appkit", feature = "gtk"), target_os = "macos"),
213 all(feature = "uikit", target_os = "ios")
214))]
215mod browsing_apple;
216#[cfg(any(
217 all(any(feature = "appkit", feature = "gtk"), target_os = "macos"),
218 all(feature = "uikit", target_os = "ios")
219))]
220mod content_apple;
221#[cfg(any(
222 all(any(feature = "appkit", feature = "gtk"), target_os = "macos"),
223 all(feature = "uikit", target_os = "ios")
224))]
225mod storage_apple;
226#[cfg(all(any(feature = "appkit", feature = "gtk"), target_os = "macos"))]
228#[doc(hidden)]
229pub use content_apple::probe as __webkit_content_probe;
230pub fn profile_support() -> day_spec::Support {
233 #[cfg(all(feature = "material", target_os = "android"))]
234 let result = android_impl::capability("supportsProfiles");
235 #[cfg(not(all(feature = "material", target_os = "android")))]
236 let result = {
237 #[cfg(any(
238 all(any(feature = "appkit", feature = "gtk"), target_os = "macos"),
239 all(feature = "uikit", target_os = "ios")
240 ))]
241 if !storage_apple::named_profiles_available() {
242 return day_spec::Support::Emulated;
243 }
244 if cfg!(all(feature = "arkui", target_env = "ohos")) {
245 day_spec::Support::Emulated
246 } else if cfg!(all(feature = "dom", target_arch = "wasm32")) {
247 day_spec::Support::Unsupported
248 } else {
249 support()
250 }
251 };
252 result
253}
254pub fn clear_data_support() -> day_spec::Support {
256 #[cfg(all(feature = "material", target_os = "android"))]
257 let result = android_impl::capability("supportsDataClearing");
258 #[cfg(not(all(feature = "material", target_os = "android")))]
259 let result = if cfg!(any(
260 all(feature = "arkui", target_env = "ohos"),
261 all(feature = "dom", target_arch = "wasm32")
262 )) {
263 day_spec::Support::Unsupported
264 } else {
265 support()
266 };
267 result
268}
269
270const DATA_REQUEST: &str = "day-web-data:";
271
272#[derive(Clone, Debug, Default, PartialEq)]
274pub struct WebProps {
275 pub renderer: WebRenderer,
276 pub profile: WebProfile,
277 pub resources: Option<ResourceProvider>,
278 pub resource_site: bool,
283 pub external_links: bool,
285 pub tabs: Option<TabLinkLabels>,
286 pub url: String,
287 pub session: u64,
291 pub inline_root: String,
296 pub inline_start: String,
299 pub inline_assets: bool,
305 pub transparent: bool,
308 pub scroll_reports: bool,
311 pub settings: WebSettings,
316 pub content: PageContent,
321 pub browse: BrowseProps,
325 pub user_agent: UserAgent,
328}
329
330#[derive(Clone, Copy, Debug, PartialEq)]
334pub struct WebSettings {
335 pub zoom: f64,
338 pub desktop_mode: bool,
340 pub javascript: bool,
342}
343
344impl WebSettings {
345 pub const ZOOM_RANGE: std::ops::RangeInclusive<f64> = 0.25..=5.0;
348
349 pub fn clamp_zoom(zoom: f64) -> f64 {
352 if zoom.is_finite() && zoom > 0.0 {
353 zoom.clamp(*Self::ZOOM_RANGE.start(), *Self::ZOOM_RANGE.end())
354 } else {
355 1.0
356 }
357 }
358}
359
360impl Default for WebSettings {
361 fn default() -> Self {
362 WebSettings {
363 zoom: 1.0,
364 desktop_mode: false,
365 javascript: true,
366 }
367 }
368}
369
370#[cfg(test)]
375pub(crate) fn desktop_user_agent(mobile: &str) -> String {
376 let major = mobile
377 .split_once("Chrome/")
378 .map(|(_, rest)| {
379 rest.chars()
380 .take_while(char::is_ascii_digit)
381 .collect::<String>()
382 })
383 .filter(|major| !major.is_empty())
384 .unwrap_or_else(|| "120".into());
385 format!(
386 "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
387 Chrome/{major}.0.0.0 Safari/537.36"
388 )
389}
390
391#[derive(Clone, Copy, PartialEq, Eq, Debug)]
411pub struct WebSession(u64);
412
413impl WebSession {
414 pub fn global(key: &'static str) -> WebSession {
417 day_core::tls_group! {
418 static KEYS: RefCell<HashMap<&'static str, u64>> = RefCell::new(HashMap::new());
419 static NEXT: Cell<u64> = const { Cell::new(1) };
420 }
421 WebSession(KEYS.with(|m| {
422 *m.borrow_mut().entry(key).or_insert_with(|| {
423 NEXT.with(|c| {
424 let v = c.get();
425 c.set(v + 1);
426 v
427 })
428 })
429 }))
430 }
431
432 pub fn id(self) -> u64 {
434 self.0
435 }
436}
437
438const LINK_REPORT: f64 = -1.0;
450
451#[derive(Clone, Copy, Debug, PartialEq, Eq)]
455pub enum LinkPolicy {
456 OpenSystem,
459 InView,
461 Ignore,
464}
465
466#[allow(
472 dead_code,
473 reason = "only the AppKit and UIKit arms load bundled pages through it"
474)]
475pub(crate) fn split_page(page: &str) -> (&str, &str) {
476 match page.find(['?', '#']) {
477 Some(i) => page.split_at(i),
478 None => (page, ""),
479 }
480}
481
482#[derive(Clone, Debug, PartialEq, Eq)]
485pub struct InlineSite {
486 root: String,
487}
488
489impl InlineSite {
490 pub fn root(&self) -> &str {
492 &self.root
493 }
494}
495
496#[derive(Clone, Debug, PartialEq, Eq)]
498pub enum PrepareError {
499 MissingIndex(String),
501 Extract(String),
504}
505
506impl std::fmt::Display for PrepareError {
507 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
508 match self {
509 PrepareError::MissingIndex(root) => {
510 write!(f, "no index.html under resource/assets/{root}")
511 }
512 PrepareError::Extract(e) => write!(f, "extracting the inline site: {e}"),
513 }
514 }
515}
516
517pub struct PrepareSite {
523 result: Option<Result<InlineSite, PrepareError>>,
524}
525
526impl Future for PrepareSite {
527 type Output = Result<InlineSite, PrepareError>;
528 fn poll(mut self: Pin<&mut Self>, _cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
529 match self.result.take() {
530 Some(r) => Poll::Ready(r),
531 None => Poll::Pending,
533 }
534 }
535}
536
537pub trait AssetDirSiteExt {
540 fn prepare_site(self) -> PrepareSite;
541}
542
543impl AssetDirSiteExt for day_core::AssetDir {
544 fn prepare_site(self) -> PrepareSite {
545 let root = self.as_str().trim_matches('/').to_string();
546 #[cfg(target_arch = "wasm32")]
549 let result = Ok(InlineSite { root });
550 #[cfg(not(target_arch = "wasm32"))]
551 let result = {
552 let index = day_spec::AssetName::dynamic(format!("{root}/index.html"));
553 match day_spec::resource(index) {
554 Some(_) => prepare_backend(root),
555 None => Err(PrepareError::MissingIndex(root)),
556 }
557 };
558 PrepareSite {
559 result: Some(result),
560 }
561 }
562}
563
564#[cfg(not(target_arch = "wasm32"))]
567#[allow(
568 clippy::unnecessary_wraps,
569 reason = "the Linux GTK arm returns an error when extraction fails"
570)]
571fn prepare_backend(root: String) -> Result<InlineSite, PrepareError> {
572 #[cfg(all(feature = "gtk", not(target_os = "macos"), not(windows)))]
576 if let Err(e) = gtk_impl::extract_site(&root) {
577 return Err(PrepareError::Extract(e));
578 }
579 Ok(InlineSite { root })
580}
581
582pub trait IntoInlineSite {
586 fn into_inline_site(self) -> InlineSite;
587}
588
589impl IntoInlineSite for InlineSite {
590 fn into_inline_site(self) -> InlineSite {
591 self
592 }
593}
594
595impl IntoInlineSite for day_core::AssetDir {
596 fn into_inline_site(self) -> InlineSite {
597 InlineSite {
598 root: self.as_str().trim_matches('/').to_string(),
599 }
600 }
601}
602
603pub fn inline_support() -> day_spec::Support {
608 if cfg!(any(
609 all(
610 any(feature = "appkit", feature = "gtk"),
611 target_os = "macos"
612 ),
613 all(feature = "uikit", target_os = "ios"),
614 all(feature = "material", target_os = "android"),
615 feature = "qt",
617 all(feature = "xaml", windows),
620 all(feature = "gtk", not(target_os = "macos")),
622 all(feature = "arkui", target_env = "ohos"),
624 all(feature = "dom", target_arch = "wasm32"),
627 )) {
628 day_spec::Support::Native
629 } else {
630 day_spec::Support::Unsupported
631 }
632}
633
634pub fn force_reload_support() -> day_spec::Support {
636 if cfg!(all(feature = "dom", target_arch = "wasm32")) {
637 day_spec::Support::Unsupported
638 } else {
639 support()
640 }
641}
642
643pub fn zoom_support() -> day_spec::Support {
648 if cfg!(any(
649 all(feature = "dom", target_arch = "wasm32"),
650 all(feature = "winui", windows)
651 )) {
652 day_spec::Support::Emulated
653 } else {
654 support()
655 }
656}
657
658pub fn desktop_mode_support() -> day_spec::Support {
663 if cfg!(all(feature = "dom", target_arch = "wasm32")) {
664 day_spec::Support::Unsupported
665 } else {
666 support()
667 }
668}
669
670pub fn javascript_support() -> day_spec::Support {
673 if cfg!(all(feature = "dom", target_arch = "wasm32")) {
674 day_spec::Support::Emulated
675 } else {
676 support()
677 }
678}
679
680#[derive(Clone, Debug, PartialEq)]
682pub enum WebPatch {
683 Load(String),
685 Back,
687 Forward,
688 Stop,
690 Reload,
692 ForceReload,
694 Eval {
697 req: u64,
698 script: String,
699 },
700 ReportState,
706 Zoom(f64),
709 DesktopMode(bool),
712 JavaScript(bool),
715 ContentRules(Vec<ContentRuleList>),
718 ScriptReply {
721 id: u64,
722 reply: Option<String>,
723 },
724 MediaDecision {
727 id: u64,
728 allow: bool,
729 },
730 PromptAnswer {
734 id: u64,
735 answer: String,
736 },
737}
738
739const SEP: char = '\u{1f}';
747
748#[derive(Clone, Debug, PartialEq, Eq)]
750pub enum EvalError {
751 Unsupported,
753 Threw { name: String, message: String },
756 ViewGone,
758 Engine(String),
760}
761
762impl std::fmt::Display for EvalError {
763 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
764 match self {
765 EvalError::Unsupported => write!(f, "javascript evaluation is unsupported here"),
766 EvalError::Threw { name, message } => write!(f, "{name}: {message}"),
767 EvalError::ViewGone => write!(f, "the web view is gone"),
768 EvalError::Engine(raw) => write!(f, "undecodable reply: {raw}"),
769 }
770 }
771}
772
773fn js_string_literal(s: &str) -> String {
779 use std::fmt::Write as _;
780 let mut out = String::with_capacity(s.len() + 2);
781 out.push('"');
782 for c in s.chars() {
783 match c {
784 '"' => out.push_str("\\\""),
785 '\\' => out.push_str("\\\\"),
786 '\n' => out.push_str("\\n"),
787 '\r' => out.push_str("\\r"),
788 '\t' => out.push_str("\\t"),
789 '\u{2028}' => out.push_str("\\u2028"),
790 '\u{2029}' => out.push_str("\\u2029"),
791 c if (c as u32) < 0x20 => {
792 let _ = write!(out, "\\u{:04x}", c as u32);
793 }
794 c => out.push(c),
795 }
796 }
797 out.push('"');
798 out
799}
800
801fn wrap_script(script: &str) -> String {
825 let src = js_string_literal(script);
826 format!(
832 "(function(){{var v;\
833 try{{eval(\"0\");}}\
834 catch(e){{return \"0\\u001f{EVAL_REFUSED}\\u001f\"+((e&&e.message)||String(e));}}\
835 try{{v=eval({src});}}\
836 catch(e){{return \"0\\u001f\"+((e&&e.name)||\"Error\")+\"\\u001f\"+((e&&e.message)||String(e));}}\
837 try{{var s=JSON.stringify(v);return \"1\\u001f\"+(s===undefined?\"null\":s);}}\
838 catch(e){{return \"0\\u001f\"+((e&&e.name)||\"TypeError\")+\"\\u001f\"+((e&&e.message)||String(e));}}\
839 }})()"
840 )
841}
842
843const EVAL_REFUSED: &str = "DayEvalRefused";
845
846pub(crate) fn engine_error(name: &str, message: &str) -> String {
853 format!("0{SEP}{name}{SEP}{message}")
854}
855
856fn wrap_expression(script: &str) -> String {
867 format!(
868 "(function(){{var v;\
869 try{{v=(\n{script}\n);}}\
870 catch(e){{return \"0\\u001f\"+((e&&e.name)||\"Error\")+\"\\u001f\"+((e&&e.message)||String(e));}}\
871 try{{var s=JSON.stringify(v);return \"1\\u001f\"+(s===undefined?\"null\":s);}}\
872 catch(e){{return \"0\\u001f\"+((e&&e.name)||\"TypeError\")+\"\\u001f\"+((e&&e.message)||String(e));}}\
873 }})()"
874 )
875}
876
877fn decode(payload: &str) -> Result<String, EvalError> {
878 match payload.split_once(SEP) {
879 Some(("1", json)) => Ok(json.to_string()),
880 Some(("0", rest)) => {
881 let (name, message) = rest.split_once(SEP).unwrap_or(("Error", rest));
882 Err(EvalError::Threw {
883 name: name.to_string(),
884 message: message.to_string(),
885 })
886 }
887 _ => Err(EvalError::Engine(payload.to_string())),
888 }
889}
890
891struct EvalShared {
892 result: RefCell<Option<Result<String, EvalError>>>,
893 waker: RefCell<Option<std::task::Waker>>,
894}
895
896day_core::tls_group! {
897 static PRIVATE_BLOCKED_NODES: RefCell<std::collections::HashSet<RNode>> = RefCell::new(std::collections::HashSet::new());
899 static REQUEST_NODES: RefCell<HashMap<u64, RNode>> = RefCell::new(HashMap::new());
900 static NEXT_REQ: Cell<u64> = const { Cell::new(1) };
901 static PENDING: RefCell<HashMap<u64, Rc<EvalShared>>> = RefCell::new(HashMap::new());
902 static PENDING_CB: RefCell<HashMap<u64, day_core::PieceOperationDone>> =
906 RefCell::new(HashMap::new());
907 static FALLBACKS: RefCell<HashMap<u64, String>> = RefCell::new(HashMap::new());
909}
910
911fn resolve(req: u64, payload: &str) {
915 let fallback = FALLBACKS.with(|f| f.borrow_mut().remove(&req));
917 let refused =
918 matches!(decode(payload), Err(EvalError::Threw { ref name, .. }) if name == EVAL_REFUSED);
919 if refused
920 && let Some(script) = fallback
921 && let Some(node) = REQUEST_NODES.with(|p| p.borrow().get(&req).copied())
922 {
923 renderer::send_patch(node, WebPatch::Eval { req, script });
924 return;
925 }
926 let renamed;
928 let payload = if refused {
929 renamed = payload.replacen(EVAL_REFUSED, "EvalError", 1);
930 renamed.as_str()
931 } else {
932 payload
933 };
934 REQUEST_NODES.with(|p| p.borrow_mut().remove(&req));
935 if let Some(done) = PENDING_CB.with(|p| p.borrow_mut().remove(&req)) {
936 done(decode(payload).map_err(|e| e.to_string()));
937 return;
938 }
939 let Some(shared) = PENDING.with(|p| p.borrow_mut().remove(&req)) else {
940 return;
941 };
942 *shared.result.borrow_mut() = Some(decode(payload));
943 if let Some(waker) = shared.waker.borrow_mut().take() {
944 waker.wake();
945 }
946}
947
948fn register_script_eval() {
955 let handler: day_core::PieceOperationFn = std::rc::Rc::new(|node, script, done| {
956 if PRIVATE_BLOCKED_NODES.with(|nodes| nodes.borrow().contains(&node))
957 || (!renderer::surface::owns(node) && eval_support() != day_spec::Support::Native)
958 {
959 done(Err(EvalError::Unsupported.to_string()));
960 return;
961 }
962 let req = NEXT_REQ.with(|c| {
963 let v = c.get();
964 c.set(v + 1);
965 v
966 });
967 let wrapped = wrap_script(script);
968 REQUEST_NODES.with(|p| p.borrow_mut().insert(req, node));
969 FALLBACKS.with(|f| f.borrow_mut().insert(req, wrap_expression(script)));
970 PENDING_CB.with(|p| p.borrow_mut().insert(req, done));
971 renderer::send_patch(
972 node,
973 WebPatch::Eval {
974 req,
975 script: wrapped,
976 },
977 );
978 });
979 day_core::register_piece_operation(KIND, "day.webview.eval", handler.clone());
980 day_core::register_piece_operation(
981 renderer::surface::KIND,
982 "day.webview.eval",
983 Rc::new(move |node, script, done| {
984 if renderer::surface::owns(node) {
985 handler(node, script, done);
986 } else {
987 done(Err(EvalError::Unsupported.to_string()));
988 }
989 }),
990 );
991}
992
993#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize)]
996pub struct NavigationState {
997 pub url: String,
998 pub title: String,
999 pub can_go_back: bool,
1000 pub can_go_forward: bool,
1001 pub loading: bool,
1002}
1003
1004#[derive(Clone, Debug, Default, PartialEq)]
1008pub struct PageState {
1009 pub url: String,
1012 pub title: String,
1014 pub loading: bool,
1016 pub progress: f64,
1019 pub can_go_back: bool,
1021 pub can_go_forward: bool,
1023}
1024
1025const PAGE_STATE_REPORT: f64 = -5.0;
1027
1028pub(crate) fn encode_page_state(state: &PageState) -> String {
1034 let flag = |b: bool| if b { '1' } else { '0' };
1035 format!(
1036 "{}{}{}{SEP}{:.2}{SEP}{}{SEP}{}",
1037 flag(state.loading),
1038 flag(state.can_go_back),
1039 flag(state.can_go_forward),
1040 state.progress.clamp(0.0, 1.0),
1041 state.url,
1042 state.title
1043 )
1044}
1045
1046pub(crate) fn page_state_event(state: &PageState) -> Event {
1048 Event::Custom {
1049 tag: "webview:state",
1050 num: PAGE_STATE_REPORT,
1051 text: encode_page_state(state),
1052 }
1053}
1054
1055#[derive(Clone, Copy, Debug, Default, PartialEq)]
1059pub struct ScrollState {
1060 pub offset: f64,
1063 pub content_height: f64,
1065 pub viewport_height: f64,
1067 pub dragging: bool,
1069}
1070
1071impl ScrollState {
1072 pub fn at_top(&self) -> bool {
1074 self.offset <= 0.5
1075 }
1076
1077 pub fn at_bottom(&self) -> bool {
1079 self.content_height > self.viewport_height
1080 && self.offset + self.viewport_height >= self.content_height - 0.5
1081 }
1082}
1083
1084const SCROLL_REPORT: f64 = -6.0;
1086
1087const BLOCKED_REPORT: f64 = -7.0;
1089const SCRIPT_MESSAGE: f64 = -8.0;
1091const CONTENT_RULES_ERROR: f64 = -9.0;
1093const MEDIA_REPORT: f64 = -10.0;
1095
1096pub(crate) fn blocked_event(loads: &[BlockedLoad]) -> Event {
1098 Event::Custom {
1099 tag: "webview:blocked",
1100 num: BLOCKED_REPORT,
1101 text: serde_json::to_string(loads).unwrap_or_default(),
1102 }
1103}
1104
1105pub(crate) fn script_message_event(id: u64, message: ScriptMessage) -> Event {
1107 Event::Custom {
1108 tag: "webview:message",
1109 num: SCRIPT_MESSAGE,
1110 text: serde_json::to_string(&content::MessageReport { id, message }).unwrap_or_default(),
1111 }
1112}
1113
1114pub(crate) fn content_rules_error_event(id: &str, message: &str) -> Event {
1116 Event::Custom {
1117 tag: "webview:rules",
1118 num: CONTENT_RULES_ERROR,
1119 text: serde_json::to_string(&ContentRulesError {
1120 id: id.to_owned(),
1121 message: message.to_owned(),
1122 })
1123 .unwrap_or_default(),
1124 }
1125}
1126
1127pub(crate) fn media_event(id: u64, request: MediaRequest) -> Event {
1130 Event::Custom {
1131 tag: "webview:media",
1132 num: MEDIA_REPORT,
1133 text: serde_json::to_string(&content::MediaReport { id, request }).unwrap_or_default(),
1134 }
1135}
1136
1137#[allow(dead_code, reason = "only the UIKit arm reports its scroll position")]
1140pub(crate) fn encode_scroll_state(state: &ScrollState) -> String {
1141 format!(
1142 "{:.1}{SEP}{:.1}{SEP}{:.1}{SEP}{}",
1143 state.offset,
1144 state.content_height,
1145 state.viewport_height,
1146 if state.dragging { '1' } else { '0' }
1147 )
1148}
1149
1150#[allow(dead_code, reason = "only the UIKit arm reports its scroll position")]
1152pub(crate) fn scroll_state_event(state: &ScrollState) -> Event {
1153 Event::Custom {
1154 tag: "webview:scroll",
1155 num: SCROLL_REPORT,
1156 text: encode_scroll_state(state),
1157 }
1158}
1159
1160fn decode_scroll_state(text: &str) -> Option<ScrollState> {
1161 let mut fields = text.split(SEP);
1162 let mut number = || -> Option<f64> {
1163 let v: f64 = fields.next()?.trim().parse().ok()?;
1164 v.is_finite().then_some(v)
1165 };
1166 let (offset, content_height, viewport_height) = (number()?, number()?, number()?);
1167 let dragging = match fields.next()? {
1168 "1" => true,
1169 "0" => false,
1170 _ => return None,
1171 };
1172 Some(ScrollState {
1173 offset,
1174 content_height,
1175 viewport_height,
1176 dragging,
1177 })
1178}
1179
1180fn decode_page_state(text: &str) -> Option<PageState> {
1183 let mut fields = text.splitn(4, SEP);
1184 let flags = fields.next()?.as_bytes();
1185 let progress: f64 = fields.next()?.trim().parse().ok()?;
1186 let url = fields.next()?.to_owned();
1187 let title = fields.next().unwrap_or_default().to_owned();
1188 if flags.len() != 3 || !progress.is_finite() {
1189 return None;
1190 }
1191 Some(PageState {
1192 url,
1193 title,
1194 loading: flags[0] == b'1',
1195 progress: (progress.clamp(0.0, 1.0) * 100.0).round() / 100.0,
1196 can_go_back: flags[1] == b'1',
1197 can_go_forward: flags[2] == b'1',
1198 })
1199}
1200
1201fn base64_decode(text: &str) -> Option<Vec<u8>> {
1204 let mut out = Vec::with_capacity(text.len() / 4 * 3);
1205 let (mut acc, mut bits) = (0u32, 0u32);
1206 for c in text.bytes() {
1207 let v = match c {
1208 b'A'..=b'Z' => c - b'A',
1209 b'a'..=b'z' => c - b'a' + 26,
1210 b'0'..=b'9' => c - b'0' + 52,
1211 b'+' | b'-' => 62,
1212 b'/' | b'_' => 63,
1213 b'=' | b'\r' | b'\n' | b' ' => continue,
1214 _ => return None,
1215 };
1216 acc = (acc << 6) | u32::from(v);
1217 bits += 6;
1218 if bits >= 8 {
1219 bits -= 8;
1220 out.push((acc >> bits) as u8);
1221 acc &= (1 << bits) - 1;
1222 }
1223 }
1224 Some(out)
1225}
1226
1227#[derive(Clone, Copy)]
1231pub struct JsHandle {
1232 node: Signal<Option<RNode>>,
1233 blocked: Signal<bool>,
1234 renderer: Signal<WebRenderer>,
1235}
1236
1237impl Default for JsHandle {
1238 fn default() -> Self {
1239 Self::new()
1240 }
1241}
1242
1243impl JsHandle {
1244 pub fn renderer(&self) -> WebRenderer {
1246 self.renderer.get_untracked()
1247 }
1248 #[track_caller]
1249 pub fn new() -> Self {
1250 JsHandle {
1251 node: Signal::new(None),
1252 blocked: Signal::new(false),
1253 renderer: Signal::new(WebRenderer::default()),
1254 }
1255 }
1256
1257 fn data_request(&self, operation: &str, url: &str, cookie: &str) -> EvalFuture {
1258 self.data_request_value(
1259 &serde_json::json!({"operation":operation,"url":url,"cookie":cookie}),
1260 )
1261 }
1262 fn data_request_value(&self, request: &serde_json::Value) -> EvalFuture {
1263 let mut future = self.eval("");
1264 future.script = Some(format!("{DATA_REQUEST}{request}"));
1265 future.fallback = None;
1267 future
1268 }
1269 pub async fn snapshot(&self, max_width_px: u32) -> Result<Vec<u8>, EvalError> {
1283 let reply = self
1284 .data_request_value(&serde_json::json!({"operation":"snapshot","width":max_width_px}))
1285 .await
1286 .map_err(|error| match error {
1287 EvalError::Threw { name, .. } if name == "Unsupported" => EvalError::Unsupported,
1288 error => error,
1289 })?;
1290 let encoded: String =
1291 serde_json::from_str(&reply).map_err(|_| EvalError::Engine(reply.clone()))?;
1292 base64_decode(&encoded).ok_or(EvalError::Engine(reply))
1293 }
1294 pub async fn navigation_state(&self) -> Result<NavigationState, EvalError> {
1302 let reply = self.data_request("navigation", "", "").await?;
1303 serde_json::from_str(&reply).map_err(|_| EvalError::Unsupported)
1304 }
1305 pub async fn cookie_header(&self, url: &str) -> Result<String, EvalError> {
1313 if !url::Url::parse(url).is_ok_and(|url| matches!(url.scheme(), "http" | "https")) {
1314 return Err(EvalError::Unsupported);
1315 }
1316 let reply = self.data_request("cookies", url, "").await?;
1317 serde_json::from_str(&reply).map_err(|_| EvalError::Unsupported)
1318 }
1319 pub fn set_cookie(&self, url: &str, cookie: &str) -> EvalFuture {
1321 let future = self.data_request("set-cookie", url, cookie);
1322 if !cookie_source_valid(url, cookie) {
1323 *future.shared.result.borrow_mut() = Some(Err(EvalError::Unsupported));
1324 }
1325 future
1326 }
1327 pub fn clear_data(&self) -> EvalFuture {
1330 self.data_request("clear", "", "")
1331 }
1332
1333 pub fn eval(&self, script: impl AsRef<str>) -> EvalFuture {
1338 EvalFuture {
1339 req: NEXT_REQ.with(|c| {
1340 let v = c.get();
1341 c.set(v + 1);
1342 v
1343 }),
1344 node: self.node,
1345 blocked: self.blocked,
1346 script: Some(wrap_script(script.as_ref())),
1347 fallback: Some(wrap_expression(script.as_ref())),
1348 shared: Rc::new(EvalShared {
1349 result: RefCell::new(None),
1350 waker: RefCell::new(None),
1351 }),
1352 sent: false,
1353 }
1354 }
1355}
1356
1357pub struct EvalFuture {
1359 blocked: Signal<bool>,
1360 req: u64,
1361 node: Signal<Option<RNode>>,
1362 script: Option<String>,
1363 fallback: Option<String>,
1365 shared: Rc<EvalShared>,
1366 sent: bool,
1367}
1368
1369impl Future for EvalFuture {
1370 type Output = Result<String, EvalError>;
1371
1372 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1373 if let Some(result) = self.shared.result.borrow_mut().take() {
1374 return Poll::Ready(result);
1375 }
1376 let Some(blocked) = day_reactive::untrack(|| self.blocked.try_get()) else {
1377 return Poll::Ready(Err(EvalError::ViewGone));
1378 };
1379 if blocked {
1380 return Poll::Ready(Err(EvalError::Unsupported));
1381 }
1382 if !self.sent {
1384 self.sent = true;
1385 let Some(node) = day_reactive::untrack(|| self.node.try_get()).flatten() else {
1386 return Poll::Ready(Err(EvalError::ViewGone));
1387 };
1388 if !renderer::surface::owns(node) && eval_support() != day_spec::Support::Native {
1389 return Poll::Ready(Err(EvalError::Unsupported));
1390 }
1391 let (req, script) = (self.req, self.script.take().unwrap_or_default());
1392 REQUEST_NODES.with(|p| p.borrow_mut().insert(req, node));
1393 if let Some(fallback) = self.fallback.take() {
1394 FALLBACKS.with(|f| f.borrow_mut().insert(req, fallback));
1395 }
1396 PENDING.with(|p| p.borrow_mut().insert(req, self.shared.clone()));
1397 renderer::send_patch(node, WebPatch::Eval { req, script });
1398 if let Some(result) = self.shared.result.borrow_mut().take() {
1403 return Poll::Ready(result);
1404 }
1405 }
1406 *self.shared.waker.borrow_mut() = Some(cx.waker().clone());
1407 Poll::Pending
1408 }
1409}
1410
1411impl Drop for EvalFuture {
1412 fn drop(&mut self) {
1413 REQUEST_NODES.with(|p| p.borrow_mut().remove(&self.req));
1414 PENDING.with(|p| p.borrow_mut().remove(&self.req));
1415 FALLBACKS.with(|f| f.borrow_mut().remove(&self.req));
1416 }
1417}
1418
1419pub fn eval_support() -> day_spec::Support {
1422 if cfg!(any(
1423 all(
1424 any(feature = "appkit", feature = "gtk"),
1425 target_os = "macos"
1426 ),
1427 all(feature = "uikit", target_os = "ios"),
1428 feature = "qt",
1429 all(feature = "dom", target_arch = "wasm32"),
1430 all(feature = "gtk", not(target_os = "macos")),
1431 all(feature = "xaml", target_os = "windows"),
1432 all(feature = "material", target_os = "android"),
1435 all(feature = "arkui", target_env = "ohos"),
1437 )) {
1438 day_spec::Support::Native
1439 } else {
1440 day_spec::Support::Unsupported
1442 }
1443}
1444
1445#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1450pub struct NewTabRequest {
1451 pub url: String,
1452 pub background: bool,
1453}
1454#[derive(Clone, Debug, PartialEq, Eq)]
1456pub struct TabLinkLabels {
1457 pub foreground: String,
1458 pub background: String,
1459}
1460const NEW_TAB_REPORT: f64 = -4.0;
1461fn new_tab_event(url: String, background: bool) -> Event {
1462 Event::Custom {
1463 tag: "webview:new-tab",
1464 num: NEW_TAB_REPORT,
1465 text: serde_json::to_string(&NewTabRequest { url, background }).unwrap_or_default(),
1466 }
1467}
1468
1469#[cfg(all(target_os = "ios", feature = "uikit"))]
1472const TAB_MODIFIER_SCRIPT: &str = r"(() => {
1473 const click = e => {
1474 const a = e.composedPath().find(n => n?.tagName === 'A' && n.href);
1475 if (!a || !(e.metaKey || e.ctrlKey || e.button === 1)) return;
1476 e.preventDefault(); e.stopImmediatePropagation();
1477 location.href = 'day-tab://open?url=' + encodeURIComponent(a.href) + '&background=' + (e.shiftKey ? '0' : '1');
1478 };
1479 addEventListener('click', click, true); addEventListener('auxclick', click, true);
1480})();";
1481#[cfg(all(target_os = "ios", feature = "uikit"))]
1482fn tab_scheme_request(input: &str) -> Option<NewTabRequest> {
1483 let url = url::Url::parse(input).ok()?;
1484 if url.scheme() != "day-tab" {
1485 return None;
1486 }
1487 let pairs: HashMap<_, _> = url.query_pairs().into_owned().collect();
1488 Some(NewTabRequest {
1489 url: pairs.get("url")?.clone(),
1490 background: pairs.get("background").is_some_and(|v| v == "1"),
1491 })
1492}
1493
1494type LinkDecider = Rc<dyn Fn(&str) -> LinkPolicy>;
1496type NewTabHandler = (TabLinkLabels, Rc<dyn Fn(&NewTabRequest)>);
1497type MessageHandler = Rc<dyn Fn(ScriptMessage) -> Option<String>>;
1498type RulesErrorHandler = Rc<dyn Fn(&ContentRulesError)>;
1499type MediaHandler = Rc<dyn Fn(&MediaRequest) -> bool>;
1500
1501#[must_use]
1502pub struct WebView {
1503 renderer: WebRenderer,
1504 profile: WebProfile,
1505 resources: Option<ResourceProvider>,
1506 resource_site: bool,
1507 page_state: Option<AnyBinding<PageState>>,
1508 scroll_state: Option<AnyBinding<ScrollState>>,
1509 url: AnyBinding<String>,
1510 go: Option<Trigger>,
1511 back: Option<Trigger>,
1512 forward: Option<Trigger>,
1513 stop: Option<Trigger>,
1514 reload: Option<Trigger>,
1515 force_reload: Option<Trigger>,
1516 js: Option<JsHandle>,
1517 session: Option<WebSession>,
1518 inline: Option<InlineSite>,
1519 inline_start: String,
1520 inline_assets: bool,
1521 transparent: bool,
1522 on_link: Option<LinkDecider>,
1523 tabs: Option<NewTabHandler>,
1524 on_load: Option<Rc<dyn Fn()>>,
1525 zoom: Option<Reactive<f64>>,
1526 desktop_mode: Option<Reactive<bool>>,
1527 javascript: Option<Reactive<bool>>,
1528 request_filter: Option<Arc<dyn RequestFilter>>,
1529 content_rules: Option<Reactive<Vec<ContentRuleList>>>,
1530 user_scripts: Vec<UserScript>,
1531 user_styles: Vec<Arc<str>>,
1532 messages: Vec<(String, MessageHandler)>,
1533 on_blocked: Option<content::BlockedCallback>,
1534 on_rules_error: Option<RulesErrorHandler>,
1535 on_media: Option<MediaHandler>,
1536 on_app_link: Option<LinkDecider>,
1537 browse: browsing::Handlers,
1538 swipe_navigation: bool,
1539 user_agent: UserAgent,
1540}
1541
1542pub fn web_view(url: impl Binding<String>) -> WebView {
1545 #[cfg(all(feature = "dom", target_arch = "wasm32"))]
1548 dom_impl::register();
1549 register_script_eval();
1552 WebView {
1553 renderer: WebRenderer::default(),
1554 profile: WebProfile::default(),
1555 url: AnyBinding::new(url),
1556 go: None,
1557 back: None,
1558 forward: None,
1559 stop: None,
1560 reload: None,
1561 force_reload: None,
1562 js: None,
1563 session: None,
1564 inline: None,
1565 inline_start: String::new(),
1566 inline_assets: false,
1567 transparent: false,
1568 on_link: None,
1569 tabs: None,
1570 on_load: None,
1571 resources: None,
1572 resource_site: false,
1573 page_state: None,
1574 scroll_state: None,
1575 zoom: None,
1576 desktop_mode: None,
1577 javascript: None,
1578 request_filter: None,
1579 content_rules: None,
1580 user_scripts: Vec::new(),
1581 user_styles: Vec::new(),
1582 messages: Vec::new(),
1583 on_blocked: None,
1584 on_rules_error: None,
1585 on_media: None,
1586 on_app_link: None,
1587 browse: browsing::Handlers::default(),
1588 swipe_navigation: false,
1589 user_agent: UserAgent::Engine,
1590 }
1591}
1592
1593pub fn web_view_inline(site: impl IntoInlineSite) -> WebView {
1602 let mut v = web_view(Signal::new(String::new()));
1603 v.inline = Some(site.into_inline_site());
1604 v.inline_start = "index.html".into();
1605 v
1606}
1607
1608pub fn web_view_resources(provider: ResourceProvider, page: &str) -> WebView {
1610 let mut view = web_view(Signal::new(provider.url(page)));
1611 view.resources = Some(provider);
1612 view.resource_site = true;
1613 view
1614}
1615
1616#[day_pieces::builder(WebViewBuilder)]
1617impl WebView {
1618 pub fn renderer(mut self, renderer: WebRenderer) -> Result<Self, RendererUnavailable> {
1625 if !renderer.available() {
1626 return Err(RendererUnavailable(renderer));
1627 }
1628 self.renderer = renderer;
1629 Ok(self)
1630 }
1631 pub fn profile(mut self, profile: WebProfile) -> Self {
1633 self.profile = profile;
1634 self
1635 }
1636 pub fn url_binding(mut self, url: impl Binding<String>) -> Self {
1639 let url = AnyBinding::new(url);
1640 if url.get_untracked().is_empty() {
1641 url.set(self.url.get_untracked());
1642 }
1643 self.url = url;
1644 self
1645 }
1646 pub fn page_state(mut self, state: impl Binding<PageState>) -> Self {
1655 self.page_state = Some(AnyBinding::new(state));
1656 self
1657 }
1658 pub fn scroll_state(mut self, state: impl Binding<ScrollState>) -> Self {
1665 self.scroll_state = Some(AnyBinding::new(state));
1666 self
1667 }
1668 pub fn resources(mut self, provider: ResourceProvider) -> Self {
1678 self.resources = Some(provider);
1679 self
1680 }
1681 pub fn on_load(mut self, callback: impl Fn() + 'static) -> Self {
1685 self.on_load = Some(Rc::new(callback));
1686 self
1687 }
1688 pub fn go(mut self, trigger: Trigger) -> Self {
1690 self.go = Some(trigger);
1691 self
1692 }
1693 pub fn back(mut self, trigger: Trigger) -> Self {
1695 self.back = Some(trigger);
1696 self
1697 }
1698 pub fn forward(mut self, trigger: Trigger) -> Self {
1700 self.forward = Some(trigger);
1701 self
1702 }
1703 pub fn stop(mut self, trigger: Trigger) -> Self {
1705 self.stop = Some(trigger);
1706 self
1707 }
1708 pub fn reload(mut self, trigger: Trigger) -> Self {
1710 self.reload = Some(trigger);
1711 self
1712 }
1713 pub fn force_reload(mut self, trigger: Trigger) -> Self {
1715 self.force_reload = Some(trigger);
1716 self
1717 }
1718 pub fn js(mut self, handle: JsHandle) -> Self {
1720 self.js = Some(handle);
1721 self
1722 }
1723 pub fn session(mut self, session: WebSession) -> Self {
1725 self.session = Some(session);
1726 self
1727 }
1728 pub fn start_page(mut self, page: impl Into<String>) -> Self {
1732 self.inline_start = page.into();
1733 self
1734 }
1735 pub fn app_assets(mut self) -> Self {
1743 self.inline_assets = true;
1744 self
1745 }
1746 pub fn transparent(mut self) -> Self {
1754 self.transparent = true;
1755 self
1756 }
1757 pub fn zoom<M>(mut self, factor: impl IntoReactive<f64, M>) -> Self {
1763 self.zoom = Some(factor.into_reactive());
1764 self
1765 }
1766 pub fn desktop_mode<M>(mut self, desktop: impl IntoReactive<bool, M>) -> Self {
1771 self.desktop_mode = Some(desktop.into_reactive());
1772 self
1773 }
1774 pub fn javascript<M>(mut self, enabled: impl IntoReactive<bool, M>) -> Self {
1782 self.javascript = Some(enabled.into_reactive());
1783 self
1784 }
1785 pub fn request_filter(mut self, filter: Arc<dyn RequestFilter>) -> Self {
1793 self.request_filter = Some(filter);
1794 self
1795 }
1796 pub fn on_blocked(mut self, f: impl Fn(&[BlockedLoad]) + 'static) -> Self {
1799 self.on_blocked = Some(Rc::new(f));
1800 self
1801 }
1802 pub fn content_rules<M>(mut self, lists: impl IntoReactive<Vec<ContentRuleList>, M>) -> Self {
1808 self.content_rules = Some(lists.into_reactive());
1809 self
1810 }
1811 pub fn on_content_rules_error(mut self, f: impl Fn(&ContentRulesError) + 'static) -> Self {
1814 self.on_rules_error = Some(Rc::new(f));
1815 self
1816 }
1817 pub fn user_script(mut self, script: UserScript) -> Self {
1820 self.user_scripts.push(script);
1821 self
1822 }
1823 pub fn user_style(mut self, css: impl Into<Arc<str>>) -> Self {
1826 self.user_styles.push(css.into());
1827 self
1828 }
1829 pub fn on_script_message(
1834 mut self,
1835 name: impl Into<String>,
1836 handler: impl Fn(ScriptMessage) -> Option<String> + 'static,
1837 ) -> Self {
1838 let name = name.into();
1839 self.messages.retain(|(known, _)| *known != name);
1840 self.messages.push((name, Rc::new(handler)));
1841 self
1842 }
1843 pub fn on_media_request(mut self, f: impl Fn(&MediaRequest) -> bool + 'static) -> Self {
1848 self.on_media = Some(Rc::new(f));
1849 self
1850 }
1851 pub fn on_new_tab<M1, M2>(
1860 mut self,
1861 foreground_label: impl IntoText<M1>,
1862 background_label: impl IntoText<M2>,
1863 f: impl Fn(&NewTabRequest) + 'static,
1864 ) -> Self {
1865 self.tabs = Some((
1866 TabLinkLabels {
1867 foreground: foreground_label.into_text().initial(),
1868 background: background_label.into_text().initial(),
1869 },
1870 Rc::new(f),
1871 ));
1872 self
1873 }
1874 pub fn on_external_link(mut self, f: impl Fn(&str) -> LinkPolicy + 'static) -> Self {
1875 self.on_link = Some(Rc::new(f));
1876 self
1877 }
1878 pub fn on_app_link(mut self, f: impl Fn(&str) -> LinkPolicy + 'static) -> Self {
1884 self.on_app_link = Some(Rc::new(f));
1885 self
1886 }
1887 pub fn on_dialog(mut self, f: impl Fn(DialogRequest, DialogResponder) + 'static) -> Self {
1891 self.browse.dialog = Some(Rc::new(f));
1892 self
1893 }
1894 pub fn on_auth(mut self, f: impl Fn(AuthRequest, AuthResponder) + 'static) -> Self {
1897 self.browse.auth = Some(Rc::new(f));
1898 self
1899 }
1900 pub fn on_download(mut self, f: impl Fn(DownloadRequest, DownloadResponder) + 'static) -> Self {
1904 self.browse.download = Some(Rc::new(f));
1905 self
1906 }
1907 pub fn on_load_error(mut self, f: impl Fn(&LoadError) + 'static) -> Self {
1911 self.browse.load_error = Some(Rc::new(f));
1912 self
1913 }
1914 pub fn on_renderer_gone(mut self, f: impl Fn(&RendererGone) + 'static) -> Self {
1919 self.browse.renderer_gone = Some(Rc::new(f));
1920 self
1921 }
1922 pub fn user_agent(mut self, user_agent: UserAgent) -> Self {
1927 self.user_agent = user_agent;
1928 self
1929 }
1930 pub fn swipe_navigation(mut self, on: bool) -> Self {
1933 self.swipe_navigation = on;
1934 self
1935 }
1936}
1937
1938pub fn open_app_link(url: &str) -> Option<String> {
1945 #[cfg(all(target_os = "android", feature = "material"))]
1946 if url.starts_with("intent:") {
1947 return android_impl::open_intent(url);
1948 }
1949 day_core::open_url(url);
1950 None
1951}
1952
1953fn open_system(url: &str, send: &impl Fn(WebPatch)) {
1956 if let Some(fallback) = open_app_link(url) {
1957 send(WebPatch::Load(fallback));
1958 }
1959}
1960
1961pub fn support() -> day_spec::Support {
1968 if cfg!(all(feature = "dom", target_arch = "wasm32")) {
1970 day_spec::Support::Emulated
1971 } else if cfg!(any(
1972 all(
1973 any(feature = "appkit", feature = "gtk"),
1974 target_os = "macos"
1975 ),
1976 all(feature = "uikit", target_os = "ios"),
1977 all(feature = "material", target_os = "android"),
1978 all(feature = "gtk", not(target_os = "macos")),
1979 feature = "qt",
1980 all(feature = "xaml", windows),
1981 all(feature = "arkui", target_env = "ohos"),
1982 )) {
1983 day_spec::Support::Native
1984 } else {
1985 day_spec::Support::Unsupported
1986 }
1987}
1988
1989struct LatestSink<T: Clone + PartialEq + 'static> {
1992 binding: AnyBinding<T>,
1993 pending: RefCell<Option<T>>,
1994 flush: Cell<Option<day_core::TaskHandle>>,
1995}
1996
1997impl<T: Clone + PartialEq + 'static> LatestSink<T> {
1998 fn new(binding: AnyBinding<T>) -> Rc<Self> {
2000 let sink = Rc::new(LatestSink {
2001 binding,
2002 pending: RefCell::new(None),
2003 flush: Cell::new(None),
2004 });
2005 let cleanup = sink.clone();
2006 day_reactive::Scope::current().on_cleanup(move || {
2007 if let Some(flush) = cleanup.flush.take() {
2008 flush.abort();
2009 }
2010 });
2011 sink
2012 }
2013
2014 fn report(self: &Rc<Self>, state: T) {
2017 *self.pending.borrow_mut() = Some(state);
2018 if let Some(flush) = self.flush.get()
2019 && !flush.is_finished()
2020 {
2021 return;
2022 }
2023 let sink = self.clone();
2024 self.flush.set(Some(day_core::task(async move {
2025 day_core::sleep(16).await;
2026 if let Some(state) = sink.pending.borrow_mut().take()
2027 && sink.binding.get_untracked() != state
2028 {
2029 sink.binding.set(state);
2030 }
2031 })));
2032 }
2033}
2034
2035impl Piece for WebView {
2036 fn build(self, cx: &mut BuildCx) -> RNode {
2037 let WebView {
2038 renderer,
2039 profile,
2040 url,
2041 go,
2042 back,
2043 forward,
2044 stop,
2045 reload,
2046 force_reload,
2047 js,
2048 session,
2049 inline,
2050 inline_start,
2051 inline_assets,
2052 transparent,
2053 on_link,
2054 tabs,
2055 on_load,
2056 mut resources,
2057 resource_site,
2058 page_state,
2059 scroll_state,
2060 zoom,
2061 desktop_mode,
2062 javascript,
2063 request_filter,
2064 content_rules,
2065 user_scripts,
2066 user_styles,
2067 messages,
2068 on_blocked,
2069 on_rules_error,
2070 on_media,
2071 on_app_link,
2072 browse,
2073 swipe_navigation,
2074 user_agent,
2075 } = self;
2076 let settings = WebSettings {
2077 zoom: zoom
2078 .as_ref()
2079 .map_or(1.0, |zoom| WebSettings::clamp_zoom(zoom.get_untracked())),
2080 desktop_mode: desktop_mode
2081 .as_ref()
2082 .is_some_and(day_pieces::Reactive::get_untracked),
2083 javascript: javascript
2084 .as_ref()
2085 .is_none_or(day_pieces::Reactive::get_untracked),
2086 };
2087 let blocked_sink = on_blocked
2090 .as_ref()
2091 .map(|_| Arc::new(content::BlockedSink::default()));
2092 let content = PageContent {
2093 requests: request_filter.map(|filter| {
2096 RequestHooks::new(
2097 filter,
2098 blocked_sink.clone(),
2099 resource_site || inline.is_some(),
2100 )
2101 }),
2102 rules: content_rules
2103 .as_ref()
2104 .map_or_default(day_pieces::Reactive::get_untracked),
2105 scripts: user_scripts,
2106 styles: user_styles,
2107 messages: messages.iter().map(|(name, _)| name.clone()).collect(),
2108 media_handler: on_media.is_some(),
2109 };
2110 let session_id = session.map_or(0, WebSession::id);
2111 let session_id = if session_id == 0 || profile == WebProfile::default() {
2112 session_id
2113 } else {
2114 profile.storage_key().bytes().fold(session_id, |h, b| {
2115 (h ^ u64::from(b)).wrapping_mul(1_099_511_628_211)
2116 })
2117 };
2118 let mut initial_url = url.get_untracked();
2119 if let (Some(_session), Some(provider)) = (session, &resources) {
2120 day_core::tls_group! {
2123 static SESSION_RESOURCES: RefCell<HashMap<(WebRenderer, u64), (ResourceProvider, String)>> = RefCell::new(HashMap::new());
2124 }
2125 let retained = SESSION_RESOURCES.with(|m| {
2126 m.borrow_mut()
2127 .entry((renderer, session_id))
2128 .or_insert_with(|| (provider.clone(), initial_url.clone()))
2129 .clone()
2130 });
2131 resources = Some(retained.0);
2132 initial_url = retained.1;
2133 url.set(initial_url.clone());
2134 }
2135 let blocked_private = (profile.private
2136 && renderer.private_browsing_support() == day_spec::Support::Unsupported)
2137 || (renderer != WebRenderer::WebView
2138 && renderer.profile_support() == day_spec::Support::Unsupported
2139 && profile != WebProfile::default());
2140 let initial = WebProps {
2141 renderer,
2142 profile,
2143 resources: if blocked_private {
2144 None
2145 } else {
2146 resources.clone()
2147 },
2148 resource_site: resource_site && resources.is_some() && !blocked_private,
2149 external_links: on_link.is_some(),
2150 tabs: tabs.as_ref().map(|(labels, _)| labels.clone()),
2151 url: if blocked_private {
2152 "about:blank".into()
2153 } else {
2154 initial_url
2155 },
2156 session: session_id,
2157 inline_root: if blocked_private {
2158 String::new()
2159 } else {
2160 inline.as_ref().map_or_default(|s| s.root.clone())
2161 },
2162 inline_start: if inline.is_some() {
2163 inline_start
2164 } else {
2165 String::new()
2166 },
2167 inline_assets: inline.is_some() && inline_assets,
2168 transparent,
2169 scroll_reports: scroll_state.is_some(),
2170 settings,
2171 content: if blocked_private {
2172 PageContent::default()
2173 } else {
2174 content
2175 },
2176 browse: browse.props(swipe_navigation),
2177 user_agent,
2178 };
2179 let surface = renderer::surface::get(renderer);
2181 let flex = Flex {
2182 grow_w: true,
2183 grow_h: true,
2184 ..Default::default()
2185 };
2186 let node = if surface.is_some() {
2187 cx.leaf(
2188 renderer::surface::KIND,
2189 &day_spec::props::CanvasProps::default(),
2190 flex,
2191 )
2192 } else {
2193 cx.leaf(KIND, &initial, flex)
2194 };
2195
2196 if let Some(host) = surface {
2197 renderer::surface::attach(host, cx, node, &initial);
2198 }
2199
2200 day_reactive::Scope::current().on_cleanup(move || {
2201 let requests = REQUEST_NODES.with(|p| {
2202 p.borrow()
2203 .iter()
2204 .filter_map(|(req, owner)| (*owner == node).then_some(*req))
2205 .collect::<Vec<_>>()
2206 });
2207 for req in requests {
2208 REQUEST_NODES.with(|p| p.borrow_mut().remove(&req));
2209 if let Some(done) = PENDING_CB.with(|p| p.borrow_mut().remove(&req)) {
2210 done(Err(EvalError::ViewGone.to_string()));
2211 }
2212 if let Some(shared) = PENDING.with(|p| p.borrow_mut().remove(&req)) {
2213 *shared.result.borrow_mut() = Some(Err(EvalError::ViewGone));
2214 if let Some(waker) = shared.waker.borrow_mut().take() {
2215 waker.wake();
2216 }
2217 }
2218 }
2219 });
2220 if blocked_private {
2221 PRIVATE_BLOCKED_NODES.with(|nodes| nodes.borrow_mut().insert(node));
2222 day_reactive::Scope::current().on_cleanup(move || {
2223 PRIVATE_BLOCKED_NODES.with(|nodes| nodes.borrow_mut().remove(&node));
2224 });
2225 }
2226 let send = move |patch: WebPatch| {
2227 if blocked_private {
2228 if let WebPatch::Eval { req, .. } = patch {
2229 resolve(
2230 req,
2231 &engine_error("Unsupported", "private browsing unavailable"),
2232 );
2233 }
2234 return;
2235 }
2236 renderer::send_patch(node, patch);
2237 };
2238
2239 if let Some(go) = go {
2242 watch(
2243 move || go.track(),
2244 move |(), _| send(WebPatch::Load(url.get_untracked())),
2245 );
2246 }
2247 if let Some(back) = back {
2248 watch(move || back.track(), move |(), _| send(WebPatch::Back));
2249 }
2250 if let Some(forward) = forward {
2251 watch(
2252 move || forward.track(),
2253 move |(), _| send(WebPatch::Forward),
2254 );
2255 }
2256 if let Some(stop) = stop {
2257 watch(move || stop.track(), move |(), _| send(WebPatch::Stop));
2258 }
2259 if let Some(reload) = reload {
2260 watch(move || reload.track(), move |(), _| send(WebPatch::Reload));
2261 }
2262
2263 if let Some(force_reload) = force_reload {
2264 watch(
2265 move || force_reload.track(),
2266 move |(), _| send(WebPatch::ForceReload),
2267 );
2268 }
2269
2270 if let Some(zoom) = zoom {
2273 bind_seeded(
2274 settings.zoom,
2275 move || WebSettings::clamp_zoom(zoom.get()),
2276 move |zoom: &f64| send(WebPatch::Zoom(*zoom)),
2277 );
2278 }
2279 if let Some(desktop) = desktop_mode {
2280 bind_seeded(
2281 settings.desktop_mode,
2282 move || desktop.get(),
2283 move |desktop: &bool| send(WebPatch::DesktopMode(*desktop)),
2284 );
2285 }
2286 if let Some(javascript) = javascript {
2287 bind_seeded(
2288 settings.javascript,
2289 move || javascript.get(),
2290 move |enabled: &bool| send(WebPatch::JavaScript(*enabled)),
2291 );
2292 }
2293 if let Some(rules) = content_rules {
2294 bind_seeded(
2295 initial.content.rules.clone(),
2296 move || rules.get(),
2297 move |rules: &Vec<ContentRuleList>| send(WebPatch::ContentRules(rules.clone())),
2298 );
2299 }
2300 if let (Some(sink), Some(callback)) = (&blocked_sink, on_blocked) {
2301 let delivery = content::deliver_blocked(sink.clone(), callback);
2302 day_reactive::Scope::current().on_cleanup(move || delivery.abort());
2303 }
2304
2305 if let Some(js) = js {
2307 js.renderer.set(renderer);
2308 js.blocked.set(blocked_private);
2309 js.node.set(Some(node));
2310 day_reactive::Scope::current().on_cleanup(move || {
2311 if js.node.try_get() == Some(Some(node)) {
2312 js.node.set(None);
2313 }
2314 });
2315 }
2316
2317 let has_page_state = page_state.is_some();
2321 let page_states = page_state.map(LatestSink::new);
2322 let scroll_states = scroll_state.map(LatestSink::new);
2324 #[cfg(all(feature = "arkui", target_env = "ohos"))]
2331 let registration = RefCell::new(None);
2332 #[cfg(all(feature = "arkui", target_env = "ohos"))]
2333 let resource_start = initial.url.clone();
2334 let keep_hooks = initial.content.requests.clone();
2337 cx.on(node, move |ev| {
2338 let _keep_resources_alive = &resources;
2339 let _keep_hooks_alive = &keep_hooks;
2340 if let Event::Custom { num, text, .. } = ev {
2341 #[cfg(all(feature = "arkui", target_env = "ohos"))]
2342 #[expect(clippy::float_cmp, reason = "report codes are small integers carried in a float")]
2343 if *num == -3.0 {
2344 let provider = resources.as_ref().map_or(0, ResourceProvider::id);
2348 *registration.borrow_mut() =
2349 resources_arkui::install(provider, keep_hooks.clone(), text);
2350 if provider != 0 {
2351 if registration.borrow().is_some() {
2352 send(WebPatch::Load(resource_start.clone()));
2353 }
2354 } else if keep_hooks.is_some() {
2355 if registration.borrow().is_none() {
2356 log::warn!("day-piece-webview: ArkWeb scheme handler unavailable; the request filter is off");
2357 }
2358 send(WebPatch::Load(String::new()));
2360 }
2361 return;
2362 }
2363 if *num >= 1.0 {
2364 resolve(*num as u64, text);
2365 } else if *num == PAGE_STATE_REPORT {
2366 if let (Some(sink), Some(state)) = (&page_states, decode_page_state(text)) {
2367 sink.report(state);
2368 }
2369 } else if *num == SCROLL_REPORT {
2370 if let (Some(sink), Some(state)) = (&scroll_states, decode_scroll_state(text)) {
2371 sink.report(state);
2372 }
2373 } else if *num == BLOCKED_REPORT {
2374 if let Some(sink) = &blocked_sink {
2375 match serde_json::from_str::<Vec<BlockedLoad>>(text) {
2376 Ok(loads) => sink.extend(loads),
2377 Err(_) => {
2378 if let Ok(load) = serde_json::from_str::<BlockedLoad>(text) {
2379 sink.push(load);
2380 }
2381 }
2382 }
2383 }
2384 } else if *num == SCRIPT_MESSAGE {
2385 if let Ok(report) = serde_json::from_str::<content::MessageReport>(text) {
2386 let reply = messages
2387 .iter()
2388 .find(|(name, _)| *name == report.message.name)
2389 .and_then(|(_, handler)| handler(report.message));
2390 send(WebPatch::ScriptReply {
2391 id: report.id,
2392 reply,
2393 });
2394 }
2395 } else if *num == CONTENT_RULES_ERROR {
2396 if let (Some(callback), Ok(error)) = (
2397 &on_rules_error,
2398 serde_json::from_str::<ContentRulesError>(text),
2399 ) {
2400 callback(&error);
2401 }
2402 } else if *num == MEDIA_REPORT {
2403 if let Ok(report) = serde_json::from_str::<content::MediaReport>(text) {
2404 let allow = on_media.as_ref().is_some_and(|f| f(&report.request));
2405 send(WebPatch::MediaDecision {
2406 id: report.id,
2407 allow,
2408 });
2409 }
2410 } else if *num == browsing::PAGE_PROMPT {
2411 browse.prompt(text, move |id, answer| {
2412 send(WebPatch::PromptAnswer {
2413 id,
2414 answer: serde_json::to_string(&answer).unwrap_or_default(),
2415 });
2416 });
2417 } else if *num == browsing::PAGE_NOTICE {
2418 browse.notice(text);
2419 } else if *num == NEW_TAB_REPORT {
2420 if let Some((_, callback)) = &tabs
2421 && let Ok(request) = serde_json::from_str::<NewTabRequest>(text)
2422 {
2423 callback(&request);
2424 }
2425 } else if *num == LINK_REPORT {
2426 let app_link = !browsing::engine_scheme(text);
2432 let policy = on_app_link
2433 .as_ref()
2434 .filter(|_| app_link)
2435 .or(on_link.as_ref())
2436 .map_or(LinkPolicy::OpenSystem, |f| f(text));
2437 match policy {
2438 LinkPolicy::OpenSystem => open_system(text, &send),
2439 LinkPolicy::InView if !app_link => {
2440 send(WebPatch::Load(text.clone()));
2441 }
2442 LinkPolicy::InView | LinkPolicy::Ignore => {}
2443 }
2444 } else if *num == 0.0 {
2445 url.set(text.clone());
2446 if let Some(callback) = &on_load {
2447 callback();
2448 }
2449 }
2450 }
2451 });
2452 if has_page_state {
2455 let ask = day_core::task(async move {
2456 day_core::sleep(0).await;
2457 send(WebPatch::ReportState);
2458 });
2459 day_reactive::Scope::current().on_cleanup(move || ask.abort());
2460 }
2461 node
2462 }
2463}
2464
2465#[cfg(all(target_os = "macos", feature = "gtk"))]
2473mod gtk_assets;
2474#[cfg(all(target_os = "macos", feature = "gtk"))]
2475#[path = "lib-gtk-macos.rs"]
2476mod gtk_macos;
2477#[cfg(all(target_os = "macos", any(feature = "appkit", feature = "gtk")))]
2478mod macos_web;
2479
2480day_pieces::glue_modules!(appkit, qt, uikit, material, xaml, arkui, dom);
2481
2482#[cfg(any(test, all(feature = "xaml", windows)))]
2483mod xaml_path;
2484
2485#[cfg(all(feature = "gtk", not(target_os = "macos"), not(windows)))]
2487#[path = "lib-gtk.rs"]
2488mod gtk_impl;
2489
2490#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2492pub enum WebRenderer {
2493 #[default]
2495 WebView,
2496 Servo,
2498}
2499impl WebRenderer {
2500 pub fn available(self) -> bool {
2502 match self {
2503 Self::WebView => support() != day_spec::Support::Unsupported,
2504 Self::Servo => renderer::capabilities(self).is_some(),
2505 }
2506 }
2507 pub fn private_browsing_support(self) -> day_spec::Support {
2509 match self {
2510 Self::WebView => private_browsing_support(),
2511 Self::Servo => renderer::capabilities(self)
2512 .map_or(day_spec::Support::Unsupported, |caps| caps.private_browsing),
2513 }
2514 }
2515 pub fn profile_support(self) -> day_spec::Support {
2517 match self {
2518 Self::WebView => profile_support(),
2519 Self::Servo => renderer::capabilities(self)
2520 .map_or(day_spec::Support::Unsupported, |caps| caps.profiles),
2521 }
2522 }
2523 pub fn clear_data_support(self) -> day_spec::Support {
2525 match self {
2526 Self::WebView => clear_data_support(),
2527 Self::Servo => renderer::capabilities(self)
2528 .map_or(day_spec::Support::Unsupported, |caps| caps.clear_data),
2529 }
2530 }
2531 pub fn zoom_support(self) -> day_spec::Support {
2533 match self {
2534 Self::WebView => zoom_support(),
2535 Self::Servo => renderer::capabilities(self)
2536 .map_or(day_spec::Support::Unsupported, |_| {
2537 day_spec::Support::Native
2538 }),
2539 }
2540 }
2541 pub fn desktop_mode_support(self) -> day_spec::Support {
2543 match self {
2544 Self::WebView => desktop_mode_support(),
2545 Self::Servo => day_spec::Support::Unsupported,
2546 }
2547 }
2548 pub fn request_filter_support(self) -> day_spec::Support {
2551 match self {
2552 Self::WebView => request_filter_support(),
2553 Self::Servo => renderer::capabilities(self)
2554 .map_or(day_spec::Support::Unsupported, |_| {
2555 day_spec::Support::Native
2556 }),
2557 }
2558 }
2559 pub fn javascript_support(self) -> day_spec::Support {
2561 match self {
2562 Self::WebView => javascript_support(),
2563 Self::Servo => day_spec::Support::Unsupported,
2564 }
2565 }
2566}
2567#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2569pub struct RendererUnavailable(pub WebRenderer);
2570impl std::fmt::Display for RendererUnavailable {
2571 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2572 write!(f, "{:?} renderer is unavailable in this build", self.0)
2573 }
2574}
2575impl std::error::Error for RendererUnavailable {}
2576
2577#[cfg(test)]
2578mod tests {
2579 #[test]
2580 fn the_expression_form_carries_the_script_as_source() {
2581 let wrapped = wrap_expression("document.title // the title");
2582 assert!(wrapped.contains("v=(\ndocument.title // the title\n);"));
2583 assert!(!wrapped.contains("eval("));
2584 assert!(wrap_script("document.title").contains("eval("));
2586 }
2587
2588 #[test]
2592 fn only_a_refused_eval_is_reported_as_one() {
2593 let throws = "globalThis.count=(globalThis.count||0)+1; throw new EvalError('mine')";
2594 let program = format!(
2595 "var first={};\
2596 var refused=(function(eval){{return {}}})(function(){{throw new EvalError('refused')}});\
2597 console.log(JSON.stringify([first,globalThis.count,refused,globalThis.touched===undefined,{}]))",
2598 wrap_script(throws),
2599 wrap_script("globalThis.touched=1"),
2600 wrap_expression("1+1")
2601 );
2602 let output = match std::process::Command::new("node")
2603 .arg("-e")
2604 .arg(&program)
2605 .output()
2606 {
2607 Ok(output) if output.status.success() => output,
2608 _ => {
2609 eprintln!("node did not run; skipping");
2610 return;
2611 }
2612 };
2613 let text = String::from_utf8_lossy(&output.stdout);
2614 let values: Vec<serde_json::Value> = serde_json::from_str(text.trim()).unwrap();
2615 assert_eq!(values[0], format!("0{SEP}EvalError{SEP}mine"));
2616 assert_eq!(values[1], 1, "the script ran once");
2617 assert_eq!(values[2], format!("0{SEP}{EVAL_REFUSED}{SEP}refused"));
2618 assert_eq!(values[3], true, "a refused script did not run");
2619 assert_eq!(values[4], format!("1{SEP}2"));
2620 }
2621
2622 #[test]
2626 fn the_wrapper_runs_the_script_as_written() {
2627 let scripts = [
2628 "'use strict'; (function(){ return this === undefined; })()",
2629 "",
2630 "var declared = 1;",
2631 "let ran = 2, v = 3, e = 4, s = 5; ran + v + e + s",
2632 "document = undefined; typeof eval",
2633 ];
2634 let wrapped: Vec<String> = scripts.iter().map(|s| wrap_script(s)).collect();
2635 let program = format!("console.log(JSON.stringify([{}]))", wrapped.join(","));
2636 let output = match std::process::Command::new("node")
2637 .arg("-e")
2638 .arg(&program)
2639 .output()
2640 {
2641 Ok(output) if output.status.success() => output,
2642 _ => {
2643 eprintln!("node did not run; skipping");
2644 return;
2645 }
2646 };
2647 let text = String::from_utf8_lossy(&output.stdout);
2648 let values: Vec<String> = serde_json::from_str(text.trim()).unwrap();
2649 assert_eq!(values[0], format!("1{SEP}true"), "strict mode kept");
2650 assert_eq!(values[1], format!("1{SEP}null"));
2651 assert_eq!(values[2], format!("1{SEP}null"));
2652 assert_eq!(values[3], format!("1{SEP}14"));
2653 assert_eq!(values[4], format!("1{SEP}\"function\""));
2654 }
2655
2656 #[test]
2657 fn servo_selection_is_explicit_and_does_not_claim_native_profiles() {
2658 assert_eq!(super::WebRenderer::default(), super::WebRenderer::WebView);
2659 assert!(!super::WebRenderer::Servo.available());
2660 assert_eq!(
2661 super::WebRenderer::Servo.private_browsing_support(),
2662 day_spec::Support::Unsupported
2663 );
2664 assert_eq!(
2665 super::WebRenderer::Servo.profile_support(),
2666 day_spec::Support::Unsupported
2667 );
2668 }
2669
2670 use super::*;
2671
2672 #[test]
2673 fn an_unpolled_evaluation_survives_its_tab_being_closed() {
2674 let scope = day_reactive::Scope::child();
2675 let mut future = scope.enter(|| JsHandle::new().eval("1 + 1"));
2676 scope.dispose();
2677 let mut context = std::task::Context::from_waker(std::task::Waker::noop());
2678 std::assert_matches!(
2679 Pin::new(&mut future).poll(&mut context),
2680 Poll::Ready(Err(EvalError::ViewGone))
2681 );
2682 }
2683
2684 #[test]
2685 fn profiles_keep_identity_and_privacy_separate() {
2686 let profile = WebProfile::persistent("publication");
2687 assert_eq!(
2688 profile.storage_key(),
2689 WebProfile::persistent("publication").storage_key()
2690 );
2691 assert_ne!(
2692 profile.storage_key(),
2693 WebProfile::private("publication").storage_key()
2694 );
2695 assert_ne!(
2696 profile.storage_key(),
2697 WebProfile::persistent("other").storage_key()
2698 );
2699 assert_ne!(
2700 profile.clone().directory("/fixture/a").storage_key(),
2701 profile.directory("/fixture/b").storage_key()
2702 );
2703 }
2704 #[test]
2705 fn response_cookies_cannot_impersonate_another_origin() {
2706 assert!(cookie_source_valid(
2707 "https://news.example.com/story",
2708 "session=fixture; Domain=.example.com; Secure; HttpOnly"
2709 ));
2710 assert!(!cookie_source_valid(
2711 "https://news.example.co.uk/",
2712 "session=fixture; Domain=co.uk"
2713 ));
2714 assert!(!cookie_source_valid(
2715 "https://project.github.io/",
2716 "session=fixture; Domain=github.io"
2717 ));
2718 assert!(!cookie_source_valid(
2719 "https://unrelated.test/",
2720 "session=fixture; Domain=example.com"
2721 ));
2722 assert!(!cookie_source_valid(
2723 "https://example.com/",
2724 "session=fixture\r\nInjected: header"
2725 ));
2726 assert!(!cookie_source_valid(
2727 "http://example.com/",
2728 "session=fixture; Secure"
2729 ));
2730 assert!(!cookie_source_valid(
2731 "https://example.com/",
2732 "__Host-session=fixture; Secure; Domain=example.com; Path=/"
2733 ));
2734 assert!(cookie_source_valid(
2735 "https://example.com/",
2736 "__Host-session=fixture; Secure; Path=/"
2737 ));
2738 }
2739 #[test]
2740 fn cookie_credentials_respect_host_path_and_transport_boundaries() {
2741 assert!(cookie_matches(
2742 "https://news.example.com/account/page",
2743 ".example.com",
2744 "/account",
2745 true
2746 ));
2747 assert!(!cookie_matches(
2748 "http://news.example.com/account",
2749 ".example.com",
2750 "/account",
2751 true
2752 ));
2753 assert!(!cookie_matches(
2754 "https://evil-example.com/account",
2755 ".example.com",
2756 "/account",
2757 false
2758 ));
2759 assert!(!cookie_matches(
2760 "https://news.example.com/accounting",
2761 ".example.com",
2762 "/account",
2763 false
2764 ));
2765 assert!(!cookie_matches(
2766 "https://news.example.com/",
2767 "example.com",
2768 "/",
2769 false
2770 ));
2771 assert!(!cookie_matches(
2772 "file:///account",
2773 ".example.com",
2774 "/",
2775 false
2776 ));
2777 assert!(cookie_matches(
2778 "https://EXAMPLE.com/",
2779 "example.com",
2780 "",
2781 false
2782 ));
2783 }
2784
2785 fn reply(parts: &[&str]) -> String {
2787 parts.join(&SEP.to_string())
2788 }
2789
2790 #[test]
2791 fn decodes_a_value() {
2792 assert_eq!(decode(&reply(&["1", "2"])), Ok("2".into()));
2793 assert_eq!(decode(&reply(&["1", "null"])), Ok("null".into()));
2794 let obj = r#"{"a":1,"b":"x"}"#;
2795 assert_eq!(decode(&reply(&["1", obj])), Ok(obj.into()));
2796 }
2797
2798 #[test]
2799 fn decodes_a_throw() {
2800 assert_eq!(
2801 decode(&reply(&["0", "TypeError", "boom"])),
2802 Err(EvalError::Threw {
2803 name: "TypeError".into(),
2804 message: "boom".into(),
2805 })
2806 );
2807 }
2808
2809 #[test]
2811 fn a_message_may_contain_the_separator() {
2812 assert_eq!(
2813 decode(&reply(&["0", "Error", "a", "b"])),
2814 Err(EvalError::Threw {
2815 name: "Error".into(),
2816 message: reply(&["a", "b"]),
2817 })
2818 );
2819 }
2820
2821 #[test]
2824 fn an_escaped_separator_inside_json_survives() {
2825 let json = r#""a\u001fb""#;
2826 assert_eq!(decode(&reply(&["1", json])), Ok(json.into()));
2827 }
2828
2829 #[test]
2830 fn an_undecodable_reply_is_an_engine_error() {
2831 assert_eq!(decode(""), Err(EvalError::Engine(String::new())));
2832 assert_eq!(decode("null"), Err(EvalError::Engine("null".into())));
2834 }
2835
2836 #[test]
2838 fn engine_errors_round_trip() {
2839 assert_eq!(
2840 decode(&engine_error("WebKitError", "process gone")),
2841 Err(EvalError::Threw {
2842 name: "WebKitError".into(),
2843 message: "process gone".into(),
2844 })
2845 );
2846 }
2847
2848 #[test]
2851 fn the_wrapper_is_lexically_sealed() {
2852 for hostile in [
2853 "1 + 1 // add",
2854 "\"unterminated",
2855 "}}})(){{{",
2856 "a\nb",
2857 "x\\y",
2858 ] {
2859 let js = wrap_script(hostile);
2860 assert!(
2861 js.trim_end().ends_with("})()"),
2862 "wrapper not closed for {hostile:?}: {js}"
2863 );
2864 assert!(
2865 !js.contains('\n'),
2866 "raw newline leaked for {hostile:?}: {js}"
2867 );
2868 }
2869 }
2870
2871 #[test]
2872 fn scroll_reports_round_trip_and_reject_garbage() {
2873 let state = ScrollState {
2874 offset: 1234.5,
2875 content_height: 8000.0,
2876 viewport_height: 700.0,
2877 dragging: true,
2878 };
2879 assert_eq!(
2880 decode_scroll_state(&encode_scroll_state(&state)),
2881 Some(state)
2882 );
2883 let java = decode_scroll_state("-12.0\u{1f}900.0\u{1f}700.0\u{1f}0").unwrap();
2885 assert!(java.at_top() && !java.dragging);
2886 assert!(!java.at_bottom());
2887 let end = ScrollState {
2888 offset: 200.0,
2889 content_height: 900.0,
2890 viewport_height: 700.0,
2891 dragging: false,
2892 };
2893 assert!(end.at_bottom());
2894 assert_eq!(decode_scroll_state("1,5\u{1f}900\u{1f}700\u{1f}0"), None);
2895 assert_eq!(decode_scroll_state("1\u{1f}NaN\u{1f}700\u{1f}0"), None);
2896 assert_eq!(decode_scroll_state("1\u{1f}2\u{1f}3\u{1f}yes"), None);
2897 assert_eq!(decode_scroll_state("1\u{1f}2"), None);
2898 }
2899
2900 #[test]
2901 fn page_state_reports_round_trip_with_a_separator_in_the_title() {
2902 let state = PageState {
2903 url: "https://example.test/a?b=c#d".into(),
2904 title: reply(&["two", "parts"]),
2905 loading: true,
2906 progress: 0.4567,
2907 can_go_back: true,
2908 can_go_forward: false,
2909 };
2910 let decoded = decode_page_state(&encode_page_state(&state)).unwrap();
2911 assert_eq!(decoded.title, state.title);
2912 assert_eq!(decoded.url, state.url);
2913 assert!(decoded.loading && decoded.can_go_back && !decoded.can_go_forward);
2914 assert_eq!(decoded.progress, 0.46);
2915 let native = decode_page_state(&reply(&["011", "1", "about:blank", ""])).unwrap();
2917 assert_eq!(native.progress, 1.0);
2918 assert!(!native.loading && native.can_go_back && native.can_go_forward);
2919 assert_eq!(decode_page_state(&reply(&["01", "1", "x", ""])), None);
2920 assert_eq!(decode_page_state(&reply(&["000", "NaN", "x", ""])), None);
2921 assert_eq!(
2922 decode_page_state(&reply(&["000", "7", "x", "t"]))
2923 .unwrap()
2924 .progress,
2925 1.0
2926 );
2927 }
2928
2929 #[test]
2930 fn zoom_factors_clamp_to_what_every_engine_accepts() {
2931 assert_eq!(WebSettings::clamp_zoom(1.25), 1.25);
2932 assert_eq!(WebSettings::clamp_zoom(0.1), 0.25);
2933 assert_eq!(WebSettings::clamp_zoom(12.0), 5.0);
2934 for nonsense in [0.0, -2.0, f64::NAN, f64::INFINITY] {
2935 assert_eq!(WebSettings::clamp_zoom(nonsense), 1.0, "{nonsense}");
2936 }
2937 }
2938
2939 #[test]
2941 fn desktop_agents_keep_the_engine_major_version() {
2942 let android = "Mozilla/5.0 (Linux; Android 14; Pixel 7 Build/UQ1A; wv) AppleWebKit/537.36 \
2943 (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.135 Mobile Safari/537.36";
2944 assert_eq!(
2945 desktop_user_agent(android),
2946 "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
2947 Chrome/131.0.0.0 Safari/537.36"
2948 );
2949 assert!(desktop_user_agent("ArkWeb/4.1 Mobile").contains(" Chrome/120.0.0.0 "));
2950 }
2951
2952 #[test]
2953 fn snapshot_replies_decode_base64() {
2954 assert_eq!(base64_decode("iVBORw0KGgo=").unwrap(), b"\x89PNG\r\n\x1a\n");
2955 assert_eq!(base64_decode("aGVsbG8").unwrap(), b"hello");
2956 assert_eq!(base64_decode("aGVs\nbG8=").unwrap(), b"hello");
2957 assert_eq!(base64_decode(""), Some(Vec::new()));
2958 assert_eq!(base64_decode("a*b"), None);
2959 }
2960
2961 #[test]
2962 fn a_start_page_keeps_its_query_out_of_the_path() {
2963 assert_eq!(split_page("index.html"), ("index.html", ""));
2964 assert_eq!(
2965 split_page("player.html?src=hello&loop=1"),
2966 ("player.html", "?src=hello&loop=1")
2967 );
2968 assert_eq!(
2969 split_page("docs/index.html#top"),
2970 ("docs/index.html", "#top")
2971 );
2972 }
2973
2974 #[test]
2975 fn escapes_a_script_into_a_literal() {
2976 assert_eq!(js_string_literal("a"), "\"a\"");
2977 assert_eq!(js_string_literal("a\"b"), "\"a\\\"b\"");
2978 assert_eq!(js_string_literal("a\\b"), "\"a\\\\b\"");
2979 assert_eq!(js_string_literal("a\nb"), "\"a\\nb\"");
2980 assert_eq!(js_string_literal("a\u{2028}b"), "\"a\\u2028b\"");
2982 assert_eq!(js_string_literal("a\u{1}b"), "\"a\\u0001b\"");
2983 }
2984}
2985
2986#[cfg(test)]
2987mod external_link_tests {
2988 use super::external_document_link as external;
2989 #[test]
2990 fn user_navigation_leaves_reader_but_loading_and_anchors_do_not() {
2991 let page = Some("file:///tmp/fixture.html");
2992 assert!(external(
2993 page,
2994 "https://example.test/story",
2995 true,
2996 false,
2997 false
2998 ));
2999 assert!(external(
3000 page,
3001 "https://example.test/story",
3002 true,
3003 true,
3004 false
3005 ));
3006 assert!(external(
3007 page,
3008 "https://example.test/story",
3009 false,
3010 true,
3011 false
3012 ));
3013 assert!(!external(
3014 page,
3015 "file:///tmp/fixture.html#note",
3016 true,
3017 false,
3018 false
3019 ));
3020 assert!(!external(
3021 page,
3022 "file:///tmp/next.html",
3023 false,
3024 false,
3025 false
3026 ));
3027 assert!(!external(
3028 page,
3029 "https://example.test/frame",
3030 true,
3031 false,
3032 true
3033 ));
3034 assert!(!external(page, "about:blank", false, true, false));
3035 assert!(external(
3036 Some("https://example.test/story?a=1#x"),
3037 "https://example.test/story?a=2",
3038 true,
3039 false,
3040 false
3041 ));
3042 }
3043}