This commit is contained in:
same mf who else 2026-03-21 17:35:31 +02:00
parent 5d627f7669
commit eb899906f9
8 changed files with 627 additions and 728 deletions

View file

@ -1,10 +1,11 @@
use crate::{*, lang::*, play::*, draw::{*, Split::*}, color::*, text::*};
use crate::{*, lang::*, play::*, draw::*, space::{*, Split::*}, color::*, text::*};
use unicode_width::{UnicodeWidthStr, UnicodeWidthChar};
use rand::distributions::uniform::UniformSampler;
use ::{
std::{
io::{stdout, Write},
time::Duration
time::Duration,
ops::{Deref, DerefMut},
},
better_panic::{Settings, Verbosity},
ratatui::{
@ -20,25 +21,36 @@ use ::{
event::{poll, read, Event, KeyEvent, KeyCode, KeyModifiers, KeyEventKind, KeyEventState},
}
};
pub struct Tui(pub Buffer, pub XYWH<u16>);
impl Screen for Tui { type Unit = u16; }
impl HasX<u16> for Tui { fn x (&self) -> X<u16> { self.1.x() } }
impl HasY<u16> for Tui { fn y (&self) -> Y<u16> { self.1.y() } }
impl HasW<u16> for Tui { fn w (&self) -> W<u16> { self.1.w() } }
impl HasH<u16> for Tui { fn h (&self) -> H<u16> { self.1.h() } }
impl Screen for Tui { type Unit = u16; }
impl Deref for Tui { type Target = Buffer; fn deref (&self) -> &Buffer { &self.0 } }
impl DerefMut for Tui { fn deref_mut (&mut self) -> &mut Buffer { &mut self.0 } }
impl HasOrigin for Tui { fn origin (&self) -> Origin { Origin::NW } }
impl AsRef<Buffer> for Tui { fn as_ref (&self) -> &Buffer { &self.0 } }
impl AsMut<Buffer> for Tui { fn as_mut (&mut self) -> &mut Buffer { &mut self.0 } }
impl AsRef<XYWH<u16>> for Tui { fn as_ref (&self) -> &XYWH<u16> { &self.0 } }
impl AsMut<XYWH<u16>> for Tui { fn as_mut (&mut self) -> &mut XYWH<u16> { &mut self.0 } }
impl X<u16> for Tui {
fn x (&self) -> u16 { self.1.0 }
fn w (&self) -> u16 { self.1.2 }
}
impl Y<u16> for Tui {
fn y (&self) -> u16 { self.1.1 }
fn h (&self) -> u16 { self.1.3 }
}
impl Tui {
fn update (&mut self, callback: &impl Fn(&mut Cell, u16, u16)) -> WH<u16> {
tui_update(self.0, self.1, callback);
self.1.wh()
fn update (&mut self, callback: &impl Fn(&mut Cell, u16, u16)) -> XYWH<u16> {
for row in 0..self.h() {
let y = self.y() + row;
for col in 0..self.w() {
let x = self.x() + col;
if x < self.0.area.width && y < self.0.area.height {
if let Some(cell) = self.0.cell_mut(Position { x, y }) {
callback(cell, col, row);
}
}
}
}
self.xywh()
}
fn tint_all (&mut self, fg: Color, bg: Color, modifier: Modifier) {
for cell in self.buffer().content.iter_mut() {
for cell in self.0.content.iter_mut() {
cell.fg = fg;
cell.bg = bg;
cell.modifier = modifier;
@ -47,9 +59,8 @@ impl Tui {
fn blit (&mut self, text: &impl AsRef<str>, x: u16, y: u16, style: Option<Style>) {
let text = text.as_ref();
let style = style.unwrap_or(Style::default());
let buf = self.buffer();
if x < buf.area.width && y < buf.area.height {
buf.set_string(x, y, text, style);
if x < self.0.area.width && y < self.0.area.height {
self.0.set_string(x, y, text, style);
}
}
}
@ -73,7 +84,7 @@ pub const fn fg_bg (fg: Color, bg: Color, draw: impl Draw<Tui>) -> impl Draw<Tui
draw.draw(to)
})
}
pub const fn fill_char (c: char) {
pub const fn fill_char (c: char) -> impl Draw<Tui> {
thunk(move|to: &mut Tui|Ok(to.update(&|cell,_,_|{
cell.set_char(c);
})))
@ -85,33 +96,31 @@ pub const fn modify (on: bool, modifier: Modifier, draw: impl Draw<Tui>) -> impl
draw.draw(to)
})
}
pub const fn fill_mod (on: bool, modifier: Modifier) {
thunk(move|to: &mut Tui|{
pub const fn fill_mod (on: bool, modifier: Modifier) -> impl Draw<Tui> {
thunk(move|to: &mut Tui|Ok({
if on {
to.update(&|cell,_,_|cell.modifier.insert(modifier))
} else {
to.update(&|cell,_,_|cell.modifier.remove(modifier))
}
})
}))
}
/// Draw contents with bold modifier applied.
pub const fn bold (on: bool, draw: impl Draw<Tui>) -> impl Draw<Tui> {
modify(on, Modifier::BOLD, draw)
}
pub const fn fill_ul (on: bool, color: Option<Color>) {
thunk(move|to: &mut Tui|{
if on {
to.update(&|cell,_,_|{
cell.modifier.insert(Modifier::UNDERLINED);
cell.underline_color = color;
})
} else {
to.update(&|cell,_,_|&|cell,_,_|{
cell.modifier.remove(Modifier::UNDERLINED);
cell.underline_color = Reset;
})
}
})
pub const fn fill_ul (color: Option<Color>) -> impl Draw<Tui> {
thunk(move|to: &mut Tui|Ok(if let Some(color) = color {
to.update(&|cell,_,_|{
cell.modifier.insert(Modifier::UNDERLINED);
cell.underline_color = color;
})
} else {
to.update(&|cell,_,_|{
cell.modifier.remove(Modifier::UNDERLINED);
cell.underline_color = Reset;
})
}))
}
/// TUI works in u16 coordinates.
@ -122,24 +131,24 @@ impl Coord for u16 {
}
impl Draw<Tui> for u64 {
fn draw (&self, _to: &mut Tui) -> Usually<WH<u16>> { todo!() }
fn draw (&self, _to: &mut Tui) -> Usually<XYWH<u16>> { todo!() }
}
impl Draw<Tui> for f64 {
fn draw (&self, _to: &mut Tui) -> Usually<WH<u16>> { todo!() }
fn draw (&self, _to: &mut Tui) -> Usually<XYWH<u16>> { todo!() }
}
impl Draw<Tui> for &str {
fn draw (&self, to: &mut Tui) -> Usually<WH<u16>> {
let XYWH(x, y, w, ..) = to.centered_xy([width_chars_max(to.w(), self), 1]);
fn draw (&self, to: &mut Tui) -> Usually<XYWH<u16>> {
let XYWH(x, y, w, ..) = to.1.centered_xy([width_chars_max(to.w(), self), 1]);
to.text(&self, x, y, w)
}
}
impl Draw<Tui> for String {
fn draw (&self, to: &mut Tui) -> Usually<WH<u16>> {
fn draw (&self, to: &mut Tui) -> Usually<XYWH<u16>> {
self.as_str().draw(to)
}
}
impl Draw<Tui> for Arc<str> {
fn draw (&self, to: &mut Tui) -> Usually<WH<u16>> {
fn draw (&self, to: &mut Tui) -> Usually<XYWH<u16>> {
self.as_ref().draw(to)
}
}
@ -150,11 +159,11 @@ mod phat {
pub const HI: &'static str = "";
/// A phat line
pub fn lo (fg: Color, bg: Color) -> impl Draw<Tui> {
H::exact(1, fg_bg(fg, bg, x_repeat(self::phat::LO)))
h_exact(1, fg_bg(fg, bg, x_repeat(self::phat::LO)))
}
/// A phat line
pub fn hi (fg: Color, bg: Color) -> impl Draw<Tui> {
H::exact(1, fg_bg(fg, bg, x_repeat(self::phat::HI)))
h_exact(1, fg_bg(fg, bg, x_repeat(self::phat::HI)))
}
}
@ -173,7 +182,7 @@ pub const fn x_repeat (c: &str) -> impl Draw<Tui> {
cell.set_symbol(&c);
}
}
Ok(WH(w, 1))
Ok(XYWH(x, y, w, 1))
})
}
@ -185,7 +194,7 @@ pub const fn y_repeat (c: &str) -> impl Draw<Tui> {
cell.set_symbol(&c);
}
}
Ok(WH(1, h))
Ok(XYWH(x, y, 1, h))
})
}
@ -201,7 +210,7 @@ pub const fn xy_repeat (c: &str) -> impl Draw<Tui> {
}
}
}
Ok(WH(w, h))
Ok(XYWH(x, y, w, h))
})
}
@ -252,8 +261,8 @@ macro_rules! border {
#[derive(Copy, Clone)] pub struct $T(pub bool, pub Style);
//impl Layout<Tui> for $T {}
impl Draw<Tui> for $T {
fn draw (&self, to: &mut Tui) -> Usually<WH<u16>> {
when(self.enabled(), |to: &mut Tui|BorderStyle::draw(self, to)).draw(to)
fn draw (&self, to: &mut Tui) -> Usually<XYWH<u16>> {
when(self.enabled(), thunk(|to: &mut Tui|BorderStyle::draw(self, to))).draw(to)
}
}
)+}
@ -376,36 +385,26 @@ pub trait BorderStyle: Draw<Tui> + Copy {
fn border_sw (&self) -> &str { Self::SW }
fn border_se (&self) -> &str { Self::SE }
fn enclose (self, w: impl Draw<Tui>) -> impl Draw<Tui> {
below(WH::fill(border(self.enabled(), self)), w)
}
fn enclose2 (self, w: impl Draw<Tui>) -> impl Draw<Tui> {
below(WH::pad(1, 1, WH::fill(border(self.enabled(), self))), w)
}
fn enclose_bg (self, w: impl Draw<Tui>) -> impl Draw<Tui> {
Tui::bg(self.style().unwrap().bg.unwrap_or(Color::Reset),
below(WH::fill(border(self.enabled(), self)), w))
}
#[inline] fn draw <'a> (&self, to: &mut impl Draw<Tui>) -> Usually<()> {
#[inline] fn draw <'a> (&self, to: &mut Tui) -> Usually<XYWH<u16>> {
if self.enabled() {
self.draw_h(to, None)?;
self.draw_v(to, None)?;
self.draw_c(to, None)?;
}
Ok(())
Ok(to.1)
}
#[inline] fn draw_h (&self, to: &mut impl Draw<Tui>, style: Option<Style>) -> Usually<XYWH<u16>> {
let area = to.area();
#[inline] fn draw_h (&self, to: &mut Tui, style: Option<Style>) -> Usually<XYWH<u16>> {
let style = style.or_else(||self.style_horizontal());
let [x, x2, y, y2] = area.lrtb();
for x in x..x2.saturating_sub(1) {
to.blit(&Self::N, x, y, style);
to.blit(&Self::S, x, y2.saturating_sub(1), style)
let y1 = to.y_north();
let y2 = to.y_south().saturating_sub(1);
for x in to.x_west()..to.x_east().saturating_sub(1) {
to.blit(&Self::N, x, y1, style);
to.blit(&Self::S, x, y2, style)
}
Ok(area)
Ok(to.xywh())
}
#[inline] fn draw_v (&self, to: &mut impl Draw<Tui>, style: Option<Style>) -> Usually<XYWH<u16>> {
let area = to.area();
#[inline] fn draw_v (&self, to: &mut Tui, style: Option<Style>) -> Usually<XYWH<u16>> {
let area = to.1;
let style = style.or_else(||self.style_vertical());
let [x, x2, y, y2] = area.lrtb();
let h = y2 - y;
@ -420,8 +419,8 @@ pub trait BorderStyle: Draw<Tui> + Copy {
}
Ok(area)
}
#[inline] fn draw_c (&self, to: &mut impl Draw<Tui>, style: Option<Style>) -> Usually<XYWH<u16>> {
let area = to.area();
#[inline] fn draw_c (&self, to: &mut Tui, style: Option<Style>) -> Usually<XYWH<u16>> {
let area = to.1;
let style = style.or_else(||self.style_corners());
let XYWH(x, y, w, h) = area;
if w > 1 && h > 1 {
@ -457,28 +456,26 @@ pub trait BorderStyle: Draw<Tui> + Copy {
/// ```
/// /// TODO
/// ```
pub fn phat <T, N: Coord> (w: N, h: N, [fg, bg, hi, lo]: [Color;4], draw: impl Draw<Tui>) -> impl Draw<Tui> {
let top = W::exact(1, self::phat::lo(bg, hi));
let low = W::exact(1, self::phat::hi(bg, lo));
pub fn phat (w: u16, h: u16, [fg, bg, hi, lo]: [Color;4], draw: impl Draw<Tui>) -> impl Draw<Tui> {
let top = w_exact(1, self::phat::lo(bg, hi));
let low = w_exact(1, self::phat::hi(bg, lo));
let draw = fg_bg(fg, bg, draw);
WH::min(w, h, south(top, north(low, WH::fill(draw))))
wh_min(Some(w), Some(h), south(top, north(low, draw)))
}
fn x_scroll () {
|to: &mut Tui|{
let XYWH(x1, y1, w, h) = to.area();
let mut buf = to.buffer.write().unwrap();
let x2 = x1 + w;
for (i, x) in (x1..=x2).enumerate() {
if let Some(cell) = buf.cell_mut(Position::from((x, y1))) {
fn x_scroll () -> impl Draw<Tui> {
thunk(|Tui(buf, XYWH(x1, y1, w, h)): &mut Tui|{
let x2 = *x1 + *w;
for (i, x) in (*x1..=x2).enumerate() {
if let Some(cell) = buf.cell_mut(Position::from((x, *y1))) {
if i < (self::scroll::ICON_DEC_H.len()) {
cell.set_fg(Rgb(255, 255, 255));
cell.set_bg(Rgb(0, 0, 0));
cell.set_char(self::scroll::ICON_DEC_H[i as usize]);
} else if i > (w as usize - self::scroll::ICON_INC_H.len()) {
} else if i > (*w as usize - self::scroll::ICON_INC_H.len()) {
cell.set_fg(Rgb(255, 255, 255));
cell.set_bg(Rgb(0, 0, 0));
cell.set_char(self::scroll::ICON_INC_H[w as usize - i]);
cell.set_char(self::scroll::ICON_INC_H[*w as usize - i]);
} else if false {
cell.set_fg(Rgb(255, 255, 255));
cell.set_bg(Reset);
@ -490,24 +487,23 @@ fn x_scroll () {
}
}
}
}
Ok(XYWH(*x1, *y1, *w, 1))
})
}
fn y_scroll () {
|to: &mut Tui|{
let XYWH(x1, y1, w, h) = to.area();
let mut buf = to.buffer.write().unwrap();
let y2 = y1 + h;
for (i, y) in (y1..=y2).enumerate() {
if let Some(cell) = buf.cell_mut(Position::from((x1, y))) {
fn y_scroll () -> impl Draw<Tui> {
thunk(|Tui(buf, XYWH(x1, y1, w, h)): &mut Tui|{
let y2 = *y1 + *h;
for (i, y) in (*y1..=y2).enumerate() {
if let Some(cell) = buf.cell_mut(Position::from((*x1, y))) {
if (i as usize) < (self::scroll::ICON_DEC_V.len()) {
cell.set_fg(Rgb(255, 255, 255));
cell.set_bg(Rgb(0, 0, 0));
cell.set_char(self::scroll::ICON_DEC_V[i as usize]);
} else if (i as usize) > (h as usize - self::scroll::ICON_INC_V.len()) {
} else if (i as usize) > (*h as usize - self::scroll::ICON_INC_V.len()) {
cell.set_fg(Rgb(255, 255, 255));
cell.set_bg(Rgb(0, 0, 0));
cell.set_char(self::scroll::ICON_INC_V[h as usize - i]);
cell.set_char(self::scroll::ICON_INC_V[*h as usize - i]);
} else if false {
cell.set_fg(Rgb(255, 255, 255));
cell.set_bg(Reset);
@ -519,11 +515,12 @@ fn y_scroll () {
}
}
}
}
Ok(XYWH(*x1, *y1, 1, *h))
})
}
/// Spawn the TUI output thread which writes colored characters to the terminal.
pub fn tui_output <W: Write, T: Draw<Tui> + Send + Sync + 'static> (
pub fn tui_output <W: Write + Send + Sync, T: Draw<Tui> + Send + Sync + 'static> (
output: W,
exited: &Arc<AtomicBool>,
state: &Arc<RwLock<T>>,
@ -532,11 +529,11 @@ pub fn tui_output <W: Write, T: Draw<Tui> + Send + Sync + 'static> (
let state = state.clone();
tui_setup(&mut output)?;
let mut backend = CrosstermBackend::new(output);
let WH(width, height) = tui_wh(&mut backend);
let Size { width, height } = backend.size().expect("get size failed");
let mut buffer_a = Buffer::empty(Rect { x: 0, y: 0, width, height });
let mut buffer_b = Buffer::empty(Rect { x: 0, y: 0, width, height });
Thread::new_sleep(exited.clone(), sleep, move |perf| {
let size = tui_wh(&mut backend);
let size = backend.size().expect("get size failed");
if let Ok(state) = state.try_read() {
tui_resize(&mut backend, &mut buffer_a, size);
buffer_a = tui_redraw(&mut backend, &mut buffer_a, &mut buffer_b);
@ -546,7 +543,7 @@ pub fn tui_output <W: Write, T: Draw<Tui> + Send + Sync + 'static> (
})
}
pub fn tui_setup (output: &mut impl Write) -> Usually<()> {
pub fn tui_setup <T: Write + Send + Sync> (output: &mut T) -> Usually<()> {
let better_panic_handler = Settings::auto().verbosity(Verbosity::Full).create_panic_handler();
std::panic::set_hook(Box::new(move |info: &std::panic::PanicHookInfo|{
output.execute(LeaveAlternateScreen).unwrap();
@ -561,10 +558,10 @@ pub fn tui_setup (output: &mut impl Write) -> Usually<()> {
pub fn tui_resize <W: Write> (
backend: &mut CrosstermBackend<W>,
buffer: &mut Tui,
size: WH<u16>
buffer: &mut Buffer,
size: XYWH<u16>
) {
if buffer.area != size {
if buffer.1 != size {
backend.clear_region(ClearType::All).unwrap();
buffer.resize(size);
buffer.reset();
@ -591,24 +588,8 @@ pub fn tui_teardown <W: Write> (backend: &mut CrosstermBackend<W>) -> Usually<()
}
pub fn tui_update (
buf: &mut Tui, area: XYWH<u16>, callback: &impl Fn(&mut Cell, u16, u16)
Tui(buf, ..): &mut Tui, area: XYWH<u16>, callback: &impl Fn(&mut Cell, u16, u16)
) {
for row in 0..area.h().0 {
let y = area.y().0 + row;
for col in 0..area.w().0 {
let x = area.x() + col;
if x < buf.area.width && y < buf.area.height {
if let Some(cell) = buf.cell_mut(Position { x, y }) {
callback(cell, col, row);
}
}
}
}
}
pub(crate) fn tui_wh <W: Write> (backend: &mut CrosstermBackend<W>) -> WH<u16> {
let Size { width, height } = backend.size().expect("get size failed");
WH(width, height)
}
/// Draw border around shrinked item.
@ -617,25 +598,26 @@ pub(crate) fn tui_wh <W: Write> (backend: &mut CrosstermBackend<W>) -> WH<u16> {
/// /// TODO
/// ```
pub const fn border <T, S: BorderStyle> (on: bool, style: S, draw: impl Draw<Tui>) -> impl Draw<Tui> {
let content = pad(Some(1), Some(1), draw);
let outline = when(on, |to: &mut Tui|{
let area = to.area();
if area.w() > 0 && area.y() > 0 {
to.blit(&style.border_nw(), area.x(), area.y(), style.style());
to.blit(&style.border_ne(), area.x() + area.w() - 1, area.y(), style.style());
to.blit(&style.border_sw(), area.x(), area.y() + area.h() - 1, style.style());
to.blit(&style.border_se(), area.x() + area.w() - 1, area.y() + area.h() - 1, style.style());
for x in area.x()+1..area.x()+area.w()-1 {
to.blit(&style.border_n(), x, area.y(), style.style());
to.blit(&style.border_s(), x, area.y() + area.h() - 1, style.style());
let content = wh_pad(1, 1, draw);
let outline = when(on, thunk(move|to: &mut Tui|{
let XYWH(x, y, w, h) = to.1;
if w > 0 && h > 0 {
to.blit(&style.border_nw(), x, y, style.style());
to.blit(&style.border_ne(), x + w - 1, y, style.style());
to.blit(&style.border_sw(), x, y + h - 1, style.style());
to.blit(&style.border_se(), x + w - 1, y + h - 1, style.style());
for x in x+1..x+w-1 {
to.blit(&style.border_n(), x, y, style.style());
to.blit(&style.border_s(), x, y + h - 1, style.style());
}
for y in area.y()+1..area.y()+area.h()-1 {
to.blit(&style.border_w(), area.x(), y, style.style());
to.blit(&style.border_e(), area.x() + area.w() - 1, y, style.style());
for y in y+1..y+h-1 {
to.blit(&style.border_w(), x, y, style.style());
to.blit(&style.border_e(), x + w - 1, y, style.style());
}
}
});
Above.split(outline, content)
Ok(XYWH(x, y, w, h))
}));
above(outline, content)
}
/// Draw TUI content or its error message.
@ -645,16 +627,15 @@ pub const fn border <T, S: BorderStyle> (on: bool, style: S, draw: impl Draw<Tui
/// let _ = tengri::tui::catcher(Ok(None));
/// let _ = tengri::tui::catcher(Err("draw fail".into()));
/// ```
pub fn catcher <T, E> (error: Usually<E>, draw: impl Draw<Tui>) -> impl Draw<Tui> {
thunk(move|to: &mut Tui|match error.as_ref() {
Ok(Some(content)) => draw(to),
Ok(None) => to.blit(&"<empty>", 0, 0, Some(Style::default().yellow())),
pub fn catcher <T: Draw<Tui>> (result: Usually<T>) -> impl Draw<Tui> {
thunk(move|to: &mut Tui|match result.as_ref() {
Ok(content) => content.draw(to),
Err(e) => {
let err_fg = rgb(255,224,244);
let err_bg = rgb(96, 24, 24);
let err_fg = Color::Rgb(255,224,244);
let err_bg = Color::Rgb(96, 24, 24);
let title = east(bold(true, "upsi daisy. "), "rendering failed.");
let error = east("\"why?\" ", bold(true, format!("{e}")));
&fg(err_fg, bg(err_bg, south(title, error)))(to)
fg(err_fg, bg(err_bg, south(title, error))).draw(to)
}
})
}
@ -730,8 +711,8 @@ pub fn tui_input <T: Do<TuiEvent, T> + Send + Sync + 'static> (
// Handle all other events by the state:
_ => {
let event = TuiEvent::from_crossterm(event);
if let Err(e) = state.write().unwrap().handle(&event) {
let event = TuiEvent(TuiKey::from_crossterm(event));
if let Err(e) = state.write().unwrap().apply(&event) {
panic!("{e}")
}
}
@ -742,17 +723,8 @@ pub fn tui_input <T: Do<TuiEvent, T> + Send + Sync + 'static> (
/// TUI input loop event.
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd)]
pub struct TuiEvent(pub Event);
impl_from!(TuiEvent: |e: Event| TuiEvent(e));
impl_from!(TuiEvent: |c: char| TuiEvent(Event::Key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE))));
impl TuiEvent {
#[cfg(feature = "lang")]
pub fn from_dsl (dsl: impl Language) -> Usually<Self> {
Ok(TuiKey::from_dsl(dsl)?.to_crossterm().map(Self))
}
}
impl Ord for TuiEvent {
fn cmp (&self, other: &Self) -> std::cmp::Ordering {
self.partial_cmp(other)
@ -763,11 +735,8 @@ impl Ord for TuiEvent {
/// TUI key spec.
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd)]
pub struct TuiKey(pub Option<KeyCode>, pub KeyModifiers);
impl TuiKey {
const SPLIT: char = '/';
pub fn to_crossterm (&self) -> Option<Event> {
self.0.map(|code|Event::Key(KeyEvent {
code,
@ -776,7 +745,6 @@ impl TuiKey {
state: KeyEventState::NONE,
}))
}
pub fn named (token: &str) -> Option<KeyCode> {
use KeyCode::*;
Some(match token {
@ -820,5 +788,4 @@ impl TuiKey {
_ => return None,
})
}
}