Skip to main content

smed_client/
lib.rs

1//! Client for smed, the SpaceMouse Enterprise driver daemon.
2//!
3//! smed speaks JSON lines over a Unix socket (`docs/api.md` in the repository is the
4//! specification). This crate holds the message types both sides use, the table of key names
5//! and a small blocking client:
6//!
7//! ```no_run
8//! use smed_client::{Client, ServerMessage};
9//!
10//! let mut client = Client::connect("example")?;
11//! while let Some(message) = client.next_message()? {
12//!     if let ServerMessage::Key { key, press, down, .. } = message {
13//!         println!("{key} {press:?} {}", if down { "down" } else { "up" });
14//!     }
15//! }
16//! # Ok::<(), std::io::Error>(())
17//! ```
18//!
19//! An application that puts its commands on the keys 1–12 and the LCD (API 2) sends its
20//! catalogue and environments, says when its window has the focus, and runs the commands smed
21//! reports:
22//!
23//! ```no_run
24//! use smed_client::{App, Client, Command, Environment, ServerMessage};
25//!
26//! let mut client = Client::connect("example")?;
27//! client.set_icon_svg("line", "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'>\
28//!     <path d='M4 20 20 4' stroke='currentColor' stroke-width='2'/></svg>")?;
29//! client.set_commands(
30//!     &App::new("Example"),
31//!     &[Command::new("sketch.line", "Line").with_icon("line"), Command::new("edit.undo", "Undo")],
32//! )?;
33//! client.set_environments(&[Environment::new("sketch", "Sketch")
34//!     .with_key("1", "sketch.line")
35//!     .with_key("9", "edit.undo")])?;
36//! client.set_environment("sketch")?;
37//! client.focus(true)?;
38//! while let Some(message) = client.next_message()? {
39//!     match message {
40//!         ServerMessage::Command { id, .. } => println!("run {id}"),
41//!         ServerMessage::Error { message } => eprintln!("smed: {message}"),
42//!         _ => {}
43//!     }
44//! }
45//! # Ok::<(), std::io::Error>(())
46//! ```
47//!
48//! An application that reads the socket in its own loop pushes what it reads into a [`Lines`]
49//! decoder instead, which hands out whole messages.
50//!
51//! The enums and structs are `#[non_exhaustive]`, so later API versions can add message types,
52//! values, and fields of `App`, `Command`, `Environment` and `DeviceInfo` without breaking your
53//! code: match messages with a `_` arm and their fields with `..`, build the structs with their
54//! `new` functions, and send client messages through the [`Client`] methods rather than building
55//! [`ClientMessage`] values. A new field in a message variant is still a breaking change of this
56//! crate.
57//!
58//! Outside this crate, a struct cannot be built field by field:
59//!
60//! ```compile_fail
61//! let command = smed_client::Command {
62//!     id: "edit.undo".into(),
63//!     label: "Undo".into(),
64//!     icon: None,
65//! };
66//! ```
67
68#![forbid(unsafe_code)]
69
70// The README's examples are compiled as doctests too, so they cannot drift from the API.
71#[cfg(doctest)]
72#[doc = include_str!("../README.md")]
73struct ReadmeDoctests;
74
75use std::collections::BTreeMap;
76use std::io::{self, Read, Write};
77use std::os::unix::net::UnixStream;
78use std::path::{Path, PathBuf};
79
80use base64::Engine as _;
81use base64::engine::general_purpose::STANDARD as BASE64;
82use serde::{Deserialize, Serialize};
83
84/// The highest API version this crate speaks.
85pub const API_VERSION: u32 = 2;
86
87/// The largest message smed accepts, in bytes (one line, icons included).
88pub const MAX_MESSAGE: usize = 256 * 1024;
89
90/// The socket's path below `$XDG_RUNTIME_DIR`.
91pub const SOCKET_IN_RUNTIME_DIR: &str = "smed/api.sock";
92
93/// Where smed listens for the current user: `$XDG_RUNTIME_DIR/smed/api.sock`, or `None` when
94/// `XDG_RUNTIME_DIR` is not set.
95pub fn default_socket_path() -> Option<PathBuf> {
96    let dir = std::env::var_os("XDG_RUNTIME_DIR").filter(|dir| !dir.is_empty())?;
97    Some(PathBuf::from(dir).join(SOCKET_IN_RUNTIME_DIR))
98}
99
100/// The device smed has, as reported in `state` and `device`.
101#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
102#[non_exhaustive]
103pub struct DeviceInfo {
104    pub vid: u16,
105    pub pid: u16,
106    /// The kernel's HID name.
107    pub name: String,
108    /// The firmware version from the USB descriptor (bcdDevice), such as `"4.42"`.
109    pub firmware: Option<String>,
110}
111
112impl DeviceInfo {
113    /// A device with USB IDs `vid`:`pid`, the kernel's HID name and the firmware version.
114    pub fn new(vid: u16, pid: u16, name: impl Into<String>, firmware: Option<String>) -> Self {
115        Self {
116            vid,
117            pid,
118            name: name.into(),
119            firmware,
120        }
121    }
122}
123
124/// Whether the device reported a key as pressed briefly or held.
125#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
126#[serde(rename_all = "snake_case")]
127#[non_exhaustive]
128pub enum Press {
129    Short,
130    Long,
131}
132
133/// Text size on the LCD.
134#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
135#[serde(rename_all = "snake_case")]
136#[non_exhaustive]
137pub enum TextSize {
138    #[default]
139    Small,
140    Large,
141}
142
143/// Colour theme of the LCD.
144#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
145#[serde(rename_all = "snake_case")]
146#[non_exhaustive]
147pub enum Theme {
148    #[default]
149    Light,
150    Dark,
151}
152
153/// The application as shown in the LCD's header (`set_commands`).
154#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
155#[non_exhaustive]
156pub struct App {
157    pub name: String,
158    /// An icon `id` from `set_icon`.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub icon: Option<String>,
161}
162
163impl App {
164    /// An application called `name`, without an icon.
165    pub fn new(name: impl Into<String>) -> Self {
166        Self {
167            name: name.into(),
168            icon: None,
169        }
170    }
171
172    /// The same application with the icon `icon` (an `id` from `set_icon`).
173    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
174        self.icon = Some(icon.into());
175        self
176    }
177}
178
179/// One command of the client's catalogue (`set_commands`).
180#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
181#[non_exhaustive]
182pub struct Command {
183    pub id: String,
184    pub label: String,
185    /// An icon `id` from `set_icon`.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub icon: Option<String>,
188}
189
190impl Command {
191    /// The command `id`, shown as `label`, without an icon.
192    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
193        Self {
194            id: id.into(),
195            label: label.into(),
196            icon: None,
197        }
198    }
199
200    /// The same command with the icon `icon` (an `id` from `set_icon`).
201    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
202        self.icon = Some(icon.into());
203        self
204    }
205}
206
207/// One environment of the client (`set_environments`): a name and which command each key
208/// runs there, by key name (`"1"`–`"12"`) and command `id`.
209#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
210#[non_exhaustive]
211pub struct Environment {
212    pub id: String,
213    pub name: String,
214    #[serde(default)]
215    pub keys: BTreeMap<String, String>,
216    /// The command a long press of a key runs instead, in the same form as `keys`; shown small
217    /// on the key's tile (since 0.2.1).
218    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
219    pub long_keys: BTreeMap<String, String>,
220}
221
222impl Environment {
223    /// The environment `id`, shown as `name`, with no keys assigned.
224    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
225        Self {
226            id: id.into(),
227            name: name.into(),
228            keys: BTreeMap::new(),
229            long_keys: BTreeMap::new(),
230        }
231    }
232
233    /// The same environment with `key` (a key name, `"1"`–`"12"`) running `command` (an `id`
234    /// from `set_commands`).
235    pub fn with_key(mut self, key: impl Into<String>, command: impl Into<String>) -> Self {
236        self.keys.insert(key.into(), command.into());
237        self
238    }
239
240    /// The same environment with a long press of `key` running `command` (an `id` from
241    /// `set_commands`) instead of the one from `keys` (since 0.2.1).
242    pub fn with_long_key(mut self, key: impl Into<String>, command: impl Into<String>) -> Self {
243        self.long_keys.insert(key.into(), command.into());
244        self
245    }
246}
247
248/// What smed sends.
249#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
250#[serde(tag = "type", rename_all = "snake_case")]
251#[non_exhaustive]
252pub enum ServerMessage {
253    Hello {
254        api: u32,
255        server: String,
256    },
257    State {
258        device: Option<DeviceInfo>,
259        lock: bool,
260        /// API 2: whether smed can draw on the LCD. Absent with API 1.
261        #[serde(default, skip_serializing_if = "Option::is_none")]
262        lcd: Option<bool>,
263    },
264    Device {
265        device: Option<DeviceInfo>,
266    },
267    /// Translation `t` and rotation `r` in the raw device frame, rotation zeroed while locked.
268    Motion {
269        t: [i16; 3],
270        r: [i16; 3],
271    },
272    Key {
273        key: String,
274        id: u8,
275        press: Press,
276        down: bool,
277    },
278    Lock {
279        on: bool,
280    },
281    /// API 2: whether this connection has the LCD, and the LCD settings.
282    Lcd {
283        owner: bool,
284        brightness: u8,
285        text_size: TextSize,
286        theme: Theme,
287    },
288    /// API 2: a key the focused client assigned a command to went down: `id` of the command,
289    /// `env` the environment it is assigned in, `key` the key's name, `press` short or long.
290    Command {
291        id: String,
292        env: String,
293        key: String,
294        press: Press,
295    },
296    /// API 2: the answer to `get_screen`: the current LCD page as a PNG (base64), drawn as it
297    /// goes to the device.
298    Screen {
299        png: String,
300    },
301    Error {
302        message: String,
303    },
304    /// A message type this crate does not know (from a newer smed); ignore it.
305    #[serde(other)]
306    Unknown,
307}
308
309impl ServerMessage {
310    /// The PNG of a `screen` message, decoded; `None` for other messages or invalid base64.
311    pub fn screen_png(&self) -> Option<Vec<u8>> {
312        match self {
313            Self::Screen { png } => BASE64.decode(png).ok(),
314            _ => None,
315        }
316    }
317}
318
319/// What a client sends.
320#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
321#[serde(tag = "type", rename_all = "snake_case")]
322#[non_exhaustive]
323pub enum ClientMessage {
324    Hello {
325        api: u32,
326        client: String,
327    },
328    SetLock {
329        on: bool,
330    },
331    GetState,
332    /// API 2: an icon for tiles and the header, kept per connection under `id`. One of `svg`
333    /// (SVG source) and `png` (base64).
334    SetIcon {
335        id: String,
336        #[serde(default, skip_serializing_if = "Option::is_none")]
337        svg: Option<String>,
338        #[serde(default, skip_serializing_if = "Option::is_none")]
339        png: Option<String>,
340    },
341    /// API 2: the application and its command catalogue; replaces the previous one.
342    SetCommands {
343        app: App,
344        commands: Vec<Command>,
345    },
346    /// API 2: the environments with their key assignments; replaces the previous ones.
347    SetEnvironments {
348        environments: Vec<Environment>,
349    },
350    /// API 2: show environment `id` (from `set_environments`); its keys run their commands.
351    SetEnvironment {
352        id: String,
353    },
354    /// API 2: the commands that cannot run now (since 0.2.1); their tiles are drawn greyed out.
355    /// Replaces the previous list; an empty one means every command can run.
356    SetUnavailable {
357        commands: Vec<String>,
358    },
359    /// API 2: this client's window got (`true`) or lost (`false`) the input focus.
360    Focus {
361        on: bool,
362    },
363    /// API 2: change the LCD settings (for every client) until smed restarts.
364    SetLcd {
365        #[serde(default, skip_serializing_if = "Option::is_none")]
366        brightness: Option<u8>,
367        #[serde(default, skip_serializing_if = "Option::is_none")]
368        text_size: Option<TextSize>,
369        #[serde(default, skip_serializing_if = "Option::is_none")]
370        theme: Option<Theme>,
371    },
372    /// API 2: ask for the current LCD page as a PNG; smed answers with `screen`.
373    GetScreen,
374    /// A message type smed does not know (from a newer client); smed ignores it.
375    #[serde(other)]
376    Unknown,
377}
378
379/// The printed keys and their 3Dx IDs (docs/protocol.md, "Key numbering").
380pub const KEYS: [(u8, &str); 31] = [
381    (1, "menu"),
382    (2, "fit"),
383    (3, "t"),
384    (5, "r"),
385    (6, "f"),
386    (9, "roll"),
387    (11, "iso"),
388    (13, "1"),
389    (14, "2"),
390    (15, "3"),
391    (16, "4"),
392    (17, "5"),
393    (18, "6"),
394    (19, "7"),
395    (20, "8"),
396    (21, "9"),
397    (22, "10"),
398    (23, "esc"),
399    (24, "alt"),
400    (25, "shift"),
401    (26, "ctrl"),
402    (27, "lock"),
403    (36, "enter"),
404    (37, "delete"),
405    (77, "11"),
406    (78, "12"),
407    (103, "v1"),
408    (104, "v2"),
409    (105, "v3"),
410    (175, "tab"),
411    (176, "space"),
412];
413
414/// The 3Dx ID of the rotation-lock key.
415pub const LOCK_KEY_ID: u8 = 27;
416
417/// The name of the key with 3Dx ID `id`, or `"id<N>"` for an ID not on the device's keys.
418pub fn key_name(id: u8) -> String {
419    KEYS.iter()
420        .find(|(key_id, _)| *key_id == id)
421        .map_or_else(|| format!("id{id}"), |(_, name)| (*name).to_owned())
422}
423
424/// The 3Dx ID of the key named `name`.
425pub fn key_id(name: &str) -> Option<u8> {
426    KEYS.iter()
427        .find(|(_, key_name)| *key_name == name)
428        .map(|(id, _)| *id)
429}
430
431/// One message as a line, `\n` included.
432pub fn to_line<T: Serialize>(message: &T) -> String {
433    // Serializing these types cannot fail: no maps with non-string keys, no foreign Serialize.
434    let mut line = serde_json::to_string(message).unwrap_or_default();
435    line.push('\n');
436    line
437}
438
439/// The longest line [`Lines`] accepts from smed. smed's longest, a `screen` with the LCD page as
440/// a PNG, stays well below it.
441pub const MAX_SERVER_LINE: usize = 1024 * 1024;
442
443/// Splits what smed sends into messages, without doing any I/O: for an application that reads
444/// the socket in its own loop (a read timeout, other work between reads). [`Client`] reads
445/// through it too.
446///
447/// ```
448/// use smed_client::{Lines, ServerMessage};
449///
450/// let mut lines = Lines::new();
451/// lines.push(br#"{"type":"lock","#);
452/// assert!(lines.next_message()?.is_none()); // the rest of the line is still to come
453/// lines.push(b"\"on\":true}\n");
454/// assert_eq!(lines.next_message()?, Some(ServerMessage::Lock { on: true }));
455/// # Ok::<(), smed_client::LineError>(())
456/// ```
457#[derive(Clone, Debug, Default)]
458pub struct Lines {
459    pending: Vec<u8>,
460    /// How many bytes at the start of `pending` are known to hold no newline.
461    scanned: usize,
462    /// How many bytes the newline search has looked at in all, for the test that each byte is
463    /// looked at once.
464    #[cfg(test)]
465    looked: usize,
466}
467
468/// What [`Lines::next_message`] found wrong.
469#[derive(Clone, Debug, PartialEq, Eq)]
470#[non_exhaustive]
471pub enum LineError {
472    /// A line that is not a message (not valid JSON, or a known type with wrong fields). The
473    /// line is dropped; the following ones still read.
474    #[non_exhaustive]
475    Invalid { reason: String },
476    /// A line longer than [`MAX_SERVER_LINE`]: everything pushed so far is dropped. That is no
477    /// smed; close the connection.
478    Overlong,
479}
480
481impl std::fmt::Display for LineError {
482    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
483        match self {
484            Self::Invalid { reason } => write!(f, "a line that is not a message: {reason}"),
485            Self::Overlong => write!(f, "a line longer than {MAX_SERVER_LINE} bytes"),
486        }
487    }
488}
489
490impl std::error::Error for LineError {}
491
492/// As `InvalidData`, with the [`LineError`] inside (`get_ref` and `downcast_ref` give it back).
493impl From<LineError> for io::Error {
494    fn from(error: LineError) -> Self {
495        io::Error::new(io::ErrorKind::InvalidData, error)
496    }
497}
498
499impl Lines {
500    /// A decoder with nothing pushed yet.
501    pub fn new() -> Self {
502        Self::default()
503    }
504
505    /// Adds bytes read from smed's socket.
506    pub fn push(&mut self, bytes: &[u8]) {
507        self.pending.extend_from_slice(bytes);
508    }
509
510    /// The next complete message, or `None` until more bytes are pushed. Blank lines and
511    /// message types this crate does not know are skipped. Each call looks only at bytes it has
512    /// not looked at yet, so a long line read in many parts costs no more than read in one.
513    pub fn next_message(&mut self) -> Result<Option<ServerMessage>, LineError> {
514        loop {
515            let unseen = &self.pending[self.scanned..];
516            #[cfg(test)]
517            {
518                self.looked += unseen.len();
519            }
520            let found = unseen.iter().position(|&byte| byte == b'\n');
521            let Some(end) = found.map(|at| self.scanned + at) else {
522                self.scanned = self.pending.len();
523                if self.pending.len() > MAX_SERVER_LINE {
524                    self.pending.clear();
525                    self.scanned = 0;
526                    return Err(LineError::Overlong);
527                }
528                return Ok(None);
529            };
530            if end > MAX_SERVER_LINE {
531                self.pending.clear();
532                self.scanned = 0;
533                return Err(LineError::Overlong);
534            }
535            let line: Vec<u8> = self.pending.drain(..=end).collect();
536            self.scanned = 0;
537            if line.iter().all(u8::is_ascii_whitespace) {
538                continue;
539            }
540            match serde_json::from_slice::<ServerMessage>(&line) {
541                Ok(ServerMessage::Unknown) => continue,
542                Ok(message) => return Ok(Some(message)),
543                Err(error) => {
544                    return Err(LineError::Invalid {
545                        reason: error.to_string(),
546                    });
547                }
548            }
549        }
550    }
551
552    /// Whether part of a line is waiting for the rest.
553    pub fn is_empty(&self) -> bool {
554        self.pending.is_empty()
555    }
556}
557
558/// A connection to smed, after the handshake.
559pub struct Client {
560    lines: Lines,
561    writer: UnixStream,
562    /// The API version both sides agreed on.
563    pub api: u32,
564    /// smed's name and version from its `hello`.
565    pub server: String,
566}
567
568impl Client {
569    /// Connects to smed at [`default_socket_path`] and introduces itself as `client`.
570    pub fn connect(client: &str) -> io::Result<Self> {
571        let path = default_socket_path()
572            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "XDG_RUNTIME_DIR is not set"))?;
573        Self::connect_to(&path, client)
574    }
575
576    /// Connects to smed at `path` and introduces itself as `client`.
577    pub fn connect_to(path: &Path, client: &str) -> io::Result<Self> {
578        let writer = UnixStream::connect(path)?;
579        let mut this = Self {
580            lines: Lines::new(),
581            writer,
582            api: 0,
583            server: String::new(),
584        };
585        this.send(&ClientMessage::Hello {
586            api: API_VERSION,
587            client: client.to_owned(),
588        })?;
589        match this.next_message()? {
590            Some(ServerMessage::Hello { api, server }) => {
591                this.api = api;
592                this.server = server;
593                Ok(this)
594            }
595            Some(ServerMessage::Error { message }) => Err(io::Error::other(message)),
596            other => Err(io::Error::new(
597                io::ErrorKind::InvalidData,
598                format!("expected hello from smed, got {other:?}"),
599            )),
600        }
601    }
602
603    /// Sends one message.
604    pub fn send(&mut self, message: &ClientMessage) -> io::Result<()> {
605        self.writer.write_all(to_line(message).as_bytes())
606    }
607
608    /// Asks smed to switch the rotation lock on or off.
609    pub fn set_lock(&mut self, on: bool) -> io::Result<()> {
610        self.send(&ClientMessage::SetLock { on })
611    }
612
613    /// Asks smed for a `state` message.
614    pub fn get_state(&mut self) -> io::Result<()> {
615        self.send(&ClientMessage::GetState)
616    }
617
618    /// Tells smed whether this client's window has the input focus (API 2): the focused
619    /// client has the LCD.
620    pub fn focus(&mut self, on: bool) -> io::Result<()> {
621        self.send(&ClientMessage::Focus { on })
622    }
623
624    /// Sends an SVG icon under `id` (API 2), for `set_commands`. `currentColor` takes the
625    /// LCD's text colour.
626    pub fn set_icon_svg(&mut self, id: &str, svg: &str) -> io::Result<()> {
627        self.send(&ClientMessage::SetIcon {
628            id: id.to_owned(),
629            svg: Some(svg.to_owned()),
630            png: None,
631        })
632    }
633
634    /// Sends a PNG icon (the file's bytes) under `id` (API 2), for `set_commands`.
635    pub fn set_icon_png(&mut self, id: &str, png: &[u8]) -> io::Result<()> {
636        self.send(&ClientMessage::SetIcon {
637            id: id.to_owned(),
638            svg: None,
639            png: Some(BASE64.encode(png)),
640        })
641    }
642
643    /// Sends the application and its command catalogue (API 2); replaces the previous one.
644    pub fn set_commands(&mut self, app: &App, commands: &[Command]) -> io::Result<()> {
645        self.send(&ClientMessage::SetCommands {
646            app: app.clone(),
647            commands: commands.to_vec(),
648        })
649    }
650
651    /// Sends the environments with their key assignments (API 2); replaces the previous ones.
652    pub fn set_environments(&mut self, environments: &[Environment]) -> io::Result<()> {
653        self.send(&ClientMessage::SetEnvironments {
654            environments: environments.to_vec(),
655        })
656    }
657
658    /// Tells smed which commands (`id`s from `set_commands`) cannot run now (API 2, since
659    /// 0.2.1): their tiles are drawn greyed out. Replaces the previous list; send an empty one
660    /// when every command can run again. smed still sends `command` for them.
661    pub fn set_unavailable<S: AsRef<str>>(&mut self, commands: &[S]) -> io::Result<()> {
662        self.send(&ClientMessage::SetUnavailable {
663            commands: commands.iter().map(|c| c.as_ref().to_owned()).collect(),
664        })
665    }
666
667    /// Shows environment `id` (from `set_environments`) on the keys and the LCD (API 2).
668    pub fn set_environment(&mut self, id: &str) -> io::Result<()> {
669        self.send(&ClientMessage::SetEnvironment { id: id.to_owned() })
670    }
671
672    /// Changes the LCD settings for every client until smed restarts (API 2); `None` keeps a
673    /// setting. smed answers with `lcd`.
674    pub fn set_lcd(
675        &mut self,
676        brightness: Option<u8>,
677        text_size: Option<TextSize>,
678        theme: Option<Theme>,
679    ) -> io::Result<()> {
680        self.send(&ClientMessage::SetLcd {
681            brightness,
682            text_size,
683            theme,
684        })
685    }
686
687    /// Asks for the current LCD page (API 2); smed answers with `screen`, see
688    /// [`ServerMessage::screen_png`].
689    pub fn get_screen(&mut self) -> io::Result<()> {
690        self.send(&ClientMessage::GetScreen)
691    }
692
693    /// The next message, blocking; `None` once smed closed the connection. Unknown message
694    /// types are skipped. A [`LineError`] comes as `InvalidData` with the `LineError` inside
695    /// (`get_ref()` and `downcast_ref`): after `Invalid` the next call reads on, after `Overlong`
696    /// close the connection. With a read
697    /// timeout on [`Client::stream`], a timeout is returned as the error it is (`WouldBlock` or
698    /// `TimedOut`) and a line it split is kept: the next call goes on with it.
699    pub fn next_message(&mut self) -> io::Result<Option<ServerMessage>> {
700        let mut chunk = [0_u8; 4096];
701        loop {
702            if let Some(message) = self.lines.next_message()? {
703                return Ok(Some(message));
704            }
705            match (&self.writer).read(&mut chunk) {
706                Ok(0) => return Ok(None),
707                Ok(len) => self.lines.push(&chunk[..len]),
708                Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
709                Err(error) => return Err(error),
710            }
711        }
712    }
713
714    /// The underlying stream, e.g. to set a read timeout or shut it down from another thread.
715    pub fn stream(&self) -> &UnixStream {
716        &self.writer
717    }
718}
719
720#[cfg(test)]
721mod tests {
722    use super::*;
723
724    fn round_trip_server(line: &str, message: ServerMessage) {
725        assert_eq!(
726            serde_json::from_str::<ServerMessage>(line).ok(),
727            Some(message.clone())
728        );
729        assert_eq!(to_line(&message), format!("{line}\n"));
730    }
731
732    // The lines are the examples in docs/api.md.
733    #[test]
734    fn server_messages_match_the_spec() {
735        round_trip_server(
736            r#"{"type":"hello","api":1,"server":"smed 0.2.1"}"#,
737            ServerMessage::Hello {
738                api: 1,
739                server: "smed 0.2.1".into(),
740            },
741        );
742        round_trip_server(
743            r#"{"type":"state","device":{"vid":9583,"pid":50739,"name":"3Dconnexion SpaceMouse Enterprise","firmware":"4.42"},"lock":false,"lcd":true}"#,
744            ServerMessage::State {
745                device: Some(DeviceInfo {
746                    vid: 0x256f,
747                    pid: 0xc633,
748                    name: "3Dconnexion SpaceMouse Enterprise".into(),
749                    firmware: Some("4.42".into()),
750                }),
751                lock: false,
752                lcd: Some(true),
753            },
754        );
755        round_trip_server(
756            r#"{"type":"state","device":null,"lock":false,"lcd":false}"#,
757            ServerMessage::State {
758                device: None,
759                lock: false,
760                lcd: Some(false),
761            },
762        );
763        round_trip_server(
764            r#"{"type":"lcd","owner":false,"brightness":100,"text_size":"small","theme":"light"}"#,
765            ServerMessage::Lcd {
766                owner: false,
767                brightness: 100,
768                text_size: TextSize::Small,
769                theme: Theme::Light,
770            },
771        );
772        round_trip_server(
773            r#"{"type":"state","device":{"vid":9583,"pid":50739,"name":"3Dconnexion SpaceMouse Enterprise","firmware":"4.42"},"lock":false}"#,
774            ServerMessage::State {
775                device: Some(DeviceInfo {
776                    vid: 0x256f,
777                    pid: 0xc633,
778                    name: "3Dconnexion SpaceMouse Enterprise".into(),
779                    firmware: Some("4.42".into()),
780                }),
781                lock: false,
782                lcd: None,
783            },
784        );
785        round_trip_server(
786            r#"{"type":"hello","api":2,"server":"smed 0.2.1"}"#,
787            ServerMessage::Hello {
788                api: 2,
789                server: "smed 0.2.1".into(),
790            },
791        );
792        round_trip_server(
793            r#"{"type":"lcd","owner":true,"brightness":40,"text_size":"small","theme":"light"}"#,
794            ServerMessage::Lcd {
795                owner: true,
796                brightness: 40,
797                text_size: TextSize::Small,
798                theme: Theme::Light,
799            },
800        );
801        round_trip_server(
802            r#"{"type":"command","id":"sketch.line","env":"sketch","key":"1","press":"short"}"#,
803            ServerMessage::Command {
804                id: "sketch.line".into(),
805                env: "sketch".into(),
806                key: "1".into(),
807                press: Press::Short,
808            },
809        );
810        round_trip_server(
811            r#"{"type":"screen","png":"iVBORw0KGgo="}"#,
812            ServerMessage::Screen {
813                png: "iVBORw0KGgo=".into(),
814            },
815        );
816        round_trip_server(
817            r#"{"type":"device","device":null}"#,
818            ServerMessage::Device { device: None },
819        );
820        round_trip_server(
821            r#"{"type":"motion","t":[0,-12,3],"r":[5,0,0]}"#,
822            ServerMessage::Motion {
823                t: [0, -12, 3],
824                r: [5, 0, 0],
825            },
826        );
827        round_trip_server(
828            r#"{"type":"key","key":"t","id":3,"press":"long","down":true}"#,
829            ServerMessage::Key {
830                key: "t".into(),
831                id: 3,
832                press: Press::Long,
833                down: true,
834            },
835        );
836        round_trip_server(
837            r#"{"type":"lock","on":true}"#,
838            ServerMessage::Lock { on: true },
839        );
840    }
841
842    #[test]
843    fn client_messages_match_the_spec() {
844        let cases = [
845            (
846                r#"{"type":"hello","api":1,"client":"smectl"}"#,
847                ClientMessage::Hello {
848                    api: 1,
849                    client: "smectl".into(),
850                },
851            ),
852            (
853                r#"{"type":"set_lock","on":false}"#,
854                ClientMessage::SetLock { on: false },
855            ),
856            (r#"{"type":"get_state"}"#, ClientMessage::GetState),
857            (
858                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>"}"#,
859                ClientMessage::SetIcon {
860                    id: "line".into(),
861                    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()),
862                    png: None,
863                },
864            ),
865            (
866                r#"{"type":"set_commands","app":{"name":"SolidCraft","icon":"logo"},"commands":[{"id":"sketch.line","label":"Line","icon":"line"},{"id":"edit.undo","label":"Undo"}]}"#,
867                ClientMessage::SetCommands {
868                    app: App {
869                        name: "SolidCraft".into(),
870                        icon: Some("logo".into()),
871                    },
872                    commands: vec![
873                        Command {
874                            id: "sketch.line".into(),
875                            label: "Line".into(),
876                            icon: Some("line".into()),
877                        },
878                        Command {
879                            id: "edit.undo".into(),
880                            label: "Undo".into(),
881                            icon: None,
882                        },
883                    ],
884                },
885            ),
886            (
887                r#"{"type":"set_environments","environments":[{"id":"sketch","name":"Sketch","keys":{"1":"sketch.line","9":"edit.undo"}}]}"#,
888                ClientMessage::SetEnvironments {
889                    environments: vec![Environment {
890                        id: "sketch".into(),
891                        name: "Sketch".into(),
892                        keys: [("1", "sketch.line"), ("9", "edit.undo")]
893                            .into_iter()
894                            .map(|(k, v)| (k.into(), v.into()))
895                            .collect(),
896                        long_keys: BTreeMap::new(),
897                    }],
898                },
899            ),
900            (
901                r#"{"type":"set_environments","environments":[{"id":"sketch","name":"Sketch","keys":{"1":"sketch.line"},"long_keys":{"1":"sketch.rectangle"}}]}"#,
902                ClientMessage::SetEnvironments {
903                    environments: vec![
904                        Environment::new("sketch", "Sketch")
905                            .with_key("1", "sketch.line")
906                            .with_long_key("1", "sketch.rectangle"),
907                    ],
908                },
909            ),
910            (
911                r#"{"type":"set_unavailable","commands":["edit.undo"]}"#,
912                ClientMessage::SetUnavailable {
913                    commands: vec!["edit.undo".into()],
914                },
915            ),
916            (
917                r#"{"type":"hello","api":2,"client":"solidcraft"}"#,
918                ClientMessage::Hello {
919                    api: 2,
920                    client: "solidcraft".into(),
921                },
922            ),
923            (r#"{"type":"focus","on":true}"#, ClientMessage::Focus { on: true }),
924            (r#"{"type":"get_screen"}"#, ClientMessage::GetScreen),
925            (
926                r#"{"type":"set_environment","id":"part"}"#,
927                ClientMessage::SetEnvironment { id: "part".into() },
928            ),
929            (
930                r#"{"type":"set_lcd","brightness":40}"#,
931                ClientMessage::SetLcd {
932                    brightness: Some(40),
933                    text_size: None,
934                    theme: None,
935                },
936            ),
937        ];
938        for (line, message) in cases {
939            assert_eq!(
940                serde_json::from_str::<ClientMessage>(line).ok(),
941                Some(message.clone())
942            );
943            assert_eq!(to_line(&message), format!("{line}\n"));
944        }
945    }
946
947    #[test]
948    fn unknown_types_and_fields_are_ignored() {
949        assert_eq!(
950            serde_json::from_str::<ServerMessage>(r#"{"type":"osd","page":2}"#).ok(),
951            Some(ServerMessage::Unknown)
952        );
953        assert_eq!(
954            serde_json::from_str::<ServerMessage>(r#"{"type":"lock","on":true,"by":"key"}"#).ok(),
955            Some(ServerMessage::Lock { on: true })
956        );
957        assert_eq!(
958            serde_json::from_str::<ClientMessage>(r#"{"type":"set_osd"}"#).ok(),
959            Some(ClientMessage::Unknown)
960        );
961    }
962
963    /// A client on one end of a socket pair, and the other end as smed.
964    fn client_pair() -> (Client, std::io::BufReader<UnixStream>) {
965        let (ours, theirs) = UnixStream::pair().unwrap();
966        // A method that sends nothing fails `sent` instead of hanging it.
967        theirs
968            .set_read_timeout(Some(std::time::Duration::from_secs(5)))
969            .unwrap();
970        let client = Client {
971            lines: Lines::new(),
972            writer: ours,
973            api: API_VERSION,
974            server: String::new(),
975        };
976        (client, std::io::BufReader::new(theirs))
977    }
978
979    fn sent(smed: &mut std::io::BufReader<UnixStream>) -> String {
980        use std::io::BufRead;
981        let mut line = String::new();
982        smed.read_line(&mut line).unwrap();
983        line.trim_end().to_owned()
984    }
985
986    // The same lines as in client_messages_match_the_spec, from the Client methods and the
987    // constructors.
988    #[test]
989    fn client_methods_send_the_spec_lines() {
990        let (mut client, mut smed) = client_pair();
991        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>";
992        client.set_icon_svg("line", svg).unwrap();
993        assert_eq!(
994            sent(&mut smed),
995            format!(r#"{{"type":"set_icon","id":"line","svg":"{svg}"}}"#)
996        );
997        client
998            .set_commands(
999                &App::new("SolidCraft").with_icon("logo"),
1000                &[
1001                    Command::new("sketch.line", "Line").with_icon("line"),
1002                    Command::new("edit.undo", "Undo"),
1003                ],
1004            )
1005            .unwrap();
1006        assert_eq!(
1007            sent(&mut smed),
1008            r#"{"type":"set_commands","app":{"name":"SolidCraft","icon":"logo"},"commands":[{"id":"sketch.line","label":"Line","icon":"line"},{"id":"edit.undo","label":"Undo"}]}"#
1009        );
1010        client
1011            .set_environments(&[Environment::new("sketch", "Sketch")
1012                .with_key("9", "edit.undo")
1013                .with_key("1", "sketch.line")])
1014            .unwrap();
1015        assert_eq!(
1016            sent(&mut smed),
1017            r#"{"type":"set_environments","environments":[{"id":"sketch","name":"Sketch","keys":{"1":"sketch.line","9":"edit.undo"}}]}"#
1018        );
1019        client
1020            .set_environments(&[Environment::new("sketch", "Sketch")
1021                .with_key("1", "sketch.line")
1022                .with_long_key("1", "sketch.rectangle")])
1023            .unwrap();
1024        assert_eq!(
1025            sent(&mut smed),
1026            r#"{"type":"set_environments","environments":[{"id":"sketch","name":"Sketch","keys":{"1":"sketch.line"},"long_keys":{"1":"sketch.rectangle"}}]}"#
1027        );
1028        client.set_unavailable(&["edit.undo"]).unwrap();
1029        assert_eq!(
1030            sent(&mut smed),
1031            r#"{"type":"set_unavailable","commands":["edit.undo"]}"#
1032        );
1033        client.set_environment("part").unwrap();
1034        assert_eq!(sent(&mut smed), r#"{"type":"set_environment","id":"part"}"#);
1035        client.focus(true).unwrap();
1036        assert_eq!(sent(&mut smed), r#"{"type":"focus","on":true}"#);
1037        client.set_lcd(Some(40), None, None).unwrap();
1038        assert_eq!(sent(&mut smed), r#"{"type":"set_lcd","brightness":40}"#);
1039        client.get_screen().unwrap();
1040        assert_eq!(sent(&mut smed), r#"{"type":"get_screen"}"#);
1041        client.set_lock(true).unwrap();
1042        assert_eq!(sent(&mut smed), r#"{"type":"set_lock","on":true}"#);
1043        client.get_state().unwrap();
1044        assert_eq!(sent(&mut smed), r#"{"type":"get_state"}"#);
1045    }
1046
1047    #[test]
1048    fn the_limits_keep_their_values() {
1049        // docs/api.md: smed refuses a line longer than 262144 bytes.
1050        assert_eq!(MAX_MESSAGE, 262_144);
1051        // Public: an application may size its buffers by it. semver-checks sees no value change.
1052        assert_eq!(MAX_SERVER_LINE, 1_048_576);
1053    }
1054
1055    #[test]
1056    fn line_errors_say_what_went_wrong() {
1057        let invalid = LineError::Invalid {
1058            reason: "expected value".into(),
1059        };
1060        assert_eq!(
1061            invalid.to_string(),
1062            "a line that is not a message: expected value"
1063        );
1064        assert_eq!(
1065            LineError::Overlong.to_string(),
1066            "a line longer than 1048576 bytes"
1067        );
1068    }
1069
1070    #[test]
1071    fn png_icons_and_screens_are_base64() {
1072        const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
1073        let (mut client, mut smed) = client_pair();
1074        client.set_icon_png("logo", PNG_SIGNATURE).unwrap();
1075        assert_eq!(
1076            sent(&mut smed),
1077            r#"{"type":"set_icon","id":"logo","png":"iVBORw0KGgo="}"#
1078        );
1079        let screen = ServerMessage::Screen {
1080            png: "iVBORw0KGgo=".into(),
1081        };
1082        assert_eq!(screen.screen_png().as_deref(), Some(PNG_SIGNATURE));
1083        let broken = ServerMessage::Screen { png: "*".into() };
1084        assert_eq!(broken.screen_png(), None);
1085        assert_eq!(ServerMessage::Lock { on: true }.screen_png(), None);
1086    }
1087
1088    #[test]
1089    fn constructors_leave_the_optional_parts_empty() {
1090        assert_eq!(
1091            App::new("Example"),
1092            App {
1093                name: "Example".into(),
1094                icon: None
1095            }
1096        );
1097        assert_eq!(Command::new("a", "A").icon, None);
1098        assert!(Environment::new("e", "E").keys.is_empty());
1099        assert_eq!(
1100            DeviceInfo::new(0x256f, 0xc633, "SpaceMouse", Some("4.42".into())),
1101            DeviceInfo {
1102                vid: 0x256f,
1103                pid: 0xc633,
1104                name: "SpaceMouse".into(),
1105                firmware: Some("4.42".into()),
1106            }
1107        );
1108    }
1109
1110    #[test]
1111    fn a_line_split_by_a_read_timeout_arrives_whole() {
1112        let (mut client, smed) = client_pair();
1113        let mut smed = smed.into_inner();
1114        client
1115            .stream()
1116            .set_read_timeout(Some(std::time::Duration::from_millis(20)))
1117            .unwrap();
1118        smed.write_all(br#"{"type":"lock","#).unwrap();
1119        let timeout = client.next_message().unwrap_err();
1120        assert!(matches!(
1121            timeout.kind(),
1122            io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
1123        ));
1124        smed.write_all(b"\"on\":true}\n").unwrap();
1125        assert_eq!(
1126            client.next_message().unwrap(),
1127            Some(ServerMessage::Lock { on: true })
1128        );
1129        drop(smed);
1130        assert_eq!(client.next_message().unwrap(), None);
1131    }
1132
1133    #[test]
1134    fn lines_hands_out_whole_messages_in_order() {
1135        let mut lines = Lines::new();
1136        assert!(lines.is_empty());
1137        lines.push(b"\n  \n{\"type\":\"lock\",\"on\":true}\n{\"type\":\"osd\"}\n{\"type\":\"lo");
1138        assert_eq!(
1139            lines.next_message().unwrap(),
1140            Some(ServerMessage::Lock { on: true })
1141        );
1142        // The unknown type is skipped; the rest of the last line is still to come.
1143        assert_eq!(lines.next_message().unwrap(), None);
1144        assert!(!lines.is_empty());
1145        lines.push(b"ck\",\"on\":false}\n");
1146        assert_eq!(
1147            lines.next_message().unwrap(),
1148            Some(ServerMessage::Lock { on: false })
1149        );
1150        assert!(lines.is_empty());
1151    }
1152
1153    #[test]
1154    fn lines_reports_invalid_json_and_reads_on() {
1155        let mut lines = Lines::new();
1156        lines.push(b"not json\n{\"type\":\"lock\",\"on\":true}\n");
1157        let error = lines.next_message().unwrap_err();
1158        assert!(matches!(error, LineError::Invalid { .. }), "{error:?}");
1159        assert_eq!(
1160            lines.next_message().unwrap(),
1161            Some(ServerMessage::Lock { on: true })
1162        );
1163    }
1164
1165    #[test]
1166    fn lines_refuses_an_overlong_line() {
1167        let mut lines = Lines::new();
1168        // Exactly the limit, then the newline: accepted.
1169        let mut longest = br#"{"type":"screen","png":""#.to_vec();
1170        longest.resize(MAX_SERVER_LINE - 2, b'A');
1171        longest.extend_from_slice(b"\"}");
1172        assert_eq!(longest.len(), MAX_SERVER_LINE);
1173        lines.push(&longest);
1174        lines.push(b"\n");
1175        assert!(matches!(
1176            lines.next_message().unwrap(),
1177            Some(ServerMessage::Screen { .. })
1178        ));
1179        // One byte more, still without a newline: refused, and everything dropped.
1180        lines.push(&vec![b'x'; MAX_SERVER_LINE + 1]);
1181        assert_eq!(lines.next_message().unwrap_err(), LineError::Overlong);
1182        assert!(lines.is_empty());
1183        // One byte more with its newline in the same push: refused too.
1184        let mut over = vec![b' '; MAX_SERVER_LINE + 1];
1185        over.push(b'\n');
1186        lines.push(&over);
1187        assert_eq!(lines.next_message().unwrap_err(), LineError::Overlong);
1188    }
1189
1190    #[test]
1191    fn lines_looks_at_each_byte_once() {
1192        // The longest line, pushed in 4 KiB parts: each call looks only at the new part.
1193        let mut longest = br#"{"type":"screen","png":""#.to_vec();
1194        longest.resize(MAX_SERVER_LINE - 2, b'A');
1195        longest.extend_from_slice(b"\"}\n");
1196        let mut lines = Lines::new();
1197        let mut handed_out = 0;
1198        for part in longest.chunks(4096) {
1199            lines.push(part);
1200            if lines.scanned < lines.pending.len() {
1201                let before = lines.scanned;
1202                let message = lines.next_message().unwrap();
1203                if message.is_none() {
1204                    assert_eq!(lines.scanned, lines.pending.len());
1205                    assert!(before <= lines.scanned);
1206                } else {
1207                    assert!(matches!(message, Some(ServerMessage::Screen { .. })));
1208                    assert!(lines.is_empty());
1209                    handed_out += 1;
1210                }
1211            }
1212        }
1213        assert_eq!(handed_out, 1);
1214        // Each byte once: a search from the start of the buffer at every call would look at
1215        // about 128 times as many.
1216        assert_eq!(lines.looked, longest.len());
1217        // After a line, the bytes behind it are looked at afresh.
1218        lines.push(b"{\"type\":\"lock\",\"on\":true}\n{\"type\":\"lock\",\"on\":false}\n");
1219        assert_eq!(
1220            lines.next_message().unwrap(),
1221            Some(ServerMessage::Lock { on: true })
1222        );
1223        assert_eq!(
1224            lines.next_message().unwrap(),
1225            Some(ServerMessage::Lock { on: false })
1226        );
1227    }
1228
1229    #[test]
1230    fn client_reports_line_errors_as_invalid_data_with_the_line_error_inside() {
1231        let (mut client, smed) = client_pair();
1232        let mut smed = smed.into_inner();
1233        smed.write_all(b"not json\n").unwrap();
1234        let error = client.next_message().unwrap_err();
1235        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
1236        let inner = error
1237            .get_ref()
1238            .and_then(|inner| inner.downcast_ref::<LineError>());
1239        assert!(
1240            matches!(inner, Some(LineError::Invalid { .. })),
1241            "{error:?}"
1242        );
1243        smed.write_all(b"{\"type\":\"lock\",\"on\":true}\n")
1244            .unwrap();
1245        assert_eq!(
1246            client.next_message().unwrap(),
1247            Some(ServerMessage::Lock { on: true })
1248        );
1249    }
1250
1251    #[test]
1252    fn every_key_has_a_unique_id_and_name() {
1253        for (index, (id, name)) in KEYS.iter().enumerate() {
1254            assert_eq!(key_id(name), Some(*id));
1255            assert_eq!(key_name(*id), *name);
1256            assert!(
1257                KEYS[index + 1..]
1258                    .iter()
1259                    .all(|(other, n)| other != id && n != name)
1260            );
1261        }
1262        assert_eq!(key_name(LOCK_KEY_ID), "lock");
1263        assert_eq!(key_name(200), "id200");
1264    }
1265}