Skip to main content

k2f_layout/
layout_context.rs

1use crate::Theme;
2use k2f_core::Pt;
3use k2f_text::FontLibrary;
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6
7// We hold fonts and theme.
8pub struct LayoutContext<'a> {
9    pub fonts: &'a FontLibrary,
10    pub theme: &'a Theme,
11    /// Derived list marker labels keyed by semantic node id (used during arrangement).
12    pub list_markers: HashMap<String, String>,
13}
14
15impl<'a> LayoutContext<'a> {
16    pub fn new(fonts: &'a FontLibrary, theme: &'a Theme) -> Self {
17        Self {
18            fonts,
19            theme,
20            list_markers: HashMap::new(),
21        }
22    }
23}
24
25/// Represents a 2D size in fixed-point units.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Size {
28    pub width: Pt,
29    pub height: Pt,
30}
31
32impl Size {
33    pub const ZERO: Size = Size {
34        width: Pt::ZERO,
35        height: Pt::ZERO,
36    };
37
38    pub fn new(width: Pt, height: Pt) -> Self {
39        Self { width, height }
40    }
41}
42
43/// Represents a 2D point in fixed-point units.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45pub struct Point {
46    pub x: Pt,
47    pub y: Pt,
48}
49
50impl Point {
51    pub const ZERO: Point = Point {
52        x: Pt::ZERO,
53        y: Pt::ZERO,
54    };
55
56    pub fn new(x: Pt, y: Pt) -> Self {
57        Self { x, y }
58    }
59}
60
61/// Constraints for layout measurement.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63pub struct SizeConstraint {
64    pub min: Size,
65    pub max: Size,
66}
67
68impl SizeConstraint {
69    pub fn new(min: Size, max: Size) -> Self {
70        Self { min, max }
71    }
72
73    /// Returns a constraint that allows anything from 0 to infinity (represented by max i128 or close to it)
74    pub fn infinite() -> Self {
75        Self {
76            min: Size::ZERO,
77            max: Size {
78                width: Pt(i128::MAX),
79                height: Pt(i128::MAX),
80            },
81        }
82    }
83
84    /// Returns the closest size to `size` that satisfies the constraints.
85    pub fn constrain(&self, size: Size) -> Size {
86        let width = size.width.0.max(self.min.width.0).min(self.max.width.0);
87        let height = size.height.0.max(self.min.height.0).min(self.max.height.0);
88        Size {
89            width: Pt(width),
90            height: Pt(height),
91        }
92    }
93}