gled-ui 2.34.0

gled's egui interface, shared by the desktop app and the browser
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
//! Repeated controls as one group rule: runs of at least four rules on
//! consecutive controls of a kind that do the same, with each scene,
//! animation or setting number either the same for all or counting up
//! with the control ("Faders 5–8 set setting n−4").

use gled_model::asset::midi_controller::{
    MidiControllerMapping, MidiInputAction, MidiOutputBindingKind,
};

use super::build::Rule;
use super::controls::Control;
use super::numbers::{
    Slot, action_numbers, action_shape, output_numbers, set_output_number, source_shape,
};
use super::sentence::Numbers;

/// The fewest rules shown as a group.
const MIN_MEMBERS: usize = 4;

/// Where in a rule a number sits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum Place {
    /// The press action, or the release action of a rule without one.
    Action,
    /// The rule's feedback output at this position.
    Feedback(usize),
}

/// How a number reads in a group.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Numbering {
    /// The same for every member.
    Same,
    /// Counting with the member's number `n`: it shows as `n + offset`
    /// (numbers shown from 1).
    Counting { offset: i32 },
}

/// Rules shown together.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RuleGroup {
    /// The member rules, by index in the rule list, in control order.
    pub(crate) rules: Vec<usize>,
    /// Each member's `n`: the number in its control's name ("Fader 3" →
    /// 3), else its position in the group from 1.
    pub(crate) numbers: Vec<i32>,
    /// The numbers that count up; all others are the same for every member.
    pub(crate) counting: Vec<(Place, Slot, i32)>,
}

impl RuleGroup {
    /// How the number in `slot` at `place` reads.
    pub(crate) fn numbering(&self, place: Place, slot: Slot) -> Numbering {
        self.counting
            .iter()
            .find(|(counted_place, counted_slot, _)| {
                *counted_place == place && *counted_slot == slot
            })
            .map_or(Numbering::Same, |(_, _, offset)| Numbering::Counting {
                offset: *offset,
            })
    }
}

/// A group's numbers at one place of its rules, for their sentences.
pub(crate) struct GroupNumbers<'a> {
    pub(crate) group: &'a RuleGroup,
    pub(crate) place: Place,
}

impl Numbers for GroupNumbers<'_> {
    fn numbering(&self, slot: Slot) -> Numbering {
        self.group.numbering(self.place, slot)
    }
}

/// The numbers of a rule's action and feedback, with where they sit.
pub(crate) fn rule_numbers(mapping: &MidiControllerMapping, rule: &Rule) -> Vec<(Place, Slot, u8)> {
    let mut numbers = Vec::new();
    if let Some(binding) = rule.press.or(rule.release) {
        numbers.extend(
            action_numbers(&mapping.input_bindings[binding].action)
                .into_iter()
                .map(|(slot, number)| (Place::Action, slot, number)),
        );
    }
    for (position, output) in rule.feedback.iter().enumerate() {
        numbers.extend(
            output_numbers(&mapping.output_bindings[*output].kind)
                .into_iter()
                .map(|(slot, number)| (Place::Feedback(position), slot, number)),
        );
    }
    numbers
}

/// How the controls of a run follow each other.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Series {
    /// Consecutive notes or controllers on one channel (pads, buttons).
    Numbers,
    /// The same note or controller on consecutive channels (a fader per
    /// channel).
    Channels,
}

impl Series {
    /// Sorts a series' members next to each other.
    fn key(self, control: &Control) -> (u8, u8) {
        let channel = control.trigger.status & 0x0F;
        match self {
            Self::Numbers => (channel, control.trigger.data1),
            Self::Channels => (control.trigger.data1, channel),
        }
    }

    /// Whether `next` follows `previous` in the series.
    fn follows(self, previous: &Control, next: &Control) -> bool {
        let (previous_outer, previous_inner) = self.key(previous);
        let (outer, inner) = self.key(next);
        outer == previous_outer && u16::from(inner) == u16::from(previous_inner) + 1
    }
}

/// The rule groups of `rules`; rules in no group stand alone.
pub(crate) fn find_groups(
    mapping: &MidiControllerMapping,
    controls: &[Control],
    rules: &[Rule],
) -> Vec<RuleGroup> {
    let mut groups = Vec::new();
    for series in [Series::Numbers, Series::Channels] {
        let grouped: Vec<usize> = groups
            .iter()
            .flat_map(|group: &RuleGroup| group.rules.iter().copied())
            .collect();
        let mut order: Vec<usize> = (0..rules.len())
            .filter(|rule| !grouped.contains(rule) && groupable(mapping, &rules[*rule]))
            .collect();
        order.sort_by_key(|&rule| {
            let control = &controls[rules[rule].control];
            (
                rules[rule].mode,
                control.trigger.status & 0xF0,
                series.key(control),
            )
        });

        let mut run: Vec<usize> = Vec::new();
        for rule in order {
            if !run.is_empty() && !continues(mapping, controls, rules, series, &run, rule) {
                groups.extend(finish(mapping, controls, rules, &run));
                run.clear();
            }
            run.push(rule);
        }
        groups.extend(finish(mapping, controls, rules, &run));
    }
    groups
}

/// Mode switches and empty rules stand alone.
fn groupable(mapping: &MidiControllerMapping, rule: &Rule) -> bool {
    match rule.press.or(rule.release) {
        Some(binding) => !matches!(
            mapping.input_bindings[binding].action,
            MidiInputAction::SelectMode { .. }
        ),
        None => false,
    }
}

/// A control's name split into its text and trailing number: "Fader 3" →
/// ("Fader", 3).
fn name_number(control: &Control) -> Option<(&str, i32)> {
    let name = control.name.trim_end();
    let digits = name.len() - name.trim_end_matches(|ch: char| ch.is_ascii_digit()).len();
    if digits == 0 || digits == name.len() || control.named_by_message {
        return None;
    }
    let (text, number) = name.split_at(name.len() - digits);
    Some((text.trim_end(), number.parse().ok()?))
}

/// The number in a control's name ("Fader 3" → 3), if it has one.
pub(crate) fn control_number(control: &Control) -> Option<i32> {
    name_number(control).map(|(_, number)| number)
}

/// The numbers of a rule's action.
pub(crate) fn action_numbers_of(mapping: &MidiControllerMapping, rule: &Rule) -> Vec<(Slot, u8)> {
    rule_numbers(mapping, rule)
        .into_iter()
        .filter(|(place, _, _)| *place == Place::Action)
        .map(|(_, slot, value)| (slot, value))
        .collect()
}

/// Whether `rule` can join `run` as its next member.
fn continues(
    mapping: &MidiControllerMapping,
    controls: &[Control],
    rules: &[Rule],
    series: Series,
    run: &[usize],
    rule: usize,
) -> bool {
    let first = &rules[run[0]];
    let last = &rules[run[run.len() - 1]];
    let candidate = &rules[rule];
    let last_control = &controls[last.control];
    let control = &controls[candidate.control];
    if candidate.mode != first.mode
        || control.kind != last_control.kind
        || control.trigger.status & 0xF0 != last_control.trigger.status & 0xF0
        || !series.follows(last_control, control)
        || !same_shape(mapping, first, candidate)
    {
        return false;
    }
    match (name_number(last_control), name_number(control)) {
        (Some((last_text, last_number)), Some((text, number))) => {
            if text != last_text || number != last_number + 1 {
                return false;
            }
        }
        (None, None) => {}
        _ => return false,
    }
    let mut members: Vec<usize> = run.to_vec();
    members.push(rule);
    counting(mapping, controls, rules, &members).is_some()
}

/// The run as a group, if it is long enough.
fn finish(
    mapping: &MidiControllerMapping,
    controls: &[Control],
    rules: &[Rule],
    run: &[usize],
) -> Option<RuleGroup> {
    if run.len() < MIN_MEMBERS {
        return None;
    }
    let (numbers, counting) = counting(mapping, controls, rules, run)?;
    Some(RuleGroup {
        rules: run.to_vec(),
        numbers,
        counting,
    })
}

/// The members' numbers `n` and the numbers that count with them, or
/// `None` when a number neither stays the same nor counts up.
fn counting(
    mapping: &MidiControllerMapping,
    controls: &[Control],
    rules: &[Rule],
    members: &[usize],
) -> Option<(Vec<i32>, Vec<(Place, Slot, i32)>)> {
    let numbers: Vec<i32> = members
        .iter()
        .enumerate()
        .map(|(position, &rule)| {
            name_number(&controls[rules[rule].control])
                .map_or(position as i32 + 1, |(_, number)| number)
        })
        .collect();
    let values: Vec<Vec<(Place, Slot, u8)>> = members
        .iter()
        .map(|&rule| rule_numbers(mapping, &rules[rule]))
        .collect();
    let mut counted = Vec::new();
    for (index, &(place, slot, first)) in values[0].iter().enumerate() {
        let column: Vec<i32> = values
            .iter()
            .map(|member| i32::from(member[index].2))
            .collect();
        if column.iter().all(|&value| value == i32::from(first)) {
            continue;
        }
        let offset = column[0] + 1 - numbers[0];
        let counts = column
            .iter()
            .zip(&numbers)
            .all(|(&value, &number)| value + 1 - number == offset);
        if !counts {
            return None;
        }
        counted.push((place, slot, offset));
    }
    Some((numbers, counted))
}

/// Whether two rules do the same apart from their numbers.
fn same_shape(mapping: &MidiControllerMapping, a: &Rule, b: &Rule) -> bool {
    let input = |index: Option<usize>| index.map(|index| &mapping.input_bindings[index]);
    let same_binding = |x: Option<usize>, y: Option<usize>| match (input(x), input(y)) {
        (Some(x), Some(y)) => {
            action_shape(&x.action) == action_shape(&y.action)
                && x.touch.is_some() == y.touch.is_some()
        }
        (None, None) => true,
        _ => false,
    };
    same_binding(a.press, b.press)
        && same_binding(a.release, b.release)
        && a.feedback.len() == b.feedback.len()
        && a.feedback.iter().zip(&b.feedback).all(|(&x, &y)| {
            same_feedback(
                &mapping.output_bindings[x].kind,
                &mapping.output_bindings[y].kind,
            )
        })
}

fn same_feedback(a: &MidiOutputBindingKind, b: &MidiOutputBindingKind) -> bool {
    match (a, b) {
        (MidiOutputBindingKind::Value(a), MidiOutputBindingKind::Value(b)) => {
            a.min == b.min
                && a.max == b.max
                && a.active_value == b.active_value
                && source_shape(&a.source) == source_shape(&b.source)
        }
        (MidiOutputBindingKind::Meter(a), MidiOutputBindingKind::Meter(b)) => {
            source_shape(&a.source) == source_shape(&b.source)
        }
        (MidiOutputBindingKind::SceneColorValue(a), MidiOutputBindingKind::SceneColorValue(b)) => {
            // What the pad shows, apart from its scene's numbers and the
            // pad's own message.
            let shape = |color: &gled_model::asset::midi_controller::MidiSceneColorValueOutput| {
                let mut kind = MidiOutputBindingKind::SceneColorValue(
                    gled_model::asset::midi_controller::MidiSceneColorValueOutput {
                        status: 0,
                        data1: 0,
                        ..color.clone()
                    },
                );
                for (slot, _) in output_numbers(&kind.clone()) {
                    set_output_number(&mut kind, slot, 0);
                }
                kind
            };
            a.mapping_name == b.mapping_name && shape(a) == shape(b)
        }
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ui::windows::midi_controllers::rules::{
        build::build_rules,
        controls::controls_of,
        test_mappings::{apc40, p1x},
    };

    /// The groups of `mapping` as "first–last" control names with mode.
    fn group_names(mapping: &MidiControllerMapping) -> Vec<(String, Option<u8>)> {
        let controls = controls_of(mapping);
        let rules = build_rules(mapping, &controls);
        find_groups(mapping, &controls, &rules)
            .iter()
            .map(|group| {
                let first = &controls[rules[group.rules[0]].control].name;
                let last = &controls[rules[group.rules[group.rules.len() - 1]].control].name;
                (format!("{first}–{last}"), rules[group.rules[0]].mode)
            })
            .collect()
    }

    #[test]
    fn the_p1x_strips_are_groups() {
        let groups = group_names(&p1x());
        for expected in [
            ("Rec 1–Rec 8", Some(0)),
            ("S 1–S 8", Some(0)),
            ("Select 1–Select 8", Some(0)),
            ("Fader 1–Fader 8", Some(0)),
            ("Select 1–Select 8", Some(1)),
            ("Fader 5–Fader 8", Some(1)),
        ] {
            assert!(
                groups.contains(&(expected.0.to_owned(), expected.1)),
                "{expected:?} in {groups:?}"
            );
        }
        assert_eq!(groups.len(), 6, "{groups:?}");
    }

    #[test]
    fn faders_5_to_8_count_their_setting_from_an_offset() {
        let mapping = p1x();
        let controls = controls_of(&mapping);
        let rules = build_rules(&mapping, &controls);
        let groups = find_groups(&mapping, &controls, &rules);
        let faders = groups
            .iter()
            .find(|group| controls[rules[group.rules[0]].control].name == "Fader 5")
            .unwrap_or_else(|| panic!("no group from Fader 5"));
        assert_eq!(faders.numbers, [5, 6, 7, 8]);
        assert_eq!(
            faders.numbering(Place::Action, Slot::Setting),
            Numbering::Counting { offset: -4 }
        );
    }

    #[test]
    fn a_row_of_pads_is_a_group_with_the_row_the_same() {
        let mapping = apc40();
        let controls = controls_of(&mapping);
        let rules = build_rules(&mapping, &controls);

        let groups = find_groups(&mapping, &controls, &rules);
        let top_row = groups
            .iter()
            .find(|group| controls[rules[group.rules[0]].control].name == "Note 32")
            .unwrap_or_else(|| panic!("no group from Note 32"));
        assert_eq!(top_row.rules.len(), 8);
        assert_eq!(top_row.numbering(Place::Action, Slot::Row), Numbering::Same);
        assert_eq!(
            top_row.numbering(Place::Action, Slot::Column),
            Numbering::Counting { offset: 0 }
        );
    }
}