use std::collections::BTreeMap;
use std::ops::Range;
use std::sync::Arc;
use egui::accesskit::{Action, Role};
use egui::scroll_area::{DragScroll, ScrollBarVisibility, ScrollSource};
use egui::style::ScrollStyle;
use egui::{
Context, CursorIcon, EventFilter, Id, Key, Modifiers, PointerButton, Rect, Response, Sense,
TextStyle, Ui, UiBuilder, WidgetInfo, pos2, vec2,
};
use crate::{DockPainter, Labels, PartState, SectionBandPaint, SectionBoundaryPaint, StylePainter};
pub mod plan;
use plan::{Asked, DragMode, Placed};
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Remembered {
pub open: bool,
#[cfg_attr(feature = "serde", serde(default))]
pub height: Option<f32>,
}
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Layout {
pub sections: BTreeMap<String, Remembered>,
#[cfg_attr(feature = "serde", serde(default))]
pub empty: f32,
}
impl Layout {
pub fn load(ctx: &Context, name: &str) -> Option<Layout> {
let id = memory_id(name);
#[cfg(feature = "serde")]
return ctx.data_mut(|d| d.get_persisted::<Layout>(id));
#[cfg(not(feature = "serde"))]
return ctx.data(|d| d.get_temp::<Layout>(id));
}
pub fn store(&self, ctx: &Context, name: &str) {
let id = memory_id(name);
let layout = self.clone();
#[cfg(feature = "serde")]
ctx.data_mut(|d| d.insert_persisted(id, layout));
#[cfg(not(feature = "serde"))]
ctx.data_mut(|d| d.insert_temp(id, layout));
}
pub fn is_open(&self, key: &str) -> Option<bool> {
self.sections.get(key).map(|s| s.open)
}
pub fn set_open(&mut self, key: &str, open: bool) {
self.sections
.entry(key.to_owned())
.or_insert(Remembered { open, height: None })
.open = open;
}
pub fn height(&self, key: &str) -> Option<f32> {
self.sections.get(key).and_then(|s| s.height)
}
pub fn set_height(&mut self, key: &str, height: Option<f32>) {
match self.sections.get_mut(key) {
Some(s) => s.height = height,
None => {
self.sections
.insert(key.to_owned(), Remembered { open: true, height });
}
}
}
pub fn reset_heights(&mut self) {
for s in self.sections.values_mut() {
s.height = None;
}
self.empty = 0.0;
}
}
fn memory_id(name: &str) -> Id {
Id::unique(("egui_stack.sections", name))
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Laid {
pub key: String,
pub title: String,
pub count: Option<u64>,
pub open: bool,
pub height: f32,
pub by_hand: bool,
#[cfg_attr(feature = "serde", serde(skip))]
pub band: Rect,
#[cfg_attr(feature = "serde", serde(skip))]
pub body: Option<Rect>,
pub scroll: f32,
pub window: Option<Range<usize>>,
pub empty: f32,
pub drag: Option<DragMode>,
}
#[derive(Clone, Debug)]
struct Hands(Vec<Option<f32>>);
impl Hands {
fn asked(&self, stack: &Shown<'_>) -> Vec<Asked> {
stack
.asked
.iter()
.zip(&self.0)
.map(|(a, &hand)| Asked { hand, ..*a })
.collect()
}
}
#[derive(Clone, Debug)]
struct Drag {
origin: f32,
top: f32,
hands: Hands,
last: f32,
}
#[derive(Clone, Debug)]
struct TitleClick {
key: String,
band: Rect,
at: f64,
}
fn temp_id(name: &str, what: &str) -> Id {
Id::unique(("egui_stack.sections", name, what))
}
fn get_temp<T: 'static + Clone + Send + Sync>(ctx: &Context, name: &str, what: &str) -> Option<T> {
ctx.data(|d| d.get_temp::<T>(temp_id(name, what)))
}
fn set_temp<T: 'static + Clone + Send + Sync>(ctx: &Context, name: &str, what: &str, value: T) {
ctx.data_mut(|d| d.insert_temp(temp_id(name, what), value));
}
fn remove_temp<T: 'static + Clone + Send + Sync>(ctx: &Context, name: &str, what: &str) {
ctx.data_mut(|d| d.remove::<T>(temp_id(name, what)));
}
const LAID: &str = "laid";
const DRAG: &str = "drag";
const TITLE_CLICK: &str = "title_click";
const CONTENT: &str = "content";
pub fn laid_out(ctx: &Context, name: &str) -> Vec<Laid> {
get_temp(ctx, name, LAID).unwrap_or_default()
}
pub fn row_height(ui: &Ui) -> f32 {
ui.spacing()
.interact_size
.y
.max(ui.text_style_height(&TextStyle::Body))
}
#[derive(Clone, Debug)]
pub struct Section {
key: String,
title: String,
count: Option<u64>,
min_height: Option<f32>,
row_height: Option<f32>,
open: bool,
}
impl Section {
pub fn new(key: impl Into<String>, title: impl Into<String>) -> Self {
Section {
key: key.into(),
title: title.into(),
count: None,
min_height: None,
row_height: None,
open: true,
}
}
pub fn count(mut self, count: u64) -> Self {
self.count = Some(count);
self
}
pub fn min_height(mut self, points: f32) -> Self {
self.min_height = Some(points.max(0.0));
self
}
pub fn row_height(mut self, points: f32) -> Self {
self.row_height = Some(points.max(1.0));
self
}
pub fn open(mut self, open: bool) -> Self {
self.open = open;
self
}
fn name(&self) -> String {
match self.count {
Some(n) => format!("{}, {n}", self.title),
None => self.title.clone(),
}
}
}
type DrawRows<'a> = Box<dyn FnOnce(&mut Ui, Range<usize>) + 'a>;
enum Body<'a> {
Scrolled(Box<dyn FnOnce(&mut Ui) + 'a>),
Rows { count: usize, draw: DrawRows<'a> },
Bare(Box<dyn FnOnce(&mut Ui) + 'a>),
}
struct Drawn {
scroll: f32,
content: f32,
window: Option<Range<usize>>,
holds_wheel: bool,
}
impl Body<'_> {
fn least(&self, ui: &Ui, row: f32) -> f32 {
match self {
Body::Rows { count, .. } => {
plan::rows_least(row, *count) + ui.spacing().scroll.content_margin.sum().y
}
Body::Scrolled(_) | Body::Bare(_) => 2.0 * row,
}
}
fn draw(self, ui: &mut Ui, salt: &str, row: f32, bars: &Bars) -> Drawn {
let rect = ui.max_rect();
let margin = ui.spacing().scroll.content_margin.sum().y;
let content = ui.style().clone();
let area = bars.on(
egui::ScrollArea::vertical()
.id_salt(("egui_stack.sections.scroll", salt))
.auto_shrink([false, false])
.max_height(rect.height())
.min_scrolled_height(0.0),
rect,
);
match self {
Body::Scrolled(draw) => {
let out = bars.show(ui, |ui| {
area.show(ui, |ui| {
ui.set_style(content);
draw(ui);
})
});
Drawn {
scroll: out.state.clamped_offset().y,
content: out.content_size.y + margin,
window: None,
holds_wheel: scrolled(ui.ctx(), &out),
}
}
Body::Rows { count, draw } => {
ui.spacing_mut().item_spacing.y = 0.0;
let content = ui.style().clone();
let mut window = None;
let out = bars.show(ui, |ui| {
area.show_rows(ui, row, count, |ui, range| {
ui.set_style(content);
window = Some(range.clone());
draw(ui, range);
})
});
Drawn {
scroll: out.state.clamped_offset().y,
content: count as f32 * row + margin,
window,
holds_wheel: scrolled(ui.ctx(), &out),
}
}
Body::Bare(draw) => {
draw(ui);
Drawn {
scroll: 0.0,
content: ui.min_rect().height(),
window: None,
holds_wheel: true,
}
}
}
}
}
#[derive(Clone, Default)]
struct Bars {
style: Option<Arc<egui::Style>>,
inset: f32,
}
impl Bars {
fn on(&self, area: egui::ScrollArea, rect: Rect) -> egui::ScrollArea {
if self.inset > 0.0 {
let inset = vec2(
self.inset.min(rect.width() / 2.0),
self.inset.min(rect.height() / 2.0),
);
area.scroll_bar_rect(rect.shrink2(inset))
} else {
area
}
}
fn show<R>(&self, ui: &mut Ui, show: impl FnOnce(&mut Ui) -> R) -> R {
let Some(style) = &self.style else {
return show(ui);
};
let mut scoped = style.as_ref().clone();
scoped.spacing = ui.spacing().clone();
ui.scope(|ui| {
ui.set_style(scoped);
show(ui)
})
.inner
}
}
fn scrolled<R>(ctx: &Context, out: &egui::scroll_area::ScrollAreaOutput<R>) -> bool {
let id = out.id.with("egui_stack.sections.offset");
let offset = out.state.clamped_offset().y;
let before = ctx.data(|d| d.get_temp::<f32>(id));
if before != Some(offset) {
ctx.data_mut(|d| d.insert_temp(id, offset));
if before.is_some() {
ctx.request_repaint();
}
}
out.content_size.y - out.inner_rect.height() > 0.5
}
fn contain_wheel_in(ui: &Ui, rect: Rect) {
if !ui.is_enabled() || !ui.rect_contains_pointer(rect) {
return;
}
let either = ui.style().always_scroll_the_only_direction;
ui.input_mut(|i| {
if either {
i.smooth_scroll_delta.x = 0.0;
}
i.smooth_scroll_delta.y = 0.0;
});
}
pub struct Stack<'a> {
sections: Vec<(Section, Body<'a>)>,
}
impl std::fmt::Debug for Stack<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list()
.entries(self.sections.iter().map(|(s, _)| &s.key))
.finish()
}
}
impl<'a> Stack<'a> {
pub fn section(&mut self, section: Section, body: impl FnOnce(&mut Ui) + 'a) -> &mut Self {
self.sections
.push((section, Body::Scrolled(Box::new(body))));
self
}
pub fn rows(
&mut self,
section: Section,
count: usize,
draw: impl FnOnce(&mut Ui, Range<usize>) + 'a,
) -> &mut Self {
let draw = Box::new(draw);
self.sections.push((section, Body::Rows { count, draw }));
self
}
pub fn bare(&mut self, section: Section, body: impl FnOnce(&mut Ui) + 'a) -> &mut Self {
self.sections.push((section, Body::Bare(Box::new(body))));
self
}
}
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct SectionsResponse {
pub toggled: Option<(String, bool)>,
pub resized: bool,
pub reset: bool,
pub layout: Layout,
}
type PullWhen<'a> = Box<dyn Fn(Modifiers, PointerButton) -> bool + 'a>;
pub struct Sections<'a> {
name: String,
capitals: bool,
grab_titles: bool,
keep_titles: bool,
band_height: Option<f32>,
pull_when: PullWhen<'a>,
overflow_scroll: Option<ScrollStyle>,
fill: bool,
bars: Bars,
painter: &'a (dyn DockPainter + Sync),
labels: Labels,
}
impl std::fmt::Debug for Sections<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Sections")
.field("name", &self.name)
.field("capitals", &self.capitals)
.field("grab_titles", &self.grab_titles)
.field("keep_titles", &self.keep_titles)
.field("band_height", &self.band_height)
.field("fill", &self.fill)
.field("labels", &self.labels)
.finish_non_exhaustive()
}
}
impl<'a> Sections<'a> {
pub fn new(name: impl Into<String>) -> Self {
Sections {
name: name.into(),
capitals: true,
grab_titles: false,
keep_titles: false,
band_height: None,
pull_when: pull_with(Some(Modifiers::COMMAND)),
overflow_scroll: None,
fill: true,
bars: Bars::default(),
painter: &StylePainter,
labels: Labels::ENGLISH,
}
}
pub fn painter(mut self, painter: &'a (dyn DockPainter + Sync)) -> Self {
self.painter = painter;
self
}
pub fn labels(mut self, labels: Labels) -> Self {
self.labels = labels;
self
}
pub fn capitals(mut self, capitals: bool) -> Self {
self.capitals = capitals;
self
}
pub fn band_height(mut self, points: f32) -> Self {
self.band_height = Some(points.max(1.0));
self
}
pub fn pull_modifiers(mut self, modifiers: Option<Modifiers>) -> Self {
self.pull_when = pull_with(modifiers);
self
}
pub fn pull_when(mut self, pulls: impl Fn(Modifiers, PointerButton) -> bool + 'a) -> Self {
self.pull_when = Box::new(pulls);
self
}
pub fn overflow_scroll(mut self, style: ScrollStyle) -> Self {
self.overflow_scroll = Some(style);
self
}
pub fn fill(mut self, fill: bool) -> Self {
self.fill = fill;
self
}
pub fn bar_style(mut self, style: Arc<egui::Style>) -> Self {
self.bars.style = Some(style);
self
}
pub fn bar_track_inset(mut self, points: f32) -> Self {
self.bars.inset = if points.is_finite() {
points.max(0.0)
} else {
0.0
};
self
}
pub fn grab_titles(mut self, grab: bool) -> Self {
self.grab_titles = grab;
self
}
pub fn keep_titles(mut self, keep: bool) -> Self {
self.keep_titles = keep;
self
}
pub fn show<'b>(self, ui: &mut Ui, add: impl FnOnce(&mut Stack<'b>)) -> SectionsResponse {
let mut stack = Stack {
sections: Vec::new(),
};
add(&mut stack);
self.lay_out(ui, stack.sections)
}
fn lay_out(&self, ui: &mut Ui, sections: Vec<(Section, Body<'_>)>) -> SectionsResponse {
let ctx = ui.ctx().clone();
let row = row_height(ui);
let band_h = self.band_height.unwrap_or(row + 4.0);
let mut layout = Layout::load(&ctx, &self.name).unwrap_or_default();
for (s, _) in §ions {
layout.sections.entry(s.key.clone()).or_insert(Remembered {
open: s.open,
height: None,
});
}
let asked: Vec<Asked> = sections
.iter()
.map(|(s, body)| {
let remembered = layout.sections[&s.key];
Asked {
open: remembered.open,
least: s
.min_height
.unwrap_or_else(|| body.least(ui, s.row_height.unwrap_or(row))),
hand: remembered.height.filter(|h| h.is_finite()),
}
})
.collect();
let keys: Vec<String> = sections.iter().map(|(s, _)| s.key.clone()).collect();
let open: Vec<bool> = asked.iter().map(|a| a.open).collect();
let room = ui.available_rect_before_wrap();
let finite = room.height().is_finite();
let bands = sections.len() as f32 * band_h;
let space = if finite {
(room.height() - bands).max(0.0)
} else {
0.0
};
let content: BTreeMap<String, f32> =
get_temp(&ctx, &self.name, CONTENT).unwrap_or_default();
let most: Vec<f32> = if self.fill {
Vec::new()
} else {
keys.iter()
.map(|k| content.get(k).copied().unwrap_or(f32::INFINITY))
.collect()
};
let (fit, spare) = plan::fit_within(&asked, &most, space, layout.empty);
let tall = bands + fit.heights.iter().sum::<f32>();
let overflows = finite && tall - room.height() > 0.5;
let stack = Shown {
keys: &keys,
asked: &asked,
heights: &fit.heights,
most: &most,
space,
empty: fit.empty - spare,
step: row,
};
let mut contents: BTreeMap<String, f32> = BTreeMap::new();
let mut response = SectionsResponse::default();
let mut laid: Vec<Laid> = Vec::with_capacity(sections.len());
let base = memory_id(&self.name);
let reach = ui.style().interaction.resize_grab_radius_side;
let window = ctx.options(|o| o.input_options.max_double_click_delay);
let (now, released) =
ui.input(|i| (i.time, i.pointer.any_down() || i.pointer.any_released()));
let last_click: Option<TitleClick> = get_temp(&ctx, &self.name, TITLE_CLICK);
let draw = |ui: &mut Ui| {
let left = ui.max_rect().left();
let width = ui.available_width();
let top = ui.cursor().min.y;
let mut y = top;
let mut boundaries = Vec::new();
for (i, (section, body)) in sections.into_iter().enumerate() {
let is_open = asked[i].open;
let band = Rect::from_min_size(pos2(left, y), vec2(width, band_h));
let mut hit = band;
let above = i
.checked_sub(1)
.and_then(|line| plan::resized_above(&open, line));
let room_below = fit.empty > 0.5 || asked[i..].iter().any(|a| a.open);
let line = above
.filter(|_| room_below)
.filter(|&above| !self.grab_titles || above + 1 == i);
if let Some(above) = line {
let edge = if self.grab_titles {
Rect::from_x_y_ranges(band.x_range(), y - reach..=y)
} else {
hit.min.y = (hit.min.y + reach).min(hit.max.y);
Rect::from_x_y_ranges(band.x_range(), y - reach..=y + reach)
};
let id = base.with(("boundary", &laid[i - 1].key));
let sense = if above == i - 1 {
Sense::click_and_drag()
} else {
Sense::CLICK | Sense::DRAG
};
let r = ui.interact(edge, id, sense);
let name = self
.labels
.resize_section
.replace("{section}", &laid[above].title);
name_boundary(&ctx, &r, &name, &stack, above);
if overflows && r.gained_focus() {
r.scroll_to_me(None);
}
let mode =
self.work_boundary(ui, &r, &stack, above, &mut layout, &mut response);
laid[above].drag = mode.or(laid[above].drag);
boundaries.push((edge, y, r.id, part_state(&r)));
}
let grabbed = above.filter(|_| self.grab_titles);
let sense = if grabbed.is_some() {
Sense::click_and_drag()
} else {
Sense::click()
};
let r = ui.interact(hit, base.with(("band", §ion.key)), sense);
if let Some(above) = grabbed {
let mode = self.work_drag(ui, &r, &stack, above, &mut layout, &mut response);
laid[above].drag = mode.or(laid[above].drag);
}
self.paint_band(ui, §ion, band, &r, is_open);
name_band(&ctx, &r, §ion.name(), is_open);
if overflows && r.gained_focus() {
r.scroll_to_me(None);
}
if self.grab_titles && r.double_clicked() {
if last_click.as_ref().is_some_and(|c| c.key == section.key) {
stack.fold(&mut layout, &mut response, i, false);
}
self.reset(&ctx, &mut layout, &mut response);
} else if r.clicked() || arrow_folds(ui, &r, is_open) {
stack.fold(&mut layout, &mut response, i, self.keep_titles);
if self.grab_titles && r.clicked() {
let key = section.key.clone();
let click = TitleClick { key, band, at: now };
set_temp(&ctx, &self.name, TITLE_CLICK, click);
ctx.request_repaint_after_secs(window as f32);
}
}
y = band.bottom();
let mut body_rect = None;
let mut drawn = None;
if is_open {
let rect = Rect::from_min_size(pos2(left, y), vec2(width, fit.heights[i]));
let mut child = ui.new_child(
UiBuilder::new()
.id_salt(("egui_stack.sections.body", &self.name, §ion.key))
.max_rect(rect)
.layout(egui::Layout::top_down(egui::Align::Min)),
);
child.set_clip_rect(rect.intersect(ui.clip_rect()));
let shown = body.draw(
&mut child,
§ion.key,
section.row_height.unwrap_or(row),
&self.bars,
);
contents.insert(section.key.clone(), shown.content);
if shown.holds_wheel {
contain_wheel_in(&child, rect);
}
drawn = Some(shown);
y = rect.bottom();
body_rect = Some(rect);
}
laid.push(Laid {
key: section.key,
title: section.title,
count: section.count,
open: is_open,
height: fit.heights[i],
by_hand: fit.by_hand[i],
band,
body: body_rect,
scroll: drawn.as_ref().map_or(0.0, |d| d.scroll),
window: drawn.and_then(|d| d.window),
empty: if i + 1 == asked.len() { fit.empty } else { 0.0 },
drag: None,
});
}
let moved = last_click
.as_ref()
.filter(|c| now - c.at <= window || released)
.and_then(|c| {
let at = stack.keys.iter().position(|k| *k == c.key)?;
((laid[at].band.top() - c.band.top()).abs() > 0.5).then_some((at, c.band))
});
if let Some((at, band)) = moved {
let r = ui.interact(band, base.with("title_click"), Sense::click());
if r.double_clicked() {
stack.fold(&mut layout, &mut response, at, false);
self.reset(&ctx, &mut layout, &mut response);
} else if r.clicked() {
stack.fold(&mut layout, &mut response, at, self.keep_titles);
}
}
for (rect, line, id, state) in boundaries {
if ui.is_rect_visible(rect) {
let boundary = SectionBoundaryPaint {
rect,
line,
id,
state,
style: ui.style(),
};
self.painter.section_boundary(ui.painter(), &boundary);
}
}
let end = if finite && !overflows {
y.min(top + room.height())
} else {
y
};
ui.advance_cursor_after_rect(Rect::from_min_max(
pos2(left, top),
pos2(left + width, end.max(top)),
));
};
if finite {
let area = egui::ScrollArea::vertical()
.id_salt(("egui_stack.sections.stack", &self.name))
.auto_shrink([false, false])
.max_height(room.height())
.min_scrolled_height(0.0)
.scroll_source(ScrollSource {
drag: DragScroll::Never,
..ScrollSource::default()
})
.scroll_bar_visibility(if overflows {
ScrollBarVisibility::AlwaysVisible
} else {
ScrollBarVisibility::AlwaysHidden
});
let area = self.bars.on(area, room);
let bodies = ui.spacing().scroll;
let content = ui.style().clone();
ui.scope(|ui| {
if overflows && let Some(style) = self.overflow_scroll {
ui.spacing_mut().scroll = style;
}
self.bars.show(ui, |ui| {
area.show(ui, |ui| {
ui.set_style(content);
ui.spacing_mut().scroll = bodies;
draw(ui);
})
});
});
} else {
draw(ui);
}
if !self.fill && contents != content {
ctx.request_repaint();
}
set_temp(&ctx, &self.name, CONTENT, contents);
if response.toggled.is_some() || response.resized || response.reset {
ctx.request_repaint();
}
layout.store(&ctx, &self.name);
set_temp(&ctx, &self.name, LAID, laid);
response.layout = layout;
response
}
fn reset(&self, ctx: &Context, layout: &mut Layout, response: &mut SectionsResponse) {
layout.reset_heights();
response.reset = true;
remove_temp::<Drag>(ctx, &self.name, DRAG);
remove_temp::<TitleClick>(ctx, &self.name, TITLE_CLICK);
}
fn paint_band(&self, ui: &Ui, section: &Section, band: Rect, r: &Response, open: bool) {
if !ui.is_rect_visible(band) {
return;
}
let title = if self.capitals {
section.title.to_uppercase()
} else {
section.title.clone()
};
let paint = SectionBandPaint {
rect: band,
id: r.id,
title: &title,
count: section.count,
open,
state: part_state(r),
style: ui.style(),
};
self.painter.section_band(ui.painter(), &paint);
}
fn pulls(&self, modifiers: Modifiers, button: PointerButton) -> bool {
(self.pull_when)(modifiers, button)
}
fn drag_mode(&self, ui: &Ui) -> DragMode {
let pull = ui.input(|i| {
[
PointerButton::Primary,
PointerButton::Secondary,
PointerButton::Middle,
PointerButton::Extra1,
PointerButton::Extra2,
]
.into_iter()
.any(|b| i.pointer.button_down(b) && self.pulls(i.modifiers, b))
});
if pull { DragMode::Pull } else { DragMode::Push }
}
fn keys_mode(&self, ui: &Ui) -> DragMode {
if ui.input(|i| self.pulls(i.modifiers, PointerButton::Primary)) {
DragMode::Pull
} else {
DragMode::Push
}
}
fn work_drag(
&self,
ui: &Ui,
r: &Response,
stack: &Shown<'_>,
above: usize,
layout: &mut Layout,
response: &mut SectionsResponse,
) -> Option<DragMode> {
let ctx = ui.ctx();
let name = &self.name;
if r.drag_started() {
let origin = ui
.input(|i| i.pointer.press_origin())
.map_or(r.rect.center().y, |p| p.y);
let drag = Drag {
origin,
top: stack.top(above),
hands: stack.hands(),
last: origin,
};
set_temp(ctx, name, DRAG, drag);
}
let mut mode = None;
if r.dragged() {
ctx.set_cursor_icon(CursorIcon::ResizeVertical);
let drag =
get_temp::<Drag>(ctx, name, DRAG).filter(|d| d.hands.0.len() == stack.keys.len());
if let (Some(mut drag), Some(pointer)) = (drag, r.interact_pointer_pos()) {
let now = self.drag_mode(ui);
let wanted = pointer.y - drag.origin;
let reach = (pointer.y - drag.last).abs();
let delta = (wanted - (stack.top(above) - drag.top)).clamp(-reach, reach);
if delta.abs() > 0.01 {
response.resized |= stack.drag(layout, &drag.hands, above, delta, now);
}
drag.last = pointer.y;
set_temp(ctx, name, DRAG, drag);
mode = Some(now);
}
}
if r.drag_stopped() {
remove_temp::<Drag>(ctx, name, DRAG);
}
mode
}
fn work_boundary(
&self,
ui: &Ui,
r: &Response,
stack: &Shown<'_>,
above: usize,
layout: &mut Layout,
response: &mut SectionsResponse,
) -> Option<DragMode> {
let ctx = ui.ctx();
if r.hovered() {
ctx.set_cursor_icon(CursorIcon::ResizeVertical);
}
if r.has_focus() {
ui.memory_mut(|m| {
m.set_focus_lock_filter(
r.id,
EventFilter {
vertical_arrows: true,
..Default::default()
},
);
});
}
if r.double_clicked() || (r.has_focus() && ui.input(|i| i.key_pressed(Key::Enter))) {
layout.reset_heights();
response.reset = true;
remove_temp::<Drag>(ctx, &self.name, DRAG);
return None;
}
let dragging = self.work_drag(ui, r, stack, above, layout, response);
let focused = r.has_focus();
let steps = ui.input(|i| {
let keys = if focused {
i.num_presses(Key::ArrowDown) as f32 - i.num_presses(Key::ArrowUp) as f32
} else {
0.0
};
keys + i.num_accesskit_action_requests(r.id, Action::Increment) as f32
- i.num_accesskit_action_requests(r.id, Action::Decrement) as f32
});
if steps != 0.0 {
let delta = steps * stack.step;
let mode = self.keys_mode(ui);
response.resized |= stack.drag(layout, &stack.hands(), above, delta, mode);
}
dragging
}
}
fn pull_with<'a>(modifiers: Option<Modifiers>) -> PullWhen<'a> {
Box::new(move |held: Modifiers, button| {
button == PointerButton::Primary && modifiers.is_some_and(|m| held.matches_exact(m))
})
}
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())
.with(PartState::DRAGGED, r.dragged())
}
fn name_band(ctx: &Context, r: &Response, name: &str, open: bool) {
let enabled = r.enabled();
r.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, name));
ctx.accesskit_node_builder(r.id, |node| node.set_expanded(open));
}
struct Shown<'a> {
keys: &'a [String],
asked: &'a [Asked],
heights: &'a [f32],
most: &'a [f32],
space: f32,
empty: f32,
step: f32,
}
impl Shown<'_> {
fn placed(&self, heights: &[f32]) -> Vec<Placed> {
self.asked
.iter()
.zip(heights)
.map(|(a, &height)| Placed {
open: a.open,
least: a.least,
height,
})
.collect()
}
fn drag(
&self,
layout: &mut Layout,
hands: &Hands,
above: usize,
delta: f32,
mode: DragMode,
) -> bool {
let placed = self.placed(self.heights);
let plan = plan::plan_drag(&placed, above, delta, self.empty, mode);
let pinned = plan::pin_plan_within(
&hands.asked(self),
self.most,
self.space,
plan.empty,
&plan.heights,
);
for (key, hand) in self.keys.iter().zip(pinned) {
layout.set_height(key, hand);
}
layout.empty = plan.empty;
let moved = |(a, b): (&f32, &f32)| (a - b).abs() > 0.01;
(plan.empty - self.empty).abs() > 0.01 || plan.heights.iter().zip(self.heights).any(moved)
}
fn hands(&self) -> Hands {
Hands(self.asked.iter().map(|a| a.hand).collect())
}
fn top(&self, above: usize) -> f32 {
self.heights[..=above].iter().sum()
}
fn fold(
&self,
layout: &mut Layout,
response: &mut SectionsResponse,
section: usize,
keep: bool,
) {
if keep {
let kept = plan::keep_title(self.asked, self.heights, self.empty, section);
for (key, hand) in self.keys.iter().zip(kept.hands) {
layout.set_height(key, hand);
}
layout.empty = kept.empty;
}
let (key, open) = (&self.keys[section], !self.asked[section].open);
layout.set_open(key, open);
response.toggled = Some((key.clone(), open));
}
fn reach(&self, above: usize) -> (bool, f32) {
let placed = self.placed(self.heights);
let plan = |delta| plan::plan_drag(&placed, above, delta, self.empty, DragMode::Push);
(
plan(-self.step).moved < 0.0,
plan(self.space).heights[above],
)
}
}
fn name_boundary(ctx: &Context, r: &Response, name: &str, stack: &Shown<'_>, above: usize) {
let value = stack.heights[above];
let (shrinks, most) = stack.reach(above);
r.widget_info(|| WidgetInfo::labeled(Role::Unknown, true, name));
ctx.accesskit_node_builder(r.id, |node| {
node.set_role(Role::Splitter);
node.set_numeric_value(f64::from(value));
node.set_min_numeric_value(f64::from(stack.asked[above].least.min(value)));
node.set_max_numeric_value(f64::from(most));
node.set_numeric_value_step(f64::from(stack.step));
if most > value {
node.add_action(Action::Increment);
}
if shrinks {
node.add_action(Action::Decrement);
}
});
}
fn arrow_folds(ui: &Ui, r: &Response, open: bool) -> bool {
if !r.has_focus() {
return false;
}
ui.memory_mut(|m| {
m.set_focus_lock_filter(
r.id,
EventFilter {
horizontal_arrows: true,
..Default::default()
},
);
});
let key = if open {
Key::ArrowLeft
} else {
Key::ArrowRight
};
ui.input(|i| i.key_pressed(key))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(feature = "serde")]
fn a_layout_keeps_its_heights_through_a_round_trip_and_drops_them_on_reset() {
let mut layout = Layout::default();
layout.set_open("live", false);
layout.set_height("live", Some(120.0));
layout.set_height("idle", Some(40.0));
let text = serde_json::to_string(&layout).unwrap();
let mut back: Layout = serde_json::from_str(&text).unwrap();
assert_eq!(back, layout);
back.reset_heights();
assert_eq!(back.height("live"), None);
assert_eq!(back.is_open("live"), Some(false), "the fold stays");
}
#[test]
#[cfg(feature = "serde")]
fn a_layout_without_heights_or_empty_room_reads_as_sized_by_the_list() {
let old = r#"{"sections":{"live":{"open":false},"idle":{"open":true}}}"#;
let layout: Layout = serde_json::from_str(old).unwrap();
assert_eq!(layout.is_open("live"), Some(false));
assert_eq!(layout.height("idle"), None);
assert_eq!(layout.empty, 0.0);
}
#[test]
fn a_band_count_past_99_is_capped() {
let style = egui::Style::default();
let band = |count| SectionBandPaint {
rect: Rect::ZERO,
id: Id::NULL,
title: "",
count,
open: true,
state: PartState::NONE,
style: &style,
};
assert_eq!(band(Some(3)).count_text().as_deref(), Some("3"));
assert_eq!(band(Some(99)).count_text().as_deref(), Some("99"));
assert_eq!(band(Some(100)).count_text().as_deref(), Some("99+"));
assert_eq!(band(None).count_text(), None);
}
}