1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Flex layout widgets: `FlexColumn` (vertical) and `FlexRow` (horizontal).
//!
//! # Y-up layout convention
//!
//! `FlexColumn` stacks children **top to bottom** visually, which in Y-up
//! coordinates means the *first* child gets the *highest* Y values. The layout
//! cursor starts at the top of the available area and moves downward.
//!
//! `FlexRow` stacks children **left to right**, as expected.
//!
//! # Flex algorithm
//!
//! Each child has a `flex` factor (stored in a parallel `Vec<f64>`):
//! - `flex = 0.0` → "fixed": the child is laid out at its natural size on
//! the main axis.
//! - `flex > 0.0` → "growing": the child receives a proportional share of
//! the remaining space after all fixed children are measured.
//!
//! Children with equal `flex` values split remaining space equally.
//!
//! # Child margin support
//!
//! Each child's `margin()` (logical units — DPI is applied once at the App
//! paint boundary) contributes to the slot size on the main axis and is
//! respected for cross-axis placement.
//! Margins are **additive** — child A's `margin.top` and child B's
//! `margin.bottom` both contribute gap space between those children (in
//! addition to `self.gap`).
//!
//! # Cross-axis anchoring
//!
//! `FlexColumn` reads each child's `h_anchor()` to place it horizontally
//! within the column's inner width. `FlexRow` reads `v_anchor()` to place
//! children vertically within the row's inner height.
use crate::color::Color;
use crate::draw_ctx::DrawCtx;
use crate::event::{Event, EventResult};
use crate::geometry::{Rect, Size};
use crate::layout_props::{resolve_fit_or_stretch, HAnchor, Insets, VAnchor, WidgetBase};
use crate::widget::Widget;
// ---------------------------------------------------------------------------
// Cross-axis placement helpers
// ---------------------------------------------------------------------------
/// Compute `(x, actual_width)` for a child in a `FlexColumn` (horizontal
/// cross-axis placement).
///
/// - `pad_l` — column's left inner-padding offset.
/// - `inner_w` — column's usable width (after padding, before margins).
/// - `margin_l/r` — child's left/right margins (logical units).
/// - `natural_w` — width returned by `child.layout()`.
/// - `min_w/max_w` — child's min/max width constraints.
fn place_cross_h(
anchor: HAnchor,
pad_l: f64,
inner_w: f64,
margin_l: f64,
margin_r: f64,
natural_w: f64,
min_w: f64,
max_w: f64,
) -> (f64, f64) {
let slot_w = (inner_w - margin_l - margin_r).max(0.0);
// Determine width.
let actual_w = if anchor.is_stretch() {
// LEFT | RIGHT → fill slot
slot_w.clamp(min_w, max_w)
} else if anchor == HAnchor::MAX_FIT_OR_STRETCH {
resolve_fit_or_stretch(natural_w, slot_w, true).clamp(min_w, max_w)
} else if anchor == HAnchor::MIN_FIT_OR_STRETCH {
resolve_fit_or_stretch(natural_w, slot_w, false).clamp(min_w, max_w)
} else {
// FIT, LEFT, RIGHT, CENTER, ABSOLUTE — use natural width.
natural_w.clamp(min_w, max_w)
};
// Determine x position.
let x = if anchor.contains(HAnchor::RIGHT) && !anchor.contains(HAnchor::LEFT) {
// RIGHT only (not stretch): right-align within margin slot.
(pad_l + inner_w - margin_r - actual_w).max(pad_l)
} else if anchor.contains(HAnchor::CENTER) && !anchor.is_stretch() {
// CENTER: center within margin slot.
pad_l + margin_l + (slot_w - actual_w) * 0.5
} else {
// LEFT, STRETCH, FIT, ABSOLUTE, MIN/MAX_FIT_OR_STRETCH — left-align.
pad_l + margin_l
};
(x, actual_w)
}
// ---------------------------------------------------------------------------
// FlexColumn
// ---------------------------------------------------------------------------
/// Stacks children top-to-bottom (first child = visually topmost).
pub struct FlexColumn {
bounds: Rect,
children: Vec<Box<dyn Widget>>,
/// Parallel to `children`. 0.0 = fixed; >0 = flex fraction.
flex_factors: Vec<f64>,
base: WidgetBase,
pub gap: f64,
pub inner_padding: Insets,
pub background: Color,
/// When `true`, paint background using `ctx.visuals().panel_fill`
/// regardless of the stored `background` colour.
pub use_panel_bg: bool,
/// When `true`, `layout` reports the column's natural content
/// width (max over children, + horizontal padding) instead of the
/// full `available.width`. Used by auto-sized ancestors that
/// want the column to shrink-to-content rather than stretch.
/// Off by default for backward compatibility.
pub fit_width: bool,
/// When `true`, children are anchored to the TOP of the column's
/// inner area, with any extra height appearing as whitespace at
/// the BOTTOM. Off by default — legacy callers (e.g. ScrollView
/// content) rely on the natural-anchored layout where children
/// occupy the BOTTOM of their slot when oversized.
pub top_anchor: bool,
}
impl FlexColumn {
pub fn new() -> Self {
Self {
bounds: Rect::default(),
children: Vec::new(),
flex_factors: Vec::new(),
base: WidgetBase::new(),
gap: 0.0,
inner_padding: Insets::ZERO,
background: Color::rgba(0.0, 0.0, 0.0, 0.0),
use_panel_bg: false,
fit_width: false,
top_anchor: false,
}
}
pub fn with_gap(mut self, gap: f64) -> Self {
self.gap = gap;
self
}
pub fn with_padding(mut self, p: f64) -> Self {
self.inner_padding = Insets::all(p);
self
}
pub fn with_inner_padding(mut self, p: Insets) -> Self {
self.inner_padding = p;
self
}
pub fn with_background(mut self, c: Color) -> Self {
self.background = c;
self
}
/// Use `ctx.visuals().panel_fill` as background instead of the stored color.
pub fn with_panel_bg(mut self) -> Self {
self.use_panel_bg = true;
self
}
/// Opt into content-fit width — `layout` reports the widest
/// child's natural width (+ horizontal padding) instead of the
/// full available width. Required when this column is the
/// content of an auto-sized `Window`; without it, wrapped Labels
/// claim the full available width and the window grows to the
/// canvas. Matches egui's per-column shrink-to-content option.
pub fn with_fit_width(mut self, fit: bool) -> Self {
self.fit_width = fit;
self
}
/// Anchor children to the TOP of the inner area rather than the
/// bottom of the natural content extent. Default is bottom (the
/// classic Y-up "natural-anchored" placement) so callers like
/// `ScrollView` whose layout pass uses `available.height ≈ ∞`
/// keep working — they need cursor_y to be derived from natural
/// extent, not from the supplied (huge) available. Opt in for
/// containers placed inside a `Resize` widget or other oversized
/// slot where you want the visible content to start at the top
/// of the frame and any extra space to appear below.
pub fn with_top_anchor(mut self, on: bool) -> Self {
self.top_anchor = on;
self
}
pub fn with_margin(mut self, m: Insets) -> Self {
self.base.margin = m;
self
}
pub fn with_h_anchor(mut self, h: HAnchor) -> Self {
self.base.h_anchor = h;
self
}
pub fn with_v_anchor(mut self, v: VAnchor) -> Self {
self.base.v_anchor = v;
self
}
pub fn with_min_size(mut self, s: Size) -> Self {
self.base.min_size = s;
self
}
pub fn with_max_size(mut self, s: Size) -> Self {
self.base.max_size = s;
self
}
/// Add a fixed-size child (flex = 0).
pub fn add(mut self, child: Box<dyn Widget>) -> Self {
self.children.push(child);
self.flex_factors.push(0.0);
self
}
/// Add a flex child that expands proportionally.
pub fn add_flex(mut self, child: Box<dyn Widget>, flex: f64) -> Self {
self.children.push(child);
self.flex_factors.push(flex.max(0.0));
self
}
/// Push a child directly (for use without builder chaining).
pub fn push(&mut self, child: Box<dyn Widget>, flex: f64) {
self.children.push(child);
self.flex_factors.push(flex.max(0.0));
}
}
impl Default for FlexColumn {
fn default() -> Self {
Self::new()
}
}
impl Widget for FlexColumn {
fn type_name(&self) -> &'static str {
"FlexColumn"
}
fn bounds(&self) -> Rect {
self.bounds
}
fn set_bounds(&mut self, b: Rect) {
self.bounds = b;
}
fn children(&self) -> &[Box<dyn Widget>] {
&self.children
}
fn children_mut(&mut self) -> &mut Vec<Box<dyn Widget>> {
&mut self.children
}
fn margin(&self) -> Insets {
self.base.margin
}
fn widget_base(&self) -> Option<&WidgetBase> {
Some(&self.base)
}
fn widget_base_mut(&mut self) -> Option<&mut WidgetBase> {
Some(&mut self.base)
}
fn padding(&self) -> Insets {
self.inner_padding
}
fn h_anchor(&self) -> HAnchor {
self.base.h_anchor
}
fn v_anchor(&self) -> VAnchor {
self.base.v_anchor
}
fn min_size(&self) -> Size {
self.base.min_size
}
fn max_size(&self) -> Size {
self.base.max_size
}
fn measure_min_height(&self, available_w: f64) -> f64 {
// Sum each child's required height (recursing through any
// FlexColumn / TextArea / Container chains) plus our own
// padding and inter-child gaps. Used by ancestor
// `Window::tight_content_fit` to compute a content-bound
// height even when one of our children is a flex-fill widget
// whose `layout` would just return the available slot.
let pad_l = self.inner_padding.left;
let pad_r = self.inner_padding.right;
let pad_t = self.inner_padding.top;
let pad_b = self.inner_padding.bottom;
let inner_w = (available_w - pad_l - pad_r).max(0.0);
let mut total = 0.0_f64;
let mut visible_n = 0_usize;
for child in self.children.iter() {
// Hidden slots (collapsed `Conditional`s, self-hiding widgets)
// consume no height, margin, or gap.
if !child.is_visible() {
continue;
}
visible_n += 1;
let m = child.margin();
let slot_w = (inner_w - m.left - m.right).max(0.0);
total += child.measure_min_height(slot_w) + m.vertical();
}
total += pad_t + pad_b;
if visible_n > 1 {
total += self.gap * (visible_n - 1) as f64;
}
total.max(self.base.min_size.height)
}
fn layout(&mut self, available: Size) -> Size {
let pad_l = self.inner_padding.left;
let pad_r = self.inner_padding.right;
let pad_t = self.inner_padding.top;
let pad_b = self.inner_padding.bottom;
let gap = self.gap;
let n = self.children.len();
if n == 0 {
return available;
}
let inner_w = (available.width - pad_l - pad_r).max(0.0);
let inner_h = (available.height - pad_t - pad_b).max(0.0);
// Child margins (logical units end-to-end; DPI applied at paint).
let margins: Vec<Insets> = self.children.iter().map(|c| c.margin()).collect();
// -------------------------------------------------------------------
// Step 1: measure fixed children on the main (vertical) axis.
//
// The slot for each fixed child = content_h + margin_top + margin_bottom.
// Flex children contribute only their margins to the space budget.
// -------------------------------------------------------------------
let mut content_heights = vec![0.0f64; n];
let mut natural_widths = vec![0.0f64; n];
let mut total_fixed_with_margins = 0.0f64;
let mut total_flex = 0.0f64;
let mut total_flex_margin_v = 0.0f64;
let mut max_child_natural_w = 0.0f64;
for i in 0..n {
if self.flex_factors[i] == 0.0 {
let m = &margins[i];
let slot_w = (inner_w - m.left - m.right).max(0.0);
// Measure at natural height; pass inner_h as the available
// height so the child can self-report its natural size.
let desired = self.children[i].layout(Size::new(slot_w, inner_h));
content_heights[i] = desired.height.clamp(
self.children[i].min_size().height,
self.children[i].max_size().height,
);
natural_widths[i] = desired.width;
}
}
// Visibility is read AFTER measuring: a child that hides itself
// (collapsed `Conditional`, a results list with no rows) reports
// `is_visible() == false` from its fresh layout state and consumes
// no slot, margin, or gap — the contract documented on
// [`crate::widgets::Conditional`]. Without this, every hidden slot
// leaves `gap` px of dead space in the flow.
let visible: Vec<bool> = self.children.iter().map(|c| c.is_visible()).collect();
let visible_n = visible.iter().filter(|v| **v).count();
let total_gap = if visible_n > 1 {
gap * (visible_n - 1) as f64
} else {
0.0
};
for i in 0..n {
if !visible[i] {
continue;
}
let m = &margins[i];
if self.flex_factors[i] == 0.0 {
total_fixed_with_margins += content_heights[i] + m.vertical();
max_child_natural_w = max_child_natural_w.max(natural_widths[i] + m.horizontal());
} else {
total_flex += self.flex_factors[i];
total_flex_margin_v += m.vertical();
}
}
// -------------------------------------------------------------------
// Step 2: distribute remaining space to flex children.
// -------------------------------------------------------------------
let remaining =
(inner_h - total_fixed_with_margins - total_gap - total_flex_margin_v).max(0.0);
let flex_unit = if total_flex > 0.0 {
remaining / total_flex
} else {
0.0
};
for i in 0..n {
if self.flex_factors[i] > 0.0 && visible[i] {
let raw = self.flex_factors[i] * flex_unit;
content_heights[i] = raw.clamp(
self.children[i].min_size().height,
self.children[i].max_size().height,
);
}
}
// Natural content height (all-fixed case) determines the column's
// reported size when there are no flex children.
let natural_content_h = total_fixed_with_margins + total_gap;
let effective_h = if total_flex > 0.0 {
inner_h
} else {
natural_content_h
};
// -------------------------------------------------------------------
// Step 3: place children top-to-bottom.
//
// In Y-up coordinates "top" = high Y. Two cursor seeds:
//
// - **Default**: start at the top of the finite inner area,
// matching egui's top-down layout. When a parent passes a
// deliberately huge height to measure natural content (the
// `ScrollView` path), fall back to the natural-content extent
// so children keep finite y-coordinates.
//
// - **`top_anchor=true`**: always start at the top of the inner
// area, even for very tall measurement slots.
let measuring_natural_height = available.height > 1.0e9;
let mut cursor_y = if self.top_anchor || !measuring_natural_height {
available.height - pad_t
} else {
pad_b + effective_h
};
for i in 0..n {
let m = &margins[i];
let slot_w = (inner_w - m.left - m.right).max(0.0);
let content_h = content_heights[i];
if !visible[i] {
// Hidden slot: zero-size bounds at the cursor, no margins,
// no gap, no cursor advance — as if the child weren't there.
self.children[i].set_bounds(Rect::new(pad_l + m.left, cursor_y, 0.0, 0.0));
continue;
}
// Subtract top margin first (moves cursor toward lower Y = downward).
cursor_y -= m.top;
let child_bottom = cursor_y - content_h;
// Layout child to obtain its natural width for cross-axis placement.
let desired = self.children[i].layout(Size::new(slot_w, content_h));
let natural_w = desired.width;
let h_anchor = self.children[i].h_anchor();
let min_w = self.children[i].min_size().width;
let max_w = self.children[i].max_size().width;
let (child_x, child_w) = place_cross_h(
h_anchor, pad_l, inner_w, m.left, m.right, natural_w, min_w, max_w,
);
// Round to integers so bitmap content (cached text, images) lands on
// exact pixel boundaries and isn't sub-pixel sampled into blur.
self.children[i].set_bounds(Rect::new(
child_x.round(),
child_bottom.round(),
child_w.round(),
content_h.round(),
));
// Advance cursor past bottom margin and inter-child gap.
cursor_y = child_bottom - m.bottom - gap;
}
// Return natural size for all-fixed layouts so ScrollView can read
// the true content height from layout()'s return value.
//
// Width: by default we report the full available width (legacy
// behaviour many callers rely on). `fit_width(true)` opts in
// to reporting the widest non-flex child's natural width +
// padding — NOT clamped to `available.width` so the parent
// (typically an auto-sized `Window`) can grow to fit content
// that exceeds the current slot.
let reported_w = if self.fit_width {
max_child_natural_w + pad_l + pad_r
} else {
available.width
};
if total_flex > 0.0 {
Size::new(reported_w, available.height)
} else {
Size::new(reported_w, natural_content_h + pad_t + pad_b)
}
}
fn paint(&mut self, ctx: &mut dyn DrawCtx) {
let bg = if self.use_panel_bg {
Some(ctx.visuals().panel_fill)
} else if self.background.a > 0.001 {
Some(self.background)
} else {
None
};
if let Some(color) = bg {
let w = self.bounds.width;
let h = self.bounds.height;
ctx.set_fill_color(color);
ctx.begin_path();
ctx.rect(0.0, 0.0, w, h);
ctx.fill();
}
}
fn on_event(&mut self, _: &Event) -> EventResult {
EventResult::Ignored
}
}