1use crate::computed_value_flags::ComputedValueFlags;
10use crate::dom::{AttributeTracker, TElement};
11use crate::logical_geometry::{LogicalSize, WritingMode};
12use crate::parser::ParserContext;
13use crate::properties::ComputedValues;
14use crate::queries::feature::{AllowsRanges, Evaluator, FeatureFlags, QueryFeatureDescription};
15use crate::queries::values::Orientation;
16use crate::queries::{FeatureType, QueryCondition};
17use crate::selector_map::{PrecomputedHashMap, PrecomputedHashSet};
18use crate::shared_lock::{
19 DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard,
20};
21use crate::stylesheets::{CssRules, CustomMediaEvaluator};
22use crate::stylist::Stylist;
23use crate::values::computed::{CSSPixelLength, ContainerType, Context, Ratio};
24use crate::values::specified::ContainerName;
25use crate::{LocalName, derives::*};
26use app_units::Au;
27use cssparser::{Parser, SourceLocation};
28use euclid::default::Size2D;
29#[cfg(feature = "gecko")]
30use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
31use selectors::kleene_value::KleeneValue;
32use selectors::matching::ElementSelectorFlags;
33use servo_arc::Arc;
34use std::fmt::{self, Write};
35use style_traits::arc_slice::ArcSlice;
36use style_traits::{CssStringWriter, CssWriter, ParseError, StyleParseErrorKind, ToCss};
37
38#[derive(Debug, ToShmem)]
40pub struct ContainerRule {
41 pub conditions: ContainerConditions,
43 pub rules: Arc<Locked<CssRules>>,
45 pub source_location: SourceLocation,
47}
48
49impl ContainerRule {
50 #[cfg(feature = "gecko")]
52 pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
53 self.rules.unconditional_shallow_size_of(ops)
55 + self.rules.read_with(guard).size_of(guard, ops)
56 }
57}
58
59impl DeepCloneWithLock for ContainerRule {
60 fn deep_clone_with_lock(&self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard) -> Self {
61 let rules = self.rules.read_with(guard);
62 Self {
63 conditions: self.conditions.clone(),
64 rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))),
65 source_location: self.source_location,
66 }
67 }
68}
69
70impl ToCssWithGuard for ContainerRule {
71 fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
72 dest.write_str("@container ")?;
73 {
74 let mut writer = CssWriter::new(dest);
75 self.conditions.to_css(&mut writer)?;
76 }
77 self.rules.read_with(guard).to_css_block(guard, dest)
78 }
79}
80
81#[derive(Clone, Debug, ToCss, ToShmem)]
85#[css(comma)]
86pub struct ContainerConditions(#[css(iterable)] pub ArcSlice<ContainerCondition>);
87
88#[derive(Clone, Debug, ToShmem)]
91pub struct AttrReferenceSet {
92 pub names: PrecomputedHashSet<LocalName>,
94 pub is_fully_parsed: bool,
97}
98
99impl Default for AttrReferenceSet {
100 fn default() -> Self {
101 Self {
102 names: Default::default(),
103 is_fully_parsed: true,
104 }
105 }
106}
107
108#[derive(Debug, Clone, Copy, MallocSizeOf, PartialEq, Eq, PartialOrd, Ord)]
112#[repr(C)]
113pub enum ContainerAttributeDependencyKind {
114 None = 0,
116 UnnamedContainer = 1,
118 NamedContainer = 2,
120}
121
122impl ContainerAttributeDependencyKind {
123 pub fn element_container_dependency_kind<E: TElement>(
128 element: E,
129 local_name: &LocalName,
130 stylist: &Stylist,
131 ) -> Self {
132 let mut name_kind = ContainerAttributeDependencyKind::None;
133 stylist.any_applicable_rule_data(element, |data| {
134 let value = data.might_have_attribute_dependency_in_container(local_name);
135 name_kind = std::cmp::max(name_kind, value);
136 name_kind == ContainerAttributeDependencyKind::NamedContainer
137 });
138 name_kind
139 }
140}
141
142#[derive(Debug, ToShmem, ToCss)]
144pub struct ContainerCondition {
145 #[css(skip_if = "ContainerName::is_none")]
146 name: ContainerName,
147 condition: Option<QueryCondition>,
148 #[css(skip)]
149 flags: FeatureFlags,
150 #[css(skip)]
151 attributes_referenced: AttrReferenceSet,
152}
153
154pub struct ContainerLookupResult<E> {
156 pub element: E,
158 pub info: ContainerInfo,
160 pub style: Arc<ComputedValues>,
162}
163
164fn container_type_axes(ty_: ContainerType, wm: WritingMode) -> FeatureFlags {
165 if ty_.intersects(ContainerType::SIZE) {
166 FeatureFlags::all_container_axes()
167 } else if ty_.intersects(ContainerType::INLINE_SIZE) {
168 let physical_axis = if wm.is_vertical() {
169 FeatureFlags::CONTAINER_REQUIRES_HEIGHT_AXIS
170 } else {
171 FeatureFlags::CONTAINER_REQUIRES_WIDTH_AXIS
172 };
173 FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS | physical_axis
174 } else {
175 FeatureFlags::empty()
176 }
177}
178
179enum TraversalResult<T> {
180 InProgress,
181 StopTraversal,
182 Done(T),
183}
184
185fn traverse_container<E, F, R>(
186 mut e: E,
187 originating_element_style: Option<&ComputedValues>,
188 evaluator: F,
189) -> Option<(E, R)>
190where
191 E: TElement,
192 F: Fn(E, Option<&ComputedValues>) -> TraversalResult<R>,
193{
194 if originating_element_style.is_some() {
195 match evaluator(e, originating_element_style) {
196 TraversalResult::InProgress => {},
197 TraversalResult::StopTraversal => return None,
198 TraversalResult::Done(result) => return Some((e, result)),
199 }
200 }
201 while let Some(element) = e.traversal_parent() {
202 match evaluator(element, None) {
203 TraversalResult::InProgress => {},
204 TraversalResult::StopTraversal => return None,
205 TraversalResult::Done(result) => return Some((element, result)),
206 }
207 e = element;
208 }
209
210 None
211}
212
213impl ContainerCondition {
214 #[inline]
216 pub fn name(&self) -> &ContainerName {
217 &self.name
218 }
219 #[inline]
221 pub fn query_condition(&self) -> Option<&QueryCondition> {
222 self.condition.as_ref()
223 }
224 pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
226 let name = input
227 .try_parse(|input| ContainerName::parse_for_query(context, input))
228 .ok()
229 .unwrap_or_else(ContainerName::none);
230 let condition = input
231 .try_parse(|input| QueryCondition::parse(context, input, FeatureType::Container))
232 .ok();
233 if condition.is_none() && name.is_none() {
234 return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
235 }
236 let mut attributes_referenced = AttrReferenceSet::default();
237 if let Some(c) = condition.as_ref() {
238 c.collect_attribute_references(&mut attributes_referenced)
239 }
240 let flags = condition
241 .as_ref()
242 .map_or(FeatureFlags::empty(), |c| c.cumulative_flags());
243 Ok(Self {
244 name,
245 condition,
246 flags,
247 attributes_referenced,
248 })
249 }
250
251 fn valid_container_info<E>(
252 &self,
253 potential_container: E,
254 originating_element_style: Option<&ComputedValues>,
255 ) -> TraversalResult<ContainerLookupResult<E>>
256 where
257 E: TElement,
258 {
259 let data;
260 let style = match originating_element_style {
261 Some(s) => s,
262 None => {
263 data = match potential_container.borrow_data() {
264 Some(d) => d,
265 None => return TraversalResult::InProgress,
266 };
267 &**data.styles.primary()
268 },
269 };
270 let wm = style.writing_mode;
271 let box_style = style.get_box();
272
273 let container_type = *box_style.get_container_type();
275 let available_axes = container_type_axes(container_type, wm);
276 if !available_axes.contains(self.flags.container_axes()) {
277 return TraversalResult::InProgress;
278 }
279
280 let container_name = box_style.get_container_name();
282 for filter_name in self.name.0.iter() {
283 if !container_name.0.contains(filter_name) {
284 return TraversalResult::InProgress;
285 }
286 }
287
288 let size = potential_container.query_container_size(box_style.get_display());
289 let style = style.to_arc();
290 TraversalResult::Done(ContainerLookupResult {
291 element: potential_container,
292 info: ContainerInfo {
293 size,
294 wm,
295 inherited_style: {
296 potential_container.traversal_parent().and_then(|parent| {
297 parent
298 .borrow_data()
299 .and_then(|data| data.styles.get_primary().cloned())
300 })
301 },
302 },
303 style,
304 })
305 }
306
307 pub fn find_container<E>(
309 &self,
310 e: E,
311 originating_element_style: Option<&ComputedValues>,
312 ) -> Option<ContainerLookupResult<E>>
313 where
314 E: TElement,
315 {
316 traverse_container(
317 e,
318 originating_element_style,
319 |element, originating_element_style| {
320 self.valid_container_info(element, originating_element_style)
321 },
322 )
323 .map(|(_, result)| result)
324 }
325
326 pub fn matches<E>(
328 &self,
329 stylist: &Stylist,
330 element: E,
331 originating_element_style: Option<&ComputedValues>,
332 invalidation_flags: &mut ComputedValueFlags,
333 ) -> KleeneValue
334 where
335 E: TElement,
336 {
337 let result = self.find_container(element, originating_element_style);
338 let condition = match self.condition {
339 Some(ref c) => c,
340 None => {
341 return KleeneValue::from(result.is_some());
344 },
345 };
346 if self.flags.contains(FeatureFlags::STYLE) {
352 invalidation_flags.insert(ComputedValueFlags::DEPENDS_ON_CONTAINER_STYLE_QUERY);
353 }
354 let (container, info) = match result {
355 Some(r) => (r.element, (r.info, r.style)),
356 None => {
357 return KleeneValue::False;
360 },
361 };
362 let size_query_container_lookup = ContainerSizeQuery::for_element(
365 container, None, false,
366 );
367 let mut attribute_tracker = AttributeTracker::new(&container);
368 Context::for_container_query_evaluation(
369 stylist.device(),
370 Some(stylist),
371 Some(info),
372 size_query_container_lookup,
373 &container,
374 |context| {
375 let matches = condition.matches(
376 context,
377 &mut CustomMediaEvaluator::none(),
378 &mut attribute_tracker,
379 );
380 let flags = context.style().flags();
381 if flags.contains(ComputedValueFlags::USES_VIEWPORT_UNITS) {
382 invalidation_flags
385 .insert(ComputedValueFlags::USES_VIEWPORT_UNITS_ON_CONTAINER_QUERIES);
386 }
387 if flags.contains(ComputedValueFlags::USES_FONT_OR_WM_RELATIVE_UNITS) {
388 invalidation_flags.insert(
389 ComputedValueFlags::USES_FONT_OR_WM_RELATIVE_UNITS_ON_CONTAINER_QUERIES,
390 );
391 }
392 if flags.intersects(ComputedValueFlags::tree_counting_function_flags()) {
393 container.apply_selector_flags(ElementSelectorFlags::HAS_SLOW_SELECTOR);
398 }
399 matches
400 },
401 )
402 }
403
404 pub fn get_attributes_referenced(&self) -> &AttrReferenceSet {
406 &self.attributes_referenced
407 }
408
409 pub fn insert_attribute_references_in_dependency_map(
414 &self,
415 kind_map: &mut PrecomputedHashMap<LocalName, ContainerAttributeDependencyKind>,
416 attribute_dependencies: &mut PrecomputedHashSet<LocalName>,
417 ) -> ContainerAttributeDependencyKind {
418 let name_kind = if self.name.is_none() {
419 ContainerAttributeDependencyKind::UnnamedContainer
420 } else {
421 ContainerAttributeDependencyKind::NamedContainer
422 };
423 for attr in &self.get_attributes_referenced().names {
424 kind_map
425 .entry_ref(attr)
426 .and_modify(|v| {
427 if *v == ContainerAttributeDependencyKind::UnnamedContainer {
428 *v = name_kind
429 }
430 })
431 .or_insert(name_kind);
432 attribute_dependencies.get_or_insert_with(attr, Clone::clone);
433 }
434 if self.attributes_referenced.is_fully_parsed {
435 ContainerAttributeDependencyKind::None
436 } else {
437 name_kind
438 }
439 }
440}
441
442#[derive(Clone)]
444pub struct ContainerInfo {
445 size: Size2D<Option<Au>>,
446 wm: WritingMode,
447 inherited_style: Option<Arc<ComputedValues>>,
448}
449
450impl ContainerInfo {
451 fn size(&self) -> Option<Size2D<Au>> {
452 Some(Size2D::new(self.size.width?, self.size.height?))
453 }
454
455 pub fn inherited_style(&self) -> Option<&ComputedValues> {
457 self.inherited_style.as_deref()
458 }
459}
460
461fn eval_width(context: &Context) -> Option<CSSPixelLength> {
462 let info = context.container_info.as_ref()?;
463 Some(CSSPixelLength::new(info.size.width?.to_f32_px()))
464}
465
466fn eval_height(context: &Context) -> Option<CSSPixelLength> {
467 let info = context.container_info.as_ref()?;
468 Some(CSSPixelLength::new(info.size.height?.to_f32_px()))
469}
470
471fn eval_inline_size(context: &Context) -> Option<CSSPixelLength> {
472 let info = context.container_info.as_ref()?;
473 Some(CSSPixelLength::new(
474 LogicalSize::from_physical(info.wm, info.size)
475 .inline?
476 .to_f32_px(),
477 ))
478}
479
480fn eval_block_size(context: &Context) -> Option<CSSPixelLength> {
481 let info = context.container_info.as_ref()?;
482 Some(CSSPixelLength::new(
483 LogicalSize::from_physical(info.wm, info.size)
484 .block?
485 .to_f32_px(),
486 ))
487}
488
489fn eval_aspect_ratio(context: &Context) -> Option<Ratio> {
490 let info = context.container_info.as_ref()?;
491 Some(Ratio::new(
492 info.size.width?.0 as f32,
493 info.size.height?.0 as f32,
494 ))
495}
496
497fn eval_orientation(context: &Context, value: Option<Orientation>) -> KleeneValue {
498 let size = match context.container_info.as_ref().and_then(|info| info.size()) {
499 Some(size) => size,
500 None => return KleeneValue::Unknown,
501 };
502 KleeneValue::from(Orientation::eval(size, value))
503}
504
505pub static CONTAINER_FEATURES: [QueryFeatureDescription; 6] = [
509 feature!(
510 atom!("width"),
511 AllowsRanges::Yes,
512 Evaluator::OptionalLength(eval_width),
513 FeatureFlags::CONTAINER_REQUIRES_WIDTH_AXIS,
514 ),
515 feature!(
516 atom!("height"),
517 AllowsRanges::Yes,
518 Evaluator::OptionalLength(eval_height),
519 FeatureFlags::CONTAINER_REQUIRES_HEIGHT_AXIS,
520 ),
521 feature!(
522 atom!("inline-size"),
523 AllowsRanges::Yes,
524 Evaluator::OptionalLength(eval_inline_size),
525 FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS,
526 ),
527 feature!(
528 atom!("block-size"),
529 AllowsRanges::Yes,
530 Evaluator::OptionalLength(eval_block_size),
531 FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS,
532 ),
533 feature!(
534 atom!("aspect-ratio"),
535 AllowsRanges::Yes,
536 Evaluator::OptionalNumberRatio(eval_aspect_ratio),
537 FeatureFlags::from_bits_truncate(
540 FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS.bits()
541 | FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS.bits()
542 ),
543 ),
544 feature!(
545 atom!("orientation"),
546 AllowsRanges::No,
547 keyword_evaluator!(eval_orientation, Orientation),
548 FeatureFlags::from_bits_truncate(
549 FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS.bits()
550 | FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS.bits()
551 ),
552 ),
553];
554
555#[derive(Copy, Clone, Default)]
559pub struct ContainerSizeQueryResult {
560 width: Option<Au>,
561 height: Option<Au>,
562}
563
564impl ContainerSizeQueryResult {
565 fn get_viewport_size(context: &Context) -> Size2D<Au> {
566 use crate::values::specified::ViewportVariant;
567 context.viewport_size_for_viewport_unit_resolution(ViewportVariant::Small)
568 }
569
570 fn get_logical_viewport_size(context: &Context) -> LogicalSize<Au> {
571 LogicalSize::from_physical(
572 context.builder.writing_mode,
573 Self::get_viewport_size(context),
574 )
575 }
576
577 pub fn get_container_inline_size(&self, context: &Context) -> Au {
579 if context.builder.writing_mode.is_horizontal() {
580 if let Some(w) = self.width {
581 return w;
582 }
583 } else if let Some(h) = self.height {
584 return h;
585 }
586 Self::get_logical_viewport_size(context).inline
587 }
588
589 pub fn get_container_block_size(&self, context: &Context) -> Au {
591 if context.builder.writing_mode.is_horizontal() {
592 self.get_container_height(context)
593 } else {
594 self.get_container_width(context)
595 }
596 }
597
598 pub fn get_container_width(&self, context: &Context) -> Au {
600 if let Some(w) = self.width {
601 return w;
602 }
603 Self::get_viewport_size(context).width
604 }
605
606 pub fn get_container_height(&self, context: &Context) -> Au {
608 if let Some(h) = self.height {
609 return h;
610 }
611 Self::get_viewport_size(context).height
612 }
613
614 fn merge(self, new_result: Self) -> Self {
616 let mut result = self;
617 if let Some(width) = new_result.width {
618 result.width.get_or_insert(width);
619 }
620 if let Some(height) = new_result.height {
621 result.height.get_or_insert(height);
622 }
623 result
624 }
625
626 fn is_complete(&self) -> bool {
627 self.width.is_some() && self.height.is_some()
628 }
629}
630
631pub enum ContainerSizeQuery<'a> {
633 NotEvaluated(Box<dyn Fn() -> ContainerSizeQueryResult + 'a>),
635 Evaluated(ContainerSizeQueryResult),
637}
638
639impl<'a> ContainerSizeQuery<'a> {
640 fn evaluate_potential_size_container<E>(
641 e: E,
642 originating_element_style: Option<&ComputedValues>,
643 ) -> TraversalResult<ContainerSizeQueryResult>
644 where
645 E: TElement,
646 {
647 let data;
648 let style = match originating_element_style {
649 Some(s) => s,
650 None => {
651 data = match e.borrow_data() {
652 Some(d) => d,
653 None => return TraversalResult::InProgress,
654 };
655 &**data.styles.primary()
656 },
657 };
658 if !style
659 .flags
660 .contains(ComputedValueFlags::SELF_OR_ANCESTOR_HAS_SIZE_CONTAINER_TYPE)
661 {
662 return TraversalResult::StopTraversal;
664 }
665
666 let wm = style.writing_mode;
667 let box_style = style.get_box();
668
669 let container_type = *box_style.get_container_type();
670 let size = e.query_container_size(box_style.get_display());
671 if container_type.intersects(ContainerType::SIZE) {
672 TraversalResult::Done(ContainerSizeQueryResult {
673 width: size.width,
674 height: size.height,
675 })
676 } else if container_type.intersects(ContainerType::INLINE_SIZE) {
677 if wm.is_horizontal() {
678 TraversalResult::Done(ContainerSizeQueryResult {
679 width: size.width,
680 height: None,
681 })
682 } else {
683 TraversalResult::Done(ContainerSizeQueryResult {
684 width: None,
685 height: size.height,
686 })
687 }
688 } else {
689 TraversalResult::InProgress
690 }
691 }
692
693 fn lookup<E>(
695 element: E,
696 originating_element_style: Option<&ComputedValues>,
697 ) -> ContainerSizeQueryResult
698 where
699 E: TElement + 'a,
700 {
701 match traverse_container(
702 element,
703 originating_element_style,
704 |e, originating_element_style| {
705 Self::evaluate_potential_size_container(e, originating_element_style)
706 },
707 ) {
708 Some((container, result)) => {
709 if result.is_complete() {
710 result
711 } else {
712 result.merge(Self::lookup(container, None))
714 }
715 },
716 None => ContainerSizeQueryResult::default(),
717 }
718 }
719
720 pub fn for_element<E>(
722 element: E,
723 known_parent_style: Option<&'a ComputedValues>,
724 is_pseudo: bool,
725 ) -> Self
726 where
727 E: TElement + 'a,
728 {
729 let parent;
730 let data;
731 let parent_style = match known_parent_style {
732 Some(s) => Some(s),
733 None => {
734 parent = match element.traversal_parent() {
736 Some(parent) => parent,
737 None => return Self::none(),
738 };
739 data = parent.borrow_data();
740 data.as_ref().map(|data| &**data.styles.primary())
741 },
742 };
743
744 let should_traverse = parent_style.is_none_or(|s| {
747 s.flags
748 .contains(ComputedValueFlags::SELF_OR_ANCESTOR_HAS_SIZE_CONTAINER_TYPE)
749 });
750 if !should_traverse {
751 return Self::none();
752 }
753 Self::NotEvaluated(Box::new(move || {
754 Self::lookup(element, if is_pseudo { known_parent_style } else { None })
755 }))
756 }
757
758 pub fn for_option_element<E>(
760 element: Option<E>,
761 known_parent_style: Option<&'a ComputedValues>,
762 is_pseudo: bool,
763 ) -> Self
764 where
765 E: TElement + 'a,
766 {
767 if let Some(e) = element {
768 Self::for_element(e, known_parent_style, is_pseudo)
769 } else {
770 Self::none()
771 }
772 }
773
774 pub fn none() -> Self {
776 ContainerSizeQuery::Evaluated(ContainerSizeQueryResult::default())
777 }
778
779 pub fn get(&mut self) -> ContainerSizeQueryResult {
781 match self {
782 Self::NotEvaluated(lookup) => {
783 *self = Self::Evaluated((lookup)());
784 match self {
785 Self::Evaluated(info) => *info,
786 _ => unreachable!("Just evaluated but not set?"),
787 }
788 },
789 Self::Evaluated(info) => *info,
790 }
791 }
792}