Compare commits

..

13 commits

Author SHA1 Message Date
mo8it 74388d4bf4 Only trigger write when needed 2024-08-26 04:41:26 +02:00
mo8it e811dd15b5 Fix list on terminals that don't disable line wrapping 2024-08-26 04:29:58 +02:00
mo8it f22700a4ec Use the correct environment variable 2024-08-26 02:43:08 +02:00
mo8it ee25a7d458 Disable terminal links in VS-Code 2024-08-26 02:41:22 +02:00
mo8it 594e212b8a Darker highlighting in the list 2024-08-26 00:53:42 +02:00
mo8it 5c355468c1 File link in the list? No problem :D 2024-08-26 00:49:56 +02:00
mo8it d1571d18f9 Only reset color and underline after link 2024-08-26 00:48:12 +02:00
mo8it cb86b44dea LOL, swapped colors 2024-08-26 00:40:30 +02:00
mo8it 833e6e0c92 Newline after resetting attributes 2024-08-26 00:24:39 +02:00
mo8it 159273e532 Take stdout as argument in watch mode 2024-08-26 00:09:04 +02:00
mo8it 631f2db1a3 Lower the maximum scroll padding 2024-08-25 23:54:18 +02:00
mo8it a1f0eaab54 Add disallowed types and methods in Clippy 2024-08-25 23:54:04 +02:00
mo8it b1898f6d8b Use queue instead of Stylize 2024-08-25 23:53:50 +02:00
12 changed files with 390 additions and 236 deletions

View file

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

13
clippy.toml Normal file
View file

@ -0,0 +1,13 @@
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, writer: &mut StdoutLock) -> Result<ExercisesProgress> {
pub fn done_current_exercise(&mut self, stdout: &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);
}
writer.write_all(RERUNNING_ALL_EXERCISES_MSG)?;
stdout.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!(writer, "\rProgress: {exercise_ind}/{n_exercises}")?;
writer.flush()?;
write!(stdout, "\rProgress: {exercise_ind}/{n_exercises}")?;
stdout.flush()?;
let success = handle.join().unwrap()?;
if !success {
writer.write_all(b"\n\n")?;
stdout.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(writer)?;
writer.write_all(FENISH_LINE.as_bytes())?;
clear_terminal(stdout)?;
stdout.write_all(FENISH_LINE.as_bytes())?;
let final_message = self.final_message.trim_ascii();
if !final_message.is_empty() {
writer.write_all(final_message.as_bytes())?;
writer.write_all(b"\n")?;
stdout.write_all(final_message.as_bytes())?;
stdout.write_all(b"\n")?;
}
Ok(ExercisesProgress::AllDone)

View file

@ -1,15 +1,27 @@
use anyhow::Result;
use crossterm::style::{style, StyledContent, Stylize};
use std::{
fmt::{self, Display, Formatter},
io::Write,
use crossterm::{
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
QueueableCommand,
};
use std::io::{self, StdoutLock, Write};
use crate::{cmd::CmdRunner, terminal_link::TerminalFileLink};
use crate::{
cmd::CmdRunner,
term::{terminal_file_link, write_ansi},
};
/// 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(
@ -18,7 +30,10 @@ fn run_bin(
cmd_runner: &CmdRunner,
) -> Result<bool> {
if let Some(output) = output.as_deref_mut() {
writeln!(output, "{}", "Output".underlined())?;
write_ansi(output, SetAttribute(Attribute::Underlined));
output.extend_from_slice(b"Output");
write_ansi(output, ResetColor);
output.push(b'\n');
}
let success = cmd_runner.run_debug_bin(bin_name, output.as_deref_mut())?;
@ -28,13 +43,11 @@ 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.
writeln!(
output,
"{}",
"The exercise didn't run successfully (nonzero exit code)"
.bold()
.red(),
)?;
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');
}
}
@ -53,18 +66,6 @@ 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,5 +1,8 @@
use anyhow::{bail, Context, Result};
use crossterm::style::Stylize;
use crossterm::{
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
QueueableCommand,
};
use serde::Deserialize;
use std::{
env::set_current_dir,
@ -144,12 +147,14 @@ pub fn init() -> Result<()> {
.status();
}
writeln!(
stdout,
"{}\n\n{}",
"Initialization done ✓".green(),
POST_INIT_MSG.bold(),
)?;
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)?;
Ok(())
}
@ -182,5 +187,6 @@ You probably already initialized Rustlings.
Run `cd rustlings`
Then run `rustlings` again";
const POST_INIT_MSG: &str = "Run `cd rustlings` to go into the generated directory.
Then run `rustlings` to get started.";
const POST_INIT_MSG: &[u8] = b"Run `cd rustlings` to go into the generated directory.
Then run `rustlings` to get started.
";

View file

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

View file

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

View file

@ -1,11 +1,17 @@
use anyhow::{bail, Result};
use crossterm::style::{style, Stylize};
use std::io::{self, Write};
use anyhow::Result;
use crossterm::{
style::{Color, ResetColor, SetForegroundColor},
QueueableCommand,
};
use std::{
io::{self, Write},
process::exit,
};
use crate::{
app_state::{AppState, ExercisesProgress},
exercise::{RunnableExercise, OUTPUT_CAPACITY},
terminal_link::TerminalFileLink,
exercise::{solution_link_line, RunnableExercise, OUTPUT_CAPACITY},
term::terminal_file_link,
};
pub fn run(app_state: &mut AppState) -> Result<()> {
@ -19,35 +25,31 @@ pub fn run(app_state: &mut AppState) -> Result<()> {
if !success {
app_state.set_pending(app_state.current_exercise_ind())?;
bail!(
"Ran {} with errors",
app_state.current_exercise().terminal_link(),
);
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);
}
writeln!(
stdout,
"{}{}",
"✓ Successfully ran ".green(),
exercise.path.green(),
)?;
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")?;
if let Some(solution_path) = app_state.current_solution_path()? {
writeln!(
stdout,
"\n{} for comparison: {}\n",
"Solution".bold(),
style(TerminalFileLink(&solution_path)).underlined().cyan(),
)?;
stdout.write_all(b"\n")?;
solution_link_line(&mut stdout, &solution_path)?;
stdout.write_all(b"\n")?;
}
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,15 +1,99 @@
use std::io::{self, BufRead, StdoutLock, Write};
use std::{
cell::Cell,
env, fmt, fs,
io::{self, BufRead, StdoutLock, Write},
};
use crossterm::{
cursor::MoveTo,
style::{Color, ResetColor, SetForegroundColor},
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
terminal::{Clear, ClearType},
QueueableCommand,
Command, 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(
stdout: &mut StdoutLock,
pub fn progress_bar<'a>(
writer: &mut impl CountedWrite<'a>,
progress: u16,
total: u16,
line_width: u16,
@ -24,9 +108,13 @@ pub fn progress_bar(
const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4;
if line_width < MIN_LINE_WIDTH {
return write!(stdout, "Progress: {progress}/{total} exercises");
writer.write_ascii(b"Progress: ")?;
// Integers are in ASCII.
writer.write_ascii(format!("{progress}/{total}").as_bytes())?;
return writer.write_ascii(b" exercises");
}
let stdout = writer.stdout();
stdout.write_all(PREFIX)?;
let width = line_width - WRAPPER_WIDTH;
@ -68,3 +156,58 @@ 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));
}

View file

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

View file

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