1use std::collections::HashMap;
15
16use crate::error::{GuiError, GuiResult};
17use crate::layout::{
18 AvailableSpace, Dimension, LayoutNodeId, LengthPercentage, LengthPercentageAuto, Point, Rect,
19 Size, Style,
20};
21
22pub const MAX_LAYOUT_DEPTH: usize = 128;
24
25pub const STRICT_TOLERANCE_PX: f32 = 0.01;
27
28#[derive(Debug, Clone, Copy, PartialEq, Default)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
32pub struct BoxDimensions {
33 pub content: Size<f32>,
35 pub padding: Rect<f32>,
37 pub border: Rect<f32>,
39 pub margin: Rect<f32>,
41}
42
43impl BoxDimensions {
44 pub const ZERO: Self = Self {
46 content: Size::ZERO,
47 padding: Rect {
48 left: 0.0,
49 right: 0.0,
50 top: 0.0,
51 bottom: 0.0,
52 },
53 border: Rect {
54 left: 0.0,
55 right: 0.0,
56 top: 0.0,
57 bottom: 0.0,
58 },
59 margin: Rect {
60 left: 0.0,
61 right: 0.0,
62 top: 0.0,
63 bottom: 0.0,
64 },
65 };
66
67 pub fn content_box(&self) -> Size<f32> {
69 self.content
70 }
71
72 pub fn padding_box(&self) -> Size<f32> {
74 Size::new(
75 (self.content.width + self.padding.left + self.padding.right).max(0.0),
76 (self.content.height + self.padding.top + self.padding.bottom).max(0.0),
77 )
78 }
79
80 pub fn border_box(&self) -> Size<f32> {
83 let p_box = self.padding_box();
84 Size::new(
85 (p_box.width + self.border.left + self.border.right).max(0.0),
86 (p_box.height + self.border.top + self.border.bottom).max(0.0),
87 )
88 }
89
90 pub fn margin_box(&self) -> Size<f32> {
93 let b_box = self.border_box();
94 Size::new(
95 (b_box.width + self.margin.left + self.margin.right).max(0.0),
96 (b_box.height + self.margin.top + self.margin.bottom).max(0.0),
97 )
98 }
99
100 pub fn validate(&self) -> GuiResult<()> {
102 if !self.content.width.is_finite()
103 || !self.content.height.is_finite()
104 || self.content.width < 0.0
105 || self.content.height < 0.0
106 {
107 return Err(GuiError::InvalidLayoutGeometry);
108 }
109 if !self.padding.left.is_finite()
110 || !self.padding.right.is_finite()
111 || !self.padding.top.is_finite()
112 || !self.padding.bottom.is_finite()
113 || self.padding.left < 0.0
114 || self.padding.right < 0.0
115 || self.padding.top < 0.0
116 || self.padding.bottom < 0.0
117 {
118 return Err(GuiError::InvalidLayoutGeometry);
119 }
120 if !self.border.left.is_finite()
121 || !self.border.right.is_finite()
122 || !self.border.top.is_finite()
123 || !self.border.bottom.is_finite()
124 || self.border.left < 0.0
125 || self.border.right < 0.0
126 || self.border.top < 0.0
127 || self.border.bottom < 0.0
128 {
129 return Err(GuiError::InvalidLayoutGeometry);
130 }
131 if !self.margin.left.is_finite()
132 || !self.margin.right.is_finite()
133 || !self.margin.top.is_finite()
134 || !self.margin.bottom.is_finite()
135 {
136 return Err(GuiError::InvalidNumericInput);
137 }
138 Ok(())
139 }
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Default)]
144pub struct BoxConstraints {
145 pub min_size: Size<Option<f32>>,
146 pub max_size: Size<Option<f32>>,
147 pub aspect_ratio: Option<f32>,
148}
149
150impl BoxConstraints {
151 pub fn clamp_dimension(val: f32, min: Option<f32>, max: Option<f32>) -> f32 {
156 let mut result = val;
157 if let Some(max_val) = max {
158 result = result.min(max_val);
159 }
160 if let Some(min_val) = min {
161 result = result.max(min_val);
162 }
163 result.max(0.0)
164 }
165
166 pub fn clamp_size(&self, size: Size<f32>) -> Size<f32> {
168 Size::new(
169 Self::clamp_dimension(size.width, self.min_size.width, self.max_size.width),
170 Self::clamp_dimension(size.height, self.min_size.height, self.max_size.height),
171 )
172 }
173
174 pub fn apply_aspect_ratio(&self, size: Size<Option<f32>>) -> Size<Option<f32>> {
179 let Some(ratio) = self.aspect_ratio else {
180 return size;
181 };
182 if ratio <= 0.0 || !ratio.is_finite() {
183 return size;
184 }
185
186 match (size.width, size.height) {
187 (Some(w), None) => Size::new(Some(w), Some((w / ratio).max(0.0))),
188 (None, Some(h)) => Size::new(Some((h * ratio).max(0.0)), Some(h)),
189 _ => size,
190 }
191 }
192}
193
194pub fn resolve_dimension(dim: Dimension, space: AvailableSpace) -> Option<f32> {
203 match dim {
204 Dimension::Length(px) => Some(px.max(0.0)),
205 Dimension::Percent(pct) => match space {
206 AvailableSpace::Definite(parent_size) => Some((parent_size * pct).max(0.0)),
207 _ => None,
208 },
209 Dimension::Auto => None,
210 }
211}
212
213pub fn resolve_padding(
215 padding: &Rect<LengthPercentage>,
216 available_space: Size<AvailableSpace>,
217) -> Rect<f32> {
218 let left = match padding.left {
219 LengthPercentage::Length(px) => px.max(0.0),
220 LengthPercentage::Percent(p) => match available_space.width {
221 AvailableSpace::Definite(w) => (w * p).max(0.0),
222 _ => 0.0,
223 },
224 };
225 let right = match padding.right {
226 LengthPercentage::Length(px) => px.max(0.0),
227 LengthPercentage::Percent(p) => match available_space.width {
228 AvailableSpace::Definite(w) => (w * p).max(0.0),
229 _ => 0.0,
230 },
231 };
232 let top = match padding.top {
233 LengthPercentage::Length(px) => px.max(0.0),
234 LengthPercentage::Percent(p) => match available_space.height {
235 AvailableSpace::Definite(h) => (h * p).max(0.0),
236 _ => 0.0,
237 },
238 };
239 let bottom = match padding.bottom {
240 LengthPercentage::Length(px) => px.max(0.0),
241 LengthPercentage::Percent(p) => match available_space.height {
242 AvailableSpace::Definite(h) => (h * p).max(0.0),
243 _ => 0.0,
244 },
245 };
246 Rect::new(left, right, top, bottom)
247}
248
249pub fn resolve_margin(
252 margin: &Rect<LengthPercentageAuto>,
253 available_space: Size<AvailableSpace>,
254) -> Rect<f32> {
255 let left = match margin.left {
256 LengthPercentageAuto::Length(px) => px,
257 LengthPercentageAuto::Percent(p) => match available_space.width {
258 AvailableSpace::Definite(w) => w * p,
259 _ => 0.0,
260 },
261 LengthPercentageAuto::Auto => 0.0,
262 };
263 let right = match margin.right {
264 LengthPercentageAuto::Length(px) => px,
265 LengthPercentageAuto::Percent(p) => match available_space.width {
266 AvailableSpace::Definite(w) => w * p,
267 _ => 0.0,
268 },
269 LengthPercentageAuto::Auto => 0.0,
270 };
271 let top = match margin.top {
272 LengthPercentageAuto::Length(px) => px,
273 LengthPercentageAuto::Percent(p) => match available_space.height {
274 AvailableSpace::Definite(h) => h * p,
275 _ => 0.0,
276 },
277 LengthPercentageAuto::Auto => 0.0,
278 };
279 let bottom = match margin.bottom {
280 LengthPercentageAuto::Length(px) => px,
281 LengthPercentageAuto::Percent(p) => match available_space.height {
282 AvailableSpace::Definite(h) => h * p,
283 _ => 0.0,
284 },
285 LengthPercentageAuto::Auto => 0.0,
286 };
287 Rect::new(left, right, top, bottom)
288}
289
290pub fn resolve_inset(
292 inset: &Rect<LengthPercentageAuto>,
293 available_space: Size<AvailableSpace>,
294) -> Rect<Option<f32>> {
295 let resolve_axis = |val: LengthPercentageAuto, space: AvailableSpace| match val {
296 LengthPercentageAuto::Length(px) => Some(px),
297 LengthPercentageAuto::Percent(p) => match space {
298 AvailableSpace::Definite(s) => Some(s * p),
299 _ => None,
300 },
301 LengthPercentageAuto::Auto => None,
302 };
303 Rect::new(
304 resolve_axis(inset.left, available_space.width),
305 resolve_axis(inset.right, available_space.width),
306 resolve_axis(inset.top, available_space.height),
307 resolve_axis(inset.bottom, available_space.height),
308 )
309}
310
311pub fn resolve_box_constraints(
313 style: &Style,
314 available_space: Size<AvailableSpace>,
315) -> BoxConstraints {
316 BoxConstraints {
317 min_size: Size::new(
318 resolve_dimension(style.min_size.width, available_space.width),
319 resolve_dimension(style.min_size.height, available_space.height),
320 ),
321 max_size: Size::new(
322 resolve_dimension(style.max_size.width, available_space.width),
323 resolve_dimension(style.max_size.height, available_space.height),
324 ),
325 aspect_ratio: style.aspect_ratio,
326 }
327}
328
329pub fn compute_box_sizing(
332 style: &Style,
333 available_space: Size<AvailableSpace>,
334 intrinsic_size: Option<Size<f32>>,
335) -> GuiResult<BoxDimensions> {
336 style.validate()?;
337
338 let padding = resolve_padding(&style.padding, available_space);
339 let border = Rect::<f32>::new(0.0, 0.0, 0.0, 0.0);
340 let margin = resolve_margin(&style.margin, available_space);
341 let constraints = resolve_box_constraints(style, available_space);
342
343 let mut raw_width = resolve_dimension(style.size.width, available_space.width);
344 let mut raw_height = resolve_dimension(style.size.height, available_space.height);
345
346 if raw_width.is_none() {
348 if let Some(intr) = intrinsic_size {
349 raw_width = Some(intr.width);
350 }
351 }
352 if raw_height.is_none() {
353 if let Some(intr) = intrinsic_size {
354 raw_height = Some(intr.height);
355 }
356 }
357
358 let sized = constraints.apply_aspect_ratio(Size::new(raw_width, raw_height));
360 let mut resolved_w = sized.width.unwrap_or(0.0);
361 let mut resolved_h = sized.height.unwrap_or(0.0);
362
363 resolved_w = BoxConstraints::clamp_dimension(
365 resolved_w,
366 constraints.min_size.width,
367 constraints.max_size.width,
368 );
369 resolved_h = BoxConstraints::clamp_dimension(
370 resolved_h,
371 constraints.min_size.height,
372 constraints.max_size.height,
373 );
374
375 if raw_height.is_none() && style.aspect_ratio.is_some() {
377 if let Some(ratio) = style.aspect_ratio {
378 if ratio > 0.0 && ratio.is_finite() {
379 resolved_h = (resolved_w / ratio).max(0.0);
380 resolved_h = BoxConstraints::clamp_dimension(
381 resolved_h,
382 constraints.min_size.height,
383 constraints.max_size.height,
384 );
385 }
386 }
387 } else if raw_width.is_none() && style.aspect_ratio.is_some() {
388 if let Some(ratio) = style.aspect_ratio {
389 if ratio > 0.0 && ratio.is_finite() {
390 resolved_w = (resolved_h * ratio).max(0.0);
391 resolved_w = BoxConstraints::clamp_dimension(
392 resolved_w,
393 constraints.min_size.width,
394 constraints.max_size.width,
395 );
396 }
397 }
398 }
399
400 let b_box = Size::new(resolved_w, resolved_h);
401 let content_w =
402 (b_box.width - padding.left - padding.right - border.left - border.right).max(0.0);
403 let content_h =
404 (b_box.height - padding.top - padding.bottom - border.top - border.bottom).max(0.0);
405
406 let dims = BoxDimensions {
407 content: Size::new(content_w, content_h),
408 padding,
409 border,
410 margin,
411 };
412 dims.validate()?;
413 Ok(dims)
414}
415
416pub fn apply_relative_offset(flow_position: Point<f32>, inset: &Rect<Option<f32>>) -> Point<f32> {
418 let mut x = flow_position.x;
419 let mut y = flow_position.y;
420
421 if let Some(left) = inset.left {
422 x += left;
423 } else if let Some(right) = inset.right {
424 x -= right;
425 }
426
427 if let Some(top) = inset.top {
428 y += top;
429 } else if let Some(bottom) = inset.bottom {
430 y -= bottom;
431 }
432
433 Point::new(x, y)
434}
435
436pub fn resolve_absolute_position(
439 parent_padding_origin: Point<f32>,
440 parent_padding_size: Size<f32>,
441 child_size: Size<f32>,
442 inset: &Rect<Option<f32>>,
443 margin: &Rect<f32>,
444) -> Point<f32> {
445 let x = if let Some(left) = inset.left {
446 parent_padding_origin.x + left + margin.left
447 } else if let Some(right) = inset.right {
448 parent_padding_origin.x + parent_padding_size.width
449 - child_size.width
450 - right
451 - margin.right
452 } else {
453 parent_padding_origin.x + margin.left
454 };
455
456 let y = if let Some(top) = inset.top {
457 parent_padding_origin.y + top + margin.top
458 } else if let Some(bottom) = inset.bottom {
459 parent_padding_origin.y + parent_padding_size.height
460 - child_size.height
461 - bottom
462 - margin.bottom
463 } else {
464 parent_padding_origin.y + margin.top
465 };
466
467 Point::new(x, y)
468}
469
470pub trait Measurer {
472 fn measure(
473 &mut self,
474 node: LayoutNodeId,
475 known_dimensions: Size<Option<f32>>,
476 available_space: Size<AvailableSpace>,
477 ) -> Option<Size<f32>>;
478}
479
480impl<F> Measurer for F
481where
482 F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
483{
484 fn measure(
485 &mut self,
486 node: LayoutNodeId,
487 known_dimensions: Size<Option<f32>>,
488 available_space: Size<AvailableSpace>,
489 ) -> Option<Size<f32>> {
490 self(node, known_dimensions, available_space)
491 }
492}
493
494#[derive(Debug, Clone, PartialEq, Eq, Hash)]
496struct TextMeasureKey {
497 text: String,
498 known_hundredths: Option<i64>,
499 avail_tag: u8,
500 avail_hundredths: i64,
501 font_tenths: i64,
502}
503
504impl TextMeasureKey {
505 fn from_inputs(
506 text: &str,
507 font_size: f32,
508 known_dimensions: Size<Option<f32>>,
509 available_space: Size<AvailableSpace>,
510 ) -> Self {
511 let (avail_tag, avail_hundredths) = match available_space.width {
512 AvailableSpace::Definite(w) => (0, (w * 100.0).round() as i64),
513 AvailableSpace::MinContent => (1, 0),
514 AvailableSpace::MaxContent => (2, 0),
515 };
516 Self {
517 text: text.to_owned(),
518 known_hundredths: known_dimensions.width.map(|w| (w * 100.0).round() as i64),
519 avail_tag,
520 avail_hundredths,
521 font_tenths: (font_size * 10.0).round() as i64,
522 }
523 }
524}
525
526#[derive(Debug, Clone, Default)]
528pub struct TextMeasurementCache {
529 measure_calls: usize,
530 cache_hits: usize,
531 cache: HashMap<TextMeasureKey, Size<f32>>,
532}
533
534impl TextMeasurementCache {
535 pub fn new() -> Self {
537 Self::default()
538 }
539
540 pub fn call_count(&self) -> usize {
542 self.measure_calls
543 }
544
545 pub fn cache_hits(&self) -> usize {
547 self.cache_hits
548 }
549
550 pub fn reset_counts(&mut self) {
552 self.measure_calls = 0;
553 self.cache_hits = 0;
554 }
555
556 pub fn clear(&mut self) {
558 self.cache.clear();
559 self.reset_counts();
560 }
561
562 pub fn measure_text(
568 &mut self,
569 text: &str,
570 font_size: f32,
571 line_height: f32,
572 known_dimensions: Size<Option<f32>>,
573 available_space: Size<AvailableSpace>,
574 ) -> Size<f32> {
575 let key = TextMeasureKey::from_inputs(text, font_size, known_dimensions, available_space);
576
577 if let Some(&cached) = self.cache.get(&key) {
578 self.cache_hits += 1;
579 return cached;
580 }
581
582 self.measure_calls += 1;
583
584 if text.is_empty() {
585 let res = Size::new(0.0, line_height);
586 self.cache.insert(key, res);
587 return res;
588 }
589
590 let char_width = font_size * 0.6;
591 let natural_width = text.len() as f32 * char_width;
592
593 let max_w = known_dimensions
594 .width
595 .or_else(|| available_space.width.into_option());
596
597 let res = match max_w {
598 Some(w) if w < natural_width && w > 0.0 => {
599 let chars_per_line = ((w / char_width).floor() as usize).max(1);
600 let lines = text.len().div_ceil(chars_per_line);
601 Size::new(w, lines as f32 * line_height)
602 }
603 _ => Size::new(natural_width, line_height),
604 };
605
606 self.cache.insert(key, res);
607 res
608 }
609}