drawbar 0.6.0

Your Nord's sounds, in a window: browse, edit and send programs, samples and pianos, in the browser or on the desktop
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
//! The header a dock wears, the geometry every dock header shares, and how a button in
//! a bar wears the bar it sits in.

use std::ops::Range;

use eframe::egui;

use crate::icon::{icon, Glyph};

/// How tall a section header is, wherever it is drawn.
pub const HEADER: f32 = 24.0;

/// How tall a dock's own header is: the tab strip's height, so the strip and the header
/// of every dock beside it read as one line across the window.
pub const DOCK: f32 = crate::tabs::HEIGHT;

/// The room a bar keeps at each end, and the gap between its parts. The title bar, the
/// tool bar, the tab strip and every header share them, so their contents line up down
/// the window.
pub(crate) const PAD: f32 = 8.0;
pub(crate) const GAP: f32 = 6.0;

/// A glyph in a bar: a toolbar action's, a tab's kind, a menu item's mark.
pub(crate) const GLYPH: f32 = 13.0;

/// The collapse triangle's box, and the grip a dock header wears before its title.
const CHEVRON: f32 = 12.0;
const GRIP: f32 = 12.0;

/// How much of the caption ink the grip keeps. It is decoration, not a control.
const GRIP_ALPHA: f32 = 0.6;

/// What a column of a table asks for: a fixed width, a share of what the fixed ones
/// leave, or a share that stops growing once it holds `max` px and leaves the rest to
/// the other shares.
pub enum Track {
    Px(f32),
    Share(f32),
    Capped { share: f32, max: f32 },
}

impl Track {
    fn px(&self) -> f32 {
        match self {
            Track::Px(px) => *px,
            Track::Share(_) | Track::Capped { .. } => 0.0,
        }
    }

    fn share(&self) -> f32 {
        match self {
            Track::Px(_) => 0.0,
            Track::Share(share) | Track::Capped { share, .. } => *share,
        }
    }
}

/// What one unit of share buys out of `spare`, once every cap that binds has taken its
/// maximum and left the rest to the shares still growing.
///
/// A cap binds when one share buys more than `max / share`, and each one that binds only
/// raises what the rest are worth — so caps taken in that order settle in a single pass.
fn rate(spare: f32, wanted: &[Track]) -> f32 {
    let mut caps: Vec<(f32, f32)> = wanted
        .iter()
        .filter_map(|track| match track {
            Track::Capped { share, max } => Some((*share, *max)),
            Track::Px(_) | Track::Share(_) => None,
        })
        .collect();
    caps.sort_by(|(share, max), (other, limit)| (max / share).total_cmp(&(limit / other)));

    let mut spare = spare;
    let mut pool: f32 = wanted.iter().map(Track::share).sum();
    for (share, max) in caps {
        if pool <= 0.0 || spare / pool * share <= max {
            break;
        }
        spare -= max;
        pool -= share;
    }
    match pool > 0.0 {
        true => spare / pool,
        false => 0.0,
    }
}

/// Where each track sits across `width`, with `gap` between two of them.
///
/// The fixed tracks are laid out first, the shares split what is left, and a share that
/// reaches its cap passes the remainder to the others. When even the fixed ones do not
/// fit, every track and every gap shrinks by one factor — so a track may reach zero, but
/// none is ever negative and none reaches past `width`.
pub fn tracks(width: f32, wanted: &[Track], gap: f32) -> Vec<Range<f32>> {
    let gaps = gap * (wanted.len().saturating_sub(1)) as f32;
    let fixed: f32 = wanted.iter().map(Track::px).sum();
    let spare = (width - gaps - fixed).max(0.0);
    let rate = rate(spare, wanted);
    let asked: Vec<f32> = wanted
        .iter()
        .map(|track| match track {
            Track::Px(px) => *px,
            Track::Share(share) => rate * share,
            Track::Capped { share, max } => (rate * share).min(*max),
        })
        .collect();

    let total: f32 = asked.iter().sum::<f32>() + gaps;
    let scale = match total > width {
        true => (width / total).max(0.0),
        false => 1.0,
    };
    let mut x = 0.0;
    asked
        .iter()
        .map(|held| {
            let track = x..x + held * scale;
            x = track.end + gap * scale;
            track
        })
        .collect()
}

/// A bordered glyph and a word: what the library's bar is narrowed by, and what the
/// selection wears.
///
/// A chip given a `fill` is **solid** — what it says is true of everything it stands
/// for. One without is hollow, and true of only some of it.
pub fn chip(
    ui: &mut egui::Ui,
    glyph: Glyph,
    size: f32,
    text: &str,
    tint: egui::Color32,
    fill: Option<egui::Color32>,
) -> egui::Response {
    let border = ui.visuals().widgets.noninteractive.bg_stroke.color;
    egui::Frame::new()
        .fill(fill.unwrap_or(egui::Color32::TRANSPARENT))
        .stroke(egui::Stroke::new(1.0_f32, border))
        .corner_radius(2.0)
        .inner_margin(egui::Margin::symmetric(5, 1))
        .show(ui, |ui| {
            ui.spacing_mut().item_spacing.x = 4.0;
            icon(ui, glyph, size, tint);
            ui.label(
                egui::RichText::new(text)
                    .text_style(crate::app::ui())
                    .color(tint),
            );
        })
        .response
}

/// A header title: [`crate::app::micro`], uppercased.
///
/// Uppercasing is the whole of the treatment — egui has no letter spacing, and a faked
/// one is worse than none.
pub fn caps(text: &str) -> egui::RichText {
    egui::RichText::new(text.to_uppercase()).text_style(crate::app::micro())
}

/// A section header: a collapse triangle, a MICRO-caps title, an optional badge.
///
/// It wears whatever panel it is on and lifts to `faint_bg_color` under the pointer
/// alone. A dock's own header is [`dock_header`], which is not a control.
pub fn panel_header(
    ui: &mut egui::Ui,
    title: &str,
    open: Option<&mut bool>,
    badge: Option<(&str, egui::Color32)>,
) -> egui::Response {
    bar(ui, HEADER, egui::Color32::TRANSPARENT, |ui| {
        if let Some(open) = open {
            if chevron(ui, *open).clicked() {
                *open = !*open;
            }
        }
        ui.label(caps(title).color(crate::app::caption(ui.visuals())));
        let Some((badge, tint)) = badge else {
            return;
        };
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            ui.label(
                egui::RichText::new(badge)
                    .text_style(crate::app::micro())
                    .color(tint),
            );
        });
    })
}

/// A dock's own header: a grip, a MICRO-caps title, and nothing to click.
///
/// ⚠️ Collapsing a dock is its toolbar toggle and the View menu. A header carrying a
/// triangle of its own would read as one of the sections beneath it.
pub fn dock_header(ui: &mut egui::Ui, title: &str) -> egui::Response {
    let fill = ui.visuals().faint_bg_color;
    let response = bar(ui, DOCK, fill, |ui| {
        let ink = crate::app::caption(ui.visuals());
        icon(
            ui,
            Glyph::GripVertical,
            GRIP,
            ink.gamma_multiply(GRIP_ALPHA),
        );
        ui.label(caps(title).color(ink));
    });
    let stroke = egui::Stroke::new(1.0_f32, ui.visuals().widgets.noninteractive.bg_stroke.color);
    let rect = response.rect;
    ui.painter()
        .hline(rect.x_range(), rect.bottom() - 0.5, stroke);
    response
}

/// A dock header carrying its own controls: [`dock_header`]'s bar, with what the bottom
/// dock puts on it in place of a plain title.
pub fn strip<R>(ui: &mut egui::Ui, contents: impl FnOnce(&mut egui::Ui) -> R) -> egui::Response {
    let fill = ui.visuals().faint_bg_color;
    bar(ui, DOCK, fill, contents)
}

/// The bar a header is drawn into: full bleed, padded at each end, laid out left to
/// right. The response is the whole bar, so a header can be clicked as one thing.
///
/// `resting` is what the bar wears when the pointer is elsewhere; under the pointer it
/// is `faint_bg_color` whatever it wears at rest.
fn bar<R>(
    ui: &mut egui::Ui,
    height: f32,
    resting: egui::Color32,
    contents: impl FnOnce(&mut egui::Ui) -> R,
) -> egui::Response {
    let (rect, response) = ui.allocate_exact_size(
        egui::vec2(ui.available_width(), height),
        egui::Sense::click(),
    );
    let fill = match response.hovered() {
        true => ui.visuals().faint_bg_color,
        false => resting,
    };
    ui.painter().rect_filled(rect, 0.0, fill);
    let mut inner = ui.new_child(
        egui::UiBuilder::new()
            .max_rect(rect.shrink2(egui::vec2(PAD, 0.0)))
            .layout(egui::Layout::left_to_right(egui::Align::Center)),
    );
    inner.spacing_mut().item_spacing.x = GAP;
    contents(&mut inner);
    response
}

/// The triangle that says which way a section will go, and answers a click of its own.
pub fn chevron(ui: &mut egui::Ui, open: bool) -> egui::Response {
    let glyph = match open {
        true => Glyph::ChevronDown,
        false => Glyph::ChevronRight,
    };
    let drawn = icon(ui, glyph, CHEVRON, crate::app::caption(ui.visuals()));
    ui.interact(drawn.rect, drawn.id.with("chevron"), egui::Sense::click())
}

/// The four sides of a dashed border: the one stroke that says a thing is not there, or
/// that an act has nothing to act on. egui draws dashes along a line, so a rectangle is
/// four of them.
pub fn dashed_rect(painter: &egui::Painter, rect: egui::Rect, stroke: egui::Stroke) {
    const DASH: f32 = 3.0;
    let corners = [
        rect.left_top(),
        rect.right_top(),
        rect.right_bottom(),
        rect.left_bottom(),
        rect.left_top(),
    ];
    for side in corners.windows(2) {
        painter.extend(egui::Shape::dashed_line(side, stroke, DASH, DASH));
    }
}

/// Dress the buttons in a bar to wear the bar: no fill and no border until the pointer
/// is on one, which is then the only thing on the bar that is lit.
///
/// Scope this into a child `Ui` — it edits the visuals every widget after it reads.
pub fn flat(ui: &mut egui::Ui) {
    let widgets = &mut ui.visuals_mut().widgets;
    widgets.inactive.weak_bg_fill = egui::Color32::TRANSPARENT;
    widgets.inactive.bg_fill = egui::Color32::TRANSPARENT;
    for state in [
        &mut widgets.inactive,
        &mut widgets.hovered,
        &mut widgets.active,
        &mut widgets.open,
    ] {
        state.bg_stroke = egui::Stroke::NONE;
    }
}

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

    fn widths(width: f32, wanted: &[Track]) -> Vec<f32> {
        tracks(width, wanted, 0.0)
            .iter()
            .map(|track| track.end - track.start)
            .collect()
    }

    /// A capped track grows with the others until it holds `max`, and what it does not
    /// take goes to the shares beside it rather than to empty space.
    #[test]
    fn a_capped_track_stops_at_its_maximum_and_hands_the_rest_to_the_other_shares() {
        let wanted = [
            Track::Capped {
                share: 1.0,
                max: 40.0,
            },
            Track::Share(1.0),
        ];
        assert_eq!(widths(60.0, &wanted), vec![30.0, 30.0]);
        assert_eq!(widths(100.0, &wanted), vec![40.0, 60.0]);
        assert_eq!(widths(1000.0, &wanted), vec![40.0, 960.0]);
    }

    /// Every track shrinks to nothing rather than turning negative or running past the
    /// width, and a cap is a maximum only — it is no floor.
    #[test]
    fn a_width_below_the_fixed_tracks_shrinks_a_capped_track_like_any_other() {
        let wanted = [
            Track::Px(50.0),
            Track::Capped {
                share: 1.0,
                max: 40.0,
            },
            Track::Share(1.0),
        ];
        for width in [0.0_f32, 10.0, 50.0] {
            let held = widths(width, &wanted);
            assert!(
                held.iter().all(|track| *track >= 0.0),
                "at {width}: {held:?}"
            );
            assert!(
                held.iter().sum::<f32>() <= width + 0.01,
                "at {width}: {held:?}"
            );
        }
    }

    #[test]
    fn a_title_is_uppercased_whatever_it_arrives_as() {
        assert_eq!(caps("send queue").text(), "SEND QUEUE");
        assert_eq!(caps("Browser").text(), "BROWSER");
    }

    /// A header is full bleed and exactly as tall as its kind, so a dock's body always
    /// starts at the same place and a header's fill reaches both edges of the panel it
    /// heads.
    ///
    /// ⚠️ A dock's header is the tab strip's height: the strip and the header of every
    /// dock beside it are one line across the window.
    #[test]
    fn a_header_claims_its_own_height_and_the_whole_width() {
        let ctx = egui::Context::default();
        let mut section = egui::Rect::ZERO;
        let mut dock = egui::Rect::ZERO;
        let mut width = 0.0;
        let _ = ctx.run(egui::RawInput::default(), |ctx| {
            ctx.style_mut(crate::app::metrics);
            egui::CentralPanel::default().show(ctx, |ui| {
                width = ui.available_width();
                section = panel_header(ui, "places", None, None).rect;
                dock = dock_header(ui, "browser").rect;
            });
        });
        assert_eq!(section.height(), HEADER);
        assert_eq!(dock.height(), crate::tabs::HEIGHT);
        assert_eq!(section.width(), width);
        assert_eq!(dock.width(), width);
    }

    /// What a frame painted over `rect`, innermost last.
    fn fills(output: &egui::FullOutput, rect: egui::Rect) -> Vec<egui::Color32> {
        fn walk(shape: &egui::Shape, rect: egui::Rect, into: &mut Vec<egui::Color32>) {
            match shape {
                egui::Shape::Rect(drawn) if drawn.rect == rect => into.push(drawn.fill),
                egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| walk(shape, rect, into)),
                _ => {}
            }
        }
        let mut found = Vec::new();
        for clipped in &output.shapes {
            walk(&clipped.shape, rect, &mut found);
        }
        found
    }

    /// One frame with the pointer over the header or away from it, answering with what
    /// the header painted behind itself.
    fn header_fill(
        ctx: &egui::Context,
        under_pointer: bool,
        header: impl Fn(&mut egui::Ui) -> egui::Response,
    ) -> Vec<egui::Color32> {
        let at = std::cell::Cell::new(egui::Pos2::ZERO);
        let mut fill = Vec::new();
        // The first frame only learns where the header is; the second points at it.
        for _ in 0..2 {
            let input = egui::RawInput {
                events: match under_pointer {
                    true => vec![egui::Event::PointerMoved(at.get())],
                    false => Vec::new(),
                },
                ..Default::default()
            };
            let mut rect = egui::Rect::NOTHING;
            let output = ctx.run(input, |ctx| {
                ctx.style_mut(crate::app::metrics);
                egui::CentralPanel::default().show(ctx, |ui| rect = header(ui).rect);
            });
            at.set(rect.center());
            fill = fills(&output, rect);
        }
        fill
    }

    /// ⚠️ A section header is part of the panel it heads until the pointer is on it.
    /// Three permanently grey bars down a dock read as three separate panels rather than
    /// as the headings of one.
    #[test]
    fn a_section_header_wears_the_panel_until_the_pointer_is_on_it() {
        let ctx = egui::Context::default();
        let section = |ui: &mut egui::Ui| panel_header(ui, "places", None, None);
        assert_eq!(
            header_fill(&ctx, false, section),
            vec![egui::Color32::TRANSPARENT],
        );
        assert_eq!(
            header_fill(&ctx, true, section),
            vec![ctx.style().visuals.faint_bg_color],
        );
    }

    /// A dock's header is the one bar that keeps its own colour: it names the dock rather
    /// than a section of it, and there is nothing on it to click.
    #[test]
    fn a_dock_header_keeps_its_own_colour_whether_or_not_it_is_pointed_at() {
        let ctx = egui::Context::default();
        let faint = ctx.style().visuals.faint_bg_color;
        for pointed in [false, true] {
            assert_eq!(
                header_fill(&ctx, pointed, |ui| dock_header(ui, "browser")),
                vec![faint],
                "pointed at: {pointed}",
            );
        }
    }

    /// The triangle is the collapse control, so a click on it is what moves the dock —
    /// not a second bool somewhere else.
    #[test]
    fn the_triangle_toggles_the_bool_it_was_handed() {
        let ctx = egui::Context::default();
        let mut open = true;
        let at = std::cell::Cell::new(egui::Pos2::ZERO);
        let frame = |press: bool, open: &mut bool| {
            let input = egui::RawInput {
                events: match press {
                    true => vec![
                        egui::Event::PointerMoved(at.get()),
                        egui::Event::PointerButton {
                            pos: at.get(),
                            button: egui::PointerButton::Primary,
                            pressed: true,
                            modifiers: egui::Modifiers::NONE,
                        },
                        egui::Event::PointerButton {
                            pos: at.get(),
                            button: egui::PointerButton::Primary,
                            pressed: false,
                            modifiers: egui::Modifiers::NONE,
                        },
                    ],
                    false => Vec::new(),
                },
                ..Default::default()
            };
            let _ = ctx.run(input, |ctx| {
                ctx.style_mut(crate::app::metrics);
                egui::CentralPanel::default().show(ctx, |ui| {
                    let rect = panel_header(ui, "browser", Some(open), None).rect;
                    at.set(egui::pos2(
                        rect.left() + PAD + CHEVRON / 2.0,
                        rect.center().y,
                    ));
                });
            });
        };
        // The first frame only learns where the triangle is; the second presses it.
        frame(false, &mut open);
        frame(true, &mut open);
        assert!(!open, "a click on the triangle shuts the dock");
        frame(true, &mut open);
        assert!(open, "and the next one opens it again");
    }
}