Skip to main content

badterm_core/
ansi.rs

1//! ANSI-BBS / ANSI X3.64 terminal emulation.
2//!
3//! [`Terminal`] consumes the byte stream from the remote system, drives a
4//! [`Screen`], and collects any replies (cursor position reports, etc.) that
5//! must be sent back.
6
7use serde::{Deserialize, Serialize};
8
9use crate::cp437;
10use crate::music::{self, Tone};
11use crate::palette::{ANSI_TO_VGA, rgb};
12use crate::screen::{Cell, Color, DEFAULT_BG, DEFAULT_FG, Look, Screen, flags};
13
14/// How incoming bytes are interpreted: the character set, and the
15/// emulations that go with it.
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(rename_all = "lowercase")]
18pub enum Encoding {
19    #[default]
20    Cp437,
21    Utf8,
22    /// Commodore 64 (see [`crate::petscii`]).
23    Petscii,
24    /// Atari 8-bit (see [`crate::atascii`]).
25    Atascii,
26    /// CP437 with AVT/0+ codes as well as ANSI (see [`crate::avatar`]).
27    Avatar,
28    /// CP437 ANSI with RIPscrip graphics (see [`crate::rip`]).
29    Rip,
30    /// Prestel viewdata (see [`crate::viewdata`]).
31    Viewdata,
32    /// Atari ST: VT-52 with IGS graphics (see [`crate::igs`]).
33    Igs,
34    /// Amiga: ANSI with SkyPix graphics (see [`crate::skypix`]).
35    Skypix,
36}
37
38impl Encoding {
39    pub const ALL: [Encoding; 9] = [
40        Encoding::Cp437,
41        Encoding::Utf8,
42        Encoding::Petscii,
43        Encoding::Atascii,
44        Encoding::Viewdata,
45        Encoding::Igs,
46        Encoding::Skypix,
47        Encoding::Avatar,
48        Encoding::Rip,
49    ];
50
51    pub fn name(self) -> &'static str {
52        match self {
53            Encoding::Cp437 => "CP437",
54            Encoding::Utf8 => "UTF-8",
55            Encoding::Petscii => "PETSCII",
56            Encoding::Atascii => "ATASCII",
57            Encoding::Avatar => "Avatar",
58            Encoding::Rip => "RIPscrip",
59            Encoding::Viewdata => "Viewdata",
60            Encoding::Igs => "IGS",
61            Encoding::Skypix => "SkyPix",
62        }
63    }
64
65    /// A C64 or Atari system, with its own screen size and font.
66    pub fn is_retro(self) -> bool {
67        matches!(self, Encoding::Petscii | Encoding::Atascii)
68    }
69
70    /// The screen such a system has, if it has its own.
71    pub fn screen_size(self) -> Option<(usize, usize)> {
72        match self {
73            Encoding::Petscii => Some((crate::petscii::COLS, crate::petscii::ROWS)),
74            Encoding::Atascii => Some((crate::atascii::COLS, crate::atascii::ROWS)),
75            Encoding::Rip => Some((crate::rip::COLS, crate::rip::ROWS)),
76            Encoding::Viewdata => Some((crate::viewdata::COLS, crate::viewdata::ROWS)),
77            Encoding::Igs => Some((crate::igs::COLS, crate::igs::ROWS)),
78            Encoding::Skypix => Some((crate::skypix::COLS, crate::skypix::ROWS)),
79            _ => None,
80        }
81    }
82
83    /// Typed or pasted text as the remote expects it. A CR (Enter) becomes
84    /// the system's own end of line.
85    pub fn encode_text(self, text: &str) -> Vec<u8> {
86        match self {
87            Encoding::Cp437 | Encoding::Avatar | Encoding::Rip | Encoding::Igs => cp437::encode(text),
88            // The Amiga's character set is ISO-8859-1.
89            Encoding::Skypix => text.chars().map(|c| if (c as u32) < 256 { c as u8 } else { b'?' }).collect(),
90            Encoding::Utf8 => text.as_bytes().to_vec(),
91            Encoding::Petscii => text
92                .chars()
93                .filter_map(|c| if c == '\r' { Some(0x0D) } else { crate::petscii::encode_char(c) })
94                .collect(),
95            Encoding::Atascii => text
96                .chars()
97                .filter_map(|c| if c == '\r' { Some(0x9B) } else { crate::atascii::encode_char(c) })
98                .collect(),
99            Encoding::Viewdata => text.chars().filter_map(crate::viewdata::encode_char).collect(),
100        }
101    }
102}
103
104const MAX_PARAMS: usize = 32;
105const MAX_STRING: usize = 4096;
106/// The Device Attributes reply: "CTerm" and the revision whose sequences
107/// BadTerm follows (1.332: the blob, flip and zoom graphics commands).
108pub const CTERM_DA: &[u8] = b"\x1b[=67;84;101;114;109;1;332c";
109/// CTerm's built-in fonts are 0-42; loaded ones would start here.
110const FIRST_LOADABLE_FONT: u32 = 43;
111/// A DCS string (a sixel picture) can be large; longer ones are cut off.
112const MAX_DCS: usize = 32 << 20;
113
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115enum State {
116    Ground,
117    Escape,
118    /// ESC followed by an intermediate byte, e.g. `ESC ( B`; waiting for the final byte.
119    EscIntermediate,
120    Csi,
121    /// OSC: collected for the window title.
122    Osc,
123    /// DCS: collected (sixel graphics).
124    Dcs,
125    /// APC: collected (SyncTERM's commands).
126    Apc,
127    /// SOS, PM: ignored until ST.
128    IgnoreString,
129    /// Saw ESC inside a string; `\` terminates it.
130    StringEsc,
131    /// An ANSI music string, up to Ctrl-N.
132    Music,
133}
134
135/// Things the front end may want to react to.
136#[derive(Clone, Debug, PartialEq)]
137pub enum TermEvent {
138    Bell,
139    Title(String),
140    /// ANSI music to play.
141    Music(Vec<Tone>),
142    /// Sound from SyncTERM's audio commands.
143    Audio(crate::audio::AudioOp),
144}
145
146pub struct Terminal {
147    pub screen: Screen,
148    pub encoding: Encoding,
149    /// Treat `ESC [ M` with no parameter as the start of ANSI music, as
150    /// many BBS doors expect, instead of "delete one line". `ESC [ N` and
151    /// `ESC [ |` always start music.
152    pub music_on_csi_m: bool,
153    /// `CSI ? 80 h` (DECSDM): sixel pictures go at the top left of the
154    /// screen and don't scroll it.
155    pub sixel_display_mode: bool,
156    state: State,
157    /// The kind of string being read: OSC, DCS or another.
158    string_kind: State,
159    dcs: Vec<u8>,
160    /// SyncTERM's file cache, pictures and pixel buffers.
161    pub syncterm: crate::syncterm::SyncTerm,
162    private: u8,
163    intermediate: u8,
164    params: Vec<u32>,
165    param_present: bool,
166    osc: Vec<u8>,
167    utf8_buf: [u8; 4],
168    utf8_len: usize,
169    utf8_need: usize,
170    replies: Vec<u8>,
171    events: Vec<TermEvent>,
172    petscii: crate::petscii::Petscii,
173    atascii: crate::atascii::Atascii,
174    avatar: crate::avatar::Avatar,
175    viewdata: crate::viewdata::Viewdata,
176    /// The RIPscrip canvas, when the encoding is RIP.
177    rip: Option<Box<crate::rip::Rip>>,
178    /// The Atari ST screen, when the encoding is IGS.
179    igs: Option<Box<crate::igs::Igs>>,
180    /// The Amiga screen, when the encoding is SkyPix.
181    skypix: Option<Box<crate::skypix::Skypix>>,
182    /// Nothing has been printed on this line yet (where a RIP line can
183    /// start).
184    line_start: bool,
185    /// Bytes not read yet because the BBS asked to wait for a sound
186    /// (`A;Wait`), until then.
187    held: Vec<u8>,
188}
189
190impl Terminal {
191    pub fn new(cols: usize, rows: usize, scrollback: usize) -> Self {
192        Terminal {
193            screen: Screen::new(cols, rows, scrollback),
194            encoding: Encoding::Cp437,
195            music_on_csi_m: false,
196            sixel_display_mode: false,
197            state: State::Ground,
198            string_kind: State::IgnoreString,
199            dcs: Vec::new(),
200            syncterm: Default::default(),
201            private: 0,
202            intermediate: 0,
203            params: Vec::with_capacity(MAX_PARAMS),
204            param_present: false,
205            osc: Vec::new(),
206            utf8_buf: [0; 4],
207            utf8_len: 0,
208            utf8_need: 0,
209            replies: Vec::new(),
210            events: Vec::new(),
211            petscii: Default::default(),
212            atascii: Default::default(),
213            avatar: Default::default(),
214            viewdata: Default::default(),
215            rip: None,
216            igs: None,
217            skypix: None,
218            line_start: true,
219            held: Vec::new(),
220        }
221    }
222
223    /// Set up the screen for the encoding: a C64 or Atari system gets that
224    /// machine's colors and font.
225    pub fn start_emulation(&mut self) {
226        match self.encoding {
227            Encoding::Petscii => self.petscii.start(&mut self.screen),
228            Encoding::Atascii => self.atascii.start(&mut self.screen),
229            Encoding::Rip => self.rip = Some(Box::default()),
230            Encoding::Viewdata => self.viewdata.start(&mut self.screen),
231            Encoding::Igs => self.igs = Some(Box::default()),
232            Encoding::Skypix => self.skypix = Some(Box::default()),
233            _ => {}
234        }
235    }
236
237    /// The RIPscrip canvas, for a RIP system.
238    pub fn rip(&self) -> Option<&crate::rip::Rip> {
239        self.rip.as_deref()
240    }
241
242    pub fn rip_mut(&mut self) -> Option<&mut crate::rip::Rip> {
243        self.rip.as_deref_mut()
244    }
245
246    /// The Atari ST screen, for an IGS system.
247    pub fn igs(&self) -> Option<&crate::igs::Igs> {
248        self.igs.as_deref()
249    }
250
251    pub fn igs_mut(&mut self) -> Option<&mut crate::igs::Igs> {
252        self.igs.as_deref_mut()
253    }
254
255    /// The Amiga screen, for a SkyPix system.
256    pub fn skypix(&self) -> Option<&crate::skypix::Skypix> {
257        self.skypix.as_deref()
258    }
259
260    /// After SkyPix has drawn: its replies, bells and cursor.
261    fn skypix_done(&mut self) {
262        let Some(sky) = self.skypix.as_deref_mut() else { return };
263        self.replies.append(&mut sky.replies);
264        for _ in 0..std::mem::take(&mut sky.bells) {
265            self.events.push(TermEvent::Bell);
266        }
267        let (x, y) = sky.cursor();
268        self.screen.move_to(x, y);
269        self.screen.cursor_visible = sky.cursor_on;
270    }
271
272    /// After IGS has drawn: its replies, bells and cursor.
273    fn igs_done(&mut self) {
274        let Some(igs) = self.igs.as_deref_mut() else { return };
275        self.replies.append(&mut igs.replies);
276        for _ in 0..std::mem::take(&mut igs.bells) {
277            self.events.push(TermEvent::Bell);
278        }
279        let (x, y) = igs.cursor();
280        self.screen.move_to(x, y);
281        self.screen.cursor_visible = igs.cursor_on;
282    }
283
284    /// Bytes the terminal wants sent to the remote (e.g. CPR replies).
285    pub fn take_replies(&mut self) -> Vec<u8> {
286        std::mem::take(&mut self.replies)
287    }
288
289    pub fn take_events(&mut self) -> Vec<TermEvent> {
290        std::mem::take(&mut self.events)
291    }
292
293    pub fn feed(&mut self, data: &[u8]) {
294        match self.encoding {
295            Encoding::Petscii => {
296                for &b in data {
297                    self.petscii.byte(&mut self.screen, b, &mut self.events);
298                }
299            }
300            Encoding::Atascii => {
301                for &b in data {
302                    self.atascii.byte(&mut self.screen, b, &mut self.events);
303                }
304            }
305            Encoding::Viewdata => self.viewdata.feed(&mut self.screen, data, &mut self.events),
306            Encoding::Igs => {
307                if let Some(igs) = self.igs.as_deref_mut() {
308                    igs.feed(data);
309                }
310                self.igs_done();
311            }
312            Encoding::Skypix => {
313                if let Some(sky) = self.skypix.as_deref_mut() {
314                    sky.feed(data);
315                }
316                self.skypix_done();
317            }
318            _ => {
319                if self.syncterm.hold.is_some() {
320                    self.held.extend_from_slice(data);
321                    return;
322                }
323                for (i, &b) in data.iter().enumerate() {
324                    self.byte(b);
325                    if self.syncterm.hold.is_some() {
326                        self.held.extend_from_slice(&data[i + 1..]);
327                        break;
328                    }
329                }
330            }
331        }
332    }
333
334    /// Time passing: sound reports the BBS asked for, and reading again
335    /// after a wait for a sound.
336    pub fn poll(&mut self, now: std::time::Instant) {
337        self.syncterm.audio.poll(now, &mut self.replies);
338        if let Some(igs) = self.igs.as_deref_mut().filter(|g| g.hold.is_some()) {
339            igs.poll(now);
340            self.igs_done();
341        }
342        if let Some(sky) = self.skypix.as_deref_mut().filter(|s| s.hold.is_some()) {
343            sky.poll(now);
344            self.skypix_done();
345        }
346        if self.syncterm.hold.is_some_and(|t| now >= t) {
347            self.syncterm.hold = None;
348            let held = std::mem::take(&mut self.held);
349            self.feed(&held);
350        }
351    }
352
353    /// When [`Terminal::poll`] has something to do.
354    pub fn next_poll(&self) -> Option<std::time::Instant> {
355        let igs = self.igs.as_ref().and_then(|g| g.hold);
356        let sky = self.skypix.as_ref().and_then(|s| s.hold);
357        [self.syncterm.hold, self.syncterm.audio.next_due(), igs, sky].into_iter().flatten().min()
358    }
359
360    fn byte(&mut self, b: u8) {
361        if self.state == State::Ground {
362            let taken = match self.encoding {
363                Encoding::Avatar => self.avatar_byte(b),
364                Encoding::Rip => self.rip_byte(b),
365                _ => false,
366            };
367            if taken {
368                return;
369            }
370        }
371        // CAN and SUB abort any sequence in progress (ECMA-48).
372        if self.state != State::Ground && (b == 0x18 || b == 0x1A) {
373            self.state = State::Ground;
374            return;
375        }
376        match self.state {
377            State::Ground => self.ground(b),
378            State::Escape => self.escape(b),
379            State::EscIntermediate => self.state = State::Ground,
380            State::Csi => self.csi(b),
381            State::Osc | State::IgnoreString => match b {
382                0x07 if self.state == State::Osc => self.finish_string(),
383                0x1B => self.state = State::StringEsc,
384                _ if self.state == State::Osc && self.osc.len() < MAX_STRING => self.osc.push(b),
385                _ => {}
386            },
387            State::Dcs | State::Apc => match b {
388                0x1B => self.state = State::StringEsc,
389                _ if self.dcs.len() < MAX_DCS => self.dcs.push(b),
390                _ => {}
391            },
392            State::Music => match b {
393                0x0E => {
394                    self.state = State::Ground;
395                    let tones = music::parse(&self.osc);
396                    if !tones.is_empty() {
397                        let ms: u64 = tones.iter().map(|t| t.ms as u64).sum();
398                        self.syncterm.audio.music(std::time::Duration::from_millis(ms));
399                        self.events.push(TermEvent::Music(tones));
400                    }
401                }
402                _ if self.osc.len() < MAX_STRING => self.osc.push(b),
403                // Too long to be music: give up on it.
404                _ => self.state = State::Ground,
405            },
406            State::StringEsc => {
407                if b == b'\\' {
408                    self.finish_string();
409                } else {
410                    // Not ST: abandon the string and treat this as a new escape.
411                    self.state = State::Escape;
412                    self.escape(b);
413                }
414            }
415        }
416    }
417
418    /// AVATAR codes, in the text stream (see [`crate::avatar`]).
419    fn avatar_byte(&mut self, b: u8) -> bool {
420        use crate::avatar::Outcome;
421        match self.avatar.byte(&mut self.screen, b) {
422            Outcome::Pass => false,
423            Outcome::Done => true,
424            Outcome::Show(bytes) => {
425                for b in bytes {
426                    self.byte(b);
427                }
428                true
429            }
430        }
431    }
432
433    /// RIP lines, which start a line with `!|` (see [`crate::rip`]).
434    fn rip_byte(&mut self, b: u8) -> bool {
435        use crate::rip::Feed;
436        let Some(rip) = self.rip.as_mut() else { return false };
437        match rip.byte(&mut self.screen, b, self.line_start) {
438            Feed::Pass => false,
439            Feed::Done => true,
440            Feed::Text(bytes) => {
441                self.line_start = false;
442                for b in bytes {
443                    self.byte(b);
444                }
445                true
446            }
447        }
448    }
449
450    fn ground(&mut self, b: u8) {
451        if self.encoding == Encoding::Utf8 && self.utf8_need > 0 {
452            if b & 0xC0 == 0x80 {
453                self.utf8_buf[self.utf8_len] = b;
454                self.utf8_len += 1;
455                if self.utf8_len == self.utf8_need {
456                    let ch = std::str::from_utf8(&self.utf8_buf[..self.utf8_len]).ok().and_then(|s| s.chars().next());
457                    self.utf8_need = 0;
458                    self.screen.put(ch.and_then(cp437::from_unicode).unwrap_or(b'?'));
459                }
460                return;
461            }
462            // Truncated sequence: show a replacement and handle this byte normally.
463            self.utf8_need = 0;
464            self.screen.put(b'?');
465        }
466        match b {
467            0x00 | 0x7F => {}
468            0x07 => self.events.push(TermEvent::Bell),
469            0x08 => self.screen.backspace(),
470            0x09 => self.screen.tab(),
471            0x0A => {
472                self.screen.line_feed();
473                self.line_start = true;
474            }
475            0x0C => self.screen.erase_display(2),
476            0x0D => {
477                self.screen.carriage_return();
478                self.line_start = true;
479            }
480            0x1B => self.state = State::Escape,
481            _ => match self.encoding {
482                // Like ANSI.SYS, every other byte is a glyph, including the
483                // "graphic" control characters (☺, ♥, ►, ...).
484                Encoding::Cp437
485                | Encoding::Petscii
486                | Encoding::Atascii
487                | Encoding::Avatar
488                | Encoding::Rip
489                | Encoding::Viewdata
490                | Encoding::Igs
491                | Encoding::Skypix => {
492                    if self.avatar.insert {
493                        self.screen.insert_chars(1);
494                    }
495                    self.line_start = false;
496                    self.screen.put(b)
497                }
498                Encoding::Utf8 => match b {
499                    0x01..=0x1F => {}
500                    0x20..=0x7E => self.screen.put(b),
501                    0xC2..=0xDF => self.utf8_start(b, 2),
502                    0xE0..=0xEF => self.utf8_start(b, 3),
503                    0xF0..=0xF4 => self.utf8_start(b, 4),
504                    _ => self.screen.put(b'?'),
505                },
506            },
507        }
508    }
509
510    fn utf8_start(&mut self, b: u8, need: usize) {
511        self.utf8_buf[0] = b;
512        self.utf8_len = 1;
513        self.utf8_need = need;
514    }
515
516    fn escape(&mut self, b: u8) {
517        self.state = State::Ground;
518        match b {
519            b'[' => {
520                self.state = State::Csi;
521                self.private = 0;
522                self.intermediate = 0;
523                self.params.clear();
524                self.param_present = false;
525            }
526            b']' => {
527                self.state = State::Osc;
528                self.string_kind = State::Osc;
529                self.osc.clear();
530            }
531            b'P' => {
532                self.state = State::Dcs;
533                self.string_kind = State::Dcs;
534                self.dcs.clear();
535            }
536            b'_' => {
537                self.state = State::Apc;
538                self.string_kind = State::Apc;
539                self.dcs.clear();
540            }
541            b'X' | b'^' => {
542                self.state = State::IgnoreString;
543                self.string_kind = State::IgnoreString;
544            }
545            0x20..=0x2F => self.state = State::EscIntermediate,
546            b'7' => self.screen.save_cursor(),
547            b'8' => self.screen.restore_cursor(),
548            b'c' => self.screen.reset(),
549            b'D' => self.screen.line_feed(),
550            b'E' => {
551                self.screen.carriage_return();
552                self.screen.line_feed();
553            }
554            b'M' => self.screen.reverse_index(),
555            0x1B => self.state = State::Escape,
556            _ => log::debug!("unhandled ESC {:?}", b as char),
557        }
558    }
559
560    fn finish_string(&mut self) {
561        self.state = State::Ground;
562        match self.string_kind {
563            State::Osc => {}
564            State::Dcs => return self.finish_dcs(),
565            State::Apc => {
566                let apc = std::mem::take(&mut self.dcs);
567                if !self.syncterm.apc(&apc, &mut self.screen, &mut self.replies) {
568                    log::debug!("unhandled APC {:?}", String::from_utf8_lossy(&apc[..apc.len().min(32)]));
569                }
570                self.events.extend(self.syncterm.audio_ops.drain(..).map(TermEvent::Audio));
571                if apc.capacity() <= 1 << 20 {
572                    self.dcs = apc;
573                    self.dcs.clear();
574                }
575                return;
576            }
577            _ => return,
578        }
579        let s = String::from_utf8_lossy(&self.osc).into_owned();
580        let (code, rest) = s.split_once(';').unwrap_or((s.as_str(), ""));
581        match code {
582            // Set the window title.
583            "0" | "2" => self.events.push(TermEvent::Title(rest.to_string())),
584            "4" => self.set_palette(rest),
585            "104" => self.reset_palette(rest),
586            _ => log::debug!("unhandled OSC {code}"),
587        }
588    }
589
590    /// A DCS string: `p1 ; p2 q ...` is a sixel picture.
591    fn finish_dcs(&mut self) {
592        let dcs = std::mem::take(&mut self.dcs);
593        let start = dcs.iter().position(|b| !matches!(b, b'0'..=b'9' | b';')).unwrap_or(dcs.len());
594        if dcs.get(start) == Some(&b'q') {
595            let params: Vec<u32> =
596                String::from_utf8_lossy(&dcs[..start]).split(';').map(|p| p.parse().unwrap_or(0)).collect();
597            let background = self.screen.look.rgb(self.screen.pen.bg);
598            let img = crate::sixel::decode(&params, &dcs[start + 1..], background);
599            self.screen.place_image(&img, !self.sixel_display_mode);
600        } else {
601            log::debug!("unhandled DCS {:?}", String::from_utf8_lossy(&dcs[..dcs.len().min(32)]));
602        }
603        // Keep the buffer for the next one unless it was a big picture.
604        if dcs.capacity() <= 1 << 20 {
605            self.dcs = dcs;
606            self.dcs.clear();
607        }
608    }
609
610    /// `OSC 4 ; index ; color [; index ; color ...]`, where a color is
611    /// `rgb:R/G/B` (1-4 hex digits each), `#RRGGBB`, or `?` to ask for it.
612    fn set_palette(&mut self, args: &str) {
613        let mut parts = args.split(';');
614        while let (Some(i), Some(spec)) = (parts.next(), parts.next()) {
615            let Ok(i) = i.trim().parse::<u8>() else { continue };
616            if spec == "?" {
617                let c = self.screen.look.palette[i as usize];
618                let reply = format!("\x1b]4;{i};rgb:{:02x}/{:02x}/{:02x}\x1b\\", c >> 16, (c >> 8) & 0xFF, c & 0xFF);
619                self.replies.extend_from_slice(reply.as_bytes());
620            } else if let Some(c) = parse_color(spec) {
621                self.screen.look.palette[i as usize] = c;
622            }
623        }
624    }
625
626    /// `OSC 104` resets the whole palette; `OSC 104 ; index ...` just those.
627    fn reset_palette(&mut self, args: &str) {
628        let standard = &Look::standard().palette;
629        if args.trim().is_empty() {
630            self.screen.look.palette = *standard;
631            return;
632        }
633        for i in args.split(';').filter_map(|i| i.trim().parse::<u8>().ok()) {
634            self.screen.look.palette[i as usize] = standard[i as usize];
635        }
636    }
637
638    fn csi(&mut self, b: u8) {
639        match b {
640            b'0'..=b'9' => {
641                if self.params.is_empty() {
642                    self.params.push(0);
643                }
644                let p = self.params.last_mut().unwrap();
645                *p = p.saturating_mul(10).saturating_add((b - b'0') as u32);
646                self.param_present = true;
647            }
648            b';' | b':' => {
649                if self.params.is_empty() {
650                    self.params.push(0);
651                }
652                if self.params.len() < MAX_PARAMS {
653                    self.params.push(0);
654                }
655                self.param_present = true;
656            }
657            0x3C..=0x3F => {
658                if !self.param_present && self.private == 0 {
659                    self.private = b;
660                }
661            }
662            // `ESC [ !` asks whether this is a RIPscrip terminal.
663            b'!' if self.encoding == Encoding::Rip && self.params.is_empty() && self.private == 0 => {
664                self.state = State::Ground;
665                self.replies.extend_from_slice(crate::rip::VERSION_REPLY);
666            }
667            0x20..=0x2F => self.intermediate = b,
668            0x40..=0x7E => {
669                self.state = State::Ground;
670                self.dispatch_csi(b);
671            }
672            // C0 controls are executed even in the middle of a sequence.
673            0x00..=0x1F => {
674                if b == 0x1B {
675                    self.state = State::Escape;
676                } else {
677                    self.ground(b);
678                }
679            }
680            _ => self.state = State::Ground,
681        }
682    }
683
684    /// Parameter `i`, with 0 or missing replaced by `default`.
685    fn p(&self, i: usize, default: u32) -> u32 {
686        match self.params.get(i) {
687            Some(&v) if v != 0 => v,
688            _ => default,
689        }
690    }
691
692    fn dispatch_csi(&mut self, b: u8) {
693        if self.intermediate != 0 {
694            // CTerm font selection: `CSI slot ; font SP D`.
695            if self.intermediate == b' ' && b == b'D' && self.private == 0 {
696                let slot = self.params.first().copied().unwrap_or(0) as usize;
697                let font = self.params.get(1).copied().unwrap_or(0);
698                if slot < 4 && font <= 255 {
699                    self.screen.look.fonts[slot] = font as u8;
700                }
701                return;
702            }
703            log::debug!("unhandled CSI with intermediate {:?} {:?}", self.intermediate as char, b as char);
704            return;
705        }
706        match self.private {
707            0 => {}
708            b'?' if b == b'S' => return self.graphics_attributes(),
709            b'?' => return self.dec_mode(b),
710            b'=' if b == b'n' => return self.cterm_report(),
711            // CTerm Device Attributes: what this CTerm-like terminal can do.
712            b'<' if b == b'c' && self.params.first().is_none_or(|&v| v == 0) => {
713                return self.replies.extend_from_slice(b"\x1b[<0;2;3;4;5;6c");
714            }
715            _ => {
716                log::debug!("unhandled private CSI {:?}{:?} {:?}", self.private as char, b as char, self.params);
717                return;
718            }
719        }
720        let no_params = self.params.is_empty();
721        if b == b'|' || no_params && (b == b'N' || b == b'M' && self.music_on_csi_m) {
722            self.state = State::Music;
723            self.osc.clear();
724            return;
725        }
726        let n = self.p(0, 1) as usize;
727        let s = &mut self.screen;
728        match b {
729            b'@' => s.insert_chars(n),
730            b'A' => s.move_by(0, -(n as isize)),
731            b'B' | b'e' => s.move_by(0, n as isize),
732            b'C' | b'a' => s.move_by(n as isize, 0),
733            b'D' => s.move_by(-(n as isize), 0),
734            b'E' => {
735                s.move_by(0, n as isize);
736                s.carriage_return();
737            }
738            b'F' => {
739                s.move_by(0, -(n as isize));
740                s.carriage_return();
741            }
742            b'G' | b'`' => {
743                let y = s.cursor().1;
744                s.move_to(n - 1, y);
745            }
746            b'd' => {
747                let x = s.cursor().0;
748                s.move_to(x, n - 1);
749            }
750            b'H' | b'f' => {
751                let (row, col) = (self.p(0, 1) as usize, self.p(1, 1) as usize);
752                self.screen.move_to(col - 1, row - 1);
753            }
754            b'J' => s.erase_display(self.params.first().copied().unwrap_or(0)),
755            b'K' => s.erase_line(self.params.first().copied().unwrap_or(0)),
756            b'L' => s.insert_lines(n),
757            b'M' => s.delete_lines(n),
758            b'P' => s.delete_chars(n),
759            b'S' => s.scroll_up(n),
760            b'T' => s.scroll_down(n),
761            b'X' => s.erase_chars(n),
762            b'Z' => s.back_tab(n),
763            // Device Attributes: CTerm, SyncTERM's emulation, which BBSes
764            // look for before sending its pictures and sounds; what it can
765            // do is asked next (`CSI < c`), and answered truthfully.
766            b'c' if self.params.first().is_none_or(|&v| v == 0) => self.replies.extend_from_slice(CTERM_DA),
767            b'm' => self.sgr(),
768            b'n' => match self.params.first().copied().unwrap_or(0) {
769                5 => self.replies.extend_from_slice(b"\x1b[0n"),
770                6 => {
771                    let (x, y) = self.screen.cursor();
772                    self.replies.extend_from_slice(format!("\x1b[{};{}R", y + 1, x + 1).as_bytes());
773                }
774                _ => {}
775            },
776            b'r' => {
777                let rows = self.screen.rows() as u32;
778                let (top, bottom) = (self.p(0, 1), self.p(1, rows));
779                self.screen.set_scroll_region(top as usize - 1, bottom as usize - 1);
780            }
781            b's' => s.save_cursor(),
782            b'u' => s.restore_cursor(),
783            // CTerm/PabloDraw 24-bit color: CSI 0;r;g;b t (bg) / CSI 1;r;g;b t (fg).
784            b't' if self.params.len() == 4 => {
785                let c = Color::Rgb(rgb(self.params[1] as u8, self.params[2] as u8, self.params[3] as u8));
786                match self.params[0] {
787                    0 => self.screen.pen.bg = c,
788                    1 => self.screen.pen.fg = c,
789                    _ => {}
790                }
791            }
792            b'h' | b'l' => {}
793            _ => log::debug!("unhandled CSI {:?} {:?}", b as char, self.params),
794        }
795    }
796
797    /// CTerm's state reports (`CSI = Ps n`).
798    fn cterm_report(&mut self) {
799        let reply = match self.params.first().copied().unwrap_or(1) {
800            // Fonts: the first loadable slot, the last selection's result
801            // (none yet), and the four slots' fonts.
802            1 => {
803                let f = self.screen.look.fonts;
804                format!("\x1b[=1;{FIRST_LOADABLE_FONT};99;{};{};{};{}n", f[0], f[1], f[2], f[3])
805            }
806            // The DEC modes that are set.
807            2 => {
808                let s = &self.screen;
809                let l = &s.look;
810                let set = [
811                    (7, s.autowrap),
812                    (25, s.cursor_visible),
813                    (31, l.bright_font),
814                    (32, l.bright_plain),
815                    (33, s.ice_colors),
816                    (34, l.blink_font),
817                    (35, l.blink_steady),
818                    (80, self.sixel_display_mode),
819                ];
820                let modes: Vec<String> = set.iter().filter(|m| m.1).map(|m| m.0.to_string()).collect();
821                format!("\x1b[=2;{}n", modes.join(";"))
822            }
823            // A cell's height and width in pixels.
824            3 => {
825                let (w, h) = self.screen.cell_px();
826                format!("\x1b[=3;{h};{w}n")
827            }
828            // No last column flag, no OSC 8 links.
829            4 => "\x1b[=4;0n".to_string(),
830            5 => "\x1b[=5;0n".to_string(),
831            6 => "\x1b[=6;0n".to_string(),
832            // Audio: the channels playing.
833            7 => self.syncterm.audio.report(self.params.get(1).map(|&c| c as usize)),
834            _ => return,
835        };
836        self.replies.extend_from_slice(reply.as_bytes());
837    }
838
839    /// XTSMGRAPHICS (`CSI ? Pi ; Pa S`): the number of sixel color
840    /// registers (1) and the graphics size (2), read only.
841    fn graphics_attributes(&mut self) {
842        let reply = match (self.params.first().copied(), self.params.get(1).copied()) {
843            (Some(1), Some(1 | 4)) => "\x1b[?1;0;256S".to_string(),
844            (Some(2), Some(1 | 4)) => {
845                let (w, h) = self.screen.size_px();
846                format!("\x1b[?2;0;{w};{h}S")
847            }
848            (Some(i @ 1..=3), _) => format!("\x1b[?{i};3;0S"),
849            (Some(i), _) => format!("\x1b[?{i};1;0S"),
850            (None, _) => return,
851        };
852        self.replies.extend_from_slice(reply.as_bytes());
853    }
854
855    fn dec_mode(&mut self, b: u8) {
856        let on = match b {
857            b'h' => true,
858            b'l' => false,
859            _ => return,
860        };
861        for &mode in &self.params {
862            match mode {
863                7 => self.screen.autowrap = on,
864                80 => self.sixel_display_mode = on,
865                25 => self.screen.cursor_visible = on,
866                // CTerm: blink attribute selects bright background (iCE colors).
867                // CTerm: bright and blink select fonts, and need not
868                // brighten or blink.
869                31 => self.screen.look.bright_font = on,
870                32 => self.screen.look.bright_plain = on,
871                33 => self.screen.ice_colors = on,
872                34 => self.screen.look.blink_font = on,
873                35 => self.screen.look.blink_steady = on,
874                _ => log::debug!("unhandled DEC mode {mode} {on}"),
875            }
876        }
877    }
878
879    fn sgr(&mut self) {
880        if self.params.is_empty() {
881            self.params.push(0);
882        }
883        let pen = &mut self.screen.pen;
884        let mut i = 0;
885        while i < self.params.len() {
886            let p = self.params[i];
887            match p {
888                0 => *pen = Cell { ch: b' ', ..Cell::default() },
889                1 => pen.flags = (pen.flags | flags::BOLD) & !flags::FAINT,
890                2 => pen.flags = (pen.flags | flags::FAINT) & !flags::BOLD,
891                4 => pen.flags |= flags::UNDERLINE,
892                5 | 6 => pen.flags |= flags::BLINK,
893                7 => pen.flags |= flags::REVERSE,
894                8 => pen.flags |= flags::CONCEAL,
895                21 | 22 => pen.flags &= !(flags::BOLD | flags::FAINT),
896                24 => pen.flags &= !flags::UNDERLINE,
897                25 => pen.flags &= !flags::BLINK,
898                27 => pen.flags &= !flags::REVERSE,
899                28 => pen.flags &= !flags::CONCEAL,
900                30..=37 => pen.fg = Color::Pc(ANSI_TO_VGA[(p - 30) as usize]),
901                39 => pen.fg = DEFAULT_FG,
902                40..=47 => pen.bg = Color::Pc(ANSI_TO_VGA[(p - 40) as usize]),
903                49 => pen.bg = DEFAULT_BG,
904                90..=97 => pen.fg = Color::Pc(ANSI_TO_VGA[(p - 90) as usize] + 8),
905                100..=107 => pen.bg = Color::Pc(ANSI_TO_VGA[(p - 100) as usize] + 8),
906                38 | 48 => {
907                    let color = match self.params.get(i + 1) {
908                        Some(5) => {
909                            let c = self.params.get(i + 2).map(|&v| Color::Xterm(v as u8));
910                            i += 2;
911                            c
912                        }
913                        Some(2) => {
914                            let c = (i + 4 < self.params.len()).then(|| {
915                                let v = &self.params[i + 2..i + 5];
916                                Color::Rgb(rgb(v[0] as u8, v[1] as u8, v[2] as u8))
917                            });
918                            i += 4;
919                            c
920                        }
921                        _ => None,
922                    };
923                    if let Some(c) = color {
924                        if p == 38 { pen.fg = c } else { pen.bg = c }
925                    }
926                }
927                _ => log::debug!("unhandled SGR {p}"),
928            }
929            i += 1;
930        }
931    }
932}
933
934/// An X11-style color: `rgb:R/G/B` with 1-4 hex digits per channel, or
935/// `#RRGGBB`.
936fn parse_color(spec: &str) -> Option<crate::palette::Rgb> {
937    let spec = spec.trim();
938    if let Some(hex) = spec.strip_prefix('#') {
939        return (hex.len() == 6).then(|| u32::from_str_radix(hex, 16).ok()).flatten();
940    }
941    let mut channels = spec.strip_prefix("rgb:")?.split('/').map(|c| {
942        let v = u32::from_str_radix(c, 16).ok().filter(|_| (1..=4).contains(&c.len()))?;
943        // Scale to 8 bits: "f" and "ffff" are both full.
944        Some((v * 255 / ((1 << (4 * c.len())) - 1)) as u8)
945    });
946    let (r, g, b) = (channels.next()??, channels.next()??, channels.next()??);
947    channels.next().is_none().then(|| rgb(r, g, b))
948}
949
950#[cfg(test)]
951mod tests {
952    use super::*;
953
954    fn term() -> Terminal {
955        Terminal::new(80, 25, 100)
956    }
957
958    fn line(t: &Terminal, y: usize) -> String {
959        Screen::row_text(t.screen.row(y))
960    }
961
962    #[test]
963    fn cursor_position_and_text() {
964        let mut t = term();
965        t.feed(b"\x1b[3;5HHi");
966        assert_eq!(line(&t, 2), "    Hi");
967        assert_eq!(t.screen.cursor(), (6, 2));
968    }
969
970    #[test]
971    fn sgr_colors() {
972        let mut t = term();
973        t.feed(b"\x1b[1;31;44mX");
974        let c = t.screen.row(0)[0];
975        assert_eq!(c.fg, Color::Pc(4));
976        assert_eq!(c.bg, Color::Pc(1));
977        assert!(c.flags & flags::BOLD != 0);
978        t.feed(b"\x1b[0;38;2;10;20;30mY");
979        assert_eq!(t.screen.row(0)[1].fg, Color::Rgb(0x0A141E));
980        t.feed(b"\x1b[38;5;196mZ");
981        assert_eq!(t.screen.row(0)[2].fg, Color::Xterm(196));
982    }
983
984    #[test]
985    fn cursor_position_report() {
986        let mut t = term();
987        t.feed(b"\x1b[10;20H\x1b[6n");
988        assert_eq!(t.take_replies(), b"\x1b[10;20R");
989    }
990
991    #[test]
992    fn device_attributes() {
993        let mut t = term();
994        t.feed(b"\x1b[c\x1b[0c");
995        assert_eq!(t.take_replies(), [CTERM_DA, CTERM_DA].concat());
996        // Secondary DA (`CSI > c`) and `CSI 1 c` are not answered.
997        t.feed(b"\x1b[>c\x1b[1c");
998        assert!(t.take_replies().is_empty());
999    }
1000
1001    #[test]
1002    fn ice_mode_toggle() {
1003        let mut t = term();
1004        t.feed(b"\x1b[?33h");
1005        assert!(t.screen.ice_colors);
1006        t.feed(b"\x1b[?33l");
1007        assert!(!t.screen.ice_colors);
1008    }
1009
1010    #[test]
1011    fn cp437_glyphs_and_utf8() {
1012        let mut t = term();
1013        t.feed(&[0xDB, 0x03]);
1014        assert_eq!(t.screen.row(0)[0].ch, 0xDB);
1015        assert_eq!(t.screen.row(0)[1].ch, 0x03);
1016        t.encoding = Encoding::Utf8;
1017        t.feed("ۂ".as_bytes());
1018        assert_eq!(t.screen.row(0)[2].ch, 0xDB);
1019        assert_eq!(t.screen.row(0)[3].ch, 0x82);
1020    }
1021
1022    #[test]
1023    fn osc_title_and_strings_ignored() {
1024        let mut t = term();
1025        t.feed(b"\x1b]0;My BBS\x07\x1bPjunk\x1b\\ok");
1026        assert_eq!(t.take_events(), vec![TermEvent::Title("My BBS".into())]);
1027        assert_eq!(line(&t, 0), "ok");
1028    }
1029
1030    #[test]
1031    fn ansi_art_line_of_exactly_80_columns() {
1032        let mut t = term();
1033        let mut data = vec![b'#'; 80];
1034        data.extend_from_slice(b"\r\nnext");
1035        t.feed(&data);
1036        assert_eq!(line(&t, 1), "next");
1037    }
1038
1039    #[test]
1040    fn save_restore_cursor() {
1041        let mut t = term();
1042        t.feed(b"\x1b[5;5H\x1b[s\x1b[1;1H\x1b[uX");
1043        assert_eq!(t.screen.row(4)[4].ch, b'X');
1044    }
1045
1046    #[test]
1047    fn ansi_music() {
1048        let mut t = term();
1049        t.feed(b"Hi\x1b[NMLO3A\x0e there\x1b[|MLO3A8\x0e");
1050        assert_eq!(line(&t, 0), "Hi there");
1051        let a = Tone { hz: 440, ms: 500 };
1052        assert_eq!(t.take_events(), [TermEvent::Music(vec![a]), TermEvent::Music(vec![Tone { ms: 250, ..a }])]);
1053
1054        // ESC [ M is delete-line unless music is wanted there.
1055        t.feed(b"\x1b[2;1Hx\x1b[1;1H\x1b[M");
1056        assert_eq!(line(&t, 0), "x");
1057        t.music_on_csi_m = true;
1058        t.feed(b"\x1b[MMLO3A\x0e\x1b[1M");
1059        assert_eq!(t.take_events(), [TermEvent::Music(vec![a])]);
1060        assert_eq!(line(&t, 0), "");
1061    }
1062
1063    #[test]
1064    fn cterm_palette_and_fonts() {
1065        let mut t = Terminal::new(80, 25, 0);
1066        // Red (ANSI 1, VGA 4) becomes orange; bright blue (ANSI 12) too.
1067        t.feed(b"\x1b]4;1;rgb:ff/80/00;12;#123456\x1b\\");
1068        assert_eq!(t.screen.look.palette[1], 0xFF8000);
1069        assert_eq!(t.screen.look.rgb(Color::Pc(4)), 0xFF8000);
1070        assert_eq!(t.screen.look.rgb(Color::Pc(9)), 0x123456);
1071        t.feed(b"\x1b[31mX");
1072        assert_eq!(t.screen.row(0)[0].resolve_with(false, &t.screen.look).0, 0xFF8000);
1073        // Queried, then reset.
1074        t.feed(b"\x1b]4;1;?\x07");
1075        assert_eq!(t.take_replies(), b"\x1b]4;1;rgb:ff/80/00\x1b\\");
1076        t.feed(b"\x1b]104;1\x07");
1077        assert_eq!(t.screen.look.palette[1], 0xAA0000);
1078        assert_eq!(t.screen.look.palette[12], 0x123456);
1079        t.feed(b"\x1b]104\x07");
1080        assert_eq!(t.screen.look, *Look::standard());
1081
1082        // Font slots, and bright text in slot 1 without brightening.
1083        t.feed(b"\x1b[0;42 D\x1b[1;40 D\x1b[?31h\x1b[?32h\x1b[1;32mB");
1084        let cell = t.screen.row(0)[1];
1085        assert_eq!(t.screen.look.fonts, [42, 40, 0, 0]);
1086        assert_eq!(t.screen.look.font_for(&cell), 40);
1087        assert_eq!(cell.resolve_with(false, &t.screen.look).0, 0x00AA00);
1088        t.feed(b"\x1b[?31l\x1b[?32l");
1089        assert_eq!(t.screen.look.font_for(&cell), 42);
1090        assert_eq!(cell.resolve_with(false, &t.screen.look).0, 0x55FF55);
1091        assert_eq!(parse_color("rgb:f/0/8"), Some(0xFF0088));
1092        assert_eq!(parse_color("rgb:ffff/0000/8080"), Some(0xFF0080));
1093        assert_eq!(parse_color("rgb:1/2"), None);
1094    }
1095
1096    #[test]
1097    fn sixel_pictures() {
1098        let mut t = term();
1099        // 16 x 36 pixels (a pixel per sixel row, six bands), red, at 3;5.
1100        let mut seq = b"\x1b[3;5HA\x1bP0;1;0q\"1;1#1;2;100;0;0".to_vec();
1101        for _ in 0..6 {
1102            seq.extend_from_slice(b"!16~-");
1103        }
1104        seq.extend_from_slice(b"\x1b\\B");
1105        t.feed(&seq);
1106        let s = &t.screen;
1107        // The picture covers columns 5-6 (from the cursor, which was after
1108        // the A) of rows 3-5; the last band ends at pixel 36, so the cursor
1109        // is on the row holding pixel 36 (row 3 + 36 / 16), in the column it
1110        // started in, where the B went.
1111        let tile = s.tiles.get(s.row(2)[5].tile).expect("a tile");
1112        assert_eq!((tile.width, tile.height), (8, 16));
1113        assert_eq!(tile.pixels[0], crate::sixel::solid(0xFF0000));
1114        assert!(s.row(4)[6].tile != 0 && s.row(2)[7].tile == 0);
1115        assert_eq!(s.row(4)[5].ch, b'B');
1116        assert_eq!(s.row(4)[5].tile, 0, "text replaces the picture");
1117        assert_eq!(t.screen.cursor(), (6, 4));
1118
1119        // The size of the screen in pixels, and the color registers.
1120        t.feed(b"\x1b[?2;1S\x1b[?1;1S\x1b[<c");
1121        assert_eq!(t.take_replies(), b"\x1b[?2;0;640;400S\x1b[?1;0;256S\x1b[<0;2;3;4;5;6c");
1122        t.feed(b"\x1b[=1n\x1b[=2n\x1b[=3n\x1b[=7n");
1123        assert_eq!(t.take_replies(), b"\x1b[=1;43;99;0;0;0;0n\x1b[=2;7;25n\x1b[=3;16;8n\x1b[=7n");
1124    }
1125
1126    #[test]
1127    fn sixel_pictures_scroll_the_screen() {
1128        let mut t = term();
1129        t.feed(b"\x1b[25;1HX\x1bPq\"1;1;8;32\x1b\\");
1130        // 32 pixels: two rows; the screen scrolled two lines (the cursor
1131        // ends on the row holding pixel 32).
1132        assert_eq!(line(&t, 22), "X");
1133        assert!(t.screen.row(22)[1].tile != 0 && t.screen.row(23)[1].tile != 0);
1134        assert_eq!(t.screen.cursor(), (1, 24));
1135        // In display mode it goes at the top left and the cursor stays.
1136        t.feed(b"\x1b[?80h\x1b[10;10H\x1bPq\"1;1;8;16\x1b\\");
1137        assert!(t.screen.row(0)[0].tile != 0);
1138        assert_eq!(t.screen.cursor(), (9, 9));
1139    }
1140
1141    #[test]
1142    fn waiting_for_a_sound_holds_the_text() {
1143        let mut t = term();
1144        // A 100 ms tone, then wait for it before showing "after".
1145        t.feed(b"\x1b_SyncTERM:A;Synth;S=1;W=SIN;F=440;T=100\x1b\\\x1b_SyncTERM:A;Queue;C=2;S=1\x1b\\");
1146        assert!(matches!(t.take_events()[..], [TermEvent::Audio(crate::audio::AudioOp::Queue { channel: 2, .. })]));
1147        t.feed(b"before\x1b_SyncTERM:A;Wait;C=2\x1b\\after");
1148        t.feed(b" more");
1149        assert_eq!(line(&t, 0), "before");
1150        let at = t.next_poll().expect("a time to read again");
1151        t.poll(at);
1152        assert_eq!(line(&t, 0), "beforeafter more");
1153        // Its state is asked for and reported when it ends.
1154        t.feed(b"\x1b[=7;2n\x1b_SyncTERM:A;Update;C=2\x1b\\");
1155        t.poll(at + std::time::Duration::from_secs(1));
1156        let replies = String::from_utf8(t.take_replies()).unwrap();
1157        assert!(replies.ends_with("\x1b[=7;2;0n"), "{replies:?}");
1158        t.feed(b"\x1b_SyncTERM:Q;libsndfileFormat;0x20;100\x1b\\");
1159        assert_eq!(t.take_replies(), b"\x1b[=7;101;32;100;1n");
1160    }
1161
1162    #[test]
1163    fn reset_returns_to_the_entrys_ice_setting() {
1164        let mut t = Terminal::new(80, 25, 0);
1165        t.screen.base_ice = true;
1166        t.feed(b"\x1b[?33l");
1167        assert!(!t.screen.ice_colors);
1168        t.feed(b"\x1bc");
1169        assert!(t.screen.ice_colors);
1170    }
1171}