Compare commits

...

14 commits

Author SHA1 Message Date
mo8it 4bb6bda9f6 Separate event handlers 2024-04-10 16:02:12 +02:00
mo8it 256c4013b7 Keep hint displayed after resizing the terminal 2024-04-10 15:56:38 +02:00
mo8it 27e9520665 Add deny_unknown_fields 2024-04-10 14:40:49 +02:00
mo8it b3642b0219 Remove todo 2024-04-10 14:35:42 +02:00
mo8it 193e0a03b2 Use light blue for the message 2024-04-10 14:31:08 +02:00
mo8it a59acf8835 Show the current exercise path 2024-04-10 14:29:31 +02:00
mo8it 62e92476e6 Fix typo 2024-04-10 04:10:05 +02:00
mo8it 6255efe8b2 Show the invalid command to avoid confusion after resizing the terminal 2024-04-10 04:08:40 +02:00
mo8it a46d66134b Fix shift of first output line 2024-04-10 03:56:41 +02:00
mo8it f034899c7f Capture terminal resize events 2024-04-10 03:54:48 +02:00
mo8it c9a5fa6097 Accept repeat keyboard events 2024-04-10 02:19:14 +02:00
mo8it d1a965f019 Make the list mode part of the watch mode 2024-04-10 02:12:50 +02:00
mo8it 533a009257 Show the progress in the progress bar, not the current exercise index 2024-04-10 00:51:41 +02:00
mo8it 4a80bf6441 Colorize the progress bar 2024-04-10 00:42:32 +02:00
10 changed files with 285 additions and 148 deletions

View file

@ -46,6 +46,7 @@ pub enum Mode {
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InfoFile {
pub exercises: Vec<Exercise>,
}
@ -65,6 +66,7 @@ impl InfoFile {
// Deserialized from the `info.toml` file.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Exercise {
// Name of the exercise
pub name: String,

View file

@ -28,13 +28,10 @@ pub fn list(state_file: &mut StateFile, exercises: &'static [Exercise]) -> Resul
let key = loop {
match event::read()? {
Event::Key(key) => {
if key.kind != KeyEventKind::Press {
continue;
}
break key;
}
Event::Key(key) => match key.kind {
KeyEventKind::Press | KeyEventKind::Repeat => break key,
KeyEventKind::Release => (),
},
// Redraw
Event::Resize(_, _) => continue 'outer,
// Ignore

View file

@ -7,7 +7,7 @@ use ratatui::{
Frame,
};
use crate::{exercise::Exercise, progress_bar::progress_bar, state_file::StateFile};
use crate::{exercise::Exercise, progress_bar::progress_bar_ratatui, state_file::StateFile};
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Filter {
@ -166,11 +166,11 @@ impl UiState {
);
frame.render_widget(
Paragraph::new(Span::raw(progress_bar(
Paragraph::new(progress_bar_ratatui(
self.progress,
self.exercises.len() as u16,
area.width,
)?))
)?)
.block(Block::default().borders(Borders::BOTTOM)),
Rect {
x: 0,
@ -186,7 +186,7 @@ impl UiState {
"↓/j ↑/k home/g end/G │ filter <d>one/<p>ending │ <r>eset │ <c>ontinue at │ <q>uit",
)
} else {
self.message.as_str().blue()
self.message.as_str().light_blue()
};
frame.render_widget(
message,

View file

@ -16,9 +16,11 @@ mod watch;
use self::{
consts::WELCOME,
exercise::{Exercise, InfoFile},
list::list,
run::run,
state_file::StateFile,
verify::{verify, VerifyState},
watch::{watch, WatchExit},
};
/// Rustlings is a collection of small exercises to get you used to writing and reading Rust code
@ -52,8 +54,6 @@ enum Subcommands {
/// The name of the exercise
name: String,
},
/// List the exercises available in Rustlings
List,
}
fn find_exercise(name: &str, exercises: &'static [Exercise]) -> Result<(usize, &'static Exercise)> {
@ -112,14 +112,17 @@ If you are just starting with Rustlings, run the command `rustlings init` to ini
let mut state_file = StateFile::read_or_default(exercises);
match args.command {
None | Some(Subcommands::Watch) => {
watch::watch(&state_file, exercises)?;
}
None | Some(Subcommands::Watch) => loop {
match watch(&mut state_file, exercises)? {
WatchExit::Shutdown => break,
// It is much easier to exit the watch mode, launch the list mode and then restart
// the watch mode instead of trying to pause the watch threads and correct the
// watch state.
WatchExit::List => list(&mut state_file, exercises)?,
}
},
// `Init` is handled above.
Some(Subcommands::Init) => (),
Some(Subcommands::List) => {
list::list(&mut state_file, exercises)?;
}
Some(Subcommands::Run { name }) => {
let (_, exercise) = find_exercise(&name, exercises)?;
run(exercise).unwrap_or_else(|_| exit(1));

View file

@ -1,41 +1,97 @@
use anyhow::{bail, Result};
use ratatui::text::{Line, Span};
use std::fmt::Write;
const PREFIX: &str = "Progress: [";
const PREFIX_WIDTH: u16 = PREFIX.len() as u16;
// Leaving the last char empty (_) for `total` > 99.
const POSTFIX_WIDTH: u16 = "] xxx/xx exercises_".len() as u16;
const WRAPPER_WIDTH: u16 = PREFIX_WIDTH + POSTFIX_WIDTH;
const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4;
const PROGRESS_EXCEEDS_MAX_ERR: &str =
"The progress of the progress bar is higher than the maximum";
pub fn progress_bar(progress: u16, total: u16, line_width: u16) -> Result<String> {
use crossterm::style::Stylize;
if progress > total {
bail!("The progress of the progress bar is higher than the maximum");
bail!(PROGRESS_EXCEEDS_MAX_ERR);
}
// "Progress: [".len() == 11
// "] xxx/xx exercises_".len() == 19 (leaving the last char empty for `total` > 99)
// 11 + 19 = 30
let wrapper_width = 30;
// If the line width is too low for a progress bar, just show the ratio.
if line_width < wrapper_width + 4 {
if line_width < MIN_LINE_WIDTH {
return Ok(format!("Progress: {progress}/{total} exercises"));
}
let mut line = String::with_capacity(usize::from(line_width));
line.push_str("Progress: [");
line.push_str(PREFIX);
let remaining_width = line_width.saturating_sub(wrapper_width);
let filled = (remaining_width * progress) / total;
let width = line_width - WRAPPER_WIDTH;
let filled = (width * progress) / total;
let mut green_part = String::with_capacity(usize::from(filled + 1));
for _ in 0..filled {
line.push('=');
green_part.push('#');
}
if filled < remaining_width {
line.push('>');
if filled < width {
green_part.push('>');
}
write!(line, "{}", green_part.green()).unwrap();
let width_minus_filled = width - filled;
if width_minus_filled > 1 {
let red_part_width = width_minus_filled - 1;
let mut red_part = String::with_capacity(usize::from(red_part_width));
for _ in 0..red_part_width {
red_part.push('-');
}
write!(line, "{}", red_part.red()).unwrap();
}
for _ in 0..(remaining_width - filled).saturating_sub(1) {
line.push(' ');
}
line.write_fmt(format_args!("] {progress:>3}/{total} exercises"))
.unwrap();
writeln!(line, "] {progress:>3}/{total} exercises").unwrap();
Ok(line)
}
pub fn progress_bar_ratatui(progress: u16, total: u16, line_width: u16) -> Result<Line<'static>> {
use ratatui::style::Stylize;
if progress > total {
bail!(PROGRESS_EXCEEDS_MAX_ERR);
}
if line_width < MIN_LINE_WIDTH {
return Ok(Line::raw(format!("Progress: {progress}/{total} exercises")));
}
let mut spans = Vec::with_capacity(4);
spans.push(Span::raw(PREFIX));
let width = line_width - WRAPPER_WIDTH;
let filled = (width * progress) / total;
let mut green_part = String::with_capacity(usize::from(filled + 1));
for _ in 0..filled {
green_part.push('#');
}
if filled < width {
green_part.push('>');
}
spans.push(green_part.green());
let width_minus_filled = width - filled;
if width_minus_filled > 1 {
let red_part_width = width_minus_filled - 1;
let mut red_part = String::with_capacity(usize::from(red_part_width));
for _ in 0..red_part_width {
red_part.push('-');
}
spans.push(red_part.red());
}
spans.push(Span::raw(format!("] {progress:>3}/{total} exercises")));
Ok(Line::from(spans))
}

View file

@ -5,6 +5,7 @@ use std::fs;
use crate::exercise::Exercise;
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StateFile {
next_exercise_ind: usize,
progress: Vec<bool>,
@ -33,7 +34,6 @@ impl StateFile {
}
fn write(&self) -> Result<()> {
// TODO: Capacity
let mut buf = Vec::with_capacity(1024);
serde_json::ser::to_writer(&mut buf, self).context("Failed to serialize the state")?;
fs::write(".rustlings-state.json", buf)

View file

@ -1,109 +1,49 @@
use anyhow::Result;
use anyhow::{Error, Result};
use notify_debouncer_mini::{
new_debouncer,
notify::{self, RecursiveMode},
DebounceEventResult, DebouncedEventKind,
};
use std::{
io::{self, BufRead, Write},
io::{self, Write},
path::Path,
sync::mpsc::{channel, Sender},
sync::mpsc::channel,
thread,
time::Duration,
};
mod debounce_event;
mod state;
mod terminal_event;
use crate::{exercise::Exercise, state_file::StateFile};
use self::state::WatchState;
enum InputEvent {
Hint,
Clear,
Quit,
Unrecognized,
}
use self::{
debounce_event::DebounceEventHandler,
state::WatchState,
terminal_event::{terminal_event_handler, InputEvent},
};
enum WatchEvent {
Input(InputEvent),
FileChange { exercise_ind: usize },
NotifyErr(notify::Error),
StdinErr(io::Error),
TerminalEventErr(io::Error),
TerminalResize,
}
struct DebouceEventHandler {
tx: Sender<WatchEvent>,
exercises: &'static [Exercise],
/// Returned by the watch mode to indicate what to do afterwards.
pub enum WatchExit {
/// Exit the program.
Shutdown,
/// Enter the list mode and restart the watch mode afterwards.
List,
}
impl notify_debouncer_mini::DebounceEventHandler for DebouceEventHandler {
fn handle_event(&mut self, event: DebounceEventResult) {
let event = match event {
Ok(event) => {
let Some(exercise_ind) = event
.iter()
.filter_map(|event| {
if event.kind != DebouncedEventKind::Any
|| !event.path.extension().is_some_and(|ext| ext == "rs")
{
return None;
}
self.exercises
.iter()
.position(|exercise| event.path.ends_with(&exercise.path))
})
.min()
else {
return;
};
WatchEvent::FileChange { exercise_ind }
}
Err(e) => WatchEvent::NotifyErr(e),
};
// An error occurs when the receiver is dropped.
// After dropping the receiver, the debouncer guard should also be dropped.
let _ = self.tx.send(event);
}
}
fn input_handler(tx: Sender<WatchEvent>) {
let mut stdin = io::stdin().lock();
let mut stdin_buf = String::with_capacity(8);
loop {
if let Err(e) = stdin.read_line(&mut stdin_buf) {
// If `send` returns an error, then the receiver is dropped and
// a shutdown has been already initialized.
let _ = tx.send(WatchEvent::StdinErr(e));
return;
}
let event = match stdin_buf.trim() {
"h" | "hint" => InputEvent::Hint,
"c" | "clear" => InputEvent::Clear,
"q" | "quit" => InputEvent::Quit,
_ => InputEvent::Unrecognized,
};
stdin_buf.clear();
if tx.send(WatchEvent::Input(event)).is_err() {
// The receiver was dropped.
return;
}
}
}
pub fn watch(state_file: &StateFile, exercises: &'static [Exercise]) -> Result<()> {
pub fn watch(state_file: &mut StateFile, exercises: &'static [Exercise]) -> Result<WatchExit> {
let (tx, rx) = channel();
let mut debouncer = new_debouncer(
Duration::from_secs(1),
DebouceEventHandler {
DebounceEventHandler {
tx: tx.clone(),
exercises,
},
@ -118,27 +58,34 @@ pub fn watch(state_file: &StateFile, exercises: &'static [Exercise]) -> Result<(
watch_state.run_exercise()?;
watch_state.render()?;
thread::spawn(move || input_handler(tx));
thread::spawn(move || terminal_event_handler(tx));
while let Ok(event) = rx.recv() {
match event {
WatchEvent::Input(InputEvent::Hint) => {
watch_state.show_hint()?;
}
WatchEvent::Input(InputEvent::Clear) | WatchEvent::TerminalResize => {
WatchEvent::Input(InputEvent::List) => {
return Ok(WatchExit::List);
}
WatchEvent::TerminalResize => {
watch_state.render()?;
}
WatchEvent::Input(InputEvent::Quit) => break,
WatchEvent::Input(InputEvent::Unrecognized) => {
watch_state.handle_invalid_cmd()?;
WatchEvent::Input(InputEvent::Unrecognized(cmd)) => {
watch_state.handle_invalid_cmd(&cmd)?;
}
WatchEvent::FileChange { exercise_ind } => {
// TODO: bool
watch_state.run_exercise_with_ind(exercise_ind)?;
watch_state.render()?;
}
WatchEvent::NotifyErr(e) => return Err(e.into()),
WatchEvent::StdinErr(e) => return Err(e.into()),
WatchEvent::NotifyErr(e) => {
return Err(Error::from(e).context("Exercise file watcher failed"))
}
WatchEvent::TerminalEventErr(e) => {
return Err(Error::from(e).context("Terminal event listener failed"))
}
}
}
@ -147,5 +94,5 @@ We hope you're enjoying learning Rust!
If you want to continue working on the exercises at a later point, you can simply run `rustlings` again.
")?;
Ok(())
Ok(WatchExit::Shutdown)
}

View file

@ -0,0 +1,44 @@
use notify_debouncer_mini::{DebounceEventResult, DebouncedEventKind};
use std::sync::mpsc::Sender;
use crate::exercise::Exercise;
use super::WatchEvent;
pub struct DebounceEventHandler {
pub tx: Sender<WatchEvent>,
pub exercises: &'static [Exercise],
}
impl notify_debouncer_mini::DebounceEventHandler for DebounceEventHandler {
fn handle_event(&mut self, event: DebounceEventResult) {
let event = match event {
Ok(event) => {
let Some(exercise_ind) = event
.iter()
.filter_map(|event| {
if event.kind != DebouncedEventKind::Any
|| !event.path.extension().is_some_and(|ext| ext == "rs")
{
return None;
}
self.exercises
.iter()
.position(|exercise| event.path.ends_with(&exercise.path))
})
.min()
else {
return;
};
WatchEvent::FileChange { exercise_ind }
}
Err(e) => WatchEvent::NotifyErr(e),
};
// An error occurs when the receiver is dropped.
// After dropping the receiver, the debouncer guard should also be dropped.
let _ = self.tx.send(event);
}
}

View file

@ -6,7 +6,7 @@ use crossterm::{
};
use std::{
fmt::Write as _,
io::{self, StdoutLock, Write as _},
io::{self, StdoutLock, Write},
};
use crate::{
@ -20,36 +20,31 @@ pub struct WatchState<'a> {
exercises: &'static [Exercise],
exercise: &'static Exercise,
current_exercise_ind: usize,
progress: u16,
stdout: Option<Vec<u8>>,
stderr: Option<Vec<u8>>,
message: Option<String>,
prompt: Vec<u8>,
hint_displayed: bool,
}
impl<'a> WatchState<'a> {
pub fn new(state_file: &StateFile, exercises: &'static [Exercise]) -> Self {
let current_exercise_ind = state_file.next_exercise_ind();
let progress = state_file.progress().iter().filter(|done| **done).count() as u16;
let exercise = &exercises[current_exercise_ind];
let writer = io::stdout().lock();
let prompt = format!(
"\n\n{}int/{}lear/{}uit? ",
"h".bold(),
"c".bold(),
"q".bold()
)
.into_bytes();
Self {
writer,
exercises,
exercise,
current_exercise_ind,
progress,
stdout: None,
stderr: None,
message: None,
prompt,
hint_displayed: false,
}
}
@ -118,19 +113,32 @@ You can keep working on this exercise or jump into the next one by removing the
}
pub fn show_prompt(&mut self) -> io::Result<()> {
self.writer.write_all(&self.prompt)?;
self.writer.write_all(b"\n\n")?;
if !self.hint_displayed {
self.writer.write_fmt(format_args!("{}int/", 'h'.bold()))?;
}
self.writer
.write_fmt(format_args!("{}ist/{}uit? ", 'l'.bold(), 'q'.bold()))?;
self.writer.flush()
}
pub fn render(&mut self) -> Result<()> {
// Prevent having the first line shifted after clearing because of the prompt.
self.writer.write_all(b"\n")?;
self.writer.execute(Clear(ClearType::All))?;
if let Some(stdout) = &self.stdout {
self.writer.write_all(stdout)?;
self.writer.write_all(b"\n")?;
}
if let Some(stderr) = &self.stderr {
self.writer.write_all(stderr)?;
self.writer.write_all(b"\n")?;
}
if let Some(message) = &self.message {
@ -138,26 +146,41 @@ You can keep working on this exercise or jump into the next one by removing the
}
self.writer.write_all(b"\n")?;
if self.hint_displayed {
self.writer
.write_fmt(format_args!("\n{}\n", "Hint".bold().cyan().underlined()))?;
self.writer.write_all(self.exercise.hint.as_bytes())?;
self.writer.write_all(b"\n\n")?;
}
let line_width = size()?.0;
let progress_bar = progress_bar(
self.current_exercise_ind as u16,
self.exercises.len() as u16,
line_width,
)?;
let progress_bar = progress_bar(self.progress, self.exercises.len() as u16, line_width)?;
self.writer.write_all(progress_bar.as_bytes())?;
self.writer.write_all(b"Current exercise: ")?;
self.writer.write_fmt(format_args!(
"{}",
self.exercise.path.to_string_lossy().bold()
))?;
self.show_prompt()?;
Ok(())
}
pub fn show_hint(&mut self) -> io::Result<()> {
self.writer.write_all(self.exercise.hint.as_bytes())?;
self.show_prompt()
pub fn show_hint(&mut self) -> Result<()> {
self.hint_displayed = true;
self.render()
}
pub fn handle_invalid_cmd(&mut self) -> io::Result<()> {
self.writer.write_all(b"Invalid command")?;
pub fn handle_invalid_cmd(&mut self, cmd: &str) -> io::Result<()> {
self.writer.write_all(b"Invalid command: ")?;
self.writer.write_all(cmd.as_bytes())?;
if cmd.len() > 1 {
self.writer
.write_all(b" (confusing input can occur after resizing the terminal)")?;
}
self.show_prompt()
}
}

View file

@ -0,0 +1,65 @@
use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use std::sync::mpsc::Sender;
use super::WatchEvent;
pub enum InputEvent {
Hint,
List,
Quit,
Unrecognized(String),
}
pub fn terminal_event_handler(tx: Sender<WatchEvent>) {
let mut input = String::with_capacity(8);
let last_input_event = loop {
let terminal_event = match event::read() {
Ok(v) => v,
Err(e) => {
// If `send` returns an error, then the receiver is dropped and
// a shutdown has been already initialized.
let _ = tx.send(WatchEvent::TerminalEventErr(e));
return;
}
};
match terminal_event {
Event::Key(key) => {
match key.kind {
KeyEventKind::Release => continue,
KeyEventKind::Press | KeyEventKind::Repeat => (),
}
match key.code {
KeyCode::Enter => {
let input_event = match input.trim() {
"h" | "hint" => InputEvent::Hint,
"l" | "list" => break InputEvent::List,
"q" | "quit" => break InputEvent::Quit,
_ => InputEvent::Unrecognized(input.clone()),
};
if tx.send(WatchEvent::Input(input_event)).is_err() {
return;
}
input.clear();
}
KeyCode::Char(c) => {
input.push(c);
}
_ => (),
}
}
Event::Resize(_, _) => {
if tx.send(WatchEvent::TerminalResize).is_err() {
return;
}
}
Event::FocusGained | Event::FocusLost | Event::Mouse(_) | Event::Paste(_) => continue,
}
};
let _ = tx.send(WatchEvent::Input(last_input_event));
}