use super::*;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Op {
Store {
dir: Vec<String>,
name: String,
data: Vec<u8>,
replace: Option<bool>,
},
Fetch {
dir: Vec<String>,
name: String,
text: bool,
},
Purge { dir: Vec<String>, name: String },
Rename {
dir: Vec<String>,
name: String,
to: String,
},
CreateDir { dir: Vec<String>, name: String },
ChangeDir { dir: Vec<String> },
Copy {
dir: Vec<String>,
name: String,
to: Vec<String>,
replace: bool,
remove: bool,
},
SetFlag { flag: i32, on: bool },
SetClock {
time: crate::clock::ClockTime,
date: crate::clock::ClockTime,
},
StoreText {
dir: Vec<String>,
target: Target,
text: String,
},
StoreScreen {
dir: Vec<String>,
name: Option<String>,
replace: bool,
screen: Graphic,
},
Server { end: bool },
Backup,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Target {
Variable(String),
Level(usize),
}
pub const TEXT_VARIABLE: &str = "SATEDIT";
pub const SCREEN_VARIABLE: &str = "SATSCRN";
pub const REPLACE_VARIABLE: &str = "SATREPL";
pub const BACKUP_VARIABLE: &str = "SATBKUP";
pub const BACKUP_MARGIN: f64 = 1024.0;
pub const BACKUP_NO_ROOM: &str = "a backup needs ";
pub fn may_serve(m: &Machine) -> bool {
no_server(m.model()).is_none()
&& m.serial_on()
&& !cmdline::command_line(m).is_ok_and(|l| l.active)
}
pub(super) fn no_server(model: Model) -> Option<String> {
(!matches!(model, Model::Hp48sx | Model::Hp48gx | Model::Hp49g)).then(|| {
format!(
"the {} has no Kermit server and no RPL user memory to write",
model.name().to_uppercase()
)
})
}
pub(super) fn quoted(name: &str) -> String {
format!("'{name}'")
}
pub(super) fn check_name(name: &str) -> crate::Result<()> {
if is_plain_name(name) {
Ok(())
} else {
Err(format!(
"{name:?} is not a plain variable name (1 to 127 characters, no digit or point first, \
no spaces, delimiters or operators)"
)
.into())
}
}
pub(super) fn components(dir: &[String]) -> crate::Result<&[String]> {
let rest = match dir.split_first() {
Some((home, rest)) if home == "HOME" => rest,
_ => dir,
};
for name in rest {
check_name(name)?;
}
Ok(rest)
}
pub(super) fn cd_command(dir: &[String]) -> String {
std::iter::once("HOME")
.chain(dir.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" ")
}
pub(super) fn directory<'a>(tree: &'a [Variable], dir: &[String]) -> crate::Result<&'a [Variable]> {
let mut vars = tree;
let mut path = String::from("HOME");
for name in dir {
path.push(' ');
path.push_str(name);
vars = vars
.iter()
.find(|v| &v.name == name)
.and_then(|v| v.variables.as_deref())
.ok_or_else(|| format!("no directory {{ {path} }}"))?;
}
Ok(vars)
}
pub(super) fn inside(path: &[String], dir: &[String], name: &str) -> bool {
path.len() > dir.len() && path.starts_with(dir) && path[dir.len()] == name
}
pub(super) fn flag_range(model: Model) -> i32 {
if model == Model::Hp49g { 128 } else { 64 }
}
pub fn store_bytes(data: &[u8]) -> (Vec<u8>, bool) {
if tfile::is_binary_file(data) {
return (data.to_vec(), true);
}
let encoded = std::str::from_utf8(data)
.ok()
.and_then(|t| charset::encode(t).ok());
(encoded.unwrap_or_else(|| data.to_vec()), false)
}
pub fn trim_fetched(mut data: Vec<u8>) -> Vec<u8> {
if tfile::is_binary_file(&data) {
let nibbles = tfile::unpack(&data[tfile::HEADER_LEN..]);
if let Ok(size) = prolog::object_size(&nibbles, 0) {
data.truncate(tfile::HEADER_LEN + size.div_ceil(2));
}
}
data
}
pub(super) fn text_refusal(text: &str) -> Option<String> {
let mut depth = 0usize;
let mut string = false;
let mut comment = false;
let mut prev: Option<char> = None;
for c in text.chars() {
let mid_word = prev.is_some_and(|p| {
!p.is_whitespace()
&& !matches!(
p,
'{' | '}' | '[' | ']' | '(' | ')' | '«' | '»' | '\'' | '"'
)
});
match c {
'"' | '@' if !string && !comment && mid_word => {
return Some(format!(
"a {c} right after a word starts a new token on the calculator: put a space before it"
));
}
'"' if !comment => string = !string,
'@' if !string => comment = !comment,
'\n' if comment => comment = false,
'{' if !string && !comment => depth += 1,
'}' if !string && !comment => match depth.checked_sub(1) {
Some(d) => depth = d,
None => return Some("a } closes a list the text did not open".into()),
},
_ => {}
}
prev = Some(c);
}
string.then(|| "the text leaves a string open (a \" is missing)".into())
}
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct CopyCase {
pub(super) is_dir: bool,
pub(super) taken: Option<bool>,
pub(super) replace: bool,
pub(super) remove: bool,
pub(super) holds_here: bool,
}
pub(super) fn copy_plan(
from: &[String],
name: &str,
into: &[String],
c: &CopyCase,
) -> crate::Result<Vec<Step>> {
let src = cd_command(from);
let dst = cd_command(into);
if from == into {
return Err(format!("{name} is in {{ {dst} }} already").into());
}
if c.is_dir && inside(into, from, name) {
return Err(format!("{name} cannot go into itself or a directory inside it").into());
}
if c.remove && c.holds_here {
return Err(
format!("{name} holds the current directory: change to another one first").into(),
);
}
match c.taken {
Some(_) if !c.replace => {
return Err(format!("{name} already exists in {{ {dst} }}").into());
}
Some(true) => {
return Err(format!(
"{name} in {{ {dst} }} is a directory, which a copy does not replace: purge it first"
)
.into());
}
Some(false) if c.is_dir => {
return Err(format!(
"a directory does not replace the variable {name} in {{ {dst} }}: purge it first"
)
.into());
}
_ => {}
}
let q = quoted(name);
let mut texts = vec![
src.clone(),
format!("{q} RCL"),
dst.clone(),
format!("{q} STO"),
];
if c.remove {
let verb = if c.is_dir { "PGDIR" } else { "PURGE" };
texts.extend([
format!("{q} RCL BYTES"),
src,
format!("{q} RCL BYTES"),
"ROT == 3 ROLLD == AND".into(),
format!("« {q} {verb} » « \"{COPY_DIFFERS}\" DOERR » IFTE"),
]);
}
Ok(texts
.into_iter()
.map(|text| Step::Host {
text,
cleanup: false,
})
.collect())
}
pub(super) const COPY_DIFFERS: &str = "Copy differs";
pub(super) fn wrapped(text: &str) -> String {
format!("{{\n{text}\n}}")
}
pub(super) fn free_name(vars: &[Variable], base: &str) -> String {
(1..)
.map(|n| match n {
1 => base.to_string(),
n => format!("{base}{n}"),
})
.find(|name| vars.iter().all(|v| &v.name != name))
.unwrap_or_default()
}
pub(super) fn parse_number(level: &str) -> Option<f64> {
let t = level.trim().replace(',', ".");
let t = t.strip_suffix('.').unwrap_or(&t);
t.parse::<f64>().ok().filter(|n| n.is_finite())
}
pub(super) fn holds_directory(data: &[u8]) -> bool {
if !tfile::is_binary_file(data) {
return false;
}
let head = &data[tfile::HEADER_LEN..data.len().min(tfile::HEADER_LEN + 3)];
prolog::read_field(&tfile::unpack(head), 0, 5) == Some(ObjectType::Directory.prolog())
}
pub(super) fn reply_count(level: &str) -> Option<u32> {
let first = level.trim().chars().next()?;
first.to_digit(10).filter(|&n| n <= 2)
}
pub(super) fn identity(u: &UserMemory<'_>, address: u32) -> crate::Result<String> {
let (size, crc) = u.identity_at(address)?;
Ok(format!("{size}:{crc:04X}"))
}
pub(super) fn algebraic(model: Model, flags: &Flags) -> bool {
model == Model::Hp49g && flags.get(-95) == Some(true)
}
pub(super) fn rpn_now(m: &Machine) -> bool {
UserMemory::of(m)
.and_then(|u| u.flags())
.is_ok_and(|f| f.get(-95) == Some(false))
}