egui_plot 0.38.0

Immediate mode plotting for the egui GUI library
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
use std::string::String;

use egui::Align;
use egui::Color32;
use egui::Direction;
use egui::Frame;
use egui::Layout;
use egui::PointerButton;
use egui::Rect;
use egui::Response;
use egui::Role;
use egui::Sense;
use egui::Shadow;
use egui::Shape;
use egui::TextStyle;
use egui::Ui;
use egui::Widget;
use egui::WidgetInfo;
use egui::epaint::CircleShape;
use egui::pos2;
use egui::vec2;

use crate::item_id::ItemId;
use crate::item_id::ItemIdMap;
use crate::item_id::ItemIdSet;
use crate::items::PlotItem;
use crate::placement::Corner;

/// How to handle multiple conflicting color for a legend item.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum ColorConflictHandling {
    PickFirst,
    PickLast,
    RemoveColor,
}

/// How to group legend entries.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum LegendGrouping {
    /// Items with the same name share a single legend entry (default).
    #[default]
    ByName,

    /// Each item gets its own legend entry, keyed by its [`ItemId`].
    ById,
}

/// The configuration for a plot legend.
#[derive(Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Legend {
    pub text_style: TextStyle,
    pub background_alpha: f32,
    pub position: Corner,
    pub title: Option<String>,

    follow_insertion_order: bool,
    grouping: LegendGrouping,
    color_conflict_handling: ColorConflictHandling,

    /// Used for overriding the `hidden_items` set in [`LegendWidget`].
    hidden_items: Option<ItemIdSet>,
}

impl Default for Legend {
    fn default() -> Self {
        Self {
            text_style: TextStyle::Body,
            background_alpha: 0.75,
            position: Corner::RightTop,
            title: None,
            follow_insertion_order: false,
            grouping: LegendGrouping::default(),
            color_conflict_handling: ColorConflictHandling::RemoveColor,
            hidden_items: None,
        }
    }
}

impl Legend {
    /// Which text style to use for the legend. Default: `TextStyle::Body`.
    #[inline]
    pub fn text_style(mut self, style: TextStyle) -> Self {
        self.text_style = style;
        self
    }

    /// The alpha of the legend background. Default: `0.75`.
    #[inline]
    pub fn background_alpha(mut self, alpha: f32) -> Self {
        self.background_alpha = alpha;
        self
    }

    /// In which corner to place the legend. Default: `Corner::RightTop`.
    #[inline]
    pub fn position(mut self, corner: Corner) -> Self {
        self.position = corner;
        self
    }

    /// Set the title of the legend. Default: `None`.
    #[inline]
    pub fn title(mut self, title: &str) -> Self {
        self.title = Some(title.to_owned());
        self
    }

    /// Specifies hidden items in the legend configuration to override the
    /// existing ones. This allows the legend traces' visibility to be
    /// controlled from the application code.
    #[inline]
    pub fn hidden_items<I>(mut self, hidden_items: I) -> Self
    where
        I: IntoIterator<Item = ItemId>,
    {
        self.hidden_items = Some(hidden_items.into_iter().collect());
        self
    }

    /// Specifies if the legend item order should be the inserted order.
    /// Default: `false`.
    /// If `true`, the order of the legend items will be the same as the order
    /// as they were added. By default it will be sorted alphabetically.
    #[inline]
    pub fn follow_insertion_order(mut self, follow: bool) -> Self {
        self.follow_insertion_order = follow;
        self
    }

    /// Specifies how to handle conflicting colors for an item.
    #[inline]
    pub fn color_conflict_handling(mut self, color_conflict_handling: ColorConflictHandling) -> Self {
        self.color_conflict_handling = color_conflict_handling;
        self
    }

    /// Specifies how legend entries are grouped. Default: [`LegendGrouping::ByName`].
    ///
    /// With [`LegendGrouping::ByName`], items sharing the same name are
    /// merged into a single legend entry. With [`LegendGrouping::ById`],
    /// each item gets its own entry keyed by its [`ItemId`].
    #[inline]
    pub fn grouping(mut self, grouping: LegendGrouping) -> Self {
        self.grouping = grouping;
        self
    }
}

#[derive(Clone)]
struct LegendEntry {
    id: ItemId,
    name: String,
    color: Color32,
    checked: bool,
    hovered: bool,
}

impl LegendEntry {
    fn new(id: ItemId, name: String, color: Color32, checked: bool) -> Self {
        Self {
            id,
            name,
            color,
            checked,
            hovered: false,
        }
    }

    fn ui(&self, ui: &mut Ui, text_style: &TextStyle) -> Response {
        let Self {
            id: _,
            name,
            color,
            checked,
            hovered: _,
        } = self;

        let font_id = text_style.resolve(ui.style());

        let galley = ui.fonts_mut(|f| f.layout_delayed_color(name.clone(), font_id, f32::INFINITY));

        let icon_size = galley.size().y;
        let icon_spacing = icon_size / 5.0;
        let total_extra = vec2(icon_size + icon_spacing, 0.0);

        let desired_size = total_extra + galley.size();
        let (rect, response) = ui.allocate_exact_size(desired_size, Sense::click());

        response.widget_info(|| WidgetInfo::selected(Role::CheckBox, ui.is_enabled(), *checked, galley.text()));

        let visuals = ui.style().interact(&response);
        let label_on_the_left = ui.layout().horizontal_placement() == Align::RIGHT;

        let icon_position_x = if label_on_the_left {
            rect.right() - icon_size / 2.0
        } else {
            rect.left() + icon_size / 2.0
        };
        let icon_position = pos2(icon_position_x, rect.center().y);
        let icon_rect = Rect::from_center_size(icon_position, vec2(icon_size, icon_size));

        let painter = ui.painter();

        // Gray background, for interaction effects, and to sow something if we're
        // disabled:
        painter.add(CircleShape {
            center: icon_rect.center(),
            radius: icon_size * 0.35,
            fill: visuals.bg_fill,
            stroke: visuals.bg_stroke,
        });

        if *checked {
            let fill = if *color == Color32::TRANSPARENT {
                ui.visuals().noninteractive().fg_stroke.color
            } else {
                *color
            };
            painter.add(Shape::circle_filled(icon_rect.center(), icon_size * 0.25, fill));
        }

        let text_position_x = if label_on_the_left {
            rect.right() - icon_size - icon_spacing - galley.size().x
        } else {
            rect.left() + icon_size + icon_spacing
        };

        let text_position = pos2(text_position_x, rect.center().y - 0.5 * galley.size().y);
        painter.galley(text_position, galley, visuals.text_color());

        response
    }
}

#[derive(Clone)]
pub struct LegendWidget {
    rect: Rect,
    entries: Vec<LegendEntry>,
    config: Legend,
}

impl LegendWidget {
    /// Create a new legend from items, the names of items that are hidden and
    /// the style of the text. Returns `None` if the legend has no entries.
    pub(crate) fn try_new<'a>(
        rect: Rect,
        config: Legend,
        items: &[Box<dyn PlotItem + 'a>],
        hidden_items: &ItemIdSet, // Existing hidden items in the plot memory.
    ) -> Option<Self> {
        // If `config.hidden_items` is not `None`, it is used.
        let hidden_items = config.hidden_items.as_ref().unwrap_or(hidden_items);

        // Collect the legend entries. With `ByName` grouping, items sharing the
        // same name are merged into a single checkbox. With `ById` grouping,
        // items sharing the same `ItemId` are merged instead. When colors conflict
        // within a merged entry, `color_conflict_handling` decides which color
        // to show.
        let mut entries: Vec<LegendEntry> = Vec::new();
        let mut seen: ItemIdMap<usize> = ItemIdMap::default();
        for item in items.iter().filter(|item| !item.name().is_empty()) {
            let dedup_key = match config.grouping {
                LegendGrouping::ByName => ItemId::new(item.name()),
                LegendGrouping::ById => item.id(),
            };

            if let Some(&idx) = seen.get(&dedup_key) {
                let entry = &mut entries[idx];
                if entry.color != item.color() {
                    match config.color_conflict_handling {
                        ColorConflictHandling::PickFirst => (),
                        ColorConflictHandling::PickLast => entry.color = item.color(),
                        ColorConflictHandling::RemoveColor => {
                            entry.color = Color32::TRANSPARENT;
                        }
                    }
                }
            } else {
                seen.insert(dedup_key, entries.len());
                let color = item.color();
                let checked = !hidden_items.contains(&item.id());
                entries.push(LegendEntry::new(item.id(), item.name().to_owned(), color, checked));
            }
        }

        if !config.follow_insertion_order {
            entries.sort_by(|a, b| a.name.cmp(&b.name));
        }

        (!entries.is_empty()).then_some(Self { rect, entries, config })
    }

    // Get the names of the hidden items.
    pub fn hidden_items(&self) -> ItemIdSet {
        self.entries
            .iter()
            .filter_map(|entry| (!entry.checked).then_some(entry.id))
            .collect()
    }

    // Get the name of the hovered items.
    pub fn hovered_item(&self) -> Option<ItemId> {
        self.entries.iter().find_map(|entry| entry.hovered.then_some(entry.id))
    }
}

impl Widget for &mut LegendWidget {
    fn ui(self, ui: &mut Ui) -> Response {
        let LegendWidget { rect, entries, config } = self;

        let main_dir = match config.position {
            Corner::LeftTop | Corner::RightTop => Direction::TopDown,
            Corner::LeftBottom | Corner::RightBottom => Direction::BottomUp,
        };
        let cross_align = match config.position {
            Corner::LeftTop | Corner::LeftBottom => Align::LEFT,
            Corner::RightTop | Corner::RightBottom => Align::RIGHT,
        };
        let layout = Layout::from_main_dir_and_cross_align(main_dir, cross_align);
        let legend_pad = 4.0;
        let legend_rect = rect.shrink(legend_pad);
        let mut legend_ui = ui.new_child(egui::UiBuilder::new().max_rect(legend_rect).layout(layout));
        legend_ui
            .scope(|ui| {
                let background_frame = Frame {
                    inner_margin: vec2(8.0, 4.0).into(),
                    corner_radius: ui.style().visuals.window_corner_radius,
                    shadow: Shadow::NONE,
                    fill: ui.style().visuals.extreme_bg_color,
                    stroke: ui.style().visuals.window_stroke(),
                    ..Default::default()
                }
                .multiply_with_opacity(config.background_alpha);
                background_frame
                    .show(ui, |ui| {
                        // always show on top of the legend - so we need to use a new scope
                        if main_dir == Direction::TopDown
                            && let Some(title) = &config.title
                        {
                            ui.heading(title);
                        }
                        let mut focus_on_item = None;

                        #[expect(
                            clippy::expect_used,
                            reason = "we checked that entries is not empty when creating the legend"
                        )]
                        let response_union = entries
                            .iter_mut()
                            .map(|entry| {
                                let response = entry.ui(ui, &config.text_style);

                                // Handle interactions. Alt-clicking must be deferred to end of loop
                                // since it may affect all entries.
                                handle_interaction_on_legend_item(&response, entry);
                                if response.clicked() && ui.input(|r| r.modifiers.alt) {
                                    focus_on_item = Some(entry.id);
                                }

                                response
                            })
                            .reduce(|r1, r2| r1.union(r2))
                            .expect("No entries in the legend");

                        if main_dir == Direction::BottomUp
                            && let Some(title) = &config.title
                        {
                            ui.heading(title);
                        }

                        if let Some(focus_on_item) = focus_on_item {
                            handle_focus_on_legend_item(&focus_on_item, entries);
                        }

                        response_union
                    })
                    .inner
            })
            .inner
    }
}

/// Handle per-entry interactions.
fn handle_interaction_on_legend_item(response: &Response, entry: &mut LegendEntry) {
    entry.checked ^= response.clicked_by(PointerButton::Primary);
    entry.hovered = response.hovered();
}

/// Handle alt-click interaction (which may affect all entries).
fn handle_focus_on_legend_item(clicked_entry: &ItemId, entries: &mut [LegendEntry]) {
    // if all other items are already hidden, we show everything
    let is_focus_item_only_visible = entries
        .iter()
        .all(|entry| !entry.checked || (clicked_entry == &entry.id));

    // either show everything or show only the focus item
    for entry in entries.iter_mut() {
        entry.checked = is_focus_item_only_visible || clicked_entry == &entry.id;
    }
}