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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Constraint layout manager — positions children using anchor relationships.
//!
//! A simplified constraint-based layout that resolves spatial relationships
//! between widgets sequentially (not a full Cassowary solver). Each constraint
//! references a target widget and describes how this widget relates to it.
use super::Layout;
use crate::compat::{Any, Vec};
use crate::core::{ObjectId, Rect};
/// Describes the type of spatial relationship between two widgets.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ConstraintType {
/// Left edge of this widget aligns with left edge of target.
LeftToLeft,
/// Left edge of this widget aligns with right edge of target.
LeftToRight,
/// Right edge of this widget aligns with left edge of target.
RightToLeft,
/// Right edge of this widget aligns with right edge of target.
RightToRight,
/// Top edge of this widget aligns with top edge of target.
TopToTop,
/// Top edge of this widget aligns with bottom edge of target.
TopToBottom,
/// Bottom edge of this widget aligns with top edge of target.
BottomToTop,
/// Bottom edge of this widget aligns with bottom edge of target.
BottomToBottom,
/// Horizontal center of this widget aligns with horizontal center of target.
CenterX,
/// Vertical center of this widget aligns with vertical center of target.
CenterY,
/// Width of this widget matches target width.
Width,
/// Height of this widget matches target height.
Height,
/// Width/height ratio is enforced (width = height * ratio).
AspectRatio(f32),
}
/// A single constraint entry linking a widget to a target with an offset and multiplier.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ConstraintRef {
/// The target widget the constraint refers to.
pub target_id: ObjectId,
/// The type of constraint.
pub constraint: ConstraintType,
/// Pixel offset applied after resolving the constraint position.
pub offset: i32,
/// Scale multiplier applied to the resolved dimension.
///
/// For [`ConstraintType::Width`] and [`ConstraintType::Height`] a non-finite value
/// (`NaN`, `±∞`) is **ignored**: the constraint leaves the widget rect unchanged rather than
/// rounding the product to a degenerate size (D09-LAYOUT-03). [`ConstraintType::AspectRatio`]
/// carries its own ratio and applies the same finite-input rule.
pub multiplier: f32,
}
/// A constraint-based layout that resolves anchor relationships between widgets.
#[derive(Debug)]
pub struct ConstraintLayout {
/// All defined constraints stored as (subject_id, ConstraintRef).
constraints: Vec<(ObjectId, ConstraintRef)>,
/// The set of child widget IDs tracked by this layout.
children: Vec<ObjectId>,
}
impl ConstraintLayout {
/// Create a new empty constraint layout.
pub fn new() -> Self {
Self { constraints: Vec::new(), children: Vec::new() }
}
/// Add a constraint linking `widget_id` to `target_id`.
pub fn add_constraint(
&mut self,
widget_id: ObjectId,
target_id: ObjectId,
constraint: ConstraintType,
offset: i32,
multiplier: f32,
) {
self.constraints
.push((widget_id, ConstraintRef { target_id, constraint, offset, multiplier }));
}
/// Remove all constraints associated with the given widget.
pub fn remove_constraints(&mut self, widget_id: ObjectId) {
self.constraints.retain(|(id, _)| *id != widget_id);
}
/// Remove all constraints.
pub fn clear_constraints(&mut self) {
self.constraints.clear();
}
/// Returns all constraints.
pub fn all_constraints(&self) -> &[(ObjectId, ConstraintRef)] {
&self.constraints
}
/// Resolve the child rect given a parent rect and a set of constraint references.
///
/// The resolution is sequential: constraints referencing earlier widgets
/// must already have been resolved. Fallback to parent rect when targets
/// are not yet resolved.
fn resolve_rect(
widget_rect: &mut Rect,
constraint: &ConstraintRef,
parent_rect: Rect,
resolved: &[(ObjectId, Rect)],
) {
let target_rect = resolved
.iter()
.find(|(id, _)| *id == constraint.target_id)
.map(|(_, r)| *r)
.unwrap_or(parent_rect);
match constraint.constraint {
ConstraintType::LeftToLeft => {
widget_rect.x = target_rect.x + constraint.offset;
}
ConstraintType::LeftToRight => {
widget_rect.x =
target_rect.x.saturating_add_unsigned(target_rect.width) + constraint.offset;
}
ConstraintType::RightToLeft => {
// Align widget right edge to target LEFT edge
let left_edge = target_rect.x;
widget_rect.x =
left_edge.saturating_sub_unsigned(widget_rect.width) + constraint.offset;
}
ConstraintType::RightToRight => {
// Align widget right edge to target RIGHT edge
let right_edge = target_rect.x.saturating_add_unsigned(target_rect.width);
widget_rect.x =
right_edge.saturating_sub_unsigned(widget_rect.width) + constraint.offset;
}
ConstraintType::TopToTop => {
widget_rect.y = target_rect.y + constraint.offset;
}
ConstraintType::TopToBottom => {
widget_rect.y =
target_rect.y.saturating_add_unsigned(target_rect.height) + constraint.offset;
}
ConstraintType::BottomToTop => {
// Align widget bottom edge to target TOP edge
let top_edge = target_rect.y;
widget_rect.y =
top_edge.saturating_sub_unsigned(widget_rect.height) + constraint.offset;
}
ConstraintType::BottomToBottom => {
// Align widget bottom edge to target BOTTOM edge
let bottom_edge = target_rect.y.saturating_add_unsigned(target_rect.height);
widget_rect.y =
bottom_edge.saturating_sub_unsigned(widget_rect.height) + constraint.offset;
}
ConstraintType::CenterX => {
let target_center_x =
target_rect.x.saturating_add((target_rect.width as i32).saturating_div(2));
widget_rect.x = target_center_x
.saturating_sub((widget_rect.width as i32).saturating_div(2))
.saturating_add(constraint.offset);
}
ConstraintType::CenterY => {
let target_center_y =
target_rect.y.saturating_add((target_rect.height as i32).saturating_div(2));
widget_rect.y = target_center_y
.saturating_sub((widget_rect.height as i32).saturating_div(2))
.saturating_add(constraint.offset);
}
ConstraintType::Width => {
// D09-LAYOUT-03: a non-finite multiplier cannot describe a scale, so it is
// ignored rather than silently rounded to a degenerate size. Without this guard
// `NaN.round() as i32` becomes `0` and `±∞`/over-range products saturate to the
// `i32` bounds, either of which changes the widget geometry. This mirrors the
// `AspectRatio` branch below, which already rejects a non-finite factor
// (principle #50: degenerate input is ignored, not coerced).
if !constraint.multiplier.is_finite() {
return;
}
let w = (target_rect.width as f32 * constraint.multiplier).round() as i32;
widget_rect.width = w.max(0) as u32;
}
ConstraintType::Height => {
// D09-LAYOUT-03: same finite-multiplier policy as the `Width` branch above.
if !constraint.multiplier.is_finite() {
return;
}
let h = (target_rect.height as f32 * constraint.multiplier).round() as i32;
widget_rect.height = h.max(0) as u32;
}
ConstraintType::AspectRatio(ratio) => {
// A zero/non-finite ratio cannot describe an aspect, so it leaves the
// rect unchanged (principle #50: degenerate input is ignored).
if !(ratio.is_finite() && ratio > 0.0) {
return;
}
// Width = height * ratio, constrained to fit within widget rect.
let w = (widget_rect.height as f32 * ratio).round() as i32;
if (widget_rect.width as i32 - w).abs() > 2 {
widget_rect.width = w.max(0) as u32;
} else {
let h = (widget_rect.width as f32 / ratio).round() as i32;
widget_rect.height = h.max(0) as u32;
}
}
}
}
}
crate::impl_default_via_new!(ConstraintLayout);
impl Layout for ConstraintLayout {
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn add_widget(&mut self, widget_id: ObjectId, _stretch: u32) {
if !self.children.contains(&widget_id) {
self.children.push(widget_id);
}
}
fn remove_widget(&mut self, widget_id: ObjectId) {
self.children.retain(|id| *id != widget_id);
self.remove_constraints(widget_id);
}
fn child_ids(&self) -> Vec<ObjectId> {
self.children.clone()
}
fn has_child(&self, id: ObjectId) -> bool {
self.children.contains(&id)
}
fn clear(&mut self) {
self.children.clear();
self.constraints.clear();
}
fn update(&self, rect: Rect, widgets: &mut dyn FnMut(ObjectId, Rect)) {
if self.constraints.is_empty() {
// No constraints: just lay out children filling the parent.
for &child_id in &self.children {
widgets(child_id, rect);
}
return;
}
// Resolve constraints sequentially. Start with a default rect for each child.
// Collect only widget IDs that have constraints.
let mut resolved: Vec<(ObjectId, Rect)> = Vec::new();
// First pass: seed resolved with parent rect for each constrained child.
for &child_id in &self.children {
resolved.push((child_id, rect));
}
// Apply constraints in order. Each constraint references a target that may
// have been positioned earlier in the constraints list.
for (subject_id, constraint_ref) in &self.constraints {
if let Some(pos) = resolved.iter().position(|(id, _)| id == subject_id) {
let mut widget_rect = resolved[pos].1;
Self::resolve_rect(&mut widget_rect, constraint_ref, rect, &resolved);
resolved[pos].1 = widget_rect;
}
}
// Second pass: for children that were referenced but have no constraint
// defined, still emit them at the parent rect position.
for &child_id in &self.children {
if let Some(pos) = resolved.iter().position(|(id, _)| *id == child_id) {
// If the child has no constraints, its rect will still be the parent rect.
// Only emit if it has at least one constraint (otherwise we'd double-emit rect-sized widgets).
let has_constraint = self.constraints.iter().any(|(id, _)| *id == child_id);
if has_constraint {
widgets(child_id, resolved[pos].1);
} else {
// No constraints for this child: fill parent.
widgets(child_id, rect);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::compat::HashMap;
#[test]
fn test_left_to_left_alignment() {
let mut layout = ConstraintLayout::new();
layout.add_widget(1, 0);
layout.add_widget(2, 0);
// Widget 2 left edge aligns with widget 1 left edge, offset +10
layout.add_constraint(2, 1, ConstraintType::LeftToLeft, 10, 1.0);
let mut rects = HashMap::new();
layout.update(Rect::new(0, 0, 200, 100), &mut |id, rect| {
rects.insert(id, rect);
});
// Widget 2 x should be widget 1 x + 10 = 0 + 10 = 10
assert_eq!(rects.get(&2).map(|r| r.x), Some(10));
}
#[test]
fn test_left_to_right_places_beside() {
let mut layout = ConstraintLayout::new();
layout.add_widget(1, 0);
layout.add_widget(2, 0);
layout.add_constraint(1, 2, ConstraintType::LeftToLeft, 0, 1.0);
// Child 1 at x=0, width=200 (parent rect). Child 2 at x=child1.right + 10
// Remove constraint on 1 and add a proper one
layout.remove_constraints(1);
layout.add_constraint(1, 2, ConstraintType::LeftToRight, 10, 1.0);
let mut rects = HashMap::new();
layout.update(Rect::new(5, 0, 200, 100), &mut |id, rect| {
rects.insert(id, rect);
});
// Widget 1 left = widget 2.right + 10. Since widget 2 has no constraint,
// widget 2 fills parent at x=5, width=200. So widget 2 right = 205.
// Widget 1 x = 205 + 10 = 215.
// But widget 2 without constraint gets parent rect (5, 0, 200, 100), so right = 205.
assert_eq!(rects.get(&1).map(|r| r.x), Some(215));
}
#[test]
fn test_center_x_alignment() {
let mut layout = ConstraintLayout::new();
layout.add_widget(1, 0);
layout.add_widget(2, 0);
// Widget 2 center aligns with widget 1 center.
// Widget 1 is at parent rect (0,0,200,100), center x = 100.
// Widget 2 has width = 200 (parent), center x = 200/2 = 100, so x stays 0.
layout.add_constraint(2, 1, ConstraintType::CenterX, 0, 1.0);
let mut rects = HashMap::new();
layout.update(Rect::new(0, 0, 200, 100), &mut |id, rect| {
rects.insert(id, rect);
});
// Widget 2 center = widget 1 center = 100. Widget 2 x = 100 - 100 = 0.
assert_eq!(rects.get(&2).map(|r| r.x), Some(0));
}
#[test]
fn test_top_to_bottom() {
let mut layout = ConstraintLayout::new();
layout.add_widget(1, 0);
layout.add_widget(2, 0);
// Widget 2 top aligns with widget 1 bottom.
layout.add_constraint(2, 1, ConstraintType::TopToBottom, 5, 1.0);
let mut rects = HashMap::new();
layout.update(Rect::new(0, 0, 200, 100), &mut |id, rect| {
rects.insert(id, rect);
});
// Widget 1 is at (0,0,200,100) (parent rect). Widget 2 y = 100 + 5 = 105.
assert_eq!(rects.get(&2).map(|r| r.y), Some(105));
}
#[test]
fn test_remove_constraints_clears_relationship() {
let mut layout = ConstraintLayout::new();
layout.add_widget(1, 0);
layout.add_widget(2, 0);
layout.add_constraint(2, 1, ConstraintType::LeftToRight, 0, 1.0);
layout.remove_constraints(2);
assert!(layout.all_constraints().is_empty());
}
#[test]
fn test_width_aspect_ratio_constraint() {
let mut layout = ConstraintLayout::new();
layout.add_widget(1, 0);
// Widget 1 has aspect ratio 2.0 (width = height * 2).
// In parent rect (0,0,200,100), width=200, height=100.
// Aspect ratio = 2.0, current ratio = 200/100 = 2.0, no change.
layout.add_constraint(1, 1, ConstraintType::AspectRatio(2.0), 0, 1.0);
let mut rects = HashMap::new();
layout.update(Rect::new(0, 0, 200, 100), &mut |id, rect| {
rects.insert(id, rect);
});
// width = height * 2 = 100 * 2 = 200, height stays 100.
assert_eq!(rects.get(&1).map(|r| r.width), Some(200));
assert_eq!(rects.get(&1).map(|r| r.height), Some(100));
}
#[test]
fn test_clear_removes_all_children_and_constraints() {
let mut layout = ConstraintLayout::new();
layout.add_widget(1, 0);
layout.add_widget(2, 0);
layout.add_constraint(2, 1, ConstraintType::LeftToRight, 0, 1.0);
layout.clear();
assert!(layout.child_ids().is_empty());
assert!(layout.all_constraints().is_empty());
}
#[test]
fn test_has_child_and_remove_widget() {
let mut layout = ConstraintLayout::new();
layout.add_widget(42, 0);
assert!(layout.has_child(42));
layout.remove_widget(42);
assert!(!layout.has_child(42));
}
// ── D09-LAYOUT-03: Width/Height multiplier must be finite ──
/// Runs a `Width` constraint with the given multiplier and returns the resolved width for
/// widget `1`, whose target shares the same parent rect. The parent is 200x100, so a valid
/// multiplier of `1.0` leaves the width at 200.
fn width_for(multiplier: f32) -> u32 {
let mut layout = ConstraintLayout::new();
layout.add_widget(1, 0);
layout.add_constraint(1, 1, ConstraintType::Width, 0, multiplier);
let mut rects = HashMap::new();
layout.update(Rect::new(0, 0, 200, 100), &mut |id, rect| {
rects.insert(id, rect);
});
rects.get(&1).map(|r| r.width).expect("widget placed")
}
/// Runs a `Height` constraint with the given multiplier; a valid `1.0` leaves the height at
/// the parent's 100.
fn height_for(multiplier: f32) -> u32 {
let mut layout = ConstraintLayout::new();
layout.add_widget(1, 0);
layout.add_constraint(1, 1, ConstraintType::Height, 0, multiplier);
let mut rects = HashMap::new();
layout.update(Rect::new(0, 0, 200, 100), &mut |id, rect| {
rects.insert(id, rect);
});
rects.get(&1).map(|r| r.height).expect("widget placed")
}
/// A non-finite multiplier must not silently shrink the widget to zero (NaN) or saturate it
/// to an extreme size (∞); the constraint is ignored and the rect keeps the parent size.
#[test]
fn width_non_finite_multiplier_is_ignored() {
assert_eq!(width_for(f32::NAN), 200, "NaN must be ignored, not rounded to 0");
assert_eq!(width_for(f32::INFINITY), 200, "+∞ must be ignored, not saturated");
assert_eq!(width_for(f32::NEG_INFINITY), 200, "-∞ must be ignored, not saturated");
}
/// The `Height` branch shares the finite-multiplier policy (D09-LAYOUT-03).
#[test]
fn height_non_finite_multiplier_is_ignored() {
assert_eq!(height_for(f32::NAN), 100, "NaN must be ignored, not rounded to 0");
assert_eq!(height_for(f32::INFINITY), 100, "+∞ must be ignored, not saturated");
assert_eq!(height_for(f32::NEG_INFINITY), 100, "-∞ must be ignored, not saturated");
}
/// Normal and huge-but-finite multipliers still scale the dimension, clamped at the `i32`
/// boundary rather than wrapping to a negative width (D09-LAYOUT-03).
#[test]
fn width_finite_multipliers_scale_within_bounds() {
assert_eq!(width_for(1.0), 200, "1.0 leaves the width unchanged");
assert_eq!(width_for(0.5), 100, "0.5 halves the width");
assert_eq!(width_for(0.0), 0, "0.0 collapses the width to zero, not negative");
// A huge finite multiplier overflows `i32` when rounded; the non-negative clamp keeps it
// from wrapping into a negative width that casts back to an enormous `u32`.
let huge = width_for(f32::MAX);
assert!(huge <= i32::MAX as u32, "a huge multiplier must saturate, not wrap: {huge}");
}
/// The `Height` branch scales finite multipliers identically.
#[test]
fn height_finite_multipliers_scale_within_bounds() {
assert_eq!(height_for(1.0), 100);
assert_eq!(height_for(0.5), 50);
assert_eq!(height_for(0.0), 0);
let huge = height_for(f32::MAX);
assert!(huge <= i32::MAX as u32, "a huge multiplier must saturate, not wrap: {huge}");
}
}