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
#![cfg(not(target_arch = "wasm32"))]

//! A very basic terminal interaction lib (windows / unix).

use core::fmt::Write;

use tinyvec::*;

#[cfg(feature = "bytemuck")]
use bytemuck::*;

use chlorine::pick;
pick! {
  if #[cfg(windows)] {
    mod windows;
    use windows as sys;
    type SysTerm = sys::WindowsTerminal;
  } else if #[cfg(unix)] {
    mod unix;
    use unix as sys;
    type SysTerm = sys::UnixTerminal;
  } else {
    compile_error!("This crate doesn't support this system.");
  }
}

macro_rules! csi {
  ($s:literal) => {
    concat!("\x1B[", $s)
  };
}

pub const ESC: u8 = 0x1B;
pub const CTRL_Q: u8 = ctrl_key(b'q');
pub const CTRL_C: u8 = ctrl_key(b'c');

/// Converts a letter byte into the byte for that Control key.
///
/// eg: ctrl_key(b'c') -> 3_u8
pub const fn ctrl_key(b: u8) -> u8 {
  b & 0b0001_1111
}

#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct WinSize {
  pub rows: u16,
  pub cols: u16,
}
#[cfg(feature = "bytemuck")]
unsafe impl Zeroable for WinSize {}
#[cfg(feature = "bytemuck")]
unsafe impl Pod for WinSize {}

#[derive(Debug, Clone, Copy)]
pub enum Key {
  Lit(u8),
  F(u8),
  Escape,
  Tab,
  Enter,
  ArrowLeft,
  ArrowUp,
  ArrowRight,
  ArrowDown,
  Home,
  End,
  Insert,
  Delete,
  Backspace,
  PageUp,
  PageDown,
  Keypad5,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Mods(pub u8);
#[allow(bad_style)]
impl Mods {
  pub const None: Mods = Mods(0);
  pub const Meta: Mods = Mods(0b1000);
  pub const Ctrl: Mods = Mods(0b0100);
  pub const Alt: Mods = Mods(0b0010);
  pub const Shift: Mods = Mods(0b0001);
}
impl core::fmt::Debug for Mods {
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    if self.0 == Self::None.0 {
      write!(f, "None")
    } else {
      if self.0 & Self::Meta.0 > 0 {
        write!(f, "Meta,")?;
      }
      if self.0 & Self::Ctrl.0 > 0 {
        write!(f, "Ctrl,")?;
      }
      if self.0 & Self::Alt.0 > 0 {
        write!(f, "Alt,")?;
      }
      if self.0 & Self::Shift.0 > 0 {
        write!(f, "Shift,")?;
      }
      Ok(())
    }
  }
}

#[derive(Debug, Clone, Copy)]
pub enum TermEvent {
  Resize { rows: u16, cols: u16 },
  Key { val: Key, mods: Mods },
  Weirdness { buf: ArrayVec<[u8; 8]> },
}

#[repr(transparent)]
pub struct Terminal(SysTerm);

impl Terminal {
  #[allow(clippy::new_without_default)]
  pub fn new() -> Self {
    Self(SysTerm::new())
  }

  pub fn flush(&mut self) -> std::io::Result<()> {
    self.0.flush()
  }

  pub fn poll_events(&mut self) -> Result<Option<TermEvent>, i32> {
    self.0.poll_events()
  }

  pub fn cursor_forward(&mut self, count: u16) -> Result<(), core::fmt::Error> {
    write!(self, "\x1B[{}C", count)
  }
  pub fn cursor_back(&mut self, count: u16) -> Result<(), core::fmt::Error> {
    write!(self, "\x1B[{}D", count)
  }
  pub fn clear_to_end_of_line(&mut self) -> Result<(), core::fmt::Error> {
    write!(self, csi!("K"))
  }
}

impl core::fmt::Write for Terminal {
  fn write_str(&mut self, s: &str) -> Result<(), core::fmt::Error> {
    self.0.write_str(s)
  }
}