1#![forbid(unsafe_code)]
69
70#[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
84pub const API_VERSION: u32 = 2;
86
87pub const MAX_MESSAGE: usize = 256 * 1024;
89
90pub const SOCKET_IN_RUNTIME_DIR: &str = "smed/api.sock";
92
93pub 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
102#[non_exhaustive]
103pub struct DeviceInfo {
104 pub vid: u16,
105 pub pid: u16,
106 pub name: String,
108 pub firmware: Option<String>,
110}
111
112impl DeviceInfo {
113 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#[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#[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#[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#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
155#[non_exhaustive]
156pub struct App {
157 pub name: String,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub icon: Option<String>,
161}
162
163impl App {
164 pub fn new(name: impl Into<String>) -> Self {
166 Self {
167 name: name.into(),
168 icon: None,
169 }
170 }
171
172 pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
174 self.icon = Some(icon.into());
175 self
176 }
177}
178
179#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
181#[non_exhaustive]
182pub struct Command {
183 pub id: String,
184 pub label: String,
185 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub icon: Option<String>,
188}
189
190impl Command {
191 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 pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
202 self.icon = Some(icon.into());
203 self
204 }
205}
206
207#[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 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
219 pub long_keys: BTreeMap<String, String>,
220}
221
222impl Environment {
223 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 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 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
262 lcd: Option<bool>,
263 },
264 Device {
265 device: Option<DeviceInfo>,
266 },
267 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 Lcd {
283 owner: bool,
284 brightness: u8,
285 text_size: TextSize,
286 theme: Theme,
287 },
288 Command {
291 id: String,
292 env: String,
293 key: String,
294 press: Press,
295 },
296 Screen {
299 png: String,
300 },
301 Error {
302 message: String,
303 },
304 #[serde(other)]
306 Unknown,
307}
308
309impl ServerMessage {
310 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#[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 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 SetCommands {
343 app: App,
344 commands: Vec<Command>,
345 },
346 SetEnvironments {
348 environments: Vec<Environment>,
349 },
350 SetEnvironment {
352 id: String,
353 },
354 SetUnavailable {
357 commands: Vec<String>,
358 },
359 Focus {
361 on: bool,
362 },
363 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 GetScreen,
374 #[serde(other)]
376 Unknown,
377}
378
379pub 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
414pub const LOCK_KEY_ID: u8 = 27;
416
417pub 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
424pub fn key_id(name: &str) -> Option<u8> {
426 KEYS.iter()
427 .find(|(_, key_name)| *key_name == name)
428 .map(|(id, _)| *id)
429}
430
431pub fn to_line<T: Serialize>(message: &T) -> String {
433 let mut line = serde_json::to_string(message).unwrap_or_default();
435 line.push('\n');
436 line
437}
438
439pub const MAX_SERVER_LINE: usize = 1024 * 1024;
442
443#[derive(Clone, Debug, Default)]
458pub struct Lines {
459 pending: Vec<u8>,
460 scanned: usize,
462 #[cfg(test)]
465 looked: usize,
466}
467
468#[derive(Clone, Debug, PartialEq, Eq)]
470#[non_exhaustive]
471pub enum LineError {
472 #[non_exhaustive]
475 Invalid { reason: String },
476 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
492impl 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 pub fn new() -> Self {
502 Self::default()
503 }
504
505 pub fn push(&mut self, bytes: &[u8]) {
507 self.pending.extend_from_slice(bytes);
508 }
509
510 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 pub fn is_empty(&self) -> bool {
554 self.pending.is_empty()
555 }
556}
557
558pub struct Client {
560 lines: Lines,
561 writer: UnixStream,
562 pub api: u32,
564 pub server: String,
566}
567
568impl Client {
569 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 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 pub fn send(&mut self, message: &ClientMessage) -> io::Result<()> {
605 self.writer.write_all(to_line(message).as_bytes())
606 }
607
608 pub fn set_lock(&mut self, on: bool) -> io::Result<()> {
610 self.send(&ClientMessage::SetLock { on })
611 }
612
613 pub fn get_state(&mut self) -> io::Result<()> {
615 self.send(&ClientMessage::GetState)
616 }
617
618 pub fn focus(&mut self, on: bool) -> io::Result<()> {
621 self.send(&ClientMessage::Focus { on })
622 }
623
624 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 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 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 pub fn set_environments(&mut self, environments: &[Environment]) -> io::Result<()> {
653 self.send(&ClientMessage::SetEnvironments {
654 environments: environments.to_vec(),
655 })
656 }
657
658 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 pub fn set_environment(&mut self, id: &str) -> io::Result<()> {
669 self.send(&ClientMessage::SetEnvironment { id: id.to_owned() })
670 }
671
672 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 pub fn get_screen(&mut self) -> io::Result<()> {
690 self.send(&ClientMessage::GetScreen)
691 }
692
693 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 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 #[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 fn client_pair() -> (Client, std::io::BufReader<UnixStream>) {
965 let (ours, theirs) = UnixStream::pair().unwrap();
966 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 #[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 assert_eq!(MAX_MESSAGE, 262_144);
1051 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 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 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 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 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 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 assert_eq!(lines.looked, longest.len());
1217 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}