use std::sync::Arc;
use egui::accesskit::{self, Role};
use egui::containers::menu::MenuConfig;
use egui::load::TexturePoll;
use egui::{
Color32, Context, EventFilter, Galley, Id, Image, Key, Painter, Popup, Pos2, Rect, Response,
Sense, TextStyle, Ui, UiBuilder, UiKind, UiStackInfo, Vec2, WidgetInfo, pos2, vec2,
};
use crate::{
DockPainter, Labels, PartState, StylePainter, TabFocus, ToolItemPaint, ToolMorePaint,
ToolSeparatorPaint,
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Orientation {
#[default]
Horizontal,
Vertical,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum ToolDisplay {
#[default]
Icons,
Beside,
Text,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum ToolKind {
Button,
Toggle,
Radio,
Menu,
Separator,
Spacer,
Custom,
}
impl ToolKind {
fn is_button(self) -> bool {
matches!(self, Self::Button | Self::Toggle | Self::Radio | Self::Menu)
}
}
type PaintIcon<'a> = Box<dyn Fn(&Painter, Rect, Color32) + 'a>;
pub enum ToolIcon<'a> {
Image(Image<'a>),
Paint(PaintIcon<'a>),
}
impl std::fmt::Debug for ToolIcon<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Image(image) => f.debug_tuple("Image").field(image).finish(),
Self::Paint(_) => f.write_str("Paint(..)"),
}
}
}
impl<'a> From<Image<'a>> for ToolIcon<'a> {
fn from(image: Image<'a>) -> Self {
Self::Image(image)
}
}
impl ToolIcon<'_> {
pub fn paint(&self, painter: &Painter, rect: Rect, color: Color32, enabled: bool) {
match self {
Self::Paint(paint) => paint(painter, rect, color),
Self::Image(image) => {
if let Ok(TexturePoll::Ready { texture }) =
image.load_for_size(painter.ctx(), rect.size())
{
let mut options = image.image_options().clone();
if !enabled {
options.tint = options.tint.gamma_multiply(0.4);
}
egui::paint_texture_at(painter, rect, &options, &texture);
}
}
}
}
}
type AddUi<'a> = Box<dyn FnOnce(&mut Ui) + 'a>;
enum Body<'a> {
None,
Menu(AddUi<'a>),
Custom(Vec2, AddUi<'a>),
}
pub struct Tool<'a> {
id: String,
kind: ToolKind,
label: String,
icon: Option<ToolIcon<'a>>,
tooltip: Option<String>,
shortcut: Option<String>,
enabled: bool,
checked: bool,
busy: bool,
body: Body<'a>,
}
impl std::fmt::Debug for Tool<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Tool")
.field("id", &self.id)
.field("kind", &self.kind)
.field("label", &self.label)
.field("icon", &self.icon)
.field("enabled", &self.enabled)
.field("checked", &self.checked)
.field("busy", &self.busy)
.finish_non_exhaustive()
}
}
impl<'a> Tool<'a> {
fn new(id: impl Into<String>, kind: ToolKind, label: impl Into<String>) -> Self {
Tool {
id: id.into(),
kind,
label: label.into(),
icon: None,
tooltip: None,
shortcut: None,
enabled: true,
checked: false,
busy: false,
body: Body::None,
}
}
pub fn button(id: impl Into<String>, label: impl Into<String>) -> Self {
Self::new(id, ToolKind::Button, label)
}
pub fn toggle(id: impl Into<String>, label: impl Into<String>, checked: bool) -> Self {
let mut tool = Self::new(id, ToolKind::Toggle, label);
tool.checked = checked;
tool
}
pub fn radio(id: impl Into<String>, label: impl Into<String>, selected: bool) -> Self {
let mut tool = Self::new(id, ToolKind::Radio, label);
tool.checked = selected;
tool
}
pub fn menu(
id: impl Into<String>,
label: impl Into<String>,
add: impl FnOnce(&mut Ui) + 'a,
) -> Self {
let mut tool = Self::new(id, ToolKind::Menu, label);
tool.body = Body::Menu(Box::new(add));
tool
}
pub fn separator() -> Self {
Self::new("", ToolKind::Separator, "")
}
pub fn spacer() -> Self {
Self::new("", ToolKind::Spacer, "")
}
pub fn custom(
id: impl Into<String>,
label: impl Into<String>,
size: Vec2,
add: impl FnOnce(&mut Ui) + 'a,
) -> Self {
let mut tool = Self::new(id, ToolKind::Custom, label);
tool.body = Body::Custom(size.max(Vec2::ZERO), Box::new(add));
tool
}
pub fn icon(mut self, icon: impl Into<ToolIcon<'a>>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn icon_painter(mut self, paint: impl Fn(&Painter, Rect, Color32) + 'a) -> Self {
self.icon = Some(ToolIcon::Paint(Box::new(paint)));
self
}
pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
self.tooltip = Some(tooltip.into());
self
}
pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
self.shortcut = Some(shortcut.into());
self
}
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
pub fn busy(mut self, busy: bool) -> Self {
self.busy = busy;
self
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct LaidTool {
pub id: String,
pub kind: ToolKind,
pub label: String,
pub icon: bool,
pub enabled: bool,
pub checked: bool,
pub busy: bool,
pub overflow: bool,
#[cfg_attr(feature = "serde", serde(skip))]
pub rect: Option<Rect>,
#[cfg_attr(feature = "serde", serde(skip))]
pub widget: Option<Id>,
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct LaidRow {
pub orientation: Orientation,
pub display: ToolDisplay,
pub title: Option<String>,
pub tools: Vec<LaidTool>,
pub overflow: usize,
#[cfg_attr(feature = "serde", serde(skip))]
pub more: Option<Id>,
#[cfg_attr(feature = "serde", serde(skip))]
pub rect: Rect,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ToolRowResponse {
pub clicked: Option<String>,
pub focused: Option<String>,
pub laid: LaidRow,
pub response: Response,
}
pub const MORE: &str = "\u{0}more";
pub fn laid_out(ctx: &Context, name: &str) -> Option<LaidRow> {
ctx.data(|d| d.get_temp::<LaidRow>(row_id(name).with("laid")))
}
pub fn focused(ctx: &Context, name: &str) -> Option<String> {
let laid = laid_out(ctx, name)?;
let focus = ctx.memory(|m| m.focused())?;
if laid.more == Some(focus) {
return Some(MORE.to_owned());
}
laid.tools
.into_iter()
.find(|t| t.widget == Some(focus))
.map(|t| t.id)
}
pub fn focus(ctx: &Context, name: &str, tool: &str) -> bool {
let Some(laid) = laid_out(ctx, name) else {
return false;
};
let widget = if tool == MORE {
laid.more
} else {
laid.tools
.iter()
.find(|t| t.id == tool && t.enabled && !t.overflow)
.and_then(|t| t.widget)
};
let Some(widget) = widget else {
return false;
};
let id = row_id(name);
ctx.data_mut(|d| d.insert_temp(id.with("stop"), widget));
ctx.memory_mut(|m| m.request_focus(widget));
true
}
fn row_id(name: &str) -> Id {
Id::unique(("egui_stack.toolbar", name))
}
pub struct ToolRow<'a> {
name: String,
title: Option<String>,
orientation: Orientation,
display: ToolDisplay,
tab_focus: TabFocus,
icon_size: f32,
padding: f32,
spacing: f32,
painter: &'a (dyn DockPainter + Sync),
texts: Labels,
}
impl std::fmt::Debug for ToolRow<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ToolRow")
.field("name", &self.name)
.field("title", &self.title)
.field("orientation", &self.orientation)
.field("display", &self.display)
.field("tab_focus", &self.tab_focus)
.finish_non_exhaustive()
}
}
struct Metrics {
icon: f32,
pad: f32,
gap: f32,
height: f32,
separator: f32,
mark: f32,
}
struct Placed {
galley: Option<Arc<Galley>>,
shortcut: Option<Arc<Galley>>,
show_icon: bool,
width: f32,
height: f32,
extent: f32,
}
impl<'a> ToolRow<'a> {
pub fn new(name: impl Into<String>) -> Self {
ToolRow {
name: name.into(),
title: None,
orientation: Orientation::Horizontal,
display: ToolDisplay::Icons,
tab_focus: TabFocus::Roving,
icon_size: 16.0,
padding: 4.0,
spacing: 2.0,
painter: &StylePainter,
texts: Labels::ENGLISH,
}
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn orientation(mut self, orientation: Orientation) -> Self {
self.orientation = orientation;
self
}
pub fn vertical(self) -> Self {
self.orientation(Orientation::Vertical)
}
pub fn display(mut self, display: ToolDisplay) -> Self {
self.display = display;
self
}
pub fn tab_focus(mut self, tab_focus: TabFocus) -> Self {
self.tab_focus = tab_focus;
self
}
pub fn icon_size(mut self, points: f32) -> Self {
self.icon_size = points.max(1.0);
self
}
pub fn padding(mut self, points: f32) -> Self {
self.padding = points.max(0.0);
self
}
pub fn spacing(mut self, points: f32) -> Self {
self.spacing = points.max(0.0);
self
}
pub fn painter(mut self, painter: &'a (dyn DockPainter + Sync)) -> Self {
self.painter = painter;
self
}
pub fn labels(mut self, labels: Labels) -> Self {
self.texts = labels;
self
}
fn metrics(&self, ui: &Ui) -> Metrics {
let text = ui.text_style_height(&TextStyle::Button);
let height = (self.icon_size.max(text) + 2.0 * self.padding).round();
Metrics {
icon: self.icon_size,
pad: self.padding,
gap: self.spacing,
height,
separator: ui.spacing().item_spacing.x.max(1.0),
mark: (self.icon_size * 0.6).round(),
}
}
fn place(&self, ui: &Ui, m: &Metrics, tool: &Tool<'_>) -> Placed {
let vertical = self.orientation == Orientation::Vertical;
match (&tool.body, tool.kind) {
(Body::Custom(size, _), _) => Placed {
galley: None,
shortcut: None,
show_icon: false,
width: size.x,
height: size.y,
extent: if vertical { size.y } else { size.x },
},
(_, ToolKind::Separator) => Placed {
galley: None,
shortcut: None,
show_icon: false,
width: m.separator,
height: m.separator,
extent: m.separator,
},
(_, ToolKind::Spacer) => Placed {
galley: None,
shortcut: None,
show_icon: false,
width: 0.0,
height: 0.0,
extent: 0.0,
},
_ => {
let show_icon = tool.icon.is_some() && self.display != ToolDisplay::Text;
let text = self.display != ToolDisplay::Icons || !show_icon;
let galley = text.then(|| label_galley(ui, &tool.label));
let mut width = 2.0 * m.pad;
if show_icon {
width += m.icon;
}
if let Some(g) = &galley {
if show_icon {
width += m.pad;
}
width += g.size().x;
}
if tool.kind == ToolKind::Menu {
width += m.pad + m.mark;
}
let width = width.max(m.height).ceil();
Placed {
galley,
shortcut: None,
show_icon,
width,
height: m.height,
extent: if vertical { m.height } else { width },
}
}
}
}
pub fn show<'t>(
self,
ui: &mut Ui,
tools: impl IntoIterator<Item = Tool<'t>>,
) -> ToolRowResponse {
let tools: Vec<Tool<'t>> = tools.into_iter().collect();
let ctx = ui.ctx().clone();
let id = row_id(&self.name);
let m = self.metrics(ui);
let vertical = self.orientation == Orientation::Vertical;
let roving = self.tab_focus == TabFocus::Roving;
let placed: Vec<Placed> = tools.iter().map(|t| self.place(ui, &m, t)).collect();
let available = ui.available_rect_before_wrap();
let room = if vertical {
available.height()
} else {
available.width()
};
let room = if room.is_finite() {
room
} else {
f32::INFINITY
};
let extents: Vec<f32> = placed.iter().map(|p| p.extent).collect();
let kinds: Vec<ToolKind> = tools.iter().map(|t| t.kind).collect();
let cut = cut(&kinds, &extents, m.gap, m.height, room);
let has_more = !cut.overflow.is_empty();
let cross = cut
.shown
.iter()
.map(|&i| {
let p = &placed[i];
match (kinds[i], vertical) {
(ToolKind::Separator | ToolKind::Spacer, _) => 0.0,
(_, true) => p.width,
(_, false) => p.height,
}
})
.fold(m.height, f32::max);
let along: f32 = cut.shown.iter().map(|&i| extents[i]).sum::<f32>()
+ if has_more { m.height } else { 0.0 };
let items = cut.shown.len() + usize::from(has_more);
let along = along + m.gap * items.saturating_sub(1) as f32;
let spacers = cut
.shown
.iter()
.filter(|&&i| kinds[i] == ToolKind::Spacer)
.count();
let spare = if spacers > 0 && room.is_finite() {
(room - along).max(0.0) / spacers as f32
} else {
0.0
};
let along = along + spare * spacers as f32;
let size = if vertical {
vec2(cross, along)
} else {
vec2(along, cross)
};
let rect = Rect::from_min_size(available.min, size);
let mut builder = UiBuilder::new()
.id_salt(("egui_stack.toolbar", &self.name))
.max_rect(rect)
.accessibility_role(Role::Toolbar);
if let Some(title) = &self.title {
builder = builder.accessibility_label(title.clone());
}
let mut row = ui.new_child(builder);
ctx.accesskit_node_builder(row.unique_id(), |node| {
node.set_orientation(if vertical {
accesskit::Orientation::Vertical
} else {
accesskit::Orientation::Horizontal
});
});
let widget = |tool: &Tool<'_>| id.with(("tool", &tool.id));
let more_id = id.with("more");
let mut group: Vec<Id> = cut
.shown
.iter()
.filter(|&&i| tools[i].kind.is_button() && tools[i].enabled)
.map(|&i| widget(&tools[i]))
.collect();
if has_more {
group.push(more_id);
}
let remembered: Option<Id> = ctx.data(|d| d.get_temp(id.with("stop")));
let stop = remembered
.filter(|r| group.contains(r))
.or_else(|| group.first().copied());
let sense = |widget: Id| {
if roving && Some(widget) != stop {
Sense::CLICK
} else {
Sense::click()
}
};
let mut clicked = None;
let mut popup_open = false;
let mut laid_tools: Vec<LaidTool> = Vec::with_capacity(tools.len());
let mut at = rect.min;
let step = |at: &mut Pos2, extent: f32| {
if vertical {
at.y += extent + m.gap;
} else {
at.x += extent + m.gap;
}
};
let mut overflowed: Vec<(Tool<'t>, Placed)> = Vec::new();
for (i, (tool, p)) in tools.into_iter().zip(placed).enumerate() {
let shown = cut.shown.contains(&i);
if !shown {
if cut.overflow.contains(&i) {
laid_tools.push(laid(&tool, true, None, None));
overflowed.push((tool, p));
}
continue;
}
let extent = if tool.kind == ToolKind::Spacer {
spare
} else {
p.extent
};
let slot = if vertical {
Rect::from_min_size(at, vec2(cross, extent))
} else {
Rect::from_min_size(at, vec2(extent, cross))
};
step(&mut at, extent);
match tool.kind {
ToolKind::Separator => {
if row.is_rect_visible(slot) {
self.painter.tool_separator(
row.painter(),
&ToolSeparatorPaint {
rect: slot,
vertical,
style: row.style(),
},
);
}
laid_tools.push(laid(&tool, false, Some(slot), None));
}
ToolKind::Spacer => laid_tools.push(laid(&tool, false, Some(slot), None)),
ToolKind::Custom => {
let tool_rect = Rect::from_center_size(slot.center(), vec2(p.width, p.height));
let tool_rect = if vertical {
tool_rect.translate(vec2(slot.left() - tool_rect.left(), 0.0))
} else {
tool_rect
};
laid_tools.push(laid(&tool, false, Some(tool_rect), None));
if let Body::Custom(_, add) = tool.body {
let mut child = row.new_child(
UiBuilder::new()
.id_salt(("custom", &tool.id))
.max_rect(tool_rect),
);
add(&mut child);
}
}
_ => {
let w = widget(&tool);
let tool_rect = slot;
let r = if tool.enabled {
row.interact(tool_rect, w, sense(w))
} else {
row.interact(tool_rect, w, Sense::hover())
};
let open = tool.kind == ToolKind::Menu
&& Popup::is_id_open(&ctx, Popup::default_response_id(&r));
popup_open |= open;
let state = part_state(&r)
.with(PartState::SELECTED, tool.checked || open)
.with(PartState::DISABLED, !tool.enabled);
self.paint_tool(&row, &m, &tool, &p, tool_rect, r.id, state, false);
name_tool(&ctx, &r, &tool, open);
let r = tooltip(r, &tool, p.galley.is_some());
laid_tools.push(laid(&tool, false, Some(tool_rect), Some(w)));
if r.clicked() {
ctx.data_mut(|d| d.insert_temp(id.with("stop"), w));
}
match tool.body {
Body::Menu(add) => {
menu_popup(&r).show(add);
}
_ => {
if r.clicked() {
clicked = Some(tool.id.clone());
}
}
}
}
}
}
let mut more = None;
if has_more {
let slot = Rect::from_min_size(at, Vec2::splat(m.height));
let slot = if vertical {
Rect::from_min_size(at, vec2(cross, m.height))
} else {
slot.translate(vec2(0.0, (cross - m.height) / 2.0))
};
let r = row.interact(slot, more_id, sense(more_id));
let open = Popup::is_id_open(&ctx, Popup::default_response_id(&r));
popup_open |= open;
if row.is_rect_visible(slot) {
self.painter.tool_more(
row.painter(),
&ToolMorePaint {
rect: slot,
id: more_id,
vertical,
state: part_state(&r).with(PartState::SELECTED, open),
style: row.style(),
},
);
}
let name = match &self.title {
Some(title) => self.texts.more_tools_in.replace("{toolbar}", title),
None => self.texts.more_tools.to_string(),
};
{
let name = name.clone();
r.widget_info(|| WidgetInfo::labeled(Role::Button, true, &name));
}
ctx.accesskit_node_builder(r.id, |node| {
node.set_expanded(open);
node.set_has_popup(accesskit::HasPopup::Menu);
});
let r = r.on_hover_text(name);
if r.clicked() {
ctx.data_mut(|d| d.insert_temp(id.with("stop"), more_id));
}
menu_popup(&r).show(|ui| {
if let Some(id) = self.more_menu(ui, &m, id, overflowed) {
clicked = Some(id);
}
});
more = Some(more_id);
}
let asked = group
.iter()
.copied()
.find(|&g| ctx.input(|i| i.has_accesskit_action_request(g, accesskit::Action::Focus)));
if let Some(to) = asked {
ctx.data_mut(|d| d.insert_temp(id.with("stop"), to));
ctx.memory_mut(|mem| mem.request_focus(to));
}
let focus = ctx.memory(|m| m.focused());
let focused_at = focus.and_then(|f| group.iter().position(|&g| g == f));
if let Some(at) = focused_at {
ctx.data_mut(|d| d.insert_temp(id.with("stop"), group[at]));
if roving && !popup_open {
let (back, forth) = if vertical {
(Key::ArrowUp, Key::ArrowDown)
} else {
(Key::ArrowLeft, Key::ArrowRight)
};
ctx.memory_mut(|mem| {
mem.set_focus_lock_filter(
group[at],
EventFilter {
horizontal_arrows: !vertical,
vertical_arrows: vertical,
..Default::default()
},
);
});
let n = group.len();
let target = ctx.input(|i| {
if i.key_pressed(forth) {
Some((at + 1) % n)
} else if i.key_pressed(back) {
Some((at + n - 1) % n)
} else if i.key_pressed(Key::Home) {
Some(0)
} else if i.key_pressed(Key::End) {
Some(n - 1)
} else {
None
}
});
if let Some(target) = target.filter(|&t| t != at) {
let to = group[target];
ctx.data_mut(|d| d.insert_temp(id.with("stop"), to));
ctx.memory_mut(|mem| mem.request_focus(to));
}
}
}
let focused = focus.and_then(|f| {
if more == Some(f) {
Some(MORE.to_owned())
} else {
laid_tools
.iter()
.find(|t| t.widget == Some(f))
.map(|t| t.id.clone())
}
});
let response = ui.allocate_rect(rect, Sense::hover());
let laid = LaidRow {
orientation: self.orientation,
display: self.display,
title: self.title.clone(),
overflow: laid_tools
.iter()
.filter(|t| t.overflow && t.kind != ToolKind::Separator)
.count(),
tools: laid_tools,
more,
rect,
};
ctx.data_mut(|d| d.insert_temp(id.with("laid"), laid.clone()));
ToolRowResponse {
clicked,
focused,
laid,
response,
}
}
#[allow(clippy::too_many_arguments)]
fn paint_tool(
&self,
ui: &Ui,
m: &Metrics,
tool: &Tool<'_>,
p: &Placed,
rect: Rect,
id: Id,
state: PartState,
in_menu: bool,
) {
if !ui.is_rect_visible(rect) {
return;
}
let y = rect.center().y;
let square = |x: f32| Rect::from_min_size(pos2(x, y - m.icon / 2.0), Vec2::splat(m.icon));
let alone = !in_menu && p.galley.is_none() && tool.kind != ToolKind::Menu;
let (icon_rect, mut x) = if alone {
let at = Rect::from_center_size(rect.center(), Vec2::splat(m.icon));
(at, at.right())
} else if p.show_icon || in_menu {
let at = square(rect.left() + m.pad);
(at, at.right() + m.pad)
} else {
(square(rect.left() + m.pad), rect.left() + m.pad)
};
let label_pos = match &p.galley {
Some(g) => {
let pos = pos2(x, y - g.size().y / 2.0);
x += g.size().x;
pos
}
None => pos2(x, y),
};
let marked = tool.kind == ToolKind::Menu
|| (in_menu && matches!(tool.kind, ToolKind::Toggle | ToolKind::Radio));
let mark = marked.then(|| {
let right = if in_menu {
rect.right() - m.pad - m.mark
} else {
(x + m.pad).max(rect.right() - m.pad - m.mark)
};
Rect::from_min_size(pos2(right, y - m.mark / 2.0), Vec2::splat(m.mark))
});
let show_icon = p.show_icon || (in_menu && tool.icon.is_some());
let shortcut_pos = p.shortcut.as_ref().map_or(pos2(x, y), |g| {
let end = rect.right() - 2.0 * m.pad - m.mark;
pos2(end - g.size().x, y - g.size().y / 2.0)
});
self.painter.tool_item(
ui.painter(),
&ToolItemPaint {
rect,
id,
kind: tool.kind,
icon: tool.icon.as_ref().filter(|_| show_icon),
icon_rect,
label: p.galley.as_ref(),
label_pos,
shortcut: p.shortcut.as_ref(),
shortcut_pos,
mark,
busy: tool.busy,
in_menu,
state,
style: ui.style(),
},
);
}
fn more_menu(
&self,
ui: &mut Ui,
m: &Metrics,
row: Id,
tools: Vec<(Tool<'_>, Placed)>,
) -> Option<String> {
let tools: Vec<(Tool<'_>, Placed)> = tools
.into_iter()
.map(|(tool, mut p)| {
if tool.kind.is_button() {
p.galley = Some(label_galley(ui, &tool.label));
p.shortcut = tool.shortcut.as_deref().map(|k| label_galley(ui, k));
p.show_icon = tool.icon.is_some();
}
(tool, p)
})
.collect();
let width = tools
.iter()
.filter(|(t, _)| t.kind.is_button())
.map(|(_, p)| {
let label = p.galley.as_ref().map_or(0.0, |g| g.size().x);
let keys = p
.shortcut
.as_ref()
.map_or(0.0, |g| 2.0 * m.pad + g.size().x);
4.0 * m.pad + m.icon + label + keys + m.mark
})
.fold(0.0, f32::max);
ui.set_min_width(width);
let mut clicked = None;
for (tool, p) in tools {
match tool.kind {
ToolKind::Separator => {
ui.separator();
}
ToolKind::Spacer => {}
ToolKind::Custom => {
if let Body::Custom(_, add) = tool.body {
add(ui);
}
}
ToolKind::Menu => {
if let Body::Menu(add) = tool.body {
ui.add_enabled_ui(tool.enabled, |ui| {
ui.menu_button(tool.label.as_str(), add);
});
}
}
_ => {
let w = row.with(("more", &tool.id));
let size = vec2(width, m.height);
let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
let sense = if tool.enabled {
Sense::click()
} else {
Sense::hover()
};
let r = ui.interact(rect, w, sense);
let state = part_state(&r)
.with(PartState::SELECTED, tool.checked)
.with(PartState::DISABLED, !tool.enabled);
self.paint_tool(ui, m, &tool, &p, rect, w, state, true);
name_tool(ui.ctx(), &r, &tool, false);
let r = match &tool.tooltip {
Some(tip) => r.on_hover_text(tip),
None => r,
};
if r.clicked() {
clicked = Some(tool.id.clone());
ui.close();
}
}
}
}
clicked
}
}
fn label_galley(ui: &Ui, label: &str) -> Arc<Galley> {
let font = TextStyle::Button.resolve(ui.style());
ui.painter()
.layout_no_wrap(label.to_owned(), font, Color32::PLACEHOLDER)
}
fn menu_popup(r: &Response) -> Popup<'_> {
let config = MenuConfig::default();
Popup::menu(r)
.close_behavior(config.close_behavior)
.info(UiStackInfo::new(UiKind::Menu).with_tag_value(MenuConfig::MENU_CONFIG_TAG, config))
}
fn tooltip(r: Response, tool: &Tool<'_>, label_shown: bool) -> Response {
let tip = match (&tool.tooltip, &tool.shortcut) {
(Some(tip), _) => tip.clone(),
(None, _) if label_shown => return r,
(None, Some(keys)) => format!("{} ({keys})", tool.label),
(None, None) => tool.label.clone(),
};
r.on_hover_text(tip)
}
fn name_tool(ctx: &Context, r: &Response, tool: &Tool<'_>, open: bool) {
let (enabled, checked) = (tool.enabled, tool.checked);
let name = tool.label.as_str();
match tool.kind {
ToolKind::Toggle => {
r.widget_info(|| WidgetInfo::selected(Role::Button, enabled, checked, name));
}
ToolKind::Radio => {
r.widget_info(|| WidgetInfo::selected(Role::RadioButton, enabled, checked, name));
}
_ => r.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, name)),
}
ctx.accesskit_node_builder(r.id, |node| {
if tool.kind == ToolKind::Menu {
node.set_expanded(open);
node.set_has_popup(accesskit::HasPopup::Menu);
}
if tool.busy {
node.set_busy();
}
});
}
fn laid(tool: &Tool<'_>, overflow: bool, rect: Option<Rect>, widget: Option<Id>) -> LaidTool {
LaidTool {
id: tool.id.clone(),
kind: tool.kind,
label: tool.label.clone(),
icon: tool.icon.is_some(),
enabled: tool.enabled,
checked: tool.checked,
busy: tool.busy,
overflow,
rect,
widget,
}
}
fn part_state(r: &Response) -> PartState {
PartState::NONE
.with(PartState::HOVERED, r.hovered())
.with(PartState::PRESSED, r.is_pointer_button_down_on())
.with(PartState::FOCUSED, r.has_focus())
}
#[derive(Debug, PartialEq)]
struct Cut {
shown: Vec<usize>,
overflow: Vec<usize>,
}
fn cut(kinds: &[ToolKind], extents: &[f32], gap: f32, more: f32, room: f32) -> Cut {
let all: f32 = extents.iter().sum::<f32>() + gap * extents.len().saturating_sub(1) as f32;
let kept = if all <= room + 0.01 {
extents.len()
} else {
let mut used = more;
extents
.iter()
.take_while(|e| {
used += *e + gap;
used <= room + 0.01
})
.count()
};
let gap_kind = |k: ToolKind| matches!(k, ToolKind::Separator | ToolKind::Spacer);
let mut end = kept;
if kept < extents.len() {
while end > 0 && gap_kind(kinds[end - 1]) {
end -= 1;
}
}
let shown: Vec<usize> = (0..end).collect();
let mut overflow: Vec<usize> = Vec::new();
for i in kept..extents.len() {
match kinds[i] {
ToolKind::Spacer => {}
ToolKind::Separator => {
let after_tool = overflow
.last()
.is_some_and(|&j| kinds[j] != ToolKind::Separator);
if after_tool {
overflow.push(i);
}
}
_ => overflow.push(i),
}
}
while overflow
.last()
.is_some_and(|&j| kinds[j] == ToolKind::Separator)
{
overflow.pop();
}
Cut { shown, overflow }
}
#[cfg(test)]
mod tests {
use super::{Cut, ToolKind, cut};
const B: ToolKind = ToolKind::Button;
const S: ToolKind = ToolKind::Separator;
const P: ToolKind = ToolKind::Spacer;
fn c(shown: &[usize], overflow: &[usize]) -> Cut {
Cut {
shown: shown.to_vec(),
overflow: overflow.to_vec(),
}
}
#[test]
fn tools_that_do_not_fit_go_into_more_from_the_end() {
let k = [B, B, B];
let e = [10.0, 10.0, 10.0];
assert_eq!(cut(&k, &e, 1.0, 10.0, 32.0), c(&[0, 1, 2], &[]));
assert_eq!(cut(&k, &e, 1.0, 8.0, 31.0), c(&[0, 1], &[2]));
assert_eq!(cut(&k, &e, 1.0, 10.0, 31.0), c(&[0], &[1, 2]));
assert_eq!(cut(&k, &e, 1.0, 10.0, 5.0), c(&[], &[0, 1, 2]));
assert_eq!(cut(&k, &e, 1.0, 10.0, f32::INFINITY), c(&[0, 1, 2], &[]));
}
#[test]
fn a_separator_never_ends_the_row_nor_starts_or_ends_the_menu() {
let k = [B, S, B, S, S, B, S];
let e = [10.0, 4.0, 10.0, 4.0, 4.0, 10.0, 4.0];
assert_eq!(cut(&k, &e, 0.0, 10.0, 25.0), c(&[0], &[2, 3, 5]));
}
#[test]
fn a_spacer_takes_no_room_and_never_goes_into_the_menu() {
let k = [B, P, B, B];
let e = [10.0, 0.0, 10.0, 10.0];
assert_eq!(cut(&k, &e, 0.0, 10.0, 30.0), c(&[0, 1, 2, 3], &[]));
assert_eq!(cut(&k, &e, 0.0, 10.0, 21.0), c(&[0], &[2, 3]));
}
}