ribir_core 0.4.0-alpha.55

A non-intrusive declarative GUI framework, to build modern native/wasm cross-platform applications.
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
486
487
488
489
490
491
492
493
494
use std::collections::HashMap;

use ribir_geom::{Rect, ZERO_SIZE};

use super::{Lerp, WidgetId, WidgetTree};
use crate::prelude::{INFINITY_SIZE, Point, Size};

/// boundary limit of the render object's layout
#[derive(Debug, Clone, PartialEq, Copy, Lerp)]
pub struct BoxClamp {
  pub min: Size,
  pub max: Size,
}

impl BoxClamp {
  pub const UNLIMITED: BoxClamp = BoxClamp { min: ZERO_SIZE, max: INFINITY_SIZE };

  /// clamp use fixed width and unfixed height
  pub const fn fixed_width(width: f32) -> Self {
    BoxClamp { min: Size::new(width, 0.), max: Size::new(width, f32::INFINITY) }
  }

  /// clamp use fixed height and unfixed width
  pub const fn fixed_height(height: f32) -> Self {
    BoxClamp { min: Size::new(0., height), max: Size::new(f32::INFINITY, height) }
  }

  /// clamp use fixed size
  pub const fn fixed_size(size: Size) -> Self { BoxClamp { min: size, max: size } }

  pub const fn min_width(width: f32) -> Self {
    let mut clamp = Self::UNLIMITED;
    clamp.min.width = width;
    clamp
  }

  pub const fn min_height(height: f32) -> Self {
    let mut clamp = Self::UNLIMITED;
    clamp.min.height = height;
    clamp
  }

  pub const fn min_size(min: Size) -> Self {
    Self { min, max: Size::new(f32::INFINITY, f32::INFINITY) }
  }

  pub const fn max_size(max: Size) -> Self { Self { min: ZERO_SIZE, max } }

  pub const fn max_height(height: f32) -> Self {
    Self { min: ZERO_SIZE, max: Size::new(f32::INFINITY, height) }
  }

  pub const fn max_width(width: f32) -> Self {
    Self { min: ZERO_SIZE, max: Size::new(width, f32::INFINITY) }
  }

  pub const fn with_min_size(mut self, size: Size) -> Self {
    self.min = Size::new(size.width.min(self.max.width), size.height.min(self.max.height));
    self
  }

  pub const fn with_max_size(mut self, size: Size) -> Self {
    self.max = Size::new(size.width.max(self.min.width), size.height.max(self.min.height));
    self
  }

  pub const fn with_fixed_height(mut self, height: f32) -> Self {
    self.min.height = height;
    self.max.height = height;
    self
  }

  pub const fn with_fixed_width(mut self, width: f32) -> Self {
    self.min.width = width;
    self.max.width = width;
    self
  }

  pub const fn with_max_width(mut self, width: f32) -> Self {
    self.max.width = width.max(self.min.width);
    self
  }

  pub const fn with_max_height(mut self, height: f32) -> Self {
    self.max.height = height.max(self.min.height);
    self
  }

  pub const fn with_min_width(mut self, width: f32) -> Self {
    self.min.width = width.min(self.max.width);
    self
  }

  pub const fn with_min_height(mut self, height: f32) -> Self {
    self.min.height = height.min(self.max.height);
    self
  }

  /// Calculates an estimated container width during child layout phases when
  /// parent width is unknown.
  ///
  /// Provides a deterministic strategy to determine container width based on
  /// constraints and child metrics:
  ///
  /// 1. **Constraint-based width**: Uses the maximum width constraint when
  ///    finite and bounded
  /// 2. **Content-based width**: Falls back to child width clamped by minimum
  ///    width constraint
  ///
  /// # Arguments
  ///
  /// - `child_width`: The child's intrinsic width requirement before clamping
  ///
  /// # Returns
  ///
  /// Estimated layout width that respects constraints while considering child
  /// requirements.
  ///
  /// # Implementation Notes
  ///
  /// The returned width represents a layout hypothesis rather than final parent
  /// dimensions. This intermediate value enables consistent layout calculations
  /// before parent constraints are fully resolved, but may differ from the
  /// final container width determined during parent layout phases.
  pub const fn container_width(&self, child_width: f32) -> f32 {
    let min = self.min.width;
    let max = self.max.width;

    // Prefer finite maximum constraint when available, otherwise use clamped child
    // width
    if max.is_finite() { max } else { min.max(child_width) }
  }

  /// Calculates an estimated container height during child layout phases when
  /// parent height is unknown.
  ///
  /// Provides a deterministic strategy to determine container height based on
  /// constraints and child metrics:
  ///
  /// 1. **Constraint-based height**: Uses the maximum height constraint when
  ///    finite and bounded
  /// 2. **Content-based height**: Falls back to child height clamped by minimum
  ///    height constraint
  ///
  /// # Arguments
  ///
  /// - `child_height`: The child's intrinsic height requirement before clamping
  ///
  /// # Returns
  ///
  /// Estimated layout height that respects constraints while considering child
  /// requirements.
  ///
  /// # Implementation Notes
  ///
  /// The returned height represents a layout hypothesis rather than final
  /// parent dimensions. This intermediate value enables consistent layout
  /// calculations before parent constraints are fully resolved, but may
  /// differ from the final container height determined during parent layout
  /// phases.
  pub const fn container_height(&self, child_height: f32) -> f32 {
    let min = self.min.height;
    let max = self.max.height;

    // Prefer finite maximum constraint when available, otherwise use clamped child
    // height
    if max.is_finite() { max } else { min.max(child_height) }
  }
}

#[derive(Default, Debug, Clone, PartialEq, Copy)]
pub struct VisualBox {
  /// the bounds rect of the render object
  pub rect: Option<Rect>,
  /// the bounds rect of the subtree
  pub subtree: Option<Rect>,
}

impl VisualBox {
  pub fn bounds_rect(&self) -> Option<Rect> {
    match (self.rect, self.subtree) {
      (Some(rect), Some(subtree)) => Some(rect.union(&subtree)),
      (Some(rect), None) => Some(rect),
      (None, Some(subtree)) => Some(subtree),
      (None, None) => None,
    }
  }
}

/// render object's layout box, the information about layout, including box
/// size, box position, and the clamp of render object layout.
#[derive(Debug, Default, Clone)]
pub struct LayoutInfo {
  /// Box bound is the bound of the layout can be place. it will be set after
  /// render object computing its layout. It's passed by render object's parent.
  pub clamp: BoxClamp,
  /// The size of the object's layout result, indicating that the object has
  /// been laid out; otherwise, it is `None`.
  pub size: Option<Size>,
  /// The position render object to place, default is zero
  pub pos: Point,

  /// the visual box of the render object
  pub visual_box: VisualBox,
}

/// Store the render object's place relative to parent coordinate and the
/// clamp passed from parent.
#[derive(Default)]
pub(crate) struct LayoutStore {
  data: HashMap<WidgetId, LayoutInfo, ahash::RandomState>,
}

impl LayoutStore {
  /// Remove the layout info of the `wid`
  pub(crate) fn force_layout(&mut self, id: WidgetId) -> Option<LayoutInfo> { self.remove(id) }

  pub(crate) fn remove(&mut self, id: WidgetId) -> Option<LayoutInfo> { self.data.remove(&id) }

  pub(crate) fn layout_box_size(&self, id: WidgetId) -> Option<Size> {
    self.layout_info(id).and_then(|info| info.size)
  }

  pub(crate) fn layout_box_pos(&self, id: WidgetId) -> Option<Point> {
    self.layout_info(id).map(|info| info.pos)
  }

  pub(crate) fn layout_info(&self, id: WidgetId) -> Option<&LayoutInfo> { self.data.get(&id) }

  /// return a mutable reference of the layout info  of `id`, if it's not exist
  /// insert a default value before return
  pub(crate) fn layout_info_or_default(&mut self, id: WidgetId) -> &mut LayoutInfo {
    self.data.entry(id).or_default()
  }
}

impl WidgetTree {
  pub(crate) fn map_to_parent(&self, id: WidgetId, pos: Point) -> Point {
    self
      .store
      .layout_box_pos(id)
      .map_or(pos, |offset| {
        let pos = id
          .assert_get(self)
          .get_transform()
          .map_or(pos, |t| t.transform_point(pos));
        pos + offset.to_vector()
      })
  }

  pub(crate) fn map_from_parent(&self, id: WidgetId, pos: Point) -> Point {
    self
      .store
      .layout_box_pos(id)
      .map_or(pos, |offset| {
        let pos = pos - offset.to_vector();
        id.assert_get(self)
          .get_transform()
          .map_or(pos, |t| {
            t.inverse()
              .map_or(pos, |t| t.transform_point(pos))
          })
      })
  }

  pub(crate) fn map_to_global(&self, pos: Point, widget: WidgetId) -> Point {
    widget
      .ancestors(self)
      .fold(pos, |pos, p| self.map_to_parent(p, pos))
  }

  pub(crate) fn map_from_global(&self, pos: Point, widget: WidgetId) -> Point {
    let stack = widget.ancestors(self).collect::<Vec<_>>();
    stack
      .iter()
      .rev()
      .fold(pos, |pos, p| self.map_from_parent(*p, pos))
  }
}

impl BoxClamp {
  /// Restricts a size to stay within the clamp's minimum and maximum bounds
  #[inline]
  pub fn clamp(self, size: Size) -> Size { size.clamp(self.min, self.max) }

  /// Creates a constraint that allows maximum expansion
  /// (sets maximum dimensions to infinity while preserving minimums)
  #[inline]
  pub fn expand(mut self) -> Self {
    self.max = INFINITY_SIZE;
    self
  }

  /// Creates a constraint with relaxed minimum requirements
  /// (sets minimum dimensions to zero while preserving maximums)
  #[inline]
  pub fn loose(mut self) -> Self {
    self.min = ZERO_SIZE;
    self
  }

  /// Removes horizontal constraints while preserving vertical bounds
  /// (width can be any value between 0 and infinity)
  pub fn free_width(mut self) -> Self {
    self.min.width = 0.0;
    self.max.width = f32::INFINITY;
    self
  }

  /// Removes vertical constraints while preserving horizontal bounds
  /// (height can be any value between 0 and infinity)
  pub fn free_height(mut self) -> Self {
    self.min.height = 0.0;
    self.max.height = f32::INFINITY;
    self
  }
}

impl Default for BoxClamp {
  fn default() -> Self {
    Self { min: Size::new(0., 0.), max: Size::new(f32::INFINITY, f32::INFINITY) }
  }
}

impl std::ops::Deref for LayoutStore {
  type Target = HashMap<WidgetId, LayoutInfo, ahash::RandomState>;
  fn deref(&self) -> &Self::Target { &self.data }
}

impl std::ops::DerefMut for LayoutStore {
  fn deref_mut(&mut self) -> &mut Self::Target { &mut self.data }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::{prelude::*, reset_test_env, test_helper::*};

  #[derive(Declare, Clone, SingleChild)]
  struct OffsetBox {
    pub offset: Point,
    pub size: Size,
  }

  impl Render for OffsetBox {
    fn perform_layout(&self, mut clamp: BoxClamp, ctx: &mut LayoutCtx) -> Size {
      clamp.max = clamp.max.min(self.size);
      let child = ctx.assert_single_child();
      ctx.perform_child_layout(child, clamp);
      ctx.update_position(child, self.offset);
      self.size
    }

    #[inline]
    fn paint(&self, _: &mut PaintingCtx) {}
  }

  #[test]
  fn fix_incorrect_relayout_root() {
    reset_test_env!();

    // Can't use layout info of dirty widget to detect if the ancestors path have
    // in relayout list. Because new widget insert by `DynWidget` not have layout
    // info, but its parent have.

    let child_box = Stateful::new(MockBox { size: Size::zero() });
    let c_child_box = child_box.clone_writer();
    let (layout_cnt, w_layout_cnt) = split_value(0);

    let w = fn_widget! {
      let child_box = child_box.clone_writer();
      @MockMulti {
        on_performed_layout: move |_| *$write(w_layout_cnt) += 1,
        @ {
          pipe!($read(child_box).size.is_empty())
            .map(move|b| {
              let child_box = child_box.clone_writer();
              fn_widget! {
                if b {
                  MockBox { size: Size::new(1., 1.) }.into_widget()
                } else {
                  child_box.into_widget()
                }
              }
            })
        }
      }
    };

    let wnd = TestWindow::from_widget(w);
    wnd.draw_frame();
    assert_eq!(*layout_cnt.read(), 1);
    {
      c_child_box.write().size = Size::new(2., 2.);
    }
    wnd.draw_frame();
    assert_eq!(*layout_cnt.read(), 2);
  }

  #[test]
  fn layout_list_from_root_to_leaf() {
    reset_test_env!();

    let layout_order = Stateful::new(vec![]);
    let trigger = Stateful::new(Size::zero());
    let order = layout_order.clone_writer();
    let size = trigger.clone_watcher();
    let w = fn_widget! {
      @MockBox {
        size: pipe!(*$read(size)),
        on_performed_layout: move |_| $write(order).push(1),
        @MockBox {
          size: pipe!(*$read(size)),
          on_performed_layout: move |_| $write(order).push(2),
          @MockBox {
            size: pipe!(*$read(size)),
            on_performed_layout: move |_| $write(order).push(3),
          }
        }
      }
    };

    let wnd = TestWindow::from_widget(w);
    wnd.draw_frame();
    assert_eq!([3, 2, 1], &**layout_order.read());
    {
      *trigger.write() = Size::new(1., 1.);
    }
    wnd.draw_frame();
    assert_eq!([3, 2, 1, 3, 2, 1], &**layout_order.read());
  }

  #[test]
  fn relayout_size() {
    reset_test_env!();

    let trigger = Stateful::new(Size::zero());
    let size = trigger.clone_watcher();
    let w = fn_widget! {
      @OffsetBox {
        size: Size::new(100., 100.),
        offset: Point::new(50., 50.),
        @MockBox {
          size: Size::new(50., 50.),
          @MockBox { size: pipe!(*$read(size)) }
        }
      }
    };

    #[track_caller]
    fn assert_rect_by_path(wnd: &TestWindow, path: &[usize], rect: Rect) {
      let info = wnd.layout_info_by_path(path).unwrap();
      assert_eq!(info.pos, rect.origin);
      assert_eq!(info.size.unwrap(), rect.size);
    }

    let wnd = TestWindow::from_widget(w);
    wnd.draw_frame();
    assert_rect_by_path(&wnd, &[0, 0], ribir_geom::rect(50., 50., 50., 50.));
    assert_rect_by_path(&wnd, &[0, 0, 0], ribir_geom::rect(0., 0., 0., 0.));

    {
      *trigger.write() = Size::new(10., 10.);
    }

    wnd.draw_frame();
    assert_rect_by_path(&wnd, &[0, 0], ribir_geom::rect(50., 50., 50., 50.));
    assert_rect_by_path(&wnd, &[0, 0, 0], ribir_geom::rect(0., 0., 10., 10.));
  }

  #[test]
  fn relayout_from_parent() {
    reset_test_env!();

    let (cnt, w_cnt) = split_value(0);
    let (size, w_size) = split_value(Size::zero());
    let w = fn_widget! {
      @MockBox {
        size: Size::new(50., 50.),
        on_performed_layout: move |_| *$write(w_cnt) += 1,
        @MockBox { size: pipe!(*$read(size)) }
      }
    };

    let wnd = TestWindow::from_widget(w);
    wnd.draw_frame();
    assert_eq!(*cnt.read(), 1);

    *w_size.write() = Size::new(10., 10.);

    wnd.draw_frame();
    assert_eq!(*cnt.read(), 2);
  }
}