gooey-rs 0.12.1

Tile-based UI library with audio support
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
//! Primary container and layout widget.
//!
//! A `Frame` element is a node with a `Layout` controller and a `Canvas` view.
//!
//! The screen is usually represented by a root frame node. A new screen `Frame` can be
//! created with the `screen::tile()` or `screen::pixel()` functions. This will create a
//! `Frame` element with zero `Canvas` coordinates and a free absolute `Layout`
//! component. This node can be optionally initialized with a `System` control ID for
//! handling system input events such as resizes.
//!
//! Child frames can be created with the `free::new()` and `tiled::new()` functions.

use std::convert::{TryFrom, TryInto};
use std::sync::LazyLock;

use crate::geometry;
use crate::prelude::*;

pub use self::builder::FrameBuilder as Builder;

pub mod free;
pub mod screen;
pub mod tiled;

pub type Frame <'element> = Widget <'element, Layout, model::Component, Canvas>;

//
//  controls
//

pub static CONTROLS : LazyLock <Controls> = LazyLock::new (||
  controls::Builder::new()
    .buttons (vec![
      controls::button::Builtin::ActivatePointer,
      controls::button::Builtin::FrameClose,
      controls::button::Builtin::FrameToggleOrientation
    ].into_iter().map (Into::into).collect::<Vec <_>>().into())
    .build()
);

/// Builtin button control `FrameClose`.
///
/// Closing a `Frame` with a `Tiled` `Layout` will produce actions to resize sibling
/// `Tiled` `Frames`. The last `Action` will be the `Destroy` action for the target
/// `Frame`.
pub fn close (
  _             : &controls::button::Release,
  elements      : &Tree <Element>,
  node_id       : &NodeId,
  action_buffer : &mut Vec <(NodeId, Action)>
) {
  use controller::component::layout;
  log::trace!("close...");
  let Widget (layout, _, _) = Frame::try_get (elements, node_id).unwrap();
  match layout.variant {
    layout::Variant::Tiled (_) => for (sibling_id, coordinates) in
      tiled::destroy_coordinates (elements, node_id)
    {
      set_coordinates (elements, &sibling_id, &coordinates, None, action_buffer);
    }
    layout::Variant::Free (..)  => {}
  }
  action_buffer.push ((node_id.clone(), Action::Destroy));
  log::trace!("...close");
}

/// Builtin button control `FrameRefresh`.
///
/// Sets the current `Layout` and refreshes the `Coordinates` of the target `Frame` and
/// any child `Frames` recursively.
pub fn refresh (
  _             : &controls::button::Release,
  elements      : &Tree <Element>,
  node_id       : &NodeId,
  action_buffer : &mut Vec <(NodeId, Action)>
) {
  log::trace!("refresh...");
  let Widget (layout, _, canvas) = Frame::try_get (elements, node_id).unwrap();
  let coordinate_kind = Some (canvas.coordinates.kind());
  set_layout (elements, node_id, layout.clone(), coordinate_kind, action_buffer);
  log::trace!("...refresh");
}

/// Builtin button control `FrameToggleOrientation`.
///
/// Switches the `Orientation` (arrangement of `Tiled` child elements) between
/// horizontal and vertical.
pub fn toggle_orientation (
  _             : &controls::button::Release,
  elements      : &Tree <Element>,
  node_id       : &NodeId,
  action_buffer : &mut Vec <(NodeId, Action)>
) {
  log::trace!("toggle_orientation...");
  let Widget (layout, _, canvas) = Frame::try_get (elements, node_id).unwrap();
  let (mut orientation, area) = layout.orientation.clone();
  orientation = orientation.toggle();
  let layout  = Layout {
    orientation: (orientation, area),
    .. layout.clone()
  };
  let coordinate_kind = Some (canvas.coordinates.kind());
  set_layout (elements, node_id, layout, coordinate_kind, action_buffer);
  log::trace!("...toggle_orientation");
}

/// Builtin button control `ActivatePointer`.
///
/// Given the target node, traverses subtree to find the top-most element that
/// intersects with the pointer; if the element is in state `Enabled`, then it is
/// focused. If the element is also a button, then push the button.
///
/// Note that this control does not need to be bound to a frame widget; it can be bound
/// to any arbitrary widget.
pub fn activate_pointer (
  release       : &controls::button::Release,
  elements      : &Tree <Element>,
  node_id       : &NodeId,
  action_buffer : &mut Vec <(NodeId, Action)>
) {
  log::trace!("activate pointer...");
  let pointer_position = {
    let pointer = POINTER.read().unwrap();
    [pointer.position_horizontal, pointer.position_vertical].into()
  };
  let mut last = None;
  for element_id in elements.traverse_pre_order_ids (node_id).unwrap() {
    let element = elements.get (&element_id).unwrap().data();
    if let Ok (Widget (_, _, canvas)) = Frame::try_from (element) {
      let canvas_aabb = {
        let aabb = geometry::integer::Aabb2::from (canvas.coordinates);
        let pixel_aabb =
          if canvas.coordinates.kind() == coordinates::Kind::Tile {
            coordinates::tile_to_pixel_aabb (aabb)
          } else {
            aabb
          };
        geometry::Aabb2::with_minmax (
          pixel_aabb.min().numcast().unwrap(),
          pixel_aabb.max().numcast().unwrap()
        ).unwrap()
      };
      if canvas_aabb.contains (pointer_position) {
        last = Some (element_id);
      }
    }
  }
  if let Some (element_id) = last {
    let element = elements.get (&element_id).unwrap().data();
    if element.controller.state == State::Enabled {
      action_buffer.push ((element_id.clone(), Action::Focus));
    }
    if element.controller.state != State::Disabled
      && let Some (child_id) = elements.children_ids (&element_id).unwrap().next()
    {
      let child = elements.get (child_id).unwrap().data();
      if let Ok (Widget (switch, _, _)) = Button::try_from (child) {
        if switch.toggle {
          match switch.state {
            switch::State::On  =>
              button::release (&None, elements, &element_id, action_buffer),
            switch::State::Off =>
              button::push (release, elements, &element_id, action_buffer)
          }
        } else {
          button::push (release, elements, &element_id, action_buffer)
        }
      }
    }
  }
  log::trace!("...activate pointer");
}

/// Builtin pointer control `HotPointer`.
///
/// Given the target node, traverses subtree to find the top-most element that
/// intersects with the pointer; if the element is in state `Enabled`, then it is
/// focused.
///
/// Note that this control does not need to be bound to a frame widget; it can be bound
/// to any arbitrary widget.
pub fn hot_pointer (
  pointer       : &input::Pointer,
  elements      : &Tree <Element>,
  node_id       : &NodeId,
  action_buffer : &mut Vec <(NodeId, Action)>
) {
  log::trace!("hot pointer...");
  debug_assert_eq!(&*POINTER.read().unwrap(), pointer);
  let pointer_position = [pointer.position_horizontal, pointer.position_vertical].into();
  let mut last = None;
  for element_id in elements.traverse_pre_order_ids (node_id).unwrap() {
    let element = elements.get (&element_id).unwrap().data();
    if let Ok (Widget (_, _, canvas)) = Frame::try_from (element) {
      let canvas_aabb = {
        let aabb = geometry::integer::Aabb2::from (canvas.coordinates);
        let pixel_aabb = if canvas.coordinates.kind() == coordinates::Kind::Tile {
          coordinates::tile_to_pixel_aabb (aabb)
        } else {
          aabb
        };
        geometry::Aabb2::with_minmax (
          pixel_aabb.min().numcast().unwrap(),
          pixel_aabb.max().numcast().unwrap()
        ).unwrap()
      };
      if canvas_aabb.contains (pointer_position) {
        last = Some (element_id);
      }
    }
  }
  if let Some (element_id) = last {
    let element = elements.get (&element_id).unwrap().data();
    if element.controller.state == State::Enabled {
      action_buffer.push ((element_id.clone(), Action::Focus));
    }
  }
  log::trace!("...hot pointer");
}

//
//  crate
//

/// Sets the given layout of the target frame and refreshes coordinates of the target
/// frame and any child frames recursively
pub (crate) fn set_layout (
  elements            : &Tree <Element>,
  frame_id            : &NodeId,
  layout              : Layout,
  coord_kind_override : Option <coordinates::Kind>,
  action_buffer       : &mut Vec <(NodeId, Action)>
) {
  log::trace!("set_layout...");
  { // update layout
    let new_layout    = layout.clone();
    let update_layout = Box::new (move |controller : &mut Controller|
      controller.component = new_layout.into());
    action_buffer.push ((frame_id.clone(), Action::ModifyController (update_layout)));
  }
  // update canvases
  for (frame_id, coordinates) in
    new_coordinates (elements, frame_id, &layout, coord_kind_override)
  {
    set_coordinates (elements, &frame_id, &coordinates,
      Some (layout.orientation.clone()), action_buffer);
  }
  log::trace!("...set_layout");
}

//
//  private
//

/// Compute the coordinates of the target frame with the given layout, and any effected
/// siblings (in the case of a tiled layout).
///
/// For a `Free` layout, this only depends on the parent frame coordinates.  A root
/// frame is handled specially: default "parent" coordinates (zero position and
/// dimensions equal to the new child layout size, or else '1' for relative sizes) are
/// used since there is no parent.
///
/// For a `Tiled` layout, the coordinates will depend on the parent frame coordinates
/// and orientation, and the weights of any other sibling frames with `Tiled` layout. It
/// is an error of a `Tiled` layout is used with a root frame since it has no parent.
///
/// TODO: update documentation for supplied coordinates kind that doesn't match parent
/// coordinates
fn new_coordinates (
  elements            : &Tree <Element>,
  frame_id            : &NodeId,
  layout              : &Layout,
  coord_kind_override : Option <coordinates::Kind>
) -> Vec <(NodeId, Coordinates)> {
  use controller::size;
  use controller::component::layout;
  use view::coordinates::dimensions;
  use view::component::Canvas;
  log::trace!("new_coordinates...");
  let out = match &layout.variant {
    layout::Variant::Free (free, area) => {
      let parent_canvas = if elements.root_node_id().unwrap() == frame_id {
        // root node is handled specially since it has no parent
        let Widget (_, _, canvas) = Frame::try_get (elements, frame_id).unwrap();
        let (width, height) = {
          // root node must not be Tiled layout
          let (free, _) = layout.variant.clone().try_into().unwrap();
          let width  = match free.size.width {
            size::Unsigned::Absolute (w) => w,
            size::Unsigned::Relative (_) => 1
          };
          let height = match free.size.height {
            size::Unsigned::Absolute (h) => h,
            size::Unsigned::Relative (_) => 1
          };
          (width, height)
        };
        let (mut parent, dimensions) =
          if canvas.coordinates.kind() == coordinates::Kind::Tile {
            ( Canvas::default_tile(),
              dimensions::Tile::new_rc (height, width).into()
            )
          } else {
            debug_assert!(canvas.coordinates.kind() == coordinates::Kind::Pixel);
            ( Canvas::default_pixel(),
              dimensions::Pixel::new_wh (width, height).into()
            )
          };
        parent.coordinates.set_dimensions (dimensions);
        parent
      } else {
        let Widget (_, _, parent_canvas) =
          Frame::try_get (elements, elements.get_parent_id (frame_id)).unwrap();
        parent_canvas.clone()
      };
      vec![(
        frame_id.clone(),
        free::coordinates (&parent_canvas, free, area, coord_kind_override)
      )]
    }
    layout::Variant::Tiled (tiled) => {
      debug_assert!(elements.root_node_id().unwrap() != frame_id,
        "tiled root frame is unsupported");
      tiled::new_coordinates (elements, frame_id, tiled)
    }
  };
  log::trace!("...new_coordinates");
  out
}

/// Updates coordinates of the given frame from the given parent coordinates, and
/// recursively refreshes all descendents' coordinates
fn set_coordinates (
  elements      : &Tree <Element>,
  frame_id      : &NodeId,
  coordinates   : &Coordinates,
  orientation   : Option <(Orientation, Area)>,
  action_buffer : &mut Vec <(NodeId, Action)>
) {
  log::trace!("set_coordinates...");
  { // update canvas
    let new_coordinates = *coordinates;
    let update_canvas   = Box::new (move |view : &mut View| {
      use view::component::{Canvas, Kind};
      let canvas = Canvas::try_ref_mut (&mut view.component).unwrap();
      canvas.coordinates = new_coordinates;
    });
    action_buffer.push ((frame_id.clone(), Action::ModifyView (update_canvas)));
  }
  // update children
  for (child_id, coordinates) in update_children (
    elements, frame_id, coordinates, orientation, action_buffer
  ) {
    set_coordinates (elements, &child_id, &coordinates, None, action_buffer);
  }
  log::trace!("...set_coordinates");
}

/// Returns new coordinates for child frames and push any update actions for other child
/// nodes resulting from setting the given new coordinates to the target frame
fn update_children (
  elements      : &Tree <Element>,
  frame_id      : &NodeId,
  coordinates   : &Coordinates,
  orientation   : Option <(Orientation, Area)>,
  action_buffer : &mut Vec <(NodeId, Action)>
) -> Vec <(NodeId, Coordinates)> {
  use view::component::{Body, Canvas, Image, Kind};
  log::trace!("update_children...");
  let mut child_coordinates = vec![];
  let (mut tiled_ids, mut tiled_layouts) = (vec![], vec![]);
  let node = elements.get (frame_id).unwrap();
  let Widget (layout, _, canvas) = Frame::try_from (node.data()).unwrap();
  let new_canvas  = {
    let coordinates = *coordinates;
    Canvas { coordinates, .. canvas.clone() }
  };
  let orientation = orientation.unwrap_or (layout.orientation.clone());
  for child_id in node.children().iter() {
    if let Ok (Widget (layout, _, canvas)) = Frame::try_get (elements, child_id) {
      // frames
      use controller::component::layout;
      match &layout.variant {
        layout::Variant::Free (free, area)  => {
          let coordinate_kind = Some (canvas.coordinates.kind());
          child_coordinates.push ((
            child_id.clone(),
            free::coordinates (&new_canvas, free, area, coordinate_kind)
          ))
        }
        layout::Variant::Tiled (tiled) => {
          tiled_ids.push (child_id.clone());
          tiled_layouts.push (tiled.clone());
        }
      }
    } else if let Ok (Widget (scroll, text, _)) = Textbox::try_get (elements, child_id) {
      // TODO: enforce scroll limits
      let new_body    = textbox::body (&new_canvas, scroll, text);
      let update_body = Box::new (|view : &mut View|{
        let body = Body::try_ref_mut (&mut view.component).unwrap();
        *body = new_body;
      });
      action_buffer.push ((child_id.clone(), Action::ModifyView (update_body)));
    } else if let Ok (Widget (scroll, pixmap, _)) =
      Picture::try_get (elements, child_id)
    {
      let new_image    = picture::image (&new_canvas, scroll, pixmap);
      let update_image = Box::new (|view : &mut View|{
        let image = Image::try_ref_mut (&mut view.component).unwrap();
        *image = new_image;
      });
      action_buffer.push ((child_id.clone(), Action::ModifyView (update_image)));
    }
  }
  child_coordinates.extend (
    tiled_ids.into_iter().zip (
      tiled::child_coordinates (&orientation, &new_canvas, tiled_layouts)));
  log::trace!("...update_children");
  child_coordinates
}

//
//  builder
//

mod builder {
  use derive_builder::Builder;
  use crate::prelude::*;

  #[derive(Builder)]
  #[builder(public, pattern="owned", build_fn(private), setter(strip_option))]
  struct Frame <'a, A : Application> {
    elements    : &'a Tree <Element>,
    parent_id   : &'a NodeId,
    #[builder(default)]
    appearances : Appearances,
    #[builder(default)]
    bindings    : Option <&'a Bindings <A>>,
    #[builder(default)]
    border      : Option <Border>,
    #[builder(default)]
    clear_color : canvas::ClearColor,
    #[builder(default)]
    disabled    : bool,
    #[builder(default)]
    layout      : Layout,
    #[builder(default)]
    name        : Option <String>
  }

  impl <'a, A : Application> FrameBuilder <'a, A> {
    pub const fn new (elements : &'a Tree <Element>, parent_id : &'a NodeId) -> Self {
      FrameBuilder {
        elements:    Some (elements),
        parent_id:   Some (parent_id),
        appearances: None,
        bindings:    None,
        border:      None,
        clear_color: None,
        disabled:    None,
        layout:      None,
        name:        None
      }
    }
  }

  impl <A : Application> BuildActions for FrameBuilder <'_, A> {
    /// Returns a create action and any sibling update actions (tile layout only).
    fn build_actions (self) -> Vec<(NodeId, Action)> {
      use controller::component::layout;
      use crate::widget::{set_option, BuildElement};
      log::trace!("build actions...");
      let Frame {
        elements, parent_id, appearances, bindings, border, clear_color, disabled,
        layout, name
      } = self.build()
        .map_err(|err| log::error!("frame builder error: {err:?}")).unwrap();
      let out = match layout.variant {
        layout::Variant::Free (free, area) => {
          let frame = {
            let mut free = super::free::Builder::new (elements, parent_id)
              .appearances (appearances)
              .area (area)
              .clear_color (clear_color)
              .disabled (disabled)
              .layout (free)
              .orientation (layout.orientation);
            set_option!(free, bindings, bindings);
            set_option!(free, border, border);
            set_option!(free, name, name);
            free.build_element()
          };
          vec![(
            parent_id.clone(),
            Action::create_singleton (frame, CreateOrder::Append)
          )]
        }
        layout::Variant::Tiled (tiled) => {
          let mut tiled =
            super::tiled::Builder::new (elements, parent_id)
              .appearances (appearances)
              .clear_color (clear_color)
              .disabled (disabled)
              .layout (tiled)
              .orientation (layout.orientation);
            set_option!(tiled, bindings, bindings);
            set_option!(tiled, border, border);
            set_option!(tiled, name, name);
          tiled.build_actions()
        }
      };
      log::trace!("...build actions");
      out
    }
  }
}