gled 2.28.4

gled is an application for creating animations and effects on artnet or dmx installations
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
use super::{App, svg::Svg};
use crate::ui::scoped_frame;
use crate::{
    app::timing::{CONNECTED_PEERS, LINK_ACTIVE_COLOR},
    input::artnet::ARTNET_CONFIG,
    storage::{STORAGE_DIR, asset::Asset},
    ui::{
        action::UiAction, logo::logo_image, window_common::window_buttons,
        windows::channel_overwrites::ChannelOverwrites,
    },
};
use egui::{
    Button, Color32, Frame, Id, Image, Key, KeyboardShortcut, Modifiers, PointerButton, Response,
    Sense, Slider, Stroke, TextFormat, Ui, UiBuilder, UiKind, Vec2, ViewportCommand, ViewportId,
    Widget, text::LayoutJob,
};
use epaint::{Margin, RectShape, StrokeKind};
use std::{
    sync::{Arc, atomic::Ordering::Relaxed},
    time::{SystemTime, UNIX_EPOCH},
};
use tracing::debug;

const BPM_BAR_WIDTH: f32 = 500.0;

impl App {
    pub fn menu(&mut self, ui: &mut Ui, viewport_id: Option<ViewportId>) {
        egui::Panel::top(format!("{viewport_id:?} menu")).show_inside(ui, |ui| {
            if crate::storage::is_loading() {
                ui.disable();
            }
            let title_bar_response = ui.interact(
                ui.available_rect_before_wrap(),
                Id::new("title_bar"),
                Sense::click_and_drag(),
            );

            // Interact with the title bar (drag to move window):
            if title_bar_response.double_clicked() {
                let is_maximized = ui.input(|i| i.viewport().maximized.unwrap_or(false));
                ui.ctx()
                    .send_viewport_cmd(ViewportCommand::Maximized(!is_maximized));
            }

            if title_bar_response.drag_started_by(PointerButton::Primary) {
                ui.ctx().send_viewport_cmd(ViewportCommand::StartDrag);
            }

            egui::MenuBar::new().ui(ui, |ui| {
                Frame::new().show(ui, |ui| {
                    ui.set_height(32.0);
                    let mut bpm_rect = ui.available_rect_before_wrap();
                    bpm_rect.set_left((bpm_rect.width() - BPM_BAR_WIDTH) * 0.55);
                    bpm_rect.set_width(BPM_BAR_WIDTH);

                    self.menus(ui);
                    ui.put(bpm_rect, BpmBar { app: self });
                    self.window_buttons(ui);
                });
            });
        });
    }

    fn menus(&mut self, ui: &mut Ui) {
        ui.horizontal_centered(|ui| {
            ui.take_available_height();
            ui.scope(|ui| {
                ui.spacing_mut().button_padding = egui::vec2(4.0, 4.0);

                if ui.add(Button::image(Image::new(logo_image()))).clicked() {
                    self.windows.about.toggle();
                };

                ui.separator();

                let mut open_project = ui
                    .ctx()
                    .input_mut(|i| i.consume_key(Modifiers::COMMAND, Key::O));
                let mut save_project = ui
                    .ctx()
                    .input_mut(|i| i.consume_key(Modifiers::COMMAND, Key::S));
                let mut open_svg_file = ui.ctx().input_mut(|i| {
                    i.consume_key(Modifiers::COMMAND.plus(Modifiers::SHIFT), Key::O)
                });
                let mut save_svg_file = ui.ctx().input_mut(|i| {
                    i.consume_key(Modifiers::COMMAND.plus(Modifiers::SHIFT), Key::S)
                });

                ui.menu_button("Project", |ui| {
                    ui.set_min_width(300.0);

                    if let Some(project) = self
                        .project_id
                        .and_then(|id| Asset::get(id, &self.collections))
                    {
                        ui.label(format!("Project: {}", project.name()));
                    } else {
                        ui.label("No project loaded");
                    }

                    ui.separator();

                    if ui
                        .add(Button::new("Load project").shortcut_text(
                            ui.ctx().format_shortcut(&KeyboardShortcut::new(
                                Modifiers::COMMAND,
                                Key::O,
                            )),
                        ))
                        .clicked()
                    {
                        open_project = true;
                        ui.close_kind(UiKind::Menu);
                    }

                    if ui
                        .add_enabled(
                            self.project.is_some(),
                            Button::new("Save project").shortcut_text(ui.ctx().format_shortcut(
                                &KeyboardShortcut::new(Modifiers::COMMAND, Key::S),
                            )),
                        )
                        .clicked()
                    {
                        save_project = true;
                        ui.close_kind(UiKind::Menu);
                    }

                    if ui
                        .add_enabled(self.project.is_some(), Button::new("Close project"))
                        .clicked()
                    {
                        self.project.take();
                        ui.close_kind(UiKind::Menu);
                    }

                    ui.separator();

                    if ui
                        .add_enabled(
                            self.project.is_some(),
                            Button::new("Open SVG file").shortcut_text(ui.ctx().format_shortcut(
                                &KeyboardShortcut::new(
                                    Modifiers::COMMAND | Modifiers::SHIFT,
                                    Key::O,
                                ),
                            )),
                        )
                        .clicked()
                    {
                        open_svg_file = true;
                        ui.close_kind(UiKind::Menu);
                    }

                    if ui
                        .add_enabled(
                            self.svg().is_some(),
                            Button::new("Save SVG file").shortcut_text(ui.ctx().format_shortcut(
                                &KeyboardShortcut::new(
                                    Modifiers::COMMAND | Modifiers::SHIFT,
                                    Key::S,
                                ),
                            )),
                        )
                        .clicked()
                    {
                        save_svg_file = true;
                        ui.close_kind(UiKind::Menu);
                    }

                    if ui.button("Open SVG templates folder").clicked() {
                        open::that(STORAGE_DIR.join("svg")).ok();
                        ui.close_kind(UiKind::Menu);
                    }

                    ui.separator();

                    if ui
                        .add_enabled(self.project.is_some(), Button::new("External Devices"))
                        .clicked()
                    {
                        self.windows.external_device_settings.open();
                        ui.close_kind(UiKind::Menu);
                    }
                    if ui
                        .add_enabled(self.project.is_some(), Button::new("Channel Overwrites"))
                        .clicked()
                    {
                        self.windows.channel_overwrites.open();
                        ui.close_kind(UiKind::Menu);
                    }
                    if ui
                        .add_enabled(self.project.is_some(), Button::new("Output Routings"))
                        .clicked()
                    {
                        self.windows.output_routings.open();
                        ui.close_kind(UiKind::Menu);
                    }
                    if ui
                        .add_enabled(self.project.is_some(), Button::new("Shortcuts"))
                        .clicked()
                    {
                        self.windows.shortcuts.open();
                        ui.close_kind(UiKind::Menu);
                    }
                });

                if open_project {
                    self.windows.projects.open();
                }
                if save_project
                    && let (Some(project), Some(mut asset)) = (
                        self.project.as_ref(),
                        self.project_id
                            .and_then(|id| Asset::get(id, &self.collections))
                            .map(Arc::unwrap_or_clone),
                    )
                {
                    asset.data = project.to_owned();
                    asset.data.artnet_config = ARTNET_CONFIG.lock().clone();
                    asset.data.output_routings = self.extract_output.routings.clone();
                    asset.data.channel_overwrites = ChannelOverwrites::get();
                    asset.save(&mut self.collections);
                }

                if open_svg_file {
                    std::thread::Builder::new()
                        .name("gled:ui:open_svg".to_string())
                        .spawn(|| {
                            if let Some(path) = rfd::FileDialog::new()
                                .set_title("Open SVG file")
                                .add_filter("svg", &["svg"])
                                .pick_file()
                            {
                                UiAction::SetSvg(match Svg::load(&path) {
                                    Ok(svg) => {
                                        debug!("Loaded svg file \"{}\"", path.display());
                                        Some(svg)
                                    }
                                    Err(err) => {
                                        UiAction::Error(format!(
                                            "Could not load svg file \"{}\": {err:?}",
                                            path.display()
                                        ))
                                        .enqueue();

                                        None
                                    }
                                })
                                .enqueue();
                            }
                        })
                        .ok();
                }
                if save_svg_file
                    && let (Some(svg), Some(path)) = (
                        self.svg(),
                        rfd::FileDialog::new()
                            .set_title("Save SVG file")
                            .add_filter("svg", &["svg"])
                            .save_file(),
                    )
                {
                    match svg.save(&path) {
                        Ok(_) => {
                            debug!("Saved svg file \"{}\"", path.display());
                        }
                        Err(err) => {
                            UiAction::Error(format!(
                                "Could not save svg file \"{}\": {err:?}",
                                path.display()
                            ))
                            .enqueue();
                        }
                    };
                }

                ui.menu_button("Assets", |ui| {
                    ui.set_min_width(300.0);

                    if ui.button("Animations").clicked() {
                        self.windows.animations.open();
                        ui.close_kind(UiKind::Menu);
                    }
                    if ui.button("Curves").clicked() {
                        self.windows.curves.open();
                        ui.close_kind(UiKind::Menu);
                    }
                    if ui.button("Output Devices").clicked() {
                        self.windows.output_devices.open();
                        ui.close_kind(UiKind::Menu);
                    }
                    if ui.button("MIDI Controllers").clicked() {
                        self.windows.midi_controllers.open();
                        ui.close_kind(UiKind::Menu);
                    }
                    if ui.button("Palettes").clicked() {
                        self.windows.palettes.open();
                        ui.close_kind(UiKind::Menu);
                    }
                    if ui.button("Projects").clicked() {
                        self.windows.projects.open();
                        ui.close_kind(UiKind::Menu);
                    }
                    if ui.button("Scenes").clicked() {
                        self.windows.scenes.open();
                        ui.close_kind(UiKind::Menu);
                    }
                });

                ui.menu_button("Config", |ui| {
                    ui.set_min_width(300.0);

                    if ui.button("Git Configuration").clicked() {
                        self.windows.git_config.open();
                        ui.close_kind(UiKind::Menu);
                    }

                    ui.separator();

                    ui.label("GPU preference");
                    let mut prefer_discrete_gpu = self.persistent_state.prefer_discrete_gpu();
                    if ui
                        .checkbox(
                            &mut prefer_discrete_gpu,
                            "Prefer discrete GPU (changing requires restart of GLED)",
                        )
                        .on_hover_text("Needs restart of gled")
                        .changed()
                    {
                        self.persistent_state
                            .set_prefer_discrete_gpu(prefer_discrete_gpu);
                        self.persistent_state.save();
                    }
                    ui.label("Framerate Limiter");
                    let mut fps_limit = self.persistent_state.fps_limit();
                    ui.spacing_mut().slider_width = 290.0;
                    if ui
                        .add(
                            Slider::new(&mut fps_limit, 30.0..=1000.0)
                                .integer()
                                .custom_formatter(|n, _| format!("{n:.0} fps")),
                        )
                        .changed()
                    {
                        self.persistent_state.set_fps_limit(fps_limit);
                        self.persistent_state.save();
                    }
                    if ui
                        .checkbox(
                            self.persistent_state.effects_always_render_mut(),
                            "Always render all scenes",
                        )
                        .changed()
                    {
                        self.persistent_state.save();
                    };

                    if ui
                        .checkbox(
                            self.persistent_state.double_render_mut(),
                            "Render twice per frame (2× output rate)",
                        )
                        .changed()
                    {
                        self.persistent_state.save();
                    };

                    ui.separator();

                    egui::gui_zoom::zoom_menu_buttons(ui);
                });

                let mut open_new_window = ui.ctx().input_mut(|i| {
                    i.consume_key(Modifiers::COMMAND.plus(Modifiers::SHIFT), Key::N)
                });
                ui.menu_button("Window", |ui| {
                    ui.set_min_width(300.0);

                    if ui
                        .add(Button::new("Open new window").shortcut_text(
                            ui.ctx().format_shortcut(&KeyboardShortcut::new(
                                Modifiers::COMMAND.plus(Modifiers::SHIFT),
                                Key::N,
                            )),
                        ))
                        .clicked()
                    {
                        open_new_window = true;
                        ui.close_kind(UiKind::Menu);
                    }
                });

                if open_new_window {
                    let viewport_id =
                        ViewportId(Id::new(format!("Second Window {}", rand::random::<u64>())));
                    self.other_main_windows.insert(viewport_id);
                }
                ui.separator();
            });
        });
    }

    fn window_buttons(&mut self, ui: &mut Ui) {
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            window_buttons(ui);

            let underlined = TextFormat {
                underline: Stroke::new(1.0, Color32::GRAY),
                ..Default::default()
            };
            let mut blackout_text = LayoutJob::default();
            blackout_text.append("B", 0.0, underlined);
            blackout_text.append("lackout", 0.0, TextFormat::default());
            let mut blackout = Button::new(blackout_text);
            if self.blackout
                && SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .map(|d| d.as_millis() / 200 % 2 == 0)
                    .unwrap_or_default()
            {
                blackout = blackout.fill(Color32::DARK_RED);
            }
            if ui
                .add_sized(Vec2::new(100.0, BUTTON_HEIGHT), blackout)
                .clicked()
                || self
                    .project
                    .as_ref()
                    .map(|project| project.blackout_input_is_new())
                    .unwrap_or_default()
            {
                self.blackout = !self.blackout;
            }

            self.blackout_hold = self
                .project
                .as_ref()
                .map(|project| project.blackout_hold_input_is_live())
                .unwrap_or_default();

            ui.separator();
        });
    }
}

struct BpmBar<'a> {
    pub app: &'a mut App,
}

const BUTTON_HEIGHT: f32 = 25.0;

impl Widget for BpmBar<'_> {
    fn ui(self, ui: &mut Ui) -> Response {
        let app = self.app;
        let rect = ui.available_rect_before_wrap();

        let resp = scoped_frame(
            ui,
            UiBuilder::default()
                .max_rect(rect)
                .layout(egui::Layout::right_to_left(egui::Align::Center)),
            Frame::new()
                .fill(Color32::from_gray(20))
                .inner_margin(Margin::symmetric(10, 0)),
            |ui| {
                // add background shadow
                ui.painter().add(
                    RectShape::filled(
                        ui.available_rect_before_wrap().expand(1.0),
                        ui.ctx().global_style().visuals.widgets.active.corner_radius,
                        Color32::from_white_alpha(10),
                    )
                    .with_blur_width(15.0),
                );

                app.timing.tap_button(
                    ui,
                    Vec2::new(80.0, BUTTON_HEIGHT),
                    app.project
                        .as_ref()
                        .map(|project| project.tap_input_is_new())
                        .unwrap_or_default(),
                    &app.persistent_state,
                );

                app.timing.double_button(
                    ui,
                    app.project
                        .as_ref()
                        .map(|project| project.double_input_is_new())
                        .unwrap_or_default(),
                    &app.persistent_state,
                );
                app.timing.half_button(
                    ui,
                    app.project
                        .as_ref()
                        .map(|project| project.half_input_is_new())
                        .unwrap_or_default(),
                    &app.persistent_state,
                );

                ui.spacing_mut().slider_width = ui.available_width() - 80.0;
                ui.add_enabled(
                    !app.persistent_state.ableton_link_read_only(),
                    Slider::new(&mut app.timing.change_beats_per_minute, 20.0..=999.0)
                        .custom_formatter(|n, _| format!("{n:.1} bpm")),
                );
            },
        );
        ui.painter().vline(
            rect.left(),
            rect.top()..=rect.bottom(),
            ui.style().visuals.widgets.noninteractive.bg_stroke,
        );
        ui.painter().vline(
            rect.right(),
            rect.top()..=rect.bottom(),
            ui.style().visuals.widgets.noninteractive.bg_stroke,
        );
        if CONNECTED_PEERS.load(Relaxed) > 0 {
            ui.painter().rect_stroke(
                rect,
                5.0,
                Stroke::new(1.0, LINK_ACTIVE_COLOR),
                StrokeKind::Outside,
            );
        }
        resp.response
    }
}