1use zarch::ebcdic::CodePage;
6
7pub trait Terminal: std::fmt::Debug {
10 fn size(&self) -> (usize, usize);
11 fn send(&mut self, stream: &[u8]) -> Result<(), String>;
12 fn receive(&mut self) -> Result<Option<Vec<u8>>, String>;
14}
15
16pub const WRITE: u8 = 0xF1;
17pub const ERASE_WRITE: u8 = 0xF5;
18pub const ERASE_WRITE_ALTERNATE: u8 = 0x7E;
19pub const ERASE_ALL_UNPROTECTED: u8 = 0x6F;
20
21pub const WCC_ALARM: u8 = 0x04;
22pub const WCC_RESTORE: u8 = 0x02;
23pub const WCC_RESET_MDT: u8 = 0x01;
24
25pub const SF: u8 = 0x1D;
26pub const SFE: u8 = 0x29;
27pub const SBA: u8 = 0x11;
28pub const SA: u8 = 0x28;
29pub const MF: u8 = 0x2C;
30pub const IC: u8 = 0x13;
31pub const PT: u8 = 0x05;
32pub const RA: u8 = 0x3C;
33pub const EUA: u8 = 0x12;
34
35pub const PROTECTED: u8 = 0x20;
36pub const NUMERIC: u8 = 0x10;
37pub const DISPLAY: u8 = 0x0C;
38pub const INTENSIFIED: u8 = 0x08;
39pub const NON_DISPLAY: u8 = 0x0C;
40pub const MDT: u8 = 0x01;
41
42pub const AID_ENTER: u8 = 0x7D;
43pub const AID_CLEAR: u8 = 0x6D;
44pub const AID_PA1: u8 = 0x6C;
45pub const AID_PA2: u8 = 0x6E;
46pub const AID_PA3: u8 = 0x6B;
47pub const AID_NONE: u8 = 0x60;
48
49const CODES: [u8; 64] = [
51 0x40, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5,
52 0xD6, 0xD7, 0xD8, 0xD9, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0x6A, 0x6B,
53 0x6C, 0x6D, 0x6E, 0x6F, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
54];
55
56pub fn encode_address(address: usize) -> [u8; 2] {
58 if address < 4096 {
59 [CODES[address >> 6], CODES[address & 0x3F]]
60 } else {
61 [((address >> 8) & 0x3F) as u8, (address & 0xFF) as u8]
62 }
63}
64
65pub fn decode_address(bytes: [u8; 2]) -> usize {
66 if bytes[0] & 0xC0 == 0 {
67 (usize::from(bytes[0] & 0x3F) << 8) | usize::from(bytes[1])
68 } else {
69 (usize::from(bytes[0] & 0x3F) << 6) | usize::from(bytes[1] & 0x3F)
70 }
71}
72
73pub fn attribute_byte(bits: u8) -> u8 {
75 CODES[usize::from(bits & 0x3F)]
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub struct FieldView {
81 pub attribute_at: usize,
82 pub attribute: u8,
83 pub start: usize,
84 pub len: usize,
85}
86
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct Screen {
89 pub rows: usize,
90 pub columns: usize,
91 data: Vec<u8>,
92 attributes: Vec<Option<u8>>,
93 pub cursor: usize,
94 pub alarm: bool,
95 pub keyboard_locked: bool,
96}
97
98impl Screen {
99 pub fn new(rows: usize, columns: usize) -> Self {
100 let size = rows * columns;
101 Self { rows, columns, data: vec![0; size], attributes: vec![None; size], cursor: 0, alarm: false, keyboard_locked: true }
102 }
103
104 pub fn size(&self) -> usize {
105 self.rows * self.columns
106 }
107
108 pub fn position(&self, address: usize) -> (usize, usize) {
110 (address / self.columns + 1, address % self.columns + 1)
111 }
112
113 pub fn address(&self, row: usize, column: usize) -> usize {
114 ((row - 1) * self.columns + column - 1) % self.size()
115 }
116
117 fn erase(&mut self) {
118 self.data.fill(0);
119 self.attributes.fill(None);
120 self.cursor = 0;
121 }
122
123 pub fn fields(&self) -> Vec<FieldView> {
125 let size = self.size();
126 let starts: Vec<usize> = (0..size).filter(|&a| self.attributes[a].is_some()).collect();
127 starts
128 .iter()
129 .enumerate()
130 .map(|(i, &at)| {
131 let next = starts[(i + 1) % starts.len()];
132 let len = (next + size - at - 1) % size;
133 FieldView { attribute_at: at, attribute: self.attributes[at].unwrap_or(0), start: (at + 1) % size, len: if starts.len() == 1 { size - 1 } else { len } }
134 })
135 .collect()
136 }
137
138 pub fn field_at(&self, address: usize) -> Option<FieldView> {
140 let size = self.size();
141 self.fields().into_iter().find(|f| f.attribute_at == address || (address + size - f.start) % size < f.len)
142 }
143
144 pub fn field_data(&self, field: &FieldView) -> Vec<u8> {
145 (0..field.len).map(|i| self.data[(field.start + i) % self.size()]).collect()
146 }
147
148 fn set_attribute(&mut self, address: usize, attribute: u8) {
149 self.attributes[address] = Some(attribute);
150 self.data[address] = 0;
151 }
152
153 fn put(&mut self, address: &mut usize, byte: u8) {
154 self.attributes[*address] = None;
155 self.data[*address] = byte;
156 *address = (*address + 1) % self.size();
157 }
158
159 fn next_unprotected(&self, from: usize) -> usize {
160 let size = self.size();
161 (1..=size)
162 .map(|i| (from + i) % size)
163 .find(|&a| self.attributes[a].is_some_and(|attr| attr & PROTECTED == 0))
164 .map_or(0, |a| (a + 1) % size)
165 }
166
167 pub fn apply(&mut self, stream: &[u8]) -> Result<(), String> {
169 let (&command, rest) = stream.split_first().ok_or("an empty data stream")?;
170 match command {
171 ERASE_WRITE | ERASE_WRITE_ALTERNATE | 0x05 | 0x0D => self.erase(),
172 WRITE | 0x01 => {}
173 ERASE_ALL_UNPROTECTED | 0x0F => {
174 let size = self.size();
175 for f in self.fields().iter().filter(|f| f.attribute & PROTECTED == 0) {
176 for i in 0..f.len {
177 self.data[(f.start + i) % size] = 0;
178 }
179 self.attributes[f.attribute_at] = Some(f.attribute & !MDT);
180 }
181 self.keyboard_locked = false;
182 return Ok(());
183 }
184 other => return Err(format!("3270 command X'{other:02X}' is not supported")),
185 }
186 let Some((&wcc, mut orders)) = rest.split_first() else { return Ok(()) };
187 if wcc & WCC_RESET_MDT != 0 {
188 for a in 0..self.size() {
189 if let Some(attr) = self.attributes[a] {
190 self.attributes[a] = Some(attr & !MDT);
191 }
192 }
193 }
194 let mut at = self.cursor;
195 let size = self.size();
196 let address = |bytes: &[u8]| -> Result<usize, String> {
197 let [a, b] = bytes.get(..2).and_then(|s| s.try_into().ok()).ok_or("a buffer address cut short")?;
198 let address = decode_address([a, b]);
199 if address >= size { Err(format!("buffer address {address} is past the screen ({size})")) } else { Ok(address) }
200 };
201 while let Some((&byte, rest)) = orders.split_first() {
202 orders = rest;
203 match byte {
204 SBA => {
205 at = address(orders)?;
206 orders = &orders[2..];
207 }
208 SF => {
209 let (&attr, rest) = orders.split_first().ok_or("SF without an attribute")?;
210 self.set_attribute(at, attr);
211 at = (at + 1) % size;
212 orders = rest;
213 }
214 SFE => {
215 let (&pairs, rest) = orders.split_first().ok_or("SFE without a count")?;
216 let pairs = usize::from(pairs);
217 let list = rest.get(..pairs * 2).ok_or("SFE cut short")?;
218 let attr = list.chunks(2).find(|p| p[0] == 0xC0).map_or(0x40, |p| p[1]);
219 self.set_attribute(at, attr);
220 at = (at + 1) % size;
221 orders = &rest[pairs * 2..];
222 }
223 SA => orders = orders.get(2..).ok_or("SA cut short")?,
224 MF => {
225 let (&pairs, rest) = orders.split_first().ok_or("MF without a count")?;
226 orders = rest.get(usize::from(pairs) * 2..).ok_or("MF cut short")?;
227 }
228 IC => self.cursor = at,
229 PT => at = self.next_unprotected(at),
230 RA => {
231 let stop = address(orders)?;
232 let fill = *orders.get(2).ok_or("RA without a character")?;
233 orders = &orders[3..];
234 loop {
235 self.put(&mut at, fill);
236 if at == stop {
237 break;
238 }
239 }
240 }
241 EUA => {
242 let stop = address(orders)?;
243 orders = &orders[2..];
244 while at != stop {
245 if self.field_at(at).is_some_and(|f| f.attribute & PROTECTED == 0) && self.attributes[at].is_none() {
246 self.data[at] = 0;
247 }
248 at = (at + 1) % size;
249 }
250 }
251 data => self.put(&mut at, data),
252 }
253 }
254 self.alarm = wcc & WCC_ALARM != 0;
255 if wcc & WCC_RESTORE != 0 {
256 self.keyboard_locked = false;
257 }
258 Ok(())
259 }
260
261 pub fn type_at(&mut self, address: usize, text: &[u8]) -> Result<(), String> {
264 let field = self.field_at(address).ok_or("the screen has no fields")?;
265 if field.attribute & PROTECTED != 0 || field.attribute_at == address {
266 return Err(format!("row {} column {} is protected", self.position(address).0, self.position(address).1));
267 }
268 let size = self.size();
269 let offset = (address + size - field.start) % size;
270 for (i, &b) in text.iter().take(field.len - offset).enumerate() {
271 self.data[(address + i) % size] = b;
272 }
273 self.attributes[field.attribute_at] = Some(field.attribute | MDT);
274 self.cursor = (address + text.len().min(field.len - offset)) % size;
275 Ok(())
276 }
277
278 pub fn erase_eof(&mut self, address: usize) -> Result<(), String> {
280 let field = self.field_at(address).ok_or("the screen has no fields")?;
281 if field.attribute & PROTECTED != 0 {
282 return Err("ERASE EOF in a protected field".into());
283 }
284 let size = self.size();
285 let offset = (address + size - field.start) % size;
286 for i in offset..field.len {
287 self.data[(field.start + i) % size] = 0;
288 }
289 self.attributes[field.attribute_at] = Some(field.attribute | MDT);
290 Ok(())
291 }
292
293 pub fn read_modified(&self, aid: u8) -> Vec<u8> {
296 if matches!(aid, AID_CLEAR | AID_PA1 | AID_PA2 | AID_PA3) {
297 return vec![aid];
298 }
299 let mut out = vec![aid];
300 out.extend(encode_address(self.cursor));
301 for f in self.fields().iter().filter(|f| f.attribute & MDT != 0) {
302 out.push(SBA);
303 out.extend(encode_address(f.start));
304 out.extend(self.field_data(f).into_iter().filter(|&b| b != 0));
305 }
306 out
307 }
308
309 pub fn render(&self, page: &CodePage) -> String {
311 let mut shown: Vec<char> = self.data.iter().map(|&b| if b == 0 { ' ' } else { page.decode_byte(b) }).collect();
312 for f in self.fields() {
313 shown[f.attribute_at] = ' ';
314 if f.attribute & DISPLAY == NON_DISPLAY {
315 for i in 0..f.len {
316 shown[(f.start + i) % self.size()] = ' ';
317 }
318 }
319 }
320 shown.chunks(self.columns).map(|row| row.iter().collect::<String>().trim_end().to_owned()).collect::<Vec<_>>().join("\n")
321 }
322}
323
324#[derive(Clone, Debug, PartialEq, Eq)]
327pub struct Inbound {
328 pub aid: u8,
329 pub cursor: Option<usize>,
330 pub fields: Vec<(usize, Vec<u8>)>,
331}
332
333pub fn parse_inbound(stream: &[u8]) -> Result<Inbound, String> {
334 let (&aid, rest) = stream.split_first().ok_or("an empty inbound stream")?;
335 if rest.is_empty() {
336 return Ok(Inbound { aid, cursor: None, fields: Vec::new() });
337 }
338 let cursor = decode_address(rest.get(..2).and_then(|s| s.try_into().ok()).ok_or("the cursor address is cut short")?);
339 let mut fields = Vec::new();
340 let mut i = 2;
341 while i < rest.len() {
342 if rest[i] != SBA {
343 return Err(format!("expected SBA at byte {}", i + 1));
344 }
345 let at = decode_address(rest.get(i + 1..i + 3).and_then(|s| s.try_into().ok()).ok_or("an SBA address is cut short")?);
346 let end = rest[i + 3..].iter().position(|&b| b == SBA).map_or(rest.len(), |p| i + 3 + p);
347 fields.push((at, rest[i + 3..end].to_vec()));
348 i = end;
349 }
350 Ok(Inbound { aid, cursor: Some(cursor), fields })
351}
352
353pub fn aid_of(key: &str) -> Option<u8> {
355 let key = key.to_ascii_uppercase();
356 let pf = |n: u8| -> u8 {
357 match n {
358 1..=9 => 0xF0 + n,
359 10..=12 => 0x7A + n - 10,
360 13..=21 => 0xC1 + n - 13,
361 _ => 0x4A + n - 22,
362 }
363 };
364 Some(match key.as_str() {
365 "ENTER" => AID_ENTER,
366 "CLEAR" => AID_CLEAR,
367 "PA1" => AID_PA1,
368 "PA2" => AID_PA2,
369 "PA3" => AID_PA3,
370 k => match k.strip_prefix("PF").and_then(|n| n.parse::<u8>().ok()) {
371 Some(n @ 1..=24) => pf(n),
372 _ => return None,
373 },
374 })
375}
376
377#[derive(Clone, Debug, PartialEq, Eq)]
379pub enum Action {
380 Type { row: usize, column: usize, text: String },
381 EraseEof { row: usize, column: usize },
382 Cursor { row: usize, column: usize },
383 Key(u8),
384}
385
386pub fn parse_script(text: &str) -> Result<Vec<Action>, String> {
389 let mut actions = Vec::new();
390 for (n, raw) in text.lines().enumerate() {
391 let line = raw.trim();
392 if line.is_empty() || line.starts_with('#') {
393 continue;
394 }
395 let bad = |why: &str| format!("screen script line {}: {why}: {raw}", n + 1);
396 let mut words = line.splitn(4, ' ');
397 let verb = words.next().unwrap_or("").to_ascii_lowercase();
398 let at = |words: &mut std::str::SplitN<'_, char>| -> Result<(usize, usize), String> {
399 let row = words.next().and_then(|w| w.parse().ok()).filter(|&r: &usize| r >= 1).ok_or_else(|| bad("expected a row from 1"))?;
400 let column = words.next().and_then(|w| w.parse().ok()).filter(|&c: &usize| c >= 1).ok_or_else(|| bad("expected a column from 1"))?;
401 Ok((row, column))
402 };
403 actions.push(match verb.as_str() {
404 "type" => {
405 let (row, column) = at(&mut words)?;
406 Action::Type { row, column, text: words.next().unwrap_or("").to_owned() }
407 }
408 "eof" => {
409 let (row, column) = at(&mut words)?;
410 Action::EraseEof { row, column }
411 }
412 "cursor" => {
413 let (row, column) = at(&mut words)?;
414 Action::Cursor { row, column }
415 }
416 key => Action::Key(aid_of(key).ok_or_else(|| bad("not type, eof, cursor or an AID key"))?),
417 });
418 }
419 Ok(actions)
420}
421
422pub struct Scripted {
425 pub screen: Screen,
426 actions: std::collections::VecDeque<Action>,
427 page: &'static CodePage,
428 pub shown: std::rc::Rc<std::cell::RefCell<Vec<String>>>,
429}
430
431impl std::fmt::Debug for Scripted {
432 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433 write!(f, "Scripted({}x{}, {} actions left)", self.screen.rows, self.screen.columns, self.actions.len())
434 }
435}
436
437impl Scripted {
438 pub fn new(rows: usize, columns: usize, actions: Vec<Action>, page: &'static CodePage) -> Self {
439 Self { screen: Screen::new(rows, columns), actions: actions.into(), page, shown: Default::default() }
440 }
441}
442
443impl Terminal for Scripted {
444 fn size(&self) -> (usize, usize) {
445 (self.screen.rows, self.screen.columns)
446 }
447
448 fn send(&mut self, stream: &[u8]) -> Result<(), String> {
449 self.screen.apply(stream)?;
450 self.shown.borrow_mut().push(self.screen.render(self.page));
451 Ok(())
452 }
453
454 fn receive(&mut self) -> Result<Option<Vec<u8>>, String> {
455 while let Some(action) = self.actions.pop_front() {
456 match action {
457 Action::Type { row, column, text } => {
458 let bytes = self.page.encode_lossy(&text);
459 self.screen.type_at(self.screen.address(row, column), &bytes)?;
460 }
461 Action::EraseEof { row, column } => self.screen.erase_eof(self.screen.address(row, column))?,
462 Action::Cursor { row, column } => self.screen.cursor = self.screen.address(row, column),
463 Action::Key(aid) => return Ok(Some(self.screen.read_modified(aid))),
464 }
465 }
466 Ok(None)
467 }
468}
469
470#[cfg(test)]
471mod tests {
472 use super::*;
473
474 fn page() -> &'static CodePage {
475 CodePage::by_ccsid(37).unwrap()
476 }
477
478 #[test]
479 fn addresses_round_trip_in_both_encodings() {
480 for a in [0, 1, 79, 80, 1919, 4095] {
481 assert_eq!(decode_address(encode_address(a)), a);
482 }
483 assert_eq!(encode_address(80), [0xC1, 0x50]);
484 assert_eq!(decode_address(encode_address(5000)), 5000);
485 assert_eq!(encode_address(5000)[0] & 0xC0, 0);
486 }
487
488 #[test]
489 fn a_write_builds_fields_and_read_modified_returns_what_was_typed() {
490 let mut s = Screen::new(24, 80);
491 let mut stream = vec![ERASE_WRITE, WCC_RESTORE, SBA];
492 stream.extend(encode_address(0));
493 stream.extend([SF, attribute_byte(PROTECTED | INTENSIFIED)]);
494 stream.extend(page().encode("NAME:").unwrap());
495 stream.extend([SF, attribute_byte(0), IC]);
496 stream.extend([SBA]);
497 stream.extend(encode_address(20));
498 stream.extend([SF, attribute_byte(PROTECTED)]);
499 s.apply(&stream).unwrap();
500 assert_eq!(s.fields().len(), 3);
501 assert_eq!(s.cursor, 7);
502 assert!(!s.keyboard_locked);
503 assert!(s.type_at(1, b"x").is_err());
504 s.type_at(7, &page().encode("SMITH").unwrap()).unwrap();
505 assert_eq!(s.render(page()).lines().next().unwrap(), " NAME: SMITH");
506 let inbound = s.read_modified(AID_ENTER);
507 let read = parse_inbound(&inbound).unwrap();
508 assert_eq!((read.aid, read.cursor), (AID_ENTER, Some(12)));
509 assert_eq!(read.fields, vec![(7, page().encode("SMITH").unwrap())]);
510 assert_eq!(s.read_modified(AID_CLEAR), vec![AID_CLEAR]);
511 }
512
513 #[test]
514 fn wcc_resets_modified_bits_and_eau_clears_unprotected_data() {
515 let mut s = Screen::new(24, 80);
516 let mut stream = vec![ERASE_WRITE, WCC_RESTORE, SF, attribute_byte(0)];
517 stream.extend(page().encode("AB").unwrap());
518 s.apply(&stream).unwrap();
519 s.type_at(1, &page().encode("Z").unwrap()).unwrap();
520 assert_eq!(s.fields()[0].attribute & MDT, MDT);
521 s.apply(&[WRITE, WCC_RESET_MDT]).unwrap();
522 assert_eq!(s.fields()[0].attribute & MDT, 0);
523 s.apply(&[ERASE_ALL_UNPROTECTED]).unwrap();
524 assert!(s.field_data(&s.fields()[0]).iter().all(|&b| b == 0));
525 }
526
527 #[test]
528 fn non_display_fields_render_blank_and_bad_streams_are_refused() {
529 let mut s = Screen::new(2, 10);
530 let mut stream = vec![ERASE_WRITE, 0, SF, attribute_byte(NON_DISPLAY)];
531 stream.extend(page().encode("SECRET").unwrap());
532 s.apply(&stream).unwrap();
533 assert_eq!(s.render(page()), "\n");
534 assert!(s.apply(&[0x99]).is_err());
535 assert!(s.apply(&[WRITE, 0, SBA, 0x7F]).is_err());
536 }
537
538 #[test]
539 fn aid_keys_and_screen_scripts() {
540 assert_eq!(aid_of("enter"), Some(0x7D));
541 assert_eq!(aid_of("PF1"), Some(0xF1));
542 assert_eq!(aid_of("PF12"), Some(0x7C));
543 assert_eq!(aid_of("PF13"), Some(0xC1));
544 assert_eq!(aid_of("PF24"), Some(0x4C));
545 assert_eq!(aid_of("PF25"), None);
546 let script = parse_script("# order entry\ntype 5 20 SMITH & CO\neof 6 20\ncursor 7 1\nENTER\nPF3\n").unwrap();
547 assert_eq!(script[0], Action::Type { row: 5, column: 20, text: "SMITH & CO".into() });
548 assert_eq!(script[1], Action::EraseEof { row: 6, column: 20 });
549 assert_eq!(script[3], Action::Key(0x7D));
550 assert_eq!(script[4], Action::Key(0xF3));
551 assert!(parse_script("type 0 1 X").is_err());
552 assert!(parse_script("jump 1 1").is_err());
553 }
554}