1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
use std::{
fmt::Debug,
hash::Hash,
sync::Arc,
};
pub use euclid::Rect;
use crate::{
geometry::Length,
measure::Phase,
scaled::Scaled,
};
pub struct SizeFnContext {
pub parent: f32,
pub available_parent: f32,
pub parent_margin: f32,
pub root: f32,
pub phase: Phase,
}
#[cfg(feature = "serde")]
pub use serde::*;
#[derive(Clone)]
pub struct SizeFn(Arc<dyn Fn(SizeFnContext) -> Option<f32> + Sync + Send>, u64);
#[cfg(feature = "serde")]
impl Serialize for SizeFn {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str("Fn")
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for SizeFn {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct FnVisitor;
use serde::de::Visitor;
impl Visitor<'_> for FnVisitor {
type Value = SizeFn;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("\"Fn\"")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
if v == "Fn" {
Ok(SizeFn(Arc::new(|_ctx| None), 0))
} else {
Err(E::custom(format!("expected \"Fn\", got {v}")))
}
}
}
deserializer.deserialize_str(FnVisitor)
}
}
impl SizeFn {
pub fn new(func: impl Fn(SizeFnContext) -> Option<f32> + 'static + Sync + Send) -> Self {
Self(Arc::new(func), 0)
}
pub fn new_data<D: Hash>(
func: impl Fn(SizeFnContext) -> Option<f32> + 'static + Sync + Send,
data: &D,
) -> Self {
use std::hash::Hasher;
let mut hasher = std::hash::DefaultHasher::default();
data.hash(&mut hasher);
Self(Arc::new(func), hasher.finish())
}
pub fn call(&self, context: SizeFnContext) -> Option<f32> {
(self.0)(context)
}
}
impl Debug for SizeFn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("SizeFn")
}
}
impl PartialEq for SizeFn {
fn eq(&self, other: &Self) -> bool {
self.1 == other.1
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Default, PartialEq, Clone, Debug)]
pub enum Size {
/// Sizes the element based on its content. This is the default.
///
/// Can also be created with [`Size::auto`].
///
/// ```
/// # use torin::prelude::*;
/// let size = Size::auto();
/// ```
#[default]
Inner,
/// Expands to fill all the available space from its parent.
///
/// Can also be created with [`Size::fill`].
///
/// ```
/// # use torin::prelude::*;
/// let size = Size::fill();
/// ```
Fill,
/// Expand to the biggest sibling when using [`Content::fit`](crate::content::Content::fit).
///
/// Can also be created with [`Size::fill_minimum`].
///
/// ```
/// # use torin::prelude::*;
/// let size = Size::fill_minimum();
/// ```
FillMinimum,
/// Sizes as a percentage relative to the parent's size.
///
/// Can also be created with [`Size::percent`].
///
/// ```
/// # use torin::prelude::*;
/// let size = Size::percent(50.0);
/// ```
Percentage(Length),
/// Fixed size in pixels.
///
/// Can also be created with [`Size::px`].
///
/// ```
/// # use torin::prelude::*;
/// let size = Size::px(200.0);
/// ```
Pixels(Length),
/// Sizes as a percentage relative to the root (window) size.
///
/// Can also be created with [`Size::window_percent`].
///
/// ```
/// # use torin::prelude::*;
/// let size = Size::window_percent(80.0);
/// ```
RootPercentage(Length),
/// Dynamic size computed by a closure at layout time.
///
/// Can also be created with [`Size::func`] or [`Size::func_data`].
Fn(Box<SizeFn>),
/// Flex grow factor, fills the available space proportionally in the final layout phase.
///
/// Can also be created with [`Size::flex`].
///
/// ```
/// # use torin::prelude::*;
/// let size = Size::flex(1.0);
/// ```
Flex(Length),
}
impl Size {
/// Use an [`Inner`](Size::Inner) size.
pub fn auto() -> Size {
Size::Inner
}
/// Use a [`Fill`](Size::Fill) size.
pub fn fill() -> Size {
Size::Fill
}
/// Use a [`FillMinimum`](Size::FillMinimum) size.
pub fn fill_minimum() -> Size {
Size::FillMinimum
}
/// Use a [`Percentage`](Size::Percentage) size.
pub fn percent(percent: impl Into<f32>) -> Size {
Size::Percentage(Length::new(percent.into()))
}
/// Use a [`Pixels`](Size::Pixels) size.
pub fn px(px: impl Into<f32>) -> Size {
Size::Pixels(Length::new(px.into()))
}
/// Use a [`RootPercentage`](Size::RootPercentage) size.
pub fn window_percent(percent: impl Into<f32>) -> Size {
Size::RootPercentage(Length::new(percent.into()))
}
/// Use a [`Flex`](Size::Flex) size.
pub fn flex(flex: impl Into<f32>) -> Size {
Size::Flex(Length::new(flex.into()))
}
/// Use a dynamic [`Fn`](Size::Fn) size computed by the given closure.
pub fn func(func: impl Fn(SizeFnContext) -> Option<f32> + 'static + Sync + Send) -> Size {
Self::Fn(Box::new(SizeFn::new(func)))
}
/// Use a dynamic [`Fn`](Size::Fn) size with hashable data for equality checks.
pub fn func_data<D: Hash>(
func: impl Fn(SizeFnContext) -> Option<f32> + 'static + Sync + Send,
data: &D,
) -> Size {
Self::Fn(Box::new(SizeFn::new_data(func, data)))
}
pub(crate) fn flex_grow(&self) -> Option<Length> {
match self {
Self::Flex(f) => Some(*f),
_ => None,
}
}
pub(crate) fn is_flex(&self) -> bool {
matches!(self, Self::Flex(_))
}
pub(crate) fn inner_sized(&self) -> bool {
matches!(self, Self::Inner | Self::FillMinimum)
}
pub fn pretty(&self) -> String {
match self {
Self::Inner => "auto".to_string(),
Self::Pixels(s) => format!("{}", s.get()),
Self::Fn(_) => "Fn".to_string(),
Self::Percentage(p) => format!("{}%", p.get()),
Self::Fill => "fill".to_string(),
Self::FillMinimum => "fill-min".to_string(),
Self::RootPercentage(p) => format!("{}% of root", p.get()),
Self::Flex(f) => format!("flex({})", f.get()),
}
}
pub(crate) fn eval(
&self,
parent: f32,
available_parent: f32,
parent_margin: f32,
root: f32,
phase: Phase,
) -> Option<f32> {
match self {
Self::Pixels(px) => Some(px.get() + parent_margin),
Self::Percentage(per) => Some(parent / 100.0 * per.get()),
Self::Fill => Some(available_parent),
Self::RootPercentage(per) => Some(root / 100.0 * per.get()),
Self::Flex(_) | Self::FillMinimum if phase == Phase::Final => Some(available_parent),
Self::Fn(f) => f.call(SizeFnContext {
parent,
available_parent,
parent_margin,
root,
phase,
}),
_ => None,
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn min_max(
&self,
value: f32,
parent_value: f32,
available_parent_value: f32,
single_margin: f32,
margin: f32,
minimum: &Self,
maximum: &Self,
root_value: f32,
phase: Phase,
) -> f32 {
let value = self
.eval(
parent_value,
available_parent_value,
margin,
root_value,
phase,
)
.unwrap_or(value + margin);
let minimum_value = minimum
.eval(
parent_value,
available_parent_value,
margin,
root_value,
phase,
)
.map(|v| v + single_margin);
let maximum_value = maximum.eval(
parent_value,
available_parent_value,
margin,
root_value,
phase,
);
let mut final_value = value;
if let Some(minimum_value) = minimum_value
&& minimum_value > final_value
{
final_value = minimum_value;
}
if let Some(maximum_value) = maximum_value
&& final_value > maximum_value
{
final_value = maximum_value;
}
final_value
}
pub(crate) fn most_fitting_size<'a>(&self, size: &'a f32, available_size: &'a f32) -> &'a f32 {
match self {
Self::Inner => available_size,
_ => size,
}
}
}
impl Scaled for Size {
fn scale(&mut self, scale_factor: f32) {
if let Self::Pixels(s) = self {
*s *= scale_factor;
}
}
}