1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4use crate::GraphNode;
5
6pub const FLOAT_KIND: &str = "core.float";
7pub const INT_KIND: &str = "core.int";
8pub const UINT_KIND: &str = "core.uint";
9pub const BOOL_KIND: &str = "core.bool";
10pub const COLOR_KIND: &str = "core.color";
11pub const STRING_KIND: &str = "core.string";
12pub const BANG_KIND: &str = "core.bang";
13pub const MESSAGE_KIND: &str = "core.message";
14pub const COMMENT_KIND: &str = "core.comment";
15pub const PANEL_KIND: &str = "core.panel";
16pub const OPERATOR_ADD_KIND: &str = "core.operator.add";
17pub const OPERATOR_SUB_KIND: &str = "core.operator.sub";
18pub const OPERATOR_MUL_KIND: &str = "core.operator.mul";
19pub const OPERATOR_DIV_KIND: &str = "core.operator.div";
20pub const OPERATOR_POW_KIND: &str = "core.operator.pow";
21pub const OPERATOR_MIN_KIND: &str = "core.operator.min";
22pub const OPERATOR_MAX_KIND: &str = "core.operator.max";
23pub const OPERATOR_SQRT_KIND: &str = "core.operator.sqrt";
24
25pub const DEFAULT_FLOAT_REPRESENTATION: &str = "f32";
26pub const DEFAULT_INT_REPRESENTATION: &str = "i32";
27pub const DEFAULT_UINT_REPRESENTATION: &str = "u32";
28pub const DEFAULT_COLOR_REPRESENTATION: &str = "rgba32f";
29pub const DEFAULT_COLOR_SPACE: &str = "linear";
30
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32#[serde(tag = "type", rename_all = "camelCase")]
33pub enum ControlValue {
34 #[serde(rename = "float")]
35 Float { representation: String, value: f64 },
36 #[serde(rename = "int")]
37 Int { representation: String, value: i64 },
38 #[serde(rename = "uint")]
39 Uint { representation: String, value: u64 },
40 #[serde(rename = "bool")]
41 Bool { value: bool },
42 #[serde(rename = "string")]
43 String { value: String },
44 #[serde(rename = "color")]
45 Color {
46 representation: String,
47 #[serde(rename = "colorSpace", default = "default_color_space")]
48 color_space: String,
49 value: [f64; 4],
50 },
51}
52
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54#[serde(rename_all = "camelCase")]
55pub struct ControlMessage {
56 pub selector: String,
57 #[serde(default)]
58 pub atoms: Vec<ControlValue>,
59}
60
61impl ControlValue {
62 pub fn float(value: f64) -> Self {
63 Self::Float {
64 representation: DEFAULT_FLOAT_REPRESENTATION.to_owned(),
65 value,
66 }
67 }
68
69 pub fn int(value: i64) -> Self {
70 Self::Int {
71 representation: DEFAULT_INT_REPRESENTATION.to_owned(),
72 value,
73 }
74 }
75
76 pub fn uint(value: u64) -> Self {
77 Self::Uint {
78 representation: DEFAULT_UINT_REPRESENTATION.to_owned(),
79 value,
80 }
81 }
82
83 pub fn bool(value: bool) -> Self {
84 Self::Bool { value }
85 }
86
87 pub fn string(value: impl Into<String>) -> Self {
88 Self::String {
89 value: value.into(),
90 }
91 }
92
93 pub fn color(value: [f64; 4]) -> Self {
94 Self::Color {
95 representation: DEFAULT_COLOR_REPRESENTATION.to_owned(),
96 color_space: DEFAULT_COLOR_SPACE.to_owned(),
97 value,
98 }
99 }
100
101 pub(crate) fn for_node_default(node: &GraphNode) -> Option<Self> {
102 match node.kind.as_str() {
103 FLOAT_KIND => Some(Self::Float {
104 representation: read_representation_param(node, DEFAULT_FLOAT_REPRESENTATION),
105 value: read_f64_param(node).unwrap_or(0.0),
106 }),
107 INT_KIND => Some(Self::Int {
108 representation: read_representation_param(node, DEFAULT_INT_REPRESENTATION),
109 value: read_i64_param(node).unwrap_or(0),
110 }),
111 UINT_KIND => Some(Self::Uint {
112 representation: read_representation_param(node, DEFAULT_UINT_REPRESENTATION),
113 value: read_u64_param(node).unwrap_or(0),
114 }),
115 BOOL_KIND => Some(Self::bool(read_bool_param(node).unwrap_or(false))),
116 COLOR_KIND => Some(Self::Color {
117 representation: read_representation_param(node, DEFAULT_COLOR_REPRESENTATION),
118 color_space: read_color_space_param(node),
119 value: read_rgba_param(node).unwrap_or([1.0, 1.0, 1.0, 1.0]),
120 }),
121 STRING_KIND | MESSAGE_KIND => {
122 Some(Self::string(read_string_param(node).unwrap_or_default()))
123 }
124 COMMENT_KIND => Some(Self::string(
125 node.params
126 .get("text")
127 .and_then(Value::as_str)
128 .unwrap_or_default(),
129 )),
130 PANEL_KIND => Some(Self::string(
131 node.params
132 .get("color")
133 .and_then(Value::as_str)
134 .unwrap_or("transparent"),
135 )),
136 OPERATOR_ADD_KIND | OPERATOR_SUB_KIND | OPERATOR_MUL_KIND | OPERATOR_DIV_KIND
137 | OPERATOR_POW_KIND | OPERATOR_MIN_KIND | OPERATOR_MAX_KIND | OPERATOR_SQRT_KIND => {
138 Some(Self::float(0.0))
139 }
140 _ => None,
141 }
142 }
143
144 pub fn kind_label(&self) -> String {
145 match self {
146 Self::Float { representation, .. } => format!("number.float/{representation}"),
147 Self::Int { representation, .. } => format!("number.int/{representation}"),
148 Self::Uint { representation, .. } => format!("number.uint/{representation}"),
149 Self::Bool { .. } => "boolean".to_owned(),
150 Self::String { .. } => "string".to_owned(),
151 Self::Color { representation, .. } => format!("color/{representation}"),
152 }
153 }
154
155 pub fn matches_stored_type(&self, stored: &Self) -> bool {
156 matches!(
157 (self, stored),
158 (Self::Float { .. }, Self::Float { .. })
159 | (Self::Int { .. }, Self::Int { .. })
160 | (Self::Uint { .. }, Self::Uint { .. })
161 | (Self::Bool { .. }, Self::Bool { .. })
162 | (Self::String { .. }, Self::String { .. })
163 | (Self::Color { .. }, Self::Color { .. })
164 )
165 }
166
167 pub fn as_f32(&self) -> Option<f32> {
168 match self {
169 Self::Float { value, .. } => Some(sanitize_f64(*value) as f32),
170 _ => None,
171 }
172 }
173
174 pub fn as_i32(&self) -> Option<i32> {
175 match self {
176 Self::Int { value, .. } => {
177 Some((*value).clamp(i32::MIN as i64, i32::MAX as i64) as i32)
178 }
179 _ => None,
180 }
181 }
182
183 pub fn as_u32(&self) -> Option<u32> {
184 match self {
185 Self::Uint { value, .. } => Some((*value).min(u32::MAX as u64) as u32),
186 _ => None,
187 }
188 }
189
190 pub fn as_bool(&self) -> Option<bool> {
191 match self {
192 Self::Bool { value } => Some(*value),
193 _ => None,
194 }
195 }
196
197 pub fn as_rgba_f32(&self) -> Option<[f32; 4]> {
198 match self {
199 Self::Color { value, .. } => {
200 Some(value.map(|component| component.clamp(0.0, 1.0) as f32))
201 }
202 _ => None,
203 }
204 }
205}
206
207impl ControlMessage {
208 pub fn bang() -> Self {
209 Self {
210 selector: "bang".to_owned(),
211 atoms: Vec::new(),
212 }
213 }
214
215 pub fn from_value(value: ControlValue) -> Self {
216 let selector = match value {
217 ControlValue::Float { .. } => "float",
218 ControlValue::Int { .. } => "int",
219 ControlValue::Uint { .. } => "uint",
220 ControlValue::Bool { .. } => "bool",
221 ControlValue::String { .. } => "symbol",
222 ControlValue::Color { .. } => "color",
223 }
224 .to_owned();
225 Self {
226 selector,
227 atoms: vec![value],
228 }
229 }
230
231 pub fn parse_text(text: &str) -> Self {
232 let trimmed = text.trim();
233 if trimmed.is_empty() {
234 return Self {
235 selector: "symbol".to_owned(),
236 atoms: vec![ControlValue::string(String::new())],
237 };
238 }
239
240 let mut parts = trimmed.splitn(2, char::is_whitespace);
241 let selector = parts.next().unwrap_or_default();
242 let rest = parts.next().unwrap_or_default().trim();
243 match selector {
244 "bang" if rest.is_empty() => Self::bang(),
245 "set" => Self {
246 selector: "set".to_owned(),
247 atoms: parse_message_atoms(rest),
248 },
249 "float" => typed_or_generic_message(selector, rest, parse_float_atom),
250 "int" => typed_or_generic_message(selector, rest, parse_int_atom),
251 "uint" => typed_or_generic_message(selector, rest, parse_uint_atom),
252 "bool" => typed_or_generic_message(selector, rest, parse_bool_atom),
253 "symbol" => Self {
254 selector: "symbol".to_owned(),
255 atoms: vec![ControlValue::string(rest.to_owned())],
256 },
257 "color" => typed_or_generic_message(selector, rest, parse_color_atom),
258 "on" | "off" | "true" | "false" if rest.is_empty() => Self {
259 selector: selector.to_owned(),
260 atoms: Vec::new(),
261 },
262 _ if rest.is_empty() => {
263 if let Some(value) = parse_scalar_atom(trimmed) {
264 Self::from_value(value)
265 } else {
266 Self {
267 selector: "symbol".to_owned(),
268 atoms: vec![ControlValue::string(trimmed.to_owned())],
269 }
270 }
271 }
272 _ => Self {
273 selector: selector.to_owned(),
274 atoms: parse_message_atoms(rest),
275 },
276 }
277 }
278
279 pub fn first_atom(&self) -> Option<&ControlValue> {
280 self.atoms.first()
281 }
282
283 pub fn to_text(&self) -> String {
284 if self.atoms.is_empty() {
285 return self.selector.clone();
286 }
287 if self.atoms.len() == 1
288 && let Some(payload) = typed_atom_payload_to_text(&self.selector, &self.atoms[0])
289 {
290 return format!("{} {}", self.selector, payload);
291 }
292 format!(
293 "{} {}",
294 self.selector,
295 self.atoms
296 .iter()
297 .map(atom_to_text)
298 .collect::<Vec<_>>()
299 .join(" ")
300 )
301 }
302}
303
304fn parse_message_atoms(text: &str) -> Vec<ControlValue> {
305 if text.is_empty() {
306 return Vec::new();
307 }
308 let tokens = text.split_whitespace().collect::<Vec<_>>();
309 let mut atoms = Vec::new();
310 let mut index = 0usize;
311 while index < tokens.len() {
312 let token = tokens[index];
313 if token == "color"
314 && index + 4 < tokens.len()
315 && let Some(color) = parse_color_atom(&tokens[index + 1..index + 5].join(" "))
316 {
317 atoms.push(color);
318 index += 5;
319 continue;
320 }
321 atoms.push(
322 parse_scalar_atom(token).unwrap_or_else(|| ControlValue::string(token.to_owned())),
323 );
324 index += 1;
325 }
326 atoms
327}
328
329fn parse_scalar_atom(token: &str) -> Option<ControlValue> {
330 match token.to_ascii_lowercase().as_str() {
331 "true" | "on" => Some(ControlValue::bool(true)),
332 "false" | "off" => Some(ControlValue::bool(false)),
333 _ => token
334 .parse::<i64>()
335 .map(ControlValue::int)
336 .or_else(|_| token.parse::<f64>().map(ControlValue::float))
337 .ok(),
338 }
339}
340
341fn typed_or_generic_message(
342 selector: &str,
343 rest: &str,
344 parser: fn(&str) -> Option<ControlValue>,
345) -> ControlMessage {
346 parser(rest)
347 .map(ControlMessage::from_value)
348 .unwrap_or_else(|| ControlMessage {
349 selector: selector.to_owned(),
350 atoms: parse_message_atoms(rest),
351 })
352}
353
354fn parse_float_atom(text: &str) -> Option<ControlValue> {
355 let mut tokens = text.split_whitespace();
356 let token = tokens.next()?;
357 tokens.next().is_none().then_some(())?;
358 token.parse::<f64>().ok().map(ControlValue::float)
359}
360
361fn parse_int_atom(text: &str) -> Option<ControlValue> {
362 let mut tokens = text.split_whitespace();
363 let token = tokens.next()?;
364 tokens.next().is_none().then_some(())?;
365 token.parse::<i64>().ok().map(ControlValue::int)
366}
367
368fn parse_uint_atom(text: &str) -> Option<ControlValue> {
369 let mut tokens = text.split_whitespace();
370 let token = tokens.next()?;
371 tokens.next().is_none().then_some(())?;
372 token.parse::<u64>().ok().map(ControlValue::uint)
373}
374
375fn parse_bool_atom(text: &str) -> Option<ControlValue> {
376 let mut tokens = text.split_whitespace();
377 let token = tokens.next()?.to_ascii_lowercase();
378 tokens.next().is_none().then_some(())?;
379 match token.as_str() {
380 "1" | "on" | "true" => Some(ControlValue::bool(true)),
381 "0" | "off" | "false" => Some(ControlValue::bool(false)),
382 _ => None,
383 }
384}
385
386fn parse_color_atom(text: &str) -> Option<ControlValue> {
387 let tokens = text.split_whitespace().collect::<Vec<_>>();
388 let [r, g, b, a] = tokens.as_slice() else {
389 return None;
390 };
391 Some(ControlValue::color([
392 r.parse::<f64>().ok()?,
393 g.parse::<f64>().ok()?,
394 b.parse::<f64>().ok()?,
395 a.parse::<f64>().ok()?,
396 ]))
397}
398
399fn typed_atom_payload_to_text(selector: &str, atom: &ControlValue) -> Option<String> {
400 match (selector, atom) {
401 ("float", ControlValue::Float { value, .. }) => Some(value.to_string()),
402 ("int", ControlValue::Int { value, .. }) => Some(value.to_string()),
403 ("uint", ControlValue::Uint { value, .. }) => Some(value.to_string()),
404 ("bool", ControlValue::Bool { value }) => {
405 Some(if *value { "on" } else { "off" }.to_owned())
406 }
407 ("symbol", ControlValue::String { value }) => Some(value.clone()),
408 ("color", ControlValue::Color { value, .. }) => Some(format!(
409 "{} {} {} {}",
410 value[0], value[1], value[2], value[3]
411 )),
412 _ => None,
413 }
414}
415
416fn atom_to_text(atom: &ControlValue) -> String {
417 match atom {
418 ControlValue::Float { value, .. } => value.to_string(),
419 ControlValue::Int { value, .. } => value.to_string(),
420 ControlValue::Uint { value, .. } => value.to_string(),
421 ControlValue::Bool { value } => {
422 if *value {
423 "on".to_owned()
424 } else {
425 "off".to_owned()
426 }
427 }
428 ControlValue::String { value } => value.clone(),
429 ControlValue::Color { value, .. } => {
430 format!("color {} {} {} {}", value[0], value[1], value[2], value[3])
431 }
432 }
433}
434
435fn read_f64_param(node: &GraphNode) -> Option<f64> {
436 node.params.get("value").and_then(Value::as_f64)
437}
438
439fn read_i64_param(node: &GraphNode) -> Option<i64> {
440 node.params.get("value").and_then(Value::as_i64)
441}
442
443fn read_u64_param(node: &GraphNode) -> Option<u64> {
444 node.params.get("value").and_then(Value::as_u64)
445}
446
447fn read_bool_param(node: &GraphNode) -> Option<bool> {
448 node.params.get("value").and_then(Value::as_bool)
449}
450
451fn read_string_param(node: &GraphNode) -> Option<&str> {
452 node.params.get("value").and_then(Value::as_str)
453}
454
455fn read_representation_param(node: &GraphNode, default: &str) -> String {
456 node.params
457 .get("representation")
458 .and_then(Value::as_str)
459 .unwrap_or(default)
460 .to_owned()
461}
462
463fn read_color_space_param(node: &GraphNode) -> String {
464 node.params
465 .get("colorSpace")
466 .and_then(Value::as_str)
467 .unwrap_or(DEFAULT_COLOR_SPACE)
468 .to_owned()
469}
470
471fn read_rgba_param(node: &GraphNode) -> Option<[f64; 4]> {
472 let values = node.params.get("value")?.as_array()?;
473 let [r, g, b, a] = values.as_slice() else {
474 return None;
475 };
476 Some([r.as_f64()?, g.as_f64()?, b.as_f64()?, a.as_f64()?])
477}
478
479fn default_color_space() -> String {
480 DEFAULT_COLOR_SPACE.to_owned()
481}
482
483fn sanitize_f64(value: f64) -> f64 {
484 if value.is_finite() { value } else { 0.0 }
485}
486
487#[cfg(test)]
488mod tests {
489 use serde_json::{Map, json};
490
491 use super::*;
492
493 #[test]
494 fn serializes_control_values_with_canonical_type_labels() {
495 assert_eq!(
496 serde_json::to_value(ControlValue::float(32.0)).unwrap(),
497 json!({ "type": "float", "representation": "f32", "value": 32.0 })
498 );
499 assert_eq!(
500 serde_json::to_value(ControlValue::int(32)).unwrap(),
501 json!({ "type": "int", "representation": "i32", "value": 32 })
502 );
503 assert_eq!(
504 serde_json::to_value(ControlValue::uint(32)).unwrap(),
505 json!({ "type": "uint", "representation": "u32", "value": 32 })
506 );
507 assert_eq!(
508 serde_json::to_value(ControlValue::bool(true)).unwrap(),
509 json!({ "type": "bool", "value": true })
510 );
511 assert_eq!(
512 serde_json::to_value(ControlValue::string("ready".to_owned())).unwrap(),
513 json!({ "type": "string", "value": "ready" })
514 );
515 assert_eq!(
516 serde_json::to_value(ControlValue::color([0.1, 0.2, 0.3, 1.0])).unwrap(),
517 json!({
518 "type": "color",
519 "representation": "rgba32f",
520 "colorSpace": "linear",
521 "value": [0.1, 0.2, 0.3, 1.0]
522 })
523 );
524 }
525
526 #[test]
527 fn deserializes_color_with_default_color_space() {
528 assert_eq!(
529 serde_json::from_value::<ControlValue>(json!({
530 "type": "color",
531 "representation": "rgba32f",
532 "value": [0.1, 0.2, 0.3, 1.0]
533 }))
534 .unwrap(),
535 ControlValue::Color {
536 representation: "rgba32f".to_owned(),
537 color_space: "linear".to_owned(),
538 value: [0.1, 0.2, 0.3, 1.0],
539 }
540 );
541 }
542
543 #[test]
544 fn serializes_control_messages_with_selector_and_atoms() {
545 assert_eq!(
546 serde_json::to_value(ControlMessage::bang()).unwrap(),
547 json!({ "selector": "bang", "atoms": [] })
548 );
549 assert_eq!(
550 serde_json::to_value(ControlMessage::from_value(ControlValue::float(0.5))).unwrap(),
551 json!({
552 "selector": "float",
553 "atoms": [{ "type": "float", "representation": "f32", "value": 0.5 }]
554 })
555 );
556 assert_eq!(
557 ControlMessage::parse_text("set on"),
558 ControlMessage {
559 selector: "set".to_owned(),
560 atoms: vec![ControlValue::bool(true)]
561 }
562 );
563 }
564
565 #[test]
566 fn parses_and_formats_control_message_text() {
567 assert_eq!(
568 ControlMessage::parse_text(" "),
569 ControlMessage {
570 selector: "symbol".to_owned(),
571 atoms: vec![ControlValue::string(String::new())]
572 }
573 );
574 assert_eq!(
575 ControlMessage::parse_text("route 1 on label"),
576 ControlMessage {
577 selector: "route".to_owned(),
578 atoms: vec![
579 ControlValue::int(1),
580 ControlValue::bool(true),
581 ControlValue::string("label".to_owned())
582 ]
583 }
584 );
585 assert_eq!(
586 ControlMessage::parse_text("set"),
587 ControlMessage {
588 selector: "set".to_owned(),
589 atoms: Vec::new()
590 }
591 );
592 assert_eq!(ControlMessage::bang().to_text(), "bang");
593 assert_eq!(
594 ControlMessage::from_value(ControlValue::string("ready".to_owned())).to_text(),
595 "symbol ready"
596 );
597 assert_eq!(
598 ControlMessage::from_value(ControlValue::uint(9)).to_text(),
599 "uint 9"
600 );
601 assert_eq!(
602 ControlMessage::from_value(ControlValue::int(-7)).to_text(),
603 "int -7"
604 );
605 assert_eq!(
606 ControlMessage::from_value(ControlValue::bool(true)).to_text(),
607 "bool on"
608 );
609 assert_eq!(
610 ControlMessage::from_value(ControlValue::bool(false)).to_text(),
611 "bool off"
612 );
613 assert_eq!(
614 ControlMessage::from_value(ControlValue::color([1.0, 0.5, 0.25, 1.0])).to_text(),
615 "color 1 0.5 0.25 1"
616 );
617 assert_eq!(
618 ControlMessage::parse_text("color 1 0.5 0.25 1"),
619 ControlMessage::from_value(ControlValue::color([1.0, 0.5, 0.25, 1.0]))
620 );
621 assert_eq!(
622 ControlMessage::parse_text("set color 1 0.5 0.25 1"),
623 ControlMessage {
624 selector: "set".to_owned(),
625 atoms: vec![ControlValue::color([1.0, 0.5, 0.25, 1.0])]
626 }
627 );
628 assert_eq!(
629 ControlMessage::parse_text("symbol hello world"),
630 ControlMessage {
631 selector: "symbol".to_owned(),
632 atoms: vec![ControlValue::string("hello world".to_owned())]
633 }
634 );
635 assert_eq!(
636 ControlMessage::parse_text("float 1.25"),
637 ControlMessage::from_value(ControlValue::float(1.25))
638 );
639 assert_eq!(
640 ControlMessage::parse_text("int -12"),
641 ControlMessage::from_value(ControlValue::int(-12))
642 );
643 assert_eq!(
644 ControlMessage::parse_text("uint 12"),
645 ControlMessage::from_value(ControlValue::uint(12))
646 );
647 assert_eq!(
648 ControlMessage::parse_text("bool off"),
649 ControlMessage::from_value(ControlValue::bool(false))
650 );
651 assert_eq!(
652 ControlMessage::parse_text("float 1 2"),
653 ControlMessage {
654 selector: "float".to_owned(),
655 atoms: vec![ControlValue::int(1), ControlValue::int(2)]
656 }
657 );
658 assert_eq!(
659 ControlMessage::parse_text("int nope"),
660 ControlMessage {
661 selector: "int".to_owned(),
662 atoms: vec![ControlValue::string("nope".to_owned())]
663 }
664 );
665 assert_eq!(
666 ControlMessage::parse_text("uint -1"),
667 ControlMessage {
668 selector: "uint".to_owned(),
669 atoms: vec![ControlValue::int(-1)]
670 }
671 );
672 assert_eq!(
673 ControlMessage::parse_text("bool maybe"),
674 ControlMessage {
675 selector: "bool".to_owned(),
676 atoms: vec![ControlValue::string("maybe".to_owned())]
677 }
678 );
679 assert_eq!(
680 ControlMessage::parse_text("color 1 2 3"),
681 ControlMessage {
682 selector: "color".to_owned(),
683 atoms: vec![
684 ControlValue::int(1),
685 ControlValue::int(2),
686 ControlValue::int(3)
687 ]
688 }
689 );
690 assert_eq!(
691 (ControlMessage {
692 selector: "list".to_owned(),
693 atoms: vec![
694 ControlValue::float(1.5),
695 ControlValue::uint(2),
696 ControlValue::bool(true),
697 ControlValue::bool(false),
698 ControlValue::string("label".to_owned()),
699 ControlValue::color([0.1, 0.2, 0.3, 1.0])
700 ]
701 })
702 .to_text(),
703 "list 1.5 2 on off label color 0.1 0.2 0.3 1"
704 );
705 }
706
707 #[test]
708 fn derives_default_value_from_graph_node_params() {
709 assert_eq!(
710 ControlValue::for_node_default(&node(FLOAT_KIND, json!(1.5))),
711 Some(ControlValue::float(1.5))
712 );
713 assert_eq!(
714 ControlValue::for_node_default(&node(INT_KIND, json!(7))),
715 Some(ControlValue::int(7))
716 );
717 assert_eq!(
718 ControlValue::for_node_default(&node(UINT_KIND, json!(7))),
719 Some(ControlValue::uint(7))
720 );
721 assert_eq!(
722 ControlValue::for_node_default(&node(BOOL_KIND, json!(true))),
723 Some(ControlValue::bool(true))
724 );
725 assert_eq!(
726 ControlValue::for_node_default(&node(COLOR_KIND, json!([0.1, 0.2, 0.3, 1.0]))),
727 Some(ControlValue::color([0.1, 0.2, 0.3, 1.0]))
728 );
729 assert_eq!(
730 ControlValue::for_node_default(&node(STRING_KIND, json!("ready"))),
731 Some(ControlValue::string("ready".to_owned()))
732 );
733 assert_eq!(
734 ControlValue::for_node_default(&node(BOOL_KIND, json!(true))),
735 Some(ControlValue::bool(true))
736 );
737 assert_eq!(
738 ControlValue::for_node_default(&node(MESSAGE_KIND, json!("perform"))),
739 Some(ControlValue::string("perform".to_owned()))
740 );
741 let mut comment = node(COMMENT_KIND, json!(null));
742 comment.params.insert("text".to_owned(), json!("note"));
743 assert_eq!(
744 ControlValue::for_node_default(&comment),
745 Some(ControlValue::string("note".to_owned()))
746 );
747 let mut panel = node(PANEL_KIND, json!(null));
748 panel.params.insert("color".to_owned(), json!("#00ff00"));
749 assert_eq!(
750 ControlValue::for_node_default(&panel),
751 Some(ControlValue::string("#00ff00".to_owned()))
752 );
753 assert_eq!(
754 ControlValue::for_node_default(&node(FLOAT_KIND, json!(0.75))),
755 Some(ControlValue::float(0.75))
756 );
757 assert_eq!(
758 ControlValue::for_node_default(&node(BOOL_KIND, json!(true))),
759 Some(ControlValue::bool(true))
760 );
761 }
762
763 #[test]
764 fn invalid_or_missing_params_use_type_defaults() {
765 assert_eq!(
766 ControlValue::for_node_default(&node(FLOAT_KIND, json!("bad"))),
767 Some(ControlValue::float(0.0))
768 );
769 assert_eq!(
770 ControlValue::for_node_default(&node(INT_KIND, json!(1.25))),
771 Some(ControlValue::int(0))
772 );
773 assert_eq!(
774 ControlValue::for_node_default(&node(UINT_KIND, json!(-1))),
775 Some(ControlValue::uint(0))
776 );
777 assert_eq!(
778 ControlValue::for_node_default(&node(BOOL_KIND, json!("bad"))),
779 Some(ControlValue::bool(false))
780 );
781 assert_eq!(
782 ControlValue::for_node_default(&node(COLOR_KIND, json!([0.1, 0.2]))),
783 Some(ControlValue::color([1.0, 1.0, 1.0, 1.0]))
784 );
785 assert_eq!(
786 ControlValue::for_node_default(&node(STRING_KIND, json!(false))),
787 Some(ControlValue::string(String::new()))
788 );
789 assert_eq!(
790 ControlValue::for_node_default(&node(COMMENT_KIND, json!(null))),
791 Some(ControlValue::string(String::new()))
792 );
793 assert_eq!(
794 ControlValue::for_node_default(&node(PANEL_KIND, json!(null))),
795 Some(ControlValue::string("transparent".to_owned()))
796 );
797 }
798
799 #[test]
800 fn matches_only_stored_value_types() {
801 assert!(ControlValue::float(1.0).matches_stored_type(&ControlValue::float(0.0)));
802 assert!(ControlValue::int(1).matches_stored_type(&ControlValue::int(0)));
803 assert!(ControlValue::bool(true).matches_stored_type(&ControlValue::bool(false)));
804 assert!(
805 ControlValue::string("a".to_owned())
806 .matches_stored_type(&ControlValue::string("b".to_owned()))
807 );
808 assert!(
809 ControlValue::color([1.0, 0.0, 0.0, 1.0])
810 .matches_stored_type(&ControlValue::color([0.0, 0.0, 0.0, 1.0]))
811 );
812 assert!(!ControlValue::float(1.0).matches_stored_type(&ControlValue::int(1)));
813 }
814
815 #[test]
816 fn reports_kind_labels_for_diagnostics() {
817 assert_eq!(ControlValue::float(1.0).kind_label(), "number.float/f32");
818 assert_eq!(ControlValue::int(1).kind_label(), "number.int/i32");
819 assert_eq!(ControlValue::uint(1).kind_label(), "number.uint/u32");
820 assert_eq!(ControlValue::bool(true).kind_label(), "boolean");
821 assert_eq!(ControlValue::string("x".to_owned()).kind_label(), "string");
822 assert_eq!(
823 ControlValue::color([0.0, 0.0, 0.0, 1.0]).kind_label(),
824 "color/rgba32f"
825 );
826 assert_eq!(ControlMessage::bang().selector, "bang");
827 }
828
829 #[test]
830 fn converts_shader_values() {
831 assert_eq!(ControlValue::float(1.25).as_f32(), Some(1.25));
832 assert_eq!(ControlValue::float(f64::NAN).as_f32(), Some(0.0));
833 assert_eq!(ControlValue::int(i64::MAX).as_i32(), Some(i32::MAX));
834 assert_eq!(ControlValue::uint(u64::MAX).as_u32(), Some(u32::MAX));
835 assert_eq!(ControlValue::bool(true).as_bool(), Some(true));
836 assert_eq!(
837 ControlValue::color([-1.0, 0.25, 2.0, 1.0]).as_rgba_f32(),
838 Some([0.0, 0.25, 1.0, 1.0])
839 );
840 assert_eq!(ControlValue::bool(false).as_f32(), None);
841 assert_eq!(ControlValue::bool(false).as_i32(), None);
842 assert_eq!(ControlValue::bool(false).as_u32(), None);
843 assert_eq!(ControlValue::float(0.0).as_rgba_f32(), None);
844 assert_eq!(ControlValue::float(0.0).as_bool(), None);
845 }
846
847 fn node(kind: &str, value: serde_json::Value) -> GraphNode {
848 let mut params = Map::new();
849 params.insert("value".to_owned(), value);
850 GraphNode {
851 id: "value_1".to_owned(),
852 kind: kind.to_owned(),
853 kind_version: "0.1.0".to_owned(),
854 params,
855 ports: Vec::new(),
856 }
857 }
858}