use egui::epaint::CircleShape;
use egui::{
pos2, vec2, Align, Align2, Color32, Frame, Layout, PointerButton, Rect, Response, Sense,
Shadow, Shape, TextStyle, Ui, UiBuilder,
};
use crate::data::scope::LegendPosition;
use crate::data::traces::TraceRef;
#[derive(Clone, Debug)]
pub struct LegendEntryData {
pub id: egui_plot::ItemId,
pub label: String,
pub color: Color32,
}
pub fn trace_item_id(name: &TraceRef) -> egui_plot::ItemId {
egui_plot::ItemId::new(&name.0)
}
pub fn xy_pair_item_id(x: &TraceRef, y: &TraceRef) -> egui_plot::ItemId {
egui_plot::ItemId::new(("liveplot_xy_pair", &x.0, &y.0))
}
pub fn xy_last_point_item_id(pair_id: egui_plot::ItemId) -> egui_plot::ItemId {
egui_plot::ItemId::new((pair_id, "last"))
}
pub fn threshold_item_id(name: &str) -> egui_plot::ItemId {
egui_plot::ItemId::new(("liveplot_threshold", name))
}
pub fn trigger_item_id(name: &str) -> egui_plot::ItemId {
egui_plot::ItemId::new(("liveplot_trigger", name))
}
pub fn measurement_item_id(name: &str) -> egui_plot::ItemId {
egui_plot::ItemId::new(("liveplot_measurement", name))
}
pub fn marker_item_id(name: &str) -> egui_plot::ItemId {
egui_plot::ItemId::new(("liveplot_marker", name))
}
#[derive(Debug, Default)]
pub struct ScopeLegendResult {
pub hidden_items: Vec<egui_plot::ItemId>,
pub hovered_item: Option<egui_plot::ItemId>,
pub rect: Option<Rect>,
}
pub fn render_scope_legend(
ui: &mut Ui,
frame: Rect,
position: LegendPosition,
entries: &[LegendEntryData],
salt: usize,
is_hidden: impl Fn(&egui_plot::ItemId) -> bool,
) -> Option<ScopeLegendResult> {
if entries.is_empty() {
return None;
}
let cross_align = match position {
LegendPosition::LeftTop | LegendPosition::LeftBottom => Align::LEFT,
LegendPosition::RightTop | LegendPosition::RightBottom => Align::RIGHT,
};
let layout = Layout::top_down(cross_align);
let anchor = match position {
LegendPosition::LeftTop => Align2::LEFT_TOP,
LegendPosition::RightTop => Align2::RIGHT_TOP,
LegendPosition::LeftBottom => Align2::LEFT_BOTTOM,
LegendPosition::RightBottom => Align2::RIGHT_BOTTOM,
};
let legend_rect = frame.shrink(4.0);
let max_height = (legend_rect.height() - 16.0).max(24.0);
let max_width = (legend_rect.width() * 0.75).max(40.0);
let mut checked: Vec<bool> = entries.iter().map(|e| !is_hidden(&e.id)).collect();
let mut result = ScopeLegendResult::default();
let background = 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(0.75);
let mut measure_ui = ui.new_child(
UiBuilder::new()
.id_salt(("scope_legend_measure", salt))
.max_rect(legend_rect)
.layout(Layout::top_down(Align::LEFT))
.invisible(),
);
let measured_size = background
.show(&mut measure_ui, |ui| {
egui::ScrollArea::vertical()
.id_salt("liveplot_scope_legend_measure")
.auto_shrink([true, true])
.max_height(max_height)
.max_width(max_width)
.show(ui, |ui| {
ui.set_max_width(max_width);
let font_id = TextStyle::Body.resolve(ui.style());
for entry in entries {
legend_entry_ui(ui, &entry.label, entry.color, true, &font_id);
}
});
})
.response
.rect
.size();
let anchored_rect = anchor.anchor_size(anchor.pos_in_rect(&legend_rect), measured_size);
let mut legend_ui = ui.new_child(
UiBuilder::new()
.id_salt(("scope_legend", salt))
.max_rect(anchored_rect)
.layout(layout),
);
let frame_resp = background.show(&mut legend_ui, |ui| {
egui::ScrollArea::vertical()
.id_salt("liveplot_scope_legend")
.auto_shrink([true, true])
.max_height(max_height)
.max_width(max_width)
.show(ui, |ui| {
ui.set_max_width(max_width);
let font_id = TextStyle::Body.resolve(ui.style());
let mut focus: Option<usize> = None;
for (i, entry) in entries.iter().enumerate() {
let response =
legend_entry_ui(ui, &entry.label, entry.color, checked[i], &font_id);
checked[i] ^= response.clicked_by(PointerButton::Primary);
if response.hovered() {
result.hovered_item = Some(entry.id);
}
if response.clicked() && ui.input(|r| r.modifiers.alt) {
focus = Some(i);
}
}
if let Some(fi) = focus {
let only_visible = entries
.iter()
.enumerate()
.all(|(i, _)| !checked[i] || i == fi);
for (i, c) in checked.iter_mut().enumerate() {
*c = only_visible || i == fi;
}
}
});
});
result.rect = Some(frame_resp.response.rect);
result.hidden_items = entries
.iter()
.zip(checked.iter())
.filter_map(|(e, c)| (!*c).then_some(e.id))
.collect();
Some(result)
}
fn legend_entry_ui(
ui: &mut Ui,
label: &str,
color: Color32,
checked: bool,
font_id: &egui::FontId,
) -> Response {
let galley =
ui.fonts_mut(|f| f.layout_delayed_color(label.to_owned(), font_id.clone(), 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());
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();
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
}