nsys-curses-utils 0.1.1

Rust *curses utilities
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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
#![feature(decl_macro)]

use std::{fs, io};
use std::path::Path;
use std::sync::LazyLock;
use bmp;
use log;
use easycurses;
use pancurses;
use png;
use easycurses::EasyCurses;
use mat::Mat;

pub use pancurses::COLOR_PAIR as color_pair;

type PancursesResult = i32;

/// Eight default color values, 10% lum (black), 50% lum (hues), 90% lum (white)
pub static INIT_COLORS_DEFAULT : LazyLock <[[u8; 3]; 8]> = LazyLock::new (||{
  use easycurses::Color;
  let mut colors = [[0,0,0]; 8];
  colors[Color::Black   as usize ] = [  25,  25,  25 ];
  colors[Color::Red     as usize ] = [ 238,   0,   0 ];
  colors[Color::Green   as usize ] = [   0, 163,   0 ];
  colors[Color::Blue    as usize ] = [  67,  67, 255 ];
  colors[Color::Yellow  as usize ] = [ 137, 137,   0 ];
  colors[Color::Magenta as usize ] = [ 181,   0, 181 ];
  colors[Color::Cyan    as usize ] = [   0, 147, 147 ];
  colors[Color::White   as usize ] = [ 230, 230, 230 ];
  colors
});

/// Log an error and panic if pancurses call returns `ERR`
pub macro pancurses_ok {
  ($e:expr) => {{
    let result = $e;
    if result != $crate::pancurses::OK {
      $crate::log::error!("{}:l{}: pancurses error: {:?}", file!(), line!(),
        result);
      panic!()
    }
  }}
}

/// Log a warning but don't panic
pub macro pancurses_warn_ok {
  ($e:expr) => {{
    let result = $e;
    if result != $crate::pancurses::OK {
      $crate::log::warn!("{}:l{}: pancurses error: {:?}", file!(), line!(),
        result);
    }
  }}
}

/// Log an error and panic if pancurses call *does not* return `ERR`
pub macro pancurses_err {
  ($e:expr) => {{
    let result = $e;
    if result != $crate::pancurses::ERR {
      $crate::log::error!("{}:l{}: pancurses expected error, got: {:?}",
        file!(), line!(), result);
      panic!()
    }
  }}
}

/// Log a warning if pancurses call *does not* return `ERR`
pub macro pancurses_warn_err {
  ($e:expr) => {{
    let result = $e;
    if result != $crate::pancurses::ERR {
      $crate::log::warn!("{}:l{}: pancurses expected error, got: {:?}",
        file!(), line!(), result);
    }
  }}
}

#[cfg(not(target_os = "windows"))]
pub const ATTRIBUTE_MASK : pancurses::chtype = pancurses::A_ATTRIBUTES;
#[cfg(target_os = "windows")]
pub const ATTRIBUTE_MASK : pancurses::chtype =
  !0x0 << pancurses::PDC_CHARTEXT_BITS;

/// Wraps an `EasyCurses` window
#[derive(Debug)]
pub struct Curses {
  pub easycurses : EasyCurses
}

/// Constructs the color pair number that `easycurses` assigned to this color
/// combination, equal to `1 + (8 * fg + bg)`, giving a number in the range
/// `1-64`
#[inline]
pub const fn color_pair_id (fg : easycurses::Color, bg : easycurses::Color) -> u8 {
  1 + 8 * fg as u8 + bg as u8
}

/// Constructs the color pair attribute `chtype`.
///
/// Equivalent to `COLOR_PAIR(color_pair_id(fg,bg))`.
#[inline]
pub /*const*/ fn color_pair_attr (fg : easycurses::Color, bg : easycurses::Color)
  -> pancurses::chtype
{
  color_pair (color_pair_id (fg, bg) as pancurses::chtype)
}

/// Get the 8-bit character data from the first byte of a `chtype`.
#[inline]
pub const fn chtype_character (ch : pancurses::chtype) -> char {
  ch.to_le_bytes()[0] as char
}

/// Get the color pair number from the second byte of a `chtype`
#[inline]
pub const fn chtype_color_pair (ch : pancurses::chtype) -> i16 {
  ch.to_le_bytes()[1] as i16
}

/// Returns the (fg, bg) color for the given color pair index.
///
/// Returns None if the index was >64.
///
/// Returns `Some (White, Black)` if the index is 0.
#[inline]
#[expect(clippy::missing_panics_doc)]
pub const fn color_pair_colors (color_pair : i16)
  -> Option <(easycurses::Color, easycurses::Color)>
{
  if color_pair == 0 {
    Some ((easycurses::Color::White, easycurses::Color::Black))
  } else if color_pair <= 64 {
    let bg = (color_pair-1) & 0b0000_0111;
    let fg = ((color_pair-1) & 0b0011_1000) >> 3;
    Some ((
      color_from_primitive (fg).unwrap(),
      color_from_primitive (bg).unwrap()
    ))
  } else {
    None
  }
}

/// Get the attributes of a `chtype` (equivalent to `A_ATTRIBUTES & ch` in
/// ncurses)
#[inline]
pub const fn chtype_attrs (ch : pancurses::chtype) -> pancurses::chtype {
  ATTRIBUTE_MASK & ch
}

pub const fn color_from_primitive (color : i16) -> Option <easycurses::Color> {
  use easycurses::Color;
  let color = match color {
    0 => Color::Black,
    1 => Color::Red,
    2 => Color::Green,
    3 => Color::Yellow,
    4 => Color::Blue,
    5 => Color::Magenta,
    6 => Color::Cyan,
    7 => Color::White,
    _ => return None
  };
  Some (color)
}

pub const fn color_complement (color : easycurses::Color) -> easycurses::Color {
  use easycurses::Color;
  match color {
    Color::Black   => Color::White,
    Color::White   => Color::Black,
    Color::Red     => Color::Cyan,
    Color::Green   => Color::Magenta,
    Color::Blue    => Color::Yellow,
    Color::Cyan    => Color::Red,
    Color::Magenta => Color::Green,
    Color::Yellow  => Color::Blue
  }
}

/// Maps pure primary or secondary color (e.g. [255, 255, 0, 255]) with `a > 0` to
/// easycurses Color
///
/// Returns `None` when `a == 0` or if any color bytes are something other than
/// 0 or 255
pub const fn rgba_to_color (rgba : [u8; 4]) -> Option <easycurses::Color> {
  use easycurses::Color;
  let color = match rgba {
    [  _,   _,   _,   0] => return None,
    [  0,   0,   0,   _] => Color::Black,
    [255, 255, 255,   _] => Color::White,
    [255,   0,   0,   _] => Color::Red,
    [  0, 255,   0,   _] => Color::Green,
    [  0,   0, 255,   _] => Color::Blue,
    [  0, 255, 255,   _] => Color::Cyan,
    [255,   0, 255,   _] => Color::Magenta,
    [255, 255,   0,   _] => Color::Yellow,
    _ => return None
  };
  Some (color)
}

/// Sets the background to the given rgba color and the foreground to its complement.
#[inline]
pub fn rgba_to_color_pair (rgba : [u8; 4]) -> Option <pancurses::ColorPair> {
  #[expect(trivial_numeric_casts)]
  #[expect(clippy::unnecessary_cast)]
  rgba_to_color (rgba).map (
    |bg| pancurses::ColorPair (color_pair_id (color_complement (bg), bg) as u8))
}

/// &#9888; Note: the curses window must be created before calling the method,
/// as `ACS_CKBOARD()` returns `0x0` before initialization.
///
/// Uses `pancurses::ACS_CKBOARD()` to create half-tones from pixels with 50%
/// intensity.
///
/// Foreground will always be black, but will be transparent for pure chroma
/// pixels.
#[inline]
pub fn rgba_to_color_halftone (rgba : [u8; 4]) -> Option <pancurses::chtype> {
  use easycurses::Color;
  let fg = Color::Black;
  let (bg, ch) = if let Some (bg) = rgba_to_color (rgba) {
    (bg, b' ' as pancurses::chtype)
  } else {
    let bg = match rgba {
      [  _,   _,   _,   0] => return None,
      [  0,   0,   0,   _] => Color::Black,
      [128, 128, 128,   _] => Color::White,
      [128,   0,   0,   _] => Color::Red,
      [  0, 128,   0,   _] => Color::Green,
      [  0,   0, 128,   _] => Color::Blue,
      [  0, 128, 128,   _] => Color::Cyan,
      [128,   0, 128,   _] => Color::Magenta,
      [128, 128,   0,   _] => Color::Yellow,
      _ => return None
    };
    (bg, pancurses::ACS_CKBOARD())
  };
  Some (ch | color_pair_attr (fg, bg))
}

/// *Deprecated*: this doesn't really work for non-ASCII unicode, use `image_ascii_load`
/// functions instead.
///
/// Load a text file
#[deprecated]
#[expect(clippy::missing_panics_doc)]
pub fn image_text_load <P : AsRef <Path>> (path : P) -> Mat <char> {
  use io::Read;
  let mut buf = String::new();
  let _ = fs::File::open (path).unwrap().read_to_string (&mut buf).unwrap();
  buf.pop();  // read_to_end includes a final newline
  #[expect(deprecated)]
  image_text_load_str (&buf)
}

/// *Deprecated*: this doesn't really work for non-ASCII unicode, use `image_ascii_load`
/// functions instead.
///
/// Load a text image from raw string data.
///
/// Newlines will be stripped out and the horizontal dimension will be determined by the
/// longest line.
#[deprecated]
#[expect(clippy::missing_panics_doc)]
pub fn image_text_load_str (chars : &str) -> Mat <char> {
  let lines   = chars.lines();
  let rows    = lines.clone().count();
  let cols    = lines.clone().map (str::len).max().unwrap();
  let mut vec = Vec::new();
  for line in lines {
    let len = line.chars().count();
    vec.extend (line.chars());
    vec.extend (std::iter::repeat_n (' ', cols - len));
  }
  Mat::from_vec ((rows, cols).into(), vec).unwrap()
}

/// Load an ASCII text file
#[expect(clippy::missing_panics_doc)]
pub fn image_ascii_load <P : AsRef <Path>> (path : P) -> Mat <u8> {
  use io::Read;
  let mut buf = Vec::new();
  let _ = fs::File::open (path).unwrap().read_to_end (&mut buf).unwrap();
  buf.pop();  // read_to_end includes a final newline
  image_ascii_load_bytes (buf.as_slice())
}

/// Load a ASCII text image from raw bytes.
///
/// Newlines will be stripped out and the horizontal dimension will be determined by the
/// longest line.
#[expect(clippy::missing_panics_doc)]
pub fn image_ascii_load_bytes (chars : &[u8]) -> Mat <u8> {
  let split   = chars.split (|ch| ch == &b'\n');
  let rows    = split.clone().count();
  let cols    = split.clone().map (<[u8]>::len).max().unwrap();
  let mut vec = Vec::new();
  for line in split {
    let len = line.len();
    vec.extend (line);
    vec.extend (std::iter::repeat_n (b' ', cols - len));
  }
  Mat::from_vec ((rows, cols).into(), vec).unwrap()
}

/// Load an image of pure chroma pixels
#[inline]
#[expect(clippy::missing_panics_doc)]
pub fn image_color_load_bmp24 <P : AsRef <Path>> (path : P) -> Mat <easycurses::Color> {
  let image = bmp::open (path).unwrap();
  image_color_load_bmp24_helper (image)
}

/// Load an image of pure chroma pixels from memory
#[inline]
#[expect(clippy::missing_panics_doc)]
pub fn image_color_load_bmp24_bytes (mut bytes : &[u8]) -> Mat <easycurses::Color> {
  let image = bmp::from_reader (&mut bytes).unwrap();
  image_color_load_bmp24_helper (image)
}

/// Load an image of pure chroma pixels with alpha channel values of `0` as
/// transparency
#[inline]
#[expect(clippy::missing_panics_doc)]
pub fn image_color_load_png <P : AsRef <Path>> (path : P)
  -> Mat <Option <easycurses::Color>>
{
  let file    = io::BufReader::new (fs::File::open (path).unwrap());
  let decoder = png::Decoder::new (file);
  image_color_load_png_helper (decoder)
}

/// Load an image of pure chroma pixels with alpha channel values of `0` as transparency
#[inline]
pub fn image_color_load_png_bytes (bytes : &[u8]) -> Mat <Option <easycurses::Color>> {
  let decoder = png::Decoder::new (io::Cursor::new (bytes));
  image_color_load_png_helper (decoder)
}

/// Load an image of pure chroma background pixels with the color pair foreground set to
/// the complement of the background
#[inline]
#[expect(clippy::missing_panics_doc)]
pub fn image_color_bg_load_bmp24 <P : AsRef <Path>> (path : P)
  -> Mat <pancurses::ColorPair>
{
  let image = bmp::open (path).unwrap();
  image_color_bg_load_bmp24_helper (image)
}

/// Load an image of pure chroma background pixels with the color pair foreground set to
/// the complement of the background
#[inline]
#[expect(clippy::missing_panics_doc)]
pub fn image_color_bg_load_bmp24_bytes (mut bytes : &[u8])
  -> Mat <pancurses::ColorPair>
{
  let image = bmp::from_reader (&mut bytes).unwrap();
  image_color_bg_load_bmp24_helper (image)
}

/// Load foreground and background pair of 24bit BMP image color data.
///
/// &#9888; Images must have the same dimensions.
#[expect(clippy::missing_panics_doc)]
pub fn image_color_pair_load_bmp24 <P : AsRef <Path>> (fg : P, bg : P)
  -> Mat <pancurses::ColorPair>
{
  let fg = bmp::open (fg).unwrap();
  let bg = bmp::open (bg).unwrap();
  image_color_pair_load_bmp24_helper (fg, bg)
}

/// Load foreground and background pair of 24bit BMP image color data.
///
/// &#9888; Images must have the same dimensions.
#[expect(clippy::missing_panics_doc)]
pub fn image_color_pair_load_bmp24_bytes (mut fg : &[u8], mut bg : &[u8])
  -> Mat <pancurses::ColorPair>
{
  let fg = bmp::from_reader (&mut fg).unwrap();
  let bg = bmp::from_reader (&mut bg).unwrap();
  image_color_pair_load_bmp24_helper (fg, bg)
}

/// Load an image of pure chroma pixels
#[expect(clippy::missing_panics_doc)]
pub fn image_color_halftone_load_bmp24 <P : AsRef <Path>> (path : P)
  -> Mat <pancurses::chtype>
{
  let image = bmp::open (path).unwrap();
  image_color_halftone_load_bmp24_helper (image)
}

/// Load an image of pure chroma pixels
#[expect(clippy::missing_panics_doc)]
pub fn image_color_halftone_load_bmp24_bytes (mut bytes : &[u8])
  -> Mat <pancurses::chtype>
{
  let image = bmp::from_reader (&mut bytes).unwrap();
  image_color_halftone_load_bmp24_helper (image)
}

/// Load an image of ASCII characters as `pancurses::chtype`s
#[expect(clippy::missing_panics_doc)]
pub fn image_chtype (colors : &Mat <pancurses::ColorPair>, chars : &Mat <u8>)
  -> Mat <pancurses::chtype>
{
  let dimensions = colors.dimensions();
  assert_eq!(dimensions, chars.dimensions());
  let vec = colors.elements().zip (chars.elements()).map (|(color, ch)|
    color_pair (color.0 as pancurses::chtype) |
    *ch as pancurses::chtype
  ).collect::<Vec <pancurses::chtype>>();
  Mat::from_vec (dimensions, vec).unwrap()
}

/// Load an image of UTF8 characters as `pancurses::chtype`s.
#[expect(clippy::missing_panics_doc)]
pub fn image_chtype_text (colors : &Mat <pancurses::ColorPair>, chars : &Mat <char>)
  -> Mat <pancurses::chtype>
{
  let dimensions = colors.dimensions();
  assert_eq!(dimensions, chars.dimensions());
  let vec = colors.elements().zip (chars.elements()).map (|(color, ch)|
    color_pair (color.0 as pancurses::chtype) |
    *ch as pancurses::chtype
  ).collect::<Vec <pancurses::chtype>>();
  Mat::from_vec (dimensions, vec).unwrap()
}

//
//  private
//

fn image_color_load_bmp24_helper (image : bmp::Image) -> Mat <easycurses::Color> {
  let cols  = image.get_width()  as usize;
  let rows  = image.get_height() as usize;
  let vec   = image.coordinates().map (|(x, y)|{
    let pixel = image.get_pixel (x, y);
    rgba_to_color ([pixel.r, pixel.g, pixel.b, 255]).unwrap()
  }).collect::<Vec <easycurses::Color>>();
  Mat::from_vec ((rows, cols).into(), vec).unwrap()
}

fn image_color_bg_load_bmp24_helper (image : bmp::Image) -> Mat <pancurses::ColorPair> {
  let cols  = image.get_width()  as usize;
  let rows  = image.get_height() as usize;
  let vec   = image.coordinates().map (|(x, y)|{
    let pixel = image.get_pixel (x, y);
    rgba_to_color_pair ([pixel.r, pixel.g, pixel.b, 255]).unwrap()
  }).collect::<Vec <pancurses::ColorPair>>();
  Mat::from_vec ((rows, cols).into(), vec).unwrap()
}

fn image_color_pair_load_bmp24_helper (fg : bmp::Image, bg : bmp::Image)
  -> Mat <pancurses::ColorPair>
{
  let rows = fg.get_height() as usize;
  let cols = fg.get_width()  as usize;
  assert_eq!(rows, bg.get_height() as usize);
  assert_eq!(cols, bg.get_width()  as usize);
  let vec  = fg.coordinates().map (|(x, y)|{
    let fg = {
      let pixel = fg.get_pixel (x, y);
      rgba_to_color ([pixel.r, pixel.g, pixel.b, 255]).unwrap()
    };
    let bg = {
      let pixel = bg.get_pixel (x, y);
      rgba_to_color ([pixel.r, pixel.g, pixel.b, 255]).unwrap()
    };
    #[expect(trivial_numeric_casts)]
    #[expect(clippy::unnecessary_cast)]
    pancurses::ColorPair (color_pair_id (fg, bg) as u8)
  }).collect::<Vec <pancurses::ColorPair>>();
  Mat::from_vec ((rows, cols).into(), vec).unwrap()
}

fn image_color_halftone_load_bmp24_helper (image : bmp::Image)
  -> Mat <pancurses::chtype>
{
  let cols  = image.get_width()  as usize;
  let rows  = image.get_height() as usize;
  let vec   = image.coordinates().map (|(x, y)|{
    let pixel = image.get_pixel (x, y);
    rgba_to_color_halftone ([pixel.r, pixel.g, pixel.b, 255]).unwrap()
  }).collect::<Vec <pancurses::chtype>>();
  Mat::from_vec ((rows, cols).into(), vec).unwrap()
}

fn image_color_load_png_helper <R> (decoder : png::Decoder <R>)
  -> Mat <Option <easycurses::Color>>
where R : io::BufRead + io::Seek {
  let mut reader = decoder.read_info().unwrap();
  let info = reader.info();
  match info.color_type {
    png::ColorType::Rgba => {}
    _ => {
      log::error!("invalid color type: {:?}", info.color_type);
      panic!()
    }
  }
  match info.bit_depth {
    png::BitDepth::Eight => {}
    _ => {
      log::error!("invalid bit depth: {:?}", info.bit_depth);
      panic!()
    }
  }
  let mut bytes = vec![0; reader.output_buffer_size().unwrap()];
  let rows  = info.height as usize;
  let cols  = info.width  as usize;
  reader.next_frame (&mut bytes).unwrap();
  let mut vec = Vec::with_capacity (rows * cols);
  for i in 0..rows {
    for j in 0..cols {
      let offset = i * 4 * cols + j * 4;
      let pixel  = &bytes[offset..offset+4];
      debug_assert_eq!(pixel.len(), 4);
      let color  = rgba_to_color ([pixel[0], pixel[1], pixel[2], pixel[3]]);
      vec.push (color);
    }
  }
  Mat::from_vec ((rows, cols).into(), vec).unwrap()
}

impl Curses {
  /// Constructs an easycurses window with some default options set:
  ///
  /// - hidden cursor
  /// - no input echo
  /// - no line buffering
  /// - modified primary colors on windows
  ///
  /// Colors are in the format accepted by `pancurses::init_color`
  #[expect(clippy::missing_panics_doc)]
  pub fn new (color_init : Option <&[[u8; 3]; 8]>) -> Self {
    log::trace!("new...");
    use easycurses::{CursorVisibility, InputMode};
    let easycurses = EasyCurses::initialize_system().unwrap();
    easycurses.win.keypad (true);                   // return special key codes
    let mut curses = Curses { easycurses };
    curses.set_cursor_visibility (CursorVisibility::Invisible); // hide cursor
    curses.set_echo (false);                        // no input echo
    curses.set_input_mode (InputMode::Character);   // no line buffering
    if let Some (colors) = color_init {
      if !pancurses::can_change_color() {
        log::warn!("curses color init: pancurses backend reports terminal can \
          not change color");
      } else {
        let init_color = |color_name| {
          #[expect(clippy::cast_possible_truncation)]
          const fn byte_to_milli_color (byte : u8) -> i16 {
            ((byte as f64 / 255.0) * 1000.0) as i16
          }
          let color = colors[color_name as usize];
          pancurses_ok!(pancurses::init_color (
            color_name as i16,
            byte_to_milli_color (color[0]),
            byte_to_milli_color (color[1]),
            byte_to_milli_color (color[2])
          ));
        };
        init_color (easycurses::Color::Black);
        init_color (easycurses::Color::Red);
        init_color (easycurses::Color::Green);
        init_color (easycurses::Color::Blue);
        init_color (easycurses::Color::Yellow);
        init_color (easycurses::Color::Magenta);
        init_color (easycurses::Color::Cyan);
        init_color (easycurses::Color::White);
      }
    }
    log::trace!("...new");
    curses
  }

  /// Get a reference to the underlying pancurses window
  #[inline]
  pub const fn win (&self) -> &pancurses::Window {
    &self.easycurses.win
  }

  /// Blocking getch
  #[inline]
  pub fn getch_wait (&mut self) -> Option <easycurses::Input> {
    use easycurses::{InputMode, TimeoutMode};
    self.set_input_mode (InputMode::Character);
    self.set_input_timeout (TimeoutMode::Never);
    self.get_input()
  }

  /// Block until timeout getch
  #[inline]
  pub fn getch_timeout (&mut self, timeout : u32) -> Option <easycurses::Input> {
    use easycurses::{InputMode, TimeoutMode};
    self.set_input_mode (InputMode::Character);
    debug_assert!(timeout <= i32::MAX as u32);
    #[expect(clippy::cast_possible_wrap)]
    self.set_input_timeout (TimeoutMode::WaitUpTo (timeout as i32));
    self.get_input()
  }

  /// Non-blocking getch
  #[inline]
  pub fn getch_nowait (&mut self) -> Option <easycurses::Input> {
    use easycurses::{InputMode, TimeoutMode};
    self.set_input_mode (InputMode::Character);
    self.set_input_timeout (TimeoutMode::Immediate);
    self.get_input()
  }

  /// Blocking getline
  #[inline]
  pub fn getline_wait (&mut self) -> Option <easycurses::Input> {
    use easycurses::{InputMode, TimeoutMode};
    self.set_input_mode (InputMode::Cooked);
    self.set_input_timeout (TimeoutMode::Never);
    self.get_input()
  }

  /// Non-blocking getline
  #[inline]
  pub fn getline_nowait (&mut self) -> Option <easycurses::Input> {
    use easycurses::{InputMode, TimeoutMode};
    self.set_input_mode (InputMode::Cooked);
    self.set_input_timeout (TimeoutMode::Immediate);
    self.get_input()
  }

  #[inline]
  pub fn rows (&self) -> i32 {
    self.win().get_max_y()
  }

  #[inline]
  pub fn columns (&self) -> i32 {
    self.win().get_max_x()
  }

  #[inline]
  pub fn dimensions_rc (&self) -> (i32, i32) {
    self.easycurses.get_row_col_count()
  }

  #[inline]
  pub fn center_col (&self) -> i32 {
    let (_, cols) = self.get_row_col_count();
    cols / 2
  }

  #[inline]
  pub fn center_row (&self) -> i32 {
    let (rows, _) = self.get_row_col_count();
    rows / 2
  }

  #[inline]
  pub fn center_rc (&self) -> (i32, i32) {
    let (rows, cols) = self.get_row_col_count();
    (rows / 2, cols / 2)
  }

  /// Returns the (row, col) of the upper left corner of the inserted text
  pub fn print_centered (&mut self,
    string     : &str,
    row_offset : Option <i32>,
    col_offset : Option <i32>
  ) -> (i32, i32) {
    let (longest, count) = string.lines().fold ((0,0),
      |(longest, count), next| {
        let next_len = next.len();
        (usize::max (longest, next_len), count+1)
      }
    );
    #[expect(clippy::cast_possible_truncation)]
    #[expect(clippy::cast_possible_wrap)]
    let half_longest = longest as i32 / 2;
    let half_count   = count / 2;
    let (center_row, center_col) = {
      let (row, col) = self.center_rc();
      (row + row_offset.unwrap_or (0), col + col_offset.unwrap_or (0))
    };
    for (i, line) in string.lines().enumerate() {
      #[expect(clippy::cast_possible_truncation)]
      #[expect(clippy::cast_possible_wrap)]
      let at_row = center_row - half_count + i as i32;
      let at_col = center_col - half_longest;
      // NOTE: move_rc returns false if the cursor is moved outside of the
      // window
      let _ = self.move_rc (at_row, at_col);
      // NOTE: print returns false if the cursor would be advanced past the end
      // of the window
      let _ = self.print (line);
    }
    (center_row - half_count, center_col - half_longest)
  }

  /// Draws a border with `pancurses::draw_bux()` using `ACS_VLINE` and
  /// `ACS_HLINE` (corners will be `ACS_*` corners as well).
  #[inline]
  #[must_use]
  pub fn draw_border_default (&mut self) -> PancursesResult {
    self.win().draw_box (pancurses::ACS_VLINE(), pancurses::ACS_HLINE())
  }

  /// Draw a box with min (upper left) and max (lower right) coordinates.
  ///
  /// *Note*: this is not like the ncurses 'box' function which draws a window
  /// border with matching top/bottom and left/right sides.
  #[must_use]
  pub fn draw_box (&mut self,
    ch     : pancurses::chtype,
    rc_min : (i32, i32),
    rc_max : (i32, i32)
  ) -> PancursesResult {
    let mut out = pancurses::OK;
    // this will return the first error and ignore all others
    let mut result_ok = |result| if out == pancurses::OK {
      out = result;
    };
    // take the min/max anyway in case they are not in the right order
    let (min_row, min_col) =
      (i32::min (rc_min.0, rc_max.0), i32::min (rc_min.1, rc_max.1));
    let (max_row, max_col) =
      (i32::max (rc_min.0, rc_max.0), i32::max (rc_min.1, rc_max.1));
    let rows = max_row - min_row + 1;
    let cols = max_col - min_col + 1;
    let _ = self.move_rc (min_row, min_col);
    result_ok (self.win().hline (ch, cols));
    let _ = self.move_rc (min_row, min_col);
    result_ok (self.win().vline (ch, rows));
    let _ = self.move_rc (max_row, min_col);
    result_ok (self.win().hline (ch, cols));
    let _ = self.move_rc (min_row, max_col);
    result_ok (self.win().vline (ch, rows));
    out
  }

  /// Draws a box with explicit top/sides and corners.
  ///
  /// This is like the ncurses `border()` function, except around sub-area of the window
  /// instead of the entire window.
  // TODO: create types for border params
  #[must_use]
  #[expect(clippy::too_many_arguments)]
  pub fn draw_border (&mut self,
    left             : pancurses::chtype,
    right            : pancurses::chtype,
    top              : pancurses::chtype,
    bottom           : pancurses::chtype,
    top_left         : pancurses::chtype,
    top_right        : pancurses::chtype,
    bottom_left      : pancurses::chtype,
    bottom_right     : pancurses::chtype,
    rc_min           : (i32, i32),
    rc_max           : (i32, i32),
    thickness_top    : u32,
    thickness_bottom : u32,
    thickness_left   : u32,
    thickness_right  : u32
  ) -> PancursesResult {
    let mut out = pancurses::OK;
    // this will return the first error and ignore all others
    let mut result_ok = |result| if out == pancurses::OK {
      out = result;
    };
    #[expect(clippy::cast_possible_wrap)]
    let (thickness_top, thickness_bottom, thickness_left, thickness_right) = (
      thickness_top    as i32,
      thickness_bottom as i32,
      thickness_left   as i32,
      thickness_right  as i32);
    // take the min/max anyway in case they are not in the right order
    let (min_row, min_col) =
      (i32::min (rc_min.0, rc_max.0), i32::min (rc_min.1, rc_max.1));
    let (max_row, max_col) =
      (i32::max (rc_min.0, rc_max.0), i32::max (rc_min.1, rc_max.1));
    let rows = max_row - min_row + 1;
    let cols = max_col - min_col + 1;
    let total_width  = thickness_left + thickness_right;
    let total_height = thickness_top  + thickness_bottom;
    for i in 0..thickness_top {
      let _ = self.move_rc (min_row + i, min_col);
      result_ok (self.win().hline (top_left, thickness_left));
      let _ = self.move_rc (min_row + i, min_col + thickness_left);
      result_ok (self.win().hline (top, cols - total_width));
      let _ = self.move_rc (min_row + i, min_col + cols - thickness_right);
      result_ok (self.win().hline (top_right, thickness_right));
    }
    for i in 0..thickness_bottom {
      let _ = self.move_rc (max_row - i, min_col);
      result_ok (self.win().hline (bottom_left, thickness_left));
      let _ = self.move_rc (max_row - i, min_col + thickness_left);
      result_ok (self.win().hline (bottom, cols - total_width));
      let _ = self.move_rc (max_row - i, min_col + cols - thickness_right);
      result_ok (self.win().hline (bottom_right, thickness_right));
    }
    for i in 0..thickness_left {
      let _ = self.move_rc (min_row + thickness_top, min_col + i);
      result_ok (self.win().vline (left, rows - total_height));
    }
    for i in 0..thickness_right {
      let _ = self.move_rc (min_row + thickness_top, max_col - i);
      result_ok (self.win().vline (right, rows - total_height));
    }
    out
  }

  /// Draws a filled rectangular box with the given characters.
  pub fn draw_rect (&mut self,
    border      : pancurses::chtype,
    fill        : pancurses::chtype,
    rc_min      : (i32, i32),
    rc_max      : (i32, i32),
    thickness_h : u32,        // thickness of top and bottom border
    thickness_v : u32         // thickness of left and right border
  ) {
    let mut out = pancurses::OK;
    // this will return the first error and ignore all others
    let mut result_ok = |result| if out == pancurses::OK {
      out = result;
    };
    // take the min/max anyway in case they are not in the right order
    let (min_row, min_col) =
      (i32::min (rc_min.0, rc_max.0), i32::min (rc_min.1, rc_max.1));
    let (max_row, max_col) =
      (i32::max (rc_min.0, rc_max.0), i32::max (rc_min.1, rc_max.1));
    let rows = max_row - min_row + 1;
    let cols = max_col - min_col + 1;
    for i in 0..rows {
      let _ = self.move_rc (min_row + i, min_col);
      result_ok (self.win().hline (fill, cols));
    }
    #[expect(clippy::cast_possible_wrap)]
    for i in 0..thickness_h as i32 {
      let _ = self.move_rc (min_row + i, min_col);
      result_ok (self.win().hline (border, cols));
      let _ = self.move_rc (max_row - i, min_col);
      result_ok (self.win().hline (border, cols));
    }
    #[expect(clippy::cast_possible_wrap)]
    for i in 0..thickness_v as i32 {
      let _ = self.move_rc (min_row, min_col + i);
      result_ok (self.win().vline (border, rows));
      let _ = self.move_rc (min_row, max_col - i);
      result_ok (self.win().vline (border, rows));
    }
  }

  /// Draw color image data using `chgat`
  #[expect(clippy::missing_panics_doc)]
  pub fn draw_image_color_pair (&mut self,
    at_rc : (i32, i32), image : &Mat <pancurses::ColorPair>
  ) {
    let mut row = 0;
    while row < image.height() {
      let mut col = 0;
      loop {
        let color = *image.get ((row, col).into()).unwrap();
        #[expect(clippy::cast_possible_truncation)]
        #[expect(clippy::cast_possible_wrap)]
        let start = col as i32;
        col += 1;
        while col < image.width()-1 {
          if color == *image.get ((row, col).into()).unwrap() {
            col += 1;
          } else {
            break
          }
        }
        // NOTE: returns -1 if start position is outside the window
        #[expect(clippy::cast_possible_truncation)]
        #[expect(clippy::cast_possible_wrap)]
        let _ = self.win().mvchgat (
          at_rc.0 + row   as i32,
          at_rc.1 + start,
          col as i32 - start,
          0x0, color.0 as i16);
        if col == image.width() {
          break
        }
      }
      row += 1;
    }
  }

  /// Draw chtype image data using `addch`
  #[expect(clippy::missing_panics_doc)]
  pub fn draw_image_chtype (&mut self,
    at_rc : (i32, i32), image : &Mat <pancurses::chtype>
  ) {
    let dimensions = image.dimensions();
    for row in 0..dimensions.rows {
      #[expect(clippy::cast_possible_truncation)]
      #[expect(clippy::cast_possible_wrap)]
      for col in 0..dimensions.columns {
        let ch = *image.get ((row, col).into()).unwrap();
        let at_row = at_rc.0 + row as i32;
        let at_col = at_rc.1 + col as i32;
        // NOTE: function returns -1 when adding character outside the window
        let _ = self.win().mvaddch (at_row, at_col, ch);
      }
    }
  }

  /// Logs some current curses (and terminal) attributes
  pub fn log_info (&self) {
    log::info!("log info...");
    log::info!("  cursor(row,col):     {:?}", self.get_cursor_rc());
    log::info!("  dimensions(row,col): {:?}", self.dimensions_rc());
    log::info!("  is color terminal:   {}",   self.is_color_terminal());
    log::info!("  can change color:    {}",   pancurses::can_change_color());
    log::info!("  maximum color pairs: {}",   pancurses::COLOR_PAIRS());
    log::info!("  maximum colors:      {}",   pancurses::COLORS());
    log::info!("  colors:");
    #[expect(clippy::cast_possible_truncation)]
    for i in 0..pancurses::COLORS() as i16 {
      let color_string = if let Some (color) = color_from_primitive (i) {
        format!("{color:?}")
      } else {
        i.to_string()
      };
      let rgb = pancurses::color_content (i);
      log::info!("    {color_string}: {rgb:?}");
    }
    log::info!("...log info");
  }
}

impl Default for Curses {
  /// Calls `Curses::new` with `None`
  fn default() -> Self {
    Curses::new (None)
  }
}

impl std::ops::Deref for Curses {
  type Target = EasyCurses;
  fn deref (&self) -> &EasyCurses {
    &self.easycurses
  }
}

impl std::ops::DerefMut for Curses {
  fn deref_mut (&mut self) -> &mut EasyCurses {
    &mut self.easycurses
  }
}

#[cfg(test)]
mod tests {
  //use super::*;
  #[test]
  fn color_from_primitive() {
    use super::color_from_primitive;
    for i in 0..8 {
      assert_eq!(i, color_from_primitive (i).unwrap() as i16);
    }
  }
}