use egui::{Color32, CornerRadius, FontId, Rect, Sense, TextureId, Ui, Vec2};
use crate::FULL_UV;
use crate::Icons;
use crate::metrics::{ICON_MEDIUM, TAB_HEIGHT, TAB_STRIP_PADDING};
const TAB_FONT_SIZE: f32 = 12.5;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TabIcon<'a> {
None,
Glyph(&'a str),
Texture(TextureId),
}
#[derive(Clone, Copy, Debug)]
pub struct TabItem<'a> {
pub label: &'a str,
pub icon: TabIcon<'a>,
pub dirty: bool,
pub warning: bool,
pub missing: bool,
}
impl<'a> TabItem<'a> {
pub fn new(label: &'a str, icon: TabIcon<'a>) -> Self {
Self {
label,
icon,
dirty: false,
warning: false,
missing: false,
}
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TabEvent {
Select(usize),
Close(usize),
}
pub fn show_tab_strip(
ui: &mut Ui,
icons: &mut Icons,
tabs: &[TabItem<'_>],
active: usize,
close_label: &str,
controls_width: f32,
controls: impl FnOnce(&mut Ui, &mut Icons),
) -> Option<TabEvent> {
let bar = ui.max_rect();
ui.painter().rect_filled(bar, 0.0, ui.visuals().window_fill);
let tabs_rect = Rect::from_min_max(
egui::pos2(bar.left() + TAB_STRIP_PADDING, bar.top()),
egui::pos2((bar.right() - controls_width).max(bar.left() + 80.0), bar.bottom()),
);
let mut event = None;
ui.scope_builder(
egui::UiBuilder::new()
.max_rect(tabs_rect)
.layout(egui::Layout::left_to_right(egui::Align::Center)),
|ui| event = scrolling_tabs(ui, icons, tabs, active, close_label, tabs_rect),
);
ui.scope_builder(
egui::UiBuilder::new()
.max_rect(bar)
.layout(egui::Layout::right_to_left(egui::Align::Center)),
|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
ui.add_space(2.0);
controls(ui, icons);
},
);
event
}
fn scrolling_tabs(
ui: &mut Ui,
icons: &mut Icons,
tabs: &[TabItem<'_>],
active: usize,
close_label: &str,
area: Rect,
) -> Option<TabEvent> {
ui.spacing_mut().item_spacing.x = 0.0;
let scroll_id = ui.scope_id().with("workbench_tab_scroll");
let mut offset: f32 = ui.ctx().data_mut(|data| *data.get_temp_mut_or_default(scroll_id));
if ui.rect_contains_pointer(area) {
let wheel = ui.input(|input| {
input
.events
.iter()
.filter_map(|event| match event {
egui::Event::MouseWheel {
unit, delta, modifiers, ..
} if !modifiers.command && !modifiers.alt => Some(match unit {
egui::MouseWheelUnit::Point => -delta.y,
egui::MouseWheelUnit::Line => -delta.y * 20.0,
egui::MouseWheelUnit::Page => -delta.y * area.width(),
}),
_ => None,
})
.sum::<f32>()
});
if wheel.abs() > 0.0 {
offset = (offset + wheel).max(0.0);
ui.ctx().request_repaint();
}
}
let revealed_id = ui.scope_id().with("workbench_tab_revealed");
let revealed: Option<usize> = ui.ctx().data(|data| data.get_temp(revealed_id));
let mut active_span = None;
let mut event = None;
let output = egui::ScrollArea::horizontal()
.auto_shrink([false, true])
.scroll_source(egui::scroll_area::ScrollSource::SCROLL_BAR)
.horizontal_scroll_offset(offset)
.show(ui, |ui| {
ui.horizontal_centered(|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
let origin = ui.cursor().min.x;
for (index, tab) in tabs.iter().enumerate() {
let start = ui.cursor().min.x - origin;
let hit = tab_button(ui, icons, tab, index, index == active, close_label);
if index == active {
active_span = Some((start, ui.min_rect().right() - origin));
}
event = event.or(hit);
}
});
});
let mut stored = output.state.clamped_offset().x;
if revealed != Some(active)
&& let Some((start, end)) = active_span
{
let visible = output.inner_rect.width();
let max = (output.content_size.x - visible).max(0.0);
let target = if start < stored {
start
} else if end > stored + visible {
end - visible
} else {
stored
};
stored = target.clamp(0.0, max);
if (stored - output.state.clamped_offset().x).abs() > 0.5 {
ui.ctx().request_repaint();
}
ui.ctx().data_mut(|data| data.insert_temp(revealed_id, active));
}
ui.ctx().data_mut(|data| data.insert_temp(scroll_id, stored));
event
}
fn tab_button(
ui: &mut Ui,
icons: &mut Icons,
tab: &TabItem<'_>,
index: usize,
active: bool,
close_label: &str,
) -> Option<TabEvent> {
let font = FontId::proportional(TAB_FONT_SIZE);
let text_width = ui
.painter()
.layout_no_wrap(tab.label.to_owned(), font.clone(), Color32::WHITE)
.rect
.width();
let width = (text_width + 58.0).clamp(96.0, 212.0);
let (rect, response) = ui.allocate_exact_size(Vec2::new(width, TAB_HEIGHT), Sense::click());
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, active, tab.label));
let active_t = ui
.ctx()
.animate_bool_with_time(response.id.with("active"), active, 0.16);
let hover_t = ui
.ctx()
.animate_bool_with_time(response.id.with("hover"), response.hovered() && !active, 0.10);
let radius = CornerRadius {
nw: 4,
ne: 4,
sw: 0,
se: 0,
};
if active_t > 0.01 {
ui.painter()
.rect_filled(rect, radius, ui.visuals().panel_fill.gamma_multiply(active_t));
}
if hover_t > 0.01 {
let fill = ui.visuals().widgets.hovered.weak_bg_fill.gamma_multiply(hover_t);
ui.painter().rect_filled(rect, radius, fill);
}
let icon_center = egui::pos2(rect.left() + 15.0, rect.center().y);
match tab.icon {
TabIcon::None => {}
TabIcon::Glyph(name) => {
icons.paint(ui, name, icon_center, ICON_MEDIUM, ui.visuals().text_color());
}
TabIcon::Texture(texture) => {
let icon_rect = crate::foundation::icons::pixel_rect(ui.ctx(), icon_center, ICON_MEDIUM);
ui.painter().image(texture, icon_rect, FULL_UV, Color32::WHITE);
}
}
let color = if tab.warning || tab.missing {
ui.visuals().warn_fg_color
} else if active {
ui.visuals().text_color()
} else {
ui.visuals().weak_text_color()
};
let mut job = egui::text::LayoutJob::single_section(tab.label.to_owned(), egui::TextFormat::simple(font, color));
job.wrap = egui::text::TextWrapping::truncate_at_width((rect.width() - 28.0 - 26.0).max(16.0));
let galley = ui.painter().layout_job(job);
let text_pos = egui::pos2(rect.left() + 28.0, rect.center().y - galley.size().y / 2.0);
ui.painter().galley(text_pos, galley.clone(), color);
if tab.missing {
let y = rect.center().y;
ui.painter().line_segment(
[
egui::pos2(text_pos.x, y),
egui::pos2(text_pos.x + galley.rect.width(), y),
],
crate::style::get(ui.ctx()).border(color),
);
}
if tab.dirty && !response.hovered() && !active {
ui.painter().circle_filled(
egui::pos2(rect.right() - 12.0, rect.center().y),
3.0,
ui.visuals().weak_text_color(),
);
}
let close_rect = Rect::from_center_size(egui::pos2(rect.right() - 13.0, rect.center().y), Vec2::splat(16.0));
let close = ui.interact(
close_rect,
ui.scope_id().with(("workbench_tab_close", index)),
Sense::click(),
);
close.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{close_label} {}", tab.label)));
let close = close.on_hover_text(close_label);
let visible = active || ui.rect_contains_pointer(rect) || close.hovered();
let close_t = ui
.ctx()
.animate_bool_with_time(response.id.with("close"), visible, 0.12);
if close_t > 0.05 {
if close.hovered() {
ui.painter().rect_filled(
close_rect,
crate::style::get(ui.ctx()).tight(),
ui.visuals().widgets.hovered.weak_bg_fill,
);
}
let tint = ui.visuals().text_color().gamma_multiply(close_t);
icons.paint(ui, "close", close_rect.center(), 12.0, tint);
}
if close.clicked() || response.middle_clicked() {
Some(TabEvent::Close(index))
} else if response.clicked() {
Some(TabEvent::Select(index))
} else {
None
}
}