#![forbid(unsafe_code)]
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;
use std::collections::BTreeMap;
use std::io::{self, Read, Write};
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use serde::{Deserialize, Serialize};
pub const API_VERSION: u32 = 2;
pub const MAX_MESSAGE: usize = 256 * 1024;
pub const SOCKET_IN_RUNTIME_DIR: &str = "smed/api.sock";
pub fn default_socket_path() -> Option<PathBuf> {
let dir = std::env::var_os("XDG_RUNTIME_DIR").filter(|dir| !dir.is_empty())?;
Some(PathBuf::from(dir).join(SOCKET_IN_RUNTIME_DIR))
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DeviceInfo {
pub vid: u16,
pub pid: u16,
pub name: String,
pub firmware: Option<String>,
}
impl DeviceInfo {
pub fn new(vid: u16, pid: u16, name: impl Into<String>, firmware: Option<String>) -> Self {
Self {
vid,
pid,
name: name.into(),
firmware,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Press {
Short,
Long,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TextSize {
#[default]
Small,
Large,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Theme {
#[default]
Light,
Dark,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct App {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
}
impl App {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
icon: None,
}
}
pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
self.icon = Some(icon.into());
self
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Command {
pub id: String,
pub label: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
}
impl Command {
pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
Self {
id: id.into(),
label: label.into(),
icon: None,
}
}
pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
self.icon = Some(icon.into());
self
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Environment {
pub id: String,
pub name: String,
#[serde(default)]
pub keys: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub long_keys: BTreeMap<String, String>,
}
impl Environment {
pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
Self {
id: id.into(),
name: name.into(),
keys: BTreeMap::new(),
long_keys: BTreeMap::new(),
}
}
pub fn with_key(mut self, key: impl Into<String>, command: impl Into<String>) -> Self {
self.keys.insert(key.into(), command.into());
self
}
pub fn with_long_key(mut self, key: impl Into<String>, command: impl Into<String>) -> Self {
self.long_keys.insert(key.into(), command.into());
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ServerMessage {
Hello {
api: u32,
server: String,
},
State {
device: Option<DeviceInfo>,
lock: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
lcd: Option<bool>,
},
Device {
device: Option<DeviceInfo>,
},
Motion {
t: [i16; 3],
r: [i16; 3],
},
Key {
key: String,
id: u8,
press: Press,
down: bool,
},
Lock {
on: bool,
},
Lcd {
owner: bool,
brightness: u8,
text_size: TextSize,
theme: Theme,
},
Command {
id: String,
env: String,
key: String,
press: Press,
},
Screen {
png: String,
},
Error {
message: String,
},
#[serde(other)]
Unknown,
}
impl ServerMessage {
pub fn screen_png(&self) -> Option<Vec<u8>> {
match self {
Self::Screen { png } => BASE64.decode(png).ok(),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ClientMessage {
Hello {
api: u32,
client: String,
},
SetLock {
on: bool,
},
GetState,
SetIcon {
id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
svg: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
png: Option<String>,
},
SetCommands {
app: App,
commands: Vec<Command>,
},
SetEnvironments {
environments: Vec<Environment>,
},
SetEnvironment {
id: String,
},
SetUnavailable {
commands: Vec<String>,
},
Focus {
on: bool,
},
SetLcd {
#[serde(default, skip_serializing_if = "Option::is_none")]
brightness: Option<u8>,
#[serde(default, skip_serializing_if = "Option::is_none")]
text_size: Option<TextSize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
theme: Option<Theme>,
},
GetScreen,
#[serde(other)]
Unknown,
}
pub const KEYS: [(u8, &str); 31] = [
(1, "menu"),
(2, "fit"),
(3, "t"),
(5, "r"),
(6, "f"),
(9, "roll"),
(11, "iso"),
(13, "1"),
(14, "2"),
(15, "3"),
(16, "4"),
(17, "5"),
(18, "6"),
(19, "7"),
(20, "8"),
(21, "9"),
(22, "10"),
(23, "esc"),
(24, "alt"),
(25, "shift"),
(26, "ctrl"),
(27, "lock"),
(36, "enter"),
(37, "delete"),
(77, "11"),
(78, "12"),
(103, "v1"),
(104, "v2"),
(105, "v3"),
(175, "tab"),
(176, "space"),
];
pub const LOCK_KEY_ID: u8 = 27;
pub fn key_name(id: u8) -> String {
KEYS.iter()
.find(|(key_id, _)| *key_id == id)
.map_or_else(|| format!("id{id}"), |(_, name)| (*name).to_owned())
}
pub fn key_id(name: &str) -> Option<u8> {
KEYS.iter()
.find(|(_, key_name)| *key_name == name)
.map(|(id, _)| *id)
}
pub fn to_line<T: Serialize>(message: &T) -> String {
let mut line = serde_json::to_string(message).unwrap_or_default();
line.push('\n');
line
}
pub const MAX_SERVER_LINE: usize = 1024 * 1024;
#[derive(Clone, Debug, Default)]
pub struct Lines {
pending: Vec<u8>,
scanned: usize,
#[cfg(test)]
looked: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum LineError {
#[non_exhaustive]
Invalid { reason: String },
Overlong,
}
impl std::fmt::Display for LineError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Invalid { reason } => write!(f, "a line that is not a message: {reason}"),
Self::Overlong => write!(f, "a line longer than {MAX_SERVER_LINE} bytes"),
}
}
}
impl std::error::Error for LineError {}
impl From<LineError> for io::Error {
fn from(error: LineError) -> Self {
io::Error::new(io::ErrorKind::InvalidData, error)
}
}
impl Lines {
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, bytes: &[u8]) {
self.pending.extend_from_slice(bytes);
}
pub fn next_message(&mut self) -> Result<Option<ServerMessage>, LineError> {
loop {
let unseen = &self.pending[self.scanned..];
#[cfg(test)]
{
self.looked += unseen.len();
}
let found = unseen.iter().position(|&byte| byte == b'\n');
let Some(end) = found.map(|at| self.scanned + at) else {
self.scanned = self.pending.len();
if self.pending.len() > MAX_SERVER_LINE {
self.pending.clear();
self.scanned = 0;
return Err(LineError::Overlong);
}
return Ok(None);
};
if end > MAX_SERVER_LINE {
self.pending.clear();
self.scanned = 0;
return Err(LineError::Overlong);
}
let line: Vec<u8> = self.pending.drain(..=end).collect();
self.scanned = 0;
if line.iter().all(u8::is_ascii_whitespace) {
continue;
}
match serde_json::from_slice::<ServerMessage>(&line) {
Ok(ServerMessage::Unknown) => continue,
Ok(message) => return Ok(Some(message)),
Err(error) => {
return Err(LineError::Invalid {
reason: error.to_string(),
});
}
}
}
}
pub fn is_empty(&self) -> bool {
self.pending.is_empty()
}
}
pub struct Client {
lines: Lines,
writer: UnixStream,
pub api: u32,
pub server: String,
}
impl Client {
pub fn connect(client: &str) -> io::Result<Self> {
let path = default_socket_path()
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "XDG_RUNTIME_DIR is not set"))?;
Self::connect_to(&path, client)
}
pub fn connect_to(path: &Path, client: &str) -> io::Result<Self> {
let writer = UnixStream::connect(path)?;
let mut this = Self {
lines: Lines::new(),
writer,
api: 0,
server: String::new(),
};
this.send(&ClientMessage::Hello {
api: API_VERSION,
client: client.to_owned(),
})?;
match this.next_message()? {
Some(ServerMessage::Hello { api, server }) => {
this.api = api;
this.server = server;
Ok(this)
}
Some(ServerMessage::Error { message }) => Err(io::Error::other(message)),
other => Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("expected hello from smed, got {other:?}"),
)),
}
}
pub fn send(&mut self, message: &ClientMessage) -> io::Result<()> {
self.writer.write_all(to_line(message).as_bytes())
}
pub fn set_lock(&mut self, on: bool) -> io::Result<()> {
self.send(&ClientMessage::SetLock { on })
}
pub fn get_state(&mut self) -> io::Result<()> {
self.send(&ClientMessage::GetState)
}
pub fn focus(&mut self, on: bool) -> io::Result<()> {
self.send(&ClientMessage::Focus { on })
}
pub fn set_icon_svg(&mut self, id: &str, svg: &str) -> io::Result<()> {
self.send(&ClientMessage::SetIcon {
id: id.to_owned(),
svg: Some(svg.to_owned()),
png: None,
})
}
pub fn set_icon_png(&mut self, id: &str, png: &[u8]) -> io::Result<()> {
self.send(&ClientMessage::SetIcon {
id: id.to_owned(),
svg: None,
png: Some(BASE64.encode(png)),
})
}
pub fn set_commands(&mut self, app: &App, commands: &[Command]) -> io::Result<()> {
self.send(&ClientMessage::SetCommands {
app: app.clone(),
commands: commands.to_vec(),
})
}
pub fn set_environments(&mut self, environments: &[Environment]) -> io::Result<()> {
self.send(&ClientMessage::SetEnvironments {
environments: environments.to_vec(),
})
}
pub fn set_unavailable<S: AsRef<str>>(&mut self, commands: &[S]) -> io::Result<()> {
self.send(&ClientMessage::SetUnavailable {
commands: commands.iter().map(|c| c.as_ref().to_owned()).collect(),
})
}
pub fn set_environment(&mut self, id: &str) -> io::Result<()> {
self.send(&ClientMessage::SetEnvironment { id: id.to_owned() })
}
pub fn set_lcd(
&mut self,
brightness: Option<u8>,
text_size: Option<TextSize>,
theme: Option<Theme>,
) -> io::Result<()> {
self.send(&ClientMessage::SetLcd {
brightness,
text_size,
theme,
})
}
pub fn get_screen(&mut self) -> io::Result<()> {
self.send(&ClientMessage::GetScreen)
}
pub fn next_message(&mut self) -> io::Result<Option<ServerMessage>> {
let mut chunk = [0_u8; 4096];
loop {
if let Some(message) = self.lines.next_message()? {
return Ok(Some(message));
}
match (&self.writer).read(&mut chunk) {
Ok(0) => return Ok(None),
Ok(len) => self.lines.push(&chunk[..len]),
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(error),
}
}
}
pub fn stream(&self) -> &UnixStream {
&self.writer
}
}
#[cfg(test)]
mod tests {
use super::*;
fn round_trip_server(line: &str, message: ServerMessage) {
assert_eq!(
serde_json::from_str::<ServerMessage>(line).ok(),
Some(message.clone())
);
assert_eq!(to_line(&message), format!("{line}\n"));
}
#[test]
fn server_messages_match_the_spec() {
round_trip_server(
r#"{"type":"hello","api":1,"server":"smed 0.2.1"}"#,
ServerMessage::Hello {
api: 1,
server: "smed 0.2.1".into(),
},
);
round_trip_server(
r#"{"type":"state","device":{"vid":9583,"pid":50739,"name":"3Dconnexion SpaceMouse Enterprise","firmware":"4.42"},"lock":false,"lcd":true}"#,
ServerMessage::State {
device: Some(DeviceInfo {
vid: 0x256f,
pid: 0xc633,
name: "3Dconnexion SpaceMouse Enterprise".into(),
firmware: Some("4.42".into()),
}),
lock: false,
lcd: Some(true),
},
);
round_trip_server(
r#"{"type":"state","device":null,"lock":false,"lcd":false}"#,
ServerMessage::State {
device: None,
lock: false,
lcd: Some(false),
},
);
round_trip_server(
r#"{"type":"lcd","owner":false,"brightness":100,"text_size":"small","theme":"light"}"#,
ServerMessage::Lcd {
owner: false,
brightness: 100,
text_size: TextSize::Small,
theme: Theme::Light,
},
);
round_trip_server(
r#"{"type":"state","device":{"vid":9583,"pid":50739,"name":"3Dconnexion SpaceMouse Enterprise","firmware":"4.42"},"lock":false}"#,
ServerMessage::State {
device: Some(DeviceInfo {
vid: 0x256f,
pid: 0xc633,
name: "3Dconnexion SpaceMouse Enterprise".into(),
firmware: Some("4.42".into()),
}),
lock: false,
lcd: None,
},
);
round_trip_server(
r#"{"type":"hello","api":2,"server":"smed 0.2.1"}"#,
ServerMessage::Hello {
api: 2,
server: "smed 0.2.1".into(),
},
);
round_trip_server(
r#"{"type":"lcd","owner":true,"brightness":40,"text_size":"small","theme":"light"}"#,
ServerMessage::Lcd {
owner: true,
brightness: 40,
text_size: TextSize::Small,
theme: Theme::Light,
},
);
round_trip_server(
r#"{"type":"command","id":"sketch.line","env":"sketch","key":"1","press":"short"}"#,
ServerMessage::Command {
id: "sketch.line".into(),
env: "sketch".into(),
key: "1".into(),
press: Press::Short,
},
);
round_trip_server(
r#"{"type":"screen","png":"iVBORw0KGgo="}"#,
ServerMessage::Screen {
png: "iVBORw0KGgo=".into(),
},
);
round_trip_server(
r#"{"type":"device","device":null}"#,
ServerMessage::Device { device: None },
);
round_trip_server(
r#"{"type":"motion","t":[0,-12,3],"r":[5,0,0]}"#,
ServerMessage::Motion {
t: [0, -12, 3],
r: [5, 0, 0],
},
);
round_trip_server(
r#"{"type":"key","key":"t","id":3,"press":"long","down":true}"#,
ServerMessage::Key {
key: "t".into(),
id: 3,
press: Press::Long,
down: true,
},
);
round_trip_server(
r#"{"type":"lock","on":true}"#,
ServerMessage::Lock { on: true },
);
}
#[test]
fn client_messages_match_the_spec() {
let cases = [
(
r#"{"type":"hello","api":1,"client":"smectl"}"#,
ClientMessage::Hello {
api: 1,
client: "smectl".into(),
},
),
(
r#"{"type":"set_lock","on":false}"#,
ClientMessage::SetLock { on: false },
),
(r#"{"type":"get_state"}"#, ClientMessage::GetState),
(
r#"{"type":"set_icon","id":"line","svg":"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><path d='M4 20 20 4' stroke='currentColor' stroke-width='2'/></svg>"}"#,
ClientMessage::SetIcon {
id: "line".into(),
svg: Some("<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><path d='M4 20 20 4' stroke='currentColor' stroke-width='2'/></svg>".into()),
png: None,
},
),
(
r#"{"type":"set_commands","app":{"name":"SolidCraft","icon":"logo"},"commands":[{"id":"sketch.line","label":"Line","icon":"line"},{"id":"edit.undo","label":"Undo"}]}"#,
ClientMessage::SetCommands {
app: App {
name: "SolidCraft".into(),
icon: Some("logo".into()),
},
commands: vec![
Command {
id: "sketch.line".into(),
label: "Line".into(),
icon: Some("line".into()),
},
Command {
id: "edit.undo".into(),
label: "Undo".into(),
icon: None,
},
],
},
),
(
r#"{"type":"set_environments","environments":[{"id":"sketch","name":"Sketch","keys":{"1":"sketch.line","9":"edit.undo"}}]}"#,
ClientMessage::SetEnvironments {
environments: vec![Environment {
id: "sketch".into(),
name: "Sketch".into(),
keys: [("1", "sketch.line"), ("9", "edit.undo")]
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect(),
long_keys: BTreeMap::new(),
}],
},
),
(
r#"{"type":"set_environments","environments":[{"id":"sketch","name":"Sketch","keys":{"1":"sketch.line"},"long_keys":{"1":"sketch.rectangle"}}]}"#,
ClientMessage::SetEnvironments {
environments: vec![
Environment::new("sketch", "Sketch")
.with_key("1", "sketch.line")
.with_long_key("1", "sketch.rectangle"),
],
},
),
(
r#"{"type":"set_unavailable","commands":["edit.undo"]}"#,
ClientMessage::SetUnavailable {
commands: vec!["edit.undo".into()],
},
),
(
r#"{"type":"hello","api":2,"client":"solidcraft"}"#,
ClientMessage::Hello {
api: 2,
client: "solidcraft".into(),
},
),
(r#"{"type":"focus","on":true}"#, ClientMessage::Focus { on: true }),
(r#"{"type":"get_screen"}"#, ClientMessage::GetScreen),
(
r#"{"type":"set_environment","id":"part"}"#,
ClientMessage::SetEnvironment { id: "part".into() },
),
(
r#"{"type":"set_lcd","brightness":40}"#,
ClientMessage::SetLcd {
brightness: Some(40),
text_size: None,
theme: None,
},
),
];
for (line, message) in cases {
assert_eq!(
serde_json::from_str::<ClientMessage>(line).ok(),
Some(message.clone())
);
assert_eq!(to_line(&message), format!("{line}\n"));
}
}
#[test]
fn unknown_types_and_fields_are_ignored() {
assert_eq!(
serde_json::from_str::<ServerMessage>(r#"{"type":"osd","page":2}"#).ok(),
Some(ServerMessage::Unknown)
);
assert_eq!(
serde_json::from_str::<ServerMessage>(r#"{"type":"lock","on":true,"by":"key"}"#).ok(),
Some(ServerMessage::Lock { on: true })
);
assert_eq!(
serde_json::from_str::<ClientMessage>(r#"{"type":"set_osd"}"#).ok(),
Some(ClientMessage::Unknown)
);
}
fn client_pair() -> (Client, std::io::BufReader<UnixStream>) {
let (ours, theirs) = UnixStream::pair().unwrap();
theirs
.set_read_timeout(Some(std::time::Duration::from_secs(5)))
.unwrap();
let client = Client {
lines: Lines::new(),
writer: ours,
api: API_VERSION,
server: String::new(),
};
(client, std::io::BufReader::new(theirs))
}
fn sent(smed: &mut std::io::BufReader<UnixStream>) -> String {
use std::io::BufRead;
let mut line = String::new();
smed.read_line(&mut line).unwrap();
line.trim_end().to_owned()
}
#[test]
fn client_methods_send_the_spec_lines() {
let (mut client, mut smed) = client_pair();
let svg = "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><path d='M4 20 20 4' stroke='currentColor' stroke-width='2'/></svg>";
client.set_icon_svg("line", svg).unwrap();
assert_eq!(
sent(&mut smed),
format!(r#"{{"type":"set_icon","id":"line","svg":"{svg}"}}"#)
);
client
.set_commands(
&App::new("SolidCraft").with_icon("logo"),
&[
Command::new("sketch.line", "Line").with_icon("line"),
Command::new("edit.undo", "Undo"),
],
)
.unwrap();
assert_eq!(
sent(&mut smed),
r#"{"type":"set_commands","app":{"name":"SolidCraft","icon":"logo"},"commands":[{"id":"sketch.line","label":"Line","icon":"line"},{"id":"edit.undo","label":"Undo"}]}"#
);
client
.set_environments(&[Environment::new("sketch", "Sketch")
.with_key("9", "edit.undo")
.with_key("1", "sketch.line")])
.unwrap();
assert_eq!(
sent(&mut smed),
r#"{"type":"set_environments","environments":[{"id":"sketch","name":"Sketch","keys":{"1":"sketch.line","9":"edit.undo"}}]}"#
);
client
.set_environments(&[Environment::new("sketch", "Sketch")
.with_key("1", "sketch.line")
.with_long_key("1", "sketch.rectangle")])
.unwrap();
assert_eq!(
sent(&mut smed),
r#"{"type":"set_environments","environments":[{"id":"sketch","name":"Sketch","keys":{"1":"sketch.line"},"long_keys":{"1":"sketch.rectangle"}}]}"#
);
client.set_unavailable(&["edit.undo"]).unwrap();
assert_eq!(
sent(&mut smed),
r#"{"type":"set_unavailable","commands":["edit.undo"]}"#
);
client.set_environment("part").unwrap();
assert_eq!(sent(&mut smed), r#"{"type":"set_environment","id":"part"}"#);
client.focus(true).unwrap();
assert_eq!(sent(&mut smed), r#"{"type":"focus","on":true}"#);
client.set_lcd(Some(40), None, None).unwrap();
assert_eq!(sent(&mut smed), r#"{"type":"set_lcd","brightness":40}"#);
client.get_screen().unwrap();
assert_eq!(sent(&mut smed), r#"{"type":"get_screen"}"#);
client.set_lock(true).unwrap();
assert_eq!(sent(&mut smed), r#"{"type":"set_lock","on":true}"#);
client.get_state().unwrap();
assert_eq!(sent(&mut smed), r#"{"type":"get_state"}"#);
}
#[test]
fn the_limits_keep_their_values() {
assert_eq!(MAX_MESSAGE, 262_144);
assert_eq!(MAX_SERVER_LINE, 1_048_576);
}
#[test]
fn line_errors_say_what_went_wrong() {
let invalid = LineError::Invalid {
reason: "expected value".into(),
};
assert_eq!(
invalid.to_string(),
"a line that is not a message: expected value"
);
assert_eq!(
LineError::Overlong.to_string(),
"a line longer than 1048576 bytes"
);
}
#[test]
fn png_icons_and_screens_are_base64() {
const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
let (mut client, mut smed) = client_pair();
client.set_icon_png("logo", PNG_SIGNATURE).unwrap();
assert_eq!(
sent(&mut smed),
r#"{"type":"set_icon","id":"logo","png":"iVBORw0KGgo="}"#
);
let screen = ServerMessage::Screen {
png: "iVBORw0KGgo=".into(),
};
assert_eq!(screen.screen_png().as_deref(), Some(PNG_SIGNATURE));
let broken = ServerMessage::Screen { png: "*".into() };
assert_eq!(broken.screen_png(), None);
assert_eq!(ServerMessage::Lock { on: true }.screen_png(), None);
}
#[test]
fn constructors_leave_the_optional_parts_empty() {
assert_eq!(
App::new("Example"),
App {
name: "Example".into(),
icon: None
}
);
assert_eq!(Command::new("a", "A").icon, None);
assert!(Environment::new("e", "E").keys.is_empty());
assert_eq!(
DeviceInfo::new(0x256f, 0xc633, "SpaceMouse", Some("4.42".into())),
DeviceInfo {
vid: 0x256f,
pid: 0xc633,
name: "SpaceMouse".into(),
firmware: Some("4.42".into()),
}
);
}
#[test]
fn a_line_split_by_a_read_timeout_arrives_whole() {
let (mut client, smed) = client_pair();
let mut smed = smed.into_inner();
client
.stream()
.set_read_timeout(Some(std::time::Duration::from_millis(20)))
.unwrap();
smed.write_all(br#"{"type":"lock","#).unwrap();
let timeout = client.next_message().unwrap_err();
assert!(matches!(
timeout.kind(),
io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
));
smed.write_all(b"\"on\":true}\n").unwrap();
assert_eq!(
client.next_message().unwrap(),
Some(ServerMessage::Lock { on: true })
);
drop(smed);
assert_eq!(client.next_message().unwrap(), None);
}
#[test]
fn lines_hands_out_whole_messages_in_order() {
let mut lines = Lines::new();
assert!(lines.is_empty());
lines.push(b"\n \n{\"type\":\"lock\",\"on\":true}\n{\"type\":\"osd\"}\n{\"type\":\"lo");
assert_eq!(
lines.next_message().unwrap(),
Some(ServerMessage::Lock { on: true })
);
assert_eq!(lines.next_message().unwrap(), None);
assert!(!lines.is_empty());
lines.push(b"ck\",\"on\":false}\n");
assert_eq!(
lines.next_message().unwrap(),
Some(ServerMessage::Lock { on: false })
);
assert!(lines.is_empty());
}
#[test]
fn lines_reports_invalid_json_and_reads_on() {
let mut lines = Lines::new();
lines.push(b"not json\n{\"type\":\"lock\",\"on\":true}\n");
let error = lines.next_message().unwrap_err();
assert!(matches!(error, LineError::Invalid { .. }), "{error:?}");
assert_eq!(
lines.next_message().unwrap(),
Some(ServerMessage::Lock { on: true })
);
}
#[test]
fn lines_refuses_an_overlong_line() {
let mut lines = Lines::new();
let mut longest = br#"{"type":"screen","png":""#.to_vec();
longest.resize(MAX_SERVER_LINE - 2, b'A');
longest.extend_from_slice(b"\"}");
assert_eq!(longest.len(), MAX_SERVER_LINE);
lines.push(&longest);
lines.push(b"\n");
assert!(matches!(
lines.next_message().unwrap(),
Some(ServerMessage::Screen { .. })
));
lines.push(&vec![b'x'; MAX_SERVER_LINE + 1]);
assert_eq!(lines.next_message().unwrap_err(), LineError::Overlong);
assert!(lines.is_empty());
let mut over = vec![b' '; MAX_SERVER_LINE + 1];
over.push(b'\n');
lines.push(&over);
assert_eq!(lines.next_message().unwrap_err(), LineError::Overlong);
}
#[test]
fn lines_looks_at_each_byte_once() {
let mut longest = br#"{"type":"screen","png":""#.to_vec();
longest.resize(MAX_SERVER_LINE - 2, b'A');
longest.extend_from_slice(b"\"}\n");
let mut lines = Lines::new();
let mut handed_out = 0;
for part in longest.chunks(4096) {
lines.push(part);
if lines.scanned < lines.pending.len() {
let before = lines.scanned;
let message = lines.next_message().unwrap();
if message.is_none() {
assert_eq!(lines.scanned, lines.pending.len());
assert!(before <= lines.scanned);
} else {
assert!(matches!(message, Some(ServerMessage::Screen { .. })));
assert!(lines.is_empty());
handed_out += 1;
}
}
}
assert_eq!(handed_out, 1);
assert_eq!(lines.looked, longest.len());
lines.push(b"{\"type\":\"lock\",\"on\":true}\n{\"type\":\"lock\",\"on\":false}\n");
assert_eq!(
lines.next_message().unwrap(),
Some(ServerMessage::Lock { on: true })
);
assert_eq!(
lines.next_message().unwrap(),
Some(ServerMessage::Lock { on: false })
);
}
#[test]
fn client_reports_line_errors_as_invalid_data_with_the_line_error_inside() {
let (mut client, smed) = client_pair();
let mut smed = smed.into_inner();
smed.write_all(b"not json\n").unwrap();
let error = client.next_message().unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
let inner = error
.get_ref()
.and_then(|inner| inner.downcast_ref::<LineError>());
assert!(
matches!(inner, Some(LineError::Invalid { .. })),
"{error:?}"
);
smed.write_all(b"{\"type\":\"lock\",\"on\":true}\n")
.unwrap();
assert_eq!(
client.next_message().unwrap(),
Some(ServerMessage::Lock { on: true })
);
}
#[test]
fn every_key_has_a_unique_id_and_name() {
for (index, (id, name)) in KEYS.iter().enumerate() {
assert_eq!(key_id(name), Some(*id));
assert_eq!(key_name(*id), *name);
assert!(
KEYS[index + 1..]
.iter()
.all(|(other, n)| other != id && n != name)
);
}
assert_eq!(key_name(LOCK_KEY_ID), "lock");
assert_eq!(key_name(200), "id200");
}
}