1use crate::computed_value_flags::ComputedValueFlags;
10use crate::dom::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::shared_lock::{
18 DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard,
19};
20use crate::str::CssStringWriter;
21use crate::stylesheets::CssRules;
22use crate::stylist::Stylist;
23use crate::values::computed::{CSSPixelLength, ContainerType, Context, Ratio};
24use crate::values::specified::ContainerName;
25use app_units::Au;
26use cssparser::{Parser, SourceLocation};
27use euclid::default::Size2D;
28#[cfg(feature = "gecko")]
29use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
30use selectors::kleene_value::KleeneValue;
31use servo_arc::Arc;
32use std::fmt::{self, Write};
33use style_traits::{CssWriter, ParseError, ToCss};
34
35#[derive(Debug, ToShmem)]
37pub struct ContainerRule {
38 pub condition: Arc<ContainerCondition>,
40 pub rules: Arc<Locked<CssRules>>,
42 pub source_location: SourceLocation,
44}
45
46impl ContainerRule {
47 pub fn query_condition(&self) -> &QueryCondition {
49 &self.condition.condition
50 }
51
52 pub fn container_name(&self) -> &ContainerName {
54 &self.condition.name
55 }
56
57 #[cfg(feature = "gecko")]
59 pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
60 self.rules.unconditional_shallow_size_of(ops)
62 + self.rules.read_with(guard).size_of(guard, ops)
63 }
64}
65
66impl DeepCloneWithLock for ContainerRule {
67 fn deep_clone_with_lock(&self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard) -> Self {
68 let rules = self.rules.read_with(guard);
69 Self {
70 condition: self.condition.clone(),
71 rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))),
72 source_location: self.source_location.clone(),
73 }
74 }
75}
76
77impl ToCssWithGuard for ContainerRule {
78 fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
79 dest.write_str("@container ")?;
80 {
81 let mut writer = CssWriter::new(dest);
82 if !self.condition.name.is_none() {
83 self.condition.name.to_css(&mut writer)?;
84 writer.write_char(' ')?;
85 }
86 self.condition.condition.to_css(&mut writer)?;
87 }
88 self.rules.read_with(guard).to_css_block(guard, dest)
89 }
90}
91
92#[derive(Debug, ToShmem, ToCss)]
94pub struct ContainerCondition {
95 #[css(skip_if = "ContainerName::is_none")]
96 name: ContainerName,
97 condition: QueryCondition,
98 #[css(skip)]
99 flags: FeatureFlags,
100}
101
102pub struct ContainerLookupResult<E> {
104 pub element: E,
106 pub info: ContainerInfo,
108 pub style: Arc<ComputedValues>,
110}
111
112fn container_type_axes(ty_: ContainerType, wm: WritingMode) -> FeatureFlags {
113 if ty_.intersects(ContainerType::SIZE) {
114 FeatureFlags::all_container_axes()
115 } else if ty_.intersects(ContainerType::INLINE_SIZE) {
116 let physical_axis = if wm.is_vertical() {
117 FeatureFlags::CONTAINER_REQUIRES_HEIGHT_AXIS
118 } else {
119 FeatureFlags::CONTAINER_REQUIRES_WIDTH_AXIS
120 };
121 FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS | physical_axis
122 } else {
123 FeatureFlags::empty()
124 }
125}
126
127enum TraversalResult<T> {
128 InProgress,
129 StopTraversal,
130 Done(T),
131}
132
133fn traverse_container<E, F, R>(
134 mut e: E,
135 originating_element_style: Option<&ComputedValues>,
136 evaluator: F,
137) -> Option<(E, R)>
138where
139 E: TElement,
140 F: Fn(E, Option<&ComputedValues>) -> TraversalResult<R>,
141{
142 if originating_element_style.is_some() {
143 match evaluator(e, originating_element_style) {
144 TraversalResult::InProgress => {},
145 TraversalResult::StopTraversal => return None,
146 TraversalResult::Done(result) => return Some((e, result)),
147 }
148 }
149 while let Some(element) = e.traversal_parent() {
150 match evaluator(element, None) {
151 TraversalResult::InProgress => {},
152 TraversalResult::StopTraversal => return None,
153 TraversalResult::Done(result) => return Some((element, result)),
154 }
155 e = element;
156 }
157
158 None
159}
160
161impl ContainerCondition {
162 pub fn parse<'a>(
164 context: &ParserContext,
165 input: &mut Parser<'a, '_>,
166 ) -> Result<Self, ParseError<'a>> {
167 let name = input
168 .try_parse(|input| ContainerName::parse_for_query(context, input))
169 .ok()
170 .unwrap_or_else(ContainerName::none);
171 let condition = QueryCondition::parse(context, input, FeatureType::Container)?;
172 let flags = condition.cumulative_flags();
173 Ok(Self {
174 name,
175 condition,
176 flags,
177 })
178 }
179
180 fn valid_container_info<E>(
181 &self,
182 potential_container: E,
183 originating_element_style: Option<&ComputedValues>,
184 ) -> TraversalResult<ContainerLookupResult<E>>
185 where
186 E: TElement,
187 {
188 let data;
189 let style = match originating_element_style {
190 Some(s) => s,
191 None => {
192 data = match potential_container.borrow_data() {
193 Some(d) => d,
194 None => return TraversalResult::InProgress,
195 };
196 &**data.styles.primary()
197 },
198 };
199 let wm = style.writing_mode;
200 let box_style = style.get_box();
201
202 let container_type = box_style.clone_container_type();
204 let available_axes = container_type_axes(container_type, wm);
205 if !available_axes.contains(self.flags.container_axes()) {
206 return TraversalResult::InProgress;
207 }
208
209 let container_name = box_style.clone_container_name();
211 for filter_name in self.name.0.iter() {
212 if !container_name.0.contains(filter_name) {
213 return TraversalResult::InProgress;
214 }
215 }
216
217 let size = potential_container.query_container_size(&box_style.clone_display());
218 let style = style.to_arc();
219 TraversalResult::Done(ContainerLookupResult {
220 element: potential_container,
221 info: ContainerInfo { size, wm },
222 style,
223 })
224 }
225
226 pub fn find_container<E>(
228 &self,
229 e: E,
230 originating_element_style: Option<&ComputedValues>,
231 ) -> Option<ContainerLookupResult<E>>
232 where
233 E: TElement,
234 {
235 match traverse_container(
236 e,
237 originating_element_style,
238 |element, originating_element_style| {
239 self.valid_container_info(element, originating_element_style)
240 },
241 ) {
242 Some((_, result)) => Some(result),
243 None => None,
244 }
245 }
246
247 pub(crate) fn matches<E>(
249 &self,
250 stylist: &Stylist,
251 element: E,
252 originating_element_style: Option<&ComputedValues>,
253 invalidation_flags: &mut ComputedValueFlags,
254 ) -> KleeneValue
255 where
256 E: TElement,
257 {
258 let result = self.find_container(element, originating_element_style);
259 let (container, info) = match result {
260 Some(r) => (Some(r.element), Some((r.info, r.style))),
261 None => (None, None),
262 };
263 let size_query_container_lookup = ContainerSizeQuery::for_option_element(
266 container, None, false,
267 );
268 Context::for_container_query_evaluation(
269 stylist.device(),
270 Some(stylist),
271 info,
272 size_query_container_lookup,
273 |context| {
274 let matches = self.condition.matches(context);
275 if context
276 .style()
277 .flags()
278 .contains(ComputedValueFlags::USES_VIEWPORT_UNITS)
279 {
280 invalidation_flags
283 .insert(ComputedValueFlags::USES_VIEWPORT_UNITS_ON_CONTAINER_QUERIES);
284 }
285 matches
286 },
287 )
288 }
289}
290
291#[derive(Copy, Clone)]
293pub struct ContainerInfo {
294 size: Size2D<Option<Au>>,
295 wm: WritingMode,
296}
297
298impl ContainerInfo {
299 fn size(&self) -> Option<Size2D<Au>> {
300 Some(Size2D::new(self.size.width?, self.size.height?))
301 }
302}
303
304fn eval_width(context: &Context) -> Option<CSSPixelLength> {
305 let info = context.container_info.as_ref()?;
306 Some(CSSPixelLength::new(info.size.width?.to_f32_px()))
307}
308
309fn eval_height(context: &Context) -> Option<CSSPixelLength> {
310 let info = context.container_info.as_ref()?;
311 Some(CSSPixelLength::new(info.size.height?.to_f32_px()))
312}
313
314fn eval_inline_size(context: &Context) -> Option<CSSPixelLength> {
315 let info = context.container_info.as_ref()?;
316 Some(CSSPixelLength::new(
317 LogicalSize::from_physical(info.wm, info.size)
318 .inline?
319 .to_f32_px(),
320 ))
321}
322
323fn eval_block_size(context: &Context) -> Option<CSSPixelLength> {
324 let info = context.container_info.as_ref()?;
325 Some(CSSPixelLength::new(
326 LogicalSize::from_physical(info.wm, info.size)
327 .block?
328 .to_f32_px(),
329 ))
330}
331
332fn eval_aspect_ratio(context: &Context) -> Option<Ratio> {
333 let info = context.container_info.as_ref()?;
334 Some(Ratio::new(
335 info.size.width?.0 as f32,
336 info.size.height?.0 as f32,
337 ))
338}
339
340fn eval_orientation(context: &Context, value: Option<Orientation>) -> KleeneValue {
341 let size = match context.container_info.as_ref().and_then(|info| info.size()) {
342 Some(size) => size,
343 None => return KleeneValue::Unknown,
344 };
345 KleeneValue::from(Orientation::eval(size, value))
346}
347
348pub static CONTAINER_FEATURES: [QueryFeatureDescription; 6] = [
352 feature!(
353 atom!("width"),
354 AllowsRanges::Yes,
355 Evaluator::OptionalLength(eval_width),
356 FeatureFlags::CONTAINER_REQUIRES_WIDTH_AXIS,
357 ),
358 feature!(
359 atom!("height"),
360 AllowsRanges::Yes,
361 Evaluator::OptionalLength(eval_height),
362 FeatureFlags::CONTAINER_REQUIRES_HEIGHT_AXIS,
363 ),
364 feature!(
365 atom!("inline-size"),
366 AllowsRanges::Yes,
367 Evaluator::OptionalLength(eval_inline_size),
368 FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS,
369 ),
370 feature!(
371 atom!("block-size"),
372 AllowsRanges::Yes,
373 Evaluator::OptionalLength(eval_block_size),
374 FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS,
375 ),
376 feature!(
377 atom!("aspect-ratio"),
378 AllowsRanges::Yes,
379 Evaluator::OptionalNumberRatio(eval_aspect_ratio),
380 FeatureFlags::from_bits_truncate(
383 FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS.bits()
384 | FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS.bits()
385 ),
386 ),
387 feature!(
388 atom!("orientation"),
389 AllowsRanges::No,
390 keyword_evaluator!(eval_orientation, Orientation),
391 FeatureFlags::from_bits_truncate(
392 FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS.bits()
393 | FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS.bits()
394 ),
395 ),
396];
397
398#[derive(Copy, Clone, Default)]
402pub struct ContainerSizeQueryResult {
403 width: Option<Au>,
404 height: Option<Au>,
405}
406
407impl ContainerSizeQueryResult {
408 fn get_viewport_size(context: &Context) -> Size2D<Au> {
409 use crate::values::specified::ViewportVariant;
410 context.viewport_size_for_viewport_unit_resolution(ViewportVariant::Small)
411 }
412
413 fn get_logical_viewport_size(context: &Context) -> LogicalSize<Au> {
414 LogicalSize::from_physical(
415 context.builder.writing_mode,
416 Self::get_viewport_size(context),
417 )
418 }
419
420 pub fn get_container_inline_size(&self, context: &Context) -> Au {
422 if context.builder.writing_mode.is_horizontal() {
423 if let Some(w) = self.width {
424 return w;
425 }
426 } else {
427 if let Some(h) = self.height {
428 return h;
429 }
430 }
431 Self::get_logical_viewport_size(context).inline
432 }
433
434 pub fn get_container_block_size(&self, context: &Context) -> Au {
436 if context.builder.writing_mode.is_horizontal() {
437 self.get_container_height(context)
438 } else {
439 self.get_container_width(context)
440 }
441 }
442
443 pub fn get_container_width(&self, context: &Context) -> Au {
445 if let Some(w) = self.width {
446 return w;
447 }
448 Self::get_viewport_size(context).width
449 }
450
451 pub fn get_container_height(&self, context: &Context) -> Au {
453 if let Some(h) = self.height {
454 return h;
455 }
456 Self::get_viewport_size(context).height
457 }
458
459 fn merge(self, new_result: Self) -> Self {
461 let mut result = self;
462 if let Some(width) = new_result.width {
463 result.width.get_or_insert(width);
464 }
465 if let Some(height) = new_result.height {
466 result.height.get_or_insert(height);
467 }
468 result
469 }
470
471 fn is_complete(&self) -> bool {
472 self.width.is_some() && self.height.is_some()
473 }
474}
475
476pub enum ContainerSizeQuery<'a> {
478 NotEvaluated(Box<dyn Fn() -> ContainerSizeQueryResult + 'a>),
480 Evaluated(ContainerSizeQueryResult),
482}
483
484impl<'a> ContainerSizeQuery<'a> {
485 fn evaluate_potential_size_container<E>(
486 e: E,
487 originating_element_style: Option<&ComputedValues>,
488 ) -> TraversalResult<ContainerSizeQueryResult>
489 where
490 E: TElement,
491 {
492 let data;
493 let style = match originating_element_style {
494 Some(s) => s,
495 None => {
496 data = match e.borrow_data() {
497 Some(d) => d,
498 None => return TraversalResult::InProgress,
499 };
500 &**data.styles.primary()
501 },
502 };
503 if !style
504 .flags
505 .contains(ComputedValueFlags::SELF_OR_ANCESTOR_HAS_SIZE_CONTAINER_TYPE)
506 {
507 return TraversalResult::StopTraversal;
509 }
510
511 let wm = style.writing_mode;
512 let box_style = style.get_box();
513
514 let container_type = box_style.clone_container_type();
515 let size = e.query_container_size(&box_style.clone_display());
516 if container_type.intersects(ContainerType::SIZE) {
517 TraversalResult::Done(ContainerSizeQueryResult {
518 width: size.width,
519 height: size.height,
520 })
521 } else if container_type.intersects(ContainerType::INLINE_SIZE) {
522 if wm.is_horizontal() {
523 TraversalResult::Done(ContainerSizeQueryResult {
524 width: size.width,
525 height: None,
526 })
527 } else {
528 TraversalResult::Done(ContainerSizeQueryResult {
529 width: None,
530 height: size.height,
531 })
532 }
533 } else {
534 TraversalResult::InProgress
535 }
536 }
537
538 fn lookup<E>(
540 element: E,
541 originating_element_style: Option<&ComputedValues>,
542 ) -> ContainerSizeQueryResult
543 where
544 E: TElement + 'a,
545 {
546 match traverse_container(
547 element,
548 originating_element_style,
549 |e, originating_element_style| {
550 Self::evaluate_potential_size_container(e, originating_element_style)
551 },
552 ) {
553 Some((container, result)) => {
554 if result.is_complete() {
555 result
556 } else {
557 result.merge(Self::lookup(container, None))
559 }
560 },
561 None => ContainerSizeQueryResult::default(),
562 }
563 }
564
565 pub fn for_element<E>(
567 element: E,
568 known_parent_style: Option<&'a ComputedValues>,
569 is_pseudo: bool,
570 ) -> Self
571 where
572 E: TElement + 'a,
573 {
574 let parent;
575 let data;
576 let parent_style = match known_parent_style {
577 Some(s) => Some(s),
578 None => {
579 parent = match element.traversal_parent() {
581 Some(parent) => parent,
582 None => return Self::none(),
583 };
584 data = parent.borrow_data();
585 data.as_ref().map(|data| &**data.styles.primary())
586 },
587 };
588
589 let should_traverse = parent_style.map_or(true, |s| {
592 s.flags
593 .contains(ComputedValueFlags::SELF_OR_ANCESTOR_HAS_SIZE_CONTAINER_TYPE)
594 });
595 if !should_traverse {
596 return Self::none();
597 }
598 return Self::NotEvaluated(Box::new(move || {
599 Self::lookup(element, if is_pseudo { known_parent_style } else { None })
600 }));
601 }
602
603 pub fn for_option_element<E>(
605 element: Option<E>,
606 known_parent_style: Option<&'a ComputedValues>,
607 is_pseudo: bool,
608 ) -> Self
609 where
610 E: TElement + 'a,
611 {
612 if let Some(e) = element {
613 Self::for_element(e, known_parent_style, is_pseudo)
614 } else {
615 Self::none()
616 }
617 }
618
619 pub fn none() -> Self {
621 ContainerSizeQuery::Evaluated(ContainerSizeQueryResult::default())
622 }
623
624 pub fn get(&mut self) -> ContainerSizeQueryResult {
626 match self {
627 Self::NotEvaluated(lookup) => {
628 *self = Self::Evaluated((lookup)());
629 match self {
630 Self::Evaluated(info) => *info,
631 _ => unreachable!("Just evaluated but not set?"),
632 }
633 },
634 Self::Evaluated(info) => *info,
635 }
636 }
637}