gled-model 2.34.0

The data model of gled: projects, scenes, effects, animations, curves and assets
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
mod control;
mod mode;
mod output;
mod target;

pub use control::MidiControl;
pub use mode::{MidiMode, MidiModeHighlight, binding_in_mode};
pub use output::{
    MidiColorSource, MidiEffectParameter, MidiMeterOutput, MidiNamedSceneColorMapping,
    MidiOutputBinding, MidiOutputBindingKind, MidiOutputBindingSelector, MidiSceneColorMessage,
    MidiSceneColorMessageMap, MidiSceneColorValueOutput, MidiValueOutput, MidiValueSource,
    MidiValueSourceKind,
};
pub use target::{MidiEffectTarget, MidiEffectTargetKind, MidiEncoder, MidiRelativeEncoding};

use super::AssetTrait;
use serde::{Deserialize, Serialize};
use strum::{Display, EnumDiscriminants, EnumIter};

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Default)]
pub struct MidiController {
    pub mapping: MidiControllerMapping,
    /// The devices that get this controller while the project assigns
    /// them none, as port keys (`normalize_controller_key`).
    #[serde(default)]
    pub default_for_ports: Vec<String>,
}

impl AssetTrait for MidiController {
    const DIR_NAME: &'static str = "midi_controllers";
    const NAME: &'static str = "MIDI Controller";
    const SHOW_NAME_IF_SELECTED: bool = true;
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Default)]
pub struct MidiControllerMapping {
    pub input_bindings: Vec<MidiInputBinding>,
    pub output_bindings: Vec<MidiOutputBinding>,
    pub color_mappings: Vec<MidiNamedSceneColorMapping>,
    /// The controller's physical controls, named; bindings belong to the
    /// control whose trigger they match. Empty in mappings saved before
    /// controls had names.
    #[serde(default)]
    pub controls: Vec<MidiControl>,
    /// The modes the controller switches between; the first is active until
    /// a `SelectMode` binding picks another. Empty without modes.
    #[serde(default)]
    pub modes: Vec<MidiMode>,
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct MidiInputBinding {
    pub name: String,
    pub trigger: MidiTrigger,
    pub action: MidiInputAction,
    /// The mode the binding works in, by its position; `None` in all.
    #[serde(default)]
    pub mode: Option<u8>,
    /// The note a touch-sensitive control sends while it is touched; the
    /// interfaces then outline what the binding changes. Its note off, or
    /// velocity 0, is the release.
    #[serde(default)]
    pub touch: Option<MidiTrigger>,
}

impl Default for MidiInputBinding {
    fn default() -> Self {
        Self {
            name: "Input".to_owned(),
            trigger: MidiTrigger::default(),
            action: MidiInputAction::Tap,
            mode: None,
            touch: None,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct MidiTrigger {
    pub status: u8,
    pub data1: u8,
    pub match_data1: bool,
}

impl Default for MidiTrigger {
    fn default() -> Self {
        Self {
            status: 0,
            data1: 0,
            match_data1: true,
        }
    }
}

/// `MidiInputActionKind` is the action without its settings; it reads as
/// the label the controller window shows.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, EnumDiscriminants)]
#[strum_discriminants(
    name(MidiInputActionKind),
    derive(Display, EnumIter),
    strum(serialize_all = "title_case")
)]
pub enum MidiInputAction {
    Tap,
    SetMainDimmer,
    /// Moves the main dimmer by an encoder's units, 1/127 each.
    #[strum_discriminants(strum(serialize = "Set Main Dimmer (Relative)"))]
    SetMainDimmerRelative {
        encoder: MidiEncoder,
    },
    SetBlackout,
    /// Flips the blackout on a press (any value above 0).
    ToggleBlackout,
    /// Adds the value as two's complement steps to the tempo, one BPM each.
    SetSpeedAdd,
    SetSpeedMultiply,
    /// Moves the tempo by an encoder's units, one BPM each.
    #[strum_discriminants(strum(serialize = "Set Speed (Relative)"))]
    SetSpeedRelative {
        encoder: MidiEncoder,
    },
    #[strum_discriminants(strum(serialize = "Select Scene (Distributed 0-127)"))]
    SelectSceneDistributed,
    /// Selects the scene an encoder's units away, in row-major order.
    #[strum_discriminants(strum(serialize = "Select Scene (Relative)"))]
    SelectSceneRelative {
        encoder: MidiEncoder,
    },
    /// Moves the selection an encoder's units of rows up or down in the
    /// same column, stopping at the first and last row. Row scene targets
    /// then work on the new row.
    #[strum_discriminants(strum(serialize = "Select Row (Relative)"))]
    SelectSceneRow {
        encoder: MidiEncoder,
    },
    /// Moves the selection an encoder's units of columns left or right in
    /// the same row, stopping at the first and last column. Column scene
    /// targets then work on the new column.
    #[strum_discriminants(strum(serialize = "Select Column (Relative)"))]
    SelectSceneColumn {
        encoder: MidiEncoder,
    },
    SelectScene {
        target: MidiSceneTarget,
    },
    /// Switches the controller to one of its mapping's modes on a press.
    SelectMode {
        mode: u8,
    },
    /// Selects an effect of the selected scene on a press.
    #[strum_discriminants(strum(serialize = "Select Effect"))]
    SelectSceneEffect {
        index: u8,
    },
    /// Selects the effect an encoder's units away in the selected scene.
    #[strum_discriminants(strum(serialize = "Select Effect (Relative)"))]
    SelectSceneEffectRelative {
        encoder: MidiEncoder,
    },
    /// Spreads the value over the selected scene's effects.
    #[strum_discriminants(strum(serialize = "Select Effect (Distributed 0-127)"))]
    SelectSceneEffectDistributed,
    ToggleSceneActive {
        target: MidiSceneTarget,
    },
    SetSceneActive {
        target: MidiSceneTarget,
    },
    FlashScene {
        target: MidiSceneTarget,
    },
    SetSceneOpacity {
        target: MidiSceneTarget,
    },
    SetSceneInputDimmer {
        target: MidiSceneTarget,
    },
    SetSceneBeatOffset {
        target: MidiSceneTarget,
    },
    SetSceneIgnoreMainDimmer {
        target: MidiSceneTarget,
    },
    SetSceneSetOffsetOnFlash {
        target: MidiSceneTarget,
    },
    #[strum_discriminants(strum(serialize = "Set Effect Setting (n,n) f32"))]
    SetSceneEffectSettingF32 {
        target: MidiSceneTarget,
        #[serde(rename = "effect_index")]
        effect: MidiEffectTarget,
        setting_index: u8,
    },
    #[strum_discriminants(strum(serialize = "Set Effect Opacity"))]
    SetSceneEffectOpacity {
        target: MidiSceneTarget,
        #[serde(rename = "effect_index")]
        effect: MidiEffectTarget,
    },
    #[strum_discriminants(strum(serialize = "Set Effect Color Shift"))]
    SetSceneEffectColorShift {
        target: MidiSceneTarget,
        #[serde(rename = "effect_index")]
        effect: MidiEffectTarget,
    },
    #[strum_discriminants(strum(serialize = "Set Effect Beat Progression"))]
    SetSceneEffectBeatProgression {
        target: MidiSceneTarget,
        #[serde(rename = "effect_index")]
        effect: MidiEffectTarget,
    },
    #[strum_discriminants(strum(serialize = "Set Effect Beat Offset"))]
    SetSceneEffectBeatOffset {
        target: MidiSceneTarget,
        #[serde(rename = "effect_index")]
        effect: MidiEffectTarget,
    },
    #[strum_discriminants(strum(serialize = "Set Effect Speed Exponent"))]
    SetSceneEffectSpeedExponent {
        target: MidiSceneTarget,
        #[serde(rename = "effect_index")]
        effect: MidiEffectTarget,
    },
    /// Picks the effect's layout: 0 inherits the tile's layout, 1 is the
    /// topology, 2… the layouts in stack order (`Patch::layout_refs`). Was the
    /// effect's group index before the patch.
    #[serde(alias = "SetSceneEffectGroupIndex")]
    #[strum_discriminants(strum(serialize = "Set Effect Layout"))]
    SetSceneEffectLayout {
        target: MidiSceneTarget,
        #[serde(rename = "effect_index")]
        effect: MidiEffectTarget,
    },
}

/// `MidiSceneTargetKind` is the target without its position; it reads as
/// the label the controller window shows.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Default, EnumDiscriminants)]
#[strum_discriminants(
    name(MidiSceneTargetKind),
    derive(Display, EnumIter),
    strum(serialize_all = "title_case")
)]
pub enum MidiSceneTarget {
    #[default]
    #[strum_discriminants(strum(serialize = "Selected Scene"))]
    Selected,
    #[strum_discriminants(strum(serialize = "Quick Scene"))]
    Quick { index: u8 },
    #[strum_discriminants(strum(serialize = "Grid Scene"))]
    Grid { row: u8, col: u8 },
    /// The scene in column `col` of the selected scene's row.
    #[strum_discriminants(strum(serialize = "Row Scene"))]
    Row { col: u8 },
    /// The scene in row `row` of the selected scene's column.
    #[strum_discriminants(strum(serialize = "Column Scene"))]
    Column { row: u8 },
}
/// A port name without the numbers some systems append, such as
/// `"APC40 [2]"` → `"APC40"`, or ALSA's client and port address,
/// `"iCON P1-X1:iCON P1-X1 MIDI 1 32:0"` → `"iCON P1-X1:iCON P1-X1 MIDI 1"`,
/// which changes with the order devices are plugged in. A controller so
/// keeps its mapping when it is plugged in again.
pub fn normalize_controller_key(port_name: &str) -> String {
    let trimmed = strip_alsa_address(port_name.trim());
    if let Some(prefix) = trimmed.strip_suffix(']')
        && let Some((base, suffix)) = prefix.rsplit_once(" [")
        && !base.is_empty()
        && !suffix.is_empty()
        && suffix.chars().all(|ch| ch.is_ascii_digit())
    {
        return base.to_owned();
    }

    trimmed.to_owned()
}

/// `name` without a trailing `" <client>:<port>"` address.
fn strip_alsa_address(name: &str) -> &str {
    let Some((base, address)) = name.rsplit_once(' ') else {
        return name;
    };
    let is_number = |part: &str| !part.is_empty() && part.chars().all(|ch| ch.is_ascii_digit());
    match address.split_once(':') {
        Some((client, port)) if !base.is_empty() && is_number(client) && is_number(port) => {
            base.trim_end()
        }
        _ => name,
    }
}

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

    #[test]
    fn a_full_meter_lights_all_twelve_leds_of_its_strip() {
        let meter = MidiMeterOutput {
            strip: 2,
            source: MidiValueSource::default(),
        };
        assert_eq!(meter.message(1.0), [0xD0, 0x2C]);
        assert_eq!(meter.message(0.0), [0xD0, 0x20]);
        assert_eq!(meter.message(2.0), [0xD0, 0x2C]);
    }

    #[test]
    fn alsa_addresses_are_not_part_of_the_controller_key() {
        assert_eq!(
            normalize_controller_key("iCON P1-X1:iCON P1-X1 MIDI 1 32:0"),
            "iCON P1-X1:iCON P1-X1 MIDI 1"
        );
        assert_eq!(
            normalize_controller_key("iCON P1-X1:iCON P1-X1 MIDI 1 36:0"),
            normalize_controller_key("iCON P1-X1:iCON P1-X1 MIDI 1 32:0")
        );
    }

    #[test]
    fn numbered_port_names_keep_their_number() {
        assert_eq!(normalize_controller_key("APC40 [2]"), "APC40");
        assert_eq!(normalize_controller_key("Port 2"), "Port 2");
    }

    /// Groups became layouts; a controller saved with the group names must
    /// still load, and then means the effect's layout.
    #[test]
    fn group_index_bindings_saved_before_the_patch_load_as_layout_bindings() {
        let action: MidiInputAction = serde_json::from_str(
            r#"{"SetSceneEffectGroupIndex": {"target": "Selected", "effect_index": 1}}"#,
        )
        .expect("an old group index action must load");
        assert_eq!(
            action,
            MidiInputAction::SetSceneEffectLayout {
                target: MidiSceneTarget::Selected,
                effect: MidiEffectTarget::Index { index: 1 },
            }
        );

        let source: MidiValueSource = serde_json::from_str(
            r#"{"SceneEffectGroupIndex": {"target": "Selected", "effect_index": 1}}"#,
        )
        .expect("an old group index feedback must load");
        assert_eq!(
            source,
            MidiValueSource::SceneEffectLayout {
                target: MidiSceneTarget::Selected,
                effect: MidiEffectTarget::Index { index: 1 },
            }
        );
    }

    /// Mappings saved before controls had names and beat lights could
    /// pulse on every beat still load: without controls, and with the
    /// window once per bar.
    #[test]
    fn mappings_saved_before_named_controls_load() {
        let mapping: MidiControllerMapping = serde_json::from_str(
            r#"{
                "input_bindings": [],
                "output_bindings": [{
                    "name": "Tap light",
                    "kind": {"Value": {"status": 144, "data1": 82, "min": 0, "max": 127,
                        "active_value": 127, "source": {"BeatFlankPulse": {
                            "start_beat": 0.0, "end_beat": 0.5, "blackout_blink_value": null}}}}
                }],
                "color_mappings": []
            }"#,
        )
        .expect("an old mapping must load");
        assert!(mapping.controls.is_empty());
        assert_eq!(
            mapping.output_bindings[0].kind.source(),
            Some(&MidiValueSource::BeatFlankPulse {
                start_beat: 0.0,
                end_beat: 0.5,
                blackout_blink_value: None,
                every_beat: false,
            })
        );
    }

    /// The controller window lists these labels; the generated kinds must
    /// read exactly as the hand-written labels did.
    #[test]
    fn kinds_read_as_the_controller_window_labels() {
        use strum::IntoEnumIterator;
        let actions: Vec<String> = MidiInputActionKind::iter().map(|k| k.to_string()).collect();
        assert_eq!(
            actions,
            [
                "Tap",
                "Set Main Dimmer",
                "Set Main Dimmer (Relative)",
                "Set Blackout",
                "Toggle Blackout",
                "Set Speed Add",
                "Set Speed Multiply",
                "Set Speed (Relative)",
                "Select Scene (Distributed 0-127)",
                "Select Scene (Relative)",
                "Select Row (Relative)",
                "Select Column (Relative)",
                "Select Scene",
                "Select Mode",
                "Select Effect",
                "Select Effect (Relative)",
                "Select Effect (Distributed 0-127)",
                "Toggle Scene Active",
                "Set Scene Active",
                "Flash Scene",
                "Set Scene Opacity",
                "Set Scene Input Dimmer",
                "Set Scene Beat Offset",
                "Set Scene Ignore Main Dimmer",
                "Set Scene Set Offset On Flash",
                "Set Effect Setting (n,n) f32",
                "Set Effect Opacity",
                "Set Effect Color Shift",
                "Set Effect Beat Progression",
                "Set Effect Beat Offset",
                "Set Effect Speed Exponent",
                "Set Effect Layout",
            ]
        );
        let sources: Vec<String> = MidiValueSourceKind::iter().map(|k| k.to_string()).collect();
        assert_eq!(
            sources,
            [
                "Selected Scene Opacity",
                "Selected Scene (Distributed 0-127)",
                "Selected Effect (Distributed 0-127)",
                "Selected Scene Opacity Live",
                "Effect Live Value",
                "Effect Selected",
                "Selected Scene Input Dimmer",
                "Selected Scene Beat Offset",
                "Selected Scene Ignore Main Dimmer",
                "Selected Scene Set Offset On Flash",
                "Main Dimmer",
                "Beat Flank",
                "Blackout",
                "Scene Opacity",
                "Scene Opacity Live",
                "Scene Input Dimmer",
                "Scene Beat Offset",
                "Scene Ignore Main Dimmer",
                "Scene Set Offset On Flash",
                "Scene Active",
                "Scene Flashed",
                "Scene Selected",
                "Mode Active",
                "Scene Effect Setting (n,n) f32",
                "Effect Opacity",
                "Effect Color Shift",
                "Effect Beat Progression",
                "Effect Beat Offset",
                "Effect Speed Exponent",
                "Effect Layout",
            ]
        );
        let targets: Vec<String> = MidiSceneTargetKind::iter().map(|k| k.to_string()).collect();
        assert_eq!(
            targets,
            [
                "Selected Scene",
                "Quick Scene",
                "Grid Scene",
                "Row Scene",
                "Column Scene"
            ]
        );
        let effects: Vec<String> = MidiEffectTargetKind::iter()
            .map(|k| k.to_string())
            .collect();
        assert_eq!(effects, ["Selected Effect", "Effect Index"]);
        let outputs: Vec<String> = MidiOutputBindingSelector::iter()
            .map(|k| k.to_string())
            .collect();
        assert_eq!(
            outputs,
            ["Single Value", "Scene Color Mapping", "Mackie Meter"]
        );
        assert_eq!(MidiColorSource::default().to_string(), "Scene Color");
    }
}