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
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! Interaction components

use std::cell::RefCell;
use std::convert::TryFrom;
use std::iter::FromIterator;
use log;
use bitflags::bitflags;
use key_vec::KeyVec;
use smallvec::SmallVec;
use strum::EnumCount;

use crate::prelude::*;

// control trait and types
pub mod controls;
pub use self::controls::Controls;
// serializable bindings and builder
pub mod bindings;
pub use self::bindings::Bindings;
// controller components
pub mod component;
pub use self::component::Component;
// data types
pub mod alignment;
pub mod offset;
pub mod size;
pub use self::alignment::Alignment;
pub use self::offset::Offset;
pub use self::size::Size;

/// A component that holds control bindings and interaction state.
///
/// Controllers handle the translation of `view::Input` events to interface
/// `Action`s via `Control` bindings.
// TODO: builder pattern? because input_map is private, we can't use .. syntax
#[derive(Clone, Debug, Default)]
pub struct Controller {
  pub component   : Component,
  /// Defines behavior and appearance
  pub state       : State,
  /// View appearance selection for each state
  pub appearances : Appearances,
  /// Controls whether the node will be moved to the last sibling position
  /// ("top") when processed by a `Focus` action (either as the target node or
  /// an ancestor of the target node).
  ///
  /// Defaults to `false`. Note that some widget builders may set this to true
  /// unless overridden (e.g. free frame widgets).
  pub focus_top   : bool,
  /// Controls whether unhandled input is bubbled up to parent: when true
  /// unhandled input will be trapped (not bubbled), when false unhandled input
  /// will be passed to the parent node.
  ///
  /// Defaults to `InputMask::empty()`
  pub bubble_trap : InputMask,
  /// Defines mappings from inputs to controls
  pub(crate) input_map : InputMap
}

/// Determines appearance and behavior
#[derive(Clone, Debug, Default, Eq, PartialEq, EnumCount)]
pub enum State {
  #[default]
  Enabled,
  Focused,
  Disabled
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum Area {
  /// Specifies the area inside any border (default)
  #[default]
  Interior,
  /// Specifies the total area including any border
  Exterior
}

/// Flow of child content
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Orientation {
  #[default]
  Horizontal,
  Vertical
}

/// Selection of an appearance for each state
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Appearances (pub [Appearance; State::COUNT]);
#[derive(Default)]
pub struct AppearancesBuilder ([Appearance; State::COUNT]);

bitflags! {
  #[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
  pub struct InputMask : u8 {
    const AXIS    = 0b0000_0001;
    const BUTTON  = 0b0000_0010;
    const MOTION  = 0b0000_0100;
    const POINTER = 0b0000_1000;
    const SYSTEM  = 0b0001_0000;
    const TEXT    = 0b0010_0000;
    const WHEEL   = 0b0100_0000;
  }
}

/// Concrete control bindings for all input types.
///
/// Given an input event, if a corresponding control is not contained in this
/// struct, the input will either be trapped (discarded) or else passed up to
/// the parent node (depending on the state of the Controller `bubble_trap`
/// flag).
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct InputMap {
  pub button_any      : Option <controls::Button>,
  pub buttons         : KeyVec <input::Button, controls::Button>,
  pub release_buttons : KeyVec <input::Button, controls::Button>,
  pub axes            : KeyVec <u32, controls::Axis>,
  pub motion          : Option <controls::Motion>,
  pub pointer         : Option <controls::Pointer>,
  pub system          : Option <controls::System>,
  pub text            : Option <controls::Text>,
  pub wheel           : Option <controls::Wheel>
}

/// An input result for registering or removing button release controls.
///
/// This is optionally returned by `controller.handle_input()` when a button release
/// control needs to be registered or removed from the focused node.
#[derive(Debug)]
pub (crate) enum ButtonRelease {
  Insert (input::Button, SmallVec <[(controls::Button, NodeId); 1]>),
  Remove (input::Button, NodeId)
}

/// Allows focus directed to a parent frame to be redirected to a different node:
///
/// - Fields
/// - Menus: if the first child of the focused Frame is a Menu (Selection) node, focus
///   will be redirected to the appropriate item node
pub (crate) fn refocus (node_id : &NodeId, elements : &Tree <Element>)
  -> Option <NodeId>
{
  let node    = elements.get (node_id).unwrap();
  let element = node.data();
  if element.controller.state != State::Focused {
    log::warn!("refocus state not focused: {:?}", element.controller.state);
    debug_assert!(false);
  }
  let mut refocus_id = None;
  // frame
  if Frame::try_from (element).is_ok() {
    let mut children_ids = node.children().iter();
    // first child
    if let Some (child_id) = children_ids.next() {
      let child = elements.get_element (child_id);
      if Field::try_from (child).is_ok() || Numbox::try_from (child).is_ok() {
        refocus_id = Some (child_id.clone());
      } else if let Ok (Widget (selection, _, _)) = Menu::try_from (child) {
        // refocus menu selection
        refocus_id = selection.current.clone()
          .or_else (|| menu::find_first_item (elements, children_ids));
      }
    }
  }
  refocus_id
}

impl Controller {
  #[inline]
  pub fn with_bindings <A : Application> (bindings : &Bindings <A>) -> Self {
    Controller { input_map: bindings.into(), .. Controller::default() }
  }

  #[inline]
  pub fn get_appearance (&self) -> &Appearance {
    self.appearances.get (self.state.clone())
  }

  #[inline]
  pub fn get_bindings <A : Application> (&self) -> Bindings <A> {
    self.input_map.to_bindings()
  }

  /// Replaces all existing bindings
  #[inline]
  pub fn set_bindings <A : Application> (&mut self, bindings : &Bindings <A>) {
    self.clear_bindings();
    self.add_bindings (bindings);
  }

  /// Must be new bindings or else panics
  #[inline]
  pub fn add_bindings <A : Application> (&mut self, bindings : &Bindings <A>) {
    self.input_map.add_bindings (bindings)
  }

  /// Replaces existing bindings; should not fail
  #[inline]
  pub fn insert_bindings <A : Application> (&mut self, bindings : &Bindings <A>) {
    self.input_map.insert_bindings (bindings)
  }

  /// Remove matching controls
  #[inline]
  pub fn remove_bindings (&mut self, controls : &Controls) {
    self.input_map.remove_bindings (controls)
  }

  #[inline]
  pub fn clear_buttons (&mut self) {
    self.input_map.buttons.clear()
  }

  #[inline]
  pub const fn remove_any_button (&mut self) {
    self.input_map.button_any = None
  }

  #[inline]
  pub const fn remove_system (&mut self) {
    self.input_map.system = None
  }

  #[inline]
  pub const fn remove_text (&mut self) {
    self.input_map.text = None
  }

  #[inline]
  pub const fn remove_motion (&mut self) {
    self.input_map.motion = None
  }

  #[inline]
  pub const fn remove_pointer (&mut self) {
    self.input_map.pointer = None
  }

  #[inline]
  pub fn clear_bindings (&mut self) {
    self.input_map.clear()
  }

  pub (crate) fn handle_input <A : Application> (&self,
    input         : Input,
    elements      : &Tree <Element>,
    node_id       : &NodeId,
    action_buffer : &mut Vec <(NodeId, Action)>
  ) -> Result <Option <ButtonRelease>, Input> {
    use controls::Control;
    log::trace!("handle_input...");
    let mut button_release = None;
    match &input {
      Input::Button (button, state) => {
        if let Component::Cursor (cursor) = &self.component &&
          let input::button::Variant::Keycode (keycode) = button.variant &&
          !button.modifiers.intersects (
            input::Modifiers::ALT | input::Modifiers::CTRL | input::Modifiers::SUPER)
        {
          if cursor.ignore.contains (&keycode) {
            // if the cursor is configured to ignore this keycode, allow the input to
            // bubble
            return Err (input)
          } else if keycode.is_printable() {
            // if the keycode is printible, consume the input and the cursor will handle
            // the text input
            return Ok (None)
          }
        }
        match state {
          input::button::State::Pressed => {
            // if the button matched was an any key or has Modifiers::ANY set, we need
            // to set the Modifier::ANY flag if a release control is bound so that it
            // will still be matched if modifiers change
            let mut any = false;
            // in backends that don't report key repeat events (Winit), if there is a
            // release event bound to the button then assumes the press was a repeat and
            // ignore
            if self.input_map.release_buttons
              .binary_search_by_key (&button, |(b, _)| b).is_ok()
            {
              return Ok (None)
            }
            let control = if let Some (control) = self.input_map.button_any.as_ref() {
              any = true;
              Some (control)
            } else if let Ok (index) = self.input_map.buttons
              .binary_search_by_key (&button, |(b, _)| b)
            {
              // NOTE: input::Button has special PartialEq implementation where
              // Modifiers::ANY in either lhs or rhs means the buttons are considered
              // equal if their input::button::Variant are equal
              let (b, control) = &self.input_map.buttons[index];
              if b.modifiers.contains (input::Modifiers::ANY) {
                any = true;
              }
              Some (control)
            } else {
              None
            };
            #[expect(clippy::unnecessary_literal_unwrap)]
            if let Some (control) = control {
              let release = Some (RefCell::new (SmallVec::new()));
              control.fun::<A::ButtonControls>().0
                (&release, elements, node_id, action_buffer);
              let controls = release.unwrap().into_inner();
              if !controls.is_empty() {
                let mut button = *button;
                if any {
                  button.modifiers.set (input::Modifiers::ANY, true);
                }
                button_release = Some (ButtonRelease::Insert (button, controls));
              }
            }
          }
          input::button::State::Released => {
            let control = if let Ok (index) = self.input_map.release_buttons
              .binary_search_by_key (&button, |(b, _)| b)
            {
              let (_, control) = &self.input_map.release_buttons[index];
              Some (control)
            } else {
              None
            };
            if let Some (control) = control {
              control.fun::<A::ButtonControls>().0
                (&None, elements, node_id, action_buffer);
              button_release =
                Some (ButtonRelease::Remove (*button, node_id.clone()));
            }
          }
        }
      }
      Input::Axis (axis) => {
        if let Ok (index) = self.input_map.axes
          .binary_search_by_key (&axis.axis, |(a, _)| *a)
        {
          let (_, control) = &self.input_map.axes[index];
          control.fun::<A::AxisControls>().0
            (&axis.value, elements, node_id, action_buffer)
        }
      }
      Input::Motion (motion) => {
        if let Some (control) = self.input_map.motion.as_ref() {
          control.fun::<A::MotionControls>().0
            (motion, elements, node_id, action_buffer)
        }
      }
      Input::Pointer (pointer) => {
        if let Some (control) = self.input_map.pointer.as_ref() {
          control.fun::<A::PointerControls>().0
            (pointer, elements, node_id, action_buffer)
        }
      }
      Input::System (system) => {
        if let Some (control) = self.input_map.system.as_ref() {
          control.fun::<A::SystemControls>().0
            (system, elements, node_id, action_buffer)
        }
      }
      Input::Text (text) => {
        if let Some (control) = self.input_map.text.as_ref() {
          control.fun::<A::TextControls>().0
            (text, elements, node_id, action_buffer)
        }
      }
      Input::Wheel (wheel) => {
        if let Some (control) = self.input_map.wheel.as_ref() {
          control.fun::<A::WheelControls>().0
            (wheel, elements, node_id, action_buffer)
        }
      }
    }
    log::trace!("...handle_input");
    if action_buffer.is_empty() && button_release.is_none() {
      Err (input)
    } else {
      Ok (button_release)
    }
  }

  pub (crate) fn release_buttons (&mut self) -> Vec <controls::Button> {
    self.input_map.release_buttons.drain (..).map (|(_, control)| control)
      .collect()
  }

  pub (crate) fn release_button_insert (&mut self,
    input : input::Button, control : controls::Button
  ) {
    if self.input_map.release_buttons.insert (input, control).is_some() {
      log::debug!("button release control already exists: {:?}", (input, control));
    }
  }

  pub (crate) fn release_button_remove (&mut self, input : input::Button) {
    match self.input_map.release_buttons
      .binary_search_by_key (&&input, |(b, _)| b)
    {
      Ok  (index) => {
        let _ = self.input_map.release_buttons.remove_index (index);
      }
      Err (_) => {
        log::warn!("remove release button not present: {input:?}");
        debug_assert!(false);
      }
    }
  }

  pub (crate) fn update_view_focus (&self, view : &mut View) {
    view.appearance = self.get_appearance().clone();
    if let view::Component::Body (body) = &mut view.component &&
      let Component::Cursor (cursor) = &self.component
    {
      match self.state {
        State::Focused  => {
          let caret = char::try_from (cursor.caret).unwrap();
          body.0.push (caret);
        }
        State::Enabled  => {
          let _ = body.0.pop().unwrap();
        }
        State::Disabled => {}
      }
    }
  }
}

impl From <Component> for Controller {
  fn from (component : Component) -> Self {
    Controller { component, .. Controller::default() }
  }
}

impl From<&Input> for InputMask {
  fn from (input : &Input) -> Self {
    match input {
      Input::Axis   (_)    => InputMask::AXIS,
      Input::Button (_, _) => InputMask::BUTTON,
      Input::Motion (_)    => InputMask::MOTION,
      Input::Pointer(_)    => InputMask::POINTER,
      Input::System (_)    => InputMask::SYSTEM,
      Input::Text   (_)    => InputMask::TEXT,
      Input::Wheel  (_)    => InputMask::WHEEL
    }
  }
}

impl InputMap {
  pub(crate) fn to_bindings <A : Application> (&self) -> Bindings <A> {
    let buttons    = self.buttons.iter().copied()
      .map (|(button, control)| controls::button::Binding::new (control.into(), button))
      .collect();
    let any_button = self.button_any.map (Into::into);
    let system     = self.system.map (Into::into);
    let text       = self.text.map (Into::into);
    let motion     = self.motion.map (Into::into);
    let pointer    = self.pointer.map (Into::into);
    Bindings { buttons, any_button, system, text, motion, pointer }
  }

  /// Add new `Bindings` to the `InputMap`.
  ///
  /// Panics if there is a conflict with current:
  ///
  /// ```should_panic
  /// use gooey::application;
  /// use gooey::interface::controller::{bindings, controls, Controller};
  /// use gooey::interface::view::input;
  /// let bindings = bindings::Builder::<application::Default>::new()
  ///   .buttons (vec![
  ///     ( controls::button::Builtin::FormSubmitCallback.into(),
  ///       input::button::Keycode::Enter.into()
  ///     ).into()
  ///   ])
  ///   .build();
  /// let mut controller = Controller::with_bindings(&bindings);
  /// controller.add_bindings (&bindings);  // panic! duplicate bindings
  /// ```
  pub(crate) fn add_bindings <A : Application> (&mut self, bindings : &Bindings <A>) {
    let Bindings { buttons, any_button, system, text, motion, pointer } = bindings;
    // buttons
    let buttons_len  = self.buttons.len();
    let bindings_len = buttons.len();
    self.buttons.extend (buttons.iter().map (|binding| (binding.1, binding.0.0)));
    assert_eq!(self.buttons.len(), buttons_len + bindings_len);
    // any button
    any_button.clone().map (|button| {
      assert!(self.button_any.is_none());
      self.button_any = Some (button.into());
    });
    // system
    system.clone().map (|system| {
      assert!(self.system.is_none());
      self.system = Some (system.into());
    });
    // text
    text.clone().map (|text| {
      assert!(self.text.is_none());
      self.text = Some (text.into());
    });
    // motion
    motion.clone().map (|motion| {
      assert!(self.motion.is_none());
      self.motion = Some (motion.into());
    });
    // pointer
    pointer.clone().map (|pointer| {
      assert!(self.pointer.is_none());
      self.pointer = Some (pointer.into());
    });
  }

  /// Insert Bindings to the `InputMap`, replacing any existing `Bindings`
  pub(crate) fn insert_bindings <A : Application> (&mut self, bindings : &Bindings <A>) {
    let Bindings { buttons, any_button, system, text, motion, pointer } = bindings;
    // buttons
    self.buttons.extend (buttons.iter().map (|binding| (binding.1, binding.0.0)));
    // any button
    any_button.clone().map (|button| self.button_any = Some (button.into()));
    // system
    system.clone().map (|system| self.system = Some (system.into()));
    // text
    text.clone().map (|text| self.text = Some (text.into()));
    // motion
    motion.clone().map (|motion| self.motion = Some (motion.into()));
    // pointer
    pointer.clone().map (|pointer| self.pointer = Some (pointer.into()));
  }

  /// Remove matching controls
  pub(crate) fn remove_bindings (&mut self, controls : &Controls) {
    let Controls { buttons, any_button, system, text, motion, pointer } = controls;
    // buttons
    self.buttons.retain (|(_, button)| !buttons.contains (button));
    // any button
    if &self.button_any == any_button {
      self.button_any = None;
    }
    // system
    if &self.system == system {
      self.system = None;
    }
    // text
    if &self.text == text {
      self.text = None;
    }
    // motion
    if &self.motion == motion {
      self.motion = None;
    }
    // pointer
    if &self.pointer == pointer {
      self.pointer = None;
    }
  }

  #[inline]
  pub(crate) fn clear (&mut self) {
    *self = InputMap::default()
  }
}

impl <A : Application> From <&Bindings <A>> for InputMap {
  /// Constructs an `InputMap` with the given `Bindings`
  fn from (bindings : &Bindings <A>) -> Self {
    let Bindings { buttons, any_button, system, text, motion, pointer } = bindings;
    let buttons    = KeyVec::from_iter (buttons.iter()
      .map (|binding| (binding.1, binding.0.0)));
    let button_any = any_button.clone().map (Into::into);
    let system     = system.clone().map (Into::into);
    let text       = text.clone().map (Into::into);
    let motion     = motion.clone().map (Into::into);
    let pointer    = pointer.clone().map (Into::into);
    InputMap {
      buttons, button_any, system, text, motion, pointer, .. InputMap::default()
    }
  }
}

impl State {
  /// Changes state to Focused and issues a warning if state was not Enabled
  #[inline]
  pub fn focus (&mut self) {
    if self != &State::Enabled {
      log::warn!("focus state not enabled: {self:?}");
    }
    debug_assert_eq!(self, &State::Enabled);
    *self = State::Focused;
  }
  /// Changes state to Enabled and issues a warning if state was not Focused
  #[inline]
  pub fn defocus (&mut self) {
    if self != &State::Focused {
      log::warn!("defocus state not focused: {self:?}");
    }
    debug_assert_eq!(self, &State::Focused);
    *self = State::Enabled;
  }
  /// Changes state to Enabled and issues a warning if state was not Disabled
  #[inline]
  pub fn enable (&mut self) {
    if self != &State::Disabled {
      log::warn!("enable state not disabled: {self:?}");
    }
    debug_assert_eq!(self, &State::Disabled);
    *self = State::Enabled;
  }
  /// Changes state to Disabled and issues a warning if state was not Enabled
  #[inline]
  pub fn disable (&mut self) {
    if self != &State::Enabled {
      log::warn!("disable state not enabled: {self:?}");
    }
    debug_assert_eq!(self, &State::Enabled);
    *self = State::Disabled;
  }
}


impl Appearances {
  #[inline]
  pub const fn get (&self, state : State) -> &Appearance {
    &self.0[state as usize]
  }

  #[inline]
  pub const fn get_mut (&mut self, state : State) -> &mut Appearance {
    &mut self.0[state as usize]
  }
}

impl AppearancesBuilder {
  pub fn transparent() -> Self {
    AppearancesBuilder::default()
      .style_fg (State::Focused,  Color::TRANSPARENT)
      .style_bg (State::Focused,  Color::TRANSPARENT)
      .style_fg (State::Enabled,  Color::TRANSPARENT)
      .style_bg (State::Enabled,  Color::TRANSPARENT)
      .style_fg (State::Disabled, Color::TRANSPARENT)
      .style_bg (State::Disabled, Color::TRANSPARENT)
  }

  #[inline]
  pub const fn state (mut self, state : State, appearance : Appearance) -> Self {
    self.0[state as usize] = appearance;
    self
  }
  #[inline]
  pub const fn style (mut self, state : State, style : Style) -> Self {
    self.0[state as usize].style = Some (style);
    self
  }
  #[inline]
  pub fn style_default (mut self, state : State) -> Self {
    self.0[state as usize].style = Some (Style::default());
    self
  }
  #[inline]
  pub const fn sound (mut self, state : State, sound : Sound) -> Self {
    self.0[state as usize].sound = Some (sound);
    self
  }
  #[inline]
  pub const fn pointer (mut self, state : State, pointer : Pointer) -> Self {
    self.0[state as usize].pointer = Some (pointer);
    self
  }
  #[inline]
  pub fn style_fg (mut self, state : State, color : Color) -> Self {
    let state = state as usize;
    let mut style = self.0[state].style.take().unwrap_or_default();
    style.fg = color;
    self.0[state].style = Some (style);
    self
  }
  #[inline]
  pub fn style_bg (mut self, state : State, color : Color) -> Self {
    let state = state as usize;
    let mut style = self.0[state].style.take().unwrap_or_default();
    style.bg = color;
    self.0[state].style = Some (style);
    self
  }
  #[inline]
  pub fn style_lo (mut self, state : State, color : Color) -> Self {
    let state = state as usize;
    let mut style = self.0[state].style.take().unwrap_or_default();
    style.lo = color;
    self.0[state].style = Some (style);
    self
  }
  #[inline]
  pub fn style_hi (mut self, state : State, color : Color) -> Self {
    let state = state as usize;
    let mut style = self.0[state].style.take().unwrap_or_default();
    style.hi = color;
    self.0[state].style = Some (style);
    self
  }
  #[inline]
  pub const fn build (self) -> Appearances {
    Appearances (self.0)
  }
}


impl Orientation {
  pub const fn toggle (self) -> Self {
    match self {
      Orientation::Horizontal => Orientation::Vertical,
      Orientation::Vertical   => Orientation::Horizontal
    }
  }
}