group tui_engine and tui_content; cargo update

This commit is contained in:
🪞👃🪞 2025-03-16 23:33:27 +02:00
parent 877b344765
commit 71dead5150
13 changed files with 150 additions and 72 deletions

View file

@ -0,0 +1,306 @@
use crate::*;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FocusState<T: Copy + Debug + PartialEq> {
Focused(T),
Entered(T),
}
impl<T: Copy + Debug + PartialEq> FocusState<T> {
pub fn inner (&self) -> T {
match self {
Self::Focused(inner) => *inner,
Self::Entered(inner) => *inner,
}
}
pub fn set_inner (&mut self, inner: T) {
*self = match self {
Self::Focused(_) => Self::Focused(inner),
Self::Entered(_) => Self::Entered(inner),
}
}
pub fn is_focused (&self) -> bool { matches!(self, Self::Focused(_)) }
pub fn is_entered (&self) -> bool { matches!(self, Self::Entered(_)) }
pub fn focus (&mut self) { *self = Self::Focused(self.inner()) }
pub fn enter (&mut self) { *self = Self::Entered(self.inner()) }
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum FocusCommand<T: Send + Sync> {
Up,
Down,
Left,
Right,
Next,
Prev,
Enter,
Exit,
Set(T)
}
impl<F: HasFocus + HasEnter + FocusGrid + FocusOrder> Command<F> for FocusCommand<F::Item> {
fn execute (self, state: &mut F) -> Perhaps<FocusCommand<F::Item>> {
match self {
Self::Next => { state.focus_next(); },
Self::Prev => { state.focus_prev(); },
Self::Up => { state.focus_up(); },
Self::Down => { state.focus_down(); },
Self::Left => { state.focus_left(); },
Self::Right => { state.focus_right(); },
Self::Enter => { state.focus_enter(); },
Self::Exit => { state.focus_exit(); },
Self::Set(to) => { state.set_focused(to); },
}
Ok(None)
}
}
/// Trait for things that have focusable subparts.
pub trait HasFocus {
type Item: Copy + PartialEq + Debug + Send + Sync;
/// Get the currently focused item.
fn focused (&self) -> Self::Item;
/// Get the currently focused item.
fn set_focused (&mut self, to: Self::Item);
/// Loop forward until a specific item is focused.
fn focus_to (&mut self, to: Self::Item) {
self.set_focused(to);
self.focus_updated();
}
/// Run this on focus update
fn focus_updated (&mut self) {}
}
/// Trait for things that have enterable subparts.
pub trait HasEnter: HasFocus {
/// Get the currently focused item.
fn entered (&self) -> bool;
/// Get the currently focused item.
fn set_entered (&mut self, entered: bool);
/// Enter into the currently focused component
fn focus_enter (&mut self) {
self.set_entered(true);
self.focus_updated();
}
/// Exit the currently entered component
fn focus_exit (&mut self) {
self.set_entered(false);
self.focus_updated();
}
}
/// Trait for things that implement directional navigation between focusable elements.
pub trait FocusGrid: HasFocus {
fn focus_layout (&self) -> &[&[Self::Item]];
fn focus_cursor (&self) -> (usize, usize);
fn focus_cursor_mut (&mut self) -> &mut (usize, usize);
fn focus_current (&self) -> Self::Item {
let (x, y) = self.focus_cursor();
self.focus_layout()[y][x]
}
fn focus_update (&mut self) {
self.focus_to(self.focus_current());
self.focus_updated()
}
fn focus_up (&mut self) {
let original_focused = self.focused();
let (_, original_y) = self.focus_cursor();
loop {
let (x, y) = self.focus_cursor();
let next_y = if y == 0 {
self.focus_layout().len().saturating_sub(1)
} else {
y - 1
};
if next_y == original_y {
break
}
let next_x = if self.focus_layout()[y].len() == self.focus_layout()[next_y].len() {
x
} else {
((x as f32 / self.focus_layout()[original_y].len() as f32)
* self.focus_layout()[next_y].len() as f32) as usize
};
*self.focus_cursor_mut() = (next_x, next_y);
if self.focus_current() != original_focused {
break
}
}
self.focus_update();
}
fn focus_down (&mut self) {
let original_focused = self.focused();
let (_, original_y) = self.focus_cursor();
loop {
let (x, y) = self.focus_cursor();
let next_y = if y >= self.focus_layout().len().saturating_sub(1) {
0
} else {
y + 1
};
if next_y == original_y {
break
}
let next_x = if self.focus_layout()[y].len() == self.focus_layout()[next_y].len() {
x
} else {
((x as f32 / self.focus_layout()[original_y].len() as f32)
* self.focus_layout()[next_y].len() as f32) as usize
};
*self.focus_cursor_mut() = (next_x, next_y);
if self.focus_current() != original_focused {
break
}
}
self.focus_update();
}
fn focus_left (&mut self) {
let original_focused = self.focused();
let (original_x, y) = self.focus_cursor();
loop {
let x = self.focus_cursor().0;
let next_x = if x == 0 {
self.focus_layout()[y].len().saturating_sub(1)
} else {
x - 1
};
if next_x == original_x {
break
}
*self.focus_cursor_mut() = (next_x, y);
if self.focus_current() != original_focused {
break
}
}
self.focus_update();
}
fn focus_right (&mut self) {
let original_focused = self.focused();
let (original_x, y) = self.focus_cursor();
loop {
let x = self.focus_cursor().0;
let next_x = if x >= self.focus_layout()[y].len().saturating_sub(1) {
0
} else {
x + 1
};
if next_x == original_x {
break
}
self.focus_cursor_mut().0 = next_x;
if self.focus_current() != original_focused {
break
}
}
self.focus_update();
}
}
/// Trait for things that implement next/prev navigation between focusable elements.
pub trait FocusOrder {
/// Focus the next item.
fn focus_next (&mut self);
/// Focus the previous item.
fn focus_prev (&mut self);
}
/// Next/prev navigation for directional focusables works in the given way.
impl<T: FocusGrid + HasEnter> FocusOrder for T {
/// Focus the next item.
fn focus_next (&mut self) {
let current = self.focused();
let (x, y) = self.focus_cursor();
if x < self.focus_layout()[y].len().saturating_sub(1) {
self.focus_right();
} else {
self.focus_down();
self.focus_cursor_mut().0 = 0;
}
if self.focused() == current { // FIXME: prevent infinite loop
self.focus_next()
}
self.focus_exit();
self.focus_update();
}
/// Focus the previous item.
fn focus_prev (&mut self) {
let current = self.focused();
let (x, _) = self.focus_cursor();
if x > 0 {
self.focus_left();
} else {
self.focus_up();
let (_, y) = self.focus_cursor();
let next_x = self.focus_layout()[y].len().saturating_sub(1);
self.focus_cursor_mut().0 = next_x;
}
if self.focused() == current { // FIXME: prevent infinite loop
self.focus_prev()
}
self.focus_exit();
self.focus_update();
}
}
pub trait FocusWrap<T> {
fn wrap <W: Content<TuiOut>> (self, focus: T, content: &'_ W) -> impl Content<TuiOut> + '_;
}
pub fn to_focus_command <T: Send + Sync> (input: &TuiIn) -> Option<FocusCommand<T>> {
Some(match input.event() {
kpat!(Tab) => FocusCommand::Next,
kpat!(Shift-Tab) => FocusCommand::Prev,
kpat!(BackTab) => FocusCommand::Prev,
kpat!(Shift-BackTab) => FocusCommand::Prev,
kpat!(Up) => FocusCommand::Up,
kpat!(Down) => FocusCommand::Down,
kpat!(Left) => FocusCommand::Left,
kpat!(Right) => FocusCommand::Right,
kpat!(Enter) => FocusCommand::Enter,
kpat!(Esc) => FocusCommand::Exit,
_ => return None
})
}
#[macro_export] macro_rules! impl_focus {
($Struct:ident $Focus:ident $Grid:expr $(=> [$self:ident : $update_focus:expr])?) => {
impl HasFocus for $Struct {
type Item = $Focus;
/// Get the currently focused item.
fn focused (&self) -> Self::Item {
self.focus.inner()
}
/// Get the currently focused item.
fn set_focused (&mut self, to: Self::Item) {
self.focus.set_inner(to)
}
$(fn focus_updated (&mut $self) { $update_focus })?
}
impl HasEnter for $Struct {
/// Get the currently focused item.
fn entered (&self) -> bool {
self.focus.is_entered()
}
/// Get the currently focused item.
fn set_entered (&mut self, entered: bool) {
if entered {
self.focus.to_entered()
} else {
self.focus.to_focused()
}
}
}
impl FocusGrid for $Struct {
fn focus_cursor (&self) -> (usize, usize) {
self.cursor
}
fn focus_cursor_mut (&mut self) -> &mut (usize, usize) {
&mut self.cursor
}
fn focus_layout (&self) -> &[&[$Focus]] {
use $Focus::*;
&$Grid
}
}
}
}

View file

@ -0,0 +1,63 @@
use crate::*;
pub struct MenuBar<E: Engine, S, C: Command<S>> {
pub menus: Vec<Menu<E, S, C>>,
pub index: usize,
}
impl<E: Engine, S, C: Command<S>> MenuBar<E, S, C> {
pub fn new () -> Self { Self { menus: vec![], index: 0 } }
pub fn add (mut self, menu: Menu<E, S, C>) -> Self {
self.menus.push(menu);
self
}
}
pub struct Menu<E: Engine, S, C: Command<S>> {
pub title: Arc<str>,
pub items: Vec<MenuItem<E, S, C>>,
pub index: Option<usize>,
}
impl<E: Engine, S, C: Command<S>> Menu<E, S, C> {
pub fn new (title: impl AsRef<str>) -> Self {
Self {
title: title.as_ref().to_string(),
items: vec![],
index: None,
}
}
pub fn add (mut self, item: MenuItem<E, S, C>) -> Self {
self.items.push(item);
self
}
pub fn sep (mut self) -> Self {
self.items.push(MenuItem::sep());
self
}
pub fn cmd (mut self, hotkey: &'static str, text: &'static str, command: C) -> Self {
self.items.push(MenuItem::cmd(hotkey, text, command));
self
}
pub fn off (mut self, hotkey: &'static str, text: &'static str) -> Self {
self.items.push(MenuItem::off(hotkey, text));
self
}
}
pub enum MenuItem<E: Engine, S, C: Command<S>> {
/// Unused.
__(PhantomData<E>, PhantomData<S>),
/// A separator. Skip it.
Separator,
/// A menu item with command, description and hotkey.
Command(&'static str, &'static str, C),
/// A menu item that can't be activated but has description and hotkey
Disabled(&'static str, &'static str)
}
impl<E: Engine, S, C: Command<S>> MenuItem<E, S, C> {
pub fn sep () -> Self {
Self::Separator
}
pub fn cmd (hotkey: &'static str, text: &'static str, command: C) -> Self {
Self::Command(hotkey, text, command)
}
pub fn off (hotkey: &'static str, text: &'static str) -> Self {
Self::Disabled(hotkey, text)
}
}

View file

@ -0,0 +1,175 @@
use crate::*;
use rand::{thread_rng, distributions::uniform::UniformSampler};
impl Tui {
pub const fn null () -> Color { Color::Reset }
pub const fn g (g: u8) -> Color { Color::Rgb(g, g, g) }
pub const fn red () -> Color { Color::Rgb(255,0, 0) }
pub const fn orange () -> Color { Color::Rgb(255,128,0) }
pub const fn yellow () -> Color { Color::Rgb(255,255,0) }
pub const fn brown () -> Color { Color::Rgb(128,255,0) }
pub const fn green () -> Color { Color::Rgb(0,255,0) }
pub const fn electric () -> Color { Color::Rgb(0,255,128) }
//fn bg0 () -> Color { Color::Rgb(20, 20, 20) }
//fn bg () -> Color { Color::Rgb(28, 35, 25) }
//fn border_bg () -> Color { Color::Rgb(40, 50, 30) }
//fn border_fg (f: bool) -> Color { if f { Self::bo1() } else { Self::bo2() } }
//fn title_fg (f: bool) -> Color { if f { Self::ti1() } else { Self::ti2() } }
//fn separator_fg (_: bool) -> Color { Color::Rgb(0, 0, 0) }
//fn mode_bg () -> Color { Color::Rgb(150, 160, 90) }
//fn mode_fg () -> Color { Color::Rgb(255, 255, 255) }
//fn status_bar_bg () -> Color { Color::Rgb(28, 35, 25) }
//fn bo1 () -> Color { Color::Rgb(100, 110, 40) }
//fn bo2 () -> Color { Color::Rgb(70, 80, 50) }
//fn ti1 () -> Color { Color::Rgb(150, 160, 90) }
//fn ti2 () -> Color { Color::Rgb(120, 130, 100) }
}
pub trait HasColor { fn color (&self) -> ItemColor; }
#[macro_export] macro_rules! has_color {
(|$self:ident:$Struct:ident$(<$($L:lifetime),*$($T:ident$(:$U:path)?),*>)?|$cb:expr) => {
impl $(<$($L),*$($T $(: $U)?),*>)? HasColor for $Struct $(<$($L),*$($T),*>)? {
fn color (&$self) -> ItemColor { $cb }
}
}
}
/// A color in OKHSL and RGB representations.
#[derive(Debug, Default, Copy, Clone, PartialEq)] pub struct ItemColor {
pub okhsl: Okhsl<f32>,
pub rgb: Color,
}
from!(|okhsl: Okhsl<f32>|ItemColor = Self { okhsl, rgb: okhsl_to_rgb(okhsl) });
pub fn okhsl_to_rgb (color: Okhsl<f32>) -> Color {
let Srgb { red, green, blue, .. }: Srgb<f32> = Srgb::from_color_unclamped(color);
Color::Rgb((red * 255.0) as u8, (green * 255.0) as u8, (blue * 255.0) as u8,)
}
from!(|rgb: Color|ItemColor = Self { rgb, okhsl: rgb_to_okhsl(rgb) });
pub fn rgb_to_okhsl (color: Color) -> Okhsl<f32> {
if let Color::Rgb(r, g, b) = color {
Okhsl::from_color(Srgb::new(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0))
} else {
unreachable!("only Color::Rgb is supported")
}
}
// A single color within item theme parameters, in OKHSL and RGB representations.
impl ItemColor {
pub const fn from_rgb (rgb: Color) -> Self {
Self { rgb, okhsl: Okhsl::new_const(OklabHue::new(0.0), 0.0, 0.0) }
}
pub const fn from_okhsl (okhsl: Okhsl<f32>) -> Self {
Self { rgb: Color::Rgb(0, 0, 0), okhsl }
}
pub fn random () -> Self {
let mut rng = thread_rng();
let lo = Okhsl::new(-180.0, 0.01, 0.25);
let hi = Okhsl::new( 180.0, 0.9, 0.5);
UniformOkhsl::new(lo, hi).sample(&mut rng).into()
}
pub fn random_dark () -> Self {
let mut rng = thread_rng();
let lo = Okhsl::new(-180.0, 0.025, 0.075);
let hi = Okhsl::new( 180.0, 0.5, 0.150);
UniformOkhsl::new(lo, hi).sample(&mut rng).into()
}
pub fn random_near (color: Self, distance: f32) -> Self {
color.mix(Self::random(), distance)
}
pub fn mix (&self, other: Self, distance: f32) -> Self {
if distance > 1.0 { panic!("color mixing takes distance between 0.0 and 1.0"); }
self.okhsl.mix(other.okhsl, distance).into()
}
}
/// A color in OKHSL and RGB with lighter and darker variants.
#[derive(Debug, Default, Copy, Clone, PartialEq)] pub struct ItemPalette {
pub base: ItemColor,
pub light: ItemColor,
pub lighter: ItemColor,
pub lightest: ItemColor,
pub dark: ItemColor,
pub darker: ItemColor,
pub darkest: ItemColor,
}
impl ItemPalette {
pub const G: [Self;256] = {
let mut builder = konst::array::ArrayBuilder::new();
while !builder.is_full() {
let index = builder.len() as u8;
let light = (index as f64 * 1.3) as u8;
let lighter = (index as f64 * 1.6) as u8;
let lightest = (index as f64 * 1.9) as u8;
let dark = (index as f64 * 0.9) as u8;
let darker = (index as f64 * 0.6) as u8;
let darkest = (index as f64 * 0.3) as u8;
builder.push(ItemPalette {
base: ItemColor::from_rgb(Color::Rgb(index, index, index )),
light: ItemColor::from_rgb(Color::Rgb(light, light, light, )),
lighter: ItemColor::from_rgb(Color::Rgb(lighter, lighter, lighter, )),
lightest: ItemColor::from_rgb(Color::Rgb(lightest, lightest, lightest, )),
dark: ItemColor::from_rgb(Color::Rgb(dark, dark, dark, )),
darker: ItemColor::from_rgb(Color::Rgb(darker, darker, darker, )),
darkest: ItemColor::from_rgb(Color::Rgb(darkest, darkest, darkest, )),
});
}
builder.build()
};
pub fn random () -> Self { ItemColor::random().into() }
pub fn random_near (color: Self, distance: f32) -> Self {
color.base.mix(ItemColor::random(), distance).into()
}
pub const G00: Self = {
let color: ItemColor = ItemColor {
okhsl: Okhsl { hue: OklabHue::new(0.0), lightness: 0.0, saturation: 0.0 },
rgb: Color::Rgb(0, 0, 0)
};
Self {
base: color,
light: color,
lighter: color,
lightest: color,
dark: color,
darker: color,
darkest: color,
}
};
pub fn from_tui_color (base: Color) -> Self {
Self::from_item_color(ItemColor::from_rgb(base))
}
pub fn from_item_color (base: ItemColor) -> Self {
let mut light = base.okhsl;
light.lightness = (light.lightness * 1.3).min(1.0);
let mut lighter = light;
lighter.lightness = (lighter.lightness * 1.3).min(1.0);
let mut lightest = base.okhsl;
lightest.lightness = 0.95;
let mut dark = base.okhsl;
dark.lightness = (dark.lightness * 0.75).max(0.0);
dark.saturation = (dark.saturation * 0.75).max(0.0);
let mut darker = dark;
darker.lightness = (darker.lightness * 0.66).max(0.0);
darker.saturation = (darker.saturation * 0.66).max(0.0);
let mut darkest = darker;
darkest.lightness = 0.1;
darkest.saturation = (darkest.saturation * 0.50).max(0.0);
Self {
base,
light: light.into(),
lighter: lighter.into(),
lightest: lightest.into(),
dark: dark.into(),
darker: darker.into(),
darkest: darkest.into(),
}
}
}
from!(|base: Color| ItemPalette = Self::from_tui_color(base));
from!(|base: ItemColor|ItemPalette = Self::from_item_color(base));

View file

@ -0,0 +1,87 @@
use crate::*;
/// Browses for phrase to import/export
#[derive(Debug, Clone)]
pub struct FileBrowser {
pub cwd: PathBuf,
pub dirs: Vec<(OsString, String)>,
pub files: Vec<(OsString, String)>,
pub filter: String,
pub index: usize,
pub scroll: usize,
pub size: Measure<TuiOut>
}
/// Commands supported by [FileBrowser]
#[derive(Debug, Clone, PartialEq)]
pub enum FileBrowserCommand {
Begin,
Cancel,
Confirm,
Select(usize),
Chdir(PathBuf),
Filter(Arc<str>),
}
content!(TuiOut: |self: FileBrowser| /*Stack::down(|add|{
let mut i = 0;
for (_, name) in self.dirs.iter() {
if i >= self.scroll {
add(&Tui::bold(i == self.index, name.as_str()))?;
}
i += 1;
}
for (_, name) in self.files.iter() {
if i >= self.scroll {
add(&Tui::bold(i == self.index, name.as_str()))?;
}
i += 1;
}
add(&format!("{}/{i}", self.index))?;
Ok(())
})*/"todo");
impl FileBrowser {
pub fn new (cwd: Option<PathBuf>) -> Usually<Self> {
let cwd = if let Some(cwd) = cwd { cwd } else { std::env::current_dir()? };
let mut dirs = vec![];
let mut files = vec![];
for entry in std::fs::read_dir(&cwd)? {
let entry = entry?;
let name = entry.file_name();
let decoded = name.clone().into_string().unwrap_or_else(|_|"<unreadable>".to_string());
let meta = entry.metadata()?;
if meta.is_dir() {
dirs.push((name, format!("📁 {decoded}")));
} else if meta.is_file() {
files.push((name, format!("📄 {decoded}")));
}
}
Ok(Self {
cwd,
dirs,
files,
filter: "".to_string(),
index: 0,
scroll: 0,
size: Measure::new(),
})
}
pub fn len (&self) -> usize {
self.dirs.len() + self.files.len()
}
pub fn is_dir (&self) -> bool {
self.index < self.dirs.len()
}
pub fn is_file (&self) -> bool {
self.index >= self.dirs.len()
}
pub fn path (&self) -> PathBuf {
self.cwd.join(if self.is_dir() {
&self.dirs[self.index].0
} else if self.is_file() {
&self.files[self.index - self.dirs.len()].0
} else {
unreachable!()
})
}
pub fn chdir (&self) -> Usually<Self> {
Self::new(Some(self.path()))
}
}