//! Text and controls used by the original in-mission help terminal. use crate::ui_configuration::read; use fparkan_path::{normalize_relative, PathPolicy}; use fparkan_vfs::{Vfs, VfsError}; use std::collections::BTreeMap; const CONTROL_TABLES: [&str; 4] = ["ui_hero", "ui_bots", "ui_hq", "ui_other"]; /// A token from a mission's CP1251 `Mistips.mis`. #[derive(Debug, PartialEq, Eq)] pub enum MissionTip { /// Original bytes to draw with the game font. Text(Vec), /// An explicit line break independent of the file's physical newlines. Break, /// RGB tint for the following text. Color([u8; 3]), /// Closes a color span. EndColor, /// Line spacing as a percentage. Interleave(u16), } /// One entry in a help command table, in its original CP1251 encoding. #[derive(Debug, PartialEq, Eq)] pub struct HelpBinding { /// Command identifier as read from a `.man` file. pub command: String, /// Localized description from `Command.dsc`. pub description: Vec, /// Modifier and primary key labels from `Scancode.dsc`. pub keys: [Vec; 2], } /// Resource-backed pages that are available before any messages have arrived. #[derive(Debug)] pub struct HelpResources { /// None for maps without a `Mistips.mis` file. pub mission: Option>, /// Battle suit, warbot, bunker/MCU, and additional controls, in native order. pub controls: [Vec; 4], } impl HelpResources { /// Loads the selected mission's tips and the original help bindings. /// The alternate input profile reads the `_d.man` variants. pub fn load(vfs: &dyn Vfs, mission: &str, alternate_controls: bool) -> Result { let mission_directory = mission .rsplit_once(['/', '\\']) .map_or("", |(directory, _)| directory); let tips = if mission_directory.is_empty() { "Mistips.mis".into() } else { format!("{mission_directory}/Mistips.mis") }; let path = normalize_relative(tips.as_bytes(), PathPolicy::StrictLegacy) .map_err(|error| error.to_string())?; let mission = match vfs.read(&path) { Ok(bytes) => Some(parse_tips(&bytes)?), Err(VfsError::NotFound(_)) => None, Err(error) => return Err(error.to_string()), }; let commands = read(vfs, "Command.dsc")?; let scancodes = read(vfs, "Scancode.dsc")?; let commands = descriptions(&commands); let scancodes = descriptions(&scancodes); let mut controls = std::array::from_fn(|_| Vec::new()); for (section, base) in controls.iter_mut().zip(CONTROL_TABLES) { let suffix = if alternate_controls { "_d" } else { "" }; let path = format!("{base}{suffix}.man"); let data = read(vfs, &path)?; *section = control_table(&data, &commands, &scancodes) .map_err(|error| format!("{path}: {error}"))?; } Ok(Self { mission, controls }) } } fn parse_tips(mut input: &[u8]) -> Result, String> { let mut output = Vec::new(); while let Some(start) = input.windows(2).position(|pair| pair == b"<<") { if start != 0 { output.push(MissionTip::Text(input[..start].to_vec())); } input = &input[start + 2..]; let end = input .windows(2) .position(|pair| pair == b">>") .ok_or("unterminated mission advice directive")?; let command = std::str::from_utf8(&input[..end]) .map_err(|_| "mission advice directive is outside ASCII")?; output.push(parse_tip_directive(command)?); input = &input[end + 2..]; } if !input.is_empty() { output.push(MissionTip::Text(input.to_vec())); } Ok(output) } fn parse_tip_directive(command: &str) -> Result { if command == "br" { return Ok(MissionTip::Break); } if command == "/color" { return Ok(MissionTip::EndColor); } if let Some(value) = command.strip_prefix("interleave=") { return value .parse() .map(MissionTip::Interleave) .map_err(|_| format!("invalid mission advice spacing {value}")); } if let Some(value) = command.strip_prefix("color=") { let channels = value .split(',') .map(str::parse) .collect::, _>>(); if let Ok(channels) = channels { if let Ok(rgb) = channels.try_into() { return Ok(MissionTip::Color(rgb)); } } return Err(format!("invalid mission advice color {value}")); } Err(format!("unknown mission advice directive {command}")) } fn descriptions(input: &[u8]) -> BTreeMap<&[u8], &[u8]> { input .split(|&byte| byte == b'\n') .map(<[u8]>::trim_ascii) .filter(|line| line.starts_with(b"SCAN_") || line.starts_with(b"CMD_")) .map(|line| { let end = line .iter() .position(u8::is_ascii_whitespace) .unwrap_or(line.len()); (&line[..end], line[end..].trim_ascii()) }) .collect() } fn control_table( input: &[u8], commands: &BTreeMap<&[u8], &[u8]>, scancodes: &BTreeMap<&[u8], &[u8]>, ) -> Result, String> { input .split(|&byte| byte == b'\n') .map(<[u8]>::trim_ascii) .filter(|line| !line.is_empty()) .map(|line| { let mut fields = line .split(u8::is_ascii_whitespace) .filter(|part| !part.is_empty()); let (Some(command), Some(modifier), Some(key), None) = (fields.next(), fields.next(), fields.next(), fields.next()) else { return Err("expected command, modifier, and scancode".into()); }; let description = description_field(commands, command)?; let keys = [ description_field(scancodes, modifier)?, description_field(scancodes, key)?, ]; let command = std::str::from_utf8(command) .map_err(|_| "command identifier is outside ASCII")? .to_owned(); Ok(HelpBinding { command, description, keys, }) }) .collect() } fn description_field( records: &BTreeMap<&[u8], &[u8]>, identifier: &[u8], ) -> Result, String> { records .get(identifier) .map(|&value| value.to_vec()) .ok_or_else(|| { format!( "missing help description for {}", String::from_utf8_lossy(identifier) ) }) } #[cfg(test)] mod tests { use super::*; #[test] fn advice_preserves_cp1251_and_explicit_breaks() { assert_eq!( parse_tips(b"<><>\xcd\xe0<><
>").unwrap(), [ MissionTip::Interleave(150), MissionTip::Color([255, 0, 0]), MissionTip::Text(vec![0xcd, 0xe0]), MissionTip::EndColor, MissionTip::Break, ] ); assert!(parse_tips(b"<>").is_err()); assert!(parse_tips(b"unfinished < 1); } }