1use std::hash::{Hash, Hasher};
63
64use egui::{
65 Align as EguiAlign, AsIdSalt, IdSalt, InnerResponse, Layout, Pos2, Rect, Response, Sense,
66 Shape, TextStyle, TextWrapMode, Ui, UiBuilder, Vec2, pos2, vec2,
67};
68
69use super::{Space, TextRole, UiPop};
70use crate::theme::Tokens;
71
72#[derive(Clone, Copy, Debug, PartialEq)]
74pub enum Length {
75 Em(f32),
78 Percent(f32),
80}
81
82impl Length {
83 pub fn points(self, em: f32, width: f32) -> f32 {
85 match self {
86 Length::Em(n) => n * em,
87 Length::Percent(p) => p / 100.0 * width,
88 }
89 }
90}
91
92#[derive(Clone, Copy, Debug, PartialEq)]
93enum Size {
94 Content,
95 Fr(f32),
96 Fixed(Length),
97}
98
99#[derive(Clone, Copy, Debug, PartialEq)]
101pub struct Track {
102 size: Size,
103 min: Option<Length>,
104 max: Option<Length>,
105}
106
107impl Track {
108 pub const CONTENT: Track = Track {
111 size: Size::Content,
112 min: None,
113 max: None,
114 };
115
116 pub fn fr(weight: f32) -> Self {
119 Self::of(Size::Fr(weight.max(0.0)))
120 }
121
122 pub fn em(n: f32) -> Self {
124 Self::of(Size::Fixed(Length::Em(n)))
125 }
126
127 pub fn percent(p: f32) -> Self {
129 Self::of(Size::Fixed(Length::Percent(p)))
130 }
131
132 pub fn min(mut self, min: Length) -> Self {
134 self.min = Some(min);
135 self
136 }
137
138 pub fn max(mut self, max: Length) -> Self {
140 self.max = Some(max);
141 self
142 }
143
144 fn of(size: Size) -> Self {
145 Self {
146 size,
147 min: None,
148 max: None,
149 }
150 }
151
152 fn clamp(&self, w: f32, em: f32, width: f32) -> f32 {
153 let w = self.max.map_or(w, |m| w.min(m.points(em, width)));
154 self.min.map_or(w, |m| w.max(m.points(em, width))).max(0.0)
155 }
156}
157
158#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
161pub enum Align {
162 Start,
164 Center,
166 End,
168 #[default]
171 Baseline,
172}
173
174impl Align {
175 fn share(self) -> f32 {
176 match self {
177 Align::Start | Align::Baseline => 0.0,
178 Align::Center => 0.5,
179 Align::End => 1.0,
180 }
181 }
182}
183
184#[derive(Clone, Debug)]
185pub(super) struct Spec {
186 id_salt: Option<IdSalt>,
187 tracks: Vec<Track>,
188 gap: Space,
189 row_gap: Space,
190 align: Align,
191 justify: Align,
192 equal: bool,
193 fold_below: Option<Length>,
194}
195
196impl Spec {
197 fn new(tracks: impl IntoIterator<Item = Track>) -> Self {
198 let mut tracks: Vec<Track> = tracks.into_iter().collect();
199 if tracks.is_empty() {
200 tracks.push(Track::CONTENT);
201 }
202 Self {
203 id_salt: None,
204 tracks,
205 gap: Space::Inline,
206 row_gap: Space::Inline,
207 align: Align::Baseline,
208 justify: Align::Start,
209 equal: false,
210 fold_below: None,
211 }
212 }
213}
214
215#[derive(Clone, Debug)]
218pub struct Row(pub(super) Spec);
219
220impl Row {
221 pub fn new(tracks: impl IntoIterator<Item = Track>) -> Self {
223 Self(Spec::new(tracks))
224 }
225
226 pub fn id_salt(mut self, salt: impl AsIdSalt) -> Self {
229 self.0.id_salt = Some(IdSalt::new(salt));
230 self
231 }
232
233 pub fn gap(mut self, gap: Space) -> Self {
235 self.0.gap = gap;
236 self
237 }
238
239 pub fn align(mut self, align: Align) -> Self {
241 self.0.align = align;
242 self
243 }
244
245 pub fn justify(mut self, justify: Align) -> Self {
248 self.0.justify = justify;
249 self
250 }
251
252 pub fn equal_widths(mut self) -> Self {
255 self.0.equal = true;
256 self
257 }
258}
259
260#[derive(Clone, Debug)]
264pub struct Grid(pub(super) Spec);
265
266impl Grid {
267 pub fn new(id_salt: impl AsIdSalt, tracks: impl IntoIterator<Item = Track>) -> Self {
269 let mut spec = Spec::new(tracks);
270 spec.id_salt = Some(IdSalt::new(id_salt));
271 spec.gap = Space::Group;
272 Self(spec)
273 }
274
275 pub fn gap(mut self, gap: Space) -> Self {
277 self.0.gap = gap;
278 self
279 }
280
281 pub fn row_gap(mut self, gap: Space) -> Self {
283 self.0.row_gap = gap;
284 self
285 }
286
287 pub fn align(mut self, align: Align) -> Self {
290 self.0.align = align;
291 self
292 }
293
294 pub fn equal_widths(mut self) -> Self {
296 self.0.equal = true;
297 self
298 }
299
300 pub fn fold_below(mut self, width: Length) -> Self {
304 self.0.fold_below = Some(width);
305 self
306 }
307}
308
309#[derive(Clone, Copy, Debug, Default, PartialEq)]
311struct Cell {
312 height: f32,
313 baseline: f32,
314}
315
316#[derive(Clone, Debug, Default)]
318struct Measured {
319 content: Vec<f32>,
321 lines: Vec<Vec<Cell>>,
323 texts: Vec<u64>,
326 remeasure: bool,
328}
329
330impl Measured {
331 fn near(&self, other: &Self) -> bool {
332 let close = |a: f32, b: f32| (a - b).abs() < 0.5;
333 self.content.len() == other.content.len()
334 && self
335 .content
336 .iter()
337 .zip(&other.content)
338 .all(|(a, b)| close(*a, *b))
339 && self.lines.len() == other.lines.len()
340 && self.lines.iter().zip(&other.lines).all(|(a, b)| {
341 a.len() == b.len()
342 && a.iter()
343 .zip(b)
344 .all(|(a, b)| close(a.height, b.height) && close(a.baseline, b.baseline))
345 })
346 && self.texts == other.texts
347 && self.remeasure == other.remeasure
348 }
349}
350
351pub struct Cells<'a> {
353 ui: &'a mut Ui,
354 spec: Spec,
355 id: egui::Id,
356 prev: Measured,
357 next: Measured,
358 folded: bool,
359 measuring: bool,
360 xs: Vec<f32>,
361 widths: Vec<f32>,
362 origin: Pos2,
363 full_width: f32,
364 bottom_limit: f32,
365 body_row: f32,
366 body_baseline: f32,
367 index: usize,
368 line_top: f32,
369 line_bottom: f32,
370 right: f32,
371 ppp: f32,
372}
373
374impl std::fmt::Debug for Cells<'_> {
375 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376 f.debug_struct("Cells")
377 .field("id", &self.id)
378 .field("index", &self.index)
379 .field("folded", &self.folded)
380 .field("widths", &self.widths)
381 .finish_non_exhaustive()
382 }
383}
384
385impl Cells<'_> {
386 pub fn cell<R>(&mut self, add: impl FnOnce(&mut Ui) -> R) -> R {
389 let n = self.spec.tracks.len();
390 let (line, col) = (self.index / n, self.index % n);
391 let index = self.index;
392 self.index += 1;
393 let space = |s: Space| s.points(&Tokens::of(self.ui.ctx()));
394 if index > 0 && (self.folded || col == 0) {
395 let gap = match (self.folded, col) {
396 (true, 0) => space(Space::Group).max(space(self.spec.row_gap)),
397 (true, _) => space(Space::Inline),
398 _ => space(self.spec.row_gap),
399 };
400 self.line_top = self.round(self.line_bottom + gap);
401 self.line_bottom = self.line_top;
402 }
403 let track = self.spec.tracks[col];
404 let content = track.size == Size::Content;
405 let equal = self.spec.equal && content;
406 let (x, width) = if self.folded {
407 (self.origin.x, self.full_width)
408 } else if equal && self.measuring {
409 (self.xs[col], 0.0)
410 } else {
411 (self.xs[col], self.widths[col])
412 };
413 let offset = if self.folded {
414 0.0
415 } else {
416 self.round(self.offset(line, col))
417 };
418 let top = self.line_top + offset;
419 let rect = Rect::from_min_max(pos2(x, top), pos2(x + width, self.bottom_limit.max(top)));
420 let layout = if equal {
421 Layout::top_down_justified(EguiAlign::Center)
422 } else {
423 Layout::top_down(EguiAlign::Min)
424 };
425 let mut child = self.ui.new_child(
426 UiBuilder::new()
427 .id_salt(("egui_pop.cell", index))
428 .max_rect(rect)
429 .layout(layout),
430 );
431 if content && !self.folded {
432 child.style_mut().wrap_mode = Some(TextWrapMode::Extend);
433 }
434 let layer = child.layer_id();
435 let start = self
436 .ui
437 .ctx()
438 .graphics(|g| g.get(layer).map_or(0, |l| l.next_idx().0));
439 let out = add(&mut child);
440 let used = child.min_rect();
441 let (first, texts) = scan(self.ui.ctx(), layer, start);
442 let height = (used.bottom() - top).max(0.0);
443 let baseline = first.map_or((height - self.body_row) / 2.0 + self.body_baseline, |y| {
444 y - top
445 });
446 self.line_bottom = self.line_bottom.max(used.bottom());
447 self.right = self.right.max(used.right()).max(rect.right());
448 if !self.folded {
449 if content {
450 let w = used.width().max(0.0);
453 self.next.content[col] = self.next.content[col].max(w);
454 }
455 if equal {
456 let mut h = std::hash::DefaultHasher::new();
457 (self.next.texts[col], texts).hash(&mut h);
458 self.next.texts[col] = h.finish();
459 }
460 if self.next.lines.len() <= line {
461 self.next.lines.resize(line + 1, vec![Cell::default(); n]);
462 }
463 self.next.lines[line][col] = Cell { height, baseline };
464 }
465 out
466 }
467
468 pub fn header(&mut self, text: impl Into<String>) -> Response {
471 let text = text.into();
472 self.cell(|ui| ui.text_role(TextRole::Muted, text))
473 }
474
475 fn offset(&self, line: usize, col: usize) -> f32 {
477 let Some(cells) = self.prev.lines.get(line) else {
478 return 0.0;
479 };
480 let Some(cell) = cells.get(col) else {
481 return 0.0;
482 };
483 match self.spec.align {
484 Align::Start => 0.0,
485 Align::Baseline => {
486 let base = cells.iter().map(|c| c.baseline).fold(0.0, f32::max);
487 base - cell.baseline
488 }
489 align => {
490 let tallest = cells.iter().map(|c| c.height).fold(0.0, f32::max);
491 (tallest - cell.height) * align.share()
492 }
493 }
494 }
495
496 fn round(&self, v: f32) -> f32 {
497 (v * self.ppp).round() / self.ppp
498 }
499}
500
501fn scan(ctx: &egui::Context, layer: egui::LayerId, start: usize) -> (Option<f32>, u64) {
504 fn visit(shape: &Shape, first: &mut Option<f32>, hash: &mut std::hash::DefaultHasher) {
505 match shape {
506 Shape::Vec(shapes) => shapes.iter().for_each(|s| visit(s, first, hash)),
507 Shape::Text(t) => {
508 t.galley.text().hash(hash);
509 if t.angle != 0.0 {
510 return;
511 }
512 let Some(row) = t.galley.rows.iter().find(|r| !r.row.glyphs.is_empty()) else {
513 return;
514 };
515 let y = t.pos.y + row.pos.y + row.row.glyphs[0].pos.y;
516 *first = Some(first.map_or(y, |f| f.min(y)));
517 }
518 _ => {}
519 }
520 }
521 let mut first = None;
522 let mut hash = std::hash::DefaultHasher::new();
523 ctx.graphics(|g| {
524 if let Some(list) = g.get(layer) {
525 list.all_entries()
526 .skip(start)
527 .for_each(|c| visit(&c.shape, &mut first, &mut hash));
528 }
529 });
530 (first, hash.finish())
531}
532
533fn widths(
535 tracks: &[Track],
536 content: &[f32],
537 width: f32,
538 gap: f32,
539 em: f32,
540 equal: bool,
541) -> Vec<f32> {
542 let mut out: Vec<f32> = tracks
543 .iter()
544 .enumerate()
545 .map(|(i, t)| match t.size {
546 Size::Content => t.clamp(content.get(i).copied().unwrap_or(0.0), em, width),
547 Size::Fixed(l) => t.clamp(l.points(em, width), em, width),
548 Size::Fr(_) => 0.0,
549 })
550 .collect();
551 if equal {
552 let widest = tracks
553 .iter()
554 .zip(&out)
555 .filter(|(t, _)| t.size == Size::Content)
556 .map(|(_, w)| *w)
557 .fold(0.0, f32::max);
558 for (t, w) in tracks.iter().zip(out.iter_mut()) {
559 if t.size == Size::Content {
560 *w = widest;
561 }
562 }
563 }
564 let gaps = gap * tracks.len().saturating_sub(1) as f32;
567 let mut left = width - gaps - out.iter().sum::<f32>();
568 let mut open: Vec<usize> = (0..tracks.len())
569 .filter(|i| matches!(tracks[*i].size, Size::Fr(_)))
570 .collect();
571 while !open.is_empty() {
572 let weight: f32 = open
573 .iter()
574 .map(|i| match tracks[*i].size {
575 Size::Fr(w) => w,
576 _ => 0.0,
577 })
578 .sum();
579 let share = |i: usize| match tracks[i].size {
580 Size::Fr(w) if weight > 0.0 => left.max(0.0) * w / weight,
581 _ => 0.0,
582 };
583 let held = open.iter().position(|&i| {
584 let s = share(i);
585 (tracks[i].clamp(s, em, width) - s).abs() > 0.01
586 });
587 match held {
588 Some(k) => {
589 let i = open.remove(k);
590 out[i] = tracks[i].clamp(share(i), em, width);
591 left -= out[i];
592 }
593 None => {
594 for &i in &open {
595 out[i] = share(i);
596 }
597 break;
598 }
599 }
600 }
601 out
602}
603
604pub(super) fn show<R>(
605 ui: &mut Ui,
606 spec: Spec,
607 add: impl FnOnce(&mut Cells<'_>) -> R,
608) -> InnerResponse<R> {
609 let id = match spec.id_salt {
610 Some(salt) => ui.make_persistent_id(salt),
611 None => {
612 let id = ui.next_auto_id();
613 ui.skip_ahead_auto_ids(1);
614 id
615 }
616 };
617 let tokens = Tokens::of(ui.ctx());
618 let em = tokens.text_role.body.size.max(1.0);
619 let avail = ui.available_rect_before_wrap();
620 let full_width = avail.width().max(0.0);
621 let prev = ui
622 .data(|d| d.get_temp::<Measured>(id))
623 .unwrap_or_else(|| Measured {
624 remeasure: true,
625 ..Measured::default()
626 });
627 let folded = spec
628 .fold_below
629 .is_some_and(|l| full_width < l.points(em, full_width));
630 let n = spec.tracks.len();
631 let gap = spec.gap.points(&tokens);
632 let mut content = prev.content.clone();
633 content.resize(n, 0.0);
634 let ws = widths(&spec.tracks, &content, full_width, gap, em, spec.equal);
635 let ppp = ui.ctx().pixels_per_point();
636 let round = |v: f32| (v * ppp).round() / ppp;
637 let total = ws.iter().sum::<f32>() + gap * n.saturating_sub(1) as f32;
638 let mut x = avail.left() + (full_width - total).max(0.0) * spec.justify.share();
639 let mut xs = Vec::with_capacity(n);
640 for w in &ws {
641 xs.push(round(x));
642 x += w + gap;
643 }
644 let body = TextStyle::Body.resolve(ui.style());
645 let probe = ui
646 .painter()
647 .layout_no_wrap("Hg".to_owned(), body, egui::Color32::WHITE);
648 let body_row = probe.size().y;
649 let body_baseline = probe
650 .rows
651 .first()
652 .and_then(|r| r.row.glyphs.first().map(|g| r.pos.y + g.pos.y))
653 .unwrap_or(body_row);
654 let top = round(avail.top());
655 let measuring = prev.remeasure;
656 let mut next = Measured {
657 content: vec![0.0; n],
658 texts: vec![0; n],
659 ..Measured::default()
660 };
661 if folded {
662 next = Measured {
664 remeasure: false,
665 ..prev.clone()
666 };
667 }
668 let mut cells = Cells {
669 ui,
670 id,
671 prev,
672 next,
673 folded,
674 measuring,
675 xs,
676 widths: ws,
677 origin: avail.min,
678 full_width,
679 bottom_limit: avail.bottom(),
680 body_row,
681 body_baseline,
682 index: 0,
683 line_top: top,
684 line_bottom: top,
685 right: avail.left(),
686 ppp,
687 spec,
688 };
689 let inner = add(&mut cells);
690 let Cells {
691 ui,
692 id,
693 prev,
694 mut next,
695 folded,
696 spec,
697 line_bottom,
698 right,
699 ..
700 } = cells;
701 if !folded {
702 next.remeasure = spec.equal && next.texts != prev.texts;
703 if measuring {
704 next.remeasure = false;
706 }
707 }
708 let changed = !next.near(&prev) || (measuring && !folded);
709 if changed {
710 ui.data_mut(|d| d.insert_temp(id, next));
711 ui.ctx()
712 .request_discard("egui-pop row or grid sizes changed");
713 }
714 let has_fr = spec.tracks.iter().any(|t| matches!(t.size, Size::Fr(_)));
715 let right = if has_fr || folded {
716 right.max(avail.right())
717 } else {
718 right
719 };
720 let rect = Rect::from_min_max(avail.min, pos2(right, line_bottom.max(avail.top())));
721 let response = ui.allocate_rect(rect, Sense::hover());
722 InnerResponse::new(inner, response)
723}
724
725#[derive(Clone, Debug)]
735pub struct Flow {
736 id_salt: Option<IdSalt>,
737 gap: Space,
738 row_gap: Space,
739}
740
741impl Default for Flow {
742 fn default() -> Self {
743 Self::new()
744 }
745}
746
747impl Flow {
748 pub fn new() -> Self {
750 Self {
751 id_salt: None,
752 gap: Space::Inline,
753 row_gap: Space::Inline,
754 }
755 }
756
757 pub fn id_salt(mut self, salt: impl AsIdSalt) -> Self {
760 self.id_salt = Some(IdSalt::new(salt));
761 self
762 }
763
764 pub fn gap(mut self, gap: Space) -> Self {
766 self.gap = gap;
767 self
768 }
769
770 pub fn row_gap(mut self, gap: Space) -> Self {
772 self.row_gap = gap;
773 self
774 }
775}
776
777#[derive(Clone, Debug, Default, PartialEq)]
779struct FlowSizes(Vec<Vec2>);
780
781pub struct FlowCells<'a> {
783 ui: &'a mut Ui,
784 prev: Vec<Vec2>,
785 next: Vec<Vec2>,
786 spacing: Vec2,
787}
788
789impl std::fmt::Debug for FlowCells<'_> {
790 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
791 f.debug_struct("FlowCells")
792 .field("index", &self.next.len())
793 .finish_non_exhaustive()
794 }
795}
796
797impl FlowCells<'_> {
798 pub fn cell<R>(&mut self, add: impl FnOnce(&mut Ui) -> R) -> R {
802 let index = self.next.len();
803 let size = self.prev.get(index).copied().unwrap_or(Vec2::ZERO);
806 let spacing = self.spacing;
807 let layout = Layout::left_to_right(EguiAlign::Center);
808 let out = self.ui.allocate_ui_with_layout(size, layout, |ui| {
809 ui.spacing_mut().item_spacing = spacing;
810 ui.style_mut().wrap_mode = Some(TextWrapMode::Extend);
811 add(ui)
812 });
813 self.next.push(out.response.rect.size());
814 out.inner
815 }
816}
817
818pub(super) fn show_flow<R>(
819 ui: &mut Ui,
820 flow: Flow,
821 add: impl FnOnce(&mut FlowCells<'_>) -> R,
822) -> InnerResponse<R> {
823 let id = match flow.id_salt {
824 Some(salt) => ui.make_persistent_id(salt),
825 None => {
826 let id = ui.next_auto_id();
827 ui.skip_ahead_auto_ids(1);
828 id
829 }
830 };
831 let tokens = Tokens::of(ui.ctx());
832 let prev = ui.data(|d| d.get_temp::<FlowSizes>(id));
833 let measuring = prev.is_none();
834 let prev = prev.unwrap_or_default().0;
835 let spacing = ui.spacing().item_spacing;
836 let gaps = vec2(flow.gap.points(&tokens), flow.row_gap.points(&tokens));
837 let layout = Layout::left_to_right(EguiAlign::Center).with_main_wrap(true);
838 let initial = vec2(
842 ui.available_size_before_wrap().x,
843 ui.spacing().interact_size.y,
844 );
845 let InnerResponse { inner, response } = ui.allocate_ui_with_layout(initial, layout, |ui| {
846 ui.spacing_mut().item_spacing = gaps;
847 let mut cells = FlowCells {
848 ui,
849 prev,
850 next: Vec::new(),
851 spacing,
852 };
853 let inner = add(&mut cells);
854 let close = |a: &Vec2, b: &Vec2| (*a - *b).abs().max_elem() < 0.5;
855 let changed = cells.prev.len() != cells.next.len()
856 || cells
857 .prev
858 .iter()
859 .zip(&cells.next)
860 .any(|(a, b)| !close(a, b));
861 (inner, changed.then_some(cells.next))
862 });
863 let (inner, next) = inner;
864 if let Some(next) = next {
865 ui.data_mut(|d| d.insert_temp(id, FlowSizes(next)));
866 ui.ctx().request_discard("egui-pop flow sizes changed");
867 } else if measuring {
868 ui.data_mut(|d| d.insert_temp(id, FlowSizes::default()));
869 }
870 InnerResponse::new(inner, response)
871}
872
873#[cfg(test)]
874mod tests {
875 use super::*;
876
877 #[test]
878 fn fractions_share_what_is_left_and_respect_their_bounds() {
879 let em = 10.0;
880 let t = [Track::fr(1.0), Track::fr(3.0)];
881 assert_eq!(widths(&t, &[], 410.0, 10.0, em, false), vec![100.0, 300.0]);
882 let t = [Track::fr(1.0).min(Length::Em(20.0)), Track::fr(3.0)];
883 assert_eq!(widths(&t, &[], 410.0, 10.0, em, false), vec![200.0, 200.0]);
884 let t = [Track::fr(1.0), Track::fr(1.0).max(Length::Percent(10.0))];
885 assert_eq!(widths(&t, &[], 400.0, 0.0, em, false), vec![360.0, 40.0]);
886 let t = [
887 Track::CONTENT,
888 Track::em(5.0),
889 Track::percent(25.0),
890 Track::fr(1.0),
891 ];
892 assert_eq!(
893 widths(&t, &[30.0], 400.0, 10.0, em, false),
894 vec![30.0, 50.0, 100.0, 190.0]
895 );
896 }
897
898 #[test]
899 fn equal_widths_take_the_widest_content() {
900 let t = [Track::CONTENT; 3];
901 assert_eq!(
902 widths(&t, &[20.0, 50.0, 35.0], 400.0, 0.0, 10.0, true),
903 vec![50.0; 3]
904 );
905 }
906}