use crate::app_state::AppState;
use crate::compiler::Compiler;
use crate::runner::{self, RunStatus};
use crate::term::{self, write_stdout};
use crate::view;
use crossterm::event::{self, Event, KeyCode, KeyModifiers};
use crossterm::terminal::{EnterAlternateScreen, LeaveAlternateScreen};
use notify_debouncer_mini::{new_debouncer, DebouncedEvent, DebouncedEventKind};
use std::io;
use std::path::Path;
use std::sync::mpsc;
use std::time::{Duration, SystemTime};
enum WatchEvent {
FileChanged,
Key(KeyCode),
Quit,
}
struct TerminalGuard {
alternate_screen: bool,
raw_mode: bool,
}
impl TerminalGuard {
fn enter() -> anyhow::Result<Self> {
let mut guard = Self {
alternate_screen: false,
raw_mode: false,
};
crossterm::execute!(io::stdout(), EnterAlternateScreen)?;
guard.alternate_screen = true;
crossterm::terminal::enable_raw_mode()?;
guard.raw_mode = true;
Ok(guard)
}
}
impl Drop for TerminalGuard {
fn drop(&mut self) {
if self.raw_mode {
let _ = crossterm::terminal::disable_raw_mode();
}
if self.alternate_screen {
let _ = crossterm::execute!(io::stdout(), LeaveAlternateScreen);
}
}
}
struct RawModeGuard;
impl RawModeGuard {
fn enter() -> anyhow::Result<Self> {
crossterm::terminal::enable_raw_mode()?;
Ok(Self)
}
}
impl Drop for RawModeGuard {
fn drop(&mut self) {
let _ = crossterm::terminal::disable_raw_mode();
}
}
fn current_exercise_mtime(state: &AppState) -> Option<SystemTime> {
state
.current_exercise()
.and_then(|e| e.path.metadata().ok())
.and_then(|m| m.modified().ok())
}
pub fn run_watch(
state: &mut AppState,
compiler: &Compiler,
exercises_dir: &Path,
build_dir: &Path,
welcome: Option<&str>,
) -> anyhow::Result<()> {
let (tx, rx) = mpsc::channel();
let mut hint_level: usize = 0;
let mut last_run_success;
let mut last_mtime = current_exercise_mtime(state);
let tx_fs = tx.clone();
let mut debouncer = new_debouncer(
Duration::from_millis(500),
move |res: Result<Vec<DebouncedEvent>, notify::Error>| {
if let Ok(events) = res {
for event in events {
if event.kind == DebouncedEventKind::Any {
let path_str = event.path.to_string_lossy().to_string();
if path_str.ends_with(".c") {
let _ = tx_fs.send(WatchEvent::FileChanged);
}
}
}
}
},
)?;
debouncer
.watcher()
.watch(exercises_dir, notify::RecursiveMode::Recursive)?;
if let Some(msg) = welcome {
write_stdout("\n")?;
for line in msg.lines() {
write_stdout(&format!(" {line}\n"))?;
}
write_stdout("\n")?;
write_stdout(&format!(
" cmetal v{} — compiler: {}\n",
env!("CARGO_PKG_VERSION"),
compiler.kind()
))?;
write_stdout("\n")?;
write_stdout(" Press any key to start...\n")?;
{
let _raw = RawModeGuard::enter()?;
let _ = event::read();
}
}
let _guard = TerminalGuard::enter()?;
print_watch_header(state, compiler)?;
last_run_success = run_current_exercise(state, compiler, build_dir);
print_watch_commands()?;
while rx.try_recv().is_ok() {}
let tx_key = tx.clone();
std::thread::spawn(move || loop {
if let Ok(Event::Key(key_event)) = event::read() {
if key_event.modifiers.contains(KeyModifiers::CONTROL)
&& key_event.code == KeyCode::Char('c')
{
let _ = tx_key.send(WatchEvent::Quit);
break;
}
let _ = tx_key.send(WatchEvent::Key(key_event.code));
}
});
loop {
match rx.recv() {
Ok(WatchEvent::FileChanged) => {
let new_mtime = current_exercise_mtime(state);
if new_mtime == last_mtime {
continue;
}
last_mtime = new_mtime;
term::clear_screen();
print_watch_header(state, compiler)?;
last_run_success = run_current_exercise(state, compiler, build_dir);
print_watch_commands()?;
while rx.try_recv().is_ok() {}
}
Ok(WatchEvent::Key(KeyCode::Char('n'))) => {
if last_run_success? {
if let Some(name) = state.current_exercise().map(|e| e.name().to_string()) {
state.mark_done(&name);
}
}
if state.all_done() {
term::clear_screen();
write_stdout("\r\n")?;
term::print_success("All exercises completed! Congratulations!")?;
write_stdout("\r\n")?;
break;
}
state.next_pending();
state.save()?;
hint_level = 0; last_mtime = current_exercise_mtime(state);
term::clear_screen();
print_watch_header(state, compiler)?;
last_run_success = run_current_exercise(state, compiler, build_dir);
print_watch_commands()?;
while rx.try_recv().is_ok() {}
}
Ok(WatchEvent::Key(KeyCode::Char('p'))) => {
if state.prev() {
state.save()?;
hint_level = 0;
last_mtime = current_exercise_mtime(state);
term::clear_screen();
print_watch_header(state, compiler)?;
last_run_success = run_current_exercise(state, compiler, build_dir);
print_watch_commands()?;
while rx.try_recv().is_ok() {}
}
}
Ok(WatchEvent::Key(KeyCode::Char('h'))) => {
if let Some(exercise) = state.current_exercise() {
let hints = exercise.hints();
term::clear_screen();
print_watch_header(state, compiler)?;
write_stdout("\r\n")?;
if hints.is_empty() {
term::print_warning("No hints available for this exercise.")?;
} else {
let current = hint_level.min(hints.len() - 1);
for i in 0..=current {
term::print_header(&format!("Hint {} of {}:", i + 1, hints.len()))?;
write_stdout("\r\n")?;
for line in hints[i].lines() {
write_stdout(&format!(" {line}\r\n"))?;
}
write_stdout("\r\n")?;
}
if current + 1 < hints.len() {
hint_level = current + 1;
term::print_info(&format!(
"Press 'h' again for the next hint ({} more).",
hints.len() - current - 1
))?;
} else {
term::print_info("No more hints. You've seen them all!")?;
}
}
write_stdout("\r\n")?;
print_watch_commands()?;
}
}
Ok(WatchEvent::Key(KeyCode::Char('l'))) => {
term::clear_screen();
write_stdout("\r\n")?;
term::print_header("Exercises:")?;
write_stdout("\r\n")?;
for (i, ex) in state.exercises.iter().enumerate() {
write_stdout(&format!(
" {} {}{}\r\n",
view::status_marker(state, i, ex),
ex.name(),
view::compiler_note(ex)
))?;
}
write_stdout("\r\n")?;
print_watch_commands()?;
}
Ok(WatchEvent::Key(KeyCode::Char('r'))) => {
term::clear_screen();
print_watch_header(state, compiler)?;
last_run_success = run_current_exercise(state, compiler, build_dir);
print_watch_commands()?;
while rx.try_recv().is_ok() {}
}
Ok(WatchEvent::Key(KeyCode::Char('q'))) | Ok(WatchEvent::Quit) => {
break;
}
Ok(_) => {}
Err(_) => break,
}
}
drop(_guard); state.save()?;
Ok(())
}
fn print_watch_header(state: &AppState, compiler: &Compiler) -> anyhow::Result<()> {
let (done, total) = state.progress();
write_stdout("\r\n")?;
term::print_header(&format!(
"cmetal v{} [{}] Exercise {} of {}",
env!("CARGO_PKG_VERSION"),
compiler.kind(),
state.current_index + 1,
total
))?;
term::print_progress(done, total)?;
write_stdout("\r\n")?;
Ok(())
}
fn print_watch_commands() -> anyhow::Result<()> {
write_stdout("\r\n")?;
let mut stdout = io::stdout();
let _ = crossterm::execute!(
stdout,
crossterm::style::SetForegroundColor(crossterm::style::Color::DarkGrey)
);
write_stdout(" [n] next [p] prev [h] hint [l] list [r] re-run [q] quit\r\n")?;
let _ = crossterm::execute!(
stdout,
crossterm::style::SetAttribute(crossterm::style::Attribute::Reset)
);
Ok(())
}
fn run_current_exercise(
state: &AppState,
compiler: &Compiler,
build_dir: &Path,
) -> anyhow::Result<bool> {
let exercise = match state.current_exercise() {
Some(e) => e,
None => {
term::print_warning("No exercises found.")?;
return Ok(false);
}
};
write_stdout(&format!(" Exercise: {}\r\n", exercise.name()))?;
write_stdout(&format!(" File: {}\r\n", exercise.path.display()))?;
write_stdout("\r\n")?;
let status = match runner::evaluate(exercise, compiler, build_dir) {
Ok(status) => status,
Err(e) => {
term::print_error(&format!("Error verifying {}: {e:#}", exercise.name()))?;
return Ok(false);
}
};
let revealed = runner::reveal_if_passed(exercise, &status);
view::report_outcome(exercise, compiler, &status, revealed.as_deref())?;
match &status {
RunStatus::Passed(_) => {
term::print_info("Press 'n' to move to the next exercise.")?;
}
RunStatus::Unsupported => {
term::print_info("Press 'n' to skip it, or restart cmetal with --compiler.")?;
}
_ => {}
}
Ok(status.passed())
}