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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
//! Curses (terminal) backend

use std;
use std::sync::{LazyLock, Mutex};
use {log, easycurses, pancurses, nsys};

use crate::{Application, Interface, Tree};
use crate::math::Vector2;
use crate::geometry::integer::Aabb2;
use crate::geometry::intersect::integer as intersect;
use crate::interface::{view, View};
use crate::widget;
use crate::tree::NodeId;
use super::{Graphics, Presentation};

pub static INIT_COLORS : LazyLock <Mutex <Option <[[u8; 3]; 8]>>> =
  LazyLock::new (|| Mutex::new (None));

/// A pancurses-based presentation implementation.
#[derive(Debug)]
pub struct Curses {
  inner           : nsys::curses::Curses,
  /// Pancuses doesn't generate release button events, so we simulate them by generating
  /// a release event on the next frame for each press. Note that this includes key
  /// repeat events.
  release_buttons : Vec <view::input::Button>
}

pub fn border_acs_lines() -> view::Border {
  #[expect(trivial_numeric_casts)]
  view::Border {
    top:              pancurses::ACS_HLINE()    as u32,
    bottom:           pancurses::ACS_HLINE()    as u32,
    left:             pancurses::ACS_VLINE()    as u32,
    right:            pancurses::ACS_VLINE()    as u32,
    top_left:         pancurses::ACS_ULCORNER() as u32,
    top_right:        pancurses::ACS_URCORNER() as u32,
    bottom_left:      pancurses::ACS_LLCORNER() as u32,
    bottom_right:     pancurses::ACS_LRCORNER() as u32,
    thickness_top:    1,
    thickness_bottom: 1,
    thickness_left:   1,
    thickness_right:  1
  }
}

impl Curses {
  #[inline]
  pub const fn inner (&self) -> &nsys::curses::Curses {
    &self.inner
  }
  #[inline]
  pub const fn inner_mut (&mut self) -> &mut nsys::curses::Curses {
    &mut self.inner
  }
  #[inline]
  pub fn dimensions (&self) -> view::dimensions::Tile {
    let (rows, columns) = self.inner.dimensions_rc();
    debug_assert!(rows > 0);
    debug_assert!(columns > 0);
    Vector2::new (rows as u32, columns as u32).into()
  }
}

impl Default for Curses {
  fn default() -> Self {
    let mut inner =  {
      let init_colors = INIT_COLORS.lock().unwrap();
      nsys::curses::Curses::new (init_colors.as_ref())
    };
    // push a resize event so the interface screen element can be initialized
    inner.un_get_input (pancurses::Input::KeyResize);
    Curses { inner, release_buttons: Vec::new() }
  }
}

impl Graphics     for Curses { }
impl Presentation for Curses {
  fn with_root (_root : View, _id : NodeId) -> Self {
    Self::default()
  }

  /// Create a new interface with a root screen frame element
  fn make_interface <A : Application> () -> Interface <A, Self> {
    use widget::BuildElement;
    // create a root screen frame and use the resize control function to update the
    // dimensions
    let screen = widget::frame::screen::TileBuilder::<A>::new().build_element();
    let mut interface = Interface::<A, Self>::with_root (screen);
    let dimensions = interface.presentation.dimensions();
    let mut actions = vec![];
    widget::frame::screen::resize (
      &view::input::System::Resized {
        width:  dimensions.columns(),
        height: dimensions.rows()
      },
      interface.elements(),
      interface.root_id(),
      &mut actions
    );
    let _ = interface.actions (actions);
    interface
  }

  fn get_input (&mut self, input_buffer : &mut Vec <view::Input>) {
    use view::{input, Input};
    log::trace!("get input...");
    input_buffer.extend (self.release_buttons.drain (..)
      .map (|button|{
        let input = Input::Button (button, input::button::State::Released);
        log::debug!("input: {input:?}");
        input
      }));
    if let Some (pancurses_input) = self.inner.getch_nowait() {
      log::trace!("pancurses input: {pancurses_input:?}");
      let input = match pancurses_input.into() {
        // pancurses::Input::KeyResize is converted to input::System::Resize{0,0}
        Input::System (input::System::Resized { width: 0, height: 0 }) => {
          // get the current dimensions
          let (width, height) = {
            let (rows, columns) = self.inner.dimensions_rc();
            debug_assert!(rows    >= 0);
            debug_assert!(columns >= 0);
            // NOTE: the curses display represents dimensions as (rows, columns) pairs,
            // but the interface represents dimensions in (width, height), so these
            // values are transposed when generating the resize event
            (columns as u32, rows as u32)
          };
          input::System::Resized { width, height }.into()
        }
        Input::Button (button, pressed) => {
          debug_assert_eq!(pressed, input::button::State::Pressed);
          // release next frame
          self.release_buttons.push (button);
          Input::Button (button, pressed)
        }
        Input::Text (input::Text::Char (ch)) => {
          // generate a button event for char input
          let button = {
            let (keycode, modifiers) = char_to_keycode (ch);
            input::Button { variant: keycode.into(), modifiers }
          };
          let input = Input::Text (input::Text::Char (ch));
          log::debug!("input: {input:?}");
          input_buffer.push (input);
          // release next frame
          self.release_buttons.push (button);
          (button, input::button::State::Pressed).into()
        }
        input => input
      };
      log::debug!("input: {input:?}");
      input_buffer.push (input);
    }
    log::trace!("...get input");
  }

  fn display_view <V : AsRef <View>> (&mut self,
    view_tree      : &Tree <V>,
    _display_values : std::vec::Drain <(NodeId, view::Display)>
  ) {
    use std::collections::VecDeque;
    use pancurses::chtype;
    use nsys::curses::{color_pair_attr, pancurses_ok, pancurses_warn_ok};
    use view::component::{canvas, Body, Canvas, Image, Kind};
    log::trace!("display view...");
    // trace info
    let (attrs, colors) = self.inner.win().attrget();
    let bkgd = self.inner.win().getbkgd();
    log::trace!("  window: attributes: {attrs:064b}");
    log::trace!("  window: color pair: {colors}");
    log::trace!("  window: background: {bkgd:064b}");
    // screen is the root canvas element
    let screen_id     = view_tree.root_node_id().unwrap();
    let screen        = view_tree.get (screen_id).unwrap().data().as_ref();
    let screen_canvas = Canvas::try_ref (&screen.component).unwrap();
    // set background and clear display if clear color is set
    // TODO: this logic may need to rethinking
    let (clear, bg_color) = {
      let color = match screen_canvas.clear_color {
        canvas::ClearColor::Appearance =>
          screen.appearance.style.as_ref().map(|style| style.bg),
        canvas::ClearColor::Fixed (clear_color) => clear_color
      };
      ( color.is_some(),
        // 0x00 == no color bits: color pair id 0 should be white/black
        color.map_or (0x00, |color| {
          let bg = convert_color (color).unwrap();
          color_pair_attr (easycurses::Color::White, bg)
        })
      )
    };
    self.inner.win().bkgdset (' ' as chtype | bg_color);
    if clear {
      pancurses_ok!(self.inner.win().erase());
    }
    // initialize style
    let style = screen.appearance.style.clone().unwrap_or_default();
    // draw screen border if present
    #[expect(trivial_numeric_casts)]
    if let Some (border) = screen_canvas.border.as_ref() {
      let rc_min = (0,0);
      let rc_max = (
        screen_canvas.coordinates.dimensions().vec().numcast().unwrap()
          - Vector2::new (1,1)
      ).into_tuple();
      let color = color_pair_attr (
        convert_color (style.fg).unwrap(),
        convert_color (style.bg).unwrap());
      pancurses_warn_ok!(self.inner.draw_border (
        border.left         as chtype | color,
        border.right        as chtype | color,
        border.top          as chtype | color,
        border.bottom       as chtype | color,
        border.top_left     as chtype | color,
        border.top_right    as chtype | color,
        border.bottom_left  as chtype | color,
        border.bottom_right as chtype | color,
        rc_min, rc_max,
        border.thickness_top    as u32,
        border.thickness_bottom as u32,
        border.thickness_left   as u32,
        border.thickness_right  as u32
      ));
    }
    // clip first-level child canvases and draw
    let screen_aabb  = screen_canvas.coordinates.into();
    let mut canvases = VecDeque::new();
    for child_id in view_tree.children_ids (screen_id).unwrap() {
      let child = view_tree.get (child_id).unwrap().data().as_ref();
      let style = child.appearance.style.as_ref().unwrap_or (&style);
      if let Some (child_canvas) = Canvas::try_ref (&child.component) &&
        let Some ((canvas, body_aabb)) =
          canvas_and_body_aabb (child_canvas, screen_aabb)
      {
        canvases.push_back ((child_id, canvas, style, body_aabb));
      }
    }
    while canvases.len() > 0 {
      let (node_id, canvas, style, body_aabb) = canvases.pop_front().unwrap();
      let node = view_tree.get (node_id).unwrap();
      let mut text  = None;
      let mut image = None;
      for child_id in node.children().iter().rev() {
        let child = view_tree.get (child_id).unwrap().data().as_ref();
        let style = child.appearance.style.as_ref().unwrap_or (style);
        if let Some (child_canvas) = Canvas::try_ref (&child.component) &&
          let Some ((canvas, body_aabb)) =
            canvas_and_body_aabb (child_canvas, screen_aabb)
        {
          canvases.push_front ((child_id, canvas, style, body_aabb));
        } else if let Some (child_text) = Body::try_ref (&child.component) {
          debug_assert!(text.is_none());
          // NOTE: this slicing is unsafe if the string contains multi-byte
          // characters
          let skip  = body_aabb.min().0.x as usize;
          let take  = body_aabb.max().0.x as usize - skip;
          let start = body_aabb.min().0.y as usize;
          let end   = body_aabb.max().0.y as usize;
          text = Some ((
            child_text.0.lines().skip (skip).take (take).map (
              move |line| &line[start.min (line.len())..end.min (line.len())]),
            child.appearance.style.clone()
          ));
        } else if let Some (child_image) = Image::try_ref (&child.component) {
          debug_assert!(image.is_none());
          match child_image {
            Image::Raw64 (pixmap) => {
              let skip  = body_aabb.min().0.x as usize;
              let take  = body_aabb.max().0.x as usize - skip;
              let start = body_aabb.min().0.y as usize;
              let end   = body_aabb.max().0.y as usize;
              image = Some (pixmap.rows().skip (skip).take (take).map (
                move |row| &row[start.min (row.len())..end.min (row.len())]
              ));
            }
            Image::Raw8(_) | Image::Raw16(_) | Image::Raw32(_) |
            Image::Texture(_) => {
              // TODO: image resource
              image = None;
            }
          }
        }
      }
      self.draw_canvas (&canvas, style, text, image, true);
    }
    // TODO: win().refresh() ?
    //self.inner.draw_border_default();  // TODO: debug
    log::trace!("...display view");

    fn canvas_and_body_aabb (child_canvas : &Canvas, screen_aabb : Aabb2 <i32>)
      -> Option <(Canvas, Aabb2 <i32>)>
    {
      let child_aabb = child_canvas.coordinates.into();
      intersect::continuous_aabb2_aabb2 (screen_aabb, child_aabb).map (
        |intersection| {
          let coordinates = view::Coordinates::tile_from_aabb (intersection);
          let mut canvas  = Canvas {
            coordinates, .. child_canvas.clone()
          };
          let (body_width, body_height) = child_canvas.body_wh();
          let (mut body_min_row, mut body_min_col) = (0, 0);
          let (mut body_max_row, mut body_max_col) =
            (body_height as i32, body_width as i32);
          if let Some (border) = canvas.border.as_mut() {
            let outside_top = screen_aabb.min().0.x - child_aabb.min().0.x;
            if outside_top > 0 {
              body_min_row = (outside_top as u32)
                .saturating_sub (border.thickness_top as u32) as i32;
              border.thickness_top = border.thickness_top
                .saturating_sub (outside_top    as u16);
            }
            let outside_bottom = child_aabb.max().0.x - screen_aabb.max().0.x;
            if outside_bottom > 0 {
              body_max_row -= (outside_bottom as u32)
                .saturating_sub (border.thickness_bottom as u32) as i32;
              border.thickness_bottom = border.thickness_bottom
                .saturating_sub (outside_bottom as u16);
            }
            let outside_left = screen_aabb.min().0.y - child_aabb.min().0.y;
            if outside_left > 0 {
              body_min_col = (outside_left as u32)
                .saturating_sub (border.thickness_left as u32) as i32;
              border.thickness_left   = border.thickness_left
                .saturating_sub (outside_left   as u16);
            }
            let outside_right = child_aabb.max().0.y - screen_aabb.max().0.y;
            if outside_right > 0 {
              body_max_col -= (outside_right as u32)
                .saturating_sub (border.thickness_right as u32) as i32;
              border.thickness_right  = border.thickness_right
                .saturating_sub (outside_right  as u16);
            }
          }
          ( canvas,
            Aabb2::with_minmax (
              [body_min_row, body_min_col].into(),
              [body_max_row, body_max_col].into()
            )
          )
        }
      )
    }
  }
}

impl Curses {
  // TODO: debug flag
  fn draw_canvas <'a> (&mut self,
    canvas : &view::component::Canvas,
    style  : &view::Style,
    text   : Option <(impl Iterator <Item=&'a str>, Option <view::Style>)>,
    image  : Option <impl Iterator <Item=&'a [u64]>>,
    _debug : bool
  ) {
    use std::convert::TryInto;
    use nsys::curses::{chtype_color_pair, color_pair_attr, pancurses_ok,
      pancurses_warn_ok};
    use pancurses::chtype;
    use crate::interface::view::component::canvas;
    log::trace!("draw_canvas...");
    let curses  = &mut self.inner;
    let (position, dimensions)
      : (view::position::Tile, view::dimensions::Tile)
      = canvas.coordinates.try_into().unwrap();
    let (rc_min, rc_max) = {
      let (row,  col)  = (position.row(), position.column());
      let (rows, cols) = (dimensions.rows() as i32, dimensions.columns() as i32);
      ( (row, col),
        (row + rows-1, col + cols-1) )
    };
    // clear
    let clear_color = match canvas.clear_color {
      canvas::ClearColor::Appearance    => Some (style.bg),
      canvas::ClearColor::Fixed (color) => color
    };
    clear_color.map (|color|{
      let border       = ' ' as chtype;
      let bgcolor      = convert_color (color).unwrap();
      let fill_color   = color_pair_attr (easycurses::Color::White, bgcolor);
      let fill         = ' ' as chtype | fill_color;
      curses.draw_rect (border, fill, rc_min, rc_max, 0,0);  // 0,0: no border
    });
    let color = color_pair_attr (
      convert_color (style.fg).unwrap(),
      convert_color (style.bg).unwrap());
    let color_pair = chtype_color_pair (color);
    pancurses_ok!(curses.win().color_set (color_pair));
    curses.win().bkgdset (b' ' as chtype | color);
    // border
    #[expect(trivial_numeric_casts)]
    let (border_thickness_top, border_thickness_left) =
      canvas.border.as_ref().map (|border|{
        pancurses_warn_ok!(curses.draw_border (
          border.left         as chtype | color,
          border.right        as chtype | color,
          border.top          as chtype | color,
          border.bottom       as chtype | color,
          border.top_left     as chtype | color,
          border.top_right    as chtype | color,
          border.bottom_left  as chtype | color,
          border.bottom_right as chtype | color,
          rc_min, rc_max,
          border.thickness_top    as u32,
          border.thickness_bottom as u32,
          border.thickness_left   as u32,
          border.thickness_right  as u32
        ));
        ( border.thickness_top  as i32,
          border.thickness_left as i32 )
      }).unwrap_or_default();
    // text
    text.map (|(text, style)|{
      style.map (|style|{
        let color = color_pair_attr (
          convert_color (style.fg).unwrap(),
          convert_color (style.bg).unwrap());
        let color_pair = chtype_color_pair (color);
        pancurses_ok!(curses.win().color_set (color_pair));
        curses.win().bkgdset (b' ' as chtype | color);
      });
      for (i, line) in text.enumerate() {
        let printable = line.trim_start_matches ('\0');
        let skip = line.len() - printable.len();
        let row = rc_min.0 + border_thickness_top + i as i32;
        let col = rc_min.1 + border_thickness_left + skip as i32;
        if line.len() > 0 {
          let _ = curses.win().mvaddstr (row, col, printable);
        }
      }
    });
    // image
    image.map (|image|{
      for (i, line) in image.enumerate() {
        let row = rc_min.0 + border_thickness_top + i as i32;
        let col = rc_min.1 + border_thickness_left;
        for (j, ch) in line.iter().enumerate() {
          if *ch != 0x0 {
            let _ = curses.win().mvaddch (row, col+j as i32, *ch as chtype);
          }
        }
      }
    });
    log::trace!("...draw_canvas");
  }
}

impl From <pancurses::Input> for view::Input {

  /// Convert from pancurses input to an input button (keycode). Note that
  /// easycurses exports an alias of `pancurses::Input` as `easycurses::Input`.
  ///
  /// Note that some key combinations may not be captured or may be missing
  /// modifiers.
  fn from (input : pancurses::Input) -> Self {
    use pancurses::Input::*;
    use view::input::{self, button::Keycode, Modifiers};
    const ALT   : Modifiers = Modifiers::ALT;
    const CTRL  : Modifiers = Modifiers::CTRL;
    const SHIFT : Modifiers = Modifiers::SHIFT;
    const EMPTY : Modifiers = Modifiers::empty();
    let unhandled = |input| {
      log::warn!("curses unhandled input: {input:?}");
      (Keycode::NonConvert, EMPTY)
    };
    #[expect(clippy::match_same_arms)]
    let (keycode, modifiers) = match input {
      Character (ch) => match ch {
        'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' |
        'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' |
        'y' | 'z' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0' |
        '-' | '=' | '`' | '[' | ']' | '\\'| ';' | '\''| ',' | '.' | '/' | 'A' |
        'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' |
        'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' |
        'Z' | '!' | '@' | '#' | '$' | '%' | '^' | '&' | '*' | '(' | ')' | '_' |
        '+' | '~' | '{' | '}' | '|' | ':' | '"' | '<' | '>' | '?' | ' ' | '\n'|
        '\t'    => return input::Text::Char (ch).into(),
        special => {
          let unhandled = |ch| {
            log::warn!("curses unhandled special character: {ch:?}");
            (Keycode::NonConvert, EMPTY)
          };
          let keyname = pancurses::keyname (special as i32).unwrap_or_else (||{
            log::error!("pancurses keyname failed for special char {special:?}");
            unreachable!()
          });
          log::trace!("keyname: {keyname:?}");
          match keyname.as_str() {
            "^A" => (Keycode::A, CTRL),
            "^B" => (Keycode::B, CTRL),
            "^C" => (Keycode::C, CTRL),
            "^D" => (Keycode::D, CTRL),
            "^E" => (Keycode::E, CTRL),
            "^F" => (Keycode::F, CTRL),
            "^G" => (Keycode::G, CTRL),
            // NOTE: on windows (pdcurses) backspace is emitted as CTRL+H
            "^H" => (Keycode::Backspace, EMPTY),
            "^I" => (Keycode::I, CTRL),
            "^J" => (Keycode::J, CTRL),
            "^K" => (Keycode::K, CTRL),
            "^L" => (Keycode::L, CTRL),
            "^M" => (Keycode::M, CTRL),
            "^N" => (Keycode::N, CTRL),
            "^O" => (Keycode::O, CTRL),
            "^P" => (Keycode::P, CTRL),
            "^Q" => (Keycode::Q, CTRL),
            "^R" => (Keycode::R, CTRL),
            "^S" => (Keycode::S, CTRL),
            "^T" => (Keycode::T, CTRL),
            "^U" => (Keycode::U, CTRL),
            "^V" => (Keycode::V, CTRL),
            "^W" => (Keycode::W, CTRL),
            "^X" => (Keycode::X, CTRL),
            "^Y" => (Keycode::Y, CTRL),
            "^Z" => (Keycode::Z, CTRL),
            "^_" => (Keycode::Minus, SHIFT | CTRL),
            "^?" => (Keycode::Backspace,   EMPTY),
            "^[" => (Keycode::Escape, EMPTY), // note does not capture modifiers
            // note this is generated by other key combinations, e.g. Ctrl+Space
            "^@" => (Keycode::Key2, CTRL),
            // PDCurses
            "KEY_PAUSE"      => (Keycode::Pause,  EMPTY),
            "KEY_SCROLLLOCK" => (Keycode::ScrollLock, EMPTY),
            "KEY_SDOWN"      => (Keycode::Down,   SHIFT),
            "KEY_SUP"        => (Keycode::Up,     SHIFT),
            "KEY_B2"         => (Keycode::Numpad5, SHIFT),
            "SHF_PADENTER"   => (Keycode::NumpadEnter, SHIFT),
            "SHF_PADMINUS"   => (Keycode::NumpadSubtract, SHIFT),
            "SHF_PADPLUS"    => (Keycode::NumpadAdd,    SHIFT),
            "SHF_PADSLASH"   => (Keycode::NumpadDivide, SHIFT),
            "SHF_PADSTAR"    => (Keycode::NumpadMultiply, SHIFT),
            "KEY_F(25)"      => (Keycode::F1,     CTRL),
            "KEY_F(26)"      => (Keycode::F2,     CTRL),
            "KEY_F(27)"      => (Keycode::F3,     CTRL),
            "KEY_F(28)"      => (Keycode::F4,     CTRL),
            "KEY_F(29)"      => (Keycode::F5,     CTRL),
            "KEY_F(30)"      => (Keycode::F6,     CTRL),
            "KEY_F(31)"      => (Keycode::F7,     CTRL),
            "KEY_F(32)"      => (Keycode::F8,     CTRL),
            "KEY_F(33)"      => (Keycode::F9,     CTRL),
            "KEY_F(34)"      => (Keycode::F10,    CTRL),
            "KEY_F(35)"      => (Keycode::F11,    CTRL),
            "KEY_F(36)"      => (Keycode::F12,    CTRL),
            "KEY_F(37)"      => (Keycode::F1,     ALT),
            "KEY_F(38)"      => (Keycode::F2,     ALT),
            "KEY_F(39)"      => (Keycode::F3,     ALT),
            "KEY_F(40)"      => (Keycode::F4,     ALT),
            "KEY_F(41)"      => (Keycode::F5,     ALT),
            "KEY_F(42)"      => (Keycode::F6,     ALT),
            "KEY_F(43)"      => (Keycode::F7,     ALT),
            "KEY_F(44)"      => (Keycode::F8,     ALT),
            "KEY_F(45)"      => (Keycode::F9,     ALT),
            "KEY_F(46)"      => (Keycode::F10,    ALT),
            "KEY_F(47)"      => (Keycode::F11,    ALT),
            "KEY_F(48)"      => (Keycode::F12,    ALT),
            "CTL_0"          => (Keycode::Key0,   CTRL),
            "CTL_1"          => (Keycode::Key1,   CTRL),
            "CTL_2"          => (Keycode::Key2,   CTRL),
            "CTL_3"          => (Keycode::Key3,   CTRL),
            "CTL_4"          => (Keycode::Key4,   CTRL),
            "CTL_5"          => (Keycode::Key5,   CTRL),
            "CTL_6"          => (Keycode::Key6,   CTRL),
            "CTL_7"          => (Keycode::Key7,   CTRL),
            "CTL_8"          => (Keycode::Key8,   CTRL),
            "CTL_9"          => (Keycode::Key9,   CTRL),
            "CTL_DOWN"       => (Keycode::Down,   CTRL),
            "CTL_LEFT"       => (Keycode::Left,   CTRL),
            "CTL_RIGHT"      => (Keycode::Right,  CTRL),
            "CTL_UP"         => (Keycode::Up,     CTRL),
            "CTL_PAD0"       => (Keycode::Numpad0, CTRL),
            "CTL_PAD1"       => (Keycode::Numpad1, CTRL),
            "CTL_PAD2"       => (Keycode::Numpad2, CTRL),
            "CTL_PAD3"       => (Keycode::Numpad3, CTRL),
            "CTL_PAD4"       => (Keycode::Numpad4, CTRL),
            "CTL_PAD5"       => (Keycode::Numpad5, CTRL),
            "CTL_PAD6"       => (Keycode::Numpad6, CTRL),
            "CTL_PAD7"       => (Keycode::Numpad7, CTRL),
            "CTL_PAD8"       => (Keycode::Numpad8, CTRL),
            "CTL_PAD9"       => (Keycode::Numpad9, CTRL),
            "CTL_PADENTER"   => (Keycode::NumpadEnter, CTRL),
            "CTL_PADMINUS"   => (Keycode::NumpadSubtract, CTRL),
            "CTL_PADPLUS"    => (Keycode::NumpadAdd,  CTRL),
            "CTL_PADSLASH"   => (Keycode::NumpadDivide, CTRL),
            "CTL_PADSTOP"    => (Keycode::NumpadDecimal, CTRL),
            "CTL_PADSTAR"    => (Keycode::NumpadMultiply, CTRL),
            "CTL_BQUOTE"     => (Keycode::Grave,  CTRL),
            "CTL_DEL"        => (Keycode::Delete, CTRL),
            "CTL_END"        => (Keycode::End,    CTRL),
            "CTL_FLASH"      => (Keycode::Slash,  CTRL),
            "CTL_HOME"       => (Keycode::Home,   CTRL),
            "CTL_INS"        => (Keycode::Insert, CTRL),
            "CTL_PAUSE"      => (Keycode::Pause,  CTRL),
            "CTL_PGDN"       => (Keycode::PageDown, CTRL),
            "CTL_PGUP"       => (Keycode::PageUp, CTRL),
            "CTL_SEMICOLON"  => (Keycode::Semicolon, CTRL),
            "CTL_STOP"       => (Keycode::Period, CTRL),
            "CTL_TAB"        => (Keycode::Tab,    CTRL),
            "ALT_0"          => (Keycode::Key0, ALT),
            "ALT_1"          => (Keycode::Key1, ALT),
            "ALT_2"          => (Keycode::Key2, ALT),
            "ALT_3"          => (Keycode::Key3, ALT),
            "ALT_4"          => (Keycode::Key4, ALT),
            "ALT_5"          => (Keycode::Key5, ALT),
            "ALT_6"          => (Keycode::Key6, ALT),
            "ALT_7"          => (Keycode::Key7, ALT),
            "ALT_8"          => (Keycode::Key8, ALT),
            "ALT_9"          => (Keycode::Key9, ALT),
            "ALT_A"          => (Keycode::A, ALT),
            "ALT_B"          => (Keycode::B, ALT),
            "ALT_C"          => (Keycode::C, ALT),
            "ALT_D"          => (Keycode::D, ALT),
            "ALT_E"          => (Keycode::E, ALT),
            "ALT_F"          => (Keycode::F, ALT),
            "ALT_G"          => (Keycode::G, ALT),
            "ALT_H"          => (Keycode::H, ALT),
            "ALT_I"          => (Keycode::I, ALT),
            "ALT_J"          => (Keycode::J, ALT),
            "ALT_K"          => (Keycode::K, ALT),
            "ALT_L"          => (Keycode::L, ALT),
            "ALT_M"          => (Keycode::M, ALT),
            "ALT_N"          => (Keycode::N, ALT),
            "ALT_O"          => (Keycode::O, ALT),
            "ALT_P"          => (Keycode::P, ALT),
            "ALT_Q"          => (Keycode::Q, ALT),
            "ALT_R"          => (Keycode::R, ALT),
            "ALT_S"          => (Keycode::S, ALT),
            "ALT_T"          => (Keycode::T, ALT),
            "ALT_U"          => (Keycode::U, ALT),
            "ALT_V"          => (Keycode::V, ALT),
            "ALT_W"          => (Keycode::W, ALT),
            "ALT_X"          => (Keycode::X, ALT),
            "ALT_Y"          => (Keycode::Y, ALT),
            "ALT_Z"          => (Keycode::Z, ALT),
            "ALT_BKSP"       => (Keycode::Backspace,   ALT),
            "ALT_BQUOTE"     => (Keycode::Grave,  ALT),
            "ALT_BSLASH"     => (Keycode::Backslash, ALT),
            "^\\"            => (Keycode::LBracket, ALT),
            "ALT_COMMA"      => (Keycode::Comma, ALT),
            "ALT_DEL"        => (Keycode::Delete, ALT),
            "ALT_END"        => (Keycode::End,    ALT),
            "ALT_ENTER"      => (Keycode::Enter, ALT),
            "ALT_EQUALS"     => (Keycode::Equal, ALT),
            "ALT_HOME"       => (Keycode::Home,   ALT),
            "ALT_INS"        => (Keycode::Insert, ALT),
            "ALT_FQUOTE"     => (Keycode::Quote, ALT),
            "ALT_FSLASH"     => (Keycode::Slash, ALT),
            "ALT_MINUS"      => (Keycode::Minus, ALT),
            "ALT_PGDN"       => (Keycode::PageDown, ALT),
            "ALT_PGUP"       => (Keycode::PageUp, ALT),
            "ALT_RBRACKET"   => (Keycode::RBracket, ALT),
            "ALT_SCROLLLOCK" => (Keycode::ScrollLock, ALT),
            "ALT_SEMICOLON"  => (Keycode::Semicolon, ALT),
            "ALT_STOP"       => (Keycode::Period, ALT),
            "ALT_PADENTER"   => (Keycode::NumpadEnter, ALT),
            "ALT_PADMINUS"   => (Keycode::NumpadSubtract, ALT),
            "ALT_PADSLASH"   => (Keycode::NumpadDivide, ALT),
            "ALT_PADSTAR"    => (Keycode::NumpadMultiply, ALT),
            "ALT_PADSTOP"    => (Keycode::NumpadDecimal, ALT),
            ch => unhandled (ch)
          }
        }
      },
      Unknown(_) => unhandled (input),
      KeyCodeYes => unhandled (input),

      KeyBreak => (Keycode::Pause, EMPTY),
      KeyDown => (Keycode::Down, EMPTY),
      KeyUp => (Keycode::Up, EMPTY),
      KeyLeft => (Keycode::Left, EMPTY),
      KeyRight => (Keycode::Right, EMPTY),
      KeyHome => (Keycode::Home, EMPTY),
      KeyBackspace => (Keycode::Backspace, EMPTY),
      KeyF0 => unhandled (input),
      KeyF1 => (Keycode::F1, EMPTY),
      KeyF2 => (Keycode::F2, EMPTY),
      KeyF3 => (Keycode::F3, EMPTY),
      KeyF4 => (Keycode::F4, EMPTY),
      KeyF5 => (Keycode::F5, EMPTY),
      KeyF6 => (Keycode::F6, EMPTY),
      KeyF7 => (Keycode::F7, EMPTY),
      KeyF8 => (Keycode::F8, EMPTY),
      KeyF9 => (Keycode::F9, EMPTY),
      KeyF10 => (Keycode::F10, EMPTY),
      KeyF11 => (Keycode::F11, EMPTY),
      KeyF12 => (Keycode::F12, EMPTY),
      KeyF13 => (Keycode::F13, EMPTY),
      KeyF14 => (Keycode::F14, EMPTY),
      KeyF15 => (Keycode::F15, EMPTY),

      KeyDL => unhandled (input),
      KeyIL => unhandled (input),
      KeyDC => (Keycode::Delete, EMPTY),
      KeyIC => (Keycode::Insert, EMPTY),
      KeyEIC => unhandled (input),
      KeyClear => unhandled (input),
      KeyEOS => unhandled (input),
      KeyEOL => unhandled (input),
      KeySF => (Keycode::Down, SHIFT),
      KeySR => (Keycode::Up, SHIFT),
      KeyNPage => (Keycode::PageDown, EMPTY),
      KeyPPage => (Keycode::PageUp, EMPTY),
      KeySTab => unhandled (input),  // shift+tab generates KeyBTab
      KeyCTab => unhandled (input),
      KeyCATab => unhandled (input),
      KeyEnter => (Keycode::Enter, EMPTY),
      KeySReset => unhandled (input),
      KeyReset => unhandled (input),
      KeyPrint => unhandled (input),
      KeyLL => unhandled (input),
      KeyAbort => unhandled (input),
      KeySHelp => unhandled (input),
      KeyLHelp => unhandled (input),
      KeyBTab => (Keycode::Tab, SHIFT),
      KeyBeg => unhandled (input),
      KeyCancel => unhandled (input),
      KeyClose => unhandled (input),
      KeyCommand => unhandled (input),
      KeyCopy => (Keycode::Copy, EMPTY),
      KeyCreate => unhandled (input),
      KeyEnd => (Keycode::End, EMPTY),
      KeyExit => unhandled (input),
      KeyFind => unhandled (input),
      KeyHelp => unhandled (input),
      KeyMark => unhandled (input),
      KeyMessage => unhandled (input),
      KeyMove => unhandled (input),
      KeyNext => unhandled (input),
      KeyOpen => unhandled (input),
      KeyOptions => unhandled (input),
      KeyPrevious => unhandled (input),
      KeyRedo => unhandled (input),
      KeyReference => unhandled (input),
      KeyRefresh => unhandled (input),
      KeyReplace => unhandled (input),
      KeyRestart => unhandled (input),
      KeyResume => unhandled (input),
      KeySave => unhandled (input),
      KeySBeg => unhandled (input),
      KeySCancel => unhandled (input),
      KeySCommand => unhandled (input),
      KeySCopy => unhandled (input),
      KeySCreate => unhandled (input),
      KeySDC => (Keycode::Delete, SHIFT),
      KeySDL => unhandled (input),
      KeySelect => unhandled (input),
      KeySEnd => (Keycode::End, SHIFT),
      KeySEOL => unhandled (input),
      KeySExit => unhandled (input),
      KeySFind => unhandled (input),
      KeySHome => (Keycode::Home, SHIFT),
      KeySIC => (Keycode::Insert, SHIFT),

      // PDCurses produces KeySMessage on Shift+Left
      KeySLeft | KeySMessage => (Keycode::Left, SHIFT),
      KeySMove => unhandled (input),
      KeySNext => (Keycode::PageDown, SHIFT),
      KeySOptions => unhandled (input),
      KeySPrevious => (Keycode::PageUp, SHIFT),
      KeySPrint => unhandled (input),
      KeySRedo => unhandled (input),
      KeySReplace => unhandled (input),
      // PDCurses produces KeySResume on Shift+Right
      KeySRight | KeySResume => (Keycode::Right, SHIFT),
      KeySSave => unhandled (input),
      KeySSuspend => unhandled (input),
      KeySUndo => unhandled (input),
      KeySuspend => unhandled (input),
      KeyUndo => unhandled (input),

      // NOTE: because we don't have access to the pancurses window in this
      // scope, we return a resize input event with zero dimensions; the
      // get_input() impl will take care of setting the correct size before
      // returning the event
      KeyResize => return input::System::Resized { width: 0, height: 0 }.into(),
      KeyEvent => unhandled (input),
      KeyMouse => unhandled (input),

      KeyA1 => unhandled (input),
      KeyA3 => unhandled (input),
      KeyB2 => unhandled (input),
      KeyC1 => unhandled (input),
      KeyC3 => unhandled (input)
    };
    ( input::Button {
        variant: keycode.into(),
        modifiers
      },
      input::button::State::Pressed
    ).into()
  }
}

/// Converts a character to a keycode+modifier. The modifier is 'SHIFT' if the
/// character is uppercase or requires pressing shift to type under usual
/// circumstances (e.g. '!'), and empty otherwise.
fn char_to_keycode (ch : char)
  -> (view::input::button::Keycode, view::input::Modifiers)
{
  use view::input::Modifiers;
  use view::input::button::Keycode;
  const EMPTY : Modifiers = Modifiers::empty();
  const SHIFT : Modifiers = Modifiers::SHIFT;
  match ch {
    'a' => (Keycode::A, EMPTY),
    'b' => (Keycode::B, EMPTY),
    'c' => (Keycode::C, EMPTY),
    'd' => (Keycode::D, EMPTY),
    'e' => (Keycode::E, EMPTY),
    'f' => (Keycode::F, EMPTY),
    'g' => (Keycode::G, EMPTY),
    'h' => (Keycode::H, EMPTY),
    'i' => (Keycode::I, EMPTY),
    'j' => (Keycode::J, EMPTY),
    'k' => (Keycode::K, EMPTY),
    'l' => (Keycode::L, EMPTY),
    'm' => (Keycode::M, EMPTY),
    'n' => (Keycode::N, EMPTY),
    'o' => (Keycode::O, EMPTY),
    'p' => (Keycode::P, EMPTY),
    'q' => (Keycode::Q, EMPTY),
    'r' => (Keycode::R, EMPTY),
    's' => (Keycode::S, EMPTY),
    't' => (Keycode::T, EMPTY),
    'u' => (Keycode::U, EMPTY),
    'v' => (Keycode::V, EMPTY),
    'w' => (Keycode::W, EMPTY),
    'x' => (Keycode::X, EMPTY),
    'y' => (Keycode::Y, EMPTY),
    'z' => (Keycode::Z, EMPTY),
    '1' => (Keycode::Key1, EMPTY),
    '2' => (Keycode::Key2, EMPTY),
    '3' => (Keycode::Key3, EMPTY),
    '4' => (Keycode::Key4, EMPTY),
    '5' => (Keycode::Key5, EMPTY),
    '6' => (Keycode::Key6, EMPTY),
    '7' => (Keycode::Key7, EMPTY),
    '8' => (Keycode::Key8, EMPTY),
    '9' => (Keycode::Key9, EMPTY),
    '0' => (Keycode::Key0, EMPTY),
    '-' => (Keycode::Minus, EMPTY),
    '=' => (Keycode::Equal, EMPTY),
    '`' => (Keycode::Grave, EMPTY),
    '[' => (Keycode::LBracket, EMPTY),
    ']' => (Keycode::RBracket, EMPTY),
    '\\' => (Keycode::Backslash, EMPTY),
    ';' => (Keycode::Semicolon, EMPTY),
    '\'' => (Keycode::Quote, EMPTY),
    ',' => (Keycode::Comma, EMPTY),
    '.' => (Keycode::Period, EMPTY),
    '/' => (Keycode::Slash, EMPTY),
    'A' => (Keycode::A, SHIFT),
    'B' => (Keycode::B, SHIFT),
    'C' => (Keycode::C, SHIFT),
    'D' => (Keycode::D, SHIFT),
    'E' => (Keycode::E, SHIFT),
    'F' => (Keycode::F, SHIFT),
    'G' => (Keycode::G, SHIFT),
    'H' => (Keycode::H, SHIFT),
    'I' => (Keycode::I, SHIFT),
    'J' => (Keycode::J, SHIFT),
    'K' => (Keycode::K, SHIFT),
    'L' => (Keycode::L, SHIFT),
    'M' => (Keycode::M, SHIFT),
    'N' => (Keycode::N, SHIFT),
    'O' => (Keycode::O, SHIFT),
    'P' => (Keycode::P, SHIFT),
    'Q' => (Keycode::Q, SHIFT),
    'R' => (Keycode::R, SHIFT),
    'S' => (Keycode::S, SHIFT),
    'T' => (Keycode::T, SHIFT),
    'U' => (Keycode::U, SHIFT),
    'V' => (Keycode::V, SHIFT),
    'W' => (Keycode::W, SHIFT),
    'X' => (Keycode::X, SHIFT),
    'Y' => (Keycode::Y, SHIFT),
    'Z' => (Keycode::Z, SHIFT),
    '!' => (Keycode::Key1, SHIFT),
    '@' => (Keycode::Key2, SHIFT),
    '#' => (Keycode::Key3, SHIFT),
    '$' => (Keycode::Key4, SHIFT),
    '%' => (Keycode::Key5, SHIFT),
    '^' => (Keycode::Key6, SHIFT),
    '&' => (Keycode::Key7, SHIFT),
    '*' => (Keycode::Key8, SHIFT),
    '(' => (Keycode::Key9, SHIFT),
    ')' => (Keycode::Key0, SHIFT),
    '_' => (Keycode::Minus, SHIFT),
    '+' => (Keycode::Equal, SHIFT),
    '~' => (Keycode::Grave, SHIFT),
    '{' => (Keycode::LBracket, SHIFT),
    '}' => (Keycode::RBracket, SHIFT),
    '|' => (Keycode::Backslash, SHIFT),
    ':' => (Keycode::Semicolon, SHIFT),
    '"' => (Keycode::Quote, SHIFT),
    '<' => (Keycode::Comma, SHIFT),
    '>' => (Keycode::Period, SHIFT),
    '?' => (Keycode::Slash, SHIFT),
    ' ' => (Keycode::Space, EMPTY),
    '\n' => (Keycode::Enter, EMPTY),
    '\t' => (Keycode::Tab, EMPTY),
    _ => unreachable!()
  }
}

const fn convert_color (color : view::Color)
  -> Result <easycurses::Color, view::Color>
{
  use view::color::*;
  let color = match color {
    Color::Named (named) => match named {
      Named::Monochrome (Monochrome::White)  => easycurses::Color::White,
      Named::Monochrome (Monochrome::Grey)   => return Err (color),
      Named::Monochrome (Monochrome::Black)  => easycurses::Color::Black,
      Named::Hue (hue) => match hue {
        Hue::Primary    (Primary::Red)       => easycurses::Color::Red,
        Hue::Primary    (Primary::Green)     => easycurses::Color::Green,
        Hue::Primary    (Primary::Blue)      => easycurses::Color::Blue,
        Hue::Secondary  (Secondary::Cyan)    => easycurses::Color::Cyan,
        Hue::Secondary  (Secondary::Yellow)  => easycurses::Color::Yellow,
        Hue::Secondary  (Secondary::Magenta) => easycurses::Color::Magenta,
        _ => return Err (color)
      }
    },
    Color::Raw (_) => return Err (color)
  };
  Ok (color)
}