1pub(crate) fn ua_styles_for_tag(tag: &str) -> &'static [(&'static str, &'static str)] {
5 match tag {
6 "h1" => &[
7 ("display", "block"),
8 ("font-size", "32"),
9 ("font-weight", "bold"),
10 ("margin-top", "21"),
11 ("margin-bottom", "21"),
12 ],
13 "h2" => &[
14 ("display", "block"),
15 ("font-size", "24"),
16 ("font-weight", "bold"),
17 ("margin-top", "20"),
18 ("margin-bottom", "20"),
19 ],
20 "h3" => &[
21 ("display", "block"),
22 ("font-size", "18"),
23 ("font-weight", "bold"),
24 ("margin-top", "18"),
25 ("margin-bottom", "18"),
26 ],
27 "p" => &[
28 ("display", "block"),
29 ("margin-top", "16"),
30 ("margin-bottom", "16"),
31 ],
32 "body" => &[
33 ("display", "block"),
34 ("margin", "8"),
35 ],
36 "ul" | "ol" => &[
40 ("display", "block"),
41 ("padding-left", "40px"),
42 ],
43 "li" => &[
44 ("display", "block"),
45 ],
46 "pre" => &[
47 ("display", "block"),
48 ("white-space", "pre"),
49 ("font-family", "monospace"),
50 ("background-color", "#f6f8fa"),
51 ("color", "#24292e"),
52 ("border-color", "#d0d7de"),
53 ("border-style", "solid"),
54 ("border-width", "1px"),
55 ("border-radius", "6px"),
56 ("padding", "12px"),
57 ("margin-top", "10px"),
58 ("margin-bottom", "10px"),
59 ],
60 "code" => &[
61 ("display", "inline"),
62 ("background-color", "#f0f0f0"),
63 ("color", "#d63384"),
64 ("padding", "2px 4px"),
65 ("border-radius", "3px"),
66 ],
67 "blockquote" => &[
68 ("display", "block"),
69 ("margin-left", "20px"),
70 ("margin-right", "20px"),
71 ("margin-top", "10px"),
72 ("margin-bottom", "10px"),
73 ("border-left", "4px solid #BD93F9"),
74 ],
75 "div" | "html" | "form" | "header" | "footer" | "main" | "section" | "nav"
76 | "hr" | "article" | "aside" | "figure" | "figcaption" | "fieldset" | "legend"
77 | "dl" | "dt" | "dd" | "details" | "summary" => &[
78 ("display", "block"),
79 ],
80 "select" | "video" | "audio" | "iframe" | "svg" | "canvas" => &[
81 ("display", "inline-block"),
82 ],
83 "center" => &[
84 ("display", "block"),
85 ("text-align", "center"),
86 ],
87 "img" => &[
88 ("display", "inline-block"),
89 ],
90 "a" => &[
91 ("display", "inline"),
92 ("text-decoration", "underline"),
93 ],
94 "strong" | "b" => &[
95 ("display", "inline"),
96 ("font-weight", "bold"),
97 ],
98 "em" | "i" => &[
99 ("display", "inline"),
100 ("font-style", "italic"),
101 ],
102 "u" => &[
103 ("display", "inline"),
104 ("text-decoration", "underline"),
105 ],
106 "s" | "del" | "strike" => &[
107 ("display", "inline"),
108 ("text-decoration", "line-through"),
109 ],
110 "input" | "button" => &[
111 ("display", "inline-block"),
112 ("border-radius", "6px"),
113 ("white-space", "nowrap"),
114 ],
115 "textarea" => &[
116 ("display", "inline-block"),
117 ("border-radius", "6px"),
118 ],
119 "table" => &[
120 ("display", "table"),
121 ("border-color", "#6272A4"),
122 ],
123 "thead" | "tbody" | "tfoot" => &[
124 ("display", "table-row-group"),
125 ],
126 "tr" => &[
127 ("display", "table-row"),
128 ],
129 "td" => &[
131 ("display", "table-cell"),
132 ("padding", "1px"),
133 ],
134 "th" => &[
135 ("display", "table-cell"),
136 ("padding", "1px"),
137 ("font-weight", "bold"),
138 ("text-align", "center"),
139 ],
140 "caption" => &[
141 ("display", "block"),
142 ("text-align", "center"),
143 ],
144 "head" | "title" | "meta" | "link" | "style" | "script" | "template"
145 | "noscript" => &[
146 ("display", "none"),
147 ],
148 _ => &[
149 ("display", "inline"),
150 ],
151 }
152}
153
154use super::*;
157
158
159#[inline]
173pub(crate) fn layout_poll() -> bool {
174 #[cfg(target_os = "none")]
175 return crate::kernel::window_mgr::layout_poll();
176 #[cfg(not(target_os = "none"))]
177 false
178}
179
180pub fn style_tree<'a>(root: &'a Node, stylesheet: &StyleSheet) -> StyledNode<'a> {
181 let rule_index = super::rule_index::RuleIndex::build(&stylesheet.rules);
184 style_tree_with_index(root, stylesheet, &rule_index)
185}
186
187pub fn style_tree_with_index<'a>(
191 root: &'a Node,
192 stylesheet: &StyleSheet,
193 rule_index: &super::rule_index::RuleIndex,
194) -> StyledNode<'a> {
195 crate::os_lib::css::units::set_root_font_px(crate::os_lib::css::units::ROOT_FONT_SIZE_PX);
197 let mut ancestors = Vec::new();
198 style_tree_with_ancestors_vars(
199 root,
200 stylesheet,
201 Some(rule_index),
202 &mut ancestors,
203 None,
204 None,
205 &alloc::rc::Rc::new(super::types::CssVars::default()),
206 &alloc::rc::Rc::new(BTreeMap::new()),
207 &BTreeMap::new(),
208 )
209 .0
210}
211
212pub fn style_tree_with_memo<'a>(
214 root: &'a Node,
215 stylesheet: &StyleSheet,
216 rule_index: &super::rule_index::RuleIndex,
217 memo: &mut super::style_memo::StyleMemo,
218) -> StyledNode<'a> {
219 crate::os_lib::css::units::set_root_font_px(crate::os_lib::css::units::ROOT_FONT_SIZE_PX);
220 memo.begin(rule_index as *const _ as usize);
221 let mut ancestors = Vec::new();
222 let empty: BTreeMap<String, i64> = BTreeMap::new();
223 let stack_init = crate::os_lib::css::counter_scope::CounterScopeStack::from_map(&empty);
224 let root_desc = super::style_memo::desc_key((0, 0), root, &[super::style_memo::children_shape(root)]);
226 let root_keys = super::style_memo::NodeKeys {
227 own: super::style_memo::child_key(root_desc, (0, 0), super::style_memo::children_shape(root)),
228 desc: root_desc,
229 };
230 let out = style_tree_with_ancestors_vars_stack(
231 root,
232 stylesheet,
233 Some(rule_index),
234 &mut ancestors,
235 None,
236 None,
237 &alloc::rc::Rc::new(super::types::CssVars::default()),
238 &alloc::rc::Rc::new(BTreeMap::new()),
239 &empty,
240 &stack_init,
241 Some(&mut *memo),
242 root_keys,
243 )
244 .0;
245 memo.end();
246 out
247}
248
249fn html_legacy_dimension_to_css(raw: &str) -> Option<String> {
253 let s = raw.trim();
254 if s.is_empty() {
255 return None;
256 }
257 if let Some(pct) = s.strip_suffix('%') {
258 let pct = pct.trim();
259 return pct.parse::<f32>().ok().map(|_| alloc::format!("{}%", pct));
260 }
261 let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();
262 if digits.is_empty() {
263 return None;
264 }
265 Some(alloc::format!("{}px", digits))
266}
267
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269pub(crate) struct ContainerName {
270 buf: [u8; 16],
271 len: u8,
272}
273
274impl ContainerName {
275 pub fn new(s: &str) -> Self {
276 let bytes = s.trim().as_bytes();
277 let len = bytes.len().min(16) as u8;
278 let mut buf = [0u8; 16];
279 buf[..len as usize].copy_from_slice(&bytes[..len as usize]);
280 Self { buf, len }
281 }
282
283 pub fn matches(&self, other: &str) -> bool {
284 let other_bytes = other.trim().as_bytes();
285 if other_bytes.len() != self.len as usize {
286 return false;
287 }
288 self.buf[..self.len as usize].eq_ignore_ascii_case(other_bytes)
289 }
290}
291
292#[derive(Debug, Clone, Copy)]
293pub(crate) struct AncestorContext<'a> {
294 pub(crate) node: &'a Node,
295 pub(crate) sibling_index: Option<usize>,
296 pub(crate) sibling_count: Option<usize>,
297 pub(crate) bloom: super::rule_index::AncestorBloom,
300 pub(crate) display: Option<&'static str>,
302 pub(crate) is_container: bool,
304 pub(crate) container_name: Option<ContainerName>,
306 pub(crate) container_size: Option<crate::os_lib::css::container_query::ContainerSize>,
308 pub(crate) in_disabled_fieldset: bool,
311}
312
313fn static_display(v: &str) -> Option<&'static str> {
315 const KNOWN: &[&str] = &[
316 "block", "inline", "inline-block", "flex", "inline-flex", "grid", "inline-grid",
317 "grid-lanes", "inline-grid-lanes", "none",
318 "contents", "table", "table-row", "table-cell", "list-item", "flow-root",
319 ];
320 let v = v.trim();
321 KNOWN.iter().copied().find(|k| *k == v)
322}
323
324#[inline]
325fn resolve_font_size_px(values: &mut BTreeMap<String, String>, parent_inherited: &BTreeMap<String, String>, is_root: bool) {
331 use crate::os_lib::css::units as css_units;
332 let px_of = |v: &str| v.trim().strip_suffix("px").and_then(|n| n.trim().parse::<f32>().ok());
333 let parent_px = parent_inherited
334 .get("font-size")
335 .and_then(|v| px_of(v))
336 .unwrap_or(css_units::ROOT_FONT_SIZE_PX);
337 let resolved = values.get("font-size").and_then(|v| {
338 let t = v.trim();
339 if t.ends_with("px") || t.contains('(') {
340 None
341 } else {
342 css_units::parse_font_size_with_parent(t, parent_px)
343 }
344 });
345 if let Some(px) = resolved {
346 values.insert(String::from("font-size"), alloc::format!("{}px", px));
347 }
348 if is_root {
349 if let Some(px) = values.get("font-size").and_then(|v| px_of(v)) {
350 css_units::set_root_font_px(px);
351 }
352 }
353}
354
355fn insert_ua_pairs(specified_values: &mut BTreeMap<String, String>, pairs: &[(&'static str, &'static str)]) {
356 for &(k, v) in pairs {
357 specified_values.insert(String::from(k), String::from(v));
358 }
359}
360
361fn cand_beats(new: &AppliedDecl<'_>, cur: &AppliedDecl<'_>) -> bool {
366 let (new_imp, new_layer, new_spec, new_order, _) = *new;
367 let (cur_imp, cur_layer, cur_spec, cur_order, _) = *cur;
368 if new_imp != cur_imp {
369 return new_imp;
370 }
371 let (cur_rank, new_rank) = if new_imp {
372 (cur_layer.map(|l| -(l as i64)).unwrap_or(i64::MIN), new_layer.map(|l| -(l as i64)).unwrap_or(i64::MIN))
373 } else {
374 (cur_layer.map(|l| l as i64).unwrap_or(i64::MAX), new_layer.map(|l| l as i64).unwrap_or(i64::MAX))
375 };
376 new_rank > cur_rank || (new_rank == cur_rank && (new_spec > cur_spec || (new_spec == cur_spec && new_order >= cur_order)))
377}
378
379fn pick_cascade_winner<'r>(mut list: alloc::vec::Vec<AppliedDecl<'r>>) -> Option<AppliedDecl<'r>> {
382 loop {
383 let mut best: Option<AppliedDecl<'r>> = None;
384 for c in list.iter() {
385 if best.as_ref().is_none_or(|b| cand_beats(c, b)) {
386 best = Some(*c);
387 }
388 }
389 let w = best?;
390 if w.4.trim().eq_ignore_ascii_case("revert-layer") {
391 list.retain(|c| !(c.0 == w.0 && c.1 == w.1));
392 continue;
393 }
394 return Some(w);
395 }
396}
397
398fn resolve_revert_layer_and_all<'r>(
403 cands: alloc::vec::Vec<(alloc::borrow::Cow<'r, str>, AppliedDecl<'r>)>,
404 applied: &mut AppliedMap<'r>,
405) -> bool {
406 let mut all_list: alloc::vec::Vec<AppliedDecl<'r>> = alloc::vec::Vec::new();
407 let mut by_key: BTreeMap<alloc::borrow::Cow<'r, str>, alloc::vec::Vec<AppliedDecl<'r>>> = BTreeMap::new();
408 for (k, c) in cands {
409 if k == "all" {
410 all_list.push(c);
411 } else {
412 by_key.entry(k).or_default().push(c);
413 }
414 }
415 let all_applies = |k: &str| !k.starts_with("--") && k != "direction" && k != "unicode-bidi" && !k.starts_with("x-");
417 for (k, mut list) in by_key {
418 if all_applies(&k) {
419 list.extend(all_list.iter().copied());
420 }
421 if let Some(w) = pick_cascade_winner(list) {
422 applied.insert(k, w);
423 }
424 }
425 match pick_cascade_winner(all_list) {
426 Some(w) => matches!(w.4.trim().to_ascii_lowercase().as_str(), "unset" | "initial"),
427 None => false,
428 }
429}
430
431pub(crate) type AppliedDecl<'r> = (bool, Option<usize>, (u32, u32, u32), usize, &'r str);
432type AppliedMap<'r> = indexmap::IndexMap<
435 alloc::borrow::Cow<'r, str>,
436 AppliedDecl<'r>,
437 core::hash::BuildHasherDefault<crate::os_lib::util::fnv::FnvHasher>,
438>;
439
440pub(crate) const BOX_SHORTHANDS: &[(&str, [&str; 4])] = &[
443 ("margin", ["margin-top", "margin-right", "margin-bottom", "margin-left"]),
444 ("padding", ["padding-top", "padding-right", "padding-bottom", "padding-left"]),
445 (
446 "border-width",
447 ["border-top-width", "border-right-width", "border-bottom-width", "border-left-width"],
448 ),
449 ("inset", ["top", "right", "bottom", "left"]),
450];
451
452fn is_border_cascade_key(k: &str) -> bool {
454 let Some(rest) = k.strip_prefix("border") else {
455 return false;
456 };
457 let rest = rest.strip_prefix('-').unwrap_or(rest);
458 if k == "border" {
459 return true;
460 }
461 if matches!(rest, "width" | "style" | "color" | "top" | "right" | "bottom" | "left") {
462 return true;
463 }
464 for side in ["top-", "right-", "bottom-", "left-"] {
465 if let Some(p) = rest.strip_prefix(side) {
466 return matches!(p, "width" | "style" | "color");
467 }
468 }
469 false
470}
471
472pub(crate) fn decl_outranks(a: &AppliedDecl<'_>, b: &AppliedDecl<'_>) -> bool {
474 if a.0 != b.0 {
475 return a.0;
476 }
477 if a.0 {
478 let ar = a.1.map(|l| -(l as i64)).unwrap_or(i64::MIN);
479 let br = b.1.map(|l| -(l as i64)).unwrap_or(i64::MIN);
480 ar > br || (ar == br && (a.2 > b.2 || (a.2 == b.2 && a.3 >= b.3)))
481 } else {
482 let ar = a.1.map(|l| l as i64).unwrap_or(i64::MAX);
483 let br = b.1.map(|l| l as i64).unwrap_or(i64::MAX);
484 ar > br || (ar == br && (a.2 > b.2 || (a.2 == b.2 && a.3 >= b.3)))
485 }
486}
487
488fn drop_overridden_longhands(
500 applied: &mut AppliedMap<'_>,
501 specified_values: &mut BTreeMap<String, String>,
502) {
503 for (short, longs) in BOX_SHORTHANDS {
504 let Some(sh) = applied.get(*short) else {
505 continue;
506 };
507 let sh_rank: AppliedDecl<'_> = (sh.0, sh.1, sh.2, sh.3, "");
508 for long in longs {
509 specified_values.remove(*long);
510 let long_loses = applied.get(*long).is_some_and(|l| !decl_outranks(l, &sh_rank));
511 if long_loses {
512 applied.swap_remove(*long);
513 }
514 }
515 }
516}
517
518pub(crate) fn compute_styles<'a>(
519 root: &'a Node,
520 stylesheet: &StyleSheet,
521 ancestors: &[AncestorContext<'a>],
522 sibling_index: Option<usize>,
523 sibling_count: Option<usize>,
524 active_pseudo_states: &[&str],
525) -> BTreeMap<String, String> {
526 let (vals, _, _, _) = compute_styles_with_vars(
527 root,
528 stylesheet,
529 None,
530 ancestors,
531 sibling_index,
532 sibling_count,
533 active_pseudo_states,
534 &alloc::rc::Rc::new(super::types::CssVars::default()),
535 &BTreeMap::new(),
536 None,
537 );
538 vals
539}
540
541pub(crate) fn compute_styles_with_vars<'a>(
546 root: &'a Node,
547 stylesheet: &StyleSheet,
548 rule_index: Option<&super::rule_index::RuleIndex>,
549 ancestors: &[AncestorContext<'a>],
550 sibling_index: Option<usize>,
551 sibling_count: Option<usize>,
552 active_pseudo_states: &[&str],
553 parent_vars: &alloc::rc::Rc<super::types::CssVars>,
554 counters_in: &BTreeMap<String, i64>,
555 type_position: Option<(Option<usize>, Option<usize>)>,
556) -> (
557 BTreeMap<String, String>,
558 alloc::rc::Rc<super::types::CssVars>,
559 BTreeMap<String, i64>,
560 alloc::collections::BTreeSet<String>,
561) {
562 compute_styles_with_vars_stack(
563 root,
564 stylesheet,
565 rule_index,
566 ancestors,
567 sibling_index,
568 sibling_count,
569 active_pseudo_states,
570 parent_vars,
571 counters_in,
572 None,
573 type_position,
574 )
575}
576
577pub(crate) fn compute_styles_with_vars_stack<'a>(
578 root: &'a Node,
579 stylesheet: &StyleSheet,
580 rule_index: Option<&super::rule_index::RuleIndex>,
581 ancestors: &[AncestorContext<'a>],
582 sibling_index: Option<usize>,
583 sibling_count: Option<usize>,
584 active_pseudo_states: &[&str],
585 parent_vars: &alloc::rc::Rc<super::types::CssVars>,
586 counters_in: &BTreeMap<String, i64>,
587 counter_stack: Option<&crate::os_lib::css::counter_scope::CounterScopeStack>,
588 type_position: Option<(Option<usize>, Option<usize>)>,
590) -> (
591 BTreeMap<String, String>,
592 alloc::rc::Rc<super::types::CssVars>,
593 BTreeMap<String, i64>,
594 alloc::collections::BTreeSet<String>,
595) {
596 let mut specified_values = BTreeMap::new();
597 let mut own_vars: BTreeMap<String, String> = BTreeMap::new();
606 let mut counters_out = if counters_in.is_empty() {
607 BTreeMap::new()
608 } else {
609 counters_in.clone()
610 };
611 let mut counters_reset_names = alloc::collections::BTreeSet::new();
612
613 match &root.node_type {
614 NodeType::Element {
615 tag_name,
616 attributes,
617 classes: _,
618 id: _,
619 } => {
620 let ua_styles = ua_styles_for_tag(tag_name.as_str());
621 let is_ol = tag_name.eq_ignore_ascii_case("ol");
622 if is_ol || tag_name.eq_ignore_ascii_case("ul") {
623 let start_attr = if is_ol {
624 attributes.get("start").and_then(|s| s.trim().parse::<i64>().ok())
625 } else {
626 None
627 };
628 let reversed = is_ol && attributes.contains_key("reversed");
629 let start_val = if reversed {
630 let li_count = root
631 .children
632 .iter()
633 .filter(|c| {
634 matches!(&c.node_type, NodeType::Element { tag_name, .. } if tag_name.eq_ignore_ascii_case("li"))
635 })
636 .count() as i64;
637 start_attr.unwrap_or(li_count) + 1
638 } else {
639 start_attr.map(|n| n - 1).unwrap_or(0)
640 };
641 specified_values.insert(
642 String::from("counter-reset"),
643 alloc::format!("list-item {start_val}"),
644 );
645 } else if tag_name.eq_ignore_ascii_case("li") {
646 let parent_reversed = ancestors.last().is_some_and(|a| {
647 matches!(&a.node.node_type, NodeType::Element { tag_name, attributes, .. }
648 if tag_name.eq_ignore_ascii_case("ol") && attributes.contains_key("reversed"))
649 });
650 let incr = if parent_reversed { "list-item -1" } else { "list-item" };
651 specified_values.insert(String::from("counter-increment"), String::from(incr));
652 } else if tag_name.as_str() == "dialog" {
653 if !attributes.contains_key("open") {
654 specified_values.insert(String::from("display"), String::from("none"));
655 } else if attributes.contains_key("_modal") {
656 specified_values.insert(String::from("position"), String::from("fixed"));
658 specified_values.insert(String::from("top"), String::from("0"));
659 specified_values.insert(String::from("bottom"), String::from("0"));
660 specified_values.insert(String::from("left"), String::from("0"));
661 specified_values.insert(String::from("right"), String::from("0"));
662 specified_values.insert(String::from("margin"), String::from("auto"));
663 specified_values.insert(String::from("z-index"), String::from("2147483647"));
664 specified_values.insert(String::from("background-color"), String::from("#ffffff"));
665 specified_values.insert(String::from("border"), String::from("1px solid #000000"));
666 specified_values.insert(String::from("x-backdrop-background"), String::from("rgba(0, 0, 0, 0.32)"));
667 }
668 } else if tag_name.as_str() == "a" && attributes.contains_key("href") {
669 specified_values.insert(String::from("color"), String::from("-webkit-link"));
670 specified_values.insert(String::from("cursor"), String::from("pointer"));
671 } else if matches!(tag_name.as_str(), "button" | "summary") {
672 specified_values.insert(String::from("cursor"), String::from("pointer"));
673 } else if tag_name.as_str() == "textarea" {
674 specified_values.insert(String::from("cursor"), String::from("text"));
675 } else if tag_name.as_str() == "input" {
676 let input_type = attributes.get("type").map(|s| s.to_ascii_lowercase()).unwrap_or_else(|| String::from("text"));
677 if matches!(input_type.as_str(), "button" | "submit" | "reset") {
678 specified_values.insert(String::from("cursor"), String::from("pointer"));
679 } else if !matches!(input_type.as_str(), "hidden" | "checkbox" | "radio" | "range" | "color" | "file") {
680 specified_values.insert(String::from("cursor"), String::from("text"));
681 }
682 }
683
684 if matches!(
695 tag_name.as_str(),
696 "img" | "iframe" | "video" | "embed" | "object"
697 ) {
698 if let Some(w) = attributes.get("width").and_then(|v| html_legacy_dimension_to_css(v)) {
699 specified_values.insert(String::from("width"), w);
700 }
701 if let Some(h) = attributes.get("height").and_then(|v| html_legacy_dimension_to_css(v)) {
702 specified_values.insert(String::from("height"), h);
703 }
704 }
705
706 if attributes.contains_key("hidden") {
711 specified_values.insert(String::from("display"), String::from("none"));
712 }
713
714 if attributes.contains_key("popover") && !attributes.contains_key("_popover_open") {
721 specified_values.insert(String::from("display"), String::from("none"));
722 }
723
724 if let Some(parent_ctx) = ancestors.last() {
726 if let NodeType::Element { tag_name: parent_tag, attributes: parent_attrs, .. } = &parent_ctx.node.node_type {
727 if parent_tag == "details" && !parent_attrs.contains_key("open") {
728 let mut first_summary_idx = None;
730 for (idx, child) in parent_ctx.node.children.iter().enumerate() {
731 if let NodeType::Element { tag_name: child_tag, .. } = &child.node_type {
732 if child_tag == "summary" {
733 first_summary_idx = Some(idx);
734 break;
735 }
736 }
737 }
738
739 let is_first_summary = if let Some(fs_idx) = first_summary_idx {
740 sibling_index == Some(fs_idx)
741 } else {
742 false
743 };
744
745 if !is_first_summary {
746 specified_values.insert(String::from("display"), String::from("none"));
747 }
748 }
749 }
750 }
751
752 if attributes.contains_key("inert") {
761 specified_values.insert(String::from("pointer-events"), String::from("none"));
762 }
763
764 if let Some(dv) = attributes.get("dir").map(|v| v.trim().to_lowercase()) {
770 if dv == "ltr" || dv == "rtl" {
771 specified_values.insert(String::from("direction"), dv);
772 }
773 }
774
775 let mut applied: AppliedMap<'_> = AppliedMap::default();
778
779 let node_ctx = crate::os_lib::css::selector::NodeMatchContext::with_type_position(
786 root,
787 ancestors,
788 sibling_index,
789 type_position,
790 );
791
792 let mut rule_orders: alloc::vec::Vec<usize> = alloc::vec::Vec::new();
799 if let NodeType::Element {
801 tag_name,
802 classes,
803 id,
804 attributes,
805 } = &root.node_type
806 {
807 {
808 if let Some(idx) = rule_index {
809 if idx
810 .candidates_into_with_attrs(
811 tag_name.as_str(),
812 id.as_deref(),
813 classes.as_slice(),
814 attributes.keys().map(String::as_str),
815 &mut rule_orders,
816 )
817 .is_err()
818 {
819 rule_orders.extend(0..stylesheet.rules.len());
820 }
821 } else {
822 rule_orders.extend(0..stylesheet.rules.len());
823 }
824 }
825 }
826
827 let parent_bloom = ancestors.last().map(|a| a.bloom).unwrap_or_default();
828 let mut need_slow = false;
832 let mut collect = false;
833 let mut cands: alloc::vec::Vec<(alloc::borrow::Cow<'_, str>, AppliedDecl<'_>)> = alloc::vec::Vec::new();
834 loop {
835 for &rule_order in rule_orders.iter() {
836 let rule = &stylesheet.rules[rule_order];
837 if let Some(q) = &rule.media_query {
844 if !crate::os_lib::css::media_query_matches(q) {
845 continue;
846 }
847 }
848 if let Some(q) = &rule.container_query {
858 let mut cw = crate::os_lib::viewport::CONTAINER_HINT_W
859 .load(core::sync::atomic::Ordering::Relaxed);
860 let mut ch = crate::os_lib::viewport::CONTAINER_HINT_H
861 .load(core::sync::atomic::Ordering::Relaxed);
862 if cw <= 0 {
863 cw = crate::os_lib::viewport::VIEWPORT_HINT_W
864 .load(core::sync::atomic::Ordering::Relaxed);
865 }
866 if ch <= 0 {
867 ch = crate::os_lib::viewport::VIEWPORT_HINT_H
868 .load(core::sync::atomic::Ordering::Relaxed);
869 }
870 let default_size = crate::os_lib::css::container_query::ContainerSize {
871 width: cw,
872 height: ch,
873 };
874 let all_ok = q.split("&&").all(|one| {
876 let (name_opt, cond) = if let Some((n, c)) = one.split_once('|') {
878 let n = n.trim();
879 (if n.is_empty() { None } else { Some(n) }, c)
880 } else {
881 (None, one)
882 };
883
884 let target_size = ancestors.iter().rev().find_map(|a| {
886 if !a.is_container {
887 return None;
888 }
889 if let Some(q_name) = name_opt {
890 if a.container_name.is_some_and(|cn| cn.matches(q_name)) {
891 return a.container_size;
892 }
893 None
894 } else {
895 a.container_size
896 }
897 }).unwrap_or(default_size);
898
899 crate::os_lib::css::container_query::condition_matches(cond, target_size)
900 });
901 if !all_ok {
902 continue;
903 }
904 }
905 let mut m0: Option<((u32, u32, u32), Option<PseudoElement>)> = None;
910 let mut m_more: alloc::vec::Vec<((u32, u32, u32), Option<PseudoElement>)> = alloc::vec::Vec::new();
911 for (sel_i, selector) in rule.selectors.iter().enumerate() {
912 if let Some(idx) = rule_index {
914 if !idx.ancestors_may_match(rule_order, sel_i, &parent_bloom) {
915 continue;
916 }
917 }
918 if matches_selector(
919 selector,
920 root,
921 ancestors,
922 sibling_index,
923 sibling_count,
924 active_pseudo_states,
925 &node_ctx,
926 ) {
927 let spec = selector_specificity(selector);
928 let pe = selector_pseudo_element(selector);
929 match m0.as_mut() {
930 None => m0 = Some((spec, pe)),
931 Some(slot) if slot.1 == pe => {
932 if spec > slot.0 {
933 slot.0 = spec;
934 }
935 }
936 Some(_) => match m_more.iter_mut().find(|(_, p)| *p == pe) {
937 Some(slot) => {
938 if spec > slot.0 {
939 slot.0 = spec;
940 }
941 }
942 None => m_more.push((spec, pe)),
943 },
944 }
945 }
946 }
947 for (spec, matched_pseudo_el) in m0.into_iter().chain(m_more) {
948 for (decl_i, decl) in rule.declarations.iter().enumerate() {
957 let decl_order = (rule_order << 10) | decl_i.min(1023);
960 let key: Option<alloc::borrow::Cow<'_, str>> = match matched_pseudo_el {
961 Some(PseudoElement::Before) => {
965 Some(alloc::borrow::Cow::Owned(alloc::format!("x-before-{}", decl.name)))
966 }
967 Some(PseudoElement::After) => {
968 Some(alloc::borrow::Cow::Owned(alloc::format!("x-after-{}", decl.name)))
969 }
970 Some(PseudoElement::Marker) => {
971 matches!(decl.name.as_str(), "color" | "font-size" | "content")
972 .then(|| alloc::borrow::Cow::Owned(alloc::format!("x-marker-{}", decl.name)))
973 }
974 Some(PseudoElement::Placeholder) => {
975 (decl.name == "color").then_some(alloc::borrow::Cow::Borrowed("x-placeholder-color"))
976 }
977 Some(PseudoElement::FirstLine) => matches!(
978 decl.name.as_str(),
979 "color" | "font-size" | "font-weight" | "font-style"
980 )
981 .then(|| alloc::borrow::Cow::Owned(alloc::format!("x-first-line-{}", decl.name))),
982 Some(PseudoElement::FirstLetter) => matches!(
983 decl.name.as_str(),
984 "color" | "font-size" | "font-weight" | "font-style"
985 )
986 .then(|| alloc::borrow::Cow::Owned(alloc::format!("x-first-letter-{}", decl.name))),
987 Some(PseudoElement::Selection) => matches!(
988 decl.name.as_str(),
989 "color" | "background-color" | "background"
990 )
991 .then(|| alloc::borrow::Cow::Owned(alloc::format!("x-selection-{}", decl.name))),
992 Some(PseudoElement::Backdrop) => {
993 Some(alloc::borrow::Cow::Owned(alloc::format!("x-backdrop-{}", decl.name)))
994 }
995 None => Some(alloc::borrow::Cow::Borrowed(decl.name.as_str())),
996 };
997 let Some(key) = key else {
998 continue;
999 };
1000 if collect {
1001 cands.push((key, (decl.important, rule.layer, spec, decl_order, decl.value.as_str())));
1002 continue;
1003 }
1004 if !need_slow
1005 && ((decl.name.len() == 3 && decl.name == "all")
1006 || (decl.value.len() == 12 && decl.value.eq_ignore_ascii_case("revert-layer")))
1007 {
1008 need_slow = true;
1009 }
1010 let should_replace = match applied.get(key.as_ref()) {
1011 Some((cur_imp, cur_layer, cur_spec, cur_order, _)) => {
1012 if decl.important != *cur_imp {
1013 decl.important } else if decl.important {
1015 let cur_rank = cur_layer.map(|l| -(l as i64)).unwrap_or(i64::MIN);
1017 let new_rank = rule.layer.map(|l| -(l as i64)).unwrap_or(i64::MIN);
1018 new_rank > cur_rank
1019 || (new_rank == cur_rank
1020 && (spec > *cur_spec
1021 || (spec == *cur_spec && decl_order >= *cur_order)))
1022 } else {
1023 let cur_rank = cur_layer.map(|l| l as i64).unwrap_or(i64::MAX);
1026 let new_rank = rule.layer.map(|l| l as i64).unwrap_or(i64::MAX);
1027 new_rank > cur_rank
1028 || (new_rank == cur_rank
1029 && (spec > *cur_spec
1030 || (spec == *cur_spec && decl_order >= *cur_order)))
1031 }
1032 }
1033 None => true,
1034 };
1035 if should_replace {
1036 applied.insert(key, (decl.important, rule.layer, spec, decl_order, decl.value.as_str()));
1040 }
1041 }
1042 }
1043 }
1044 if need_slow && !collect {
1045 collect = true;
1046 applied.clear();
1047 continue;
1048 }
1049 break;
1050 }
1051 let mut all_reset = false;
1052 if collect {
1053 all_reset = resolve_revert_layer_and_all(core::mem::take(&mut cands), &mut applied);
1054 if all_reset {
1055 specified_values.clear();
1057 }
1058 }
1059 drop_overridden_longhands(&mut applied, &mut specified_values);
1064 let mut important_keys: alloc::collections::BTreeSet<alloc::borrow::Cow<'_, str>> =
1065 alloc::collections::BTreeSet::new();
1066 for (k, (is_important, _, _, _, _)) in &applied {
1067 if *is_important {
1068 important_keys.insert(k.clone());
1069 }
1070 }
1071 let mut border_ranks: alloc::vec::Vec<(String, AppliedDecl<'static>)> = alloc::vec::Vec::new();
1074 let mut applied: alloc::vec::Vec<_> = applied.into_iter().collect();
1075 applied.sort_by_key(|(k, _)| !k.starts_with("--"));
1076 for (k, (imp, layer, spec, ord, v)) in applied {
1077 if is_border_cascade_key(k.as_ref()) {
1078 border_ranks.push((String::from(k.as_ref()), (imp, layer, spec, ord, "")));
1079 }
1080 if k.starts_with("--") {
1081 if (super::types::VarsView { own: &own_vars, parent: parent_vars }).get(k.as_ref()).map(String::as_str) != Some(v) {
1085 own_vars.insert(k.into_owned(), String::from(v));
1086 }
1087 } else {
1088 let resolved = if v.contains("var(") {
1089 resolve_css_var(v, &super::types::VarsView { own: &own_vars, parent: parent_vars })
1090 } else {
1091 String::from(v)
1092 };
1093 let resolved = if resolved.contains("env(") {
1094 resolve_css_env(&resolved)
1095 } else {
1096 resolved
1097 };
1098 let resolved = if k.as_ref() != "content" && resolved.to_ascii_lowercase().contains("attr(") {
1099 super::values::resolve_css_attr(&resolved, attributes)
1100 } else {
1101 resolved
1102 };
1103 let resolved = if resolved.to_ascii_lowercase().contains("random-item(") {
1104 super::values::resolve_random_item(&resolved)
1105 } else {
1106 resolved
1107 };
1108 let resolved = if k.as_ref() == "margin-trim" {
1109 super::values::normalize_margin_trim(&resolved)
1110 } else {
1111 resolved
1112 };
1113 specified_values.insert(k.into_owned(), resolved);
1114 }
1115 }
1116
1117 for &(k, v) in ua_styles.iter().filter(|_| !all_reset) {
1121 if !specified_values.contains_key(k) {
1122 let covered_by_shorthand = match k {
1123 "margin-top" | "margin-right" | "margin-bottom" | "margin-left" => {
1124 specified_values.contains_key("margin")
1125 }
1126 "padding-top" | "padding-right" | "padding-bottom" | "padding-left" => {
1127 specified_values.contains_key("padding")
1128 }
1129 "border-top-width" | "border-right-width" | "border-bottom-width" | "border-left-width" => {
1130 specified_values.contains_key("border-width")
1131 }
1132 _ => false,
1133 };
1134 if !covered_by_shorthand {
1135 specified_values.insert(String::from(k), String::from(v));
1136 }
1137 }
1138 }
1139
1140 if let Some(style_attr) = attributes.get("style") {
1141 for (inline_i, decl) in style_attr.split(';').enumerate() {
1142 let mut parts = decl.splitn(2, ':');
1143 if let (Some(k), Some(v)) = (parts.next(), parts.next()) {
1144 let k_trim = k.trim().to_string();
1145 let raw_value = v.trim();
1146 let (v_trim, inline_important) = match raw_value.rfind('!') {
1148 Some(pos)
1149 if raw_value
1150 .get(pos + 1..)
1151 .unwrap_or("")
1152 .trim()
1153 .eq_ignore_ascii_case("important") =>
1154 {
1155 (
1156 String::from(raw_value.get(..pos).unwrap_or("").trim()),
1157 true,
1158 )
1159 }
1160 _ => (String::from(raw_value), false),
1161 };
1162 if v_trim.is_empty() && !k_trim.starts_with("--") {
1166 continue;
1167 }
1168 if !k_trim.starts_with("--") && !declaration_value_valid(&k_trim, &v_trim) {
1170 continue;
1171 }
1172 if !k_trim.is_empty() {
1173 if important_keys.contains(k_trim.as_str()) && !inline_important {
1176 continue;
1177 }
1178 if k_trim.starts_with("--") {
1179 if (super::types::VarsView { own: &own_vars, parent: parent_vars }).get(&k_trim) != Some(&v_trim) {
1180 own_vars.insert(k_trim, v_trim);
1181 }
1182 } else {
1183 let resolved = if v_trim.contains("var(") {
1184 resolve_css_var(&v_trim, &super::types::VarsView { own: &own_vars, parent: parent_vars })
1185 } else {
1186 v_trim
1187 };
1188 let resolved = if resolved.contains("env(") {
1189 resolve_css_env(&resolved)
1190 } else {
1191 resolved
1192 };
1193 let resolved = if k_trim != "content" && resolved.to_ascii_lowercase().contains("attr(") {
1194 super::values::resolve_css_attr(&resolved, attributes)
1195 } else {
1196 resolved
1197 };
1198 let resolved = if resolved.to_ascii_lowercase().contains("random-item(") {
1199 super::values::resolve_random_item(&resolved)
1200 } else {
1201 resolved
1202 };
1203 if let Some((_, longs)) =
1206 BOX_SHORTHANDS.iter().find(|(sh, _)| *sh == k_trim.as_str())
1207 {
1208 for long in longs {
1209 if !important_keys.contains(*long) {
1210 specified_values.remove(*long);
1211 }
1212 }
1213 }
1214 if is_border_cascade_key(&k_trim) {
1215 let rank: AppliedDecl<'static> = (
1217 inline_important,
1218 None,
1219 (u32::MAX, u32::MAX, u32::MAX),
1220 (usize::MAX >> 1) + inline_i,
1221 "",
1222 );
1223 if let Some(e) = border_ranks.iter_mut().find(|(bk, _)| *bk == k_trim) {
1224 e.1 = rank;
1225 } else {
1226 border_ranks.push((k_trim.clone(), rank));
1227 }
1228 }
1229 let resolved = if k_trim == "margin-trim" {
1230 super::values::normalize_margin_trim(&resolved)
1231 } else {
1232 resolved
1233 };
1234 if resolved.trim().eq_ignore_ascii_case("revert-layer") {
1236 continue;
1237 }
1238 specified_values.insert(k_trim, resolved);
1239 }
1240 }
1241 }
1242 }
1243 }
1244 expand_border_shorthands(&mut specified_values, &border_ranks);
1245 expand_place_shorthands(&mut specified_values);
1246 expand_flex_flow_shorthand(&mut specified_values);
1247 expand_grid_shorthand(&mut specified_values);
1248 expand_grid_template_shorthand(&mut specified_values);
1249 expand_text_emphasis_shorthand(&mut specified_values);
1250 expand_font_shorthand(&mut specified_values);
1251 expand_background_shorthand(&mut specified_values);
1252 expand_container_shorthand(&mut specified_values);
1253
1254 if !stylesheet.keyframes.is_empty()
1256 && (specified_values.contains_key("animation")
1257 || specified_values.contains_key("animation-name"))
1258 {
1259 let mut anim_specs = if let Some(anim) = specified_values.get("animation") {
1260 super::animation::parse_animations(anim)
1261 } else {
1262 alloc::vec::Vec::new()
1263 };
1264 if let Some(name) = specified_values.get("animation-name") {
1265 anim_specs.extend(super::animation::resolve_animation_specs(
1266 Some(name.as_str()),
1267 specified_values.get("animation-duration").map(String::as_str),
1268 specified_values.get("animation-timing-function").map(String::as_str),
1269 specified_values.get("animation-delay").map(String::as_str),
1270 specified_values.get("animation-iteration-count").map(String::as_str),
1271 specified_values.get("animation-direction").map(String::as_str),
1272 specified_values.get("animation-fill-mode").map(String::as_str),
1273 specified_values.get("animation-play-state").map(String::as_str),
1274 ));
1275 }
1276 for spec in anim_specs {
1277 if let Some(kf) = stylesheet.keyframes.iter().rfind(|k| k.name == spec.name) {
1278 let sampled = super::animation::sample_animation(&spec, kf, 0.0);
1279 for (prop, val) in sampled {
1280 if important_keys.contains(prop.as_str()) {
1281 continue;
1282 }
1283 if val.trim().eq_ignore_ascii_case("revert-layer") {
1284 continue;
1285 }
1286 specified_values.insert(prop, val);
1287 }
1288 }
1289 }
1290 }
1291
1292 counters_reset_names = apply_counter_decls(&specified_values, &mut counters_out);
1295 let mut stack_buf;
1296 let current_stack = if let Some(st) = counter_stack {
1297 stack_buf = st.clone();
1298 crate::os_lib::css::counter_scope::apply_counter_decls_to_stack(&specified_values, &mut stack_buf);
1299 Some(&stack_buf)
1300 } else {
1301 None
1302 };
1303 let quotes_pairs = specified_values
1307 .get("quotes")
1308 .and_then(|v| parse_quotes_pairs(v));
1309 let has_generated_content = ["x-before-content", "x-after-content", "x-marker-content"]
1317 .iter()
1318 .any(|k| specified_values.contains_key(*k));
1319 let quote_depth = if has_generated_content {
1320 ancestors
1321 .iter()
1322 .filter(|a| {
1323 matches!(&a.node.node_type, NodeType::Element { tag_name, .. } if tag_name == "q")
1324 })
1325 .count()
1326 } else {
1327 0
1328 };
1329 for key in ["x-before-content", "x-after-content", "x-marker-content"] {
1330 if let Some(raw) = specified_values.get(key).cloned() {
1331 if key != "x-marker-content"
1334 && matches!(raw.trim().to_ascii_lowercase().as_str(), "none" | "normal")
1335 {
1336 specified_values.remove(key);
1337 continue;
1338 }
1339 let resolved = crate::os_lib::css::selector::parse_content_value_with_stack(
1340 &raw,
1341 attributes,
1342 &counters_out,
1343 current_stack,
1344 quotes_pairs.as_deref(),
1345 quote_depth,
1346 &stylesheet.counter_styles,
1347 );
1348 specified_values.insert(String::from(key), resolved);
1349 }
1350 }
1351 }
1352 NodeType::Text(_) => {
1353 specified_values.insert(String::from("display"), String::from("inline"));
1354 }
1355 }
1356 let css_vars = if own_vars.is_empty() {
1357 parent_vars.clone()
1358 } else {
1359 alloc::rc::Rc::new(super::types::CssVars::layered(parent_vars, own_vars))
1360 };
1361 (specified_values, css_vars, counters_out, counters_reset_names)
1362}
1363
1364pub(crate) const INHERITED_PROPS: &[&str] = &[
1366 "color",
1367 "-webkit-text-fill-color",
1368 "font-family",
1376 "font-size",
1377 "font-weight",
1378 "font-style",
1379 "line-height",
1380 "text-align",
1381 "letter-spacing",
1382 "word-spacing",
1383 "white-space",
1384 "text-transform",
1385 "list-style-type",
1386 "list-style-image",
1387 "list-style-position",
1388 "list-style",
1389 "tab-size",
1390 "direction",
1391 "writing-mode",
1393 "visibility",
1394 "text-indent",
1399 "border-collapse",
1403 "text-emphasis-style",
1405 "text-emphasis-color",
1406 "cursor",
1408 "word-break",
1410 "overflow-wrap",
1411 "word-wrap",
1412 "fill",
1415];
1416
1417pub(crate) fn style_tree_with_ancestors<'a>(
1418 root: &'a Node,
1419 stylesheet: &StyleSheet,
1420 ancestors: &[AncestorContext<'a>],
1421 sibling_index: Option<usize>,
1422 sibling_count: Option<usize>,
1423) -> StyledNode<'a> {
1424 let mut stack = ancestors.to_vec();
1425 style_tree_with_ancestors_vars(
1426 root,
1427 stylesheet,
1428 None,
1429 &mut stack,
1430 sibling_index,
1431 sibling_count,
1432 &alloc::rc::Rc::new(super::types::CssVars::default()),
1433 &alloc::rc::Rc::new(BTreeMap::new()),
1434 &BTreeMap::new(),
1435 )
1436 .0
1437}
1438
1439pub(crate) fn style_tree_with_ancestors_vars<'a>(
1443 root: &'a Node,
1444 stylesheet: &StyleSheet,
1445 rule_index: Option<&super::rule_index::RuleIndex>,
1446 ancestors_stack: &mut Vec<AncestorContext<'a>>,
1447 sibling_index: Option<usize>,
1448 sibling_count: Option<usize>,
1449 parent_vars: &alloc::rc::Rc<super::types::CssVars>,
1450 parent_inherited: &alloc::rc::Rc<BTreeMap<String, String>>,
1451 counters_in: &BTreeMap<String, i64>,
1452) -> (StyledNode<'a>, BTreeMap<String, i64>, alloc::collections::BTreeSet<String>) {
1453 let stack_init = crate::os_lib::css::counter_scope::CounterScopeStack::from_map(counters_in);
1454 let (node, counters_out, resets, _final_stack) = style_tree_with_ancestors_vars_stack(
1455 root,
1456 stylesheet,
1457 rule_index,
1458 ancestors_stack,
1459 sibling_index,
1460 sibling_count,
1461 parent_vars,
1462 parent_inherited,
1463 counters_in,
1464 &stack_init,
1465 None,
1466 super::style_memo::NodeKeys::default(),
1467 );
1468 (node, counters_out, resets)
1469}
1470
1471#[inline]
1472fn resolve_node_state_bits(
1473 node: &Node,
1474 idx: &super::rule_index::RuleIndex,
1475 memo: Option<&mut super::style_memo::StyleMemo>,
1476) -> u8 {
1477 let NodeType::Element {
1478 tag_name,
1479 id,
1480 classes,
1481 attributes,
1482 } = &node.node_type
1483 else {
1484 return super::rule_index::STATE_INVALID;
1485 };
1486 if let Some(cached) = memo.as_ref().and_then(|m| m.get_state_bits(&node.features_hash)) {
1487 return cached;
1488 }
1489 let mut c = Vec::new();
1490 let bits = match idx.candidates_into_with_attrs(
1491 tag_name.as_str(),
1492 id.as_deref(),
1493 classes.as_slice(),
1494 attributes.keys().map(String::as_str),
1495 &mut c,
1496 ) {
1497 Ok(()) => match idx.states_of(&c) {
1498 Some(b) => b,
1499 None => super::rule_index::STATE_INVALID,
1500 },
1501 Err(_) => super::rule_index::STATE_INVALID,
1502 };
1503 if let Some(m) = memo {
1504 m.put_state_bits(node.features_hash, bits);
1505 }
1506 bits
1507}
1508
1509pub(crate) fn style_tree_with_ancestors_vars_stack<'a>(
1510 root: &'a Node,
1511 stylesheet: &StyleSheet,
1512 rule_index: Option<&super::rule_index::RuleIndex>,
1513 ancestors_stack: &mut Vec<AncestorContext<'a>>,
1514 sibling_index: Option<usize>,
1515 sibling_count: Option<usize>,
1516 parent_vars: &alloc::rc::Rc<super::types::CssVars>,
1517 parent_inherited: &alloc::rc::Rc<BTreeMap<String, String>>,
1518 counters_in: &BTreeMap<String, i64>,
1519 counter_stack_in: &crate::os_lib::css::counter_scope::CounterScopeStack,
1520 memo: Option<&mut super::style_memo::StyleMemo>,
1521 keys: super::style_memo::NodeKeys,
1522) -> (
1523 StyledNode<'a>,
1524 BTreeMap<String, i64>,
1525 alloc::collections::BTreeSet<String>,
1526 crate::os_lib::css::counter_scope::CounterScopeStack,
1527) {
1528 let (styled, counters_out, resets, stack_out, _) = style_tree_with_ancestors_vars_stack_inner(
1529 root,
1530 stylesheet,
1531 rule_index,
1532 ancestors_stack,
1533 sibling_index,
1534 sibling_count,
1535 parent_vars,
1536 parent_inherited,
1537 counters_in,
1538 counter_stack_in,
1539 memo,
1540 keys,
1541 None,
1542 );
1543 (styled, counters_out, resets, stack_out)
1544}
1545
1546fn style_tree_with_ancestors_vars_stack_inner<'a>(
1547 root: &'a Node,
1548 stylesheet: &StyleSheet,
1549 rule_index: Option<&super::rule_index::RuleIndex>,
1550 ancestors_stack: &mut Vec<AncestorContext<'a>>,
1551 sibling_index: Option<usize>,
1552 sibling_count: Option<usize>,
1553 parent_vars: &alloc::rc::Rc<super::types::CssVars>,
1554 parent_inherited: &alloc::rc::Rc<BTreeMap<String, String>>,
1555 counters_in: &BTreeMap<String, i64>,
1556 counter_stack_in: &crate::os_lib::css::counter_scope::CounterScopeStack,
1557 mut memo: Option<&mut super::style_memo::StyleMemo>,
1558 keys: super::style_memo::NodeKeys,
1559 type_position: Option<(Option<usize>, Option<usize>)>,
1560) -> (
1561 StyledNode<'a>,
1562 BTreeMap<String, i64>,
1563 alloc::collections::BTreeSet<String>,
1564 crate::os_lib::css::counter_scope::CounterScopeStack,
1565 Option<alloc::rc::Rc<super::style_memo::CachedElementSubtree>>,
1566) {
1567 if let NodeType::Text(_) = &root.node_type {
1572 let mut specified_values = BTreeMap::new();
1573 specified_values.insert(String::from("display"), String::from("inline"));
1574 for (k, v) in parent_inherited.iter() {
1575 specified_values.insert(k.clone(), v.clone());
1576 }
1577 return (
1578 StyledNode {
1579 node: root,
1580 specified_values: alloc::rc::Rc::new(specified_values),
1581 hover_values: None,
1582 focus_values: None,
1583 active_values: None,
1584 css_vars: parent_vars.clone(),
1585 children: alloc::vec::Vec::new(),
1586 edges_cache: core::cell::RefCell::new(alloc::vec::Vec::new()),
1587 intrinsic_size_cache: core::cell::RefCell::new(None), block_intrinsic_cache: core::cell::RefCell::new(None), layout_subtree_cache: core::cell::Cell::new(None),
1588 },
1589 counters_in.clone(),
1590 alloc::collections::BTreeSet::new(),
1591 counter_stack_in.clone(),
1592 None,
1593 );
1594 }
1595
1596 let (memo_key, subtree_key, cached_bits) = match (memo.as_deref_mut(), &root.node_type, rule_index) {
1599 (Some(m), NodeType::Element { .. }, Some(idx)) => {
1600 let bits = resolve_node_state_bits(root, idx, Some(m));
1601 if !m.enabled {
1602 m.skips[0] += 1;
1603 (None, None, bits)
1604 } else if !counters_in.is_empty() || !counter_stack_in.is_empty() {
1605 m.skips[1] += 1;
1606 (None, None, bits)
1607 } else if bits & super::rule_index::STATE_INVALID != 0 {
1608 m.skips[3] += 1;
1609 (None, None, bits)
1610 } else if bits & super::rule_index::STATE_HAS_ANC != 0 {
1611 m.skips[2] += 1;
1612 (None, None, bits)
1613 } else {
1614 let mut h = super::style_memo::KeyHasher::new();
1617 h.key(keys.own);
1618 let sub = if bits & super::rule_index::STATE_HAS != 0 {
1619 super::style_memo::node_subtree_hash(root)
1620 } else {
1621 (0, 0)
1622 };
1623 h.key(sub);
1624 if bits & super::rule_index::STATE_SIB_ALL != 0 {
1625 if let Some(p) = ancestors_stack.last() {
1626 h.key(super::style_memo::children_hash(p.node));
1627 }
1628 }
1629 let mk = h.finish();
1630 let mut sh = super::style_memo::KeyHasher::new();
1631 sh.key(mk);
1632 sh.key(super::style_memo::node_subtree_hash(root));
1633 (Some(mk), Some(sh.finish()), bits)
1634 }
1635 }
1636 (None, NodeType::Element { .. }, Some(idx)) => {
1637 (None, None, resolve_node_state_bits(root, idx, None))
1638 }
1639 _ => (None, None, super::rule_index::STATE_INVALID),
1640 };
1641
1642 if let (Some(sk), Some(m)) = (subtree_key, memo.as_deref_mut()) {
1645 if !m.verify {
1646 if let Some(cached_rc) = m.get_subtree(&sk) {
1647 if let Some(styled) = cached_rc.instantiate(root) {
1648 m.hits += cached_rc.element_count;
1649 m.subtree_hits += 1;
1650 if let Some(px) = cached_rc.root_font_px {
1651 crate::os_lib::css::units::set_root_font_px(px);
1652 }
1653 return (
1654 styled,
1655 counters_in.clone(),
1656 alloc::collections::BTreeSet::new(),
1657 counter_stack_in.clone(),
1658 Some(cached_rc),
1659 );
1660 }
1661 }
1662 }
1663 m.subtree_misses += 1;
1664 }
1665
1666 let compute_self = || -> super::style_memo::MemoEntry {
1668 let (mut specified_values, css_vars, counters_after_self, counters_reset_self) = compute_styles_with_vars_stack(
1669 root,
1670 stylesheet,
1671 rule_index,
1672 ancestors_stack.as_slice(),
1673 sibling_index,
1674 sibling_count,
1675 &[],
1676 parent_vars,
1677 counters_in,
1678 Some(counter_stack_in),
1679 type_position,
1680 );
1681
1682 resolve_all_shorthand(&mut specified_values);
1685 if specified_values.get("display").is_some_and(|v| v.trim().eq_ignore_ascii_case("inherit")) {
1689 match ancestors_stack.last().and_then(|a| a.display) {
1690 Some(d) => {
1691 specified_values.insert(String::from("display"), String::from(d));
1692 }
1693 None => {
1694 specified_values.remove("display");
1695 }
1696 }
1697 }
1698 if specified_values.get("color").is_some_and(|v| v.trim().eq_ignore_ascii_case("currentcolor")) {
1702 specified_values.remove("color");
1703 }
1704 for dim_prop in ["width", "height"] {
1712 if specified_values.get(dim_prop).is_some_and(|v| {
1713 matches!(
1714 v.trim().to_ascii_lowercase().as_str(),
1715 "initial" | "unset" | "revert"
1716 )
1717 }) {
1718 specified_values.insert(String::from(dim_prop), String::from("auto"));
1719 }
1720 }
1721 strip_css_wide_keywords(&mut specified_values);
1722 let is_document_root = matches!(&root.node_type, NodeType::Element { tag_name, .. } if tag_name.eq_ignore_ascii_case("html"));
1723 resolve_font_size_px(&mut specified_values, parent_inherited, is_document_root);
1724
1725 for (k, v) in parent_inherited.iter() {
1729 if !specified_values.contains_key(k) {
1730 specified_values.insert(k.clone(), v.clone());
1731 }
1732 }
1733 expand_logical_box_shorthands(&mut specified_values);
1740 resolve_logical_properties(&mut specified_values);
1743 resolve_current_color(&mut specified_values);
1746 let (uses_hover, uses_focus, uses_active) = if cached_bits & super::rule_index::STATE_INVALID == 0 {
1758 (
1759 cached_bits & super::rule_index::STATE_HOVER != 0,
1760 cached_bits & super::rule_index::STATE_FOCUS != 0,
1761 cached_bits & super::rule_index::STATE_ACTIVE != 0,
1762 )
1763 } else {
1764 match &root.node_type {
1765 NodeType::Element { .. } => (true, true, true),
1766 _ => (false, false, false),
1769 }
1770 };
1771
1772 let hover_opt = if !uses_hover {
1773 None
1774 } else {
1775 let (hover_values_raw, _, _, _) = compute_styles_with_vars(
1776 root,
1777 stylesheet,
1778 rule_index,
1779 ancestors_stack.as_slice(),
1780 sibling_index,
1781 sibling_count,
1782 &["hover"],
1783 &css_vars,
1784 &counters_after_self,
1785 type_position,
1786 );
1787 let mut has_hover_diff = false;
1788 for (k, v) in &hover_values_raw {
1789 if specified_values.get(k) != Some(v) {
1790 has_hover_diff = true;
1791 break;
1792 }
1793 }
1794 if has_hover_diff {
1795 Some(hover_values_raw)
1796 } else {
1797 None
1798 }
1799 };
1800
1801 let focus_opt = if !uses_focus {
1802 None
1803 } else {
1804 let (focus_values_raw, _, _, _) = compute_styles_with_vars(
1805 root,
1806 stylesheet,
1807 rule_index,
1808 ancestors_stack.as_slice(),
1809 sibling_index,
1810 sibling_count,
1811 &["focus"],
1812 &css_vars,
1813 &counters_after_self,
1814 type_position,
1815 );
1816 let mut has_focus_diff = false;
1817 for (k, v) in &focus_values_raw {
1818 if specified_values.get(k) != Some(v) {
1819 has_focus_diff = true;
1820 break;
1821 }
1822 }
1823 if has_focus_diff {
1824 Some(focus_values_raw)
1825 } else {
1826 None
1827 }
1828 };
1829
1830 let active_opt = if !uses_active {
1831 None
1832 } else {
1833 let (active_values_raw, _, _, _) = compute_styles_with_vars(
1834 root,
1835 stylesheet,
1836 rule_index,
1837 ancestors_stack.as_slice(),
1838 sibling_index,
1839 sibling_count,
1840 &["active"],
1841 &css_vars,
1842 &counters_after_self,
1843 type_position,
1844 );
1845 let mut has_active_diff = false;
1846 for (k, v) in &active_values_raw {
1847 if specified_values.get(k) != Some(v) {
1848 has_active_diff = true;
1849 break;
1850 }
1851 }
1852 if has_active_diff {
1853 Some(active_values_raw)
1854 } else {
1855 None
1856 }
1857 };
1858
1859 if let Some(v) = specified_values.get("writing-mode") {
1861 if !matches!(v.trim(), "horizontal-tb" | "inherit" | "initial") {
1862 super::types::WM_SEEN.store(true, core::sync::atomic::Ordering::Relaxed);
1863 }
1864 }
1865 let mut has_any_new_inherited = false;
1867 for k in INHERITED_PROPS {
1868 if let Some(v) = specified_values.get(*k) {
1869 if parent_inherited.get(*k) != Some(v) {
1870 has_any_new_inherited = true;
1871 break;
1872 }
1873 }
1874 }
1875 let inherited_for_children = if !has_any_new_inherited {
1876 parent_inherited.clone()
1877 } else {
1878 let mut map = BTreeMap::new();
1879 for k in INHERITED_PROPS {
1880 if let Some(v) = specified_values.get(*k) {
1881 map.insert(String::from(*k), v.clone());
1882 }
1883 }
1884 alloc::rc::Rc::new(map)
1885 };
1886 let root_font_px = is_document_root.then(crate::os_lib::css::units::root_font_px);
1887 super::style_memo::MemoEntry::new(
1888 alloc::rc::Rc::new(specified_values),
1889 css_vars,
1890 counters_after_self,
1891 counters_reset_self,
1892 hover_opt,
1893 focus_opt,
1894 active_opt,
1895 inherited_for_children,
1896 root_font_px,
1897 )
1898 };
1899 let entry = match (memo_key, memo.as_deref_mut()) {
1900 (Some(k), Some(m)) => match m.get(&k) {
1901 Some(hit) if !m.verify => {
1902 m.hits += 1;
1903 if let Some(px) = hit.root_font_px {
1904 crate::os_lib::css::units::set_root_font_px(px);
1905 }
1906 hit
1907 }
1908 Some(hit) => {
1909 let fresh = compute_self();
1910 m.hits += 1;
1911 if !hit.same_result(&fresh) {
1912 m.mismatches += 1;
1913 if m.mismatches <= 3 {
1914 crate::warn!("[CSS][MEMO] 使い回しの結果が計算し直した結果と違う: tag={:?}", match &root.node_type { NodeType::Element { tag_name, .. } => tag_name.as_str(), _ => "#text" });
1915 }
1916 }
1917 fresh
1918 }
1919 None => {
1920 let fresh = compute_self();
1921 m.misses += 1;
1922 m.put(k, fresh.clone());
1923 fresh
1924 }
1925 },
1926 _ => compute_self(),
1927 };
1928 let super::style_memo::MemoEntry {
1929 specified: specified_values,
1930 css_vars,
1931 counters_after: counters_after_self,
1932 counters_reset: counters_reset_self,
1933 hover: hover_opt,
1934 focus: focus_opt,
1935 active: active_opt,
1936 inherited_for_children,
1937 root_font_px,
1938 result_hash,
1939 ..
1940 } = entry;
1941
1942 let mut bloom = ancestors_stack.last().map(|a| a.bloom).unwrap_or_default();
1943 if let NodeType::Element { tag_name, id, classes, .. } = &root.node_type {
1944 bloom.insert_element(tag_name, id.as_deref(), classes);
1945 }
1946 let own_display = match specified_values.get("display") {
1947 Some(v) => static_display(v),
1948 None => match &root.node_type {
1949 NodeType::Element { tag_name, .. } => static_display(default_display_for(tag_name)),
1950 NodeType::Text(_) => Some("inline"),
1951 },
1952 };
1953 let c_type = specified_values.get("container-type").map(|s| s.trim()).unwrap_or("");
1954 let is_container = matches!(c_type, "size" | "inline-size");
1955 let container_name = specified_values.get("container-name")
1956 .map(|s| s.trim())
1957 .filter(|s| !s.is_empty() && *s != "none")
1958 .map(ContainerName::new);
1959
1960 let container_size = if is_container {
1961 let px_of = |v: &str| v.trim().strip_suffix("px").and_then(|n| n.trim().parse::<f32>().ok()).map(|f| f as i32);
1962 let w = specified_values.get("width")
1963 .or_else(|| specified_values.get("inline-size"))
1964 .and_then(|v| px_of(v))
1965 .or_else(|| {
1966 ancestors_stack.iter().rev().find_map(|a| a.container_size.map(|s| s.width))
1968 })
1969 .unwrap_or_else(|| {
1970 crate::os_lib::viewport::VIEWPORT_HINT_W.load(core::sync::atomic::Ordering::Relaxed).max(800)
1971 });
1972 let h = specified_values.get("height")
1973 .or_else(|| specified_values.get("block-size"))
1974 .and_then(|v| px_of(v))
1975 .unwrap_or(0);
1976 Some(crate::os_lib::css::container_query::ContainerSize { width: w, height: h })
1977 } else {
1978 None
1979 };
1980
1981 let in_disabled_fieldset = ancestors_stack.last().is_some_and(|a| a.in_disabled_fieldset)
1982 || matches!(&root.node_type, NodeType::Element { tag_name, attributes, .. }
1983 if tag_name == "fieldset" && attributes.contains_key("disabled"));
1984 ancestors_stack.push(AncestorContext {
1985 node: root,
1986 in_disabled_fieldset,
1987 sibling_index,
1988 sibling_count,
1989 bloom,
1990 display: own_display,
1991 is_container,
1992 container_name,
1993 container_size,
1994 });
1995 let mut counters_running = counters_after_self;
1996 let mut stack_running = counter_stack_in.clone();
1997 let pushed_resets_self = crate::os_lib::css::counter_scope::apply_counter_decls_to_stack(&specified_values, &mut stack_running);
1998 let child_count = root.children.len();
1999 let can_cache_self = subtree_key.is_some()
2000 && counters_running.is_empty()
2001 && counters_reset_self.is_empty()
2002 && pushed_resets_self.is_empty()
2003 && counters_in.is_empty()
2004 && counter_stack_in.is_empty();
2005 let mut all_children_cacheable = can_cache_self;
2006 let mut has_text_child = false;
2007 let mut total_subtree_elements: u32 = 1;
2008 let mut cached_children = if can_cache_self {
2009 alloc::vec::Vec::with_capacity(child_count)
2010 } else {
2011 alloc::vec::Vec::new()
2012 };
2013 let mut children = alloc::vec::Vec::with_capacity(child_count);
2014 let (parent_key, sib_keys) = if memo.is_some() {
2019 let mut h = super::style_memo::KeyHasher::new();
2020 h.key(keys.desc);
2021 h.key(result_hash);
2022 let sib = match rule_index {
2023 Some(ix) => super::style_memo::sibling_keys(root, ix.needs_full_siblings(), |n| ix.sibling_relevant(n)),
2024 None => super::style_memo::sibling_keys(root, true, |_| true),
2025 };
2026 (h.finish(), sib)
2027 } else {
2028 ((0, 0), alloc::vec::Vec::new())
2029 };
2030 let type_positions = if child_count > crate::os_lib::css::selector::TYPE_POSITION_TABLE_MIN_CHILDREN {
2033 Some(crate::os_lib::css::selector::type_positions_of_children(root))
2034 } else {
2035 None
2036 };
2037 for (idx, child) in root.children.iter().enumerate() {
2038 if layout_poll() {
2042 all_children_cacheable = false;
2043 break;
2044 }
2045 let child_key = match sib_keys.get(idx) {
2046 Some(&(sk, pos)) => {
2047 let shape = super::style_memo::children_shape(child);
2048 let own = super::style_memo::child_key(parent_key, sk, shape);
2049 let desc = match rule_index {
2050 Some(ix) => {
2051 let need = ix.ancestor_needs(child);
2052 let mut extra = [(0u64, 0u64); 2];
2053 let mut extra_len = 0usize;
2054 if need.siblings {
2055 extra[extra_len] = sk;
2056 extra_len += 1;
2057 } else if need.position {
2058 extra[extra_len] = pos;
2059 extra_len += 1;
2060 }
2061 if need.children {
2062 extra[extra_len] = shape;
2063 extra_len += 1;
2064 }
2065 super::style_memo::desc_key(parent_key, child, &extra[..extra_len])
2066 }
2067 None => own,
2068 };
2069 super::style_memo::NodeKeys { own, desc }
2070 }
2071 None => super::style_memo::NodeKeys::default(),
2072 };
2073 let counters_before_child = if counters_running.is_empty() {
2074 None
2075 } else {
2076 Some(counters_running.clone())
2077 };
2078 let (child_styled, counters_after_child, reset_names_in_child, stack_after_child, child_cached) =
2079 style_tree_with_ancestors_vars_stack_inner(
2080 child,
2081 stylesheet,
2082 rule_index,
2083 ancestors_stack,
2084 Some(idx),
2085 Some(child_count),
2086 &css_vars,
2087 &inherited_for_children,
2088 &counters_running,
2089 &stack_running,
2090 memo.as_deref_mut(),
2091 child_key,
2092 type_positions.as_ref().and_then(|t| t.get(idx).copied()),
2093 );
2094 if matches!(child.node_type, NodeType::Text(_)) {
2095 has_text_child = true;
2096 if all_children_cacheable {
2097 cached_children.push(super::style_memo::CachedSubtreeChild::Text);
2098 }
2099 } else if all_children_cacheable {
2100 match child_cached {
2101 Some(rc) => {
2102 total_subtree_elements = total_subtree_elements.saturating_add(rc.element_count);
2103 cached_children.push(super::style_memo::CachedSubtreeChild::Element(rc));
2104 }
2105 None => {
2106 all_children_cacheable = false;
2107 }
2108 }
2109 }
2110 counters_running = counters_after_child;
2111 stack_running = stack_after_child;
2112 if !reset_names_in_child.is_empty() {
2113 if let Some(before) = &counters_before_child {
2114 for name in &reset_names_in_child {
2115 match before.get(name) {
2116 Some(v) => {
2117 counters_running.insert(name.clone(), *v);
2118 }
2119 None => {
2120 counters_running.remove(name);
2121 }
2122 }
2123 }
2124 } else {
2125 for name in &reset_names_in_child {
2126 counters_running.remove(name);
2127 }
2128 }
2129 }
2130 children.push(child_styled);
2131 }
2132 ancestors_stack.pop();
2133
2134 for name in &pushed_resets_self {
2135 stack_running.pop_reset(name);
2136 }
2137
2138 let mut built_subtree: Option<alloc::rc::Rc<super::style_memo::CachedElementSubtree>> = None;
2139 if let (Some(sk), Some(m)) = (subtree_key, memo) {
2140 if all_children_cacheable
2141 && counters_running.is_empty()
2142 && stack_running.is_empty()
2143 && total_subtree_elements <= super::style_memo::StyleMemo::MAX_SUBTREE_ELEMENTS
2144 {
2145 let text_child_specified = if has_text_child {
2146 let mut map = BTreeMap::new();
2147 map.insert(String::from("display"), String::from("inline"));
2148 for (k, v) in inherited_for_children.iter() {
2149 map.insert(k.clone(), v.clone());
2150 }
2151 Some(alloc::rc::Rc::new(map))
2152 } else {
2153 None
2154 };
2155 let pseudo = if hover_opt.is_some() || focus_opt.is_some() || active_opt.is_some() {
2156 Some(alloc::boxed::Box::new(super::style_memo::CachedPseudoStyles {
2157 hover: hover_opt.clone(),
2158 focus: focus_opt.clone(),
2159 active: active_opt.clone(),
2160 }))
2161 } else {
2162 None
2163 };
2164 let rc = alloc::rc::Rc::new(super::style_memo::CachedElementSubtree {
2165 node_features: root.features_hash,
2166 specified_values: specified_values.clone(),
2167 css_vars: css_vars.clone(),
2168 inherited_for_children: inherited_for_children.clone(),
2169 text_child_specified,
2170 pseudo,
2171 root_font_px,
2172 children: cached_children,
2173 element_count: total_subtree_elements,
2174 });
2175 m.put_subtree(sk, rc.clone());
2176 built_subtree = Some(rc);
2177 }
2178 }
2179
2180 attach_flow_pseudo_boxes(root, &specified_values, &css_vars, &mut children);
2181
2182 (
2183 StyledNode {
2184 node: root,
2185 specified_values,
2186 hover_values: hover_opt,
2187 focus_values: focus_opt,
2188 active_values: active_opt,
2189 css_vars: css_vars.clone(),
2190 children,
2191 edges_cache: Default::default(),
2192 intrinsic_size_cache: Default::default(), block_intrinsic_cache: Default::default(), layout_subtree_cache: Default::default(),
2193 },
2194 counters_running,
2195 counters_reset_self,
2196 stack_running,
2197 built_subtree,
2198 )
2199}
2200
2201pub(crate) fn attach_flow_pseudo_boxes<'a>(
2206 node: &'a crate::os_lib::dom::Node,
2207 specified_values: &alloc::rc::Rc<BTreeMap<String, String>>,
2208 css_vars: &alloc::rc::Rc<CssVars>,
2209 children: &mut alloc::vec::Vec<StyledNode<'a>>,
2210) {
2211 let has_before = specified_values.contains_key("x-before-content");
2212 let has_after = specified_values.contains_key("x-after-content");
2213 if !has_before && !has_after {
2214 return;
2215 }
2216 let NodeType::Element { tag_name, .. } = &node.node_type else { return };
2217 let display = specified_values
2218 .get("display")
2219 .map(String::as_str)
2220 .unwrap_or_else(|| default_display_for(tag_name));
2221 if !super::flow_pseudo::flow_pseudo_parent_ok(tag_name, display) {
2222 return;
2223 }
2224 let mk = |which: &str| -> Option<StyledNode<'a>> {
2225 let vals = super::flow_pseudo::flow_pseudo_values(specified_values, which)?;
2226 Some(StyledNode {
2227 node,
2228 specified_values: alloc::rc::Rc::new(vals),
2229 hover_values: None,
2230 focus_values: None,
2231 active_values: None,
2232 css_vars: css_vars.clone(),
2233 children: alloc::vec::Vec::new(),
2234 edges_cache: Default::default(),
2235 intrinsic_size_cache: Default::default(),
2236 block_intrinsic_cache: Default::default(),
2237 layout_subtree_cache: Default::default(),
2238 })
2239 };
2240 if has_after {
2241 if let Some(b) = mk("after") {
2242 children.push(b);
2243 }
2244 }
2245 if has_before {
2246 if let Some(b) = mk("before") {
2247 children.insert(0, b);
2248 }
2249 }
2250}
2251
2252pub fn default_display_for(tag_name: &str) -> &'static str {
2255 match tag_name {
2256 "head" | "title" | "meta" | "link" | "style" | "script" => "none",
2257 "html" | "body" | "div" | "p" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "ul" | "ol"
2258 | "li" | "form" | "center" | "header" | "footer" | "main" | "section" | "nav" | "hr"
2259 | "caption" | "details" | "summary" => "block",
2260 "table" => "table",
2261 "thead" | "tbody" | "tfoot" => "table-row-group",
2262 "tr" => "table-row",
2263 "td" | "th" => "table-cell",
2264 _ => "inline",
2265 }
2266}