rcus-core 0.2.0

Core types for rcus: retained view tree, style, input, and the host bridge protocol
Documentation
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use serde::{Deserialize, Serialize};

use crate::boxstyle::{Radius, Shadow};

#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Size {
    pub width: f32,
    pub height: f32,
}

impl Size {
    /// Builds a size. A zero component means "not set on this axis", which is
    /// what makes a partial size work from JSON: `{"height": 32}` keeps the
    /// width flexible.
    pub const fn new(width: f32, height: f32) -> Self {
        Self { width, height }
    }

    pub fn width(self, value: f32) -> Self {
        Self {
            width: value,
            ..self
        }
    }

    pub fn height(self, value: f32) -> Self {
        Self {
            width: self.width,
            height: value,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Rect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

impl Rect {
    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    pub fn right(self) -> f32 {
        self.x + self.width
    }

    pub fn bottom(self) -> f32 {
        self.y + self.height
    }

    pub fn contains(self, x: f32, y: f32) -> bool {
        x >= self.x && x < self.right() && y >= self.y && y < self.bottom()
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Insets {
    pub left: f32,
    pub top: f32,
    pub right: f32,
    pub bottom: f32,
}

impl Insets {
    pub const fn all(value: f32) -> Self {
        Self {
            left: value,
            top: value,
            right: value,
            bottom: value,
        }
    }

    pub const fn symmetric(horizontal: f32, vertical: f32) -> Self {
        Self {
            left: horizontal,
            top: vertical,
            right: horizontal,
            bottom: vertical,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Color {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

impl Color {
    pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
        Self { r, g, b, a }
    }

    pub fn hex(value: u32) -> Self {
        Self::rgba(
            ((value >> 16) & 0xff) as f32 / 255.0,
            ((value >> 8) & 0xff) as f32 / 255.0,
            (value & 0xff) as f32 / 255.0,
            1.0,
        )
    }

    pub const TRANSPARENT: Self = Self {
        r: 0.0,
        g: 0.0,
        b: 0.0,
        a: 0.0,
    };
}

/// Opaque black, the default text color for a style that names none.
impl Default for Color {
    fn default() -> Self {
        Self::rgba(0.0, 0.0, 0.0, 1.0)
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Axis {
    #[default]
    Column,
    Row,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Align {
    #[default]
    Stretch,
    Start,
    Center,
    End,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Justify {
    #[default]
    Start,
    Center,
    End,
    SpaceBetween,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Style {
    pub size: Option<Size>,
    pub min_size: Option<Size>,
    pub max_size: Option<Size>,
    pub padding: Insets,
    pub gap: f32,
    pub flex_grow: f32,
    pub flex_shrink: f32,
    pub align: Align,
    pub justify: Justify,
    pub background: Option<Color>,
    pub clip: bool,
    /// Takes the whole content box on the parent's main axis, which is what a
    /// scrollback panel or a virtual list wants.
    pub fill: bool,
    pub row_height: f32,
    /// Overrides the line box height. `None` derives it from `font_size` and
    /// the real font metrics, which is what a view spec wants.
    pub line_height: Option<f32>,
    /// Font size in pixels, used by text renderers for shaping and metrics.
    pub font_size: f32,
    pub color: Option<Color>,
    pub weight: f32,
    /// How round this box's corners are. Zero everywhere means a hard rectangle,
    /// which is what every view that never mentions radius gets.
    pub radius: Radius,
    /// Border thickness in pixels, drawn inside the box so it cannot grow it.
    pub border_width: f32,
    pub border_color: Option<Color>,
    /// Drawn behind the box, outside its edges.
    pub shadow: Option<Shadow>,
}

impl Default for Style {
    fn default() -> Self {
        Self {
            size: None,
            min_size: None,
            max_size: None,
            padding: Insets::default(),
            gap: 0.0,
            flex_grow: 0.0,
            flex_shrink: 1.0,
            align: Align::Stretch,
            justify: Justify::Start,
            background: None,
            clip: false,
            fill: false,
            row_height: 24.0,
            line_height: None,
            font_size: 14.0,
            color: None,
            weight: 400.0,
            radius: Radius::default(),
            border_width: 0.0,
            border_color: None,
            shadow: None,
        }
    }
}

impl Style {
    pub fn size(mut self, size: Size) -> Self {
        self.size = Some(size);
        self
    }

    pub fn width(mut self, value: f32) -> Self {
        let size = self.size.unwrap_or_default();
        self.size = Some(size.width(value));
        self
    }

    pub fn height(mut self, value: f32) -> Self {
        let size = self.size.unwrap_or_default();
        self.size = Some(size.height(value));
        self
    }

    pub fn min_size(mut self, size: Size) -> Self {
        self.min_size = Some(size);
        self
    }

    pub fn max_size(mut self, size: Size) -> Self {
        self.max_size = Some(size);
        self
    }

    pub fn padding(mut self, value: Insets) -> Self {
        self.padding = value;
        self
    }

    pub fn gap(mut self, value: f32) -> Self {
        self.gap = value;
        self
    }

    pub fn flex_grow(mut self, value: f32) -> Self {
        self.flex_grow = value.max(0.0);
        self
    }

    pub fn align(mut self, value: Align) -> Self {
        self.align = value;
        self
    }

    pub fn justify(mut self, value: Justify) -> Self {
        self.justify = value;
        self
    }

    pub fn background(mut self, value: Color) -> Self {
        self.background = Some(value);
        self
    }

    pub fn clip(mut self, value: bool) -> Self {
        self.clip = value;
        self
    }

    pub fn fill(mut self, value: bool) -> Self {
        self.fill = value;
        self
    }

    pub fn row_height(mut self, value: f32) -> Self {
        self.row_height = value.max(1.0);
        self
    }

    /// Pins the line box height instead of deriving it from the font.
    pub fn line_height(mut self, value: f32) -> Self {
        self.line_height = Some(value.max(1.0));
        self
    }

    pub fn font_size(mut self, value: f32) -> Self {
        self.font_size = value.max(1.0);
        self
    }

    /// Resolved line box height for a style, given the font's own line height.
    pub fn resolved_line_height(&self, font_line_height: f32) -> f32 {
        self.line_height
            .unwrap_or_else(|| font_line_height.max(1.0))
    }

    pub fn color(mut self, value: Color) -> Self {
        self.color = Some(value);
        self
    }

    pub fn weight(mut self, value: f32) -> Self {
        self.weight = value;
        self
    }

    /// Rounds the corners by the same amount on every corner, which is what a
    /// card, a button or an input wants.
    pub fn radius(mut self, value: f32) -> Self {
        self.radius = Radius {
            sm: value,
            md: value,
            lg: value,
        };
        self
    }

    /// Rounds each corner size separately, for a panel that is subtly rounded and
    /// a popover that is not.
    pub fn radius_sized(mut self, radius: Radius) -> Self {
        self.radius = radius;
        self
    }

    /// Sets the border width and colour together, because a border with no
    /// colour is not a border.
    pub fn border(mut self, width: f32, color: Color) -> Self {
        self.border_width = width.max(0.0);
        self.border_color = Some(color);
        self
    }

    pub fn shadow(mut self, shadow: Shadow) -> Self {
        self.shadow = Some(shadow);
        self
    }

    /// The radius this box actually draws with, never more than half its shorter
    /// side: a radius wider than the box turns the corners inside out.
    pub fn corner_radius(&self, width: f32, height: f32) -> f32 {
        self.radius
            .standard()
            .max(0.0)
            .min((width.min(height)) / 2.0)
    }

    /// The border width this box actually draws with.
    pub fn border_px(&self) -> f32 {
        self.border_width.max(0.0)
    }

    /// How far this box's shadow reaches past its edges, so a draw that wants to
    /// contain the shadow knows how much room to ask for.
    pub fn shadow_reach(&self) -> f32 {
        self.shadow.map(|shadow| shadow.reach()).unwrap_or(0.0)
    }

    /// Resolved size along the given axis, if the style pins a non-zero one.
    pub fn main_size(&self, axis: Axis) -> Option<f32> {
        self.size.and_then(|size| {
            let value = match axis {
                Axis::Column => size.height,
                Axis::Row => size.width,
            };
            (value > 0.0).then_some(value)
        })
    }

    /// Resolved size across the given axis, if the style pins a non-zero one.
    pub fn cross_size(&self, axis: Axis) -> Option<f32> {
        self.size.and_then(|size| {
            let value = match axis {
                Axis::Column => size.width,
                Axis::Row => size.height,
            };
            (value > 0.0).then_some(value)
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_box_defaults_to_a_flat_rectangle() {
        let style = Style::default();
        assert_eq!(style.radius, Radius::default());
        assert_eq!(style.border_width, 0.0);
        assert!(style.border_color.is_none());
        assert!(style.shadow.is_none());
        assert_eq!(style.corner_radius(100.0, 40.0), 0.0);
        assert_eq!(style.border_px(), 0.0);
        assert_eq!(style.shadow_reach(), 0.0);
    }

    #[test]
    fn a_border_sets_its_width_and_colour_together() {
        let style = Style::default().border(1.0, Color::rgba(0.2, 0.2, 0.2, 1.0));
        assert_eq!(style.border_px(), 1.0);
        assert_eq!(style.border_color, Some(Color::rgba(0.2, 0.2, 0.2, 1.0)));
    }

    #[test]
    fn a_negative_border_is_clamped_to_nothing() {
        let style = Style::default().border(-3.0, Color::rgba(1.0, 1.0, 1.0, 1.0));
        assert_eq!(style.border_px(), 0.0);
    }

    #[test]
    fn a_radius_rounds_every_corner_the_same_way() {
        let style = Style::default().radius(6.0);
        assert_eq!(style.corner_radius(100.0, 40.0), 6.0);
    }

    #[test]
    fn a_radius_wider_than_the_box_is_halved_rather_than_inverted() {
        // A radius larger than half the short side would fold the corners
        // through each other, so the box clamps to a circle's worth.
        let style = Style::default().radius(40.0);
        assert_eq!(style.corner_radius(20.0, 20.0), 10.0);
    }

    #[test]
    fn separate_radius_sizes_are_kept() {
        let style = Style::default().radius_sized(Radius {
            sm: 2.0,
            md: 6.0,
            lg: 10.0,
        });
        assert_eq!(
            style.corner_radius(100.0, 40.0),
            6.0,
            "a box uses md by default"
        );
        assert_eq!(style.radius.lg, 10.0);
    }

    #[test]
    fn a_shadow_reports_how_much_room_it_needs() {
        let style = Style::default().shadow(Shadow {
            offset_y: 2.0,
            blur: 8.0,
            color: Color::rgba(0.0, 0.0, 0.0, 0.4),
            ..Shadow::default()
        });
        assert_eq!(style.shadow_reach(), 10.0);
    }

    #[test]
    fn a_box_decodes_a_border_and_a_radius_from_json() {
        let style: Style = serde_json::from_str(
            r#"{"radius":6,"borderWidth":1,"borderColor":{"r":1,"g":0,"b":0,"a":1}}"#,
        )
        .expect("decodes");
        assert_eq!(style.corner_radius(100.0, 40.0), 6.0);
        assert_eq!(style.border_px(), 1.0);
        assert_eq!(style.border_color.map(|c| c.r), Some(1.0));
    }

    #[test]
    fn a_box_omitting_the_new_keys_still_decodes() {
        let style: Style = serde_json::from_str(r#"{"fontSize":13}"#).expect("decodes");
        assert_eq!(style.font_size, 13.0);
        assert_eq!(style.radius, Radius::default());
    }
}