From de3c663ccd4a61b750a13be6e4f244ef047d7249 Mon Sep 17 00:00:00 2001 From: TQ Hirsch Date: Wed, 11 Nov 2020 15:38:01 +0100 Subject: [PATCH] Initial commit --- .envrc | 1 + .gitignore | 1 + Cargo.toml | 14 ++ shell.nix | 8 + src/encoding.rs | 19 +++ src/encoding/cp037.rs | 70 +++++++++ src/main.rs | 53 +++++++ src/tn3270.rs | 158 ++++++++++++++++++++ src/tn3270/stream.rs | 340 ++++++++++++++++++++++++++++++++++++++++++ 9 files changed, 664 insertions(+) create mode 100644 .envrc create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 shell.nix create mode 100644 src/encoding.rs create mode 100644 src/encoding/cp037.rs create mode 100644 src/main.rs create mode 100644 src/tn3270.rs create mode 100644 src/tn3270/stream.rs diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..051d09d --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +eval "$(lorri direnv)" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..7539d69 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "tn3270s" +version = "0.1.0" +authors = ["TQ Hirsch "] +edition = "2018" +description = "TN3270 telnet server" +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +libtelnet-rs = "1.1.0" +structopt = "0.3.20" +anyhow = "1.0.33" +thiserror = "1.0.21" +bitflags = "1.2.1" diff --git a/shell.nix b/shell.nix new file mode 100644 index 0000000..ec2d63e --- /dev/null +++ b/shell.nix @@ -0,0 +1,8 @@ +{ pkgs ? import {} }: + +pkgs.mkShell { + buildInputs = [ + # keep this line if you use bash + pkgs.bashInteractive + ]; +} diff --git a/src/encoding.rs b/src/encoding.rs new file mode 100644 index 0000000..134a2d1 --- /dev/null +++ b/src/encoding.rs @@ -0,0 +1,19 @@ +mod cp037; + +pub trait SBCS { + fn from_unicode(ch: char) -> Option; + fn to_unicode(ch: u8) -> char; +} + +pub fn to_cp037(stream: impl Iterator) -> impl Iterator { + stream.map(|ch| { + let ch = cp037::ENCODE_TBL.get(ch as usize) + .copied() + .unwrap_or(0x40); + if ch < 0x40 { // prohibit sending control codes. + 0x40 + } else { + ch + } + }) +} \ No newline at end of file diff --git a/src/encoding/cp037.rs b/src/encoding/cp037.rs new file mode 100644 index 0000000..86a0ab6 --- /dev/null +++ b/src/encoding/cp037.rs @@ -0,0 +1,70 @@ +#[allow(unused)] +pub const ENCODE_TBL: [u8; 256] = [ + 0x00, 0x01, 0x02, 0x03, 0x37, 0x2d, 0x2e, 0x2f, + 0x16, 0x05, 0x25, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x3c, 0x3d, 0x32, 0x26, + 0x18, 0x19, 0x3f, 0x27, 0x1c, 0x1d, 0x1e, 0x1f, + 0x40, 0x5a, 0x7f, 0x7b, 0x5b, 0x6c, 0x50, 0x7d, + 0x4d, 0x5d, 0x5c, 0x4e, 0x6b, 0x60, 0x4b, 0x61, + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, + 0xf8, 0xf9, 0x7a, 0x5e, 0x4c, 0x7e, 0x6e, 0x6f, + 0x7c, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, + 0xc8, 0xc9, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, + 0xd7, 0xd8, 0xd9, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, + 0xe7, 0xe8, 0xe9, 0xba, 0xe0, 0xbb, 0xb0, 0x6d, + 0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, + 0xa7, 0xa8, 0xa9, 0xc0, 0x4f, 0xd0, 0xa1, 0x07, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x15, 0x06, 0x17, + 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x09, 0x0a, 0x1b, + 0x30, 0x31, 0x1a, 0x33, 0x34, 0x35, 0x36, 0x08, + 0x38, 0x39, 0x3a, 0x3b, 0x04, 0x14, 0x3e, 0xff, + 0x41, 0xaa, 0x4a, 0xb1, 0x9f, 0xb2, 0x6a, 0xb5, + 0xbd, 0xb4, 0x9a, 0x8a, 0x5f, 0xca, 0xaf, 0xbc, + 0x90, 0x8f, 0xea, 0xfa, 0xbe, 0xa0, 0xb6, 0xb3, + 0x9d, 0xda, 0x9b, 0x8b, 0xb7, 0xb8, 0xb9, 0xab, + 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9e, 0x68, + 0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, + 0xac, 0x69, 0xed, 0xee, 0xeb, 0xef, 0xec, 0xbf, + 0x80, 0xfd, 0xfe, 0xfb, 0xfc, 0xad, 0xae, 0x59, + 0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9c, 0x48, + 0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, + 0x8c, 0x49, 0xcd, 0xce, 0xcb, 0xcf, 0xcc, 0xe1, + 0x70, 0xdd, 0xde, 0xdb, 0xdc, 0x8d, 0x8e, 0xdf, +]; +#[allow(unused)] +pub const DECODE_TBL: [u8; 256] = [ + 0x00, 0x01, 0x02, 0x03, 0x9c, 0x09, 0x86, 0x7f, + 0x97, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x9d, 0x85, 0x08, 0x87, + 0x18, 0x19, 0x92, 0x8f, 0x1c, 0x1d, 0x1e, 0x1f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x0a, 0x17, 0x1b, + 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, + 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, + 0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, + 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5, + 0xe7, 0xf1, 0xa2, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, + 0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef, + 0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0xac, + 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5, + 0xc7, 0xd1, 0xa6, 0x2c, 0x25, 0x5f, 0x3e, 0x3f, + 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf, + 0xcc, 0x60, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, + 0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, + 0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, + 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, + 0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, + 0xb5, 0x7e, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, + 0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0xdd, 0xde, 0xae, + 0x5e, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc, + 0xbd, 0xbe, 0x5b, 0x5d, 0xaf, 0xa8, 0xb4, 0xd7, + 0x7b, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, + 0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, + 0x7d, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, + 0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xf9, 0xfa, 0xff, + 0x5c, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0xb3, 0xdb, 0xdc, 0xd9, 0xda, 0x9f, +]; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..ea52d9d --- /dev/null +++ b/src/main.rs @@ -0,0 +1,53 @@ +use structopt::StructOpt; +use std::time::Duration; + +mod tn3270; +mod encoding; + +#[derive(StructOpt)] +pub struct Cli { + #[structopt(short="h", long = "host", default_value="[::1]")] + host: String, + #[structopt(short="p", long = "port", default_value="2101")] + port: u16, + +} + +fn run(mut session: tn3270::Session) -> anyhow::Result<()> { + use tn3270::stream::*; + let mut record = WriteCommand::new(WriteCommandCode::Write, WCC::RESET); + let bufsz = BufferAddressCalculator { width: 80, height: 24 }; + record.set_buffer_address(0) + .erase_unprotected_to_address(bufsz.encode_address(79, 23)) + .set_buffer_address(bufsz.encode_address(31,1)) + .set_attribute(ExtendedFieldAttribute::ForegroundColor(Color::Red)) + .send_text("Hello from Rust!"); + session.send_record(record)?; + + std::thread::sleep(Duration::from_secs(60)); + Ok(()) +} + +fn main() -> anyhow::Result<()> { + let options: Cli = Cli::from_args(); + let server = std::net::TcpListener::bind((options.host.as_str(), options.port))?; + + for client in server.incoming() { + let client = client?; + std::thread::spawn(move || { + let session = match tn3270::Session::new(client) { + Ok(session) => session, + Err(err) => { + eprintln!("Error accepting session: {}", err); + return; + } + }; + + run(session); + + }); + } + println!("Hello, world!"); + + Ok(()) +} diff --git a/src/tn3270.rs b/src/tn3270.rs new file mode 100644 index 0000000..4db9ff8 --- /dev/null +++ b/src/tn3270.rs @@ -0,0 +1,158 @@ +use libtelnet_rs::{ + Parser, + events::*, + telnet::{ + op_option as tn_opt, + op_command as tn_cmd, + } +}; +use std::net::TcpStream; +use libtelnet_rs::telnet::op_option::EOR; +use std::io::{Write, Read}; +use std::time::Duration; + +pub mod stream; + +pub struct Session { + + parser: Parser, + ibuf: Vec, + obuf: Vec, + + stream: std::net::TcpStream, + + term_type: Option>, + is_eor: bool, + is_bin: bool, + cur_record: Vec, +} + +type Error = std::io::Error; + +impl Session { + pub fn new(stream: TcpStream) -> Result { + let mut session = Session { + parser: Parser::new(), + ibuf: Vec::new(), + obuf: Vec::new(), + stream, + term_type: None, + is_bin: false, + is_eor: false, + cur_record: Vec::new(), + }; + + session.parser.options.support(tn_opt::EOR); + session.parser.options.support_remote(tn_opt::TTYPE); + session.parser.options.support(tn_opt::TTYPE); + session.parser.options.support(tn_opt::BINARY); + + eprintln!("Negotiating..."); + session.negotiate()?; + eprintln!("Negotiation complete."); + Ok(session) + } + + fn option_state(&self, opt: u8) -> bool { + let opt = self.parser.options.get_option(opt); + opt.local_state && opt.remote_state + } + + fn process_events(&mut self, mut events: Vec) -> Result>, Error> { + let mut extra_events = Vec::new(); + let mut sendbuf = Vec::new(); + let mut records_in = Vec::new(); + while !events.is_empty() || !extra_events.is_empty() { + events.append(&mut extra_events); + extra_events.truncate(0); + for mut event in events.drain(..) { + match event { + TelnetEvents::DataSend(ref mut data) => sendbuf.append(data), + TelnetEvents::DataReceive(ref mut data) => self.cur_record.append(data), + TelnetEvents::IAC(TelnetIAC { command: tn_cmd::EOR }) => + records_in.push(std::mem::replace(&mut self.cur_record, Vec::new())), + TelnetEvents::IAC(iac) => eprintln!("Unknown IAC {}", iac.command), + TelnetEvents::Negotiation(TelnetNegotiation { command: tn_cmd::WILL, option: tn_opt::TTYPE }) => { + eprintln!("WILL ttype"); + let sub = self.parser.subnegotiation(tn_opt::TTYPE, vec![1]); + if let Some(event) = sub { + eprintln!("Sending subnegotiation"); + extra_events.push(event); + } else { + eprintln!("Didn't do subnegotiation"); + } + + } + TelnetEvents::Negotiation(TelnetNegotiation { command, option }) => { + eprintln!("Negotiate: {}/{}", command, option); + self.is_eor = self.option_state(tn_opt::EOR); + self.is_bin = self.option_state(tn_opt::BINARY); + } + TelnetEvents::Subnegotiation(TelnetSubnegotiation { option: tn_opt::TTYPE, buffer }) => { + if buffer[0] == 0 { + self.term_type = Some(buffer[1..].to_vec()); + + // If the terminal type is correct, we also need to negotiate EOR and BINARY + extra_events.extend( + [ + self.parser._will(tn_opt::EOR), + self.parser._do(tn_opt::EOR), + self.parser._will(tn_opt::BINARY), + self.parser._do(tn_opt::BINARY), + ].iter_mut() + .flat_map(Option::take) + ) + } + } + TelnetEvents::Subnegotiation(_) => {}, + TelnetEvents::DecompressImmediate(_) => unimplemented!("We don't support MCCP"), + } + } + } + + eprintln!("Sending: {:?}", &sendbuf); + self.stream.write(sendbuf.as_slice())?; + Ok(records_in) + } + + fn is_ready(&self) -> bool { + self.term_type.is_some() && self.is_bin && self.is_eor + } + + fn negotiate(&mut self) -> Result { + let mut initial_negotiation = vec![]; + initial_negotiation.extend(self.parser._do(tn_opt::TTYPE)); + initial_negotiation.extend(self.parser._will(tn_opt::TTYPE)); + + self.process_events(initial_negotiation); + + // Large enough for a TCP packet + let mut idata = Vec::with_capacity(2000); + idata.resize(idata.capacity(), 0); + + // Make sure that negotiation completes quickly + self.stream.set_read_timeout(Some(Duration::from_secs(5))); + + while !self.is_ready() { + let len = self.stream.read(&mut idata[..])?; + if len == 0 { + return Ok(false) + } + let events = self.parser.receive(&idata[..len]); + // eprintln!("Received events: {:#?}", &events); + self.process_events(events)?; + } + + Ok(true) + + } + + pub fn send_record(&mut self, record: impl Into>) -> std::io::Result<()> { + + let mut send_data = Parser::escape_iac(record.into()); + send_data.extend_from_slice(&[libtelnet_rs::telnet::op_command::IAC, libtelnet_rs::telnet::op_command::EOR]); + self.stream.write_all(send_data.as_slice()) + } + +} + diff --git a/src/tn3270/stream.rs b/src/tn3270/stream.rs new file mode 100644 index 0000000..f003956 --- /dev/null +++ b/src/tn3270/stream.rs @@ -0,0 +1,340 @@ +use bitflags::bitflags; +use std::io::Write; + +static WCC_TRANS: [u8; 64] = [ + 0x40, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, + 0xC8, 0xC9, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, + 0x50, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, + 0xD8, 0xD9, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, + 0x60, 0x61, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, + 0xE8, 0xE9, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, + 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, + 0xF8, 0xF9, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, +]; + +bitflags! { + pub struct WCC: u8 { + const UNUSED = 0x80; + const RESET = 0x40; + const PRINT_FLAG1 = 0x20; + const PRINT_FLAG2 = 0x10; + const START_PRINTER = 0x08; + const SOUND_ALARM = 0x04; + const KBD_RESTORE = 0x02; + const RESET_MDT = 0x01; + } +} + +bitflags! { + pub struct FieldAttribute: u8 { + const PROTECTED = 0x20; + const NUMERIC = 0x10; + const NON_DISPLAY = 0x0C; + const DISPLAY_SELECTOR_PEN_DETECTABLE = 0x04; + const INTENSE_SELECTOR_PEN_DETECTABLE = 0x08; + const MODIFIED = 0x01; + } +} + +fn make_ascii_translatable(val: u8) -> u8 { + WCC_TRANS[(val & 0x3F) as usize] +} + +impl WCC { + pub fn to_ascii_compat(self) -> u8 { + make_ascii_translatable(self.bits()) + } + + pub fn from_ascii_compat(value: u8) -> Self { + Self::from_bits(value & 0x3F).unwrap() + } +} + +pub trait OutputRecord { + type Response; + + fn write_to(&self, writer: &mut dyn Write) -> std::io::Result<()>; +} + +pub struct WriteCommand { + data: Vec, +} + +#[derive(Copy, Clone, Debug)] +pub enum WriteCommandCode { + Write, + EraseWrite, + EraseWriteAlternate, + EraseAllUnprotected, + WriteStructuredField, +} + +impl WriteCommandCode { + pub fn to_command_code(self) -> u8 { + match self { + WriteCommandCode::Write => 0xF1, + WriteCommandCode::EraseWrite => 0xF5, + WriteCommandCode::EraseWriteAlternate => 0x7E, + WriteCommandCode::EraseAllUnprotected => 0x6F, + WriteCommandCode::WriteStructuredField => 0xF3, + } + } +} + +#[derive(Copy, Clone, Debug, Hash)] +pub enum Color { + Default, + /// Black on displays, white on printers + NeutralBG, + Blue, + Red, + Pink, + Green, + Turquoise, + Yellow, + // White on displays, black on printers + NeutralFG, + Black, + DeepBlue, + Orange, + Purple, + PaleGreen, + PaleTurquoise, + Grey, + White, +} + +impl Into for Color { + fn into(self) -> u8 { + match self { + Color::Default => 0x00, + Color::NeutralBG => 0xF0, + Color::Blue => 0xF1, + Color::Red => 0xF2, + Color::Pink => 0xF3, + Color::Green => 0xF4, + Color::Turquoise => 0xF5, + Color::Yellow => 0xF6, + Color::NeutralFG => 0xF7, + Color::Black => 0xF8, + Color::DeepBlue => 0xF9, + Color::Orange => 0xFA, + Color::Purple => 0xFB, + Color::PaleGreen => 0xFC, + Color::PaleTurquoise => 0xFD, + Color::Grey => 0xFE, + Color::White => 0xFF, + } + } +} + +#[derive(Copy, Clone, Debug, Hash)] +pub enum Highlighting { + Default, + Normal, + Blink, + Reverse, + Underscore, +} + +impl Into for Highlighting { + fn into(self) -> u8 { + match self { + Highlighting::Default => 0x00, + Highlighting::Normal => 0xF0, + Highlighting::Blink => 0xF1, + Highlighting::Reverse => 0xF2, + Highlighting::Underscore => 0xF4, + } + } +} + +bitflags! { + pub struct FieldOutline: u8 { + const NO_OUTLINE = 0; + const UNDERLINE = 0b0001; + const RIGHT = 0b0010; + const OVERLINE = 0b0100; + const LEFT = 0b1000; + } +} + +#[derive(Copy, Clone, Debug, Hash)] +enum Transparency { + Default, + Or, + Xor, + Opaque, +} + +impl Into for Transparency { + fn into(self) -> u8 { + match self { + Transparency::Default => 0x00, + Transparency::Or => 0xF0, + Transparency::Xor => 0xF1, + Transparency::Opaque => 0xF2, + } + } +} + +bitflags! { + pub struct FieldValidation: u8 { + const MANDATORY_FILL = 0b100; + const MANDATORY_ENTRY = 0b010; + const TRIGGER = 0b001; + } +} + +#[derive(Copy, Clone, Debug, Hash)] +pub enum ExtendedFieldAttribute { + AllAttributes, + ExtendedHighlighting(Highlighting), + ForegroundColor(Color), + CharacterSet(u8), + BackgroundColor(Color), + Transparency(Transparency), + FieldAttribute(FieldAttribute), + FieldValidation(FieldValidation), + FieldOutlining(FieldOutline), + +} + +impl ExtendedFieldAttribute { + pub fn encoded(self) -> (u8, u8) { + match self { + ExtendedFieldAttribute::AllAttributes => (0x00,0x00), + ExtendedFieldAttribute::FieldAttribute(fa) => (0xC0, make_ascii_translatable(fa.bits)), + ExtendedFieldAttribute::ExtendedHighlighting(fa) => (0x41, fa.into()), + ExtendedFieldAttribute::BackgroundColor(c) => (0x45, c.into()), + ExtendedFieldAttribute::ForegroundColor(c) => (0x42, c.into()), + ExtendedFieldAttribute::CharacterSet(cs) => (0x43, cs.into()), + ExtendedFieldAttribute::FieldOutlining(fo) => (0xC2, fo.bits()), + ExtendedFieldAttribute::Transparency(v) => (0x46, v.into()), + ExtendedFieldAttribute::FieldValidation(v) => (0xC1, v.bits()), + } + } +} + +#[derive(Copy, Clone, Debug)] +pub struct BufferAddressCalculator { + pub width: u16, + pub height: u16, +} + +impl BufferAddressCalculator { + pub fn encode_address(self, x: u16, y: u16) -> u16 { + self.width * y + x + } +} + +impl WriteCommand { + pub fn new(command: WriteCommandCode, wcc: WCC) -> Self { + WriteCommand { + data: vec![command.to_command_code(), wcc.to_ascii_compat(), ] + } + } + + pub fn start_field(&mut self, fa: FieldAttribute) -> &mut Self { + self.data.push(0x1D); + self.data.push(fa.bits()); + self + } + + pub fn start_field_extended(&mut self, fa: FieldAttribute, attrs: impl IntoIterator) -> &mut Self { + self.data.push(0x29); + let nattr_pos = self.data.len(); + self.data.push(0); + let mut i = 1; + self.data.push(0xC0); + self.data.push(make_ascii_translatable(fa.bits())); + + for (typ, value) in attrs.into_iter().map(ExtendedFieldAttribute::encoded) { + self.data.push(typ); + self.data.push(value); + i += 1; + } + self.data[nattr_pos] = i; + self + } + + pub fn set_buffer_address(&mut self, address: u16) -> &mut Self { + self.data.push(0x11); + self.data.push((address >> 8) as u8); + self.data.push((address & 0xFF) as u8); + return self; + } + + pub fn set_attribute(&mut self, attr: ExtendedFieldAttribute) -> &mut Self { + let (typ, val) = attr.encoded(); + self.data.extend_from_slice(&[0x28, typ, val]); + self + } + + pub fn modify_field(&mut self, attrs: impl IntoIterator) -> &mut Self { + self.data.push(0x2C); + let nattr_pos = self.data.len(); + self.data.push(0); + let mut i = 0; + for (typ, value) in attrs.into_iter().map(ExtendedFieldAttribute::encoded) { + self.data.push(typ); + self.data.push(value); + i += 1; + } + self.data[nattr_pos] = i; + self + } + + fn encode_address(&mut self, address: u16) { + self.data.push((address >> 8) as u8); + self.data.push((address & 0xFF) as u8); + + } + + pub fn insert_cursor(&mut self, address: u16) -> &mut Self { + self.data.push(0x13); + self.encode_address(address); + return self; + } + + pub fn program_tab(&mut self) -> &mut Self { + self.data.push(0x05); + self + } + + // This must be followed by either a character or a graphic escape + pub fn repeat_to_address(&mut self, address: u16) -> &mut Self { + self.data.push(0x3C); + self.encode_address(address); + self + } + + pub fn erase_unprotected_to_address(&mut self, address: u16) -> &mut Self { + self.data.push(0x12); + self.encode_address(address); + self + } + + pub fn graphic_escape(&mut self, charcode: u8) -> &mut Self { + self.data.push(0x08); + self.data.push(charcode); + self + } + + pub fn send_text(&mut self, data: &str) -> &mut Self { + self.data.extend(crate::encoding::to_cp037(data.chars())); + self + } +} + +impl AsRef<[u8]> for WriteCommand { + fn as_ref(&self) -> &[u8] { + self.data.as_slice() + } +} + +impl Into> for WriteCommand { + fn into(self) -> Vec { + self.data + } +} \ No newline at end of file