Skip to main content

hexicon_host/
lib.rs

1//! The interface between the Hexicon VM and the system it runs on.
2//!
3//! The VM has no direct access to terminals, files, clocks, or randomness.
4//! Everything outside the VM goes through a [`Host`], which keeps the VM
5//! portable to WebAssembly and makes runs reproducible under test.
6
7pub mod entities;
8pub mod pane;
9pub mod rich;
10
11use std::cell::RefCell;
12use std::collections::{HashMap, VecDeque};
13use std::rc::Rc;
14
15/// Why a file could not be read or written.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum FileError {
18    /// There is no file by that name.
19    NotFound,
20    /// The host does not let the program use that file.
21    Denied,
22    /// The host has no files.
23    Unsupported,
24    /// Anything else, such as a full disk.
25    Failed,
26}
27
28/// What kind of thing a file name refers to. The values are the ones
29/// programs see, and can be combined.
30pub mod file_type {
31    /// An ordinary file.
32    pub const FILE: u32 = 0x01;
33    /// A directory.
34    pub const DIR: u32 = 0x02;
35    /// A character device.
36    pub const CHAR: u32 = 0x04;
37    /// A block device.
38    pub const BLOCK: u32 = 0x08;
39    /// A pipe.
40    pub const PIPE: u32 = 0x10;
41    /// A socket.
42    pub const SOCKET: u32 = 0x20;
43    /// A symbolic link.
44    pub const LINK: u32 = 0x40;
45}
46
47/// Attributes of a file. The values are the ones programs see.
48pub mod file_attr {
49    /// Not normally listed.
50    pub const HIDDEN: u32 = 0x01;
51    /// Belongs to the system.
52    pub const SYSTEM: u32 = 0x02;
53    /// Can be read.
54    pub const READ: u32 = 0x04;
55    /// Can be written.
56    pub const WRITE: u32 = 0x08;
57}
58
59/// What the host knows about a file.
60#[derive(Debug, Clone, Default, PartialEq, Eq)]
61pub struct FileInfo {
62    /// A combination of [`file_type`] values.
63    pub kind: u32,
64    /// A combination of [`file_attr`] values.
65    pub attrs: u32,
66    /// The size in bytes.
67    pub size: u64,
68    /// When the file was last read, in seconds since the start of 1970.
69    pub accessed: Option<i64>,
70    /// When the file was last changed.
71    pub modified: Option<i64>,
72    /// When the file was created.
73    pub created: Option<i64>,
74    /// Where a symbolic link leads.
75    pub link_target: Option<String>,
76}
77
78/// Where a file is in relation to the folder a program's file access is
79/// confined to.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum Sandbox {
82    /// In the folder, or in a folder within it.
83    Inside,
84    /// The folder itself.
85    Itself,
86    /// A folder the sandbox is in.
87    Contains,
88    /// Anywhere else.
89    Outside,
90}
91
92/// What a host has when it is asked for input.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum Input {
95    /// A line the player entered, or a key.
96    Text(String),
97    /// There is no more input and never will be.
98    End,
99    /// There is none yet. The VM stops where it is and hands control
100    /// back, and asks again when it is resumed. A host that cannot wait
101    /// for the player without freezing, as in a browser, answers this
102    /// way; one that can wait never needs to.
103    Pending,
104}
105
106/// Which file dialog a program asks for.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum FileDialog {
109    /// A file to read: one that is there.
110    Open,
111    /// A file to write: one that may not be there yet.
112    Save,
113}
114
115/// What kind of file a program asks for, so that a dialog can show files
116/// of that kind and name a new one as they are named.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum FileKind {
119    /// A saved game: `.hxs`.
120    SavedGame,
121    /// A transcript, or other text: `.txt`.
122    Text,
123    /// Anything else.
124    Other,
125}
126
127impl FileKind {
128    /// The kind a program's file type code (`FileTypeSave`, ...) asks for.
129    pub fn from_code(code: i64) -> Self {
130        match code {
131            15 => FileKind::SavedGame,
132            2 | 7 => FileKind::Text,
133            _ => FileKind::Other,
134        }
135    }
136}
137
138/// What the player did with a file dialog.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub enum FileChoice {
141    /// They chose a file: its name, as the host's file functions take it.
142    Chosen(String),
143    /// They chose none.
144    Cancelled,
145    /// They have not chosen yet. As with [`Input::Pending`], the VM stops
146    /// and asks again when it is resumed.
147    Pending,
148}
149
150/// The time on the host's clock.
151#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
152pub struct Time {
153    /// Milliseconds since the start of 1970, UTC.
154    pub unix_millis: i64,
155    /// How far local time is ahead of UTC, in seconds.
156    pub utc_offset_seconds: i32,
157}
158
159/// The services a VM needs from the system it runs on.
160pub trait Host {
161    /// Display text on the main console.
162    fn print(&mut self, text: &str);
163
164    /// What the display can do beyond plain text, if it is a rich
165    /// display; `None` for a display of text, which gets its text through
166    /// [`Host::print`], broken into lines that fit.
167    fn rich_display(&self) -> Option<rich::RichDisplay> {
168        None
169    }
170
171    /// On a rich display: what the program wrote, as it wrote it, markup
172    /// and all, in order. The host checks it with a [`rich::Checker`].
173    fn print_markup(&mut self, markup: &str) {
174        let _ = markup;
175    }
176
177    /// On a rich display: a line the player typed, from a script, shown
178    /// as the player's own words.
179    fn print_input(&mut self, text: &str) {
180        let _ = text;
181    }
182
183    /// Fill a buffer with unpredictable bytes, for seeding the random
184    /// number generator. A host that leaves the buffer alone gives every
185    /// run the same seed, which is what tests want.
186    fn random_bytes(&mut self, buffer: &mut [u8]) {
187        let _ = buffer;
188    }
189
190    /// The whole contents of a file. Names are the host's to interpret:
191    /// a path on a system with a file system, a key in a browser's
192    /// storage.
193    fn read_file(&mut self, name: &str) -> Result<Vec<u8>, FileError> {
194        let _ = name;
195        Err(FileError::Unsupported)
196    }
197
198    /// Create a file with the given contents, replacing any there was.
199    fn write_file(&mut self, name: &str, data: &[u8]) -> Result<(), FileError> {
200        let _ = (name, data);
201        Err(FileError::Unsupported)
202    }
203
204    /// What a name refers to, or `None` if nothing. With `follow_links`,
205    /// a symbolic link is described by what it leads to.
206    ///
207    /// File names are in one syntax on every host: parts separated by
208    /// `/`, with `.` for the folder itself and `..` for the one above. A
209    /// name that does not start at a root is relative to wherever the
210    /// host keeps the program's files.
211    fn file_info(&mut self, name: &str, follow_links: bool) -> Option<FileInfo> {
212        let _ = (name, follow_links);
213        None
214    }
215
216    /// Delete a file.
217    fn delete_file(&mut self, name: &str) -> Result<(), FileError> {
218        let _ = name;
219        Err(FileError::Unsupported)
220    }
221
222    /// Give a file a new name, which must not be in use.
223    fn rename_file(&mut self, from: &str, to: &str) -> Result<(), FileError> {
224        let _ = (from, to);
225        Err(FileError::Unsupported)
226    }
227
228    /// Create a directory, and with `parents` any directories above it
229    /// that are missing.
230    fn create_dir(&mut self, name: &str, parents: bool) -> Result<(), FileError> {
231        let _ = (name, parents);
232        Err(FileError::Unsupported)
233    }
234
235    /// Remove a directory, which has to be empty unless `contents` says
236    /// to delete what is in it too.
237    fn remove_dir(&mut self, name: &str, contents: bool) -> Result<(), FileError> {
238        let _ = (name, contents);
239        Err(FileError::Unsupported)
240    }
241
242    /// The names in a directory, without the path to it. A host whose
243    /// directories have entries for themselves and their parents includes
244    /// `.` and `..`.
245    fn list_dir(&mut self, name: &str) -> Option<Vec<String>> {
246        let _ = name;
247        None
248    }
249
250    /// The full name of a file, from a root.
251    fn absolute_path(&mut self, name: &str) -> Option<String> {
252        let _ = name;
253        None
254    }
255
256    /// The roots of the file system: `/` on some systems, a list of
257    /// drives on others.
258    fn root_dirs(&mut self) -> Vec<String> {
259        Vec::new()
260    }
261
262    /// Where a file is in relation to the folder the program's file
263    /// access is confined to. The default confines nothing.
264    fn sandbox(&mut self, name: &str) -> Sandbox {
265        let _ = name;
266        Sandbox::Inside
267    }
268
269    /// A name for a new temporary file, which does not exist yet.
270    fn temp_file_name(&mut self) -> Option<String> {
271        None
272    }
273
274    /// The name of one of the files that programs ask for by number
275    /// because where they are kept is up to the system: 1 is the file of
276    /// settings shared by every game that uses the standard library, and
277    /// 2 the same for the web interface.
278    fn special_file(&mut self, id: i32) -> Option<String> {
279        let _ = id;
280        None
281    }
282
283    /// Add to the end of a file, creating it if it is not there.
284    fn append_file(&mut self, name: &str, data: &[u8]) -> Result<(), FileError> {
285        let _ = (name, data);
286        Err(FileError::Unsupported)
287    }
288
289    /// Read a line of input from the player, without the line ending.
290    fn read_line(&mut self) -> Input {
291        Input::End
292    }
293
294    /// Read one keystroke. A key that types a character is that character;
295    /// Enter is a newline; any other key goes by its name in square
296    /// brackets, such as `[up]` or `[f1]`.
297    fn read_key(&mut self) -> Input {
298        Input::End
299    }
300
301    /// Ask the player for a file in a dialog of the system's own, with
302    /// the program's prompt as its title, or `None` for a host that has
303    /// no such dialog: the VM then asks for the file's name as a line of
304    /// input, after the prompt, as a console of text does.
305    fn choose_file(
306        &mut self,
307        prompt: &str,
308        dialog: FileDialog,
309        kind: FileKind,
310    ) -> Option<FileChoice> {
311        let _ = (prompt, dialog, kind);
312        None
313    }
314
315    /// Clear the main console.
316    fn clear_screen(&mut self) {}
317
318    /// The width of the main console in columns, if the host has one of
319    /// its own, such as a terminal window's. Text is broken into lines
320    /// that fit. Without one the width is 80 columns.
321    fn console_width(&mut self) -> Option<usize> {
322        None
323    }
324
325    /// Input has just come from a script instead of from the player. A
326    /// host that pauses when a screenful of text has gone by since the
327    /// player last typed starts counting again from here.
328    fn script_input(&mut self) {}
329
330    /// Pause for a number of milliseconds. A host that can wait does,
331    /// and returns true. One that cannot returns false, which stops the
332    /// VM where it is; when the time has passed, the host resumes the VM,
333    /// which asks again, and this time the answer is true.
334    fn sleep(&mut self, milliseconds: u32) -> bool {
335        let _ = milliseconds;
336        true
337    }
338
339    /// Show text in the status line: the left part, which is usually the
340    /// name of the player's location.
341    fn status_line(&mut self, text: &str) {
342        let _ = text;
343    }
344
345    /// Show text at the right of the status line, usually the score.
346    fn status_right(&mut self, text: &str) {
347        let _ = text;
348    }
349
350    /// The time now. A host without a clock reports the start of 1970,
351    /// which also keeps tests reproducible.
352    fn time(&mut self) -> Time {
353        Time::default()
354    }
355
356    /// The name of the host's time zone in the zoneinfo database, such as
357    /// `America/Chicago`, if the host knows it. Without one, local time
358    /// is UTC shifted by the offset that [`Host::time`] reports.
359    fn local_time_zone(&mut self) -> Option<String> {
360        None
361    }
362
363    /// A name for the system the host runs on.
364    fn system_name(&self) -> String {
365        std::env::consts::OS.to_owned()
366    }
367
368    /// Whether the host can show panes. Without them, a program
369    /// that asks for one is told it cannot have it, as on a plain
370    /// console.
371    fn has_panes(&self) -> bool {
372        false
373    }
374
375    /// Create a pane inside another, or inside the main window
376    /// if `parent` is `None`: its handle, or `None` if the host cannot.
377    fn pane_create(
378        &mut self,
379        parent: Option<u32>,
380        placement: pane::Placement,
381        spec: pane::PaneSpec,
382    ) -> Option<u32> {
383        let _ = (parent, placement, spec);
384        None
385    }
386
387    /// Remove a pane.
388    fn pane_delete(&mut self, id: u32) {
389        let _ = id;
390    }
391
392    /// Remove the text in a pane.
393    fn pane_clear(&mut self, id: u32) {
394        let _ = id;
395    }
396
397    /// Add text to a pane. The text is already broken into lines
398    /// that fit.
399    fn pane_write(&mut self, id: u32, text: &str) {
400        let _ = (id, text);
401    }
402
403    /// On a rich display: add what the program wrote to a text pane, as
404    /// it wrote it, markup and all, as [`Host::print_markup`] does for the
405    /// main window. A text grid's text still comes through
406    /// [`Host::pane_write`].
407    fn pane_write_markup(&mut self, id: u32, markup: &str) {
408        let _ = (id, markup);
409    }
410
411    /// Show what has been written to a pane.
412    fn pane_flush(&mut self, id: u32) {
413        let _ = id;
414    }
415
416    /// Change the size of a pane. See [`pane::Screen::set_size`].
417    fn pane_set_size(&mut self, id: u32, size: i32, units: i32, advisory: bool) {
418        let _ = (id, size, units, advisory);
419    }
420
421    /// Make a pane as big as what it holds.
422    fn pane_size_to_contents(&mut self, id: u32) {
423        let _ = id;
424    }
425
426    /// Move where text goes next in a text grid, counting from zero.
427    fn pane_go_to(&mut self, id: u32, row: usize, column: usize) {
428        let _ = (id, row, column);
429    }
430
431    /// What a program can learn about a pane.
432    fn pane_info(&mut self, id: u32) -> Option<pane::PaneInfo> {
433        let _ = id;
434        None
435    }
436
437    /// Give a pane a background color: one of the colors the
438    /// host chooses, such as [`pane::color::STATUS_BG`], or an RGB value.
439    fn pane_set_screen_color(&mut self, id: u32, color: u32) {
440        let _ = (id, color);
441    }
442}
443
444/// A host that collects console output in memory.
445///
446/// Clones share one buffer, so a caller can keep a clone, hand the other to
447/// a VM, and read the output afterward.
448#[derive(Debug, Default, Clone)]
449pub struct BufferHost {
450    output: Rc<RefCell<String>>,
451    files: Rc<RefCell<HashMap<String, Vec<u8>>>>,
452    input: Rc<RefCell<VecDeque<String>>>,
453    temp_counter: Rc<RefCell<u32>>,
454    interactive: Rc<RefCell<bool>>,
455    screen: Rc<RefCell<Option<pane::Screen>>>,
456}
457
458impl BufferHost {
459    /// A host with an empty buffer.
460    pub fn new() -> Self {
461        Self::default()
462    }
463
464    /// Everything displayed so far.
465    pub fn output(&self) -> String {
466        self.output.borrow().clone()
467    }
468
469    /// Queue a line for the program to read. A read of one key takes a
470    /// whole line too, as the name of the key.
471    pub fn push_input(&self, line: &str) {
472        self.input.borrow_mut().push_back(line.to_owned());
473    }
474
475    /// Say that more input may be queued later, so that running out is
476    /// not the end of input: the program is to stop and wait.
477    pub fn set_interactive(&self, interactive: bool) {
478        *self.interactive.borrow_mut() = interactive;
479    }
480
481    fn next_input(&self) -> Input {
482        match self.input.borrow_mut().pop_front() {
483            Some(line) => Input::Text(line),
484            None if *self.interactive.borrow() => Input::Pending,
485            None => Input::End,
486        }
487    }
488
489    /// The contents of a file the program wrote.
490    pub fn file(&self, name: &str) -> Option<Vec<u8>> {
491        self.files.borrow().get(name).cloned()
492    }
493
494    /// Show panes, on a screen of the given size.
495    pub fn enable_panes(&self, rows: usize, columns: usize) {
496        *self.screen.borrow_mut() = Some(pane::Screen::new(rows, columns, true));
497    }
498
499    /// The panes, if they are shown.
500    pub fn screen(&self) -> std::cell::Ref<'_, Option<pane::Screen>> {
501        self.screen.borrow()
502    }
503
504    fn with_screen<T>(&self, f: impl FnOnce(&mut pane::Screen) -> T) -> Option<T> {
505        self.screen.borrow_mut().as_mut().map(f)
506    }
507
508    /// Supply a file for the program to read.
509    pub fn set_file(&self, name: &str, data: &[u8]) {
510        self.files
511            .borrow_mut()
512            .insert(name.to_owned(), data.to_vec());
513    }
514}
515
516impl Host for BufferHost {
517    fn print(&mut self, text: &str) {
518        self.output.borrow_mut().push_str(text);
519    }
520
521    // Files are kept in memory, shared between clones like the output.
522    fn read_file(&mut self, name: &str) -> Result<Vec<u8>, FileError> {
523        self.files
524            .borrow()
525            .get(name)
526            .cloned()
527            .ok_or(FileError::NotFound)
528    }
529
530    fn write_file(&mut self, name: &str, data: &[u8]) -> Result<(), FileError> {
531        self.files
532            .borrow_mut()
533            .insert(name.to_owned(), data.to_vec());
534        Ok(())
535    }
536
537    fn append_file(&mut self, name: &str, data: &[u8]) -> Result<(), FileError> {
538        self.files
539            .borrow_mut()
540            .entry(name.to_owned())
541            .or_default()
542            .extend_from_slice(data);
543        Ok(())
544    }
545
546    // The files have no directories: a name is only a key.
547    fn file_info(&mut self, name: &str, _follow_links: bool) -> Option<FileInfo> {
548        self.files.borrow().get(name).map(|data| FileInfo {
549            kind: file_type::FILE,
550            attrs: file_attr::READ | file_attr::WRITE,
551            size: data.len() as u64,
552            ..FileInfo::default()
553        })
554    }
555
556    fn delete_file(&mut self, name: &str) -> Result<(), FileError> {
557        match self.files.borrow_mut().remove(name) {
558            Some(_) => Ok(()),
559            None => Err(FileError::NotFound),
560        }
561    }
562
563    fn rename_file(&mut self, from: &str, to: &str) -> Result<(), FileError> {
564        let mut files = self.files.borrow_mut();
565        if files.contains_key(to) {
566            return Err(FileError::Failed);
567        }
568        let data = files.remove(from).ok_or(FileError::NotFound)?;
569        files.insert(to.to_owned(), data);
570        Ok(())
571    }
572
573    fn temp_file_name(&mut self) -> Option<String> {
574        let mut counter = self.temp_counter.borrow_mut();
575        *counter += 1;
576        Some(format!("/tmp/temp{counter}"))
577    }
578
579    fn read_line(&mut self) -> Input {
580        self.next_input()
581    }
582
583    fn read_key(&mut self) -> Input {
584        self.next_input()
585    }
586
587    fn has_panes(&self) -> bool {
588        self.screen.borrow().is_some()
589    }
590
591    fn pane_create(
592        &mut self,
593        parent: Option<u32>,
594        placement: pane::Placement,
595        spec: pane::PaneSpec,
596    ) -> Option<u32> {
597        self.with_screen(|screen| screen.create(parent, placement, spec))
598            .flatten()
599    }
600
601    fn pane_delete(&mut self, id: u32) {
602        self.with_screen(|screen| screen.delete(id));
603    }
604
605    fn pane_clear(&mut self, id: u32) {
606        self.with_screen(|screen| screen.clear(id));
607    }
608
609    fn pane_write(&mut self, id: u32, text: &str) {
610        self.with_screen(|screen| screen.write(id, text));
611    }
612
613    fn pane_set_size(&mut self, id: u32, size: i32, units: i32, advisory: bool) {
614        self.with_screen(|screen| screen.set_size(id, size, units, advisory));
615    }
616
617    fn pane_size_to_contents(&mut self, id: u32) {
618        self.with_screen(|screen| screen.size_to_contents(id));
619    }
620
621    fn pane_go_to(&mut self, id: u32, row: usize, column: usize) {
622        self.with_screen(|screen| screen.go_to(id, row, column));
623    }
624
625    fn pane_info(&mut self, id: u32) -> Option<pane::PaneInfo> {
626        self.with_screen(|screen| screen.info(id)).flatten()
627    }
628
629    fn pane_set_screen_color(&mut self, id: u32, color: u32) {
630        self.with_screen(|screen| screen.set_screen_color(id, color));
631    }
632}