1use hexicon_host::{FileChoice, FileDialog, FileKind, Input};
9
10use crate::console::{Formatter, Newline};
11use crate::error::{VmError, VmResult, code};
12use crate::file::Access;
13use crate::load::CONSOLE_WIDTH;
14use crate::object::Object;
15use crate::value::Value;
16use crate::vm::Vm;
17
18const EVT_KEY: i32 = 1;
20const EVT_TIMEOUT: i32 = 2;
21const EVT_HREF: i32 = 3;
22const EVT_NOTIMEOUT: i32 = 4;
23const EVT_EOF: i32 = 5;
24const EVT_LINE: i32 = 6;
25const EVT_COMMAND: i32 = 0x100;
26const EVT_END_QUIET_SCRIPT: i32 = 10000;
27const EVT_DIALOG: i32 = 10001;
28const EVT_FILE: i32 = 10002;
29
30const ATTR_OVERWRITE: u32 = 1;
32
33const LINE_MAX: usize = 256;
36
37const SCRIPT_QUIET: i32 = 1;
39const SCRIPT_NONSTOP: i32 = 2;
40const SCRIPT_EVENT: i32 = 4;
41const SCRIPT_GET_STATUS: i32 = 0x7000;
42
43const EVENT_TAGS: [(&str, i32); 9] = [
45 ("key", EVT_KEY),
46 ("timeout", EVT_TIMEOUT),
47 ("notimeout", EVT_NOTIMEOUT),
48 ("eof", EVT_EOF),
49 ("line", EVT_LINE),
50 ("command", EVT_COMMAND),
51 ("endqs", EVT_END_QUIET_SCRIPT),
52 ("dialog", EVT_DIALOG),
53 ("file", EVT_FILE),
54];
55
56fn event_tag(event: i32) -> &'static str {
59 if event == EVT_HREF {
60 return "href";
61 }
62 EVENT_TAGS
63 .iter()
64 .find(|(_, code)| *code == event)
65 .map_or("", |(tag, _)| tag)
66}
67
68fn is_space(c: u8) -> bool {
70 matches!(c, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')
71}
72
73fn truncate(text: &mut Vec<u8>, max: usize) {
75 if text.len() > max {
76 let mut len = max;
77 while len > 0 && text[len] & 0xc0 == 0x80 {
78 len -= 1;
79 }
80 text.truncate(len);
81 }
82}
83
84fn leading_int(text: &[u8]) -> i32 {
86 let mut rest = text;
87 while let [first, tail @ ..] = rest {
88 if !is_space(*first) {
89 break;
90 }
91 rest = tail;
92 }
93 let negative = match rest {
94 [b'-', tail @ ..] => {
95 rest = tail;
96 true
97 }
98 [b'+', tail @ ..] => {
99 rest = tail;
100 false
101 }
102 _ => false,
103 };
104 let mut value: i32 = 0;
105 for &c in rest {
106 if !c.is_ascii_digit() {
107 break;
108 }
109 value = value.wrapping_mul(10).wrapping_add(i32::from(c - b'0'));
110 }
111 if negative {
112 value.wrapping_neg()
113 } else {
114 value
115 }
116}
117
118#[derive(Debug)]
120struct Script {
121 data: Vec<u8>,
122 pos: usize,
123 quiet: bool,
125 more_mode: bool,
127 events: bool,
129}
130
131impl Script {
132 fn getc(&mut self) -> Option<u8> {
133 let c = self.data.get(self.pos).copied();
134 if c.is_some() {
135 self.pos += 1;
136 }
137 c
138 }
139
140 fn skip_line(&mut self) {
141 while let Some(c) = self.getc() {
142 if c == b'\n' || c == b'\r' {
143 break;
144 }
145 }
146 }
147
148 fn read_param(&mut self, max: usize) -> Vec<u8> {
150 let mut out = Vec::new();
151 loop {
152 match self.getc() {
153 None | Some(b'\n') => break,
154 Some(c) => {
155 if out.len() + 1 < max {
156 out.push(c);
157 }
158 }
159 }
160 }
161 truncate(&mut out, max - 1);
162 out
163 }
164
165 fn read_token(&mut self) -> (Vec<u8>, Option<u8>) {
167 let mut c = self.getc();
168 while c.is_some_and(is_space) {
169 c = self.getc();
170 }
171 let mut out = Vec::new();
172 while let Some(ch) = c {
173 if out.len() >= 31 || ch == b'>' || is_space(ch) {
174 break;
175 }
176 out.push(ch);
177 c = self.getc();
178 }
179 (out, c)
180 }
181
182 fn read_event_type(&mut self) -> Option<(i32, u32)> {
184 if !self.events {
185 loop {
187 match self.getc()? {
188 b'>' => return Some((EVT_LINE, 0)),
189 _ => self.skip_line(),
190 }
191 }
192 }
193 loop {
194 if self.getc()? != b'<' {
195 self.skip_line();
196 continue;
197 }
198 let (tag, mut c) = self.read_token();
199 let mut attrs = 0;
200 while c.is_some_and(is_space) {
201 let (attr, next) = self.read_token();
202 c = next;
203 if attr.is_empty() {
204 break;
205 }
206 if attr.eq_ignore_ascii_case(b"overwrite") {
207 attrs |= ATTR_OVERWRITE;
208 }
209 if matches!(c, Some(b'>' | b'\n' | b'\r') | None) {
210 break;
211 }
212 }
213 if c != Some(b'>') {
214 self.skip_line();
215 continue;
216 }
217 let found = EVENT_TAGS
218 .iter()
219 .find(|(name, _)| tag.eq_ignore_ascii_case(name.as_bytes()));
220 match found {
221 Some((_, event)) => return Some((*event, attrs)),
222 None => self.skip_line(),
223 }
224 }
225 }
226
227 fn read_line(&mut self) -> Option<(i32, Vec<u8>)> {
229 loop {
230 if self.events {
231 let (event, _) = self.read_event_type()?;
232 match event {
233 EVT_LINE | EVT_TIMEOUT => return Some((event, self.read_param(LINE_MAX))),
234 _ => self.skip_line(),
235 }
236 } else {
237 match self.getc()? {
238 b'>' => return Some((EVT_LINE, self.read_param(LINE_MAX))),
239 b'\n' | b'\r' => {}
240 _ => self.skip_line(),
241 }
242 }
243 }
244 }
245}
246
247#[derive(Debug)]
249struct LogFile {
250 name: String,
251 formatter: Formatter,
252}
253
254#[derive(Debug)]
256struct CommandLog {
257 name: String,
258 events: bool,
261}
262
263#[derive(Debug)]
266pub(crate) struct IoState {
267 status: Option<Formatter>,
269 in_status: bool,
271 log: Option<LogFile>,
273 command_log: Option<CommandLog>,
274 scripts: Vec<Script>,
276 read_in_progress: bool,
278 read_buf: Vec<u8>,
280 log_consoles: Vec<Option<LogFile>>,
282 pub(crate) panes: Vec<Option<crate::pane::Pane>>,
284 tick_zero: Option<i64>,
287 pub(crate) safety_read: u8,
290 pub(crate) safety_write: u8,
291 pub(crate) open_files: Vec<crate::value::ObjId>,
293 pub(crate) resources: crate::file::Resources,
295 pub(crate) zones: crate::tz::ZoneCache,
297 pub(crate) save_time: (i32, i32),
299 pub(crate) resumable: bool,
302 pub(crate) suspended: Option<(u32, usize)>,
305 pub(crate) varargc: Option<i32>,
308 prompt_shown: bool,
311}
312
313impl Default for IoState {
314 fn default() -> Self {
315 Self {
316 status: None,
317 in_status: false,
318 log: None,
319 command_log: None,
320 scripts: Vec::new(),
321 read_in_progress: false,
322 read_buf: Vec::new(),
323 log_consoles: Vec::new(),
324 panes: Vec::new(),
325 tick_zero: None,
326 safety_read: 2,
329 safety_write: 2,
330 open_files: Vec::new(),
331 resources: crate::file::Resources::new(),
332 zones: crate::tz::ZoneCache::default(),
333 save_time: (0, 0),
334 resumable: false,
335 suspended: None,
336 varargc: None,
337 prompt_shown: false,
338 }
339 }
340}
341
342impl Vm {
343 pub(crate) fn print(&mut self, text: &[u8]) {
347 if self.io.in_status {
348 if let Some(status) = &mut self.io.status {
349 status.format_text(text);
350 }
351 return;
352 }
353 if self.host.rich_display().is_some() {
354 if !self.io.scripts.last().is_some_and(|script| script.quiet) {
357 self.host.print_markup(&String::from_utf8_lossy(text));
358 }
359 } else {
360 self.console.format_text(text);
361 self.send_output();
362 }
363 if let Some(log) = &mut self.io.log {
364 log.formatter.format_text(text);
365 self.send_log();
366 }
367 }
368
369 pub(crate) fn sync_console_width(&mut self) {
373 self.flush_panes();
375 let width = self.host.console_width().unwrap_or(CONSOLE_WIDTH);
376 self.console.set_width(width);
377 }
378
379 fn send_output(&mut self) {
382 let output = self.console.take_output();
383 if !output.is_empty() && !self.io.scripts.last().is_some_and(|script| script.quiet) {
384 self.host.print(&output);
385 }
386 }
387
388 fn send_log(&mut self) {
390 if let Some(log) = &mut self.io.log {
391 let output = log.formatter.take_output();
392 if !output.is_empty() {
393 let _ = self.host.append_file(&log.name, output.as_bytes());
396 }
397 }
398 }
399
400 fn log_enabled(&self) -> bool {
402 !self.io.in_status && self.io.log.is_some()
403 }
404
405 pub(crate) fn flush_console(&mut self, newline: Newline) {
407 if self.io.in_status {
408 if let Some(status) = &mut self.io.status {
409 status.flush(newline);
410 }
411 return;
412 }
413 self.console.flush(newline);
414 self.send_output();
415 if let Some(log) = &mut self.io.log {
416 log.formatter.flush(newline);
417 self.send_log();
418 }
419 }
420
421 fn log_raw(&mut self, text: &[u8]) {
423 if let Some(log) = &mut self.io.log {
424 log.formatter.write_raw(&String::from_utf8_lossy(text));
425 self.send_log();
426 }
427 }
428
429 fn note_input_line(&mut self) {
431 if self.io.in_status {
432 if let Some(status) = &mut self.io.status {
433 status.note_input_line();
434 }
435 } else {
436 self.console.note_input_line();
437 }
438 if let Some(log) = &mut self.io.log {
439 log.formatter.note_input_line();
440 }
441 }
442
443 fn set_status_mode(&mut self, on: bool) {
445 if on && self.io.status.is_none() {
446 self.io.status = Some(Formatter::new(CONSOLE_WIDTH));
447 }
448 if on == self.io.in_status {
449 return;
450 }
451 self.io.in_status = on;
452 if !on && let Some(status) = &mut self.io.status {
453 status.format_text(b"\n");
454 status.flush(Newline::None);
455 let text = status.take_output();
456 self.host.status_line(text.trim_end());
457 }
458 }
459
460 pub fn push_input_script(&mut self, data: &[u8], quiet: bool, pause_output: bool) {
467 let mut text = Vec::with_capacity(data.len());
470 for (index, &c) in data.iter().enumerate() {
471 if c != b'\r' || data.get(index + 1) != Some(&b'\n') {
472 text.push(c);
473 }
474 }
475 const HEADER: &[u8] = b"<eventscript>\n";
476 let events = text.starts_with(HEADER);
477 let mut quiet = quiet;
478 let mut more_mode = pause_output;
479 if let Some(enclosing) = self.io.scripts.last() {
480 quiet |= enclosing.quiet;
481 more_mode &= enclosing.more_mode;
482 }
483 self.io.scripts.push(Script {
484 data: text,
485 pos: if events { HEADER.len() } else { 0 },
486 quiet,
487 more_mode,
488 events,
489 });
490 }
491
492 fn log_event(&mut self, tag: &[u8], param: Option<&[u8]>) {
494 let Some(log) = &self.io.command_log else {
495 return;
496 };
497 let tag = tag.strip_prefix(b"<").unwrap_or(tag);
498 let name = tag.strip_suffix(b">").unwrap_or(tag);
499 let mut out = Vec::new();
500 if log.events {
501 let mut param = param;
502 if name.eq_ignore_ascii_case(b"key") {
503 param = match param {
504 Some(b"\n") => Some(b"[enter]"),
505 Some(b"\t") => Some(b"[tab]"),
506 Some(b" ") => Some(b"[space]"),
507 other => other,
508 };
509 }
510 if name.eq_ignore_ascii_case(b"notimeout") || name.eq_ignore_ascii_case(b"eof") {
511 param = None;
512 }
513 if !name.is_empty() {
514 out.push(b'<');
517 out.extend_from_slice(tag);
518 out.push(b'>');
519 out.extend_from_slice(param.unwrap_or_default());
520 out.push(b'\n');
521 }
522 } else if name.eq_ignore_ascii_case(b"line")
523 && let Some(param) = param
524 {
525 out.push(b'>');
526 out.extend_from_slice(param);
527 out.push(b'\n');
528 }
529 if !out.is_empty() {
530 let _ = self.host.append_file(&log.name, &out);
531 }
532 }
533
534 fn read_line_done(&mut self) {
538 if !self.io.read_in_progress {
539 return;
540 }
541 if self.log_enabled() && self.io.scripts.last().is_none_or(|script| script.quiet) {
545 let mut text = self.io.read_buf.clone();
546 text.push(b'\n');
547 self.log_raw(&text);
548 }
549 self.note_input_line();
550 self.io.read_in_progress = false;
551 }
552
553 fn read_line_timeout(
557 &mut self,
558 timeout: Option<i32>,
559 bypass_script: bool,
560 ) -> VmResult<(i32, Vec<u8>)> {
561 let mut event = 0;
562 let mut from_script = false;
563 let mut echo = false;
564 if !self.io.read_in_progress {
565 self.flush_console(Newline::Input);
566 }
567 while let Some(script) = self.io.scripts.last_mut().filter(|_| !bypass_script) {
568 let was_quiet = script.quiet;
569 if let Some((found, line)) = script.read_line() {
570 self.io.read_buf = line;
571 event = found;
572 from_script = true;
573 echo = !was_quiet;
574 break;
575 }
576 self.io.scripts.pop();
579 let enclosing = self.io.scripts.last().map(|script| script.quiet);
580 if enclosing == Some(was_quiet) {
581 continue;
582 }
583 self.flush_console(Newline::None);
584 if was_quiet && enclosing != Some(true) {
585 if self.log_enabled() {
588 self.log_raw(b"\n");
589 }
590 self.note_input_line();
591 self.log_event(event_tag(EVT_END_QUIET_SCRIPT).as_bytes(), None);
592 return Ok((EVT_END_QUIET_SCRIPT, Vec::new()));
593 }
594 if enclosing.is_none() {
595 break;
596 }
597 }
598 if from_script {
599 self.host.script_input();
600 } else {
601 if timeout.is_some() {
602 event = EVT_NOTIMEOUT;
603 } else {
604 self.sync_console_width();
608 match self.host.read_line() {
609 Input::Text(line) => {
610 self.io.read_buf = line.into_bytes();
611 event = EVT_LINE;
612 self.note_input_line();
613 }
614 Input::End => event = EVT_EOF,
615 Input::Pending => return Err(self.suspend()),
616 }
617 }
618 }
619 self.io.read_in_progress = true;
620 if event == EVT_EOF {
621 self.read_line_done();
622 self.log_event(event_tag(event).as_bytes(), None);
623 return Ok((event, Vec::new()));
624 }
625 let mut line = self.io.read_buf.clone();
626 truncate(&mut line, LINE_MAX - 1);
627 if echo {
628 if self.host.rich_display().is_some() {
629 if !self.io.scripts.last().is_some_and(|script| script.quiet) {
631 self.host.print_input(&String::from_utf8_lossy(&line));
632 }
633 if let Some(log) = &mut self.io.log {
634 log.formatter.format_text(&line);
635 log.formatter.format_text(b"\n");
636 self.send_log();
637 }
638 } else {
639 self.print(&line);
640 self.print(b"\n");
641 }
642 }
643 if event == EVT_LINE {
644 self.read_line_done();
645 }
646 let logged = self.io.read_buf.clone();
647 self.log_event(event_tag(event).as_bytes(), Some(&logged));
648 Ok((event, line))
649 }
650
651 fn suspend(&self) -> VmError {
655 if self.io.resumable && self.run_depth <= 1 {
656 VmError::Suspend
657 } else {
658 VmError::unimplemented(
659 "waiting for input inside a callback, on a host that cannot wait",
660 )
661 }
662 }
663
664 fn read_line(&mut self, bypass_script: bool) -> VmResult<Option<Vec<u8>>> {
668 self.read_line_done();
669 loop {
670 match self.read_line_timeout(None, bypass_script)? {
671 (EVT_LINE, line) => return Ok(Some(line)),
672 (EVT_END_QUIET_SCRIPT, _) => {}
673 _ => return Ok(None),
674 }
675 }
676 }
677
678 fn read_event_script(&mut self, filter: &[i32], max: usize) -> Option<(i32, Vec<u8>, u32)> {
681 if !self.io.scripts.last()?.events {
682 return None;
683 }
684 loop {
685 let script = self.io.scripts.last_mut()?;
686 let Some((event, attrs)) = script.read_event_type() else {
687 self.io.scripts.pop();
688 continue;
689 };
690 if !filter.contains(&event) {
691 script.skip_line();
692 continue;
693 }
694 let mut param = script.read_param(max);
695 if event == EVT_KEY {
696 match param.as_slice() {
697 b"[enter]" => param = b"\n".to_vec(),
698 b"[tab]" => param = b"\t".to_vec(),
699 b"[space]" => param = b" ".to_vec(),
700 _ => {}
701 }
702 }
703 self.host.script_input();
704 return Some((event, param, attrs));
705 }
706 }
707
708 fn read_key(&mut self) -> VmResult<Option<Vec<u8>>> {
710 self.sync_console_width();
711 Ok(match self.host.read_key() {
712 Input::Text(key) => Some(match key.as_str() {
713 "\r" | "\r\n" => b"\n".to_vec(),
714 _ => key.into_bytes(),
715 }),
716 Input::End => None,
717 Input::Pending => return Err(self.suspend()),
718 })
719 }
720
721 fn event_list(&mut self, event: i32, len: usize) -> Value {
725 let mut items = vec![Value::Nil; len];
726 items[0] = Value::Int(event);
727 self.new_list(items)
728 }
729
730 fn set_list_item(&mut self, list: Value, index: usize, value: Value) {
731 if let Some(Object::List(items)) = self.objects.get_mut(list.obj_id()) {
732 let mut changed = items.to_vec();
733 changed[index] = value;
734 *items = changed.into();
735 }
736 }
737
738 fn text_dialog(
743 &mut self,
744 prompt: &str,
745 buttons: &[String],
746 bypass_script: bool,
747 ) -> VmResult<i32> {
748 if buttons.is_empty() {
749 return Ok(0);
750 }
751 let shortcut = |label: &str| {
753 let mut chars = label.chars().skip_while(|&c| c != '&');
754 chars.next().and_then(|_| chars.next())
755 };
756 let same = |a: char, b: char| a.to_uppercase().eq(b.to_uppercase());
757 loop {
758 let mut text = format!("\n{prompt} ");
759 for (index, label) in buttons.iter().enumerate() {
760 if index != 0 {
761 text.push('/');
762 }
763 match label.split_once('&') {
764 Some((before, after)) => {
765 let mut rest = after.chars();
766 let key = rest.next().unwrap_or('\0');
767 text.push_str(&format!("{before}({key}){}", rest.as_str()));
768 }
769 None => text.push_str(label),
770 }
771 }
772 text.push_str("<font face='hexicon-input'> >");
773 if !self.io.prompt_shown {
776 self.print(text.as_bytes());
777 self.io.prompt_shown = true;
778 }
779 let line = self.read_line(bypass_script)?;
780 self.io.prompt_shown = false;
781 self.print(b"</font>");
782 let Some(line) = line else {
783 return Ok(0);
784 };
785 let line = String::from_utf8_lossy(&line).into_owned();
786 let response = line.trim_start();
787 let mut letters = response.chars();
788 if let (Some(letter), None) = (letters.next(), letters.next()) {
789 let chosen = buttons
790 .iter()
791 .position(|label| shortcut(label).is_some_and(|key| same(key, letter)));
792 if let Some(index) = chosen {
793 return Ok(index as i32 + 1);
794 }
795 }
796 let matches: Vec<usize> = (0..buttons.len())
798 .filter(|&index| {
799 let mut label = buttons[index].chars().filter(|&c| c != '&');
800 response
801 .chars()
802 .all(|c| label.next().is_some_and(|l| same(c, l)))
803 })
804 .collect();
805 if let [index] = matches.as_slice() {
806 return Ok(*index as i32 + 1);
807 }
808 }
809 }
810
811 pub(crate) fn get_time(&mut self, kind: i32) -> VmResult<Value> {
814 let time = self.host.time();
815 match kind {
816 1 => {
817 let seconds = time.unix_millis.div_euclid(1000);
818 let (mut dayno, mut daytime) = self.now();
819 self.local_zone().utc_to_local(&mut dayno, &mut daytime);
820 let date = crate::date::CalDate::from_dayno(dayno);
821 let day_of_year = dayno - crate::date::CalDate::new(date.y, 1, 1).dayno() + 1;
822 let second_of_day = daytime / 1000;
823 let mut items: Vec<Value> = [
825 date.y,
826 date.m,
827 date.d,
828 date.weekday() + 1,
829 day_of_year,
830 second_of_day / 3600,
831 second_of_day / 60 % 60,
832 second_of_day % 60,
833 ]
834 .iter()
835 .map(|&n| Value::Int(n))
836 .collect();
837 items.push(match i32::try_from(seconds) {
840 Ok(seconds) => Value::Int(seconds),
841 Err(_) => {
842 let big = crate::decimal::Big::from_int(seconds, 20);
843 self.new_big(big)
844 }
845 });
846 Ok(self.new_list(items))
847 }
848 2 => {
849 let zero = *self.io.tick_zero.get_or_insert(time.unix_millis);
850 Ok(Value::Int(
851 (time.unix_millis.wrapping_sub(zero) & 0x7fff_ffff) as i32,
852 ))
853 }
854 _ => Err(VmError::new(code::BAD_VAL_BIF)),
855 }
856 }
857
858 pub(crate) fn bif_io(&mut self, index: u16, argc: u32) -> VmResult<bool> {
863 let bad_value = || VmError::new(code::BAD_VAL_BIF);
864 match index {
865 1 => {
867 Self::check_argc_range(argc, 1, 2)?;
868 let file = self.arg(0);
869 let kind = if argc >= 2 {
870 self.cast_to_int(self.arg(1))?
871 } else {
872 1
873 };
874 if !(1..=3).contains(&kind) {
875 return Err(bad_value());
876 }
877 let mut ok = true;
878 if file == Value::Nil {
879 if kind == 1 {
880 self.io.log = None;
881 } else {
882 self.io.command_log = None;
883 }
884 } else {
885 let name = self.file_name_arg(file, Access::Write)?;
886 let start: &[u8] = if kind == 3 { b"<eventscript>\n" } else { b"" };
887 ok = self.host.write_file(&name, start).is_ok();
888 if kind == 1 {
889 self.io.log = ok.then(|| LogFile {
890 name,
891 formatter: Formatter::new(CONSOLE_WIDTH),
892 });
893 } else {
894 self.io.command_log = ok.then_some(CommandLog {
895 name,
896 events: kind == 3,
897 });
898 }
899 }
900 self.r0 = if ok { Value::True } else { Value::Nil };
901 }
902 2 => {
904 Self::check_argc(argc, 0)?;
905 self.flush_console(Newline::None);
906 if self.io.in_status {
907 if let Some(status) = &mut self.io.status {
908 status.empty_buffers();
909 }
910 } else {
911 self.console.empty_buffers();
912 if let Some(log) = &mut self.io.log {
913 log.formatter.empty_buffers();
914 }
915 self.host.clear_screen();
916 }
917 }
918 3 => {
920 Self::check_argc(argc, 0)?;
921 if self.io.scripts.is_empty() {
922 self.flush_console(Newline::None);
923 if !self.io.prompt_shown {
924 self.host.print("[More]");
925 self.io.prompt_shown = true;
926 }
927 while let Some(key) = self.read_key()? {
928 if matches!(key.as_slice(), b" " | b"\n") {
929 break;
930 }
931 }
932 self.io.prompt_shown = false;
933 self.host.print("\r \r");
934 }
935 }
936 4 => {
938 Self::check_argc(argc, 0)?;
939 self.r0 = match self.read_line(false)? {
940 Some(line) => self.try_new_string(line)?,
941 None => Value::Nil,
942 };
943 }
944 5 => {
946 Self::check_argc(argc, 0)?;
947 let key = match self.read_event_script(&[EVT_KEY], 32) {
948 Some((_, key, _)) => key,
949 None => {
950 self.flush_console(Newline::Input);
951 self.read_key()?.unwrap_or_else(|| b"[eof]".to_vec())
952 }
953 };
954 self.r0 = self.try_new_string(key.clone())?;
955 self.log_event(b"key", Some(&key));
956 }
957 6 => {
959 Self::check_argc_range(argc, 0, 1)?;
960 let timeout = self.timeout_arg(argc)?;
961 const FILTER: [i32; 6] = [
962 EVT_KEY,
963 EVT_TIMEOUT,
964 EVT_NOTIMEOUT,
965 EVT_HREF,
966 EVT_EOF,
967 EVT_COMMAND,
968 ];
969 let (event, param) = match self.read_event_script(&FILTER, 1024) {
970 Some((event, param, _)) => (event, param),
971 None => {
972 self.flush_console(Newline::Input);
973 if timeout.is_some() {
974 (EVT_NOTIMEOUT, Vec::new())
975 } else {
976 match self.read_key()? {
977 Some(key) => (EVT_KEY, key),
978 None => (EVT_EOF, Vec::new()),
979 }
980 }
981 }
982 };
983 let has_detail = matches!(event, EVT_KEY | EVT_HREF | EVT_COMMAND);
984 let list = self.event_list(event, if has_detail { 2 } else { 1 });
985 let tag = event_tag(event).as_bytes();
986 match event {
987 EVT_KEY | EVT_HREF => {
988 let text = self.try_new_string(param.clone())?;
989 self.set_list_item(list, 1, text);
990 self.log_event(tag, Some(¶m));
991 }
992 EVT_COMMAND => {
993 let command = leading_int(¶m);
994 self.set_list_item(list, 1, Value::Int(command));
995 self.log_event(tag, Some(command.to_string().as_bytes()));
996 }
997 _ => self.log_event(tag, None),
998 }
999 self.r0 = list;
1000 }
1001 7 => {
1003 Self::check_argc(argc, 5)?;
1004 self.int_arg(self.arg(0))?;
1005 let prompt = self.require_str(self.arg(1))?;
1006 let prompt = String::from_utf8_lossy(&prompt).into_owned();
1007 let buttons = self.dialog_buttons(self.arg(2))?;
1008 let choice = |vm: &Self, value: Value| match value {
1009 Value::Nil => Ok(0),
1010 _ => vm.int_arg(value),
1011 };
1012 choice(self, self.arg(3))?;
1013 choice(self, self.arg(4))?;
1014 let response = match self.read_event_script(&[EVT_DIALOG], 32) {
1015 Some((_, param, _)) => {
1016 self.log_event(b"dialog", Some(¶m));
1017 leading_int(¶m)
1018 }
1019 None => {
1020 self.flush_console(Newline::Input);
1021 let response = self.text_dialog(&prompt, &buttons, false)?;
1022 self.log_event(b"dialog", Some(response.to_string().as_bytes()));
1023 response
1024 }
1025 };
1026 self.r0 = Value::Int(response);
1027 }
1028 8 => {
1030 Self::check_argc(argc, 4)?;
1031 let prompt = self.require_str(self.arg(0))?;
1032 let prompt = String::from_utf8_lossy(&prompt).into_owned();
1033 let dialog = self.int_arg(self.arg(1))?;
1034 let kind = FileKind::from_code(self.int_arg(self.arg(2))?.into());
1035 self.cast_to_int(self.arg(3))?;
1036 self.r0 = self.input_file(&prompt, dialog, kind)?;
1037 }
1038 9 => {
1040 Self::check_argc(argc, 1)?;
1041 let delay = self.cast_to_int(self.arg(0))?;
1042 self.flush_console(Newline::None);
1043 if !self.host.sleep(delay.max(0) as u32) {
1044 return Err(self.suspend());
1045 }
1046 }
1047 10 => {
1049 if argc < 1 {
1050 return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
1051 }
1052 let which = self.int_arg(self.arg(0))?;
1053 if (1..=18).contains(&which) || (20..=34).contains(&which) {
1054 Self::check_argc(argc, 1)?;
1055 }
1056 self.r0 = match which {
1057 1 => Value::True,
1058 2 => {
1059 let version = crate::identity::version_number();
1060 self.new_str(&format!(
1061 "{}.{}.{}",
1062 (version >> 16) & 0xffff,
1063 (version >> 8) & 0xff,
1064 version & 0xff
1065 ))
1066 }
1067 3 => {
1068 let name = self.host.system_name();
1069 self.new_str(&name)
1070 }
1071 33 => Value::Int(i32::from(self.host.has_panes())),
1073 which if self.host.rich_display().is_some() => {
1076 let display = self
1077 .host
1078 .rich_display()
1079 .unwrap_or_else(hexicon_host::rich::RichDisplay::full);
1080 Value::Int(rich_system_info(which, &display))
1081 }
1082 4..=18 | 20..=27 | 31 | 32 => Value::Int(0),
1085 34 => Value::Int(1),
1087 _ => Value::Nil,
1088 };
1089 }
1090 11 => {
1092 Self::check_argc(argc, 1)?;
1093 let mode = self.int_arg(self.arg(0))?;
1094 self.set_status_mode(mode != 0);
1095 }
1096 12 => {
1098 Self::check_argc(argc, 1)?;
1099 let text = self.require_str(self.arg(0))?;
1100 self.host.status_right(&String::from_utf8_lossy(&text));
1101 }
1102 13 => {
1104 Self::check_argc(argc, 1)?;
1105 let name = self.require_str(self.arg(0))?;
1106 let name = String::from_utf8_lossy(&name).into_owned();
1107 self.r0 = Value::logical(self.resource_exists(&name));
1108 }
1109 14 => {
1111 Self::check_argc_range(argc, 1, 2)?;
1112 match self.arg(0) {
1113 Value::Nil => {
1114 self.io.scripts.pop();
1115 self.r0 = Value::True;
1116 }
1117 Value::Int(SCRIPT_GET_STATUS) => {
1118 self.r0 = match self.io.scripts.last() {
1119 Some(script) => Value::Int(
1120 if script.quiet { SCRIPT_QUIET } else { 0 }
1121 | if script.more_mode { 0 } else { SCRIPT_NONSTOP }
1122 | if script.events { SCRIPT_EVENT } else { 0 },
1123 ),
1124 None => Value::Nil,
1125 };
1126 }
1127 Value::Int(_) => return Err(bad_value()),
1128 file => {
1129 let flags = if argc >= 2 {
1130 self.cast_to_int(self.arg(1))?
1131 } else {
1132 0
1133 };
1134 let name = self.file_name_arg(file, Access::Read)?;
1135 self.sync_files();
1136 self.r0 = match self.host.read_file(&name) {
1137 Ok(data) => {
1138 self.push_input_script(
1139 &data,
1140 flags & SCRIPT_QUIET != 0,
1141 flags & SCRIPT_NONSTOP == 0,
1142 );
1143 Value::True
1144 }
1145 Err(_) => Value::Nil,
1146 };
1147 }
1148 }
1149 }
1150 15 => {
1152 Self::check_argc(argc, 1)?;
1153 self.r0 = match self.int_arg(self.arg(0))? {
1154 1..=3 => self.new_str("utf8"),
1155 _ => Value::Nil,
1156 };
1157 }
1158 16 => {
1160 Self::check_argc(argc, 0)?;
1161 self.flush_console(Newline::None);
1162 }
1163 17 => {
1165 Self::check_argc_range(argc, 0, 1)?;
1166 let timeout = self.timeout_arg(argc)?;
1167 let (event, line) = self.read_line_timeout(timeout, false)?;
1168 let has_text = matches!(event, EVT_LINE | EVT_TIMEOUT);
1169 let list = self.event_list(event, if has_text { 2 } else { 1 });
1170 if has_text {
1171 let text = self.try_new_string(line)?;
1172 self.set_list_item(list, 1, text);
1173 }
1174 self.r0 = list;
1175 }
1176 18 => {
1178 Self::check_argc(argc, 1)?;
1179 self.read_line_done();
1180 }
1181 19..=29 => self.bif_pane(index, argc)?,
1183 30 => {
1185 Self::check_argc(argc, 3)?;
1186 let width = self.cast_to_int(self.arg(2))?;
1187 let name = self.file_name_arg(self.arg(0), Access::Write)?;
1188 if self.host.write_file(&name, b"").is_err() {
1189 let class = self.predef.file_creation_exc;
1190 return Err(self.throw_class(class, "error creating log file"));
1191 }
1192 let console = LogFile {
1193 name,
1194 formatter: Formatter::new(width.max(1) as usize),
1195 };
1196 let slot = match self.io.log_consoles.iter().position(Option::is_none) {
1197 Some(slot) => slot,
1198 None => {
1199 self.io.log_consoles.push(None);
1200 self.io.log_consoles.len() - 1
1201 }
1202 };
1203 self.io.log_consoles[slot] = Some(console);
1204 self.r0 = Value::Int(slot as i32 + 1);
1205 }
1206 31 => {
1208 Self::check_argc(argc, 1)?;
1209 let slot = self.log_console_arg(self.arg(0))?;
1210 if let Some(mut console) = self.io.log_consoles[slot].take() {
1211 console.formatter.flush(Newline::None);
1212 let output = console.formatter.take_output();
1213 let _ = self.host.append_file(&console.name, output.as_bytes());
1214 }
1215 self.r0 = Value::Nil;
1216 }
1217 32 => {
1219 Self::check_argc_range(argc, 1, 32767)?;
1220 let handle = self.int_arg(self.arg(0))?;
1221 let slot = if handle == -1 {
1223 None
1224 } else {
1225 Some(self.log_console_arg(self.arg(0))?)
1226 };
1227 for index in 1..argc as usize {
1228 let Some(text) = self.say_text(self.arg(index))? else {
1229 continue;
1230 };
1231 match slot {
1232 Some(slot) => {
1233 if let Some(console) = &mut self.io.log_consoles[slot] {
1234 console.formatter.format_text(&text);
1235 let output = console.formatter.take_output();
1236 let _ = self.host.append_file(&console.name, output.as_bytes());
1237 }
1238 }
1239 None => {
1240 if self.log_enabled() {
1241 if let Some(log) = &mut self.io.log {
1242 log.formatter.format_text(&text);
1243 }
1244 self.send_log();
1245 }
1246 }
1247 }
1248 }
1249 }
1250 33 => {
1252 Self::check_argc(argc, 1)?;
1253 let event = self.arg(0);
1254 let Some(len) = self.list_like_len(event)? else {
1255 return Err(VmError::new(code::BAD_TYPE_BIF));
1256 };
1257 if len < 1 {
1258 return Err(bad_value());
1259 }
1260 let kind = self.list_like_get(event, 1)?;
1261 let param = if len >= 2 {
1262 let value = self.list_like_get(event, 2)?;
1263 Some(self.path_of(value).ok_or_else(bad_value)?.into_bytes())
1264 } else {
1265 None
1266 };
1267 if let Some(text) = self.as_str(kind) {
1268 let mut tag = text.to_vec();
1269 truncate(&mut tag, 127);
1270 self.log_event(&tag, param.as_deref());
1271 } else if matches!(kind, Value::Int(_)) || self.as_big(kind).is_some() {
1272 let code = self.cast_to_int(kind)?;
1273 self.log_event(event_tag(code).as_bytes(), param.as_deref());
1274 } else {
1275 return Err(bad_value());
1276 }
1277 self.r0 = Value::Nil;
1278 }
1279 _ => {
1280 return Ok(false);
1281 }
1282 }
1283 Ok(true)
1284 }
1285
1286 fn input_file(&mut self, prompt: &str, dialog: i32, kind: FileKind) -> VmResult<Value> {
1289 const SUCCESS: i32 = 0;
1290 const FAILURE: i32 = 1;
1291 const CANCEL: i32 = 2;
1292 const OPEN: i32 = 1;
1293 const SAVE: i32 = 2;
1294 let mut name;
1295 let mut from_ui = false;
1296 let mut result;
1297 self.sync_files();
1298 if let Some((_, param, attrs)) = self.read_event_script(&[EVT_FILE], 1024) {
1299 name = String::from_utf8_lossy(¶m).into_owned();
1300 result = if name.is_empty() { CANCEL } else { SUCCESS };
1301 let mut warning = String::new();
1304 if result == SUCCESS {
1305 let exists = self.host.file_info(&name, true).is_some();
1306 if dialog == SAVE && attrs & ATTR_OVERWRITE == 0 && exists {
1307 warning = format!("The script might overwrite the file {name}. ");
1308 } else if dialog == SAVE && !exists && !self.can_create(&name) {
1309 warning = format!(
1310 "The script is attempting to write file {name}, \
1311 but that file cannot be written."
1312 );
1313 } else if dialog == OPEN && !exists {
1314 warning = format!(
1315 "The script is attempting to open file {name}, \
1316 but this file doesn't exist or isn't readable."
1317 );
1318 }
1319 }
1320 if !warning.is_empty() {
1321 let question = format!(
1322 "{warning} Do you wish to proceed? Select Yes to proceed with this file, \
1323 No to choose a different file, or Cancel to stop replaying this script."
1324 );
1325 let buttons = ["&Yes", "&No", "&Cancel"].map(str::to_owned);
1326 loop {
1327 self.flush_console(Newline::Input);
1328 let answer = match self.text_dialog(&question, &buttons, true) {
1331 Ok(answer) => answer,
1332 Err(_) => {
1333 self.io.prompt_shown = false;
1334 3
1335 }
1336 };
1337 match answer {
1338 1 => break,
1339 2 => {
1340 let (asked, chosen) = match self.ask_file(prompt, dialog, kind, true) {
1341 Ok(found) => found,
1342 Err(_) => {
1343 self.io.prompt_shown = false;
1344 (FAILURE, String::new())
1345 }
1346 };
1347 if asked == CANCEL {
1348 continue;
1349 }
1350 if asked == FAILURE {
1351 self.io.scripts.pop();
1352 }
1353 result = asked;
1354 name = chosen;
1355 break;
1356 }
1357 3 => {
1358 self.io.scripts.pop();
1359 result = CANCEL;
1360 break;
1361 }
1362 _ => break,
1365 }
1366 }
1367 }
1368 } else {
1369 (result, name) = self.ask_file(prompt, dialog, kind, false)?;
1370 from_ui = true;
1371 }
1372 let list = self.event_list(result, if result == SUCCESS { 4 } else { 1 });
1373 if result == SUCCESS {
1374 let file_name = self.new_file_name(&name);
1375 if from_ui {
1376 self.set_file_name_from_ui(file_name, dialog as u8);
1377 }
1378 self.set_list_item(list, 1, Value::Obj(file_name));
1379 self.log_event(b"file", Some(name.as_bytes()));
1380 } else {
1381 self.log_event(b"file", None);
1382 }
1383 Ok(list)
1384 }
1385
1386 fn can_create(&mut self, name: &str) -> bool {
1388 if self.host.write_file(name, b"").is_ok() {
1389 let _ = self.host.delete_file(name);
1390 true
1391 } else {
1392 false
1393 }
1394 }
1395
1396 fn ask_file(
1401 &mut self,
1402 prompt: &str,
1403 dialog: i32,
1404 kind: FileKind,
1405 bypass_script: bool,
1406 ) -> VmResult<(i32, String)> {
1407 let which = if dialog == 2 {
1408 FileDialog::Save
1409 } else {
1410 FileDialog::Open
1411 };
1412 match self.host.choose_file(prompt, which, kind) {
1413 Some(FileChoice::Chosen(name)) => return Ok((0, name)),
1414 Some(FileChoice::Cancelled) => return Ok((2, String::new())),
1415 Some(FileChoice::Pending) => return Err(self.suspend()),
1419 None => {}
1420 }
1421 if !self.io.prompt_shown {
1422 self.print(prompt.as_bytes());
1423 self.print(b" >");
1424 self.io.prompt_shown = true;
1425 }
1426 let line = self.read_line(bypass_script)?;
1427 self.io.prompt_shown = false;
1428 Ok(match line {
1429 None => (1, String::new()),
1430 Some(line) if line.is_empty() => (2, String::new()),
1431 Some(line) => (0, String::from_utf8_lossy(&line).into_owned()),
1432 })
1433 }
1434
1435 fn timeout_arg(&mut self, argc: u32) -> VmResult<Option<i32>> {
1438 if argc == 0 || self.arg(0) == Value::Nil {
1439 Ok(None)
1440 } else {
1441 self.cast_to_int(self.arg(0)).map(Some)
1442 }
1443 }
1444
1445 fn log_console_arg(&self, value: Value) -> VmResult<usize> {
1447 let handle = self.int_arg(value)?;
1448 usize::try_from(handle)
1449 .ok()
1450 .and_then(|handle| handle.checked_sub(1))
1451 .filter(|&slot| matches!(self.io.log_consoles.get(slot), Some(Some(_))))
1452 .ok_or_else(|| VmError::new(code::BAD_VAL_BIF))
1453 }
1454
1455 fn dialog_buttons(&mut self, value: Value) -> VmResult<Vec<String>> {
1458 if let Value::Int(set) = value {
1459 let labels: &[&str] = match set {
1460 1 => &["&OK"],
1461 2 => &["&OK", "&Cancel"],
1462 3 => &["&Yes", "&No"],
1463 4 => &["&Yes", "&No", "&Cancel"],
1464 _ => &[],
1465 };
1466 return Ok(labels.iter().map(|label| (*label).to_owned()).collect());
1467 }
1468 let Some(len) = self.list_like_len(value)? else {
1469 return Err(VmError::new(code::BAD_TYPE_BIF));
1470 };
1471 let mut labels = Vec::new();
1472 for index in 1..=len.min(10) {
1473 let item = self.list_like_get(value, index)?;
1474 if let Some(text) = self.as_str(item) {
1475 labels.push(String::from_utf8_lossy(&text).into_owned());
1476 } else if let Value::Int(standard) = item {
1477 let label = match standard {
1478 1 => "&OK",
1479 2 => "&Cancel",
1480 3 => "&Yes",
1481 4 => "&No",
1482 _ => continue,
1483 };
1484 labels.push(label.to_owned());
1485 }
1486 }
1487 Ok(labels)
1488 }
1489}
1490
1491fn rich_system_info(which: i32, display: &hexicon_host::rich::RichDisplay) -> i32 {
1494 let yes = |b: bool| i32::from(b);
1495 match which {
1496 4 | 19 => 1,
1498 5 | 6 | 25 | 26 => yes(display.pictures),
1500 7 | 10 | 15 | 18 | 27 => yes(display.sounds),
1503 11 => yes(display.pictures && display.show_pictures),
1505 12 => yes(display.sounds && display.play_sounds),
1506 13 => yes(display.sounds && display.play_music),
1507 14 => yes(display.links),
1508 31 => 1,
1510 32 => 4,
1511 34 => 3,
1513 _ => 0,
1516 }
1517}