1use std::io::{Seek, SeekFrom};
12use std::path::PathBuf;
13use std::rc::Rc;
14
15use crate::Engine;
16use crate::input::{Level, LineSource};
17
18pub type Hook = Box<dyn FnOnce(&mut Engine)>;
20
21pub struct Reload(Vec<(usize, Rc<[u8]>)>);
24
25#[derive(Clone, Debug)]
27pub struct OpenOutput {
28 pub path: PathBuf,
30 pub len: u64,
32 stream: Option<u32>,
34}
35
36impl Engine {
37 pub fn snapshot_outputs(&mut self) -> Vec<OpenOutput> {
39 self.printer.flush();
40 let mut out = Vec::new();
41 if self.printer.log_opened()
42 && let Some(path) = &self.files.log_name
43 {
44 out.push(OpenOutput {
45 path: path.clone(),
46 len: std::fs::metadata(path).map_or(0, |m| m.len()),
47 stream: None,
48 });
49 }
50 for n in self.printer.open_write_streams() {
51 if let Some(Some(path)) = self.write_paths.get(n as usize) {
52 out.push(OpenOutput {
53 path: path.clone(),
54 len: std::fs::metadata(path).map_or(0, |m| m.len()),
55 stream: Some(n),
56 });
57 }
58 }
59 out
60 }
61
62 pub fn resume_outputs(&mut self, outputs: &[OpenOutput]) -> std::io::Result<()> {
66 for o in outputs {
67 let mut f = std::fs::OpenOptions::new().write(true).open(&o.path)?;
68 f.set_len(o.len)?;
69 f.seek(SeekFrom::End(0))?;
70 match o.stream {
71 None => self
72 .printer
73 .set_log(Box::new(std::io::BufWriter::with_capacity(1 << 16, f))),
74 Some(n) => {
75 let w = crate::files::RecordingWriter::resume(
76 f,
77 o.path.clone(),
78 self.written_sink.clone(),
79 );
80 self.printer.open_write(n, Box::new(w));
81 }
82 }
83 }
84 Ok(())
85 }
86
87 pub fn open_input_files(&self) -> Vec<PathBuf> {
89 self.file_levels().map(|(_, path, _, _)| path).collect()
90 }
91
92 fn file_levels(&self) -> impl Iterator<Item = (usize, PathBuf, &[u8], usize)> {
95 self.input
96 .stack
97 .iter()
98 .enumerate()
99 .filter_map(|(i, l)| match l {
100 Level::Text(t) => match &t.source {
101 LineSource::File { data, pos } => {
102 let path = PathBuf::from(String::from_utf8_lossy(&t.name).into_owned());
103 Some((i, path, &data[..], *pos))
104 }
105 _ => None,
106 },
107 Level::Tokens(_) => None,
108 })
109 }
110
111 pub fn reloaded_inputs(&self) -> Result<Reload, PathBuf> {
116 let mut out = Vec::new();
117 for (i, path, data, pos) in self.file_levels() {
118 match std::fs::read(&path) {
119 Ok(new) if new.get(..pos) == data.get(..pos) => out.push((i, Rc::from(new))),
120 _ => return Err(path),
121 }
122 }
123 Ok(Reload(out))
124 }
125
126 pub fn reload_inputs(&mut self, reload: Reload) {
128 for (i, new) in reload.0 {
129 if let Some(Level::Text(t)) = self.input.stack.get_mut(i)
130 && let LineSource::File { data, .. } = &mut t.source
131 {
132 *data = new;
133 }
134 }
135 }
136
137 #[inline]
139 pub(crate) fn check_snapshot(&mut self) {
140 if self.snapshot_cs.is_some_and(|cs| cs == self.cur_cs) {
141 self.snapshot_cs = None;
142 if let Some(hook) = self.snapshot_hook.take() {
143 hook(self);
144 }
145 }
146 }
147}