Settle source layout constraints before publishing complete frames
Verify Tessera GUI / verify (push) Failing after 7m49s
Verify Tessera GUI / verify (push) Failing after 7m49s
This commit is contained in:
+6
-4
@@ -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.
|
||||
|
||||
+4
-2
@@ -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.
|
||||
|
||||
|
||||
+147
-2
@@ -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::<Vec<_>>();
|
||||
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::<f32>()
|
||||
.unwrap();
|
||||
let y = session
|
||||
.execute("tail.mounts().at(0).bounds().y", "app.main")
|
||||
.unwrap()
|
||||
.value
|
||||
.parse::<f32>()
|
||||
.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::<Vec<_>>(),
|
||||
ids
|
||||
);
|
||||
let wider = session
|
||||
.execute("paragraph.mounts().at(0).bounds().height", "app.main")
|
||||
.unwrap()
|
||||
.value
|
||||
.parse::<f32>()
|
||||
.unwrap();
|
||||
let moved = session
|
||||
.execute("tail.mounts().at(0).bounds().y", "app.main")
|
||||
.unwrap()
|
||||
.value
|
||||
.parse::<f32>()
|
||||
.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);
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ pub struct LayoutRuntime {
|
||||
pub version: u64,
|
||||
pub measured: usize,
|
||||
pub arranged: usize,
|
||||
pub settle_passes: usize,
|
||||
pub viewport: Option<Size>,
|
||||
}
|
||||
|
||||
@@ -280,6 +281,7 @@ impl LayoutRuntime {
|
||||
fn build(&mut self, root: &UiNode, structural: bool) -> Result<Frame> {
|
||||
self.measured = 0;
|
||||
self.arranged = 0;
|
||||
self.settle_passes = usize::from(!structural);
|
||||
let mut items = Vec::<Item<'_>>::new();
|
||||
let mut work = vec![(root, None::<usize>, 0, root_constraints(self.viewport))];
|
||||
let mut used = HashSet::new();
|
||||
|
||||
+171
-5
@@ -74,6 +74,13 @@ struct Plan {
|
||||
cache: Cache,
|
||||
pending: Vec<Option<Pending>>,
|
||||
constraints: Vec<[f32; 4]>,
|
||||
// Source-arranged dimensions remain exact for this solve, not business state.
|
||||
allocations: Vec<[Option<f32>; 2]>,
|
||||
custom_arrange: Vec<bool>,
|
||||
custom_measure: Vec<bool>,
|
||||
measured_limits: Vec<[Option<f32>; 2]>,
|
||||
previous: Option<Vec<u32>>,
|
||||
seen: BTreeSet<Vec<u32>>,
|
||||
}
|
||||
type Shared = Arc<Mutex<Plan>>;
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -129,7 +136,14 @@ impl NativeCallable for Step {
|
||||
.iter()
|
||||
.map(|child| plan.sizes[*child])
|
||||
.collect::<Vec<_>>();
|
||||
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::<Mount>() {
|
||||
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<WeakObjectRef>,
|
||||
}
|
||||
impl NativeCallable for Settle {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
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, "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",
|
||||
|
||||
@@ -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()))?;
|
||||
}
|
||||
|
||||
@@ -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<Instruction>) -> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user