diff --git a/README.md b/README.md index feb234c..8ef4e28 100644 --- a/README.md +++ b/README.md @@ -216,10 +216,16 @@ Declared fields now use the same runtime type-check switch as source functions, These are checks at construction/write boundaries. Enabling does not scan old objects, and changing a referenced object's shared content does not revalidate every field that refers to it. Trusted hosts still own low-level payload/storage/attach operations. Complete initialization, local/captured type-name resolution, override variance, static and effect typing remain pending. -`invalidate("paint")` requests a frame while retaining measurement caches; `invalidate("layout")` also clears affected intrinsic measurements; `invalidate("content")` also invalidates derived content and ancestor dependencies. The default reason is layout. Requests coalesce at the refresh boundary, cover all aliases/occurrences of the same current content and preserve Mount identities. Hidden objects do not force visible frames. See [visual-protocols.endor](examples/visual-protocols.endor). Source measure/arrange overrides now participate in actual layout with structural Mount contexts available before first measurement. Source paint and hitTest also run in the frame/input pipeline. Full parameter/return type and effect contracts, more precise context dependencies and general container constraint negotiation remain future work. +`invalidate("paint")` requests a frame while retaining measurement caches; `invalidate("layout")` also clears affected intrinsic measurements; `invalidate("content")` also invalidates derived content and ancestor dependencies. The default reason is layout. Requests coalesce at the refresh boundary, cover all aliases/occurrences of the same current content and preserve Mount identities. Hidden objects do not force visible frames. See [visual-protocols.endor](examples/visual-protocols.endor). Source measure/arrange overrides now participate in actual layout with structural Mount contexts available before first measurement. Source paint and hitTest also run in the frame/input pipeline. Full parameter/return type and effect contracts, more precise context dependencies and additional container allocation policies remain future work. A source subclass can override `measure(self, mount, constraints): MeasureResult` and `arrange(self, mount, geometry): Arrangement`. The persistent renderer creates stable Mount identities and parent/child/sibling links before measuring. Measurement proceeds bottom-up with the current logical viewport as the Page constraints (headless callers default to 0..1000000); native parents and explicit native base calls use the current occurrence's measured child sizes, including source overrides. Arrangement proceeds top-down; each child Bounds must be assigned exactly once using its stable slot, with nominal result types and finite geometry checked. Source arrangements can resize or move children; omission, duplicate/foreign slots and invalid geometry reject the frame. See [source-layout.endor](examples/source-layout.endor). +Source layout now repeats bottom-up measurement and top-down arrangement inside one read-only VM call until input constraints, desired sizes and all allocated bounds repeat unchanged. Source-arranged dimensions that differ from a child's measured size become exact constraints for that axis during this solve. Native parents then account for the newly measured size. A source container measurement that differs from native measurement also constrains its content on the relevant policy axis. Selected limits remain until this solve finishes; the next input/resize starts fresh. Ordinary native intrinsic-size policies are retained. See [layout-negotiation.endor](examples/layout-negotiation.endor). + +The solver detects a previously visited nonconsecutive state as a cycle. It has no fixed propagation/pass cutoff: the whole solve shares the existing 1000000-instruction/128-frame VM budget, and exhaustion is an explicit failure. It reuses one bytecode driver frame rather than nesting one frame per pass. All measurement phases clear provisional geometry from every Mount, and only the complete settled result is committed. Failed candidates preserve the active program; live layout failures stop the domain and preserve its published picture. This is not a resumable layout scheduler or an optimal/general flex solver. + +`ui.stats().layoutPasses` reports passes for the latest layout (native-only fast path uses one). Measured/arranged/cache counters include the work of all solve passes. Source annotation validation is distinguished from actual content reads: merely checking a Mount parameter's type no longer disables measurement caching, while program reads of Mount layoutVersion/geometry still bypass it conservatively. Other type/validation dependencies remain version-checked. Runtime type checks stay enabled. + Mount.bounds() rejects reads during measurement, including old geometry on an existing Mount. The current occurrence's allocated Bounds become available while its arrange method runs. Structural contexts are prepared before layout, geometry is committed after successful layout, and onMount/onUnmount notifications then run before paint/publication. Both layout phases share one read-only VM call and instruction budget; temporary results can be modified, existing business state cannot. Read versions are captured before hooks, so a hook changing a measured dependency schedules another pass before publication. Dependencies are currently tracked per object. Source measurement results are cached by Mount identity, method, child sizes, constraints and actual object reads, including decoding an existing returned MeasureResult. Cache entries contain borrowed identities and versions, adding no GC roots. Mount-reading measurements currently bypass the cache conservatively because object-level tracking cannot distinguish layoutVersion/geometry from stable structure. Global dictionary writes or changes to another field on a read object can also cause conservative misses. Native measurements keep their shape cache, and arrangement still visits each active occurrence. ui.stats() exposes sourceMeasureHits/sourceMeasureMisses; diagnostic statistics are rejected inside read-only rendering because allocation/count observations are not stable layout inputs. `Window: Object` represents a native window resource. `Window()` creates another window in the same Aster VM, up to 16 open windows per runtime. `ui.window()` returns the current event/render window, with the main window as the top-level Console default. `page.window()` reports its actual owner or nil. `page.open(window)` and `page.moveToWindow(window)` move the same Page, including navigation and business references, to that window. Omitting the open target keeps an existing owner; an unowned Page uses the calling view. `page.detachToWindow()` creates a new Window, moves the Page there and returns the resource. Dragging a Tab away from its strip invokes that same Page method. Moving a Page unmounts the old occurrence and creates destination Mounts. `window.pages()` returns a traced ObjectList in open order. See [windows.endor](examples/windows.endor). @@ -246,7 +252,7 @@ Native creation and commands remain local until the input/candidate succeeds. Fa The native window publishes its current logical content size to the existing VM worker on startup, resize and scale changes. The worker coalesces the latest size, updates the managed viewport input, and refreshes the same runtime without adding Console source/history entries. ui.viewport() returns a fresh managed width/height snapshot; reads during rendering depend on the private input object. User changes to a returned snapshot do not resize the window. Unchanged sizes cause no frame; a fresh or unopened Console runtime updates its inputs without replacing a preserved displayed page. Failed resize layouts stop the affected runtime and preserve the displayed frame. -The default Column/Button policy propagates available cross-axis width minus padding and leaves height unconstrained; Row propagates available height and leaves width unconstrained. Page uses both viewport bounds. Native and source desired sizes are clamped to their supplied constraints, while source arrange can still allocate explicit child bounds. The window clips overflow and pointer targeting to its extent; TextBlock wraps to its available width; general multi-pass constraint negotiation remains future work. See [layout-cache.endor](examples/layout-cache.endor). GET code also exposes X-Tessera-Viewport-Width/Height headers without evaluating source. +The default Column/Button policy propagates available cross-axis width minus padding and leaves height unconstrained; Row propagates available height and leaves width unconstrained. Page uses both viewport bounds. Native and source desired sizes are clamped to their supplied constraints, while source arrange can still allocate explicit child bounds. The window clips overflow and pointer targeting to its extent; TextBlock wraps to its available width; source layout now settles constraints over repeated measurement/arrangement passes as described below. See [layout-cache.endor](examples/layout-cache.endor). GET code also exposes X-Tessera-Viewport-Width/Height headers without evaluating source. Native pointer clicks now resolve source `hitTest(self, mount, point): Bool` overrides in reverse paint order, then dispatch through the existing capture/target/bubble route. The Point is local to that occurrence; `point.inside(bounds)` uses a half-open rectangle and `point.inCircle(cx, cy, radius)` includes the circle boundary. Each candidate is first restricted to its Mount rectangle, so hit shapes can refine that area, but cannot expand it. A rejected target falls through to another interactive occurrence, including a parent. Ordinary Blocks become interactive through a live click subscription or a source onEvent override; disconnecting the final click subscription updates that status. See [source-hit.endor](examples/source-hit.endor). @@ -256,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 still owns its assigned child Bounds. Row's unbounded main axis and ScrollBlock's unbounded content continue their current policies; flex allocation, automatic vertical-only scroll wrapping and general constraint convergence remain pending. 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. Row's unbounded main axis and ScrollBlock's unbounded content continue their current policies; flex allocation and automatic vertical-only scroll wrapping remain pending. 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. diff --git a/examples/layout-negotiation.endor b/examples/layout-negotiation.endor new file mode 100644 index 0000000..82b806c --- /dev/null +++ b/examples/layout-negotiation.endor @@ -0,0 +1,35 @@ +class Policy { + width: Number + function narrow(self: Policy, event: Event): Unit { self.width = 280 } + function wide(self: Policy, event: Event): Unit { self.width = 560 } +} +class ArrangedColumn: Column { + policy: Policy + function arrange(self: ArrangedColumn, mount: Mount, geometry: Bounds): Arrangement { + result = Column.arrange(self, mount, geometry) + result.children.at(0).width = self.policy.width + return result + } +} +class MeasuredColumn: Column { + width: Number + function measure(self: MeasuredColumn, mount: Mount, constraints: Constraints): MeasureResult { + result = Column.measure(self, mount, constraints) + result.width = self.width + return result + } +} +policy = Policy(280) +paragraph = TextBlock("源码 arrange 改变分配宽度后,文字会按实际宽度重新测量。增加的高度继续影响容器和相邻对象,直到整棵布局稳定后才发布。这里与下面使用的是同一个 TextBlock;每个 Mount 都有自己的约束与几何。同一套内存对象不需要复制业务状态,也不通过丢弃传播来结束更新。") +tail = TextBlock("这一行跟随上方段落。") +arranged = ArrangedColumn(0, 12, paragraph, tail, policy) +measured = MeasuredColumn(0, 12, paragraph, TextBlock("这一段的宽度来自源码 measure。"), 360) +narrow = Button("arrange 为 280") +wide = Button("arrange 为 560") +narrowConnection = narrow.on("click", policy.narrow) +wideConnection = wide.on("click", policy.wide) +page = Page() +page.title = "约束协商" +page.render(Column(24, 16, Row(0, 12, narrow, wide), arranged, measured)) +ui.window().resize(850, 700) +ui.window().setTitle("测量与排列直到稳定") diff --git a/src/README.md b/src/README.md index 2e1f0a9..8c82558 100644 --- a/src/README.md +++ b/src/README.md @@ -19,13 +19,13 @@ | tasks.rs | Managed owner scopes and callbacks, weak timer index, request-key replacement, lifecycle cancellation and budgeted worker delivery | | tabs.rs | Immutable tab chrome, shared draw/hit geometry, overflow navigation, drag gaps/anchors/insertion markers and opaque published Page identities | | window.rs | Native Window construction/close, context ownership, ordered Page roots, read-only guards, Page reordering, physical desktop placement and coalesced GUI projections | -| vm_sequence.rs | Shared validated call-sequence builder for event and lifecycle batches in the existing VM frame loop | -| source_layout.rs | Read-only source layout, per-Mount measurement caches with subcall dependencies, viewport constraints, typed/slot validation and occurrence geometry | +| vm_sequence.rs | Shared validated call-sequence builder and EXTENDED_ARG-aware same-frame repetition for layout, event and lifecycle work | +| source_layout.rs | Read-only source layout, repeated constraint/geometry solving with cycle detection, per-Mount measurement caches with subcall dependencies, viewport constraints, typed/slot validation and occurrence geometry | | source_hit.rs | Read-only source/native pointer target selectors, reverse paint order, strict Bool results and matching press/release targets | | source_paint.rs | Read-only source paint dispatch, shared VM budget, paired text-wrap bounds and checked command conversion and versioned object dependencies | | native_visual.rs | Managed native visual protocol queries with occurrence validation, value conversion and bounded results | | object_list.rs | Traced indexed results shared by Mount queries and visual protocol results | -| layout.rs | Shared native geometry/paint functions, iterative measurement/arrangement, stable occurrence IDs, measurement cache, geometry budgets and width-sensitive native text measurement | +| layout.rs | Shared native geometry/paint functions, iterative measurement/arrangement, stable occurrence IDs, measurement cache, solve-pass counters, geometry budgets and width-sensitive native text measurement | | document.rs | Published source/AST/UI snapshot, revisions, invalidation, frame validation, single-line fault banner (full cause retained in Frame), validated optional text-wrap bounds and display commands | | app.rs | Window events, logical viewport publication, redraw, native multi-window tab dragging and system widget pointer/keyboard/IME routing | | clipboard.rs | UTF-8 macOS clipboard adapter independent of Finder locale, with strict decoding and surfaced errors | @@ -132,4 +132,6 @@ Tab drops validate source and destination window/session/layout plus the actual NativeCallable implementations publish positional metadata, including internal layout/paint/hit/event continuations. The VM validates it before entering Rust. Event delivery uses the same source/native/bound arity query; binding and Task registration reject incompatible or unknown metadata before changing ownership. Native parameter/return types and effects remain checked by existing host boundaries rather than this count-only metadata. -Native TextBlock measurement and painting now share width-sensitive shaping. Column/Button cross-axis constraints feed both the native fast path and source base calls; direct base measurement also uses its supplied viewport. RenderCommand text has optional wrap_bounds, converted to a clipped WrappedText primitive. Source PaintCommand uses paired wrapWidth/wrapHeight and legacy text remains unwrapped when both are absent. General source-arrange negotiation and axis-specific ScrollBlock wrapping remain future work. +Native TextBlock measurement and painting now share width-sensitive shaping. Column/Button cross-axis constraints feed both the native fast path and source base calls; direct base measurement also uses its supplied viewport. RenderCommand text has optional wrap_bounds, converted to a clipped WrappedText primitive. Source PaintCommand uses paired wrapWidth/wrapHeight and legacy text remains unwrapped when both are absent. Source-arranged dimensions now participate in repeated constraint solving; general flex allocation, resumable work and axis-specific ScrollBlock wrapping remain future work. + +Layout convergence uses exact finite snapshots of constraints/sizes/bounds and source-selected limits. The same immutable driver loops within one shared VM budget, clears all provisional measurement geometry between passes and rejects nonconsecutive repeated states. Aster ReadAccess distinguishes annotation validation from normal reads; the bridge skips only validation-only Mount reads after independently validating the live Mount/owner context. Actual Mount reads remain volatile; all other recorded dependencies are retained. diff --git a/src/api.rs b/src/api.rs index 932fbd6..8dd2111 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1083,9 +1083,11 @@ Window is a host-provided managed resource: ui.window(), page.window(), page.ope ContainerBlock.insert(position,block) accepts a zero-based position through the current count, returns a new stable slot and preserves existing slots/Mounts. Invalid indices and child cycles fail before changing the child list. Page.moveTab(position) uses a final zero-based index in its owning window. Native drops invoke the actual Page moveToWindow/moveTab/activate methods; a declined or redirected window move skips destination reordering. A drop allows 300000 instructions per method. Source overrides participate; earlier writes do not roll back after failure. Window.moveTo(x,y) queues the physical desktop outer origin, with signed integers within +/-1000000. Detached placement preserves the saved grab offset; the window manager may adjust it and unsupported global placement reports a diagnostic. Dragging uses a 12-logical-pixel threshold, visible insertion marker and Escape cancellation. Overflow auto-scroll, external-app occlusion and mixed-DPI verification remain pending. See examples/tab-placement.endor. -Source measure and arrange overrides execute bottom-up and top-down in one read-only VM layout call. Structural Mount links exist before first measurement; bounds queries reject premature geometry. Native base layout uses current occurrence child measurements, and Arrangement must assign every stable child slot exactly once. Layout dependencies changed by lifecycle hooks trigger another pass before publication. Page constraints now use the current logical window viewport. Column/Button propagate cross-axis width and Row propagates cross-axis height; desired sizes are clamped. ui.viewport() provides a managed snapshot whose private input participates in rendering dependencies. Native resize updates are coalesced on the same worker without adding source inputs. Source measurement caches use Mount/method/children/constraints and actual subcall object reads, including returned-result decoding; Mount-reading methods conservatively bypass caching. ui.stats() exposes sourceMeasureHits/sourceMeasureMisses outside read-only rendering. Native TextBlock wrapping now uses the occurrence width in measurement/cache/painting; general constraint negotiation remains pending; ScrollBlock scrolling is described below. +Source measure and arrange overrides execute bottom-up and top-down in one read-only VM layout call. Structural Mount links exist before first measurement; bounds queries reject premature geometry. Native base layout uses current occurrence child measurements, and Arrangement must assign every stable child slot exactly once. Layout dependencies changed by lifecycle hooks trigger another pass before publication. Page constraints now use the current logical window viewport. Column/Button propagate cross-axis width and Row propagates cross-axis height; desired sizes are clamped. ui.viewport() provides a managed snapshot whose private input participates in rendering dependencies. Native resize updates are coalesced on the same worker without adding source inputs. Source measurement caches use Mount/method/children/constraints and actual subcall object reads, including returned-result decoding; Mount-reading methods conservatively bypass caching. ui.stats() exposes sourceMeasureHits/sourceMeasureMisses outside read-only rendering. Native TextBlock wrapping now uses the occurrence width in measurement/cache/painting; source measurement/arrangement now repeats until constraints and geometry settle; additional allocation policies remain pending; ScrollBlock scrolling is described below. -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/constraint convergence, vertical-only scrolling policy and broad fractional-DPI validation remain pending. See examples/wrapped-text.endor. +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. 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. diff --git a/src/endor_host.rs b/src/endor_host.rs index 7dd697b..d3444df 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -993,6 +993,143 @@ mod tests { const EXAMPLE: &str = include_str!("../examples/hello.endor"); const PAGE: &str = include_str!("../examples/page.endor"); + #[test] + fn actual_mount_version_reads_still_bypass_measurement_cache() { + let (mut session, initial) = ReplSession::load( + r#" +class Versioned: RectBlock { + function measure(self: Versioned,mount: Mount,constraints: Constraints): MeasureResult { + return MeasureResult(mount.layoutVersion,20) + } +} +rect=Versioned(80,20) +page=Page() +page.render(rect) +"#, + "app.main", + 1, + 241, + ) + .unwrap(); + let next = session + .execute("rect.invalidate(\"paint\")", "app.main") + .unwrap() + .document + .unwrap(); + assert!(next.frame.layout_version > initial.frame.layout_version); + assert!(next.frame.commands.iter().any(|command|matches!(command,RenderCommand::RoundedRect{width,..} if *width==next.frame.layout_version as f32))); + assert_eq!(source_measure_stat(&mut session, "sourceMeasureHits"), 0); + assert!(source_measure_stat(&mut session, "sourceMeasureMisses") >= 2); + } + + #[test] + fn source_allocations_and_measurement_limits_settle_before_publication() { + let (mut session, initial) = ReplSession::load_with_viewport( + include_str!("../examples/layout-negotiation.endor"), + "app.main", + 1, + 240, + Some(crate::layout::Size { + width: 850.0, + height: 700.0, + }), + ) + .unwrap(); + let ids = initial + .frame + .mounts + .iter() + .map(|m| m.id) + .collect::>(); + let width0 = session + .execute("paragraph.mounts().at(0).bounds().width", "app.main") + .unwrap() + .value; + let width1 = session + .execute("paragraph.mounts().at(1).bounds().width", "app.main") + .unwrap() + .value; + assert_eq!(width0, "280"); + assert_eq!(width1, "360"); + let height = session + .execute("paragraph.mounts().at(0).bounds().height", "app.main") + .unwrap() + .value + .parse::() + .unwrap(); + let y = session + .execute("tail.mounts().at(0).bounds().y", "app.main") + .unwrap() + .value + .parse::() + .unwrap(); + assert!(height > 20.0); + assert!(y >= height + 12.0); + assert!(source_measure_stat(&mut session, "layoutPasses") >= 2); + let changed = session + .execute("wide.click()", "app.main") + .unwrap() + .document + .unwrap(); + assert_eq!( + changed + .frame + .mounts + .iter() + .map(|m| m.id) + .collect::>(), + ids + ); + let wider = session + .execute("paragraph.mounts().at(0).bounds().height", "app.main") + .unwrap() + .value + .parse::() + .unwrap(); + let moved = session + .execute("tail.mounts().at(0).bounds().y", "app.main") + .unwrap() + .value + .parse::() + .unwrap(); + assert!(wider < height && moved < y); + assert_eq!( + session + .execute("paragraph.mounts().at(0).bounds().width", "app.main") + .unwrap() + .value, + "560" + ); + assert_eq!( + session + .execute("paragraph.mounts().at(1).bounds().width", "app.main") + .unwrap() + .value, + "360" + ); + } + + #[test] + fn alternating_source_allocations_are_rejected_as_a_cycle() { + let source = r#" +class Alternating: Column { + function arrange(self: Alternating,mount: Mount,geometry: Bounds): Arrangement { + result=Column.arrange(self,mount,geometry) + result.children.at(0).width=geometry.height + result.children.at(0).height=geometry.width + return result + } +} +page=Page() +page.render(Alternating(0,0,RectBlock(120,60))) +"#; + let error = compile(source, "app.main", 1).unwrap_err(); + assert!( + error.to_string().contains("did not converge (cycle)"), + "{error:#}" + ); + } + #[test] fn source_text_paint_rejects_incomplete_wrap_bounds() { let source = r##" @@ -2294,7 +2431,11 @@ page.render(block) assert!(painted.frame.commands.iter().any( |command| matches!(command,RenderCommand::RoundedRect {color,..} if color=="#526AC7") )); - assert_eq!(source_measure_stat(&mut session, "sourceMeasureHits"), 2); + let passes = source_measure_stat(&mut session, "layoutPasses"); + assert_eq!( + source_measure_stat(&mut session, "sourceMeasureHits"), + 2 * passes + ); assert_eq!(source_measure_stat(&mut session, "measured"), 0); let resized = click_named(&mut session, &painted, "expand"); assert!( @@ -2304,7 +2445,11 @@ page.render(block) .iter() .any(|mount| mount.width == 260.0 && mount.height == 60.0) ); - assert_eq!(source_measure_stat(&mut session, "sourceMeasureHits"), 1); + let passes = source_measure_stat(&mut session, "layoutPasses"); + assert_eq!( + source_measure_stat(&mut session, "sourceMeasureHits"), + 2 * passes - 1 + ); assert_eq!(source_measure_stat(&mut session, "sourceMeasureMisses"), 1); } diff --git a/src/layout.rs b/src/layout.rs index 16f68d6..86a44cd 100644 --- a/src/layout.rs +++ b/src/layout.rs @@ -38,6 +38,7 @@ pub struct LayoutRuntime { pub version: u64, pub measured: usize, pub arranged: usize, + pub settle_passes: usize, pub viewport: Option, } @@ -280,6 +281,7 @@ impl LayoutRuntime { fn build(&mut self, root: &UiNode, structural: bool) -> Result { self.measured = 0; self.arranged = 0; + self.settle_passes = usize::from(!structural); let mut items = Vec::>::new(); let mut work = vec![(root, None::, 0, root_constraints(self.viewport))]; let mut used = HashSet::new(); diff --git a/src/source_layout.rs b/src/source_layout.rs index 3591aed..fdade96 100644 --- a/src/source_layout.rs +++ b/src/source_layout.rs @@ -74,6 +74,13 @@ struct Plan { cache: Cache, pending: Vec>, constraints: Vec<[f32; 4]>, + // Source-arranged dimensions remain exact for this solve, not business state. + allocations: Vec<[Option; 2]>, + custom_arrange: Vec, + custom_measure: Vec, + measured_limits: Vec<[Option; 2]>, + previous: Option>, + seen: BTreeSet>, } type Shared = Arc>; #[derive(Debug, Clone, Copy)] @@ -129,7 +136,14 @@ impl NativeCallable for Step { .iter() .map(|child| plan.sizes[*child]) .collect::>(); - let bounds = plan.bounds[self.index]; + let bounds = if matches!(self.phase, Phase::Arrange) { + plan.bounds[self.index] + } else { + None + }; + if matches!(self.phase, Phase::Measure) { + plan.custom_measure[self.index] = method != native; + } let native_size = if matches!(self.phase, Phase::Measure) && method == native { let constraints = plan.constraints[self.index]; Some( @@ -180,6 +194,7 @@ impl NativeCallable for Step { }; if matches!(self.phase, Phase::Arrange) { plan.runtime.arranged += 1; + plan.custom_arrange[self.index] = method != native; } (node, children, bounds, native_size) }; @@ -303,12 +318,36 @@ impl NativeCallable for Collect { }, plan.constraints[self.index], ); + // Native shrink-to-content containers keep their existing input + // policy. Only a source measurement that differs from the native + // result supplies an additional content constraint. + if plan.custom_measure[self.index] && !plan.children[self.index].is_empty() { + let children = plan.children[self.index] + .iter() + .map(|child| plan.sizes[*child]) + .collect(); + let native = layout::measure_native( + &plan.nodes[self.index], + children, + plan.constraints[self.index], + ) + .ok() + .map(|native| layout::constrained(native, plan.constraints[self.index])); + // Equality after remeasurement does not retract a source + // limit selected earlier in this solve. New renders start fresh. + if !native.is_some_and(|native| native.width == size.width) { + plan.measured_limits[self.index][0] = Some(size.width); + } + if !native.is_some_and(|native| native.height == size.height) { + plan.measured_limits[self.index][1] = Some(size.height); + } + } // Decoding is part of the subcall dependency region: a source // method may return an existing result whose fields can change. let tracked = pending .map(|pending| { cx.store() - .end_read_tracking(pending.token) + .end_read_tracking_details(pending.token) .map(|reads| (pending, reads)) }) .transpose()?; @@ -316,7 +355,8 @@ impl NativeCallable for Collect { let mut versions = BTreeMap::new(); let mut volatile = false; let registry = desktop_type_registry(cx, self.desktop)?; - for object in reads { + for read in reads { + let object = read.object; if object == self.desktop || object == registry { continue; } @@ -324,7 +364,8 @@ impl NativeCallable for Collect { // source. Object-granular tracking cannot prove those // accesses stable, so conservatively bypass its cache. if cx.store().object(object)?.payload().as_any().is::() { - volatile = true; + volatile |= read.content_read; + continue; } versions.insert(object, cx.store().change_version(object)?); } @@ -398,13 +439,116 @@ impl NativeCallable for Collect { { return Err(invalid("arrangement bounds exceed limits")); } - plan.bounds[children[position]] = Some(bounds); + let child = children[position]; + if plan.custom_arrange[self.index] { + if bounds[2] != plan.sizes[child].width { + plan.allocations[child][0] = Some(bounds[2]); + } + if bounds[3] != plan.sizes[child].height { + plan.allocations[child][1] = Some(bounds[3]); + } + } + plan.bounds[child] = Some(bounds); } } } Ok(NativeResult::Return(Value::Nil)) } } +#[derive(Debug)] +struct Settle { + plan: Shared, + mounts: Vec, +} +impl NativeCallable for Settle { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(0)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result { + let repeat = { + let mut plan = self + .plan + .lock() + .map_err(|_| invalid("layout plan poisoned"))?; + plan.runtime.settle_passes += 1; + let mut next = plan.constraints.clone(); + for (index, children) in plan.children.iter().enumerate() { + let [_, _, width, height] = + plan.bounds[index].ok_or(invalid("unarranged occurrence"))?; + let mut available = next[index]; + if let Some(width) = plan.measured_limits[index][0] { + available[2] = width; + } + if let Some(height) = plan.measured_limits[index][1] { + available[3] = height; + } + if width != plan.sizes[index].width { + available[2] = width; + } + if height != plan.sizes[index].height { + available[3] = height; + } + let base = layout::child_constraints(&plan.nodes[index], available); + for child in children { + let mut constraints = base; + if let Some(width) = plan.allocations[*child][0] { + constraints[0] = width; + constraints[2] = width; + } + if let Some(height) = plan.allocations[*child][1] { + constraints[1] = height; + constraints[3] = height; + } + next[*child] = constraints; + } + } + let mut state = Vec::with_capacity(plan.nodes.len() * 14); + let bits = |value: f32| if value == 0.0 { 0 } else { value.to_bits() }; + for (index, constraints) in next.iter().enumerate() { + state.extend(constraints.iter().copied().map(bits)); + state.extend([ + bits(plan.sizes[index].width), + bits(plan.sizes[index].height), + ]); + state.extend( + plan.bounds[index] + .ok_or(invalid("unarranged occurrence"))? + .into_iter() + .map(bits), + ); + for dimension in plan.allocations[index] { + state.push(u32::from(dimension.is_some())); + state.push(dimension.map_or(0, bits)); + } + } + if plan.previous.as_ref() == Some(&state) && plan.constraints == next { + false + } else { + if !plan.seen.insert(state.clone()) { + return Err(invalid("layout constraints did not converge (cycle)")); + } + plan.previous = Some(state); + plan.constraints = next; + plan.bounds.fill(None); + true + } + }; + if repeat { + // No stale geometry from a prior pass is observable during measurement. + for weak in &self.mounts { + let mount = cx.upgrade(*weak)?.ok_or(invalid("layout Mount expired"))?; + if let Some(context) = &cx.store().payload::(mount, "Mount")?.layout { + context + .lock() + .map_err(|_| invalid("layout context poisoned"))? + .bounds = None; + } + } + } + Ok(NativeResult::Return(Value::Bool(repeat))) + } +} + #[derive(Debug)] struct Prepare { plan: Shared, @@ -462,6 +606,22 @@ impl NativeCallable for Prepare { ]); } } + let settle = cx.allocate(ContextNativeFunction::new( + "settle source layout", + Settle { + plan: self.plan.clone(), + mounts: self.mounts.clone(), + }, + vec![], + ))?; + let check = constants.len() as u32; + constants.push(Value::Object(settle)); + instructions.extend([ + Instruction::new(Opcode::LoadConst, check), + Instruction::simple(Opcode::PushNull), + Instruction::new(Opcode::Call, 0), + ]); + crate::vm_sequence::repeat_while(&mut instructions)?; let end = constants.len() as u32; constants.push(Value::Nil); instructions.extend([ @@ -566,6 +726,12 @@ pub fn render( cache: cache.clone(), pending: (0..count).map(|_| None).collect(), constraints, + allocations: vec![[None, None]; count], + custom_arrange: vec![false; count], + custom_measure: vec![false; count], + measured_limits: vec![[None, None]; count], + previous: None, + seen: BTreeSet::new(), })); let prepare = vm.allocate(ContextNativeFunction::new( "prepare source layout", diff --git a/src/ui_bridge.rs b/src/ui_bridge.rs index d709e98..ee17b95 100644 --- a/src/ui_bridge.rs +++ b/src/ui_bridge.rs @@ -936,6 +936,7 @@ impl NativeCallable for Function { ("sourceMeasureHits", session.measure_cache.hits as i64), ("sourceMeasureMisses", session.measure_cache.misses as i64), ("arranged", session.layout.arranged as i64), + ("layoutPasses", session.layout.settle_passes as i64), ] { cx.set_attr(stats, name, Value::Number(value.into()))?; } diff --git a/src/vm_sequence.rs b/src/vm_sequence.rs index bae81be..40482cf 100644 --- a/src/vm_sequence.rs +++ b/src/vm_sequence.rs @@ -33,3 +33,68 @@ pub fn build( crate::ui_bridge::attach_desktop_type(cx, driver, "Function", desktop)?; Ok(driver) } + +/// Consume the condition on the stack: true repeats this same frame from zero, +/// false falls through. Operand widths include EXTENDED_ARG code units. +pub fn repeat_while(instructions: &mut Vec) -> Result<(), VmError> { + let body = Instruction::encode_all(instructions)?.len() / 2; + let mut back = Instruction::new(Opcode::JumpBackward, 0); + loop { + let units = Instruction::encode_all(&[back])?.len() / 2; + let distance = u32::try_from(body + 1 + units) + .map_err(|_| VmError::ExecutionLimit("layout bytecode"))?; + if back.argument == distance { + instructions.push(Instruction::new(Opcode::PopJumpIfFalse, units as u32)); + instructions.push(back); + return Ok(()); + } + back.argument = distance; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use endor_core::{ExecutionLimits, Vm}; + #[test] + fn repeated_bytecode_handles_extended_operands_and_keeps_one_frame() { + for condition in [false, true] { + let mut instructions = vec![Instruction::simple(Opcode::Nop); 300]; + instructions.push(Instruction::new(Opcode::LoadConst, 0)); + repeat_while(&mut instructions).unwrap(); + instructions.extend([ + Instruction::new(Opcode::LoadConst, 1), + Instruction::simple(Opcode::ReturnValue), + ]); + let code = EndorCode::from_instructions( + &instructions, + vec![Value::Bool(condition), Value::Nil], + CodeLayout::default(), + ) + .unwrap(); + let mut vm = Vm::new().unwrap(); + let code = vm.new_code(code).unwrap(); + let globals = vm.new_dict().unwrap(); + let result = vm.execute_with_limits( + code, + globals, + ExecutionLimits { + max_frames: 1, + max_instructions: 1000, + }, + ); + if condition { + assert!(matches!( + result, + Err(VmError::ExecutionLimit("instructions")) + )); + } else { + assert_eq!(result.unwrap(), Value::Nil); + } + vm.release(code).unwrap(); + vm.release(globals).unwrap(); + vm.collect_cycles(); + assert_eq!(vm.object_count(), 0); + } + } +} diff --git a/vendor/aster b/vendor/aster index 44519ab..f9243c7 160000 --- a/vendor/aster +++ b/vendor/aster @@ -1 +1 @@ -Subproject commit 44519abf7e1ce879da7c27875195ca5a2393cb1a +Subproject commit f9243c77c7609a1afc7cbe6a81fdaa988677d399