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> {
265 let size = self.size();
266 if self.fields().is_empty() {
267 for (i, &b) in text.iter().take(size).enumerate() {
268 self.data[(address + i) % size] = b;
269 }
270 self.cursor = (address + text.len().min(size)) % size;
271 return Ok(());
272 }
273 let field = self.field_at(address).ok_or("the screen has no fields")?;
274 if field.attribute & PROTECTED != 0 || field.attribute_at == address {
275 return Err(format!("row {} column {} is protected", self.position(address).0, self.position(address).1));
276 }
277 let offset = (address + size - field.start) % size;
278 for (i, &b) in text.iter().take(field.len - offset).enumerate() {
279 self.data[(address + i) % size] = b;
280 }
281 self.attributes[field.attribute_at] = Some(field.attribute | MDT);
282 self.cursor = (address + text.len().min(field.len - offset)) % size;
283 Ok(())
284 }
285
286 pub fn erase_eof(&mut self, address: usize) -> Result<(), String> {
288 let field = self.field_at(address).ok_or("the screen has no fields")?;
289 if field.attribute & PROTECTED != 0 {
290 return Err("ERASE EOF in a protected field".into());
291 }
292 let size = self.size();
293 let offset = (address + size - field.start) % size;
294 for i in offset..field.len {
295 self.data[(field.start + i) % size] = 0;
296 }
297 self.attributes[field.attribute_at] = Some(field.attribute | MDT);
298 Ok(())
299 }
300
301 pub fn read_modified(&self, aid: u8) -> Vec<u8> {
304 if matches!(aid, AID_CLEAR | AID_PA1 | AID_PA2 | AID_PA3) {
305 return vec![aid];
306 }
307 let mut out = vec![aid];
308 out.extend(encode_address(self.cursor));
309 let fields = self.fields();
310 if fields.is_empty() {
312 out.extend(self.data.iter().copied().filter(|&b| b != 0));
313 return out;
314 }
315 for f in fields.iter().filter(|f| f.attribute & MDT != 0) {
316 out.push(SBA);
317 out.extend(encode_address(f.start));
318 out.extend(self.field_data(f).into_iter().filter(|&b| b != 0));
319 }
320 out
321 }
322
323 pub fn render(&self, page: &CodePage) -> String {
325 let mut shown: Vec<char> = self.data.iter().map(|&b| if b == 0 { ' ' } else { page.decode_byte(b) }).collect();
326 for f in self.fields() {
327 shown[f.attribute_at] = ' ';
328 if f.attribute & DISPLAY == NON_DISPLAY {
329 for i in 0..f.len {
330 shown[(f.start + i) % self.size()] = ' ';
331 }
332 }
333 }
334 shown.chunks(self.columns).map(|row| row.iter().collect::<String>().trim_end().to_owned()).collect::<Vec<_>>().join("\n")
335 }
336}
337
338#[derive(Clone, Debug, PartialEq, Eq)]
341pub struct Inbound {
342 pub aid: u8,
343 pub cursor: Option<usize>,
344 pub fields: Vec<(usize, Vec<u8>)>,
345}
346
347pub fn parse_inbound(stream: &[u8]) -> Result<Inbound, String> {
348 let (&aid, rest) = stream.split_first().ok_or("an empty inbound stream")?;
349 if rest.is_empty() {
350 return Ok(Inbound { aid, cursor: None, fields: Vec::new() });
351 }
352 let cursor = decode_address(rest.get(..2).and_then(|s| s.try_into().ok()).ok_or("the cursor address is cut short")?);
353 let mut fields = Vec::new();
354 let mut i = 2;
355 while i < rest.len() {
356 if rest[i] != SBA {
357 return Err(format!("expected SBA at byte {}", i + 1));
358 }
359 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")?);
360 let end = rest[i + 3..].iter().position(|&b| b == SBA).map_or(rest.len(), |p| i + 3 + p);
361 fields.push((at, rest[i + 3..end].to_vec()));
362 i = end;
363 }
364 Ok(Inbound { aid, cursor: Some(cursor), fields })
365}
366
367pub fn aid_of(key: &str) -> Option<u8> {
369 let key = key.to_ascii_uppercase();
370 let pf = |n: u8| -> u8 {
371 match n {
372 1..=9 => 0xF0 + n,
373 10..=12 => 0x7A + n - 10,
374 13..=21 => 0xC1 + n - 13,
375 _ => 0x4A + n - 22,
376 }
377 };
378 Some(match key.as_str() {
379 "ENTER" => AID_ENTER,
380 "CLEAR" => AID_CLEAR,
381 "PA1" => AID_PA1,
382 "PA2" => AID_PA2,
383 "PA3" => AID_PA3,
384 k => match k.strip_prefix("PF").and_then(|n| n.parse::<u8>().ok()) {
385 Some(n @ 1..=24) => pf(n),
386 _ => return None,
387 },
388 })
389}
390
391#[derive(Clone, Debug, PartialEq, Eq)]
393pub enum Action {
394 Type { row: usize, column: usize, text: String },
395 EraseEof { row: usize, column: usize },
396 Cursor { row: usize, column: usize },
397 Key(u8),
398}
399
400pub fn parse_script(text: &str) -> Result<Vec<Action>, String> {
403 let mut actions = Vec::new();
404 for (n, raw) in text.lines().enumerate() {
405 let line = raw.trim();
406 if line.is_empty() || line.starts_with('#') {
407 continue;
408 }
409 let bad = |why: &str| format!("screen script line {}: {why}: {raw}", n + 1);
410 let mut words = line.splitn(4, ' ');
411 let verb = words.next().unwrap_or("").to_ascii_lowercase();
412 let at = |words: &mut std::str::SplitN<'_, char>| -> Result<(usize, usize), String> {
413 let row = words.next().and_then(|w| w.parse().ok()).filter(|&r: &usize| r >= 1).ok_or_else(|| bad("expected a row from 1"))?;
414 let column = words.next().and_then(|w| w.parse().ok()).filter(|&c: &usize| c >= 1).ok_or_else(|| bad("expected a column from 1"))?;
415 Ok((row, column))
416 };
417 actions.push(match verb.as_str() {
418 "type" => {
419 let (row, column) = at(&mut words)?;
420 Action::Type { row, column, text: words.next().unwrap_or("").to_owned() }
421 }
422 "eof" => {
423 let (row, column) = at(&mut words)?;
424 Action::EraseEof { row, column }
425 }
426 "cursor" => {
427 let (row, column) = at(&mut words)?;
428 Action::Cursor { row, column }
429 }
430 key => Action::Key(aid_of(key).ok_or_else(|| bad("not type, eof, cursor or an AID key"))?),
431 });
432 }
433 Ok(actions)
434}
435
436pub struct Scripted {
439 pub screen: Screen,
440 actions: std::collections::VecDeque<Action>,
441 page: &'static CodePage,
442 pub shown: std::rc::Rc<std::cell::RefCell<Vec<String>>>,
443 pending: Option<Vec<u8>>,
445}
446
447impl std::fmt::Debug for Scripted {
448 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
449 write!(f, "Scripted({}x{}, {} actions left)", self.screen.rows, self.screen.columns, self.actions.len())
450 }
451}
452
453impl Scripted {
454 pub fn new(rows: usize, columns: usize, actions: Vec<Action>, page: &'static CodePage) -> Self {
455 Self { screen: Screen::new(rows, columns), actions: actions.into(), page, shown: Default::default(), pending: None }
456 }
457
458 pub fn push_back(&mut self, record: Vec<u8>) {
460 self.pending = Some(record);
461 }
462}
463
464#[derive(Clone, Debug)]
466pub struct SharedScript(pub std::rc::Rc<std::cell::RefCell<Scripted>>);
467
468impl Terminal for SharedScript {
469 fn size(&self) -> (usize, usize) {
470 self.0.borrow().size()
471 }
472
473 fn send(&mut self, stream: &[u8]) -> Result<(), String> {
474 self.0.borrow_mut().send(stream)
475 }
476
477 fn receive(&mut self) -> Result<Option<Vec<u8>>, String> {
478 self.0.borrow_mut().receive()
479 }
480}
481
482impl Terminal for Scripted {
483 fn size(&self) -> (usize, usize) {
484 (self.screen.rows, self.screen.columns)
485 }
486
487 fn send(&mut self, stream: &[u8]) -> Result<(), String> {
488 self.screen.apply(stream)?;
489 self.shown.borrow_mut().push(self.screen.render(self.page));
490 Ok(())
491 }
492
493 fn receive(&mut self) -> Result<Option<Vec<u8>>, String> {
494 if let Some(record) = self.pending.take() {
495 return Ok(Some(record));
496 }
497 while let Some(action) = self.actions.pop_front() {
498 match action {
499 Action::Type { row, column, text } => {
500 let bytes = self.page.encode_lossy(&text);
501 self.screen.type_at(self.screen.address(row, column), &bytes)?;
502 }
503 Action::EraseEof { row, column } => self.screen.erase_eof(self.screen.address(row, column))?,
504 Action::Cursor { row, column } => self.screen.cursor = self.screen.address(row, column),
505 Action::Key(aid) => return Ok(Some(self.screen.read_modified(aid))),
506 }
507 }
508 Ok(None)
509 }
510}
511
512#[cfg(test)]
513mod tests {
514 use super::*;
515
516 fn page() -> &'static CodePage {
517 CodePage::by_ccsid(37).unwrap()
518 }
519
520 #[test]
521 fn addresses_round_trip_in_both_encodings() {
522 for a in [0, 1, 79, 80, 1919, 4095] {
523 assert_eq!(decode_address(encode_address(a)), a);
524 }
525 assert_eq!(encode_address(80), [0xC1, 0x50]);
526 assert_eq!(decode_address(encode_address(5000)), 5000);
527 assert_eq!(encode_address(5000)[0] & 0xC0, 0);
528 }
529
530 #[test]
531 fn a_write_builds_fields_and_read_modified_returns_what_was_typed() {
532 let mut s = Screen::new(24, 80);
533 let mut stream = vec![ERASE_WRITE, WCC_RESTORE, SBA];
534 stream.extend(encode_address(0));
535 stream.extend([SF, attribute_byte(PROTECTED | INTENSIFIED)]);
536 stream.extend(page().encode("NAME:").unwrap());
537 stream.extend([SF, attribute_byte(0), IC]);
538 stream.extend([SBA]);
539 stream.extend(encode_address(20));
540 stream.extend([SF, attribute_byte(PROTECTED)]);
541 s.apply(&stream).unwrap();
542 assert_eq!(s.fields().len(), 3);
543 assert_eq!(s.cursor, 7);
544 assert!(!s.keyboard_locked);
545 assert!(s.type_at(1, b"x").is_err());
546 s.type_at(7, &page().encode("SMITH").unwrap()).unwrap();
547 assert_eq!(s.render(page()).lines().next().unwrap(), " NAME: SMITH");
548 let inbound = s.read_modified(AID_ENTER);
549 let read = parse_inbound(&inbound).unwrap();
550 assert_eq!((read.aid, read.cursor), (AID_ENTER, Some(12)));
551 assert_eq!(read.fields, vec![(7, page().encode("SMITH").unwrap())]);
552 assert_eq!(s.read_modified(AID_CLEAR), vec![AID_CLEAR]);
553 }
554
555 #[test]
556 fn an_unformatted_screen_takes_typing_anywhere_and_sends_its_whole_buffer() {
557 let mut s = Screen::new(24, 80);
558 s.type_at(0, &page().encode("SSC1 HELLO").unwrap()).unwrap();
559 let inbound = s.read_modified(AID_ENTER);
560 assert_eq!(inbound[0], AID_ENTER);
561 assert_eq!(&inbound[3..], page().encode("SSC1 HELLO").unwrap().as_slice());
562 }
563
564 #[test]
565 fn wcc_resets_modified_bits_and_eau_clears_unprotected_data() {
566 let mut s = Screen::new(24, 80);
567 let mut stream = vec![ERASE_WRITE, WCC_RESTORE, SF, attribute_byte(0)];
568 stream.extend(page().encode("AB").unwrap());
569 s.apply(&stream).unwrap();
570 s.type_at(1, &page().encode("Z").unwrap()).unwrap();
571 assert_eq!(s.fields()[0].attribute & MDT, MDT);
572 s.apply(&[WRITE, WCC_RESET_MDT]).unwrap();
573 assert_eq!(s.fields()[0].attribute & MDT, 0);
574 s.apply(&[ERASE_ALL_UNPROTECTED]).unwrap();
575 assert!(s.field_data(&s.fields()[0]).iter().all(|&b| b == 0));
576 }
577
578 #[test]
579 fn non_display_fields_render_blank_and_bad_streams_are_refused() {
580 let mut s = Screen::new(2, 10);
581 let mut stream = vec![ERASE_WRITE, 0, SF, attribute_byte(NON_DISPLAY)];
582 stream.extend(page().encode("SECRET").unwrap());
583 s.apply(&stream).unwrap();
584 assert_eq!(s.render(page()), "\n");
585 assert!(s.apply(&[0x99]).is_err());
586 assert!(s.apply(&[WRITE, 0, SBA, 0x7F]).is_err());
587 }
588
589 #[test]
590 fn aid_keys_and_screen_scripts() {
591 assert_eq!(aid_of("enter"), Some(0x7D));
592 assert_eq!(aid_of("PF1"), Some(0xF1));
593 assert_eq!(aid_of("PF12"), Some(0x7C));
594 assert_eq!(aid_of("PF13"), Some(0xC1));
595 assert_eq!(aid_of("PF24"), Some(0x4C));
596 assert_eq!(aid_of("PF25"), None);
597 let script = parse_script("# order entry\ntype 5 20 SMITH & CO\neof 6 20\ncursor 7 1\nENTER\nPF3\n").unwrap();
598 assert_eq!(script[0], Action::Type { row: 5, column: 20, text: "SMITH & CO".into() });
599 assert_eq!(script[1], Action::EraseEof { row: 6, column: 20 });
600 assert_eq!(script[3], Action::Key(0x7D));
601 assert_eq!(script[4], Action::Key(0xF3));
602 assert!(parse_script("type 0 1 X").is_err());
603 assert!(parse_script("jump 1 1").is_err());
604 }
605}