rustlings/src/list/state.rs

397 lines
12 KiB
Rust
Raw Normal View History

use anyhow::{Context, Result};
2024-08-24 01:14:12 +03:00
use crossterm::{
2024-08-24 18:17:56 +03:00
cursor::{MoveTo, MoveToNextLine},
2024-08-24 18:45:02 +03:00
style::{Attribute, Color, ResetColor, SetAttribute, SetBackgroundColor, SetForegroundColor},
2024-08-24 18:17:56 +03:00
terminal::{self, BeginSynchronizedUpdate, Clear, ClearType, EndSynchronizedUpdate},
2024-08-24 01:14:12 +03:00
QueueableCommand,
2024-04-07 20:05:29 +03:00
};
2024-08-24 01:14:12 +03:00
use std::{
fmt::Write as _,
2024-08-24 18:17:56 +03:00
io::{self, StdoutLock, Write},
2024-08-24 01:14:12 +03:00
};
2024-08-24 20:18:13 +03:00
use crate::{app_state::AppState, exercise::Exercise, term::progress_bar, MAX_EXERCISE_NAME_LEN};
// +1 for padding.
const SPACE: &[u8] = &[b' '; MAX_EXERCISE_NAME_LEN + 1];
2024-04-07 20:05:29 +03:00
2024-08-25 20:24:12 +03:00
fn next_ln(stdout: &mut StdoutLock) -> io::Result<()> {
2024-08-24 18:17:56 +03:00
stdout
.queue(Clear(ClearType::UntilNewLine))?
.queue(MoveToNextLine(1))?;
Ok(())
}
2024-04-07 20:05:29 +03:00
2024-08-25 20:24:12 +03:00
// Avoids having the last written char as the last displayed one when the
// written width is higher than the terminal width.
// Happens on the Gnome terminal for example.
fn next_ln_overwrite(stdout: &mut StdoutLock) -> io::Result<()> {
stdout.write_all(b" ")?;
next_ln(stdout)
}
2024-04-08 03:41:48 +03:00
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Filter {
Done,
Pending,
None,
}
2024-08-24 01:14:12 +03:00
pub struct ListState<'a> {
2024-08-25 20:24:12 +03:00
/// Footer message to be displayed if not empty.
2024-04-08 02:33:11 +03:00
pub message: String,
app_state: &'a mut AppState,
2024-08-24 01:14:12 +03:00
name_col_width: usize,
2024-08-25 20:24:12 +03:00
filter: Filter,
n_rows_with_filter: usize,
/// Selected row out of the displayed ones.
selected_row: Option<usize>,
2024-08-24 18:17:56 +03:00
term_width: u16,
term_height: u16,
2024-08-25 20:24:12 +03:00
separator_line: Vec<u8>,
narrow_term: bool,
show_footer: bool,
max_n_rows_to_display: usize,
scroll_padding: usize,
row_offset: usize,
2024-04-07 20:05:29 +03:00
}
2024-08-24 01:14:12 +03:00
impl<'a> ListState<'a> {
pub fn new(app_state: &'a mut AppState, stdout: &mut StdoutLock) -> io::Result<Self> {
2024-08-24 18:17:56 +03:00
stdout.queue(Clear(ClearType::All))?;
2024-08-25 20:24:12 +03:00
let name_col_title_len = 4;
2024-08-24 01:14:12 +03:00
let name_col_width = app_state
.exercises()
2024-04-07 20:05:29 +03:00
.iter()
.map(|exercise| exercise.name.len())
.max()
2024-08-25 20:24:12 +03:00
.map_or(name_col_title_len, |max| max.max(name_col_title_len));
2024-04-07 20:05:29 +03:00
2024-08-25 20:24:12 +03:00
let filter = Filter::None;
2024-08-24 01:14:12 +03:00
let n_rows_with_filter = app_state.exercises().len();
2024-08-25 20:24:12 +03:00
let selected = Some(app_state.current_exercise_ind());
2024-04-11 15:35:30 +03:00
2024-08-24 01:14:12 +03:00
let mut slf = Self {
2024-04-08 03:41:48 +03:00
message: String::with_capacity(128),
app_state,
2024-08-24 01:14:12 +03:00
name_col_width,
2024-08-25 20:24:12 +03:00
filter,
n_rows_with_filter,
selected_row: selected,
// Set by `set_term_size`
term_width: 0,
term_height: 0,
separator_line: Vec::new(),
narrow_term: false,
show_footer: true,
max_n_rows_to_display: 0,
scroll_padding: 0,
// Updated by `draw`
row_offset: 0,
2024-08-24 01:14:12 +03:00
};
2024-08-25 20:24:12 +03:00
let (width, height) = terminal::size()?;
slf.set_term_size(width, height);
2024-08-24 20:18:13 +03:00
slf.draw(stdout)?;
2024-08-24 01:14:12 +03:00
Ok(slf)
}
2024-08-25 20:24:12 +03:00
pub fn set_term_size(&mut self, width: u16, height: u16) {
self.term_width = width;
self.term_height = height;
self.separator_line = "".as_bytes().repeat(width as usize);
self.narrow_term = width < 95 && self.selected_row.is_some();
self.show_footer = height > 6;
self.max_n_rows_to_display =
(height - 1 - u16::from(self.show_footer) * (4 + u16::from(self.narrow_term))) as usize;
self.scroll_padding = (self.max_n_rows_to_display / 4).min(5);
}
fn update_offset(&mut self) {
let Some(selected) = self.selected_row else {
return;
};
let min_offset = (selected + self.scroll_padding)
.saturating_sub(self.max_n_rows_to_display.saturating_sub(1));
let max_offset = selected.saturating_sub(self.scroll_padding);
let global_max_offset = self
.n_rows_with_filter
.saturating_sub(self.max_n_rows_to_display);
self.row_offset = self
.row_offset
.max(min_offset)
.min(max_offset)
.min(global_max_offset);
}
2024-08-24 20:18:13 +03:00
fn draw_rows(
&self,
stdout: &mut StdoutLock,
filtered_exercises: impl Iterator<Item = (usize, &'a Exercise)>,
) -> io::Result<usize> {
2024-08-24 18:17:56 +03:00
let current_exercise_ind = self.app_state.current_exercise_ind();
let mut n_displayed_rows = 0;
2024-08-24 20:18:13 +03:00
for (exercise_ind, exercise) in filtered_exercises
2024-08-25 20:24:12 +03:00
.skip(self.row_offset)
.take(self.max_n_rows_to_display)
2024-08-24 20:18:13 +03:00
{
2024-08-25 20:24:12 +03:00
if self.selected_row == Some(self.row_offset + n_displayed_rows) {
2024-08-24 18:45:02 +03:00
stdout.queue(SetBackgroundColor(Color::Rgb {
r: 50,
g: 50,
b: 50,
}))?;
2024-08-24 18:17:56 +03:00
stdout.write_all("🦀".as_bytes())?;
} else {
stdout.write_all(b" ")?;
}
if exercise_ind == current_exercise_ind {
stdout.queue(SetForegroundColor(Color::Red))?;
stdout.write_all(b">>>>>>> ")?;
} else {
stdout.write_all(b" ")?;
}
if exercise.done {
stdout.queue(SetForegroundColor(Color::Yellow))?;
stdout.write_all(b"DONE ")?;
} else {
stdout.queue(SetForegroundColor(Color::Green))?;
stdout.write_all(b"PENDING ")?;
}
2024-08-24 18:45:02 +03:00
stdout.queue(SetForegroundColor(Color::Reset))?;
2024-08-24 18:17:56 +03:00
stdout.write_all(exercise.name.as_bytes())?;
stdout.write_all(&SPACE[..self.name_col_width + 2 - exercise.name.len()])?;
stdout.write_all(exercise.path.as_bytes())?;
2024-08-25 20:24:12 +03:00
next_ln_overwrite(stdout)?;
2024-08-24 18:45:02 +03:00
stdout.queue(ResetColor)?;
2024-08-24 18:17:56 +03:00
n_displayed_rows += 1;
}
2024-08-24 20:18:13 +03:00
Ok(n_displayed_rows)
}
pub fn draw(&mut self, stdout: &mut StdoutLock) -> io::Result<()> {
if self.term_height == 0 {
return Ok(());
}
stdout.queue(BeginSynchronizedUpdate)?.queue(MoveTo(0, 0))?;
// Header
stdout.write_all(b" Current State Name")?;
stdout.write_all(&SPACE[..self.name_col_width - 2])?;
stdout.write_all(b"Path")?;
2024-08-25 20:24:12 +03:00
next_ln_overwrite(stdout)?;
2024-08-24 20:18:13 +03:00
2024-08-25 20:24:12 +03:00
self.update_offset();
2024-08-24 20:18:13 +03:00
// Rows
let iter = self.app_state.exercises().iter().enumerate();
let n_displayed_rows = match self.filter {
2024-08-25 20:24:12 +03:00
Filter::Done => self.draw_rows(stdout, iter.filter(|(_, exercise)| exercise.done))?,
Filter::Pending => {
self.draw_rows(stdout, iter.filter(|(_, exercise)| !exercise.done))?
}
Filter::None => self.draw_rows(stdout, iter)?,
2024-08-24 20:18:13 +03:00
};
2024-08-25 20:24:12 +03:00
for _ in 0..self.max_n_rows_to_display - n_displayed_rows {
next_ln(stdout)?;
2024-08-24 18:17:56 +03:00
}
2024-08-25 20:24:12 +03:00
if self.show_footer {
stdout.write_all(&self.separator_line)?;
next_ln(stdout)?;
2024-08-24 18:17:56 +03:00
progress_bar(
stdout,
self.app_state.n_done(),
self.app_state.exercises().len() as u16,
self.term_width,
)?;
2024-08-25 20:24:12 +03:00
next_ln(stdout)?;
2024-08-24 18:17:56 +03:00
2024-08-25 20:24:12 +03:00
stdout.write_all(&self.separator_line)?;
next_ln(stdout)?;
2024-08-24 18:17:56 +03:00
if self.message.is_empty() {
2024-08-24 20:18:13 +03:00
// Help footer
2024-08-25 20:24:12 +03:00
if self.selected_row.is_some() {
stdout.write_all(
"↓/j ↑/k home/g end/G | <c>ontinue at | <r>eset exercise".as_bytes(),
)?;
if self.narrow_term {
next_ln_overwrite(stdout)?;
stdout.write_all(b"filter ")?;
} else {
stdout.write_all(b" | filter ")?;
}
2024-08-24 18:17:56 +03:00
} else {
2024-08-25 20:24:12 +03:00
stdout.write_all(b"filter ")?;
2024-08-24 18:17:56 +03:00
}
match self.filter {
Filter::Done => {
stdout
.queue(SetForegroundColor(Color::Magenta))?
.queue(SetAttribute(Attribute::Underlined))?;
stdout.write_all(b"<d>one")?;
stdout.queue(ResetColor)?;
stdout.write_all(b"/<p>ending")?;
}
Filter::Pending => {
stdout.write_all(b"<d>one/")?;
stdout
.queue(SetForegroundColor(Color::Magenta))?
.queue(SetAttribute(Attribute::Underlined))?;
stdout.write_all(b"<p>ending")?;
stdout.queue(ResetColor)?;
}
Filter::None => stdout.write_all(b"<d>one/<p>ending")?,
}
2024-08-25 20:24:12 +03:00
stdout.write_all(b" | <q>uit list")?;
if self.narrow_term {
next_ln_overwrite(stdout)?;
} else {
2024-08-25 20:24:12 +03:00
next_ln(stdout)?;
}
2024-08-24 18:17:56 +03:00
} else {
stdout.queue(SetForegroundColor(Color::Magenta))?;
stdout.write_all(self.message.as_bytes())?;
stdout.queue(ResetColor)?;
2024-08-25 20:24:12 +03:00
next_ln_overwrite(stdout)?;
if self.narrow_term {
next_ln(stdout)?;
2024-08-24 18:17:56 +03:00
}
}
}
stdout.queue(EndSynchronizedUpdate)?.flush()
}
2024-08-25 20:24:12 +03:00
fn update_rows(&mut self) {
self.n_rows_with_filter = match self.filter {
2024-08-24 01:14:12 +03:00
Filter::Done => self
.app_state
.exercises()
.iter()
2024-08-24 18:17:56 +03:00
.filter(|exercise| exercise.done)
2024-08-24 01:14:12 +03:00
.count(),
Filter::Pending => self
.app_state
.exercises()
.iter()
2024-08-24 18:17:56 +03:00
.filter(|exercise| !exercise.done)
2024-08-24 01:14:12 +03:00
.count(),
Filter::None => self.app_state.exercises().len(),
};
2024-08-24 01:14:12 +03:00
if self.n_rows_with_filter == 0 {
2024-08-25 20:24:12 +03:00
self.selected_row = None;
2024-08-24 01:14:12 +03:00
} else {
2024-08-25 20:24:12 +03:00
self.selected_row = Some(
self.selected_row
2024-08-24 01:14:12 +03:00
.map_or(0, |selected| selected.min(self.n_rows_with_filter - 1)),
);
}
2024-04-07 20:05:29 +03:00
}
2024-08-25 20:24:12 +03:00
#[inline]
pub fn filter(&self) -> Filter {
self.filter
}
pub fn set_filter(&mut self, filter: Filter) {
self.filter = filter;
self.update_rows();
}
2024-04-07 20:05:29 +03:00
pub fn select_next(&mut self) {
2024-08-25 20:24:12 +03:00
if let Some(selected) = self.selected_row {
self.selected_row = Some((selected + 1).min(self.n_rows_with_filter - 1));
2024-04-11 15:35:30 +03:00
}
2024-04-07 20:05:29 +03:00
}
pub fn select_previous(&mut self) {
2024-08-25 20:24:12 +03:00
if let Some(selected) = self.selected_row {
self.selected_row = Some(selected.saturating_sub(1));
2024-04-11 15:35:30 +03:00
}
2024-04-07 20:05:29 +03:00
}
pub fn select_first(&mut self) {
2024-08-24 01:14:12 +03:00
if self.n_rows_with_filter > 0 {
2024-08-25 20:24:12 +03:00
self.selected_row = Some(0);
2024-04-11 15:35:30 +03:00
}
2024-04-07 20:05:29 +03:00
}
pub fn select_last(&mut self) {
2024-08-24 01:14:12 +03:00
if self.n_rows_with_filter > 0 {
2024-08-25 20:24:12 +03:00
self.selected_row = Some(self.n_rows_with_filter - 1);
2024-04-11 15:35:30 +03:00
}
2024-04-07 20:05:29 +03:00
}
2024-08-24 18:17:56 +03:00
fn selected_to_exercise_ind(&self, selected: usize) -> Result<usize> {
match self.filter {
Filter::Done => self
.app_state
.exercises()
.iter()
.enumerate()
.filter(|(_, exercise)| exercise.done)
.nth(selected)
.context("Invalid selection index")
.map(|(ind, _)| ind),
Filter::Pending => self
.app_state
.exercises()
.iter()
.enumerate()
.filter(|(_, exercise)| !exercise.done)
.nth(selected)
.context("Invalid selection index")
.map(|(ind, _)| ind),
Filter::None => Ok(selected),
2024-08-24 01:14:12 +03:00
}
2024-04-07 20:05:29 +03:00
}
2024-08-24 01:14:12 +03:00
pub fn reset_selected(&mut self) -> Result<()> {
2024-08-25 20:24:12 +03:00
let Some(selected) = self.selected_row else {
2024-08-24 18:17:56 +03:00
self.message.push_str("Nothing selected to reset!");
2024-08-24 01:14:12 +03:00
return Ok(());
2024-04-11 15:35:30 +03:00
};
2024-08-24 18:17:56 +03:00
let exercise_ind = self.selected_to_exercise_ind(selected)?;
let exercise_path = self.app_state.reset_exercise_by_ind(exercise_ind)?;
2024-08-25 20:24:12 +03:00
self.update_rows();
2024-04-25 03:03:26 +03:00
write!(self.message, "The exercise {exercise_path} has been reset")?;
2024-08-24 01:14:12 +03:00
Ok(())
}
// Return `true` if there was something to select.
pub fn selected_to_current_exercise(&mut self) -> Result<bool> {
2024-08-25 20:24:12 +03:00
let Some(selected) = self.selected_row else {
self.message.push_str("Nothing selected to continue at!");
return Ok(false);
2024-04-11 15:35:30 +03:00
};
2024-08-24 18:17:56 +03:00
let exercise_ind = self.selected_to_exercise_ind(selected)?;
self.app_state.set_current_exercise_ind(exercise_ind)?;
2024-08-25 20:24:12 +03:00
Ok(true)
}
2024-04-07 20:05:29 +03:00
}