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
//! The controller editor: a top bar (learn, undo, test lights), the rules
//! as sentences, a status line, and the side tabs. Clicks become intents
//! that are applied after drawing, each as one undo step.

use std::collections::VecDeque;

use egui::{Panel, RichText, ScrollArea, Ui};
use gled_model::{
    asset::{
        Asset,
        midi_controller::{MidiController, MidiOutputBindingKind, normalize_controller_key},
    },
    asset_id::AssetId,
};
use gled_protocol::midi::{MidiMonitorEvent, TestCommand};
use kanal::Sender;

use super::MidiControllerTestState;
use super::color_editor::colors_tab;
use super::intent::{Intent, apply};
use super::learning::{
    Learned, Pending, hardware_message, new_control, start_learning, take_captures,
};
use super::list_state::{LearnRequest, ListState};
use super::rule_card::Cards;
use super::rule_list::rule_list;
use super::rules::{Rule, build_rules, control_index, controls_of, find_groups};
use super::side_tabs::{SideTab, devices_tab, modes_tab, monitor_tab, tab_bar};
use super::status_line::StatusLine;
use super::test_panel::render_test_device_box;
use crate::canvas::{edit::Edit, undo::UndoStack};
use crate::midi_learn::{LearnState, MidiPortDiagnostics};
use crate::ui::frame_requests;

/// What the editor remembers between frames.
#[derive(Debug, Default)]
pub(super) struct EditorState {
    list: ListState,
    undo: UndoStack<MidiController>,
    status: StatusLine,
    tab: SideTab,
    controller: Option<AssetId<MidiController>>,
    /// Learning goes on control after control until stopped.
    learning: bool,
    pending: Option<Pending>,
    /// The newest monitor event already followed.
    followed_until: u128,
}

/// What the editor works with besides the controller.
pub(super) struct EditorContext<'a> {
    pub(super) test_state: &'a mut MidiControllerTestState,
    pub(super) test_command_sender: &'a Sender<TestCommand>,
    pub(super) dirty: &'a mut bool,
    pub(super) project: &'a mut Option<gled_model::asset::project::Project>,
    pub(super) diagnostics: &'a [MidiPortDiagnostics],
    pub(super) learn_state: &'a mut LearnState,
    pub(super) events: &'a mut VecDeque<MidiMonitorEvent>,
    pub(super) others: &'a [super::OtherController],
    /// A device another controller should no longer be used for.
    pub(super) take_over: &'a mut Option<(AssetId<MidiController>, String)>,
}

pub(super) fn midi_controller_editor(
    ui: &mut Ui,
    controller: &mut Asset<MidiController>,
    state: &mut EditorState,
    context: EditorContext,
) {
    if state.controller != Some(controller.id) {
        state.controller = Some(controller.id);
        state.list.reset();
        state.undo.clear();
        state.pending = None;
        state.learning = false;
        context.learn_state.disarm();
    }
    context.learn_state.flush_timeouts();
    let controller_id = controller.id;
    let mut edit = Edit::new(&mut controller.data, &mut state.undo);

    let mut controls = controls_of(&edit.value.mapping);
    let mut intents: Vec<Intent> = Vec::new();

    // Learned controls.
    let learned = edit.apply(|controller| {
        take_captures(
            context.learn_state,
            controller_id,
            &mut controller.mapping,
            &mut controls,
        )
    });
    for learned in learned {
        match learned {
            Learned::Pending(pending) => {
                let index = control_index(&controls, &pending.trigger);
                let control = index.unwrap_or(controls.len());
                state.list.open_palette = Some((control, pending.mode));
                state.list.scroll_to = Some(control);
                let name = index.map_or_else(
                    || super::rules::message_name(&pending.trigger),
                    |index| controls[index].name.clone(),
                );
                state
                    .status
                    .edit(ui, format!("Learned {name} — pick what it does"));
                state.pending = Some(pending);
            }
            Learned::Existing(control) => {
                state.list.scroll_to = Some(control);
                state.list.highlight = Some((control, ui.input(|input| input.time)));
                state.status.edit(
                    ui,
                    format!("{} already has a rule here", controls[control].name),
                );
            }
            Learned::Message(message) => state.status.edit(ui, message),
        }
    }
    if let Some(pending) = &state.pending
        && control_index(&controls, &pending.trigger).is_none()
    {
        controls.push(new_control(&pending.trigger));
    }

    let mut rules = build_rules(&edit.value.mapping, &controls);
    // A learned control's rule waiting for its action.
    if let Some(pending) = state.pending.clone() {
        let control = control_index(&controls, &pending.trigger).unwrap_or(0);
        let exists = rules.iter().any(|rule| {
            rule.control == control
                && rule.mode == pending.mode
                && rule.press.or(rule.release).is_some()
        });
        let palette_closed =
            state.list.open_palette.is_none() && !egui::Popup::is_any_open(ui.ctx());
        if exists {
            state.pending = None;
        } else if palette_closed {
            state.status.edit(
                ui,
                format!(
                    "{} sends {} — no rule made",
                    controls[control].name,
                    super::rules::message_name(&pending.trigger)
                ),
            );
            state.pending = None;
        } else {
            rules.push(Rule {
                control,
                mode: pending.mode,
                press: None,
                release: None,
                feedback: Vec::new(),
            });
        }
    }
    let groups = find_groups(&edit.value.mapping, &controls, &rules);

    follow_hardware(
        ui,
        &mut state.list,
        &mut state.status,
        &mut state.followed_until,
        context.events,
        &edit.value.mapping,
        &controls,
        &rules,
    );
    super::top_bar::keys(
        ui,
        &mut state.list,
        &mut state.learning,
        &mut edit,
        context.learn_state,
    );

    // Side tabs.
    let mut previewed = Vec::new();
    Panel::right("midi controller tabs")
        .exact_size(340.0)
        .resizable(false)
        .show(ui, |ui| {
            tab_bar(ui, &mut state.tab);
            match state.tab {
                SideTab::Monitor => monitor_tab(ui, context.events, context.diagnostics, &controls),
                SideTab::Colors => {
                    let mut colors = edit.value.mapping.color_mappings.clone();
                    let changed = ScrollArea::vertical()
                        .show(ui, |ui| {
                            colors_tab(
                                ui,
                                &mut colors,
                                &edit.value.mapping.output_bindings,
                                context.test_command_sender,
                            )
                        })
                        .inner;
                    if changed {
                        edit.apply(|controller| controller.mapping.color_mappings = colors);
                    }
                }
                SideTab::Modes => {
                    ScrollArea::vertical().show(ui, |ui| {
                        modes_tab(ui, edit.value, &mut intents, &mut state.list)
                    });
                }
                SideTab::Devices => {
                    let known: Vec<String> = context
                        .diagnostics
                        .iter()
                        .map(|port| port.port_name.clone())
                        .chain(frame_requests::local_midi().ports)
                        .collect();
                    let mut ports = edit.value.default_for_ports.clone();
                    if devices_tab(ui, &mut ports, &known, context.others, context.take_over) {
                        edit.apply(|controller| controller.default_for_ports = ports);
                    }
                    ui.add_space(12.0);
                    ui.label(RichText::new("Test lights").strong());
                    ui.weak("Pick a connected device to light what you point at in the rules.");
                    let picked = render_test_device_box(
                        ui,
                        context.test_state,
                        context.diagnostics,
                        controller_id,
                        context.test_command_sender,
                    );
                    if let Some(port) = picked {
                        disconnect_project_mapping_for_test_port(context.project, &port);
                    }
                }
            }
        });

    // Top bar, rules, status line.
    super::top_bar::top_bar(
        ui,
        super::top_bar::Bar {
            list: &mut state.list,
            learning: &mut state.learning,
            tab: &mut state.tab,
            edit: &mut edit,
            learn_state: context.learn_state,
            test_state: context.test_state,
        },
    );
    {
        let mut cards = Cards {
            mapping: &edit.value.mapping,
            controls: &controls,
            rules: &rules,
            state: &mut state.list,
            intents: &mut intents,
            previewed: &mut previewed,
        };
        super::rule_list::mode_chips(ui, &mut cards);
    }
    ui.separator();
    let status_height = 24.0;
    ScrollArea::vertical()
        .max_height(ui.available_height() - status_height)
        .auto_shrink([false, false])
        .show(ui, |ui| {
            let mut cards = Cards {
                mapping: &edit.value.mapping,
                controls: &controls,
                rules: &rules,
                state: &mut state.list,
                intents: &mut intents,
                previewed: &mut previewed,
            };
            rule_list(ui, &mut cards, &groups);
        });
    ui.separator();
    state.status.show(ui);

    // Apply what was clicked.
    for intent in intents {
        // A rule changed on its own may move (out of its group, to another
        // mode); the list follows it.
        let follow = match &intent {
            Intent::SetAction { members, .. } | Intent::SetMode { members, .. }
                if members.rules.len() == 1 =>
            {
                Some(members.rules[0].control)
            }
            _ => None,
        };
        if let Some(control) = follow {
            state.list.scroll_to = Some(control);
            state.list.highlight = Some((control, ui.input(|input| input.time)));
        }
        let message =
            edit.apply(|controller| apply(intent, &mut controller.mapping, &mut controls));
        if let Some(message) = message {
            state.status.edit(ui, message);
        }
    }
    if let Some(request) = state.list.learn_request.take() {
        state.learning = request == LearnRequest::NewControls;
        start_learning(context.learn_state, controller_id, request, &state.list);
    }
    if state.learning && context.learn_state.active_request().is_none() && state.pending.is_none() {
        start_learning(
            context.learn_state,
            controller_id,
            LearnRequest::NewControls,
            &state.list,
        );
    }

    // Test lights for what the pointer is on.
    context.test_state.value_preview_binding_indices = previewed.into_iter().collect();
    *context.dirty |= edit.changed();
    emit_test_output_commands(
        &controller.data.mapping.output_bindings,
        context.test_state,
        context.test_command_sender,
    );
}

/// Highlights the rule of each control moved on the hardware since the
/// last frame and says what it did.
#[allow(clippy::too_many_arguments)]
fn follow_hardware(
    ui: &Ui,
    list: &mut ListState,
    status: &mut StatusLine,
    followed_until: &mut u128,
    events: &VecDeque<MidiMonitorEvent>,
    mapping: &gled_model::asset::midi_controller::MidiControllerMapping,
    controls: &[super::rules::Control],
    rules: &[Rule],
) {
    let newest = events.back().map_or(0, |event| event.timestamp_ms);
    if newest <= *followed_until {
        return;
    }
    for event in events
        .iter()
        .filter(|event| event.timestamp_ms > *followed_until)
    {
        if let Some((control, message)) =
            hardware_message(event, mapping, controls, rules, list.filter)
        {
            if let Some(control) = control {
                list.highlight = Some((control, ui.input(|input| input.time)));
                list.scroll_to = Some(control);
            }
            status.hardware(ui, message);
        }
    }
    *followed_until = newest;
}

fn disconnect_project_mapping_for_test_port(
    project: &mut Option<gled_model::asset::project::Project>,
    selected_port_name: &str,
) {
    let Some(project) = project.as_mut() else {
        return;
    };

    let normalized_selected = normalize_controller_key(selected_port_name);
    project
        .midi_active_mappings
        .retain(|port_name, _| normalize_controller_key(port_name) != normalized_selected);
}

/// Sends the "on" value of each output the pointer is on to the test
/// device, and clears those it left.
fn emit_test_output_commands(
    bindings: &[gled_model::asset::midi_controller::MidiOutputBinding],
    test_state: &mut MidiControllerTestState,
    test_command_sender: &Sender<TestCommand>,
) {
    let message =
        |binding: &gled_model::asset::midi_controller::MidiOutputBinding| match &binding.kind {
            MidiOutputBindingKind::Value(value) => {
                Some((value.status, value.data1, value.active_value))
            }
            MidiOutputBindingKind::SceneColorValue(color) => Some((color.status, color.data1, 127)),
            MidiOutputBindingKind::Meter(meter) => Some((0xD0, meter.strip << 4, 12)),
        };
    for &index in &test_state.value_preview_binding_indices {
        if let Some((status, data1, value)) = bindings.get(index).and_then(message) {
            let _ = test_command_sender.send(TestCommand::SendOutput {
                status,
                data1,
                value,
            });
        }
    }
    for &index in &test_state.value_preview_binding_indices_previous {
        if !test_state.value_preview_binding_indices.contains(&index)
            && let Some((status, data1, _)) = bindings.get(index).and_then(message)
        {
            let _ = test_command_sender.send(TestCommand::ClearOutput { status, data1 });
        }
    }
    test_state.value_preview_binding_indices_previous =
        test_state.value_preview_binding_indices.clone();
}