Compare commits

..

No commits in common. "74388d4bf44cdfebc0d6dc8e5faa81bffe71ddd6" and "d29e9e7e07a16adda35aea9ce9dd120b6ecc9dfc" have entirely different histories.

12 changed files with 238 additions and 392 deletions

View file

@ -75,8 +75,6 @@ unstable_features = "forbid"
[workspace.lints.clippy]
empty_loop = "forbid"
disallowed-types = "deny"
disallowed-methods = "deny"
infinite_loop = "deny"
mem_forget = "deny"
dbg_macro = "warn"

View file

@ -1,13 +0,0 @@
disallowed-types = [
# Inefficient. Use `.queue(…)` instead.
"crossterm::style::Stylize",
"crossterm::style::styled_content::StyledContent",
]
disallowed-methods = [
# We use `ahash` instead of the default hasher.
"std::collections::HashSet::new",
"std::collections::HashSet::with_capacity",
# Inefficient. Use `.queue(…)` instead.
"crossterm::style::style",
]

View file

@ -338,7 +338,7 @@ impl AppState {
/// Mark the current exercise as done and move on to the next pending exercise if one exists.
/// If all exercises are marked as done, run all of them to make sure that they are actually
/// done. If an exercise which is marked as done fails, mark it as pending and continue on it.
pub fn done_current_exercise(&mut self, stdout: &mut StdoutLock) -> Result<ExercisesProgress> {
pub fn done_current_exercise(&mut self, writer: &mut StdoutLock) -> Result<ExercisesProgress> {
let exercise = &mut self.exercises[self.current_exercise_ind];
if !exercise.done {
exercise.done = true;
@ -350,7 +350,7 @@ impl AppState {
return Ok(ExercisesProgress::NewPending);
}
stdout.write_all(RERUNNING_ALL_EXERCISES_MSG)?;
writer.write_all(RERUNNING_ALL_EXERCISES_MSG)?;
let n_exercises = self.exercises.len();
@ -368,12 +368,12 @@ impl AppState {
.collect::<Vec<_>>();
for (exercise_ind, handle) in handles.into_iter().enumerate() {
write!(stdout, "\rProgress: {exercise_ind}/{n_exercises}")?;
stdout.flush()?;
write!(writer, "\rProgress: {exercise_ind}/{n_exercises}")?;
writer.flush()?;
let success = handle.join().unwrap()?;
if !success {
stdout.write_all(b"\n\n")?;
writer.write_all(b"\n\n")?;
return Ok(Some(exercise_ind));
}
}
@ -395,13 +395,13 @@ impl AppState {
// Write that the last exercise is done.
self.write()?;
clear_terminal(stdout)?;
stdout.write_all(FENISH_LINE.as_bytes())?;
clear_terminal(writer)?;
writer.write_all(FENISH_LINE.as_bytes())?;
let final_message = self.final_message.trim_ascii();
if !final_message.is_empty() {
stdout.write_all(final_message.as_bytes())?;
stdout.write_all(b"\n")?;
writer.write_all(final_message.as_bytes())?;
writer.write_all(b"\n")?;
}
Ok(ExercisesProgress::AllDone)

View file

@ -1,27 +1,15 @@
use anyhow::Result;
use crossterm::{
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
QueueableCommand,
use crossterm::style::{style, StyledContent, Stylize};
use std::{
fmt::{self, Display, Formatter},
io::Write,
};
use std::io::{self, StdoutLock, Write};
use crate::{
cmd::CmdRunner,
term::{terminal_file_link, write_ansi},
};
use crate::{cmd::CmdRunner, terminal_link::TerminalFileLink};
/// The initial capacity of the output buffer.
pub const OUTPUT_CAPACITY: usize = 1 << 14;
pub fn solution_link_line(stdout: &mut StdoutLock, solution_path: &str) -> io::Result<()> {
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"Solution")?;
stdout.queue(ResetColor)?;
stdout.write_all(b" for comparison: ")?;
terminal_file_link(stdout, solution_path, Color::Cyan)?;
stdout.write_all(b"\n")
}
// Run an exercise binary and append its output to the `output` buffer.
// Compilation must be done before calling this method.
fn run_bin(
@ -30,10 +18,7 @@ fn run_bin(
cmd_runner: &CmdRunner,
) -> Result<bool> {
if let Some(output) = output.as_deref_mut() {
write_ansi(output, SetAttribute(Attribute::Underlined));
output.extend_from_slice(b"Output");
write_ansi(output, ResetColor);
output.push(b'\n');
writeln!(output, "{}", "Output".underlined())?;
}
let success = cmd_runner.run_debug_bin(bin_name, output.as_deref_mut())?;
@ -43,11 +28,13 @@ fn run_bin(
// This output is important to show the user that something went wrong.
// Otherwise, calling something like `exit(1)` in an exercise without further output
// leaves the user confused about why the exercise isn't done yet.
write_ansi(output, SetAttribute(Attribute::Bold));
write_ansi(output, SetForegroundColor(Color::Red));
output.extend_from_slice(b"The exercise didn't run successfully (nonzero exit code)");
write_ansi(output, ResetColor);
output.push(b'\n');
writeln!(
output,
"{}",
"The exercise didn't run successfully (nonzero exit code)"
.bold()
.red(),
)?;
}
}
@ -66,6 +53,18 @@ pub struct Exercise {
pub done: bool,
}
impl Exercise {
pub fn terminal_link(&self) -> StyledContent<TerminalFileLink<'_>> {
style(TerminalFileLink(self.path)).underlined().blue()
}
}
impl Display for Exercise {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.path.fmt(f)
}
}
pub trait RunnableExercise {
fn name(&self) -> &str;
fn strict_clippy(&self) -> bool;

View file

@ -1,8 +1,5 @@
use anyhow::{bail, Context, Result};
use crossterm::{
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
QueueableCommand,
};
use crossterm::style::Stylize;
use serde::Deserialize;
use std::{
env::set_current_dir,
@ -147,14 +144,12 @@ pub fn init() -> Result<()> {
.status();
}
stdout.queue(SetForegroundColor(Color::Green))?;
stdout.write_all("Initialization done ✓".as_bytes())?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n\n")?;
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(POST_INIT_MSG)?;
stdout.queue(ResetColor)?;
writeln!(
stdout,
"{}\n\n{}",
"Initialization done ✓".green(),
POST_INIT_MSG.bold(),
)?;
Ok(())
}
@ -187,6 +182,5 @@ You probably already initialized Rustlings.
Run `cd rustlings`
Then run `rustlings` again";
const POST_INIT_MSG: &[u8] = b"Run `cd rustlings` to go into the generated directory.
Then run `rustlings` to get started.
";
const POST_INIT_MSG: &str = "Run `cd rustlings` to go into the generated directory.
Then run `rustlings` to get started.";

View file

@ -10,14 +10,9 @@ use std::{
io::{self, StdoutLock, Write},
};
use crate::{
app_state::AppState,
exercise::Exercise,
term::{progress_bar, terminal_file_link, CountedWrite, MaxLenWriter},
MAX_EXERCISE_NAME_LEN,
};
use crate::{app_state::AppState, exercise::Exercise, term::progress_bar, MAX_EXERCISE_NAME_LEN};
const MAX_SCROLL_PADDING: usize = 5;
const MAX_SCROLL_PADDING: usize = 8;
// +1 for column padding.
const SPACE: &[u8] = &[b' '; MAX_EXERCISE_NAME_LEN + 1];
@ -28,6 +23,14 @@ fn next_ln(stdout: &mut StdoutLock) -> io::Result<()> {
Ok(())
}
// 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)
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Filter {
Done,
@ -156,44 +159,40 @@ impl<'a> ListState<'a> {
.skip(self.row_offset)
.take(self.max_n_rows_to_display)
{
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
if self.selected_row == Some(self.row_offset + n_displayed_rows) {
writer.stdout.queue(SetBackgroundColor(Color::Rgb {
r: 40,
g: 40,
b: 40,
stdout.queue(SetBackgroundColor(Color::Rgb {
r: 50,
g: 50,
b: 50,
}))?;
// The crab emoji has the width of two ascii chars.
writer.add_to_len(2);
writer.stdout.write_all("🦀".as_bytes())?;
stdout.write_all("🦀".as_bytes())?;
} else {
writer.write_ascii(b" ")?;
stdout.write_all(b" ")?;
}
if exercise_ind == current_exercise_ind {
writer.stdout.queue(SetForegroundColor(Color::Red))?;
writer.write_ascii(b">>>>>>> ")?;
stdout.queue(SetForegroundColor(Color::Red))?;
stdout.write_all(b">>>>>>> ")?;
} else {
writer.write_ascii(b" ")?;
stdout.write_all(b" ")?;
}
if exercise.done {
writer.stdout.queue(SetForegroundColor(Color::Green))?;
writer.write_ascii(b"DONE ")?;
stdout.queue(SetForegroundColor(Color::Yellow))?;
stdout.write_all(b"DONE ")?;
} else {
writer.stdout.queue(SetForegroundColor(Color::Yellow))?;
writer.write_ascii(b"PENDING ")?;
stdout.queue(SetForegroundColor(Color::Green))?;
stdout.write_all(b"PENDING ")?;
}
writer.stdout.queue(SetForegroundColor(Color::Reset))?;
stdout.queue(SetForegroundColor(Color::Reset))?;
writer.write_str(exercise.name)?;
writer.write_ascii(&SPACE[..self.name_col_width + 2 - exercise.name.len()])?;
stdout.write_all(exercise.name.as_bytes())?;
stdout.write_all(&SPACE[..self.name_col_width + 2 - exercise.name.len()])?;
terminal_file_link(&mut writer, exercise.path, Color::Blue)?;
stdout.write_all(exercise.path.as_bytes())?;
next_ln(stdout)?;
next_ln_overwrite(stdout)?;
stdout.queue(ResetColor)?;
n_displayed_rows += 1;
}
@ -209,11 +208,10 @@ impl<'a> ListState<'a> {
stdout.queue(BeginSynchronizedUpdate)?.queue(MoveTo(0, 0))?;
// Header
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
writer.write_ascii(b" Current State Name")?;
writer.write_ascii(&SPACE[..self.name_col_width - 2])?;
writer.write_ascii(b"Path")?;
next_ln(stdout)?;
stdout.write_all(b" Current State Name")?;
stdout.write_all(&SPACE[..self.name_col_width - 2])?;
stdout.write_all(b"Path")?;
next_ln_overwrite(stdout)?;
// Rows
let iter = self.app_state.exercises().iter().enumerate();
@ -234,7 +232,7 @@ impl<'a> ListState<'a> {
next_ln(stdout)?;
progress_bar(
&mut MaxLenWriter::new(stdout, self.term_width as usize),
stdout,
self.app_state.n_done(),
self.app_state.exercises().len() as u16,
self.term_width,
@ -244,55 +242,59 @@ impl<'a> ListState<'a> {
stdout.write_all(&self.separator_line)?;
next_ln(stdout)?;
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
if self.message.is_empty() {
// Help footer message
if self.selected_row.is_some() {
writer.write_str("↓/j ↑/k home/g end/G | <c>ontinue at | <r>eset exercise")?;
stdout.write_all(
"↓/j ↑/k home/g end/G | <c>ontinue at | <r>eset exercise".as_bytes(),
)?;
if self.narrow_term {
next_ln(stdout)?;
writer = MaxLenWriter::new(stdout, self.term_width as usize);
writer.write_ascii(b"filter ")?;
next_ln_overwrite(stdout)?;
stdout.write_all(b"filter ")?;
} else {
writer.write_ascii(b" | filter ")?;
stdout.write_all(b" | filter ")?;
}
} else {
// Nothing selected (and nothing shown), so only display filter and quit.
writer.write_ascii(b"filter ")?;
stdout.write_all(b"filter ")?;
}
match self.filter {
Filter::Done => {
writer
.stdout
stdout
.queue(SetForegroundColor(Color::Magenta))?
.queue(SetAttribute(Attribute::Underlined))?;
writer.write_ascii(b"<d>one")?;
writer.stdout.queue(ResetColor)?;
writer.write_ascii(b"/<p>ending")?;
stdout.write_all(b"<d>one")?;
stdout.queue(ResetColor)?;
stdout.write_all(b"/<p>ending")?;
}
Filter::Pending => {
writer.write_ascii(b"<d>one/")?;
writer
.stdout
stdout.write_all(b"<d>one/")?;
stdout
.queue(SetForegroundColor(Color::Magenta))?
.queue(SetAttribute(Attribute::Underlined))?;
writer.write_ascii(b"<p>ending")?;
writer.stdout.queue(ResetColor)?;
stdout.write_all(b"<p>ending")?;
stdout.queue(ResetColor)?;
}
Filter::None => writer.write_ascii(b"<d>one/<p>ending")?,
Filter::None => stdout.write_all(b"<d>one/<p>ending")?,
}
writer.write_ascii(b" | <q>uit list")?;
} else {
writer.stdout.queue(SetForegroundColor(Color::Magenta))?;
writer.write_str(&self.message)?;
stdout.queue(ResetColor)?;
next_ln(stdout)?;
}
stdout.write_all(b" | <q>uit list")?;
next_ln(stdout)?;
if self.narrow_term {
next_ln_overwrite(stdout)?;
} else {
next_ln(stdout)?;
}
} else {
stdout.queue(SetForegroundColor(Color::Magenta))?;
stdout.write_all(self.message.as_bytes())?;
stdout.queue(ResetColor)?;
next_ln_overwrite(stdout)?;
if self.narrow_term {
next_ln(stdout)?;
}
}
}
stdout.queue(EndSynchronizedUpdate)?.flush()

View file

@ -22,6 +22,7 @@ mod init;
mod list;
mod run;
mod term;
mod terminal_link;
mod watch;
const CURRENT_FORMAT_VERSION: u8 = 1;

View file

@ -1,17 +1,11 @@
use anyhow::Result;
use crossterm::{
style::{Color, ResetColor, SetForegroundColor},
QueueableCommand,
};
use std::{
io::{self, Write},
process::exit,
};
use anyhow::{bail, Result};
use crossterm::style::{style, Stylize};
use std::io::{self, Write};
use crate::{
app_state::{AppState, ExercisesProgress},
exercise::{solution_link_line, RunnableExercise, OUTPUT_CAPACITY},
term::terminal_file_link,
exercise::{RunnableExercise, OUTPUT_CAPACITY},
terminal_link::TerminalFileLink,
};
pub fn run(app_state: &mut AppState) -> Result<()> {
@ -25,31 +19,35 @@ pub fn run(app_state: &mut AppState) -> Result<()> {
if !success {
app_state.set_pending(app_state.current_exercise_ind())?;
stdout.write_all(b"Ran ")?;
terminal_file_link(&mut stdout, app_state.current_exercise().path, Color::Blue)?;
stdout.write_all(b" with errors\n")?;
exit(1);
bail!(
"Ran {} with errors",
app_state.current_exercise().terminal_link(),
);
}
stdout.queue(SetForegroundColor(Color::Green))?;
stdout.write_all("✓ Successfully ran ".as_bytes())?;
stdout.write_all(exercise.path.as_bytes())?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n")?;
writeln!(
stdout,
"{}{}",
"✓ Successfully ran ".green(),
exercise.path.green(),
)?;
if let Some(solution_path) = app_state.current_solution_path()? {
stdout.write_all(b"\n")?;
solution_link_line(&mut stdout, &solution_path)?;
stdout.write_all(b"\n")?;
writeln!(
stdout,
"\n{} for comparison: {}\n",
"Solution".bold(),
style(TerminalFileLink(&solution_path)).underlined().cyan(),
)?;
}
match app_state.done_current_exercise(&mut stdout)? {
ExercisesProgress::CurrentPending | ExercisesProgress::NewPending => {
stdout.write_all(b"Next exercise: ")?;
terminal_file_link(&mut stdout, app_state.current_exercise().path, Color::Blue)?;
stdout.write_all(b"\n")?;
}
ExercisesProgress::AllDone => (),
ExercisesProgress::CurrentPending | ExercisesProgress::NewPending => writeln!(
stdout,
"Next exercise: {}",
app_state.current_exercise().terminal_link(),
)?,
}
Ok(())

View file

@ -1,99 +1,15 @@
use std::{
cell::Cell,
env, fmt, fs,
io::{self, BufRead, StdoutLock, Write},
};
use std::io::{self, BufRead, StdoutLock, Write};
use crossterm::{
cursor::MoveTo,
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
style::{Color, ResetColor, SetForegroundColor},
terminal::{Clear, ClearType},
Command, QueueableCommand,
QueueableCommand,
};
thread_local! {
static VS_CODE: Cell<bool> = Cell::new(env::var_os("TERM_PROGRAM").is_some_and(|v| v == "vscode"));
}
pub struct MaxLenWriter<'a, 'b> {
pub stdout: &'a mut StdoutLock<'b>,
len: usize,
max_len: usize,
}
impl<'a, 'b> MaxLenWriter<'a, 'b> {
#[inline]
pub fn new(stdout: &'a mut StdoutLock<'b>, max_len: usize) -> Self {
Self {
stdout,
len: 0,
max_len,
}
}
// Additional is for emojis that take more space.
#[inline]
pub fn add_to_len(&mut self, additional: usize) {
self.len += additional;
}
}
pub trait CountedWrite<'a> {
fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()>;
fn write_str(&mut self, unicode: &str) -> io::Result<()>;
fn stdout(&mut self) -> &mut StdoutLock<'a>;
}
impl<'a, 'b> CountedWrite<'b> for MaxLenWriter<'a, 'b> {
fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()> {
let n = ascii.len().min(self.max_len.saturating_sub(self.len));
if n > 0 {
self.stdout.write_all(&ascii[..n])?;
self.len += n;
}
Ok(())
}
fn write_str(&mut self, unicode: &str) -> io::Result<()> {
if let Some((ind, c)) = unicode
.char_indices()
.take(self.max_len.saturating_sub(self.len))
.last()
{
self.stdout
.write_all(&unicode.as_bytes()[..ind + c.len_utf8()])?;
self.len += ind + 1;
}
Ok(())
}
#[inline]
fn stdout(&mut self) -> &mut StdoutLock<'b> {
self.stdout
}
}
impl<'a> CountedWrite<'a> for StdoutLock<'a> {
#[inline]
fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()> {
self.write_all(ascii)
}
#[inline]
fn write_str(&mut self, unicode: &str) -> io::Result<()> {
self.write_all(unicode.as_bytes())
}
#[inline]
fn stdout(&mut self) -> &mut StdoutLock<'a> {
self
}
}
/// Terminal progress bar to be used when not using Ratataui.
pub fn progress_bar<'a>(
writer: &mut impl CountedWrite<'a>,
pub fn progress_bar(
stdout: &mut StdoutLock,
progress: u16,
total: u16,
line_width: u16,
@ -108,13 +24,9 @@ pub fn progress_bar<'a>(
const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4;
if line_width < MIN_LINE_WIDTH {
writer.write_ascii(b"Progress: ")?;
// Integers are in ASCII.
writer.write_ascii(format!("{progress}/{total}").as_bytes())?;
return writer.write_ascii(b" exercises");
return write!(stdout, "Progress: {progress}/{total} exercises");
}
let stdout = writer.stdout();
stdout.write_all(PREFIX)?;
let width = line_width - WRAPPER_WIDTH;
@ -156,58 +68,3 @@ pub fn press_enter_prompt(stdout: &mut StdoutLock) -> io::Result<()> {
stdout.write_all(b"\n")?;
Ok(())
}
pub fn terminal_file_link<'a>(
writer: &mut impl CountedWrite<'a>,
path: &str,
color: Color,
) -> io::Result<()> {
// VS Code shows its own links. This also avoids some issues, especially on Windows.
if VS_CODE.get() {
return writer.write_str(path);
}
let canonical_path = fs::canonicalize(path).ok();
let Some(canonical_path) = canonical_path.as_deref().and_then(|p| p.to_str()) else {
return writer.write_str(path);
};
// Windows itself can't handle its verbatim paths.
#[cfg(windows)]
let canonical_path = if canonical_path.len() > 5 && &canonical_path[0..4] == r"\\?\" {
&canonical_path[4..]
} else {
canonical_path
};
writer
.stdout()
.queue(SetForegroundColor(color))?
.queue(SetAttribute(Attribute::Underlined))?;
writer.stdout().write_all(b"\x1b]8;;file://")?;
writer.stdout().write_all(canonical_path.as_bytes())?;
writer.stdout().write_all(b"\x1b\\")?;
// Only this part is visible.
writer.write_str(path)?;
writer.stdout().write_all(b"\x1b]8;;\x1b\\")?;
writer
.stdout()
.queue(SetForegroundColor(Color::Reset))?
.queue(SetAttribute(Attribute::NoUnderline))?;
Ok(())
}
pub fn write_ansi(output: &mut Vec<u8>, command: impl Command) {
struct FmtWriter<'a>(&'a mut Vec<u8>);
impl fmt::Write for FmtWriter<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0.extend_from_slice(s.as_bytes());
Ok(())
}
}
let _ = command.write_ansi(&mut FmtWriter(output));
}

26
src/terminal_link.rs Normal file
View file

@ -0,0 +1,26 @@
use std::{
fmt::{self, Display, Formatter},
fs,
};
pub struct TerminalFileLink<'a>(pub &'a str);
impl<'a> Display for TerminalFileLink<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let path = fs::canonicalize(self.0);
if let Some(path) = path.as_deref().ok().and_then(|path| path.to_str()) {
// Windows itself can't handle its verbatim paths.
#[cfg(windows)]
let path = if path.len() > 5 && &path[0..4] == r"\\?\" {
&path[4..]
} else {
path
};
write!(f, "\x1b]8;;file://{path}\x1b\\{}\x1b]8;;\x1b\\", self.0)
} else {
write!(f, "{}", self.0)
}
}
}

View file

@ -72,32 +72,35 @@ pub fn watch(
let mut watch_state = WatchState::new(app_state, manual_run);
let mut stdout = io::stdout().lock();
watch_state.run_current_exercise(&mut stdout)?;
watch_state.run_current_exercise()?;
thread::spawn(move || terminal_event_handler(tx, manual_run));
while let Ok(event) = rx.recv() {
match event {
WatchEvent::Input(InputEvent::Next) => match watch_state.next_exercise(&mut stdout)? {
WatchEvent::Input(InputEvent::Next) => match watch_state.next_exercise()? {
ExercisesProgress::AllDone => break,
ExercisesProgress::CurrentPending => watch_state.render(&mut stdout)?,
ExercisesProgress::NewPending => watch_state.run_current_exercise(&mut stdout)?,
ExercisesProgress::CurrentPending => watch_state.render()?,
ExercisesProgress::NewPending => watch_state.run_current_exercise()?,
},
WatchEvent::Input(InputEvent::Hint) => watch_state.show_hint(&mut stdout)?,
WatchEvent::Input(InputEvent::Hint) => {
watch_state.show_hint()?;
}
WatchEvent::Input(InputEvent::List) => {
return Ok(WatchExit::List);
}
WatchEvent::Input(InputEvent::Quit) => {
stdout.write_all(QUIT_MSG)?;
watch_state.into_writer().write_all(QUIT_MSG)?;
break;
}
WatchEvent::Input(InputEvent::Run) => watch_state.run_current_exercise(&mut stdout)?,
WatchEvent::Input(InputEvent::Unrecognized) => watch_state.render(&mut stdout)?,
WatchEvent::Input(InputEvent::Run) => watch_state.run_current_exercise()?,
WatchEvent::Input(InputEvent::Unrecognized) => watch_state.render()?,
WatchEvent::FileChange { exercise_ind } => {
watch_state.handle_file_change(exercise_ind, &mut stdout)?;
watch_state.handle_file_change(exercise_ind)?;
}
WatchEvent::TerminalResize => {
watch_state.render()?;
}
WatchEvent::TerminalResize => watch_state.render(&mut stdout)?,
WatchEvent::NotifyErr(e) => {
return Err(Error::from(e).context(NOTIFY_ERR));
}

View file

@ -1,17 +1,16 @@
use anyhow::Result;
use crossterm::{
style::{
Attribute, Attributes, Color, ResetColor, SetAttribute, SetAttributes, SetForegroundColor,
},
terminal, QueueableCommand,
style::{style, Stylize},
terminal,
};
use std::io::{self, StdoutLock, Write};
use crate::{
app_state::{AppState, ExercisesProgress},
clear_terminal,
exercise::{solution_link_line, RunnableExercise, OUTPUT_CAPACITY},
term::{progress_bar, terminal_file_link},
exercise::{RunnableExercise, OUTPUT_CAPACITY},
term::progress_bar,
terminal_link::TerminalFileLink,
};
#[derive(PartialEq, Eq)]
@ -22,6 +21,7 @@ enum DoneStatus {
}
pub struct WatchState<'a> {
writer: StdoutLock<'a>,
app_state: &'a mut AppState,
output: Vec<u8>,
show_hint: bool,
@ -31,7 +31,10 @@ pub struct WatchState<'a> {
impl<'a> WatchState<'a> {
pub fn new(app_state: &'a mut AppState, manual_run: bool) -> Self {
let writer = io::stdout().lock();
Self {
writer,
app_state,
output: Vec::with_capacity(OUTPUT_CAPACITY),
show_hint: false,
@ -40,11 +43,16 @@ impl<'a> WatchState<'a> {
}
}
pub fn run_current_exercise(&mut self, stdout: &mut StdoutLock) -> Result<()> {
#[inline]
pub fn into_writer(self) -> StdoutLock<'a> {
self.writer
}
pub fn run_current_exercise(&mut self) -> Result<()> {
self.show_hint = false;
writeln!(
stdout,
self.writer,
"\nChecking the exercise `{}`. Please wait…",
self.app_state.current_exercise().name,
)?;
@ -68,15 +76,11 @@ impl<'a> WatchState<'a> {
self.done_status = DoneStatus::Pending;
}
self.render(stdout)?;
self.render()?;
Ok(())
}
pub fn handle_file_change(
&mut self,
exercise_ind: usize,
stdout: &mut StdoutLock,
) -> Result<()> {
pub fn handle_file_change(&mut self, exercise_ind: usize) -> Result<()> {
// Don't skip exercises on file changes to avoid confusion from missing exercises.
// Skipping exercises must be explicit in the interactive list.
// But going back to an earlier exercise on file change is fine.
@ -85,115 +89,92 @@ impl<'a> WatchState<'a> {
}
self.app_state.set_current_exercise_ind(exercise_ind)?;
self.run_current_exercise(stdout)
self.run_current_exercise()
}
/// Move on to the next exercise if the current one is done.
pub fn next_exercise(&mut self, stdout: &mut StdoutLock) -> Result<ExercisesProgress> {
pub fn next_exercise(&mut self) -> Result<ExercisesProgress> {
if self.done_status == DoneStatus::Pending {
return Ok(ExercisesProgress::CurrentPending);
}
self.app_state.done_current_exercise(stdout)
self.app_state.done_current_exercise(&mut self.writer)
}
fn show_prompt(&self, stdout: &mut StdoutLock) -> io::Result<()> {
fn show_prompt(&mut self) -> io::Result<()> {
self.writer.write_all(b"\n")?;
if self.manual_run {
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"r")?;
stdout.queue(ResetColor)?;
stdout.write_all(b":run / ")?;
write!(self.writer, "{}:run / ", 'r'.bold())?;
}
if self.done_status != DoneStatus::Pending {
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"n")?;
stdout.queue(ResetColor)?;
stdout.write_all(b":")?;
stdout.queue(SetAttribute(Attribute::Underlined))?;
stdout.write_all(b"next")?;
stdout.queue(ResetColor)?;
stdout.write_all(b" / ")?;
write!(self.writer, "{}:{} / ", 'n'.bold(), "next".underlined())?;
}
if !self.show_hint {
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"h")?;
stdout.queue(ResetColor)?;
stdout.write_all(b":hint / ")?;
write!(self.writer, "{}:hint / ", 'h'.bold())?;
}
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"l")?;
stdout.queue(ResetColor)?;
stdout.write_all(b":list / ")?;
write!(self.writer, "{}:list / {}:quit ? ", 'l'.bold(), 'q'.bold())?;
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"q")?;
stdout.queue(ResetColor)?;
stdout.write_all(b":quit ? ")?;
stdout.flush()
self.writer.flush()
}
pub fn render(&self, stdout: &mut StdoutLock) -> io::Result<()> {
pub fn render(&mut self) -> io::Result<()> {
// Prevent having the first line shifted if clearing wasn't successful.
stdout.write_all(b"\n")?;
clear_terminal(stdout)?;
self.writer.write_all(b"\n")?;
clear_terminal(&mut self.writer)?;
stdout.write_all(&self.output)?;
self.writer.write_all(&self.output)?;
if self.show_hint {
stdout
.queue(SetAttributes(
Attributes::from(Attribute::Bold).with(Attribute::Underlined),
))?
.queue(SetForegroundColor(Color::Cyan))?;
stdout.write_all(b"Hint")?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n")?;
stdout.write_all(self.app_state.current_exercise().hint.as_bytes())?;
stdout.write_all(b"\n\n")?;
writeln!(
self.writer,
"{}\n{}\n",
"Hint".bold().cyan().underlined(),
self.app_state.current_exercise().hint,
)?;
}
if self.done_status != DoneStatus::Pending {
stdout
.queue(SetAttribute(Attribute::Bold))?
.queue(SetForegroundColor(Color::Green))?;
stdout.write_all("Exercise done ✓".as_bytes())?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n")?;
writeln!(self.writer, "{}", "Exercise done ✓".bold().green())?;
if let DoneStatus::DoneWithSolution(solution_path) = &self.done_status {
solution_link_line(stdout, solution_path)?;
writeln!(
self.writer,
"{} for comparison: {}",
"Solution".bold(),
style(TerminalFileLink(solution_path)).underlined().cyan(),
)?;
}
stdout.write_all(
"When done experimenting, enter `n` to move on to the next exercise 🦀\n\n"
.as_bytes(),
writeln!(
self.writer,
"When done experimenting, enter `n` to move on to the next exercise 🦀\n",
)?;
}
let line_width = terminal::size()?.0;
progress_bar(
stdout,
&mut self.writer,
self.app_state.n_done(),
self.app_state.exercises().len() as u16,
line_width,
)?;
writeln!(
self.writer,
"\nCurrent exercise: {}",
self.app_state.current_exercise().terminal_link(),
)?;
stdout.write_all(b"\nCurrent exercise: ")?;
terminal_file_link(stdout, self.app_state.current_exercise().path, Color::Blue)?;
stdout.write_all(b"\n\n")?;
self.show_prompt(stdout)?;
self.show_prompt()?;
Ok(())
}
pub fn show_hint(&mut self, stdout: &mut StdoutLock) -> io::Result<()> {
pub fn show_hint(&mut self) -> io::Result<()> {
self.show_hint = true;
self.render(stdout)
self.render()
}
}