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] [workspace.lints.clippy]
empty_loop = "forbid" empty_loop = "forbid"
disallowed-types = "deny"
disallowed-methods = "deny"
infinite_loop = "deny" infinite_loop = "deny"
mem_forget = "deny" mem_forget = "deny"
dbg_macro = "warn" 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. /// 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 /// 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. /// 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]; let exercise = &mut self.exercises[self.current_exercise_ind];
if !exercise.done { if !exercise.done {
exercise.done = true; exercise.done = true;
@ -350,7 +350,7 @@ impl AppState {
return Ok(ExercisesProgress::NewPending); return Ok(ExercisesProgress::NewPending);
} }
writer.write_all(RERUNNING_ALL_EXERCISES_MSG)?; stdout.write_all(RERUNNING_ALL_EXERCISES_MSG)?;
let n_exercises = self.exercises.len(); let n_exercises = self.exercises.len();
@ -368,12 +368,12 @@ impl AppState {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for (exercise_ind, handle) in handles.into_iter().enumerate() { for (exercise_ind, handle) in handles.into_iter().enumerate() {
write!(writer, "\rProgress: {exercise_ind}/{n_exercises}")?; write!(stdout, "\rProgress: {exercise_ind}/{n_exercises}")?;
writer.flush()?; stdout.flush()?;
let success = handle.join().unwrap()?; let success = handle.join().unwrap()?;
if !success { if !success {
writer.write_all(b"\n\n")?; stdout.write_all(b"\n\n")?;
return Ok(Some(exercise_ind)); return Ok(Some(exercise_ind));
} }
} }
@ -395,13 +395,13 @@ impl AppState {
// Write that the last exercise is done. // Write that the last exercise is done.
self.write()?; self.write()?;
clear_terminal(writer)?; clear_terminal(stdout)?;
writer.write_all(FENISH_LINE.as_bytes())?; stdout.write_all(FENISH_LINE.as_bytes())?;
let final_message = self.final_message.trim_ascii(); let final_message = self.final_message.trim_ascii();
if !final_message.is_empty() { if !final_message.is_empty() {
writer.write_all(final_message.as_bytes())?; stdout.write_all(final_message.as_bytes())?;
writer.write_all(b"\n")?; stdout.write_all(b"\n")?;
} }
Ok(ExercisesProgress::AllDone) Ok(ExercisesProgress::AllDone)

View file

@ -1,15 +1,27 @@
use anyhow::Result; use anyhow::Result;
use crossterm::style::{style, StyledContent, Stylize}; use crossterm::{
use std::{ style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
fmt::{self, Display, Formatter}, QueueableCommand,
io::Write,
}; };
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. /// The initial capacity of the output buffer.
pub const OUTPUT_CAPACITY: usize = 1 << 14; 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. // Run an exercise binary and append its output to the `output` buffer.
// Compilation must be done before calling this method. // Compilation must be done before calling this method.
fn run_bin( fn run_bin(
@ -18,7 +30,10 @@ fn run_bin(
cmd_runner: &CmdRunner, cmd_runner: &CmdRunner,
) -> Result<bool> { ) -> Result<bool> {
if let Some(output) = output.as_deref_mut() { 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())?; 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. // This output is important to show the user that something went wrong.
// Otherwise, calling something like `exit(1)` in an exercise without further output // Otherwise, calling something like `exit(1)` in an exercise without further output
// leaves the user confused about why the exercise isn't done yet. // leaves the user confused about why the exercise isn't done yet.
writeln!( write_ansi(output, SetAttribute(Attribute::Bold));
output, write_ansi(output, SetForegroundColor(Color::Red));
"{}", output.extend_from_slice(b"The exercise didn't run successfully (nonzero exit code)");
"The exercise didn't run successfully (nonzero exit code)" write_ansi(output, ResetColor);
.bold() output.push(b'\n');
.red(),
)?;
} }
} }
@ -53,18 +66,6 @@ pub struct Exercise {
pub done: bool, 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 { pub trait RunnableExercise {
fn name(&self) -> &str; fn name(&self) -> &str;
fn strict_clippy(&self) -> bool; fn strict_clippy(&self) -> bool;

View file

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

View file

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

View file

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

View file

@ -1,11 +1,17 @@
use anyhow::{bail, Result}; use anyhow::Result;
use crossterm::style::{style, Stylize}; use crossterm::{
use std::io::{self, Write}; style::{Color, ResetColor, SetForegroundColor},
QueueableCommand,
};
use std::{
io::{self, Write},
process::exit,
};
use crate::{ use crate::{
app_state::{AppState, ExercisesProgress}, app_state::{AppState, ExercisesProgress},
exercise::{RunnableExercise, OUTPUT_CAPACITY}, exercise::{solution_link_line, RunnableExercise, OUTPUT_CAPACITY},
terminal_link::TerminalFileLink, term::terminal_file_link,
}; };
pub fn run(app_state: &mut AppState) -> Result<()> { pub fn run(app_state: &mut AppState) -> Result<()> {
@ -19,35 +25,31 @@ pub fn run(app_state: &mut AppState) -> Result<()> {
if !success { if !success {
app_state.set_pending(app_state.current_exercise_ind())?; app_state.set_pending(app_state.current_exercise_ind())?;
bail!( stdout.write_all(b"Ran ")?;
"Ran {} with errors", terminal_file_link(&mut stdout, app_state.current_exercise().path, Color::Blue)?;
app_state.current_exercise().terminal_link(), stdout.write_all(b" with errors\n")?;
); exit(1);
} }
writeln!( stdout.queue(SetForegroundColor(Color::Green))?;
stdout, stdout.write_all("✓ Successfully ran ".as_bytes())?;
"{}{}", stdout.write_all(exercise.path.as_bytes())?;
"✓ Successfully ran ".green(), stdout.queue(ResetColor)?;
exercise.path.green(), stdout.write_all(b"\n")?;
)?;
if let Some(solution_path) = app_state.current_solution_path()? { if let Some(solution_path) = app_state.current_solution_path()? {
writeln!( stdout.write_all(b"\n")?;
stdout, solution_link_line(&mut stdout, &solution_path)?;
"\n{} for comparison: {}\n", stdout.write_all(b"\n")?;
"Solution".bold(),
style(TerminalFileLink(&solution_path)).underlined().cyan(),
)?;
} }
match app_state.done_current_exercise(&mut stdout)? { 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::AllDone => (),
ExercisesProgress::CurrentPending | ExercisesProgress::NewPending => writeln!(
stdout,
"Next exercise: {}",
app_state.current_exercise().terminal_link(),
)?,
} }
Ok(()) 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::{ use crossterm::{
cursor::MoveTo, cursor::MoveTo,
style::{Color, ResetColor, SetForegroundColor}, style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
terminal::{Clear, ClearType}, 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. /// Terminal progress bar to be used when not using Ratataui.
pub fn progress_bar( pub fn progress_bar<'a>(
stdout: &mut StdoutLock, writer: &mut impl CountedWrite<'a>,
progress: u16, progress: u16,
total: u16, total: u16,
line_width: u16, line_width: u16,
@ -24,9 +108,13 @@ pub fn progress_bar(
const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4; const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4;
if line_width < MIN_LINE_WIDTH { 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)?; stdout.write_all(PREFIX)?;
let width = line_width - WRAPPER_WIDTH; 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")?; stdout.write_all(b"\n")?;
Ok(()) 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); 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)); thread::spawn(move || terminal_event_handler(tx, manual_run));
while let Ok(event) = rx.recv() { while let Ok(event) = rx.recv() {
match event { 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::AllDone => break,
ExercisesProgress::CurrentPending => watch_state.render()?, ExercisesProgress::CurrentPending => watch_state.render(&mut stdout)?,
ExercisesProgress::NewPending => watch_state.run_current_exercise()?, ExercisesProgress::NewPending => watch_state.run_current_exercise(&mut stdout)?,
}, },
WatchEvent::Input(InputEvent::Hint) => { WatchEvent::Input(InputEvent::Hint) => watch_state.show_hint(&mut stdout)?,
watch_state.show_hint()?;
}
WatchEvent::Input(InputEvent::List) => { WatchEvent::Input(InputEvent::List) => {
return Ok(WatchExit::List); return Ok(WatchExit::List);
} }
WatchEvent::Input(InputEvent::Quit) => { WatchEvent::Input(InputEvent::Quit) => {
watch_state.into_writer().write_all(QUIT_MSG)?; stdout.write_all(QUIT_MSG)?;
break; break;
} }
WatchEvent::Input(InputEvent::Run) => watch_state.run_current_exercise()?, WatchEvent::Input(InputEvent::Run) => watch_state.run_current_exercise(&mut stdout)?,
WatchEvent::Input(InputEvent::Unrecognized) => watch_state.render()?, WatchEvent::Input(InputEvent::Unrecognized) => watch_state.render(&mut stdout)?,
WatchEvent::FileChange { exercise_ind } => { WatchEvent::FileChange { exercise_ind } => {
watch_state.handle_file_change(exercise_ind)?; watch_state.handle_file_change(exercise_ind, &mut stdout)?;
}
WatchEvent::TerminalResize => {
watch_state.render()?;
} }
WatchEvent::TerminalResize => watch_state.render(&mut stdout)?,
WatchEvent::NotifyErr(e) => { WatchEvent::NotifyErr(e) => {
return Err(Error::from(e).context(NOTIFY_ERR)); return Err(Error::from(e).context(NOTIFY_ERR));
} }

View file

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