Skip to main content

egui_pop_fit/
element.rs

1//! What the caller declares: elements, their forms and size policies.
2
3use crate::size::Size;
4use core::fmt;
5
6/// An orientation an element can be laid out in.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9pub enum Orientation {
10    /// As declared: the policy's width is horizontal.
11    Horizontal,
12    /// Turned: the policy's width runs down, its height across.
13    Vertical,
14}
15
16impl fmt::Display for Orientation {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        f.write_str(match self {
19            Orientation::Horizontal => "horizontal",
20            Orientation::Vertical => "vertical",
21        })
22    }
23}
24
25/// An axis of a size policy, in the policy's own (horizontal) terms.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
28pub enum Axis {
29    /// Along the width.
30    Width,
31    /// Along the height.
32    Height,
33}
34
35impl Axis {
36    fn other(self) -> Axis {
37        match self {
38            Axis::Width => Axis::Height,
39            Axis::Height => Axis::Width,
40        }
41    }
42}
43
44/// Whether an element keeps its size or takes leftover room.
45#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
46#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
47pub enum Grow {
48    /// The element keeps its preferred size.
49    #[default]
50    Fixed,
51    /// The element grows along this axis, one slot step at a time, up to its
52    /// maximum.
53    Along(Axis),
54}
55
56/// A width-to-height ratio. A ratio with a zero term is ignored.
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
58#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
59pub struct AspectRatio {
60    /// The width term.
61    pub width: u32,
62    /// The height term.
63    pub height: u32,
64}
65
66/// A size on both axes.
67#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
68#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
69pub struct Size2 {
70    /// Across.
71    pub width: Size,
72    /// Down.
73    pub height: Size,
74}
75
76impl Size2 {
77    /// A size from its width and height.
78    pub const fn new(width: Size, height: Size) -> Size2 {
79        Size2 { width, height }
80    }
81
82    pub(crate) fn get(self, axis: Axis) -> Size {
83        match axis {
84            Axis::Width => self.width,
85            Axis::Height => self.height,
86        }
87    }
88
89    fn transposed(self) -> Size2 {
90        Size2::new(self.height, self.width)
91    }
92}
93
94/// How an element is sized, written for its horizontal orientation (the
95/// vertical orientation swaps the axes).
96#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
97#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
98pub struct SizePolicy {
99    /// The smallest size the element accepts. Below it, the element steps
100    /// down to its next form.
101    pub min_size: Size2,
102    /// The preferred size, the one the element is placed at.
103    pub size: Size2,
104    /// The largest size growth may reach.
105    pub max_size: Size2,
106    /// A width-to-height ratio the element keeps, if any.
107    pub aspect_ratio: Option<AspectRatio>,
108    /// Whether, and along which axis, the element grows.
109    pub grow: Grow,
110}
111
112impl SizePolicy {
113    /// A fixed element of one size.
114    pub const fn fixed(size: Size2) -> SizePolicy {
115        SizePolicy {
116            min_size: size,
117            size,
118            max_size: size,
119            aspect_ratio: None,
120            grow: Grow::Fixed,
121        }
122    }
123
124    /// A growable element: placed at `size`, accepting down to `min_size`,
125    /// growing along `axis` up to `max_size`.
126    pub const fn growable(min_size: Size2, size: Size2, max_size: Size2, axis: Axis) -> SizePolicy {
127        SizePolicy {
128            min_size,
129            size,
130            max_size,
131            aspect_ratio: None,
132            grow: Grow::Along(axis),
133        }
134    }
135
136    /// The same policy keeping an aspect ratio.
137    pub const fn with_aspect_ratio(mut self, width: u32, height: u32) -> SizePolicy {
138        self.aspect_ratio = Some(AspectRatio { width, height });
139        self
140    }
141
142    /// The policy made consistent (min ≤ size ≤ max on each axis, no zero
143    /// ratio), then turned to `orientation`.
144    pub(crate) fn resolved(&self, orientation: Orientation) -> SizePolicy {
145        let mut p = *self;
146        for axis in [Axis::Width, Axis::Height] {
147            let min = p.min_size.get(axis);
148            let max = p.max_size.get(axis).max(min);
149            let size = p.size.get(axis).clamp(min, max);
150            set(&mut p.max_size, axis, max);
151            set(&mut p.size, axis, size);
152        }
153        if matches!(p.aspect_ratio, Some(r) if r.width == 0 || r.height == 0) {
154            p.aspect_ratio = None;
155        }
156        if orientation == Orientation::Vertical {
157            p.min_size = p.min_size.transposed();
158            p.size = p.size.transposed();
159            p.max_size = p.max_size.transposed();
160            p.aspect_ratio = p.aspect_ratio.map(|r| AspectRatio {
161                width: r.height,
162                height: r.width,
163            });
164            if let Grow::Along(axis) = p.grow {
165                p.grow = Grow::Along(axis.other());
166            }
167        }
168        p
169    }
170}
171
172fn set(s: &mut Size2, axis: Axis, value: Size) {
173    match axis {
174        Axis::Width => s.width = value,
175        Axis::Height => s.height = value,
176    }
177}
178
179/// A grid position, in twelfths of the unit from the container's top left.
180#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
181#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
182pub struct Cell {
183    /// Twelfths from the left edge.
184    pub col: u32,
185    /// Twelfths from the top edge.
186    pub row: u32,
187}
188
189/// One element of a container, in its logical order.
190#[derive(Clone, Debug, PartialEq, Eq, Hash)]
191#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
192pub struct Element {
193    /// The caller's stable key. Hysteresis finds an element's previous
194    /// choices by it, so keep it across layouts; keys should be unique.
195    pub key: u64,
196    /// The forms, largest first. Form 0 is the full form; the others are
197    /// smaller forms, known to the engine only by index.
198    pub forms: Vec<SizePolicy>,
199    /// The supported orientations, preferred first. Empty means horizontal.
200    pub orientations: Vec<Orientation>,
201    /// An orientation chosen by the person, used instead of the preference
202    /// when it is supported.
203    pub pinned_orientation: Option<Orientation>,
204    /// A position stored from the person's layout, placed before the flow.
205    pub pin: Option<Cell>,
206}
207
208impl Element {
209    /// A horizontal element with one form.
210    pub fn new(key: u64, full: SizePolicy) -> Element {
211        Element {
212            key,
213            forms: vec![full],
214            orientations: vec![Orientation::Horizontal],
215            pinned_orientation: None,
216            pin: None,
217        }
218    }
219
220    /// Adds a smaller form, after the existing ones.
221    pub fn with_form(mut self, form: SizePolicy) -> Element {
222        self.forms.push(form);
223        self
224    }
225
226    /// Sets the supported orientations, preferred first.
227    pub fn with_orientations(mut self, orientations: &[Orientation]) -> Element {
228        self.orientations = orientations.to_vec();
229        self
230    }
231
232    /// Pins the orientation.
233    pub fn with_pinned_orientation(mut self, orientation: Orientation) -> Element {
234        self.pinned_orientation = Some(orientation);
235        self
236    }
237
238    /// Pins the position, in twelfths.
239    pub fn with_pin(mut self, col: u32, row: u32) -> Element {
240        self.pin = Some(Cell { col, row });
241        self
242    }
243
244    /// The orientations to try, in order.
245    pub(crate) fn orientation_order(&self) -> Vec<Orientation> {
246        let supported: &[Orientation] = if self.orientations.is_empty() {
247            &[Orientation::Horizontal]
248        } else {
249            &self.orientations
250        };
251        match self.pinned_orientation {
252            Some(o) if supported.contains(&o) => vec![o],
253            _ => {
254                let mut order = Vec::with_capacity(2);
255                for &o in supported {
256                    if !order.contains(&o) {
257                        order.push(o);
258                    }
259                }
260                order
261            }
262        }
263    }
264}