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
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! One rule, or one group of rules, as a card: the control's name, the
//! sentence of what it does with clickable words, and a line per light,
//! motor fader or meter showing it.

use egui::{Align, Frame, Layout, Popup, PopupCloseBehavior, RichText, Stroke, Ui};
use egui_phosphor_icons::icons;
use gled_model::asset::midi_controller::MidiControllerMapping;

use super::intent::{Intent, SlotNumbering};
use super::list_state::ListState;
use super::pickers::GroupFirst;
use super::rules::{
    Control, ControlKind, GroupNumbers, Members, Numbering, Numbers, Place, Plain, Rule, RuleGroup,
    TokenKind, action_sentence, mode_name,
};
use super::token_editors::{ActionChoice, action_token_editor};
use super::widgets::token::{sentence, token, token_color};

/// What a card draws from and where its clicks go.
pub(crate) struct Cards<'a> {
    pub(crate) mapping: &'a MidiControllerMapping,
    pub(crate) controls: &'a [Control],
    pub(crate) rules: &'a [Rule],
    pub(crate) state: &'a mut ListState,
    pub(crate) intents: &'a mut Vec<Intent>,
    /// Outputs whose "on" value the test device shows while hovered.
    pub(crate) previewed: &'a mut Vec<usize>,
}

/// The rules a card shows and how their numbers read.
pub(crate) struct Shown<'a> {
    pub(crate) members: Members,
    pub(crate) group: Option<&'a RuleGroup>,
}

impl Shown<'_> {
    pub(crate) fn first(&self) -> &Rule {
        &self.members.rules[0]
    }

    pub(crate) fn numbering(&self, place: Place) -> SlotNumbering {
        let Some(group) = self.group else {
            return SlotNumbering::default();
        };
        SlotNumbering(
            group
                .counting
                .iter()
                .filter(|(counted, _, _)| *counted == place)
                .map(|(_, slot, offset)| (*slot, Numbering::Counting { offset: *offset }))
                .collect(),
        )
    }

    pub(crate) fn numbers(&self, place: Place) -> Box<dyn Numbers + '_> {
        match self.group {
            Some(group) => Box::new(GroupNumbers { group, place }),
            None => Box::new(Plain),
        }
    }

    pub(crate) fn group_first<'c>(&self, controls: &'c [Control]) -> Option<GroupFirst<'c>> {
        self.group.map(|group| GroupFirst {
            n: group.numbers[0],
            name: &controls[self.first().control].name,
        })
    }
}

/// Draws the card of the single rule `rule`.
pub(crate) fn rule_card(ui: &mut Ui, cards: &mut Cards, rule: usize) {
    let shown = Shown {
        members: Members::single(cards.rules[rule].clone()),
        group: None,
    };
    card(ui, cards, &shown);
}

/// Draws the card of `group`, with the rule of the member opened under it.
pub(crate) fn group_card(ui: &mut Ui, cards: &mut Cards, group: &RuleGroup) {
    let shown = Shown {
        members: Members::of_group(cards.rules, group),
        group: Some(group),
    };
    card(ui, cards, &shown);
}

fn card(ui: &mut Ui, cards: &mut Cards, shown: &Shown) {
    let first = shown.first().clone();
    let key = (first.control, first.mode);
    let highlighted = cards.state.highlight.is_some_and(|(control, _)| {
        shown
            .members
            .rules
            .iter()
            .any(|rule| rule.control == control)
    });
    let stroke = if highlighted {
        Stroke::new(1.5, token_color(TokenKind::Main))
    } else {
        ui.visuals().widgets.noninteractive.bg_stroke
    };
    let response = Frame::group(ui.style())
        .stroke(stroke)
        .show(ui, |ui| {
            ui.set_width(ui.available_width());
            ui.horizontal(|ui| {
                title(ui, cards, shown);
                ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
                    card_buttons(ui, cards, shown);
                    ui.with_layout(
                        Layout::left_to_right(Align::Min).with_main_wrap(true),
                        |ui| {
                            // Each piece stays on one line; lines break between them.
                            ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
                            action_line(ui, cards, shown);
                        },
                    );
                });
            });
            if let Some(group) = shown.group {
                member_cells(ui, cards, shown, group);
            }
            conflicts(ui, cards, shown);
            super::feedback_lines::feedback_lines(ui, cards, shown);
            if cards.state.midi_open.contains(&key) && shown.group.is_none() {
                super::midi_details::midi_details(ui, cards, &first);
            }
            if cards.state.copying == Some(key) && shown.group.is_none() {
                super::copy_dialog::copy_dialog(ui, cards, &first);
            }
        })
        .response;
    if cards.state.scroll_to == Some(first.control) {
        response.scroll_to_me(Some(Align::Center));
        cards.state.scroll_to = None;
    }
    if let Some(group) = shown.group
        && let Some((first_control, mode, member)) = cards.state.open_member
        && first_control == first.control
        && mode == first.mode
        && let Some(position) = group
            .rules
            .iter()
            .position(|&rule| cards.rules[rule].control == member)
    {
        ui.indent(("member", first.control, first.mode), |ui| {
            rule_card(ui, cards, group.rules[position]);
        });
    }
}

/// The control's name, or the group's: "Fader 1–8 each".
fn title(ui: &mut Ui, cards: &mut Cards, shown: &Shown) {
    let first = shown.first();
    let control = &cards.controls[first.control];
    let icon = match control.kind {
        ControlKind::Button => icons::CIRCLE,
        ControlKind::Pad => icons::SQUARE,
        ControlKind::Fader => icons::SLIDERS_HORIZONTAL,
        ControlKind::Knob => icons::FADERS,
        ControlKind::Encoder => icons::ARROWS_CLOCKWISE,
    };
    ui.label(icon.regular().weak());
    let Some(group) = shown.group else {
        let chip = ui
            .button(RichText::new(&control.name).strong())
            .on_hover_text("Rename, re-learn or see its MIDI message");
        Popup::menu(&chip)
            .close_behavior(PopupCloseBehavior::CloseOnClickOutside)
            .show(|ui| control_menu(ui, cards, first.control));
        return;
    };
    let last = &cards.controls[shown.members.rules[shown.members.rules.len() - 1].control];
    let name = match (group.numbers.first(), group.numbers.last()) {
        (Some(from), Some(to)) if !control.named_by_message => {
            let text = control
                .name
                .trim_end_matches(|ch: char| ch.is_ascii_digit())
                .trim_end();
            format!("{text} {from}–{to}")
        }
        _ => message_range(&control.trigger, &last.trigger),
    };
    ui.label(RichText::new(name).strong());
    ui.label("each");
}

/// The menu of a control's name: rename it, learn it again.
fn control_menu(ui: &mut Ui, cards: &mut Cards, control: usize) {
    let name = &cards.controls[control].name;
    let editing = cards
        .state
        .renaming
        .get_or_insert_with(|| (control, name.clone()));
    if editing.0 != control {
        *editing = (control, name.clone());
    }
    ui.label("Name");
    let field = ui.text_edit_singleline(&mut editing.1);
    if field.lost_focus() || ui.input(|input| input.key_pressed(egui::Key::Enter)) {
        let new_name = editing.1.trim().to_owned();
        if !new_name.is_empty() && new_name != *name {
            cards.intents.push(Intent::RenameControl {
                control,
                name: new_name,
            });
        }
    }
    ui.weak(super::rules::message_name(&cards.controls[control].trigger));
    if ui.button("Learn it again: move the control").clicked() {
        cards.state.learn_request = Some(super::list_state::LearnRequest::Control(control));
        ui.close();
    }
}

/// The sentence of what the rule does, or "does nothing yet".
fn action_line(ui: &mut Ui, cards: &mut Cards, shown: &Shown) {
    let first = shown.first();
    let control = &cards.controls[first.control];
    let mapping = cards.mapping;
    let action = first
        .press
        .or(first.release)
        .map(|index| &mapping.input_bindings[index].action);
    let numbering = shown.numbering(Place::Action);
    let open_palette = cards.state.open_palette == Some((first.control, first.mode));
    if open_palette {
        cards.state.open_palette = None;
    }

    let mut choices = Vec::new();
    match action {
        Some(action) => {
            let numbers = shown.numbers(Place::Action);
            let pieces = action_sentence(action, &mapping.modes, numbers.as_ref());
            for (kind, response) in sentence(ui, &pieces) {
                let open = open_palette && kind == TokenKind::Main;
                choices.push((
                    kind,
                    action_token_editor(
                        ui,
                        &response,
                        kind,
                        Some(action),
                        &numbering,
                        &mapping.modes,
                        control.kind,
                        shown.group_first(cards.controls),
                        open,
                    ),
                ));
            }
            if ui
                .small_button(icons::X)
                .on_hover_text("Remove the action; the lights stay")
                .clicked()
            {
                cards
                    .intents
                    .push(Intent::RemoveAction(shown.members.clone()));
            }
        }
        None => {
            let response = token(
                ui,
                "does nothing yet — choose an action",
                token_color(TokenKind::Main),
            );
            choices.push((
                TokenKind::Main,
                action_token_editor(
                    ui,
                    &response,
                    TokenKind::Main,
                    None,
                    &numbering,
                    &mapping.modes,
                    control.kind,
                    None,
                    open_palette,
                ),
            ));
        }
    }
    when_token(ui, cards, shown);
    mode_token(ui, cards, shown);
    touch_token(ui, cards, shown);

    for (kind, choice) in choices {
        match choice {
            Some(ActionChoice::Set(action, numbering)) => {
                let numbering = if kind == TokenKind::Main {
                    shown.numbering(Place::Action)
                } else {
                    numbering
                };
                cards.intents.push(Intent::SetAction {
                    members: shown.members.clone(),
                    action,
                    numbering,
                });
            }
            Some(ActionChoice::RemoveAction) => cards
                .intents
                .push(Intent::RemoveAction(shown.members.clone())),
            Some(ActionChoice::DeleteRule) => cards
                .intents
                .push(Intent::RemoveRules(shown.members.clone())),
            None => {}
        }
    }
}

/// "on press", "while held" or "on release" for buttons.
fn when_token(ui: &mut Ui, cards: &mut Cards, shown: &Shown) {
    let first = shown.first();
    let control = &cards.controls[first.control];
    if !matches!(control.kind, ControlKind::Button | ControlKind::Pad) {
        return;
    }
    let text = match (first.press, first.release) {
        (Some(_), Some(_)) if first.while_held(cards.mapping) => "while held",
        (None, Some(_)) => "on release",
        (Some(_), _) => "on press",
        (None, None) => return,
    };
    ui.label("·");
    let response = token(ui, text, token_color(TokenKind::Beat));
    if first.press.is_none() {
        return;
    }
    let held = text == "while held";
    Popup::menu(&response)
        .close_behavior(PopupCloseBehavior::CloseOnClickOutside)
        .show(|ui| {
            if ui.selectable_label(!held, "On press").clicked() && held {
                cards.intents.push(Intent::SetWhileHeld {
                    members: shown.members.clone(),
                    held: false,
                });
                ui.close();
            }
            if ui
                .selectable_label(held, "While held: undone when you let go")
                .clicked()
                && !held
            {
                cards.intents.push(Intent::SetWhileHeld {
                    members: shown.members.clone(),
                    held: true,
                });
                ui.close();
            }
        });
}

/// "works in all modes" or "works in mode Rows".
fn mode_token(ui: &mut Ui, cards: &mut Cards, shown: &Shown) {
    let mapping = cards.mapping;
    if mapping.modes.is_empty() {
        return;
    }
    let first = shown.first();
    ui.label("· works in");
    let text = match first.mode {
        None => "all modes".to_owned(),
        Some(mode) => format!("mode {}", mode_name(&mapping.modes, mode)),
    };
    let response = token(ui, &text, token_color(TokenKind::Mode));
    Popup::menu(&response)
        .close_behavior(PopupCloseBehavior::CloseOnClickOutside)
        .show(|ui| {
            let mut pick = |ui: &mut Ui, mode: Option<u8>, label: String| {
                if ui.selectable_label(first.mode == mode, label).clicked() && first.mode != mode {
                    cards.intents.push(Intent::SetMode {
                        members: shown.members.clone(),
                        mode,
                    });
                    ui.close();
                }
            };
            pick(ui, None, "All modes".to_owned());
            for (index, entry) in mapping.modes.iter().enumerate() {
                pick(
                    ui,
                    u8::try_from(index).ok(),
                    format!("Only in {}", entry.name),
                );
            }
        });
}

/// "touch note 109" for a fader that tells when it is touched.
fn touch_token(ui: &mut Ui, cards: &mut Cards, shown: &Shown) {
    let Some(press) = shown.first().press else {
        return;
    };
    let Some(touch) = &cards.mapping.input_bindings[press].touch else {
        return;
    };
    ui.label("·");
    let text = if shown.group.is_some() {
        format!("touch notes {}…", touch.data1)
    } else {
        format!("touch note {}", touch.data1)
    };
    token(ui, &text, token_color(TokenKind::Encoder)).on_hover_text(
        "The note the control sends while a finger rests on it; gled outlines what it changes meanwhile. \
         Change it under MIDI.",
    );
}

/// Copy, MIDI details and delete.
fn card_buttons(ui: &mut Ui, cards: &mut Cards, shown: &Shown) {
    let first = shown.first();
    let key = (first.control, first.mode);
    if ui
        .small_button(icons::TRASH)
        .on_hover_text("Delete this rule with its lights")
        .clicked()
    {
        cards
            .intents
            .push(Intent::RemoveRules(shown.members.clone()));
    }
    if shown.group.is_none() {
        let open = cards.state.midi_open.contains(&key);
        if ui
            .selectable_label(open, "MIDI")
            .on_hover_text("The MIDI messages of this rule")
            .clicked()
        {
            if open {
                cards.state.midi_open.retain(|other| *other != key);
            } else {
                cards.state.midi_open.push(key);
            }
        }
        let copying = cards.state.copying == Some(key);
        if ui
            .selectable_label(copying, super::iconized(ui, icons::COPY, " Copy…"))
            .on_hover_text("Copy this rule to other controls, counting its numbers up")
            .clicked()
        {
            cards.state.copying = (!copying).then_some(key);
        }
    }
}

/// Rules of the same controls that act in the same mode too ("in all
/// modes" and "in mode Rows"), so a press does both; with a fix.
fn conflicts(ui: &mut Ui, cards: &mut Cards, shown: &Shown) {
    let mapping = cards.mapping;
    let acts = |rule: &Rule| rule.press.or(rule.release).is_some();
    let mut others: Vec<Rule> = Vec::new();
    for member in &shown.members.rules {
        if !acts(member) {
            continue;
        }
        for other in cards.rules {
            let overlaps =
                member.mode.is_none() || other.mode.is_none() || member.mode == other.mode;
            if other.control == member.control
                && other != member
                && overlaps
                && acts(other)
                && !others.contains(other)
            {
                others.push(other.clone());
            }
        }
    }
    let Some(first) = others.first() else {
        return;
    };
    let control = &cards.controls[first.control].name;
    let where_ = match first.mode {
        Some(mode) => format!("in mode {}", mode_name(&mapping.modes, mode)),
        None => "in all modes".to_owned(),
    };
    let does = first
        .press
        .or(first.release)
        .map(|index| {
            super::rules::text(&action_sentence(
                &mapping.input_bindings[index].action,
                &mapping.modes,
                &Plain,
            ))
        })
        .unwrap_or_default();
    ui.horizontal_wrapped(|ui| {
        ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
        ui.add_space(22.0);
        ui.colored_label(ui.visuals().warn_fg_color, icons::WARNING.regular());
        let more = if others.len() > 1 {
            format!(" (and {} more)", others.len() - 1)
        } else {
            String::new()
        };
        ui.colored_label(
            ui.visuals().warn_fg_color,
            format!("{control} also {does} {where_}{more} — both happen"),
        );
        let label = if others.len() == 1 {
            "Remove that rule".to_owned()
        } else {
            format!("Remove those {} rules", others.len())
        };
        if ui.small_button(label).clicked() {
            cards.intents.push(Intent::RemoveRules(Members {
                numbers: vec![1; others.len()],
                rules: others.clone(),
            }));
        }
    });
}

/// The group's members as number cells; a click opens that control's own
/// rule under the group.
fn member_cells(ui: &mut Ui, cards: &mut Cards, shown: &Shown, group: &RuleGroup) {
    let first = shown.first();
    ui.horizontal_wrapped(|ui| {
        ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
        ui.weak("n =");
        for (rule, number) in shown.members.rules.iter().zip(&group.numbers) {
            let control = &cards.controls[rule.control];
            let open = cards.state.open_member == Some((first.control, first.mode, rule.control));
            if ui
                .selectable_label(open, number.to_string())
                .on_hover_text(format!("{} — show its own rule", control.name))
                .clicked()
            {
                cards.state.open_member =
                    (!open).then_some((first.control, first.mode, rule.control));
            }
        }
        let first_control = &cards.controls[first.control];
        let explanation = if first_control.named_by_message {
            "(n is the control's place in the group, from 1)".to_owned()
        } else {
            format!(
                "(n is the number in the control's name: {} has n = {})",
                first_control.name, group.numbers[0]
            )
        };
        ui.weak(explanation);
    });
}

/// "Note 32–39" or "CC 7 · ch 1–8" for a group named after its messages.
fn message_range(
    first: &gled_model::asset::midi_controller::MidiTrigger,
    last: &gled_model::asset::midi_controller::MidiTrigger,
) -> String {
    let first_channel = (first.status & 0x0F) + 1;
    let last_channel = (last.status & 0x0F) + 1;
    let kind = match first.status & 0xF0 {
        0x80 | 0x90 => "Note",
        0xB0 => "CC",
        0xE0 => "Pitch bend",
        _ => "Message",
    };
    if first_channel != last_channel {
        if first.status & 0xF0 == 0xE0 {
            format!("{kind} ch {first_channel}–{last_channel}")
        } else {
            format!("{kind} {} · ch {first_channel}–{last_channel}", first.data1)
        }
    } else if first_channel == 1 {
        format!("{kind} {}–{}", first.data1, last.data1)
    } else {
        format!("{kind} {}–{} · ch {first_channel}", first.data1, last.data1)
    }
}