From 78fb66277d27eb9a1123d2f9618ba5043caf0626 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 22 Oct 2026 22:01:28 +0800 Subject: [PATCH] feat: allocate weighted flex space and remeasure affected occurrences --- README.md | 4 +- examples/flex.endor | 19 ++++++++++ src/README.md | 4 ++ src/api.rs | 4 +- src/block.rs | 8 +++- src/endor_host.rs | 87 ++++++++++++++++++++++++++++++++++++++++++++ src/layout.rs | 53 +++++++++++++++++++++++++++ src/native_visual.rs | 1 + src/presentation.rs | 1 + src/snapshot.rs | 1 + src/source_layout.rs | 34 ++++++++++------- src/ui_bridge.rs | 4 +- 12 files changed, 202 insertions(+), 18 deletions(-) create mode 100644 examples/flex.endor diff --git a/README.md b/README.md index 968356a..48154b5 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/examples/flex.endor b/examples/flex.endor new file mode 100644 index 0000000..3902161 --- /dev/null +++ b/examples/flex.endor @@ -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)) diff --git a/src/README.md b/src/README.md index 9a6c28e..dfa61d3 100644 --- a/src/README.md +++ b/src/README.md @@ -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. diff --git a/src/api.rs b/src/api.rs index a990cd9..0d98880 100644 --- a/src/api.rs +++ b/src/api.rs @@ -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: diff --git a/src/block.rs b/src/block.rs index a1c629f..a93c62e 100644 --- a/src/block.rs +++ b/src/block.rs @@ -117,6 +117,7 @@ pub struct Data { pub children: Vec, 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 { diff --git a/src/endor_host.rs b/src/endor_host.rs index 739db38..f4a1c50 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -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#" diff --git a/src/layout.rs b/src/layout.rs index aac2702..9636732 100644 --- a/src/layout.rs +++ b/src/layout.rs @@ -260,6 +260,54 @@ pub fn paint_native(node: &UiNode, x: f32, y: f32, size: Size) -> Option Vec { + 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::(); + 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::(); + 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() diff --git a/src/native_visual.rs b/src/native_visual.rs index 46b6a14..0ce8451 100644 --- a/src/native_visual.rs +++ b/src/native_visual.rs @@ -222,6 +222,7 @@ impl NativeCallable for Method { }) .collect::, _>>()? }; + 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(); diff --git a/src/presentation.rs b/src/presentation.rs index c6d09ea..da313c3 100644 --- a/src/presentation.rs +++ b/src/presentation.rs @@ -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(), diff --git a/src/snapshot.rs b/src/snapshot.rs index ca348a1..92a15b2 100644 --- a/src/snapshot.rs +++ b/src/snapshot.rs @@ -273,6 +273,7 @@ impl RenderCache { }, }; let next = UiNode { + flex: data.flex, main_align: data.main_align, block_id: block.to_string(), protocol_key, diff --git a/src/source_layout.rs b/src/source_layout.rs index d0beadb..fa15b21 100644 --- a/src/source_layout.rs +++ b/src/source_layout.rs @@ -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" diff --git a/src/ui_bridge.rs b/src/ui_bridge.rs index 1aad8d3..9f3188c 100644 --- a/src/ui_bridge.rs +++ b/src/ui_bridge.rs @@ -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