use crate::token::Token;
use fusevm::{Value, VM};
use std::cell::RefCell;
use std::io::Write as _;
pub const WRITE_STREAMS: usize = 128;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stream {
File(usize),
LogOnly,
Terminal,
}
impl Stream {
pub fn of(n: i64) -> Stream {
match n {
n if n < 0 => Stream::LogOnly,
n if n >= WRITE_STREAMS as i64 => Stream::Terminal,
n => Stream::File(n as usize),
}
}
pub fn code(self) -> i64 {
match self {
Stream::File(n) => n as i64,
Stream::LogOnly => -1,
Stream::Terminal => WRITE_STREAMS as i64,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Whatsit {
Open { stream: usize, name: String },
Write { stream: Stream, tokens: Vec<Token> },
Close { stream: usize },
Special { tokens: Vec<Token>, late: bool },
Pdf(crate::backend::PdfWhatsit),
}
pub fn out_file_name(name: &str) -> String {
let base = name.rsplit('/').next().unwrap_or(name);
match base.contains('.') {
true => name.to_string(),
false => format!("{name}.tex"),
}
}
static OUTPUT_DIRECTORY: std::sync::RwLock<Option<std::path::PathBuf>> =
std::sync::RwLock::new(None);
pub fn set_output_directory(dir: Option<std::path::PathBuf>) {
if let Ok(mut d) = OUTPUT_DIRECTORY.write() {
*d = dir;
}
}
pub fn out_path(name: &str) -> std::path::PathBuf {
let path = std::path::Path::new(name);
if path.is_absolute() {
return path.to_path_buf();
}
let dir = OUTPUT_DIRECTORY
.read()
.ok()
.and_then(|d| d.clone())
.or_else(|| std::env::var_os("TEXMF_OUTPUT_DIRECTORY").map(Into::into));
match dir {
Some(dir) => dir.join(path),
None => path.to_path_buf(),
}
}
pub fn printed_to_file(text: &str, new_line_char: i64) -> String {
let nl = u32::try_from(new_line_char).ok().and_then(char::from_u32);
text.chars()
.map(|c| match Some(c) == nl {
true => '\n',
false => c,
})
.collect()
}
pub fn file_ops(ops: Vec<crate::ir::MsgOp>, new_line_char: i64) -> Vec<crate::ir::MsgOp> {
use crate::ir::MsgOp;
ops.into_iter()
.map(|op| match op {
MsgOp::Text(t) => MsgOp::Text(printed_to_file(&t, new_line_char)),
MsgOp::If {
left,
rel,
right,
then_ops,
else_ops,
} => MsgOp::If {
left,
rel,
right,
then_ops: file_ops(then_ops, new_line_char),
else_ops: file_ops(else_ops, new_line_char),
},
MsgOp::IfOdd {
value,
then_ops,
else_ops,
} => MsgOp::IfOdd {
value,
then_ops: file_ops(then_ops, new_line_char),
else_ops: file_ops(else_ops, new_line_char),
},
other => other,
})
.collect()
}
struct Outs {
files: Vec<Option<std::io::BufWriter<std::fs::File>>>,
}
thread_local! {
static OUTS: RefCell<Outs> = RefCell::new(Outs {
files: (0..WRITE_STREAMS).map(|_| None).collect(),
});
}
pub fn close_all() {
OUTS.with(|o| {
for file in o.borrow_mut().files.iter_mut() {
if let Some(mut f) = file.take() {
let _ = f.flush();
}
}
});
}
pub fn is_open(n: usize) -> bool {
OUTS.with(|o| o.borrow().files.get(n).is_some_and(Option::is_some))
}
pub fn b_out_open(vm: &mut VM, _argc: u8) -> Value {
let name = match vm.pop() {
Value::Str(s) => s.to_string(),
other => format!("{other:?}"),
};
let stream = vm.pop().to_int();
let Ok(n) = usize::try_from(stream) else {
return Value::Undef;
};
if n >= WRITE_STREAMS {
return Value::Undef;
}
let path = out_path(&name);
let opened = std::fs::File::create(&path);
OUTS.with(|o| {
let mut o = o.borrow_mut();
if let Some(mut old) = o.files[n].take() {
let _ = old.flush();
}
if let Ok(file) = opened {
o.files[n] = Some(std::io::BufWriter::new(file));
}
});
if !is_open(n) {
return crate::runtime::fault_now(vm, format!("I can't write on file `{name}'"));
}
Value::Undef
}
pub fn b_out_is_open(vm: &mut VM, _argc: u8) -> Value {
let stream = vm.pop().to_int();
Value::Int(i64::from(usize::try_from(stream).is_ok_and(is_open)))
}
pub fn b_out_close(vm: &mut VM, _argc: u8) -> Value {
let stream = vm.pop().to_int();
if let Ok(n) = usize::try_from(stream) {
OUTS.with(|o| {
if let Some(Some(mut f)) = o.borrow_mut().files.get_mut(n).map(Option::take) {
let _ = f.flush();
}
});
}
Value::Undef
}
pub fn write_line(n: i64, line: &str) -> bool {
let Ok(n) = usize::try_from(n) else {
return false;
};
OUTS.with(|o| match o.borrow_mut().files.get_mut(n) {
Some(Some(f)) => {
let _ = f.write_all(line.as_bytes());
let _ = f.write_all(b"\n");
true
}
_ => false,
})
}
#[derive(Default, Debug)]
pub struct Written {
streams: std::collections::HashMap<usize, String>,
files: std::collections::HashMap<String, String>,
}
impl Written {
pub fn open(&mut self, stream: usize, name: &str) {
self.streams.insert(stream, name.to_string());
self.files.insert(name.to_string(), String::new());
}
pub fn write(&mut self, stream: Stream, line: &str) -> bool {
let Stream::File(n) = stream else {
return false;
};
let Some(name) = self.streams.get(&n) else {
return false;
};
let file = self.files.entry(name.clone()).or_default();
file.push_str(line);
file.push('\n');
true
}
pub fn close(&mut self, stream: usize) {
self.streams.remove(&stream);
}
pub fn is_open(&self, stream: usize) -> bool {
self.streams.contains_key(&stream)
}
pub fn text(&self, name: &str) -> Option<&str> {
let name = name.strip_prefix("./").unwrap_or(name);
self.files.get(name).map(String::as_str)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_output_name_gets_tex_only_when_it_has_no_extension() {
assert_eq!(out_file_name("foo"), "foo.tex");
assert_eq!(out_file_name("q.aux"), "q.aux");
assert_eq!(out_file_name("bar baz"), "bar baz.tex");
assert_eq!(out_file_name("dir.d/x"), "dir.d/x.tex");
assert_eq!(out_file_name("case.out"), "case.out");
}
#[test]
fn a_write_number_names_a_stream_the_log_or_the_terminal() {
assert_eq!(Stream::of(-1), Stream::LogOnly);
assert_eq!(Stream::of(0), Stream::File(0));
assert_eq!(Stream::of(127), Stream::File(127));
assert_eq!(Stream::of(128), Stream::Terminal);
assert_eq!(Stream::of(16), Stream::File(16));
}
#[test]
fn a_file_line_is_raw_but_for_the_newline_character() {
assert_eq!(printed_to_file("a\u{1}é", -1), "a\u{1}é");
assert_eq!(printed_to_file("a^b", '^' as i64), "a\nb");
}
#[test]
fn the_lowering_reads_back_what_it_wrote() {
let mut w = Written::default();
assert!(!w.write(Stream::File(3), "lost"));
w.open(3, "foo.tex");
assert!(w.write(Stream::File(3), "one"));
assert!(w.write(Stream::File(3), "two"));
w.close(3);
assert!(!w.write(Stream::File(3), "after"));
assert_eq!(w.text("./foo.tex"), Some("one\ntwo\n"));
w.open(4, "foo.tex");
assert_eq!(w.text("foo.tex"), Some(""));
}
}