1use std::cell::{LazyCell, OnceCell};
8use std::ops::{Add, AddAssign};
9
10use app_units::{Au, MAX_AU};
11use malloc_size_of_derive::MallocSizeOf;
12use style::Zero;
13use style::logical_geometry::Direction;
14use style::values::computed::{
15 LengthPercentage, MaxSize as StyleMaxSize, Percentage, Size as StyleSize,
16};
17
18use crate::context::LayoutContext;
19use crate::style_ext::{AspectRatio, Clamp, ComputedValuesExt, ContentBoxSizesAndPBM, LayoutStyle};
20use crate::{ConstraintSpace, IndefiniteContainingBlock, LogicalVec2};
21
22#[derive(PartialEq)]
23pub(crate) enum IntrinsicSizingMode {
24 Contribution,
30 Size,
36}
37
38#[derive(Clone, Copy, Debug, Default, MallocSizeOf)]
39pub(crate) struct ContentSizes {
40 pub min_content: Au,
41 pub max_content: Au,
42}
43
44impl ContentSizes {
46 pub fn max(&self, other: Self) -> Self {
47 Self {
48 min_content: self.min_content.max(other.min_content),
49 max_content: self.max_content.max(other.max_content),
50 }
51 }
52
53 pub fn max_assign(&mut self, other: Self) {
54 *self = self.max(other);
55 }
56
57 pub fn union(&self, other: &Self) -> Self {
58 Self {
59 min_content: self.min_content.max(other.min_content),
60 max_content: self.max_content + other.max_content,
61 }
62 }
63
64 pub fn map(&self, f: impl Fn(Au) -> Au) -> Self {
65 Self {
66 min_content: f(self.min_content),
67 max_content: f(self.max_content),
68 }
69 }
70}
71
72impl Zero for ContentSizes {
73 fn zero() -> Self {
74 Au::zero().into()
75 }
76
77 fn is_zero(&self) -> bool {
78 self.min_content.is_zero() && self.max_content.is_zero()
79 }
80}
81
82impl Add for ContentSizes {
83 type Output = Self;
84
85 fn add(self, rhs: Self) -> Self {
86 Self {
87 min_content: self.min_content + rhs.min_content,
88 max_content: self.max_content + rhs.max_content,
89 }
90 }
91}
92
93impl AddAssign for ContentSizes {
94 fn add_assign(&mut self, rhs: Self) {
95 *self = self.add(rhs)
96 }
97}
98
99impl ContentSizes {
100 pub fn shrink_to_fit(&self, available_size: Au) -> Au {
105 available_size.min(self.max_content).max(self.min_content)
109 }
110}
111
112impl From<Au> for ContentSizes {
113 fn from(size: Au) -> Self {
114 Self {
115 min_content: size,
116 max_content: size,
117 }
118 }
119}
120
121#[allow(clippy::too_many_arguments)]
122pub(crate) fn outer_inline(
123 layout_style: &LayoutStyle,
124 containing_block: &IndefiniteContainingBlock,
125 auto_minimum: &LogicalVec2<Au>,
126 auto_block_size_stretches_to_containing_block: bool,
127 is_replaced: bool,
128 establishes_containing_block: bool,
129 get_preferred_aspect_ratio: impl FnOnce(&LogicalVec2<Au>) -> Option<AspectRatio>,
130 get_inline_content_size: impl FnOnce(&ConstraintSpace) -> InlineContentSizesResult,
131 get_tentative_block_content_size: impl FnOnce(Option<AspectRatio>) -> Option<ContentSizes>,
132) -> InlineContentSizesResult {
133 let ContentBoxSizesAndPBM {
134 content_box_sizes,
135 pbm,
136 mut depends_on_block_constraints,
137 preferred_size_computes_to_auto,
138 } = layout_style.content_box_sizes_and_padding_border_margin(containing_block);
139 let margin = pbm.margin.map(|v| v.auto_is(Au::zero));
140 let pbm_sums = LogicalVec2 {
141 block: pbm.padding_border_sums.block + margin.block_sum(),
142 inline: pbm.padding_border_sums.inline + margin.inline_sum(),
143 };
144 let style = layout_style.style();
145 let is_table = layout_style.is_table();
146 let content_size = LazyCell::new(|| {
147 let constraint_space = if establishes_containing_block {
148 let available_block_size = containing_block
149 .size
150 .block
151 .map(|v| Au::zero().max(v - pbm_sums.block));
152 let automatic_size = if preferred_size_computes_to_auto.block &&
153 auto_block_size_stretches_to_containing_block
154 {
155 depends_on_block_constraints = true;
156 Size::Stretch
157 } else {
158 Size::FitContent
159 };
160 let aspect_ratio = get_preferred_aspect_ratio(&pbm.padding_border_sums);
161 let block_size =
162 if let Some(block_content_size) = get_tentative_block_content_size(aspect_ratio) {
163 SizeConstraint::Definite(content_box_sizes.block.resolve(
164 Direction::Block,
165 automatic_size,
166 || auto_minimum.block,
167 available_block_size,
168 || block_content_size,
169 is_table,
170 ))
171 } else {
172 content_box_sizes.block.resolve_extrinsic(
173 automatic_size,
174 auto_minimum.block,
175 available_block_size,
176 )
177 };
178 ConstraintSpace::new(block_size, style.writing_mode, aspect_ratio)
179 } else {
180 ConstraintSpace::new(
184 containing_block.size.block.into(),
185 containing_block.writing_mode,
186 None,
187 )
188 };
189 get_inline_content_size(&constraint_space)
190 });
191 let resolve_non_initial = |inline_size, stretch_values| {
192 Some(match inline_size {
193 Size::Initial => return None,
194 Size::Numeric(numeric) => (numeric, numeric, false),
195 Size::MinContent => (
196 content_size.sizes.min_content,
197 content_size.sizes.min_content,
198 content_size.depends_on_block_constraints,
199 ),
200 Size::MaxContent => (
201 content_size.sizes.max_content,
202 content_size.sizes.max_content,
203 content_size.depends_on_block_constraints,
204 ),
205 Size::FitContent => (
206 content_size.sizes.min_content,
207 content_size.sizes.max_content,
208 content_size.depends_on_block_constraints,
209 ),
210 Size::FitContentFunction(size) => {
211 let size = content_size.sizes.shrink_to_fit(size);
212 (size, size, content_size.depends_on_block_constraints)
213 },
214 Size::Stretch => return stretch_values,
215 })
216 };
217 let (mut preferred_min_content, preferred_max_content, preferred_depends_on_block_constraints) =
218 resolve_non_initial(content_box_sizes.inline.preferred, None)
219 .unwrap_or_else(|| resolve_non_initial(Size::FitContent, None).unwrap());
220 let (mut min_min_content, mut min_max_content, mut min_depends_on_block_constraints) =
221 resolve_non_initial(
222 content_box_sizes.inline.min,
223 Some((Au::zero(), Au::zero(), false)),
224 )
225 .unwrap_or((auto_minimum.inline, auto_minimum.inline, false));
226 let (mut max_min_content, max_max_content, max_depends_on_block_constraints) =
227 resolve_non_initial(content_box_sizes.inline.max, None)
228 .map(|(min_content, max_content, depends_on_block_constraints)| {
229 (
230 Some(min_content),
231 Some(max_content),
232 depends_on_block_constraints,
233 )
234 })
235 .unwrap_or_default();
236
237 if is_replaced {
245 let has_percentage = |size: Size<LengthPercentage>| {
246 matches!(size, Size::Numeric(numeric) if numeric.has_percentage())
248 };
249 if content_box_sizes.inline.preferred.is_initial() &&
250 has_percentage(style.box_size(containing_block.writing_mode).inline)
251 {
252 preferred_min_content = Au::zero();
253 }
254 if content_box_sizes.inline.max.is_initial() &&
255 has_percentage(style.max_box_size(containing_block.writing_mode).inline)
256 {
257 max_min_content = Some(Au::zero());
258 }
259 }
260
261 if is_table {
264 min_min_content.max_assign(content_size.sizes.min_content);
265 min_max_content.max_assign(content_size.sizes.min_content);
266 min_depends_on_block_constraints |= content_size.depends_on_block_constraints;
267 }
268
269 InlineContentSizesResult {
270 sizes: ContentSizes {
271 min_content: preferred_min_content
272 .clamp_between_extremums(min_min_content, max_min_content) +
273 pbm_sums.inline,
274 max_content: preferred_max_content
275 .clamp_between_extremums(min_max_content, max_max_content) +
276 pbm_sums.inline,
277 },
278 depends_on_block_constraints: depends_on_block_constraints &&
279 (preferred_depends_on_block_constraints ||
280 min_depends_on_block_constraints ||
281 max_depends_on_block_constraints),
282 }
283}
284
285#[derive(Clone, Copy, Debug, MallocSizeOf)]
286pub(crate) struct InlineContentSizesResult {
287 pub sizes: ContentSizes,
288 pub depends_on_block_constraints: bool,
289}
290
291pub(crate) trait ComputeInlineContentSizes {
292 fn compute_inline_content_sizes(
293 &self,
294 layout_context: &LayoutContext,
295 constraint_space: &ConstraintSpace,
296 ) -> InlineContentSizesResult;
297
298 fn compute_inline_content_sizes_with_fixup(
302 &self,
303 layout_context: &LayoutContext,
304 constraint_space: &ConstraintSpace,
305 ) -> InlineContentSizesResult {
306 let mut result = self.compute_inline_content_sizes(layout_context, constraint_space);
307 let sizes = &mut result.sizes;
308 sizes.max_content.max_assign(sizes.min_content);
309 result
310 }
311}
312
313#[derive(Clone, Debug, PartialEq)]
316pub(crate) enum Size<T> {
317 Initial,
322 MinContent,
324 MaxContent,
326 FitContent,
328 FitContentFunction(T),
330 Stretch,
332 Numeric(T),
335}
336
337impl<T: Copy> Copy for Size<T> {}
338
339impl<T> Default for Size<T> {
340 #[inline]
341 fn default() -> Self {
342 Self::Initial
343 }
344}
345
346impl<T> Size<T> {
347 #[inline]
348 pub(crate) fn is_initial(&self) -> bool {
349 matches!(self, Self::Initial)
350 }
351}
352
353impl<T: Clone> Size<T> {
354 #[inline]
355 pub(crate) fn to_numeric(&self) -> Option<T> {
356 match self {
357 Self::Numeric(numeric) => Some(numeric).cloned(),
358 _ => None,
359 }
360 }
361
362 #[inline]
363 pub(crate) fn map<U>(&self, f: impl FnOnce(T) -> U) -> Size<U> {
364 match self {
365 Size::Initial => Size::Initial,
366 Size::MinContent => Size::MinContent,
367 Size::MaxContent => Size::MaxContent,
368 Size::FitContent => Size::FitContent,
369 Size::FitContentFunction(size) => Size::FitContentFunction(f(size.clone())),
370 Size::Stretch => Size::Stretch,
371 Size::Numeric(numeric) => Size::Numeric(f(numeric.clone())),
372 }
373 }
374}
375
376impl From<StyleSize> for Size<LengthPercentage> {
377 fn from(size: StyleSize) -> Self {
378 match size {
379 StyleSize::LengthPercentage(lp) => Size::Numeric(lp.0),
380 StyleSize::Auto => Size::Initial,
381 StyleSize::MinContent => Size::MinContent,
382 StyleSize::MaxContent => Size::MaxContent,
383 StyleSize::FitContent => Size::FitContent,
384 StyleSize::FitContentFunction(lp) => Size::FitContentFunction(lp.0),
385 StyleSize::Stretch => Size::Stretch,
386 StyleSize::AnchorSizeFunction(_) | StyleSize::AnchorContainingCalcFunction(_) => {
387 unreachable!("anchor-size() should be disabled")
388 },
389 }
390 }
391}
392
393impl From<StyleMaxSize> for Size<LengthPercentage> {
394 fn from(max_size: StyleMaxSize) -> Self {
395 match max_size {
396 StyleMaxSize::LengthPercentage(lp) => Size::Numeric(lp.0),
397 StyleMaxSize::None => Size::Initial,
398 StyleMaxSize::MinContent => Size::MinContent,
399 StyleMaxSize::MaxContent => Size::MaxContent,
400 StyleMaxSize::FitContent => Size::FitContent,
401 StyleMaxSize::FitContentFunction(lp) => Size::FitContentFunction(lp.0),
402 StyleMaxSize::Stretch => Size::Stretch,
403 StyleMaxSize::AnchorSizeFunction(_) | StyleMaxSize::AnchorContainingCalcFunction(_) => {
404 unreachable!("anchor-size() should be disabled")
405 },
406 }
407 }
408}
409
410impl Size<LengthPercentage> {
411 #[inline]
412 pub(crate) fn to_percentage(&self) -> Option<Percentage> {
413 self.to_numeric()
414 .and_then(|length_percentage| length_percentage.to_percentage())
415 }
416
417 #[inline]
422 pub(crate) fn resolve_percentages_for_preferred(&self, basis: Option<Au>) -> Size<Au> {
423 match self {
424 Size::Numeric(numeric) => numeric
425 .maybe_to_used_value(basis)
426 .map_or(Size::Initial, Size::Numeric),
427 Size::FitContentFunction(numeric) => {
428 numeric
430 .maybe_to_used_value(basis)
431 .map_or(Size::FitContent, Size::FitContentFunction)
432 },
433 _ => self.map(|_| unreachable!("This shouldn't be called for keywords")),
434 }
435 }
436
437 #[inline]
442 pub(crate) fn resolve_percentages_for_max(&self, basis: Option<Au>) -> Size<Au> {
443 match self {
444 Size::Numeric(numeric) => numeric
445 .maybe_to_used_value(basis)
446 .map_or(Size::Initial, Size::Numeric),
447 Size::FitContentFunction(numeric) => {
448 numeric
450 .maybe_to_used_value(basis)
451 .map_or(Size::MaxContent, Size::FitContentFunction)
452 },
453 _ => self.map(|_| unreachable!("This shouldn't be called for keywords")),
454 }
455 }
456}
457
458impl LogicalVec2<Size<LengthPercentage>> {
459 pub(crate) fn percentages_relative_to_basis(
460 &self,
461 basis: &LogicalVec2<Au>,
462 ) -> LogicalVec2<Size<Au>> {
463 LogicalVec2 {
464 inline: self.inline.map(|value| value.to_used_value(basis.inline)),
465 block: self.block.map(|value| value.to_used_value(basis.block)),
466 }
467 }
468}
469
470impl Size<Au> {
471 #[inline]
474 pub(crate) fn resolve_for_preferred<F: FnOnce() -> ContentSizes>(
475 &self,
476 automatic_size: Size<Au>,
477 stretch_size: Option<Au>,
478 content_size: &LazyCell<ContentSizes, F>,
479 ) -> Au {
480 match self {
481 Self::Initial => {
482 assert!(!automatic_size.is_initial());
483 automatic_size.resolve_for_preferred(automatic_size, stretch_size, content_size)
484 },
485 Self::MinContent => content_size.min_content,
486 Self::MaxContent => content_size.max_content,
487 Self::FitContentFunction(size) => content_size.shrink_to_fit(*size),
488 Self::FitContent => {
489 content_size.shrink_to_fit(stretch_size.unwrap_or_else(|| content_size.max_content))
490 },
491 Self::Stretch => stretch_size.unwrap_or_else(|| content_size.max_content),
492 Self::Numeric(numeric) => *numeric,
493 }
494 }
495
496 #[inline]
499 pub(crate) fn resolve_for_min<F: FnOnce() -> ContentSizes>(
500 &self,
501 get_automatic_minimum_size: impl FnOnce() -> Au,
502 stretch_size: Option<Au>,
503 content_size: &LazyCell<ContentSizes, F>,
504 is_table: bool,
505 ) -> Au {
506 let result = match self {
507 Self::Initial => get_automatic_minimum_size(),
508 Self::MinContent => content_size.min_content,
509 Self::MaxContent => content_size.max_content,
510 Self::FitContentFunction(size) => content_size.shrink_to_fit(*size),
511 Self::FitContent => content_size.shrink_to_fit(stretch_size.unwrap_or_default()),
512 Self::Stretch => stretch_size.unwrap_or_default(),
513 Self::Numeric(numeric) => *numeric,
514 };
515 if is_table {
516 result.max(content_size.min_content)
525 } else {
526 result
527 }
528 }
529
530 #[inline]
533 pub(crate) fn resolve_for_max<F: FnOnce() -> ContentSizes>(
534 &self,
535 stretch_size: Option<Au>,
536 content_size: &LazyCell<ContentSizes, F>,
537 ) -> Option<Au> {
538 Some(match self {
539 Self::Initial => return None,
540 Self::MinContent => content_size.min_content,
541 Self::MaxContent => content_size.max_content,
542 Self::FitContentFunction(size) => content_size.shrink_to_fit(*size),
543 Self::FitContent => content_size.shrink_to_fit(stretch_size.unwrap_or(MAX_AU)),
544 Self::Stretch => return stretch_size,
545 Self::Numeric(numeric) => *numeric,
546 })
547 }
548
549 #[inline]
559 pub(crate) fn maybe_resolve_extrinsic(&self, stretch_size: Option<Au>) -> Option<Au> {
560 match self {
561 Self::Initial |
562 Self::MinContent |
563 Self::MaxContent |
564 Self::FitContent |
565 Self::FitContentFunction(_) => None,
566 Self::Stretch => stretch_size,
567 Self::Numeric(numeric) => Some(*numeric),
568 }
569 }
570}
571
572#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
575pub(crate) enum SizeConstraint {
576 Definite(Au),
578 MinMax(Au, Option<Au>),
581}
582
583impl Default for SizeConstraint {
584 #[inline]
585 fn default() -> Self {
586 Self::MinMax(Au::default(), None)
587 }
588}
589
590impl SizeConstraint {
591 #[inline]
592 pub(crate) fn new(preferred_size: Option<Au>, min_size: Au, max_size: Option<Au>) -> Self {
593 preferred_size.map_or_else(
594 || Self::MinMax(min_size, max_size),
595 |size| Self::Definite(size.clamp_between_extremums(min_size, max_size)),
596 )
597 }
598
599 #[inline]
600 pub(crate) fn is_definite(self) -> bool {
601 matches!(self, Self::Definite(_))
602 }
603
604 #[inline]
605 pub(crate) fn to_definite(self) -> Option<Au> {
606 match self {
607 Self::Definite(size) => Some(size),
608 _ => None,
609 }
610 }
611}
612
613impl From<Option<Au>> for SizeConstraint {
614 fn from(size: Option<Au>) -> Self {
615 size.map(SizeConstraint::Definite).unwrap_or_default()
616 }
617}
618
619#[derive(Clone, Debug, Default)]
620pub(crate) struct Sizes {
621 pub preferred: Size<Au>,
623 pub min: Size<Au>,
625 pub max: Size<Au>,
627}
628
629impl Sizes {
630 #[inline]
631 pub(crate) fn new(preferred: Size<Au>, min: Size<Au>, max: Size<Au>) -> Self {
632 Self {
633 preferred,
634 min,
635 max,
636 }
637 }
638
639 #[inline]
641 pub(crate) fn resolve(
642 &self,
643 axis: Direction,
644 automatic_size: Size<Au>,
645 get_automatic_minimum_size: impl FnOnce() -> Au,
646 stretch_size: Option<Au>,
647 get_content_size: impl FnOnce() -> ContentSizes,
648 is_table: bool,
649 ) -> Au {
650 if is_table && axis == Direction::Block {
651 return get_content_size().max_content;
656 }
657 let (preferred, min, max) = self.resolve_each(
658 automatic_size,
659 get_automatic_minimum_size,
660 stretch_size,
661 get_content_size,
662 is_table,
663 );
664 preferred.clamp_between_extremums(min, max)
665 }
666
667 #[inline]
672 pub(crate) fn resolve_each(
673 &self,
674 automatic_size: Size<Au>,
675 get_automatic_minimum_size: impl FnOnce() -> Au,
676 stretch_size: Option<Au>,
677 get_content_size: impl FnOnce() -> ContentSizes,
678 is_table: bool,
679 ) -> (Au, Au, Option<Au>) {
680 let content_size = LazyCell::new(get_content_size);
683 (
684 self.preferred
685 .resolve_for_preferred(automatic_size, stretch_size, &content_size),
686 self.min.resolve_for_min(
687 get_automatic_minimum_size,
688 stretch_size,
689 &content_size,
690 is_table,
691 ),
692 self.max.resolve_for_max(stretch_size, &content_size),
693 )
694 }
695
696 #[inline]
702 pub(crate) fn resolve_extrinsic(
703 &self,
704 automatic_size: Size<Au>,
705 automatic_minimum_size: Au,
706 stretch_size: Option<Au>,
707 ) -> SizeConstraint {
708 let (preferred, min, max) =
709 self.resolve_each_extrinsic(automatic_size, automatic_minimum_size, stretch_size);
710 SizeConstraint::new(preferred, min, max)
711 }
712
713 #[inline]
723 pub(crate) fn resolve_each_extrinsic(
724 &self,
725 automatic_size: Size<Au>,
726 automatic_minimum_size: Au,
727 stretch_size: Option<Au>,
728 ) -> (Option<Au>, Au, Option<Au>) {
729 (
730 if self.preferred.is_initial() {
731 automatic_size.maybe_resolve_extrinsic(stretch_size)
732 } else {
733 self.preferred.maybe_resolve_extrinsic(stretch_size)
734 },
735 self.min
736 .maybe_resolve_extrinsic(stretch_size)
737 .unwrap_or(automatic_minimum_size),
738 self.max.maybe_resolve_extrinsic(stretch_size),
739 )
740 }
741}
742
743struct LazySizeData<'a> {
744 sizes: &'a Sizes,
745 axis: Direction,
746 automatic_size: Size<Au>,
747 get_automatic_minimum_size: fn() -> Au,
748 stretch_size: Option<Au>,
749 is_table: bool,
750}
751
752pub(crate) struct LazySize<'a> {
756 result: OnceCell<Au>,
757 data: Option<LazySizeData<'a>>,
758}
759
760impl<'a> LazySize<'a> {
761 pub(crate) fn new(
762 sizes: &'a Sizes,
763 axis: Direction,
764 automatic_size: Size<Au>,
765 get_automatic_minimum_size: fn() -> Au,
766 stretch_size: Option<Au>,
767 is_table: bool,
768 ) -> Self {
769 Self {
770 result: OnceCell::new(),
771 data: Some(LazySizeData {
772 sizes,
773 axis,
774 automatic_size,
775 get_automatic_minimum_size,
776 stretch_size,
777 is_table,
778 }),
779 }
780 }
781
782 pub(crate) fn intrinsic() -> Self {
790 Self {
791 result: OnceCell::new(),
792 data: None,
793 }
794 }
795
796 pub(crate) fn resolve(&self, get_content_size: impl FnOnce() -> Au) -> Au {
801 *self.result.get_or_init(|| {
802 let Some(ref data) = self.data else {
803 return get_content_size();
804 };
805 data.sizes.resolve(
806 data.axis,
807 data.automatic_size,
808 data.get_automatic_minimum_size,
809 data.stretch_size,
810 || get_content_size().into(),
811 data.is_table,
812 )
813 })
814 }
815}
816
817impl From<Au> for LazySize<'_> {
818 fn from(value: Au) -> Self {
821 let result = OnceCell::new();
822 result.set(value).unwrap();
823 LazySize { result, data: None }
824 }
825}