flutmax-objdb 0.1.0

Max object definition database parsed from .maxref.xml refpages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
pub mod parser;

use std::collections::HashMap;

/// Port (inlet/outlet) type for Max objects
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PortType {
    /// Signal only (audio rate only)
    Signal,
    /// Signal + Float dual (controlled by float when no signal connection)
    SignalFloat,
    /// Int + Signal dual
    IntSignal,
    /// Float only
    Float,
    /// Int only
    Int,
    /// Bang only
    Bang,
    /// List only
    List,
    /// Symbol only
    Symbol,
    /// Any message (bang, int, float, list, symbol)
    Any,
    /// Multi-channel signal
    MultiChannelSignal,
    /// Multi-channel signal + float
    MultiChannelSignalFloat,
    /// Depends on argument type (placeholder for variable objects)
    Dynamic,
    /// Inactive inlet/outlet
    Inactive,
}

impl PortType {
    /// Convert XML type attribute string to PortType.
    /// Normalizes case differences and notation variants (/, " or ", ", ").
    pub fn from_xml_type(type_str: &str) -> Self {
        let normalized = type_str
            .to_lowercase()
            .replace(" / ", "/")
            .replace(", ", "/")
            .replace(" or ", "/");
        let normalized = normalized.trim();

        match normalized {
            "signal" => PortType::Signal,
            "signal/float" | "float/signal" | "signal/float/symbol" | "signal/float/timevalue" => {
                PortType::SignalFloat
            }
            "int/signal" | "signal/int" => PortType::IntSignal,
            "float" | "double" => PortType::Float,
            "int" | "long" | "int/voice" => PortType::Int,
            "bang" => PortType::Bang,
            "list" => PortType::List,
            "symbol" => PortType::Symbol,
            "anything" | "message" | "bang/int" | "bang/anything" | "int/float"
            | "int/float/list" | "int/list" | "float/list" | "int/float/sig" | "signal/msg"
            | "signal/message" | "signal/list" | "dictionary" | "dict" | "setvalue"
            | "midievent" | "matrix" => PortType::Any,
            "multi-channel signal" | "signal/multi-channel signal" => PortType::MultiChannelSignal,
            "multi-channel signal/float" | "multi-channel signal/message" => {
                PortType::MultiChannelSignalFloat
            }
            "inlet_type" | "outlet_type" | "objarg_type" => PortType::Dynamic,
            "inactive" => PortType::Inactive,
            "" => PortType::Any,
            _ => PortType::Any,
        }
    }

    /// Whether this port accepts Signal
    pub fn accepts_signal(&self) -> bool {
        matches!(
            self,
            PortType::Signal
                | PortType::SignalFloat
                | PortType::IntSignal
                | PortType::MultiChannelSignal
                | PortType::MultiChannelSignalFloat
        )
    }

    /// Whether this port accepts Control messages
    pub fn accepts_control(&self) -> bool {
        matches!(
            self,
            PortType::SignalFloat
                | PortType::IntSignal
                | PortType::Float
                | PortType::Int
                | PortType::Bang
                | PortType::List
                | PortType::Symbol
                | PortType::Any
                | PortType::Dynamic
                | PortType::MultiChannelSignalFloat
        )
    }
}

/// Module type
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Module {
    Max,
    Msp,
    Other(String),
}

impl Module {
    pub fn parse(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "max" => Module::Max,
            "msp" => Module::Msp,
            other => Module::Other(other.to_string()),
        }
    }
}

/// Inlet definition
#[derive(Debug, Clone)]
pub struct PortDef {
    /// Port ID (0-based)
    pub id: u32,
    /// Port type
    pub port_type: PortType,
    /// Whether this is a hot inlet (triggers output on message receipt). Always false for outlets.
    pub is_hot: bool,
    /// Description (digest text)
    pub description: String,
}

/// Inlet configuration (fixed or variable count)
#[derive(Debug, Clone)]
pub enum InletSpec {
    /// Fixed number of inlets (e.g., cycle~ = 2, biquad~ = 6)
    Fixed(Vec<PortDef>),
    /// Variable inlets depending on argument count (e.g., pack)
    Variable {
        /// Representative inlet definitions described in XML
        defaults: Vec<PortDef>,
        /// Minimum number of inlets
        min_inlets: u32,
    },
}

/// Outlet configuration (fixed or variable count)
#[derive(Debug, Clone)]
pub enum OutletSpec {
    /// Fixed number of outlets
    Fixed(Vec<PortDef>),
    /// Variable outlets depending on argument count (e.g., trigger)
    Variable {
        /// Representative outlet definitions described in XML
        defaults: Vec<PortDef>,
        /// Minimum number of outlets
        min_outlets: u32,
    },
}

/// Object argument definition
#[derive(Debug, Clone)]
pub struct ArgDef {
    pub name: String,
    pub arg_type: String,
    pub optional: bool,
}

/// Object definition
#[derive(Debug, Clone)]
pub struct ObjectDef {
    /// Object name (e.g., "cycle~", "pack", "trigger")
    pub name: String,
    /// Module (max, msp, etc.)
    pub module: Module,
    /// Category (e.g., "MSP Synthesis", "Lists")
    pub category: String,
    /// Short description
    pub digest: String,
    /// Inlet definitions
    pub inlets: InletSpec,
    /// Outlet definitions
    pub outlets: OutletSpec,
    /// Argument definitions
    pub args: Vec<ArgDef>,
}

impl ObjectDef {
    /// Whether this ObjectDef has variable inlets
    pub fn has_variable_inlets(&self) -> bool {
        matches!(self.inlets, InletSpec::Variable { .. })
    }

    /// Whether this ObjectDef has variable outlets
    pub fn has_variable_outlets(&self) -> bool {
        matches!(self.outlets, OutletSpec::Variable { .. })
    }

    /// Returns the inlet count in the default configuration
    pub fn default_inlet_count(&self) -> usize {
        match &self.inlets {
            InletSpec::Fixed(ports) => ports.len(),
            InletSpec::Variable { defaults, .. } => defaults.len(),
        }
    }

    /// Returns the outlet count in the default configuration
    pub fn default_outlet_count(&self) -> usize {
        match &self.outlets {
            OutletSpec::Fixed(ports) => ports.len(),
            OutletSpec::Variable { defaults, .. } => defaults.len(),
        }
    }
}

/// Object definition database
#[derive(Debug)]
pub struct ObjectDb {
    objects: HashMap<String, ObjectDef>,
}

impl ObjectDb {
    /// Create an empty database
    pub fn new() -> Self {
        ObjectDb {
            objects: HashMap::new(),
        }
    }

    /// Insert an ObjectDef
    pub fn insert(&mut self, def: ObjectDef) {
        self.objects.insert(def.name.clone(), def);
    }

    /// Look up by object name
    pub fn lookup(&self, name: &str) -> Option<&ObjectDef> {
        self.objects.get(name)
    }

    /// Number of registered objects
    pub fn len(&self) -> usize {
        self.objects.len()
    }

    /// Whether the database is empty
    pub fn is_empty(&self) -> bool {
        self.objects.is_empty()
    }

    /// Iterator over all object names
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.objects.keys().map(|s| s.as_str())
    }

    /// Iterator over ObjectDefs filtered by module
    pub fn by_module(&self, module: &Module) -> Vec<&ObjectDef> {
        self.objects
            .values()
            .filter(|def| &def.module == module)
            .collect()
    }
}

impl Default for ObjectDb {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_port_type_from_xml_signal() {
        assert_eq!(PortType::from_xml_type("signal"), PortType::Signal);
        assert_eq!(PortType::from_xml_type("Signal"), PortType::Signal);
    }

    #[test]
    fn test_port_type_from_xml_signal_float_variants() {
        assert_eq!(
            PortType::from_xml_type("signal/float"),
            PortType::SignalFloat
        );
        assert_eq!(
            PortType::from_xml_type("Signal/Float"),
            PortType::SignalFloat
        );
        assert_eq!(
            PortType::from_xml_type("signal, float"),
            PortType::SignalFloat
        );
        assert_eq!(
            PortType::from_xml_type("signal or float"),
            PortType::SignalFloat
        );
        assert_eq!(
            PortType::from_xml_type("float/signal"),
            PortType::SignalFloat
        );
        assert_eq!(
            PortType::from_xml_type("float / signal"),
            PortType::SignalFloat
        );
    }

    #[test]
    fn test_port_type_from_xml_int_signal_variants() {
        assert_eq!(PortType::from_xml_type("int/signal"), PortType::IntSignal);
        assert_eq!(PortType::from_xml_type("signal/int"), PortType::IntSignal);
        assert_eq!(PortType::from_xml_type("signal, int"), PortType::IntSignal);
        assert_eq!(PortType::from_xml_type("int / signal"), PortType::IntSignal);
    }

    #[test]
    fn test_port_type_from_xml_dynamic() {
        assert_eq!(PortType::from_xml_type("INLET_TYPE"), PortType::Dynamic);
        assert_eq!(PortType::from_xml_type("OUTLET_TYPE"), PortType::Dynamic);
    }

    #[test]
    fn test_port_type_from_xml_control_types() {
        assert_eq!(PortType::from_xml_type("float"), PortType::Float);
        assert_eq!(PortType::from_xml_type("int"), PortType::Int);
        assert_eq!(PortType::from_xml_type("bang"), PortType::Bang);
        assert_eq!(PortType::from_xml_type("list"), PortType::List);
        assert_eq!(PortType::from_xml_type("symbol"), PortType::Symbol);
        assert_eq!(PortType::from_xml_type("anything"), PortType::Any);
    }

    #[test]
    fn test_port_type_accepts_signal() {
        assert!(PortType::Signal.accepts_signal());
        assert!(PortType::SignalFloat.accepts_signal());
        assert!(PortType::IntSignal.accepts_signal());
        assert!(!PortType::Float.accepts_signal());
        assert!(!PortType::Any.accepts_signal());
        assert!(!PortType::Dynamic.accepts_signal());
    }

    #[test]
    fn test_port_type_accepts_control() {
        assert!(!PortType::Signal.accepts_control());
        assert!(PortType::SignalFloat.accepts_control());
        assert!(PortType::IntSignal.accepts_control());
        assert!(PortType::Float.accepts_control());
        assert!(PortType::Any.accepts_control());
        assert!(PortType::Dynamic.accepts_control());
    }

    #[test]
    fn test_module_from_str() {
        assert_eq!(Module::parse("max"), Module::Max);
        assert_eq!(Module::parse("msp"), Module::Msp);
        assert_eq!(Module::parse("jit"), Module::Other("jit".to_string()));
    }

    #[test]
    fn test_object_db_basic_operations() {
        let mut db = ObjectDb::new();
        assert!(db.is_empty());
        assert_eq!(db.len(), 0);

        let def = ObjectDef {
            name: "cycle~".to_string(),
            module: Module::Msp,
            category: "MSP Synthesis".to_string(),
            digest: "Sinusoidal oscillator".to_string(),
            inlets: InletSpec::Fixed(vec![
                PortDef {
                    id: 0,
                    port_type: PortType::SignalFloat,
                    is_hot: true,
                    description: "Frequency".to_string(),
                },
                PortDef {
                    id: 1,
                    port_type: PortType::SignalFloat,
                    is_hot: false,
                    description: "Phase (0-1)".to_string(),
                },
            ]),
            outlets: OutletSpec::Fixed(vec![PortDef {
                id: 0,
                port_type: PortType::Signal,
                is_hot: false,
                description: "Output".to_string(),
            }]),
            args: vec![],
        };

        db.insert(def);
        assert_eq!(db.len(), 1);
        assert!(!db.is_empty());

        let looked_up = db.lookup("cycle~").unwrap();
        assert_eq!(looked_up.name, "cycle~");
        assert_eq!(looked_up.module, Module::Msp);
        assert_eq!(looked_up.default_inlet_count(), 2);
        assert_eq!(looked_up.default_outlet_count(), 1);
        assert!(!looked_up.has_variable_inlets());

        assert!(db.lookup("nonexistent").is_none());
    }
}