feat: allocate weighted flex space and remeasure affected occurrences
Verify Tessera GUI / verify (push) Failing after 7m59s

This commit is contained in:
2026-10-22 22:01:28 +08:00
parent 0c1cc12b6b
commit 78fb66277d
12 changed files with 202 additions and 18 deletions
+3 -1
View File
@@ -262,7 +262,7 @@ Native TextBlock measurement now uses the occurrence's maximum width, with word
Native TextBlock painting carries its allocated width/height into the immutable frame and clips glyphs to those bounds as well as any enclosing scroll clip. Measurement and drawing use the same font/shaping implementation; drawing shapes at the device font size. Zero-width or zero-height paint bounds draw nothing. Management UI text keeps its existing single-line/explicit-newline behavior.
Source `PaintCommand` text may supply both `wrapWidth` and `wrapHeight` as finite nonnegative logical dimensions up to 1000000. Omitting both preserves unwrapped text; supplying only one is rejected. `TextBlock.paint` returns these fields, so a source override can preserve or explicitly change the boundary. Changing paint bounds does not renegotiate layout: source arrange supplies child Bounds and changed dimensions participate in the layout solve. Row's unbounded main-axis policy and flex allocation remain pending. ScrollBlock's axis policy now controls cross-axis wrapping and scrolling. Fractional-DPI wrap boundaries need broader platform validation.
Source `PaintCommand` text may supply both `wrapWidth` and `wrapHeight` as finite nonnegative logical dimensions up to 1000000. Omitting both preserves unwrapped text; supplying only one is rejected. `TextBlock.paint` returns these fields, so a source override can preserve or explicitly change the boundary. Changing paint bounds does not renegotiate layout: source arrange supplies child Bounds and changed dimensions participate in the layout solve. General flex basis/min/max and fixed-child shrinking remain pending. ScrollBlock's axis policy now controls cross-axis wrapping and scrolling. Fractional-DPI wrap boundaries need broader platform validation.
A source subclass can override `paint(self, mount, geometry): DisplayList`. The renderer invokes that method for each occurrence, after Mount synchronization and hooks, using current logical Bounds. Its commands replace that occurrence's native paint in preorder. Calling `RectBlock.paint(self, mount, geometry)` or another native base method obtains a fresh result that can be modified before returning. `DisplayList(ObjectList(command, ...))` builds multiple commands; ObjectList accepts objects and has a 10000-member bound. PaintCommand fields use kind (`roundedRect`, `strokeRoundedRect` or `text`), x/y/color and the corresponding width/height/radius, strokeWidth, or text/size fields. Commands must pass the same native validation and a total 10000-command frame limit. See [source-paint.endor](examples/source-paint.endor), including a Button source method that updates the same tint field used by two occurrences.
@@ -489,3 +489,5 @@ Block.click returns the generated Event and Block.dispatch returns the delivered
Event dispatch/click and lifecycle entry points publish External as their allowed effect bound: handlers may mutate application state or use host I/O APIs. The built-in no-op bodies do not make the overridable handler contract ReadOnly. These entry points still reject invocation inside read-only rendering.
ContainerBlock.mainAlign is a managed attribute with start (default), center, end and space-between policies. It positions children in the allocated main-axis space after padding and the configured minimum gap. Center/end use remaining positive space; space-between adds it between two or more children. Overflow keeps start positions and existing sizes; alignment does not imply flex sizing. Native arrange queries and rendering use the same actual Bounds. Source arrange overrides retain their explicit placements.
Block.flex is a nonnegative managed weight, default 0. In native containers, fixed children retain measured main-axis sizes; positive weights share the remaining allocated space after padding/gaps with zero basis. This does not request extra parent size. Actual allocated child bounds feed back into measurement before publication. Source arrangement overrides remain authoritative. General flex basis/min/max and fixed-child shrinking are not implemented yet. See [flex.endor](examples/flex.endor) for shared text reflow and native button updates.
+19
View File
@@ -0,0 +1,19 @@
class Actions {
filler: RectBlock
function balanced(self: Actions): Unit { self.filler.flex = 1 }
function narrow(self: Actions): Unit { self.filler.flex = 3 }
}
paragraph = TextBlock("GUI 和代码操控同一套 Aster 内存对象系统。对象只有一份,但每次挂载都有自己的约束和布局。这里用同一个 TextBlock 在两个容器中显示不同的换行。修改权重会重新测量文字高度,随后更新相邻布局。GUI 和代码操控同一套 Aster 内存对象系统。对象只有一份,但每次挂载都有自己的约束和布局。这里用同一个 TextBlock 在两个容器中显示不同的换行。修改权重会重新测量文字高度,随后更新相邻布局。")
paragraph.flex = 1
filler = RectBlock(20, 20)
filler.flex = 1
actions = Actions(filler)
balanced = Button("等比例分配")
balanced.onClick(actions.balanced)
narrow = Button("文字只占四分之一")
narrow.onClick(actions.narrow)
first = Row(10, 10, paragraph, filler)
second = Row(10, 10, paragraph, RectBlock(300, 20))
page = Page()
page.title = "按权重分配与文字重排"
page.render(Column(10, 10, Row(0, 10, balanced, narrow), first, second))
+4
View File
@@ -139,3 +139,7 @@ Layout convergence uses exact finite snapshots of constraints/sizes/bounds and s
ScrollBlock.axis is stored in its managed properties and projected into the visual snapshot. Axis-aware child constraints use constructor/clamped size for initial measurement and actual occurrence bounds after arrangement. Scroll projection clamps disabled offsets/limits; the same geometry feeds paint and input.
Container mainAlign projects from managed properties into UiNode and its shallow equality. Native arrangement receives the actual allocated Size, computes positive remaining main-axis space and keeps child sizes unchanged.
Block.flex is a nonnegative managed weight, default 0. In native containers, fixed children retain measured main-axis sizes; positive weights share the remaining allocated space after padding/gaps with zero basis. This does not request extra parent size. Actual allocated child bounds feed back into measurement before publication. Source arrangement overrides remain authoritative. General flex basis/min/max and fixed-child shrinking are not implemented yet.
Trees with positive flex weights use the settling driver even when all layout methods are native. This remeasures wrapping and ancestor geometry before publishing. Fast-path eligibility checks actual intrinsic implementations, rather than comparing against a mutable Block method table.
+3 -1
View File
@@ -1087,7 +1087,7 @@ Source measure and arrange overrides execute bottom-up and top-down in one read-
Source layout solves repeat in one read-only call until constraints/sizes/bounds are unchanged, reusing one bytecode frame. Source-arranged changed dimensions become exact per-axis constraints for this solve; source container measurements differing from native results constrain content using the same container policy. Selected limits reset on later inputs/resizes. Nonconsecutive repeated states report a cycle. No fixed pass/hop cutoff is used; all passes share the 1000000-instruction/128-frame budget and budget failure is explicit. Measurement clears provisional Mount geometry, and only complete settled frames publish. ui.stats().layoutPasses reports work; source/cache counters include all passes. VM annotation checks distinguish validation-only from content reads, preserving Mount-typed independent measurement caching; actual Mount reads still bypass conservatively. General flex allocation and resumable solving remain pending. See examples/layout-negotiation.endor.
TextBlock now wraps words/glyphs at its available width and measures the resulting height. Native and source-base measurement paths use current constraints; native shape/font caches include wrap width. Painting carries allocated width/height, clips glyphs and keeps ancestor scroll clipping. Source text PaintCommand may supply both wrapWidth/wrapHeight (finite nonnegative logical dimensions up to 1000000); neither preserves legacy unwrapped paint, and a partial pair is rejected. Native TextBlock.paint supplies the pair. These are derived draw bounds, not another business object. Management UI text remains unwrapped. General flex allocation, resumable solving and vertical-only scrolling policy and broad fractional-DPI validation remain pending. See examples/wrapped-text.endor.
TextBlock now wraps words/glyphs at its available width and measures the resulting height. Native and source-base measurement paths use current constraints; native shape/font caches include wrap width. Painting carries allocated width/height, clips glyphs and keeps ancestor scroll clipping. Source text PaintCommand may supply both wrapWidth/wrapHeight (finite nonnegative logical dimensions up to 1000000); neither preserves legacy unwrapped paint, and a partial pair is rejected. Native TextBlock.paint supplies the pair. These are derived draw bounds, not another business object. Management UI text remains unwrapped. General flex basis/min/max, fixed-child shrinking, resumable solving and broad fractional-DPI validation remain pending. See examples/wrapped-text.endor.
Source paint overrides execute in the actual frame pipeline under a read-only heap policy. Source hitTest overrides similarly refine native pointer targets in VM paint order; Point.inside(bounds) and Point.inCircle(cx, cy, radius) provide primitive shape queries. Managed DisplayList/ObjectList/PaintCommand and Constraints/Bounds/Point results are ordinary runtime objects.
@@ -1119,6 +1119,8 @@ ScrollBlock.axis is a managed visual attribute: "both" (default), "vertical" or
ContainerBlock.mainAlign accepts "start" (default), "center", "end" or "space-between". Native arrangement uses allocated Bounds after padding/minimum gap, distributes positive remaining main-axis space and keeps child sizes unchanged. Overflow keeps start placement. Explicit source arrange placements remain authoritative; this is alignment, not flex sizing.
Block.flex is a nonnegative weight (default 0). Native containers reserve fixed measured children, padding and gaps, then share remaining allocated main-axis space between positive weights with zero basis. Actual child allocation feeds remeasurement. It does not request parent expansion or implement general flex basis/min/max/fixed-child shrinking.
## UI host object
Positional arguments only:
+7 -1
View File
@@ -117,6 +117,7 @@ pub struct Data {
pub children: Vec<Child>,
pub padding: f32,
pub gap: f32,
pub flex: f32,
pub main_align: crate::layout::MainAlign,
pub scroll_axis: crate::scroll::Axis,
pub next_slot: u64,
@@ -144,6 +145,7 @@ impl Data {
.collect(),
padding,
gap,
flex: 0.0,
main_align: crate::layout::MainAlign::Start,
scroll_axis: crate::scroll::Axis::Both,
next_slot,
@@ -315,7 +317,7 @@ pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
fn number(value: f32) -> Value {
Value::Number((value as f64).into())
}
let mut fields = vec![];
let mut fields = vec![("flex", number(data.flex))];
match &data.kind {
Kind::Text { value, size, color } => fields.extend([
("text", Value::Text(value.clone())),
@@ -375,6 +377,10 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
}
Ok(n)
};
if name == "flex" {
data.flex = number()?;
return Ok(());
}
let container = data.is_container();
if container && name == "mainAlign" {
let Value::Text(value) = value else {
+87
View File
@@ -3889,6 +3889,93 @@ page.render(block)
);
}
#[test]
fn native_flex_reflows_shared_text_per_occurrence() {
let (mut session, initial) = ReplSession::load(
r#"
paragraph = TextBlock("Shared text has one object identity and separate layout constraints in each occurrence. Changing the sibling weight reflows only the affected occurrence.")
paragraph.flex = 1
filler = RectBlock(20, 20)
filler.flex = 1
first = Row(10, 10, paragraph, filler)
second = Row(10, 10, paragraph, RectBlock(300, 20))
page = Page()
page.render(Column(10, 10, first, second))
"#,
"app.main",
266,
1,
)
.unwrap();
initial.validate().unwrap();
let height = |session: &mut ReplSession, index| -> f32 {
session
.execute(
&format!("paragraph.mounts().at({index}).bounds().height"),
"app.main",
)
.unwrap()
.value
.parse()
.unwrap()
};
let before = height(&mut session, 0);
let other = height(&mut session, 1);
assert!(before > other);
session.execute("filler.flex = 3", "app.main").unwrap();
assert!(height(&mut session, 0) > before);
assert_eq!(height(&mut session, 1), other);
}
#[test]
fn weighted_flex_remeasures_children_and_updates_live_weights() {
let (mut session, initial) = ReplSession::load(r#"
class Wide: Row {
function measure(self: Wide, mount: Mount, constraints: Constraints): MeasureResult { return MeasureResult(340, 40) }
}
first = RectBlock(20, 20)
fixed = RectBlock(60, 20)
last = RectBlock(40, 20)
first.flex = 1
last.flex = 2
row = Wide(10, 10, first, fixed, last)
page = Page()
page.render(row)
"#, "app.main", 265, 1).unwrap();
initial.validate().unwrap();
assert_eq!(
session
.execute("first.mounts().at(0).bounds().width", "app.main")
.unwrap()
.value,
"80"
);
assert_eq!(
session
.execute("last.mounts().at(0).bounds().width", "app.main")
.unwrap()
.value,
"160"
);
session
.execute("first.flex = 3\nlast.flex = 1", "app.main")
.unwrap();
assert_eq!(
session
.execute("first.mounts().at(0).bounds().width", "app.main")
.unwrap()
.value,
"180"
);
assert_eq!(
session
.execute("last.mounts().at(0).bounds().width", "app.main")
.unwrap()
.value,
"60"
);
}
#[test]
fn main_alignment_updates_live_geometry_without_changing_sizes() {
let (mut session, initial) = ReplSession::load(r#"
+53
View File
@@ -260,6 +260,54 @@ pub fn paint_native(node: &UiNode, x: f32, y: f32, size: Size) -> Option<RenderC
}
}
/// Zero-basis weighted allocation within the space actually assigned to a
/// native container. Fixed children keep their measured sizes.
pub fn flex_sizes(node: &UiNode, bounds: Size, children: &[Size]) -> Vec<Size> {
let Some((row, padding, gap)) = container(node) else {
return children.to_vec();
};
let flexible: Vec<_> = node
.children()
.iter()
.enumerate()
.filter(|(_, child)| child.flex > 0.0)
.collect();
if flexible.is_empty() {
return children.to_vec();
}
let fixed = children
.iter()
.zip(node.children())
.filter(|(_, child)| child.flex == 0.0)
.map(|(size, _)| if row { size.width } else { size.height })
.sum::<f32>();
let available = ((if row { bounds.width } else { bounds.height })
- padding * 2.0
- gap * children.len().saturating_sub(1) as f32
- fixed)
.max(0.0);
let total = flexible
.iter()
.map(|(_, child)| child.flex as f64)
.sum::<f64>();
let mut output = children.to_vec();
let mut remaining = available;
for (position, (index, child)) in flexible.iter().enumerate() {
let share = if position + 1 == flexible.len() {
remaining
} else {
((available as f64 * child.flex as f64 / total) as f32).min(remaining)
};
if row {
output[*index].width = share;
} else {
output[*index].height = share;
}
remaining = (remaining - share).max(0.0);
}
output
}
pub fn arrange_native(
node: &UiNode,
x: f32,
@@ -460,6 +508,11 @@ impl LayoutRuntime {
continue;
}
let child_sizes: Vec<_> = item.children.iter().map(|child| sizes[*child]).collect();
let child_sizes = flex_sizes(item.node, size, &child_sizes);
for (child, allocated) in item.children.iter().zip(&child_sizes) {
sizes[*child] = *allocated;
}
for (child, point) in
item.children
.iter()
+1
View File
@@ -222,6 +222,7 @@ impl NativeCallable for Method {
})
.collect::<Result<Vec<_>, _>>()?
};
let children = layout::flex_sizes(&node, Size { width, height }, &children);
let points = layout::arrange_native(&node, x, y, Size { width, height }, &children)
.map_err(|_| invalid("native arrangement exceeds limits"))?;
let mut result = Vec::new();
+1
View File
@@ -117,6 +117,7 @@ mod tests {
height: 160.0,
});
let root = UiNode {
flex: 0.0,
main_align: crate::layout::MainAlign::Start,
block_id: "shared".into(),
protocol_key: "rect".into(),
+1
View File
@@ -273,6 +273,7 @@ impl RenderCache {
},
};
let next = UiNode {
flex: data.flex,
main_align: data.main_align,
block_id: block.to_string(),
protocol_key,
+20 -14
View File
@@ -193,7 +193,8 @@ impl NativeCallable for Step {
};
if matches!(self.phase, Phase::Arrange) {
plan.runtime.arranged += 1;
plan.custom_arrange[self.index] = !intrinsic;
plan.custom_arrange[self.index] =
!intrinsic || node.children().iter().any(|child| child.flex > 0.0);
}
(node, children, bounds, native_size)
};
@@ -658,9 +659,6 @@ pub fn render(
cache.entries.retain(|mount, _| live.contains(mount));
// Preserve the existing native measurement cache and avoid VM/result
// allocation for trees without custom layout methods. Contexts already exist.
let block_type = desktop_type(vm.object_store(), "Block", desktop)?;
let native_measure = vm.object_store().lookup_method(block_type, "measure")?;
let native_arrange = vm.object_store().lookup_method(block_type, "arrange")?;
let mut custom = false;
for weak in &mounts {
let mount = vm
@@ -672,14 +670,28 @@ pub fn render(
.object_store()
.type_of(block)?
.ok_or(invalid("untyped layout target"))?;
Ok::<_, VmError>(
vm.object_store().lookup_method(definition, "measure")? != native_measure
|| vm.object_store().lookup_method(definition, "arrange")? != native_arrange,
)
for name in ["measure", "arrange"] {
let Some(method) = vm.object_store().lookup_method(definition, name)? else {
return Ok::<_, VmError>(true);
};
if !crate::native_visual::is_intrinsic(vm.object_store(), method, name, desktop)? {
return Ok(true);
}
}
Ok(false)
})();
vm.release(mount)?;
custom |= result?;
}
let mut nodes = Vec::new();
let mut work = vec![root.clone()];
while let Some(node) = work.pop() {
custom |= node.flex > 0.0;
work.extend(node.children().iter().rev().cloned());
nodes.push(node);
}
// Flex allocation can change text wrapping and ancestor measurements even
// when every protocol method is native. Use the same settling driver.
if !custom {
cache.clear();
let mut native = runtime.frame(&root)?;
@@ -689,12 +701,6 @@ pub fn render(
*frame = native;
return Ok(BTreeSet::new());
}
let mut nodes = Vec::new();
let mut work = vec![root];
while let Some(node) = work.pop() {
work.extend(node.children().iter().rev().cloned());
nodes.push(node);
}
anyhow::ensure!(
nodes.len() == mounts.len() && nodes.len() == frame.mounts.len(),
"layout structure does not match Mount contexts"
+3 -1
View File
@@ -60,6 +60,7 @@ pub const QUERY_NAMES: &[&str] = &[
#[derive(Debug, Clone, PartialEq)]
pub struct UiNode {
pub flex: f32,
pub main_align: crate::layout::MainAlign,
pub block_id: String,
pub protocol_key: String,
@@ -80,7 +81,8 @@ impl UiNode {
}
pub fn shallow_eq(&self, other: &Self) -> bool {
if self.main_align != other.main_align
if self.flex != other.flex
|| self.main_align != other.main_align
|| self.block_id != other.block_id
|| self.protocol_key != other.protocol_key
|| self.slots != other.slots