use colored::Colorize;
use std::fs;
use std::io::Write;
use std::path::Path;
use crate::data_paths::data_path;
use crate::goal::GoalStatus;
use crate::loader::help::{HelpCommand, load_help_data};
use crate::loader::{discover_world_sources, set_active_world_path};
use crate::save_files::{self, SAVE_DIR, save_dir_for_world, set_active_save_dir};
use crate::style::GameStyle;
use crate::theme::THEME_MANAGER;
use crate::view::ViewMode;
use crate::{AMBLE_VERSION, Goal, RoomId, View, ViewItem, WorldSource};
use crate::{AmbleWorld, WorldObject, repl::ReplControl};
use anyhow::{Context, Result};
use log::{info, warn};
pub fn set_viewmode_handler(view: &mut View, mode: ViewMode) {
view.set_mode(mode);
let msg = match mode {
ViewMode::ClearVerbose => format!(
"{} mode set. {}",
"Clear".highlight(),
"Screen will be cleared with any movement and full location descriptions will always be shown.".italic()
),
ViewMode::Verbose => format!(
"{} mode set. {}",
"Verbose".highlight(),
"Full location descriptions will always be shown.".italic()
),
ViewMode::Brief => format!(
"{} mode set. {}",
"Brief".highlight(),
"Full location descriptions will only be shown on first visit and with the 'look' command.".italic()
),
};
view.push(ViewItem::EngineMessage(msg));
info!("Player changed view mode to {mode:?}");
}
pub fn quit_handler(world: &AmbleWorld, view: &mut View) -> Result<ReplControl> {
info!("$$ {} quit with a score of {}", world.player.name(), world.player.score);
let path: Vec<_> = world.player_path.iter().map(RoomId::to_string).collect();
let path_str = path.join(" > ");
info!("$$ PATH ({} moves): {path_str}", path.len().saturating_sub(1));
info!("$$ FLAGS:");
world.player.flags.iter().for_each(|i| info!("$$ -> {i}"));
info!("$$ INVENTORY:");
world
.player
.inventory
.iter()
.filter_map(|uuid| world.items.get(uuid))
.for_each(|i| info!("$$ -> {} ({})", i.name(), i.symbol()));
push_quit_summary(world, view);
Ok(ReplControl::Quit)
}
pub fn push_quit_summary(world: &AmbleWorld, view: &mut View) {
#[allow(clippy::cast_precision_loss)]
let percent = (world.player.score as f32 / world.max_score as f32) * 100.0;
let (rank, eval) = world.scoring.get_rank(percent);
let visited = world.rooms.values().filter(|r| r.visited).count();
view.push(ViewItem::QuitSummary {
title: world.scoring.report_title.clone(),
rank: rank.to_string(),
notes: eval.to_string(),
score: world.player.score,
max_score: world.max_score,
visited,
max_visited: world.rooms.len(),
});
}
pub fn help_handler(view: &mut View) {
let basic_text_path = data_path("help_basic.txt");
let commands_toml_path = data_path("help_commands.toml");
match load_help_data(&basic_text_path, &commands_toml_path) {
Ok(help_data) => {
view.push(ViewItem::Help {
basic_text: help_data.basic_text,
commands: help_data.commands,
});
},
Err(e) => {
view.push(ViewItem::Error(format!(
"Failed to load help data: {}",
e.to_string().error_style()
)));
warn!("Failed to load help data: {e}");
},
}
}
pub fn help_handler_dev(view: &mut View) {
if !crate::DEV_MODE {
view.push(ViewItem::Error(
"Developer commands are disabled in this build."
.error_style()
.to_string(),
));
warn!("player attempted to use developer help with DEV_MODE = false");
return;
}
let basic_text_path = data_path("help_basic.txt");
let commands_toml_path = data_path("help_commands.toml");
match load_help_data(&basic_text_path, &commands_toml_path) {
Ok(mut help_data) => {
let mut dev_cmds: Vec<HelpCommand> = vec![
HelpCommand {
command: ":npcs".into(),
description: "DEV: List all NPCs with location and state.".into(),
},
HelpCommand {
command: ":flags".into(),
description: "DEV: List all currently set flags (sequences as name#step).".into(),
},
HelpCommand {
command: ":sched".into(),
description: "DEV: List upcoming scheduled events with due turn and notes.".into(),
},
HelpCommand {
command: ":note <text>".into(),
description: "DEV: Append a note to the daily dev log.".into(),
},
HelpCommand {
command: ":teleport <room_symbol>".into(),
description: "DEV: Instantly move to a room (alias :port).".into(),
},
HelpCommand {
command: ":spawn <item_symbol>".into(),
description: "DEV: Spawn/move an item into inventory (alias :item).".into(),
},
HelpCommand {
command: ":set-flag <name>".into(),
description: "DEV: Create a simple flag on the player.".into(),
},
HelpCommand {
command: ":init-seq <name> <end|none>".into(),
description: "DEV: Create a sequence flag with limit or unlimited (none).".into(),
},
HelpCommand {
command: ":adv-seq <name>".into(),
description: "DEV: Advance a sequence flag by one step.".into(),
},
HelpCommand {
command: ":reset-seq <name>".into(),
description: "DEV: Reset a sequence flag to step 0.".into(),
},
];
help_data.commands.clear();
help_data.commands.append(&mut dev_cmds);
view.push(ViewItem::Help {
basic_text: help_data.basic_text,
commands: help_data.commands,
});
},
Err(e) => {
view.push(ViewItem::Error(format!(
"Failed to load help data: {}",
e.to_string().error_style()
)));
warn!("Failed to load help data: {e}");
},
}
}
pub fn goals_handler(world: &AmbleWorld, view: &mut View) {
filtered_goals(world, GoalStatus::Active)
.iter()
.map(|goal| ViewItem::ActiveGoal {
name: goal.name.clone(),
description: goal.description.clone(),
})
.for_each(|goal_item| view.push(goal_item));
filtered_goals(world, GoalStatus::Complete)
.iter()
.map(|goal| ViewItem::CompleteGoal {
name: goal.name.clone(),
description: goal.description.clone(),
})
.for_each(|goal_item| view.push(goal_item));
info!("{} checked goals status.", world.player.name());
}
pub fn list_saves_handler(world: &AmbleWorld, view: &mut View) {
let save_dir = save_dir_for_world(world);
match save_files::build_save_entries(&save_dir) {
Ok(entries) => view.push(ViewItem::SavedGamesList {
directory: save_dir.to_string_lossy().to_string(),
entries,
}),
Err(err) => view.push(ViewItem::Error(format!("Unable to list saved games: {err}"))),
}
}
pub fn filtered_goals(world: &AmbleWorld, status: GoalStatus) -> Vec<&Goal> {
world.goals.iter().filter(|goal| goal.status(world) == status).collect()
}
pub fn load_handler(world: &mut AmbleWorld, view: &mut View, gamefile: &str) -> bool {
let save_dir = save_dir_for_world(world);
let mut slots = match save_files::collect_save_slots(&save_dir) {
Ok(slots) => slots,
Err(err) => {
view.push(ViewItem::Error(format!("Unable to inspect saved games: {err}")));
return false;
},
};
if save_dir != Path::new(SAVE_DIR)
&& let Ok(legacy_slots) = save_files::collect_save_slots(Path::new(SAVE_DIR))
{
slots.extend(legacy_slots);
}
slots.retain(|slot| slot.slot == gamefile);
slots.sort_by(|a, b| b.modified.cmp(&a.modified).then(a.version.cmp(&b.version)));
let chosen_slot = slots
.iter()
.find(|slot| slot.version == AMBLE_VERSION)
.cloned()
.or_else(|| slots.first().cloned());
let (load_path, loaded_version_hint) = if let Some(slot) = chosen_slot {
(slot.path.clone(), Some(slot.version))
} else {
(save_dir.join(format!("{gamefile}-amble-{AMBLE_VERSION}.ron")), None)
};
match fs::read_to_string(load_path.as_path()) {
Ok(world_ron) => match ron::from_str::<AmbleWorld>(&world_ron) {
Ok(new_world) => {
if new_world.version != AMBLE_VERSION {
warn!(
"player loaded '{gamefile}' (v{}), current version is v{AMBLE_VERSION}",
new_world.version
);
view.push(ViewItem::Error(format!(
"{}: '{gamefile}' version is v{} -- does not match current game (v{AMBLE_VERSION}).",
"WARNING".bold().yellow(),
new_world.version.error_style(),
)));
} else if let Some(original_version) = loaded_version_hint.filter(|version| version != AMBLE_VERSION) {
info!(
"Loaded '{gamefile}' saved under v{original_version}, metadata indicates current version match."
);
}
if let Ok(sources) = discover_world_sources()
&& let Some(source) = match_world_source(&new_world, &sources)
{
set_active_world_path(source.path.clone());
}
set_active_save_dir(save_dir_for_world(&new_world));
*world = new_world;
view.push(ViewItem::ActionSuccess(format!(
"Saved game {} (v{}) loaded successfully. Sally forth.",
gamefile.underline().green(),
world.version.highlight()
)));
view.push(ViewItem::GameLoaded {
save_slot: gamefile.to_string(),
save_file: load_path.to_string_lossy().to_string(),
});
info!(
"Player reloaded AmbleWorld from file '{}' (version {})",
load_path.display(),
world.version
);
true
},
Err(err) => {
log_and_report_failed_parse(view, gamefile, &load_path, err);
false
},
},
Err(err) => {
log_and_report_failed_load(view, gamefile, load_path, err);
false
},
}
}
fn log_and_report_failed_parse(
view: &mut View,
gamefile: &str,
load_path: &std::path::PathBuf,
err: ron::de::SpannedError,
) {
view.push(ViewItem::ActionFailure(format!(
"Unable to load the {} save file. The Amble engine may have changed since it was created ({}).",
gamefile.error_style(),
err
)));
warn!(
"player attempted to load '{gamefile}' from '{}': parse failure ({err})",
load_path.display()
);
}
fn log_and_report_failed_load(view: &mut View, gamefile: &str, load_path: std::path::PathBuf, err: std::io::Error) {
if err.kind() == std::io::ErrorKind::NotFound {
view.push(ViewItem::Error(format!(
"Unable to find {} save file. Load aborted. Type {} to list available saves.",
gamefile.error_style(),
"`saves`".highlight()
)));
} else {
view.push(ViewItem::ActionFailure(format!(
"Unable to load the {} save file ({}).",
gamefile.error_style(),
err
)));
}
warn!(
"player attempted to load '{gamefile}' from '{}': {}",
load_path.display(),
err
);
}
fn match_world_source<'a>(world: &AmbleWorld, sources: &'a [WorldSource]) -> Option<&'a WorldSource> {
if !world.world_slug.trim().is_empty()
&& let Some(source) = sources.iter().find(|source| source.slug == world.world_slug)
{
return Some(source);
}
if !world.game_title.trim().is_empty() {
return sources.iter().find(|source| source.title == world.game_title);
}
None
}
pub fn save_handler(world: &AmbleWorld, view: &mut View, gamefile: &str) -> Result<()> {
let world_ron =
ron::ser::to_string(world).with_context(|| "error converting AmbleWorld to 'ron' format".to_string())?;
let save_dir = save_dir_for_world(world);
fs::create_dir_all(&save_dir).with_context(|| "error creating saved_games folder".to_string())?;
let save_path = save_dir.join(format!("{gamefile}-amble-{AMBLE_VERSION}.ron"));
let mut save_file =
fs::File::create(save_path.as_path()).with_context(|| format!("creating file '{}'", save_path.display()))?;
save_file
.write_all(world_ron.as_bytes())
.with_context(|| "failed to write AmbleWorld to .ron file".to_string())?;
view.push(ViewItem::GameSaved {
save_slot: gamefile.to_string(),
save_file: save_path.to_string_lossy().to_string(),
});
view.push(ViewItem::ActionSuccess(format!(
"Game saved to slot {} successfully. Amble on...",
gamefile.underline().green()
)));
info!("Player saved game to \"{gamefile}\"");
Ok(())
}
pub fn autosave_quiet(world: &AmbleWorld, gamefile: &str) -> Result<()> {
let world_ron =
ron::ser::to_string(world).with_context(|| "error converting AmbleWorld to 'ron' format".to_string())?;
let save_dir = save_dir_for_world(world);
fs::create_dir_all(&save_dir).with_context(|| "error creating saved_games folder".to_string())?;
let save_path = save_dir.join(format!("{gamefile}-amble-{AMBLE_VERSION}.ron"));
let mut save_file =
fs::File::create(save_path.as_path()).with_context(|| format!("creating file '{}'", save_path.display()))?;
save_file
.write_all(world_ron.as_bytes())
.with_context(|| "failed to write AmbleWorld to .ron file".to_string())?;
info!("Autosaved game to \"{gamefile}\"");
Ok(())
}
pub fn theme_handler(view: &mut View, theme_name: &str) -> Result<()> {
let manager = THEME_MANAGER
.read()
.map_err(|_| anyhow::anyhow!("Failed to access theme manager"))?;
if theme_name.is_empty() || theme_name == "list" {
let themes = manager.list_themes();
let current = manager.current_name();
view.push(ViewItem::EngineMessage(format!(
"Available themes: {}",
themes
.iter()
.map(|t| {
if t == ¤t {
format!("{t} (current)").status_style().to_string()
} else {
t.clone()
}
})
.collect::<Vec<_>>()
.join("\n")
)));
return Ok(());
}
match manager.set_theme(theme_name) {
Ok(()) => {
view.push(ViewItem::ActionSuccess(format!("Theme changed to '{theme_name}'")));
},
Err(_) => {
view.push(ViewItem::Error(format!(
"Theme '{theme_name}' not found. Use 'theme list' to see available themes."
)));
},
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::loader::scoring::{ScoringConfig, ScoringRank};
#[test]
fn help_dev_shows_only_dev_commands_when_enabled() {
if !crate::DEV_MODE {
return;
}
let mut view = View::new();
help_handler_dev(&mut view);
if let Some(commands) = view.items.iter().find_map(|entry| {
if let ViewItem::Help { commands, .. } = &entry.view_item {
Some(commands)
} else {
None
}
}) {
assert!(!commands.is_empty());
assert!(commands.iter().all(|c| c.command.starts_with(':')));
} else {
panic!(":help dev did not produce a Help ViewItem");
}
}
#[test]
fn quit_handler_uses_scoring_config() {
colored::control::set_override(false);
let custom_scoring = ScoringConfig {
ranks: vec![
ScoringRank {
threshold: 75.0,
name: "Test Master".to_string(),
description: "You aced the test.".to_string(),
},
ScoringRank {
threshold: 50.0,
name: "Test Novice".to_string(),
description: "You passed.".to_string(),
},
ScoringRank {
threshold: 0.0,
name: "Test Failure".to_string(),
description: "Better luck next time.".to_string(),
},
],
report_title: "Test Scorecard".into(),
};
let mut world = AmbleWorld::new_empty();
world.scoring = custom_scoring;
world.player.score = 60;
world.max_score = 100;
let mut view = View::new();
let result = quit_handler(&world, &mut view);
assert!(matches!(result, Ok(ReplControl::Quit)));
if let Some((rank, notes, score, max_score)) = view.items.iter().find_map(|entry| {
if let ViewItem::QuitSummary {
rank,
notes,
score,
max_score,
..
} = &entry.view_item
{
Some((rank, notes, score, max_score))
} else {
None
}
}) {
assert_eq!(rank, "Test Novice");
assert_eq!(notes, "You passed.");
assert_eq!(*score, 60);
assert_eq!(*max_score, 100);
} else {
panic!("quit_handler did not produce a QuitSummary ViewItem");
}
}
#[test]
fn quit_handler_uses_default_scoring_when_not_set() {
colored::control::set_override(false);
let mut world = AmbleWorld::new_empty();
world.player.score = 100;
world.max_score = 100;
let mut view = View::new();
let result = quit_handler(&world, &mut view);
assert!(matches!(result, Ok(ReplControl::Quit)));
if let Some(rank) = view.items.iter().find_map(|entry| {
if let ViewItem::QuitSummary { rank, .. } = &entry.view_item {
Some(rank)
} else {
None
}
}) {
assert_eq!(rank, "Stellar");
} else {
panic!("quit_handler did not produce a QuitSummary ViewItem");
}
}
}