Skip to main content

rodecaster_protocol/
change_frame.rs

1//! JUCE `ValueTreeSynchroniser` change-frame encoder and decoder.
2//!
3//! Handles low-level incremental change messages such as property modifications
4//! and child node additions or removals.
5
6use crate::juce_var::{write_compressed_int, Reader, Value};
7use crate::valuetree::{parse_node, Node};
8
9const PROPERTY_CHANGED: u8 = 1;
10const FULL_SYNC: u8 = 2;
11const CHILD_ADDED: u8 = 3;
12const CHILD_REMOVED: u8 = 4;
13const CHILD_MOVED: u8 = 5;
14const PROPERTY_REMOVED: u8 = 6;
15
16/// A decoded ValueTree change frame.
17#[derive(Debug, Clone, PartialEq)]
18pub enum ChangeFrame {
19    PropertyChanged {
20        path: Vec<u32>,
21        name: String,
22        value: Value,
23    },
24    PropertyRemoved {
25        path: Vec<u32>,
26        name: String,
27    },
28    ChildAdded {
29        path: Vec<u32>,
30        index: u32,
31        subtree: Node,
32    },
33    ChildRemoved {
34        path: Vec<u32>,
35        old_index: u32,
36    },
37    ChildMoved {
38        path: Vec<u32>,
39        old_index: u32,
40        new_index: u32,
41    },
42    FullSync {
43        root: Node,
44    },
45}
46
47impl ChangeFrame {
48    /// Path component of the change, if any (empty for `FullSync`).
49    pub fn path(&self) -> &[u32] {
50        match self {
51            ChangeFrame::PropertyChanged { path, .. }
52            | ChangeFrame::PropertyRemoved { path, .. }
53            | ChangeFrame::ChildAdded { path, .. }
54            | ChangeFrame::ChildRemoved { path, .. }
55            | ChangeFrame::ChildMoved { path, .. } => path,
56            ChangeFrame::FullSync { .. } => &[],
57        }
58    }
59
60    /// True if the change alters tree topology.
61    pub fn is_structural(&self) -> bool {
62        matches!(
63            self,
64            ChangeFrame::ChildAdded { .. }
65                | ChangeFrame::ChildRemoved { .. }
66                | ChangeFrame::ChildMoved { .. }
67                | ChangeFrame::FullSync { .. }
68        )
69    }
70}
71
72/// Decode a change-frame payload.
73pub fn decode(payload: &[u8]) -> Option<ChangeFrame> {
74    let mut reader = Reader::new(payload);
75    let change_type = reader.read_u8()?;
76    let frame = match change_type {
77        PROPERTY_CHANGED => {
78            let path = read_path(&mut reader)?;
79            let name = reader.read_cstring()?.to_string();
80            let value = reader.read_value()?;
81            ChangeFrame::PropertyChanged { path, name, value }
82        }
83        FULL_SYNC => {
84            let root = parse_node(&mut reader)?;
85            ChangeFrame::FullSync { root }
86        }
87        CHILD_ADDED => {
88            let path = read_path(&mut reader)?;
89            let index = read_compint_u32(&mut reader)?;
90            let subtree = parse_node(&mut reader)?;
91            ChangeFrame::ChildAdded {
92                path,
93                index,
94                subtree,
95            }
96        }
97        CHILD_REMOVED => {
98            let path = read_path(&mut reader)?;
99            let old_index = read_compint_u32(&mut reader)?;
100            ChangeFrame::ChildRemoved { path, old_index }
101        }
102        CHILD_MOVED => {
103            let path = read_path(&mut reader)?;
104            let old_index = read_compint_u32(&mut reader)?;
105            let new_index = read_compint_u32(&mut reader)?;
106            ChangeFrame::ChildMoved {
107                path,
108                old_index,
109                new_index,
110            }
111        }
112        PROPERTY_REMOVED => {
113            let path = read_path(&mut reader)?;
114            let name = reader.read_cstring()?.to_string();
115            ChangeFrame::PropertyRemoved { path, name }
116        }
117        _ => return None,
118    };
119    (reader.remaining() == 0).then_some(frame)
120}
121
122/// Encode a complete `fullSync` change-frame payload.
123pub fn encode_full_sync(root: &Node) -> Vec<u8> {
124    let mut out = Vec::new();
125    out.push(FULL_SYNC);
126    root.write_to_stream(&mut out);
127    out
128}
129
130/// Encode a `propertyChanged` frame.
131pub fn encode_property_changed(path: &[u32], prop_name: &str, value: &Value) -> Vec<u8> {
132    let mut out = Vec::with_capacity(8 + prop_name.len() + 16);
133    out.push(PROPERTY_CHANGED);
134    write_compressed_int(&mut out, path.len() as i64);
135    for &p in path {
136        write_compressed_int(&mut out, p as i64);
137    }
138    out.extend_from_slice(prop_name.as_bytes());
139    out.push(0);
140    value.write_to_stream(&mut out);
141    out
142}
143
144fn read_path(reader: &mut Reader) -> Option<Vec<u32>> {
145    let n = reader.read_compressed_int()?;
146    if n < 0 {
147        return None;
148    }
149    let n = n as usize;
150    let cap = n.min(reader.remaining());
151    let mut path = Vec::with_capacity(cap);
152    for _ in 0..n {
153        path.push(read_compint_u32(reader)?);
154    }
155    Some(path)
156}
157
158fn read_compint_u32(reader: &mut Reader) -> Option<u32> {
159    let v = reader.read_compressed_int()?;
160    if v < 0 {
161        return None;
162    }
163    u32::try_from(v).ok()
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    use crate::valuetree::Property;
170
171    /// PropertyChanged for `mixLevelWithAnchor` with path = [217] (single-level).
172    /// This is the exact vector the existing parser test uses, rebuilt as a
173    /// change-frame payload (`[01]` + path + `[name\0]` + var).
174    #[test]
175    fn decodes_property_changed_mix_level() {
176        let bytes = [
177            0x01, // changeType propertyChanged
178            0x01, 0x01, // writeCompressedInt(1) -> nLevels = 1
179            0x01, 0xd9, // writeCompressedInt(217) -> path[0] = 217
180            b'm', b'i', b'x', b'L', b'e', b'v', b'e', b'l', b'W', b'i', b't', b'h', b'A', b'n',
181            b'c', b'h', b'o', b'r', 0x00, // property name
182            0x01, 0x13, 0x05, b'0', b'.', b'4', b'7', b'2', b'4', b'4', b'1', b'|', b'0', b'.',
183            b'4', b'7', b'2', b'4', b'4', b'1', 0x00, // var String
184        ];
185
186        let frame = decode(&bytes).expect("decodes");
187        match frame {
188            ChangeFrame::PropertyChanged { path, name, value } => {
189                assert_eq!(path, vec![217]);
190                assert_eq!(name, "mixLevelWithAnchor");
191                assert_eq!(value, Value::String("0.472441|0.472441".to_string()));
192            }
193            other => panic!("expected PropertyChanged, got {other:?}"),
194        }
195    }
196
197    /// PropertyChanged for `faderLevel` with path = [0, 4+f] (two-level), the
198    /// exact preamble the existing FaderLevel encoder emits.
199    #[test]
200    fn decodes_property_changed_fader_level_two_level_path() {
201        // [01] type + writeCompressedInt(2) + writeCompressedInt(0) + writeCompressedInt(4+3)
202        // + "faderLevel\0" + var Int 75
203        let bytes = [
204            0x01, // propertyChanged
205            0x01, 0x02, // nLevels = 2
206            0x00, // path[0] = 0  (writeCompressedInt(0) is a single zero byte)
207            0x01, 0x07, // path[1] = 7  (4 + fader=3)
208            b'f', b'a', b'd', b'e', b'r', b'L', b'e', b'v', b'e', b'l', 0x00, // property name
209            0x01, 0x05, 0x01, 0x4b, 0x00, 0x00, 0x00, // var Int 75
210        ];
211
212        let frame = decode(&bytes).expect("decodes");
213        match frame {
214            ChangeFrame::PropertyChanged { path, name, value } => {
215                assert_eq!(path, vec![0, 7]);
216                assert_eq!(name, "faderLevel");
217                assert_eq!(value, Value::Int(75));
218            }
219            other => panic!("expected PropertyChanged, got {other:?}"),
220        }
221    }
222
223    #[test]
224    fn round_trips_property_changed_single_level() {
225        let bytes = encode_property_changed(&[217], "mixLevelWithAnchor", &Value::Bool(true));
226        let frame = decode(&bytes).expect("decodes");
227        assert_eq!(
228            frame,
229            ChangeFrame::PropertyChanged {
230                path: vec![217],
231                name: "mixLevelWithAnchor".to_string(),
232                value: Value::Bool(true),
233            }
234        );
235    }
236
237    #[test]
238    fn round_trips_property_changed_two_level() {
239        let bytes = encode_property_changed(&[0, 7], "faderLevel", &Value::Int(75));
240        let frame = decode(&bytes).expect("decodes");
241        assert_eq!(
242            frame,
243            ChangeFrame::PropertyChanged {
244                path: vec![0, 7],
245                name: "faderLevel".to_string(),
246                value: Value::Int(75),
247            }
248        );
249    }
250
251    #[test]
252    fn round_trips_property_changed_empty_path() {
253        // Change at root has no path entries.
254        let bytes = encode_property_changed(&[], "rootProp", &Value::Bool(false));
255        let frame = decode(&bytes).expect("decodes");
256        assert_eq!(
257            frame,
258            ChangeFrame::PropertyChanged {
259                path: vec![],
260                name: "rootProp".to_string(),
261                value: Value::Bool(false),
262            }
263        );
264    }
265
266    #[test]
267    fn full_sync_round_trips_via_encoder() {
268        let root = Node {
269            name: "ROOT".to_string(),
270            properties: vec![],
271            children: vec![Node {
272                name: "CHILD".to_string(),
273                properties: vec![],
274                children: vec![],
275            }],
276        };
277        let payload = encode_full_sync(&root);
278        assert_eq!(decode(&payload), Some(ChangeFrame::FullSync { root }));
279    }
280
281    #[test]
282    fn decodes_full_sync_minimal() {
283        // [02] + ValueTree stream of <ROOT/> (name + 0 props + 0 children).
284        let bytes = [
285            0x02, // fullSync
286            b'R', b'O', b'O', b'T', 0x00, // node name "ROOT\0"
287            0x00, // property count = 0 (writeCompressedInt(0))
288            0x00, // child count = 0
289        ];
290
291        let frame = decode(&bytes).expect("decodes");
292        match frame {
293            ChangeFrame::FullSync { root } => {
294                assert_eq!(root.name, "ROOT");
295                assert!(root.properties.is_empty());
296                assert!(root.children.is_empty());
297            }
298            other => panic!("expected FullSync, got {other:?}"),
299        }
300    }
301
302    #[test]
303    fn decodes_property_removed() {
304        let bytes = [
305            0x06, // propertyRemoved
306            0x01, 0x01, 0x01, 0x05, // path = [5]
307            b'g', b'o', b'n', b'e', 0x00,
308        ];
309        let frame = decode(&bytes).expect("decodes");
310        assert_eq!(
311            frame,
312            ChangeFrame::PropertyRemoved {
313                path: vec![5],
314                name: "gone".to_string(),
315            }
316        );
317    }
318
319    #[test]
320    fn decodes_child_removed() {
321        let bytes = [
322            0x04, // childRemoved
323            0x01, 0x01, 0x01, 0x02, // path = [2]
324            0x01, 0x03, // oldIndex = 3
325        ];
326        let frame = decode(&bytes).expect("decodes");
327        assert_eq!(
328            frame,
329            ChangeFrame::ChildRemoved {
330                path: vec![2],
331                old_index: 3,
332            }
333        );
334    }
335
336    #[test]
337    fn decodes_child_moved() {
338        let bytes = [
339            0x05, // childMoved
340            0x01, 0x01, 0x01, 0x02, // path = [2]
341            0x01, 0x01, // oldIndex = 1
342            0x01, 0x04, // newIndex = 4
343        ];
344        let frame = decode(&bytes).expect("decodes");
345        assert_eq!(
346            frame,
347            ChangeFrame::ChildMoved {
348                path: vec![2],
349                old_index: 1,
350                new_index: 4,
351            }
352        );
353    }
354
355    #[test]
356    fn decodes_child_added_with_subtree() {
357        let bytes = [
358            0x03, // childAdded
359            0x01, 0x01, 0x01, 0x02, // path = [2]
360            0x01, 0x00, // index = 0
361            // ValueTree stream of <NEW prop=Int(7)/>
362            b'N', b'E', b'W', 0x00, // name
363            0x01, 0x01, // property count = 1
364            b'p', b'r', b'o', b'p', 0x00, // property name
365            0x01, 0x05, 0x01, 0x07, 0x00, 0x00, 0x00, // var Int 7
366            0x00, // child count = 0
367        ];
368        let frame = decode(&bytes).expect("decodes");
369        match frame {
370            ChangeFrame::ChildAdded {
371                path,
372                index,
373                subtree,
374            } => {
375                assert_eq!(path, vec![2]);
376                assert_eq!(index, 0);
377                assert_eq!(subtree.name, "NEW");
378                assert_eq!(
379                    subtree.properties,
380                    vec![Property {
381                        name: "prop".to_string(),
382                        value: Value::Int(7),
383                    }]
384                );
385                assert!(subtree.children.is_empty());
386            }
387            other => panic!("expected ChildAdded, got {other:?}"),
388        }
389    }
390
391    #[test]
392    fn structural_flag_matches_expectations() {
393        let pc = ChangeFrame::PropertyChanged {
394            path: vec![],
395            name: String::new(),
396            value: Value::Undefined,
397        };
398        let pr = ChangeFrame::PropertyRemoved {
399            path: vec![],
400            name: String::new(),
401        };
402        let ca = ChangeFrame::ChildAdded {
403            path: vec![],
404            index: 0,
405            subtree: Node {
406                name: String::new(),
407                properties: vec![],
408                children: vec![],
409            },
410        };
411        let cr = ChangeFrame::ChildRemoved {
412            path: vec![],
413            old_index: 0,
414        };
415        let cm = ChangeFrame::ChildMoved {
416            path: vec![],
417            old_index: 0,
418            new_index: 0,
419        };
420        let fs = ChangeFrame::FullSync {
421            root: Node {
422                name: String::new(),
423                properties: vec![],
424                children: vec![],
425            },
426        };
427
428        assert!(!pc.is_structural());
429        assert!(!pr.is_structural());
430        assert!(ca.is_structural());
431        assert!(cr.is_structural());
432        assert!(cm.is_structural());
433        assert!(fs.is_structural());
434    }
435
436    #[test]
437    fn rejects_empty_payload() {
438        assert_eq!(decode(&[]), None);
439    }
440
441    #[test]
442    fn rejects_unknown_change_type() {
443        assert_eq!(decode(&[0xff]), None);
444    }
445}