Wrote b3270 arbiter

This commit is contained in:
2023-05-11 01:24:11 +02:00
parent 2b180d9a95
commit d8356ecb6c
15 changed files with 599 additions and 176 deletions

16
d3270-common/Cargo.toml Normal file
View File

@@ -0,0 +1,16 @@
[package]
name = "d3270-common"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = { version = "1.0.162", features = ["derive"]}
serde_json = "1.0.96"
#serde_cbor = "0.11.2"
anyhow = "1.0.71"
bitflags = "2.2.1"
# deps for bins
#structopt = "0.3.26"

120
d3270-common/src/b3270.rs Normal file
View File

@@ -0,0 +1,120 @@
use serde::{Deserialize, Serialize};
use indication::{CodePage, ConnectAttempt, Connection, Erase, FileTransfer, Hello, Model, Oia, Passthru, Popup, Proxy, RunResult, Screen, ScreenMode, Scroll, Setting, Stats, TerminalName, Thumb, Tls, TlsHello, TraceFile, UiError};
use operation::{Fail, Register, Run, Succeed};
pub mod operation;
pub mod indication;
pub mod types;
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub enum Indication {
Bell{}, // TODO: make sure this emits/parses {"bell": {}}
/// Indicates that the host connection has changed state.
Connection(Connection),
/// A new host connection is being attempted
ConnectAttempt(ConnectAttempt),
/// Indicates the screen size
Erase(Erase),
/// Display switch between LTR and RTL
Flipped {
/// True if display is now in RTL mode
value: bool,
},
/// An xterm escape sequence requested a new font
Font {
text: String,
},
/// The formatting state of the screen has changed.
/// A formatted string has at least one field displayed.
Formatted {
state: bool,
},
/// File transfer state change
#[serde(rename="ft")]
FileTransfer(FileTransfer),
/// An XTerm escape sequence requested a new icon name
Icon{
text: String,
},
/// The first message sent
Initialize(Vec<InitializeIndication>),
/// Change in the state of the Operator Information Area
Oia(Oia),
/// A passthru action has been invoked.
/// Clients must respond with a succeed or fail operation
Passthru(Passthru),
/// Display an asynchronous message
Popup(Popup),
/// Result of a run operation
RunResult(RunResult),
/// Change to screen contents
Screen(Screen),
/// Screen dimensions/characteristics changed
ScreenMode(ScreenMode),
/// Screen was scrolled up by one row
Scroll(Scroll),
/// Setting changed
Setting(Setting),
/// I/O statistics
Stats(Stats),
/// Reports the terminal name sent to the host during TELNET negotiation
TerminalName(TerminalName),
/// Change in the scrollbar thumb
Thumb(Thumb),
/// Indicates the name of the trace file
TraceFile(TraceFile),
/// TLS state changed
Tls(Tls),
/// Error in b3270's input
UiError(UiError),
/// Xterm escape sequence requested a change to the window title
WindowTitle{
text: String,
}
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename_all="kebab-case")]
pub enum InitializeIndication {
CodePages(Vec<CodePage>),
/// Indicates that the host connection has changed state.
Connection(Connection),
/// Indicates the screen size
Erase(Erase),
/// The first element in the initialize array
Hello(Hello),
/// Indicates which 3270 models are supported
Models(Vec<Model>),
/// Change in the state of the Operator Information Area
Oia(Oia),
/// Set of supported prefixes
Prefixes{value: String},
/// List of supported proxies
Proxies(Vec<Proxy>),
/// Screen dimensions/characteristics changed
ScreenMode(ScreenMode),
/// Setting changed
Setting(Setting),
/// Scroll thumb position
Thumb(Thumb),
/// Indicates build-time TLS config
TlsHello(TlsHello),
/// TLS state changed
Tls(Tls),
/// Trace file
TraceFile(TraceFile),
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename_all="kebab-case")]
pub enum Operation {
/// Run an action
Run(Run),
/// Register a pass-thru action
Register(Register),
/// Tell b3270 that a passthru action failed
Fail(Fail),
/// Tell b3270 that a passthru action succeeded
Succeed(Succeed),
}

View File

@@ -0,0 +1,439 @@
use serde::{Deserialize, Serialize};
use crate::b3270::types::{Color, GraphicRendition};
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
#[serde(rename_all="kebab-case")]
pub enum ActionCause {
Command,
Default,
FileTransfer,
Httpd,
Idle,
Keymap,
Macro,
None,
Password,
Paste,
Peek,
ScreenRedraw,
Script,
Typeahead,
Ui,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct CodePage{
/// The canonical name of the code page
pub name: String,
#[serde(default, skip_serializing_if="Vec::is_empty")]
pub aliases: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Connection{
/// New connection state
pub state: ConnectionState,
/// Host name, if connected
#[serde(default, skip_serializing_if="Option::is_none")]
pub host: Option<String>,
/// Source of the connection
#[serde(default, skip_serializing_if="Option::is_none")]
pub cause: Option<ActionCause>,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all="kebab-case")]
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum ComposeType {
Std,
Ge,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all="kebab-case")]
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum ConnectionState {
NotConnected,
Reconnecting,
Resolving,
TcpPending,
TlsPending,
TelnetPending,
ConnectedNvt,
ConnectedNvtCharmode,
Connected3270,
ConnectedUnbound,
ConnectedENvt,
ConnectedESscp,
#[serde(rename="connected-e-tn3270e")]
ConnectedETn3270e,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Copy)]
#[serde(rename_all="kebab-case")]
pub struct Erase {
#[serde(default, skip_serializing_if="Option::is_none")]
pub logical_rows: Option<u8>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub logical_cols: Option<u8>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub fg: Option<Color>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub bg: Option<Color>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Hello {
pub version: String,
pub build: String,
pub copyright: String,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Model {
pub model: u8,
pub rows: u8,
pub columns: u8,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
// This could be more typesafe, probably ¯\_(ツ)_/¯
pub struct Oia {
#[serde(flatten)]
pub field: OiaField,
#[serde(default, skip_serializing_if="Option::is_none")]
pub lu: Option<String>,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all="kebab-case", tag="field")]
#[derive(Debug, PartialEq, Clone)]
pub enum OiaField {
/// Composite character in progress
Compose{
value: bool,
#[serde(default, skip_serializing_if="Option::is_none")]
char: Option<String>,
#[serde(default, skip_serializing_if="Option::is_none")]
type_: Option<ComposeType>,
},
/// Insert mode
Insert{value: bool},
/// Keyboard is locked
Lock{
#[serde(default, skip_serializing_if="Option::is_none")]
value: Option<String>
},
Lu{
/// Host session logical unit name
value: String,
/// Printer session LU name
#[serde(default, skip_serializing_if="Option::is_none")]
lu: Option<String>,
},
/// Communication pending
NotUndera {
value: bool,
},
PrinterSession {
value: bool,
/// Printer session LU name
// TODO: determine if this is sent with this message or with Lu
#[serde(default, skip_serializing_if="Option::is_none")]
lu: Option<String>,
},
/// Reverse input mode
ReverseInput {
value: bool,
},
/// Screen trace count
ScreenTrace {
value: String,
},
/// Host command timer (minutes:seconds)
Script {
value: String,
},
Timing {
#[serde(default, skip_serializing_if="Option::is_none")]
value: Option<String>,
},
Typeahead {
value: bool,
},
}
#[derive(Copy, Clone, Debug, Eq, Ord, PartialOrd, PartialEq, Hash)]
pub enum OiaFieldName {
Compose,
Insert,
Lock,
Lu,
NotUndera,
PrinterSession,
ReverseInput,
ScreenTrace,
Script,
Timing,
Typeahead,
}
impl OiaField {
pub fn field_name(&self) -> OiaFieldName {
match self {
OiaField::Compose {..} => OiaFieldName::Compose,
OiaField::Insert {..} => OiaFieldName::Insert,
OiaField::Lock {..} => OiaFieldName::Lock,
OiaField::Lu {..} => OiaFieldName::Lu,
OiaField::NotUndera {..} => OiaFieldName::NotUndera,
OiaField::PrinterSession {..} => OiaFieldName::PrinterSession,
OiaField::ReverseInput {..} => OiaFieldName::ReverseInput,
OiaField::ScreenTrace {..} => OiaFieldName::ScreenTrace,
OiaField::Script {..} => OiaFieldName::Script,
OiaField::Timing {..} => OiaFieldName::Timing,
OiaField::Typeahead {..} => OiaFieldName::Typeahead,
}
}
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Proxy {
pub name: String,
pub username: String,
pub port: u16,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Setting {
pub name: String,
/// I'd love something other than depending on serde_json for this.
pub value: Option<serde_json::Value>,
pub cause: ActionCause,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
pub struct ScreenMode {
pub model: u8,
pub rows: u8,
pub cols: u8,
pub color: bool,
pub oversize: bool,
pub extended: bool,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct TlsHello {
pub supported: bool,
pub provider: String, // docs claim this is always set, but I'm not sure.
#[serde(default, skip_serializing_if="Vec::is_empty")]
pub options: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename_all="kebab-case")]
pub struct Tls {
pub secure: bool,
#[serde(default, skip_serializing_if="Option::is_none")]
pub verified: Option<bool>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub session: Option<String>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub host_cert: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename_all="kebab-case")]
pub struct ConnectAttempt {
pub host_ip: String,
pub port: String,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Copy)]
// TODO: change this to an enum
pub struct Cursor {
pub enabled: bool,
#[serde(default, skip_serializing_if="Option::is_none")]
pub row: Option<u8>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub column: Option<u8>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct FileTransfer {
#[serde(flatten)]
pub state: FileTransferState,
pub cause: ActionCause,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename_all="lowercase", tag="state")]
pub enum FileTransferState {
Awaiting,
Running{
/// Number of bytes transferred
bytes: usize
},
Aborting,
Complete{
/// Completion message
text: String,
/// Transfer succeeded
success: bool,
},
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename="kebab-case")]
pub struct Passthru {
pub p_tag: String,
#[serde(default, skip_serializing_if="Option::is_none")]
pub parent_r_tag: Option<String>,
pub action: String,
#[serde(default, skip_serializing_if="Vec::is_empty")]
pub args: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Popup {
#[serde(rename="type")]
pub type_: PopupType,
pub text: String,
#[serde(default, skip_serializing_if="Option::is_none")]
pub error: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
#[serde(rename="kebab-case")]
pub enum PopupType {
/// Error message from a connection attempt
ConnectError,
/// Error message
Error,
/// Informational message
Info,
/// Stray action output (should not happen)
Result,
/// Output from the pr3287 process
Printer,
/// Output from other child process
Child,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename="kebab-case")]
pub struct Row {
pub row: u8,
pub changes: Vec<Change>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename="kebab-case")]
pub enum CountOrText {
Count(usize),
Text(String),
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Change {
pub column: u8,
#[serde(flatten)]
pub change: CountOrText,
#[serde(default, skip_serializing_if="Option::is_none")]
pub fg: Option<Color>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub bg: Option<Color>,
#[serde(default, skip_serializing_if="Option::is_none")]
/// Graphic rendition
pub gr: Option<GraphicRendition>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Screen {
#[serde(default, skip_serializing_if="Option::is_none")]
pub cursor: Option<Cursor>,
#[serde(default, skip_serializing_if="Vec::is_empty")]
pub rows: Vec<Row>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename="kebab-case")]
pub struct RunResult {
#[serde(default, skip_serializing_if="Option::is_none")]
pub r_tag: Option<String>,
pub success: bool,
#[serde(default, skip_serializing_if="Vec::is_empty")]
pub text: Vec<String>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub abort: Option<bool>,
/// Execution time in seconds
pub time: f32,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename="kebab-case")]
pub struct Scroll {
#[serde(default, skip_serializing_if="Option::is_none")]
pub fg: Option<Color>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub bg: Option<Color>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename="kebab-case")]
pub struct Stats {
pub bytes_received: usize,
pub bytes_sent: usize,
pub records_received: usize,
pub records_sent: usize,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct TerminalName {
pub text: String,
#[serde(rename="override")]
pub override_: bool,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
pub struct Thumb {
/// Fraction of scrollbar to top of thumb
pub top: f32,
/// Fraction of scrollbar for thumb display
pub shown: f32,
/// Number of rows saved
pub saved: usize,
/// Size of a screen in rows
pub screen: usize,
/// Number of rows scrolled back
pub back: usize,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct TraceFile {
#[serde(default, skip_serializing_if="Option::is_none")]
pub name: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct UiError {
pub fatal: bool,
pub text: String,
#[serde(default, skip_serializing_if="Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub member: Option<String>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub line: Option<usize>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub column: Option<usize>,
}
#[cfg(test)]
mod test {
use super::*;
#[test]
pub fn connection_state_serializes_as_expected() {
assert_eq!(serde_json::to_string(&ConnectionState::ConnectedETn3270e).unwrap(),r#""connected-e-tn3270e""#);
assert_eq!(serde_json::to_string(&ConnectionState::ConnectedESscp).unwrap(),r#""connected-e-sscp""#);
}
}

View File

@@ -0,0 +1,48 @@
use serde::{Deserialize, Serialize};
// {"run":{"actions":[{"action":"Connect","args":["10.24.74.37:3270"]}]}}
// {"run":{"actions":"Key(a)"}}
// Operations
#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Clone)]
#[serde(rename_all="kebab-case")]
pub struct Run {
#[serde(default, skip_serializing_if="Option::is_none")]
pub r_tag: Option<String>,
#[serde(rename="type", default, skip_serializing_if="Option::is_none")]
pub type_: Option<String>,
pub actions: Vec<Action>,
}
#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Clone)]
#[serde(rename_all="kebab-case")]
pub struct Action {
pub action: String,
#[serde(default, skip_serializing_if="Vec::is_empty")]
pub args: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Clone)]
#[serde(rename_all="kebab-case")]
pub struct Register {
pub name: String,
#[serde(default, skip_serializing_if="Option::is_none")]
pub help_text: Option<String>,
#[serde(default, skip_serializing_if="Option::is_none")]
pub help_params: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Clone)]
/// Completes a passthru action unsuccessfully
#[serde(rename_all="kebab-case")]
pub struct Fail {
pub p_tag: String,
pub text: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Clone)]
#[serde(rename_all="kebab-case")]
pub struct Succeed {
pub p_tag: String,
#[serde(default, skip_serializing_if="Vec::is_empty")]
pub text: Vec<String>,
}

View File

@@ -0,0 +1,228 @@
use std::fmt::{Display, Formatter, Write};
use std::str::FromStr;
use bitflags::bitflags;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde::de::{Error, Visitor};
bitflags! {
#[derive(Clone,Copy,Debug,PartialEq, Eq, Hash)]
pub struct GraphicRendition: u16 {
const UNDERLINE = 0x001;
const BLINK = 0x002;
const HIGHLIGHT = 0x004;
const SELECTABLE = 0x008;
const REVERSE = 0x010;
const WIDE = 0x020;
const ORDER = 0x040;
const PRIVATE_USE = 0x080;
const NO_COPY = 0x100;
const WRAP = 0x200;
}
}
static FLAG_NAMES: &'static [(GraphicRendition, &'static str)] = &[
(GraphicRendition::UNDERLINE, "underline"),
(GraphicRendition::BLINK, "blink"),
(GraphicRendition::HIGHLIGHT, "highlight"),
(GraphicRendition::SELECTABLE, "selectable"),
(GraphicRendition::REVERSE, "reverse"),
(GraphicRendition::WIDE, "wide"),
(GraphicRendition::ORDER, "order"),
(GraphicRendition::PRIVATE_USE, "private-use"),
(GraphicRendition::NO_COPY, "no-copy"),
(GraphicRendition::WRAP, "wrap"),
];
impl Display for GraphicRendition {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let flag_names = FLAG_NAMES.iter()
.filter_map(|(val, name)| self.contains(*val).then_some(*name));
for (n, name) in flag_names.enumerate() {
if n != 0 {
f.write_char(',')?;
}
f.write_str(name)?;
}
Ok(())
}
}
impl Serialize for GraphicRendition {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
if serializer.is_human_readable() {
serializer.serialize_str(&self.to_string())
} else {
serializer.serialize_u16(self.bits())
}
}
}
struct GrVisitor;
impl Visitor<'_> for GrVisitor {
type Value = GraphicRendition;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
write!(formatter, "graphic rendition string or binary value")
}
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: Error {
self.visit_u64((v & 0xFFFF) as u64)
}
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: Error {
Ok(GraphicRendition::from_bits_truncate((v & 0xFFFF) as u16))
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: Error {
GraphicRendition::from_str(v).map_err(E::custom)
}
}
impl FromStr for GraphicRendition {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.split(",")
.map(|attr| {
FLAG_NAMES.iter()
.find(|(_, name)| *name == attr)
.map(|x| x.0)
.ok_or_else(|| format!("Invalid attr name {attr}"))
})
.collect()
}
}
impl<'de> Deserialize<'de> for GraphicRendition {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
if deserializer.is_human_readable() {
deserializer.deserialize_str(GrVisitor)
} else {
deserializer.deserialize_u16(GrVisitor)
}
}
}
#[cfg(test)]
mod test {
use std::str::FromStr;
use super::GraphicRendition;
#[test]
fn from_str_1() {
assert_eq!(GraphicRendition::from_str("underline,blink"), Ok(GraphicRendition::BLINK | GraphicRendition::UNDERLINE))
}
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
#[serde(rename="camelCase")]
#[repr(u8)]
pub enum Color {
NeutralBlack,
Blue,
Red,
Pink,
Green,
Turquoise,
Yellow,
NeutralWhite,
Black,
DeepBlue,
Orange,
Purple,
PaleGreen,
PaleTurquoise,
Gray,
White,
}
impl From<Color> for u8 {
fn from(value: Color) -> Self {
use Color::*;
match value {
NeutralBlack => 0,
Blue => 1,
Red => 2,
Pink => 3,
Green => 4,
Turquoise => 5,
Yellow => 6,
NeutralWhite => 7,
Black => 8,
DeepBlue => 9,
Orange => 10,
Purple => 11,
PaleGreen => 12,
PaleTurquoise => 13,
Gray => 14,
White => 15,
}
}
}
impl From<u8> for Color {
fn from(value: u8) -> Self {
use Color::*;
match value & 0xF {
0 => NeutralBlack,
1 => Blue,
2 => Red,
3 => Pink,
4 => Green,
5 => Turquoise,
6 => Yellow,
7 => NeutralWhite,
8 => Black,
9 => DeepBlue,
10 => Orange,
11 => Purple,
12 => PaleGreen,
13 => PaleTurquoise,
14 => Gray,
15 => White,
_ => unreachable!(),
}
}
}
pub trait PackedAttr {
fn c_gr(self) -> GraphicRendition;
fn c_fg(self) -> Color;
fn c_bg(self) -> Color;
fn c_setgr(self, gr: GraphicRendition) -> Self;
fn c_setfg(self, fg: Color) -> Self;
fn c_setbg(self, bg: Color) -> Self;
fn c_pack(fg: Color, bg: Color, gr: GraphicRendition) -> Self;
}
impl PackedAttr for u32 {
fn c_gr(self) -> GraphicRendition {
GraphicRendition::from_bits_truncate((self & 0xFFFF) as u16)
}
fn c_fg(self) -> Color {
((self >> 16 & 0xF) as u8).into()
}
fn c_bg(self) -> Color {
((self >> 20 & 0xF) as u8).into()
}
fn c_setgr(self, gr: GraphicRendition) -> Self {
self & !0xFFFF | gr.bits() as u32
}
fn c_setfg(self, fg: Color) -> Self {
self & !0xF0000 | (u8::from(fg) as u32) << 16
}
fn c_setbg(self, bg: Color) -> Self {
self & !0xF0000 | (u8::from(bg) as u32) << 20
}
fn c_pack(fg: Color, bg: Color, gr: GraphicRendition) -> Self {
0.c_setfg(fg).c_setbg(bg).c_setgr(gr)
}
}

View File

4
d3270-common/src/lib.rs Normal file
View File

@@ -0,0 +1,4 @@
pub mod b3270;
pub mod tracker;
pub mod executor;

View File

331
d3270-common/src/tracker.rs Normal file
View File

@@ -0,0 +1,331 @@
use std::collections::HashMap;
use crate::b3270::indication::{Change, Connection, ConnectionState, CountOrText, Cursor, Erase, Oia, OiaFieldName, Row, RunResult, Screen, ScreenMode, Scroll, Setting, TerminalName, Thumb, Tls, TraceFile};
use crate::b3270::{Indication, InitializeIndication};
use crate::b3270::types::{Color, GraphicRendition, PackedAttr};
#[derive(Copy, Clone, Debug)]
struct CharCell {
pub ch: char,
pub attr: u32,
}
pub struct Tracker {
screen: Vec<Vec<CharCell>>,
oia: HashMap<OiaFieldName, Oia>,
screen_mode: ScreenMode,
erase: Erase,
thumb: Thumb,
settings: HashMap<String, Setting>,
// These are not init indications, but need to be tracked anyways
cursor: Cursor,
connection: Connection,
formatted: bool,
terminal_name: Option<TerminalName>,
trace_file: Option<String>,
tls: Option<Tls>,
// These never change, but need to be represented in an initialize message
static_init: Vec<InitializeIndication>,
}
#[derive(Clone, Debug)]
pub enum Disposition {
// Deliver this indication to every connected client
Broadcast,
// Ignore this message
Drop,
// Send this message to one particular client
Direct(String),
}
impl Tracker {
pub fn handle_indication(&mut self, indication: &mut Indication) -> Disposition {
match indication {
Indication::Bell { .. }
| Indication::ConnectAttempt(_)
| Indication::Flipped { .. }
| Indication::Font { .. }
| Indication::Icon { .. }
| Indication::Popup(_)
| Indication::Stats(_)
| Indication::WindowTitle { .. }
=> (),
Indication::Connection(conn) => {
self.connection = conn.clone();
}
Indication::Erase(erase) => {
self.erase.logical_cols = erase.logical_cols.or(self.erase.logical_cols);
self.erase.logical_rows = erase.logical_rows.or(self.erase.logical_rows);
self.erase.fg = erase.fg.or(self.erase.fg);
self.erase.bg = erase.bg.or(self.erase.bg);
let rows = self.erase.logical_rows.unwrap_or(self.screen_mode.rows) as usize;
let cols = self.erase.logical_cols.unwrap_or(self.screen_mode.cols) as usize;
self.screen = vec![
vec![CharCell{
attr: u32::c_pack(
erase.fg.unwrap_or(Color::NeutralBlack),
erase.bg.unwrap_or(Color::Blue),
GraphicRendition::empty(),
),
ch: ' ',
};cols]
; rows
]
}
Indication::Formatted { state } => {self.formatted = *state; }
Indication::Initialize(init) => {
let mut static_init = Vec::with_capacity(init.len());
for indicator in init.clone() {
match indicator {
InitializeIndication::CodePages(_) |
InitializeIndication::Hello(_) |
InitializeIndication::Models(_) |
InitializeIndication::Prefixes { .. } |
InitializeIndication::Proxies(_) |
InitializeIndication::TlsHello(_) |
InitializeIndication::Tls(_) |
InitializeIndication::TraceFile(_) =>
static_init.push(indicator),
// The rest are passed through to normal processing.
InitializeIndication::Thumb(thumb) => {
self.handle_indication(&mut Indication::Thumb(thumb));
},
InitializeIndication::Setting(setting) => {
self.handle_indication(&mut Indication::Setting(setting));
}
InitializeIndication::ScreenMode(mode) => {
self.handle_indication(&mut Indication::ScreenMode(mode));
},
InitializeIndication::Oia(oia) => {
self.handle_indication(&mut Indication::Oia(oia));
}
InitializeIndication::Erase(erase) => {
self.handle_indication(&mut Indication::Erase(erase));
}
InitializeIndication::Connection(conn) => {
self.handle_indication(&mut Indication::Connection(conn));
}
}
}
}
Indication::Oia(oia) => {
self.oia.insert(oia.field.field_name(), oia.clone());
}
Indication::Screen(screen) => {
if let Some(cursor) = screen.cursor {
self.cursor = cursor;
}
for row in screen.rows.iter() {
let row_idx = row.row as usize - 1;
for change in row.changes.iter() {
let col_idx = change.column as usize - 1;
// update screen contents
let cols = self.screen[row_idx].iter_mut().skip(col_idx);
match change.change {
CountOrText::Count(n) => {
cols.take(n).for_each(|cell| {
let mut attr = cell.attr;
if let Some(fg) = change.fg {
attr = attr.c_setfg(fg);
}
if let Some(bg) = change.bg {
attr = attr.c_setbg(bg);
}
if let Some(gr) = change.gr {
attr = attr.c_setgr(gr);
}
cell.attr = attr;
})
}
CountOrText::Text(ref text) => {
cols.zip(text.chars()).for_each(|(cell, ch)| {
let mut attr = cell.attr;
if let Some(fg) = change.fg {
attr = attr.c_setfg(fg);
}
if let Some(bg) = change.bg {
attr = attr.c_setbg(bg);
}
if let Some(gr) = change.gr {
attr = attr.c_setgr(gr);
}
cell.attr = attr;
cell.ch = ch;
});
}
}
}
}
}
Indication::ScreenMode(mode) => {
self.screen_mode = *mode;
self.handle_indication(&mut Indication::Erase(Erase{
logical_rows: Some(self.screen_mode.rows),
logical_cols: Some(self.screen_mode.cols),
fg: None,
bg: None,
}));
}
Indication::Scroll(Scroll{ fg, bg }) => {
let fg = fg.or(self.erase.fg).unwrap_or(Color::Blue);
let bg = bg.or(self.erase.bg).unwrap_or(Color::NeutralBlack);
let mut row = self.screen.remove(0);
row.fill(CharCell{
attr: u32::c_pack(fg, bg, GraphicRendition::empty()),
ch: ' ',
});
self.screen.push(row);
}
Indication::Setting(setting) => {
self.settings.insert(setting.name.clone(), setting.clone());
}
Indication::TerminalName(term) => {
self.terminal_name = Some(term.clone());
}
Indication::Thumb(thumb) => {
self.thumb = thumb.clone();
}
Indication::TraceFile(TraceFile{name}) => {
self.trace_file = name.clone();
}
Indication::Tls(tls) => {
self.tls = Some(tls.clone());
}
// These need direction
Indication::UiError(_) => {} // we can assume that this came from the last sent command
Indication::Passthru(_) => {} // dunno how to handle this one
Indication::FileTransfer(_) => {}
Indication::RunResult(RunResult{r_tag, ..}) => {
if let Some(dest) = r_tag {
return Disposition::Direct(dest.clone());
} else {
return Disposition::Drop;
}
}
}
return Disposition::Broadcast
}
pub fn get_init_indication(&self) -> Vec<Indication> {
let mut contents = self.static_init.clone();
contents.push(InitializeIndication::ScreenMode(self.screen_mode));
contents.push(InitializeIndication::Erase(self.erase));
contents.push(InitializeIndication::Thumb(self.thumb));
contents.extend(self.oia.values()
.cloned()
.map(InitializeIndication::Oia));
contents.extend(self.settings.values()
.cloned()
.map(InitializeIndication::Setting));
contents.extend(self.tls.clone().map(InitializeIndication::Tls));
// Construct a screen snapshot
let mut result = vec![
Indication::Initialize(contents),
Indication::Connection(self.connection.clone()),
Indication::Screen(self.screen_snapshot()),
Indication::Formatted {state: self.formatted},
];
if let Some(terminal_name) = self.terminal_name.clone() {
result.push(Indication::TerminalName(terminal_name));
}
if let Some(trace_file) = self.trace_file.clone() {
result.push(Indication::TraceFile(TraceFile {
name: Some(trace_file),
}))
}
result
}
fn format_row(mut row: &[CharCell]) -> Vec<Change> {
let mut result = vec![];
let mut column = 1;
while !row.is_empty() {
let cur_gr = row[0].attr;
let split_pt = row.iter().take_while(|ch| ch.attr == cur_gr).count();
let (first, rest) = row.split_at(split_pt);
row = rest;
let content = first.iter().map(|cell| cell.ch).collect();
result.push(Change{
column,
fg: Some(cur_gr.c_fg()),
bg: Some(cur_gr.c_bg()),
gr: Some(cur_gr.c_gr()),
change: CountOrText::Text(content),
});
column += first.len() as u8;
}
result
}
fn screen_snapshot(&self) -> Screen {
Screen{
cursor: Some(self.cursor),
rows: self.screen.iter()
.map(Vec::as_slice).map(Self::format_row)
.enumerate()
.map(|(row_id, changes)| Row{
row: row_id as u8 - 1,
changes,
})
.collect()
}
}
}
impl Default for Tracker {
fn default() -> Self {
let ret = Self {
screen: vec![],
oia: Default::default(),
screen_mode: ScreenMode {
cols: 80,
rows: 43,
color: true,
model: 4,
extended: true,
oversize: false,
},
erase: Erase {
logical_rows: None,
logical_cols: None,
fg: None,
bg: None,
},
thumb: Thumb {
top: 0.0,
shown: 0.0,
saved: 0,
screen: 0,
back: 0,
},
settings: Default::default(),
cursor: Cursor {
enabled: false,
row: None,
column: None
},
connection: Connection {
state: ConnectionState::NotConnected,
host: None,
cause: None,
},
formatted: false,
terminal_name: None,
trace_file: None,
tls: None,
static_init: vec![],
};
ret
}
}