ribir_core 0.0.1-alpha.4

Ribir is a framework for building modern native/wasm cross-platform user interface 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
use ribir_geom::ZERO_SIZE;

use super::{widget_id::split_arena, DirtySet, WidgetId, WidgetTree};
use crate::{
  builtin_widgets::PerformedLayoutListener,
  context::{LayoutCtx, WindowCtx},
  prelude::{Point, Rect, Size, INFINITY_SIZE},
  widget::{QueryOrder, TreeArena},
};
use std::{cmp::Reverse, collections::HashMap};

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

impl BoxClamp {
  /// clamp use to expand the width to max
  pub const EXPAND_X: BoxClamp = BoxClamp {
    min: Size::new(f32::INFINITY, 0.),
    max: Size::new(f32::INFINITY, f32::INFINITY),
  };

  /// clamp use to expand the height to max
  pub const EXPAND_Y: BoxClamp = BoxClamp {
    min: Size::new(0., f32::INFINITY),
    max: Size::new(f32::INFINITY, f32::INFINITY),
  };

  /// clamp use to expand the size to max
  pub const EXPAND_BOTH: BoxClamp = BoxClamp {
    min: Size::new(f32::INFINITY, f32::INFINITY),
    max: Size::new(f32::INFINITY, f32::INFINITY),
  };

  /// 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 = BoxClamp::EXPAND_BOTH;
    clamp.min.width = width;
    clamp
  }

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

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

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

/// 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,
  /// object's layout size, Some value after the render
  /// object has been layout, otherwise is none value.
  pub size: Option<Size>,
  /// The position render object to place, default is zero
  pub pos: Point,
}

/// 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>,
  performed: Vec<WidgetId>,
}

pub struct Layouter<'a> {
  pub(crate) wid: WidgetId,
  pub(crate) arena: &'a mut TreeArena,
  pub(crate) store: &'a mut LayoutStore,
  pub(crate) wnd_ctx: &'a mut WindowCtx,
  pub(crate) dirty_set: &'a DirtySet,
  pub(crate) is_layout_root: bool,
}

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_position(&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) }

  pub(crate) fn swap(&mut self, id1: WidgetId, id2: WidgetId) {
    let info1 = self.layout_info(id1).cloned();
    let info2 = self.layout_info(id2).cloned();

    let mut reset = |id, v| {
      if let Some(info) = v {
        self.data.insert(id, info);
      } else {
        self.data.remove(&id);
      }
    };

    reset(id1, info2);
    reset(id2, info1);
  }

  /// 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_insert_with(LayoutInfo::default)
  }

  pub(crate) fn map_to_parent(&self, id: WidgetId, pos: Point, arena: &TreeArena) -> Point {
    self.layout_box_position(id).map_or(pos, |offset| {
      let pos = id
        .assert_get(arena)
        .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, arena: &TreeArena) -> Point {
    self.layout_box_position(id).map_or(pos, |offset| {
      let pos = pos - offset.to_vector();
      id.assert_get(arena)
        .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, arena: &TreeArena) -> Point {
    widget
      .ancestors(arena)
      .fold(pos, |pos, p| self.map_to_parent(p, pos, arena))
  }

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

  pub(crate) fn take_performed(&mut self) -> Vec<WidgetId> {
    let performed = self.performed.clone();
    self.performed.clear();
    performed
  }
}

impl BoxClamp {
  #[inline]
  pub fn clamp(self, size: Size) -> Size { size.clamp(self.min, self.max) }

  #[inline]
  pub fn expand(mut self) -> Self {
    self.max = INFINITY_SIZE;
    self
  }

  #[inline]
  pub fn loose(mut self) -> Self {
    self.min = ZERO_SIZE;
    self
  }
}

impl<'a> Layouter<'a> {
  /// perform layout of the widget this `ChildLayouter` represent,
  /// reset the widget position back to (0, 0) relative to parent, return the
  /// size result after layout
  pub fn perform_widget_layout(&mut self, clamp: BoxClamp) -> Size {
    let Self {
      wid,
      arena,
      store,
      wnd_ctx,
      dirty_set,
      is_layout_root,
    } = self;

    let size = store
      .layout_info(*wid)
      .filter(|info| clamp == info.clamp)
      .and_then(|info| info.size)
      .unwrap_or_else(|| {
        // Safety: `arena1` and `arena2` access different part of `arena`;
        let (arena1, arena2) = unsafe { split_arena(arena) };

        let layout = wid.assert_get(arena1);
        let mut ctx = LayoutCtx {
          id: *wid,
          arena: arena2,
          store,
          wnd_ctx,
          dirty_set,
        };
        let size = layout.perform_layout(clamp, &mut ctx);
        let size = clamp.clamp(size);
        let info = store.layout_info_or_default(*wid);
        info.clamp = clamp;
        info.size = Some(size);

        layout.query_all_type(
          |_: &PerformedLayoutListener| {
            store.performed.push(*wid);
            false
          },
          QueryOrder::OutsideFirst,
        );
        size
      });
    if !*is_layout_root {
      store.layout_info_or_default(*wid).pos = Point::zero();
    }
    size
  }

  /// Get layouter of the next sibling of this layouter, panic if self is not
  /// performed layout.
  pub fn into_next_sibling(self) -> Option<Self> {
    assert!(
      self.layout_rect().is_some(),
      "Before try to layout next sibling, self must performed layout."
    );
    let Self {
      arena,
      store,
      wnd_ctx,
      dirty_set,
      wid,
      ..
    } = self;
    wid.next_sibling(arena).map(move |sibling| Layouter {
      wid: sibling,
      arena,
      store,
      wnd_ctx,
      dirty_set,
      is_layout_root: false,
    })
  }

  /// Return layouter of the first child of this widget.
  pub fn into_first_child_layouter(self) -> Option<Self> {
    let Self {
      arena,
      store,
      wnd_ctx,
      dirty_set,
      wid,
      ..
    } = self;
    wid.first_child(arena).map(move |wid| Layouter {
      wid,
      arena,
      store,
      wnd_ctx,
      dirty_set,
      is_layout_root: false,
    })
  }

  pub fn has_child(&self) -> bool { self.wid.first_child(self.arena).is_some() }

  /// Return the rect of this layouter if it had performed layout.
  #[inline]
  pub fn layout_rect(&self) -> Option<Rect> {
    self
      .store
      .layout_info(self.wid)
      .and_then(|info| info.size.map(|size| Rect::new(info.pos, size)))
  }

  /// Return the position of this layouter if it had performed layout.
  #[inline]
  pub fn layout_pos(&self) -> Option<Point> {
    self.store.layout_info(self.wid).map(|info| info.pos)
  }

  /// Return the size of this layouter if it had performed layout.
  #[inline]
  pub fn layout_size(&self) -> Option<Size> {
    self.store.layout_info(self.wid).and_then(|info| info.size)
  }

  /// Update the position of the child render object should place. Relative to
  /// parent.
  #[inline]
  pub fn update_position(&mut self, pos: Point) {
    self.store.layout_info_or_default(self.wid).pos = pos;
  }

  /// Update the size of layout widget. Use this method to directly change the
  /// size of a widget, in most cast you needn't call this method, use clamp to
  /// limit the child size is enough. Use this method only it you know what you
  /// are doing.
  #[inline]
  pub fn update_size(&mut self, child: WidgetId, size: Size) {
    self.store.layout_info_or_default(child).size = Some(size);
  }

  #[inline]
  pub fn query_widget_type<W: 'static>(&self, callback: impl FnOnce(&W)) {
    self
      .wid
      .assert_get(self.arena)
      .query_on_first_type(QueryOrder::OutsideFirst, callback);
  }

  /// reset the child layout position to Point::zero()
  pub fn reset_children_position(&mut self) {
    let Self { wid, arena, store, .. } = self;
    wid.children(arena).for_each(move |id| {
      store.layout_info_or_default(id).pos = Point::zero();
    });
  }
}

impl WidgetTree {
  pub(crate) fn layout_list(&mut self) -> Option<Vec<WidgetId>> {
    if self.dirty_set.borrow().is_empty() {
      return None;
    }

    let mut needs_layout = vec![];

    let dirty_widgets = {
      let mut state_changed = self.dirty_set.borrow_mut();
      let dirty_widgets = state_changed.clone();
      state_changed.clear();
      dirty_widgets
    };

    for id in dirty_widgets.iter() {
      if id.is_dropped(&self.arena) {
        continue;
      }

      let mut relayout_root = *id;
      if let Some(info) = self.store.data.get_mut(id) {
        info.size.take();
      }

      // All ancestors of this render widget should relayout until the one which only
      // sized by parent.
      for p in id.0.ancestors(&self.arena).skip(1).map(WidgetId) {
        if self.store.layout_box_size(p).is_none() {
          break;
        }

        relayout_root = p;
        if let Some(info) = self.store.data.get_mut(&p) {
          info.size.take();
        }

        let r = self.arena.get(p.0).unwrap().get();
        if r.only_sized_by_parent() {
          break;
        }
      }
      needs_layout.push(relayout_root);
    }

    (!needs_layout.is_empty()).then(|| {
      needs_layout.sort_by_cached_key(|w| Reverse(w.ancestors(&self.arena).count()));
      needs_layout
    })
  }
}

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

#[cfg(test)]
mod tests {
  use super::*;
  use crate::{impl_query_self_only, prelude::*, test_helper::*};
  use ribir_dev_helper::*;
  use std::{cell::RefCell, rc::Rc};

  #[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 mut layouter = ctx.assert_single_child_layouter();
      layouter.perform_widget_layout(clamp);
      layouter.update_position(self.offset);
      self.size
    }
    #[inline]
    fn only_sized_by_parent(&self) -> bool { true }

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

  impl Query for OffsetBox {
    impl_query_self_only!();
  }
  #[test]
  fn fix_incorrect_relayout_root() {
    // 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 root_layout_cnt = Stateful::new(0);
    let w = widget! {
      states {
        child_box: child_box.clone(),
        root_layout_cnt: root_layout_cnt.clone(),
      }
      MockMulti {
        on_performed_layout: move |_| *root_layout_cnt += 1,
        DynWidget {
          dyns: if child_box.size.is_empty() {
            MockBox { size: Size::new(1., 1.) }.into_widget()
          } else {
            child_box.clone_stateful().into_widget()
          }
        }
      }
    };

    let app_ctx = <_>::default();
    let scheduler = FuturesLocalSchedulerPool::default().spawner();
    let mut tree = WidgetTree::new(w, WindowCtx::new(app_ctx, scheduler));
    tree.layout(Size::zero());
    assert_eq!(*root_layout_cnt.state_ref(), 1);
    {
      child_box.state_ref().size = Size::new(2., 2.);
    }
    tree.layout(Size::zero());
    assert_eq!(*root_layout_cnt.state_ref(), 2);
  }

  #[test]
  fn layout_list_from_root_to_leaf() {
    let layout_order = Stateful::new(vec![]);
    let trigger = Stateful::new(Size::zero());
    let w = widget! {
      states {
        layout_order: layout_order.clone(),
        trigger: trigger.clone()
      }
      MockBox {
        size: *trigger,
        on_performed_layout: move |_| layout_order.push(1),
        MockBox {
          size: *trigger,
          on_performed_layout: move |_| layout_order.push(2),
          MockBox {
            size: *trigger,
            on_performed_layout: move |_| layout_order.push(3),
          }
        }
      }
    };

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

  #[test]
  fn relayout_size() {
    let trigger = Stateful::new(Size::zero());
    let w = widget! {
      states {trigger: trigger.clone()}
      OffsetBox {
        size: Size::new(100., 100.),
        offset: Point::new(50., 50.),
        MockBox {
          size: Size::new(50., 50.),
          MockBox {
            size: *trigger,
          }
        }
      }
    };

    let mut wnd = TestWindow::new(w);
    wnd.draw_frame();
    assert_layout_result_by_path!(
      wnd,
      { path = [0, 0], rect == ribir_geom::rect(50., 50., 50., 50.),}
    );
    assert_layout_result_by_path!(
      wnd,
      {path = [0, 0, 0], rect == ribir_geom::rect(0., 0., 0., 0.),}
    );

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

    wnd.draw_frame();
    assert_layout_result_by_path!(
      wnd,
      {path = [0, 0], rect == ribir_geom::rect(50., 50., 50., 50.),}
    );
    assert_layout_result_by_path!(
      wnd,
      {path = [0, 0, 0], rect == ribir_geom::rect(0., 0., 10., 10.),}
    );
  }

  #[test]
  fn relayout_from_parent() {
    let trigger = Stateful::new(Size::zero());
    let cnt = Rc::new(RefCell::new(0));
    let cnt2 = cnt.clone();
    let w = widget! {
      states {trigger: trigger.clone()}
      init { let cnt = cnt2; }
      MockBox {
        size: Size::new(50., 50.),
        on_performed_layout: move |_| *cnt.borrow_mut() += 1,
        MockBox {
          size: *trigger,
        }
      }
    };

    let mut wnd = TestWindow::new(w);
    wnd.draw_frame();
    assert_eq!(*cnt.borrow(), 1);

    {
      *trigger.state_ref() = Size::new(10., 10.);
    }
    wnd.draw_frame();
    assert_eq!(*cnt.borrow(), 2);
  }

  #[test]
  fn layout_visit_prev_position() {
    #[derive(Declare)]
    struct MockWidget {
      pos: RefCell<Point>,
      size: Size,
    }

    impl Render for MockWidget {
      fn perform_layout(&self, _: BoxClamp, ctx: &mut LayoutCtx) -> Size {
        *self.pos.borrow_mut() = ctx
          .layout_store()
          .layout_box_position(ctx.id)
          .unwrap_or_default();
        self.size
      }
      #[inline]
      fn only_sized_by_parent(&self) -> bool { true }

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

    impl Query for MockWidget {
      impl_query_self_only!();
    }

    let pos = Rc::new(RefCell::new(Point::zero()));
    let pos2 = pos.clone();
    let trigger = Stateful::new(Size::zero());
    let w = widget! {
      states {trigger: trigger.clone()}
      init {
        let pos = pos2.clone();
      }
      MockMulti {
        MockBox{
          size: Size::new(50., 50.),
        }
        MockWidget {
          id: w,
          size: *trigger,
          pos: RefCell::new(Point::zero()),
          on_performed_layout: move |_| {
            *pos.borrow_mut() = *w.pos.borrow();
          }
        }
      }
    };
    let mut wnd = TestWindow::new(w);
    wnd.draw_frame();

    *trigger.state_ref() = Size::new(1., 1.);
    wnd.draw_frame();
    assert_eq!(*pos.borrow(), Point::new(50., 0.));
  }
}