refactor: organize host modules and document architecture with UML
Verify Tessera GUI / verify (push) Failing after 2m2s
Verify Tessera GUI / verify (push) Failing after 2m2s
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
use crate::geometry::{Point, Rect};
|
||||
use crate::text::TextStyle;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Color {
|
||||
pub red: u8,
|
||||
pub green: u8,
|
||||
pub blue: u8,
|
||||
pub alpha: u8,
|
||||
}
|
||||
|
||||
impl Color {
|
||||
pub const fn rgb(red: u8, green: u8, blue: u8) -> Self {
|
||||
Self {
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
alpha: 255,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
|
||||
Self {
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
alpha,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum DrawCommand {
|
||||
Clear(Color),
|
||||
PushClip(Rect),
|
||||
PopClip,
|
||||
FillRoundedRect {
|
||||
rect: Rect,
|
||||
radius: f32,
|
||||
color: Color,
|
||||
},
|
||||
StrokeRoundedRect {
|
||||
rect: Rect,
|
||||
radius: f32,
|
||||
width: f32,
|
||||
color: Color,
|
||||
},
|
||||
WrappedText {
|
||||
rect: Rect,
|
||||
value: String,
|
||||
style: TextStyle,
|
||||
color: Color,
|
||||
},
|
||||
Text {
|
||||
origin: Point,
|
||||
value: String,
|
||||
style: TextStyle,
|
||||
color: Color,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DisplayList {
|
||||
commands: Vec<DrawCommand>,
|
||||
}
|
||||
|
||||
impl DisplayList {
|
||||
pub fn push(&mut self, command: DrawCommand) {
|
||||
self.commands.push(command);
|
||||
}
|
||||
|
||||
pub fn translate(&mut self, delta: Point) {
|
||||
for command in &mut self.commands {
|
||||
match command {
|
||||
DrawCommand::WrappedText { rect, .. }
|
||||
| DrawCommand::PushClip(rect)
|
||||
| DrawCommand::FillRoundedRect { rect, .. }
|
||||
| DrawCommand::StrokeRoundedRect { rect, .. } => {
|
||||
rect.x += delta.x;
|
||||
rect.y += delta.y;
|
||||
}
|
||||
DrawCommand::Text { origin, .. } => {
|
||||
origin.x += delta.x;
|
||||
origin.y += delta.y;
|
||||
}
|
||||
DrawCommand::Clear(_) | DrawCommand::PopClip => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn commands(&self) -> &[DrawCommand] {
|
||||
&self.commands
|
||||
}
|
||||
|
||||
pub fn extend(&mut self, other: DisplayList) {
|
||||
self.commands.extend(other.commands);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Point {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
}
|
||||
|
||||
impl Point {
|
||||
pub const fn new(x: f32, y: f32) -> Self {
|
||||
Self { x, y }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Rect {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
}
|
||||
|
||||
impl Rect {
|
||||
pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
|
||||
Self {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contains(self, point: Point) -> bool {
|
||||
point.x >= self.x
|
||||
&& point.x <= self.x + self.width
|
||||
&& point.y >= self.y
|
||||
&& point.y <= self.y + self.height
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rectangle_contains_edges_but_not_outside_points() {
|
||||
let rect = Rect::new(10.0, 20.0, 30.0, 40.0);
|
||||
assert!(rect.contains(Point::new(10.0, 20.0)));
|
||||
assert!(rect.contains(Point::new(40.0, 60.0)));
|
||||
assert!(!rect.contains(Point::new(9.9, 20.0)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,639 @@
|
||||
//! Iterative measure/arrange/paint over derived visual data. Every occurrence
|
||||
//! has its own geometry; measurement caches never become semantic object state.
|
||||
use crate::{
|
||||
document::{Frame, MountGeometry, RenderCommand},
|
||||
text::{self, TextStyle},
|
||||
ui_bridge::{MAX_DIMENSION, UiKind, UiNode},
|
||||
};
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
const MAX_LAYOUT_VISITS: usize = 10_000;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum MainAlign {
|
||||
#[default]
|
||||
Start,
|
||||
Center,
|
||||
End,
|
||||
SpaceBetween,
|
||||
}
|
||||
impl MainAlign {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Start => "start",
|
||||
Self::Center => "center",
|
||||
Self::End => "end",
|
||||
Self::SpaceBetween => "space-between",
|
||||
}
|
||||
}
|
||||
pub fn parse(value: &str) -> Result<Self, endor_core::VmError> {
|
||||
match value {
|
||||
"start" => Ok(Self::Start),
|
||||
"center" => Ok(Self::Center),
|
||||
"end" => Ok(Self::End),
|
||||
"space-between" => Ok(Self::SpaceBetween),
|
||||
_ => Err(endor_core::VmError::InvalidArgument(
|
||||
"mainAlign expects start, center, end or space-between",
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Main-axis constraints interpreted independently by each parent occurrence.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct FlexPolicy {
|
||||
pub basis: Option<f32>,
|
||||
pub min: f32,
|
||||
pub max: f32,
|
||||
pub shrink: f32,
|
||||
}
|
||||
impl Default for FlexPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
basis: None,
|
||||
min: 0.0,
|
||||
max: MAX_DIMENSION as f32,
|
||||
shrink: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Size {
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum Shape {
|
||||
Text(String, u32, f32),
|
||||
Rect(f32, f32),
|
||||
Container(bool, f32, f32, Vec<Size>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
|
||||
struct Key {
|
||||
parent: Option<u64>,
|
||||
slot: u64,
|
||||
block: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct LayoutRuntime {
|
||||
sizes: HashMap<String, (Shape, Size)>,
|
||||
ids: HashMap<Key, u64>,
|
||||
next_id: u64,
|
||||
pub version: u64,
|
||||
pub measured: usize,
|
||||
pub arranged: usize,
|
||||
pub settle_passes: usize,
|
||||
pub slices: usize,
|
||||
pub viewport: Option<Size>,
|
||||
}
|
||||
|
||||
struct Item<'a> {
|
||||
node: &'a UiNode,
|
||||
parent: Option<usize>,
|
||||
children: Vec<usize>,
|
||||
id: u64,
|
||||
constraints: [f32; 4],
|
||||
}
|
||||
|
||||
fn bounded(value: f32) -> Result<f32> {
|
||||
if !value.is_finite() || !(0.0..=MAX_DIMENSION as f32).contains(&value) {
|
||||
bail!("UI layout exceeds the 1000000 coordinate/size limit");
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub fn root_constraints(viewport: Option<Size>) -> [f32; 4] {
|
||||
let size = viewport.unwrap_or(Size {
|
||||
width: MAX_DIMENSION as f32,
|
||||
height: MAX_DIMENSION as f32,
|
||||
});
|
||||
[0.0, 0.0, size.width, size.height]
|
||||
}
|
||||
pub fn child_constraints(node: &UiNode, parent: [f32; 4]) -> [f32; 4] {
|
||||
if let UiKind::Scroll { width, height, .. } = node.kind {
|
||||
return arranged_child_constraints(
|
||||
node,
|
||||
parent,
|
||||
constrained(Size { width, height }, parent),
|
||||
);
|
||||
}
|
||||
match container(node) {
|
||||
Some((true, padding, _)) => [
|
||||
0.0,
|
||||
0.0,
|
||||
MAX_DIMENSION as f32,
|
||||
(parent[3] - padding * 2.0).max(0.0),
|
||||
],
|
||||
Some((false, padding, _)) => [
|
||||
0.0,
|
||||
0.0,
|
||||
(parent[2] - padding * 2.0).max(0.0),
|
||||
MAX_DIMENSION as f32,
|
||||
],
|
||||
None => parent,
|
||||
}
|
||||
}
|
||||
/// Scroll cross-axis constraints come from this occurrence's actual viewport,
|
||||
/// including a source parent's allocation rather than only constructor size.
|
||||
pub fn arranged_child_constraints(node: &UiNode, available: [f32; 4], bounds: Size) -> [f32; 4] {
|
||||
if let UiKind::Scroll { padding, axis, .. } = node.kind {
|
||||
return [
|
||||
0.0,
|
||||
0.0,
|
||||
if axis.horizontal() {
|
||||
MAX_DIMENSION as f32
|
||||
} else {
|
||||
(bounds.width - padding * 2.0).max(0.0)
|
||||
},
|
||||
if axis.vertical() {
|
||||
MAX_DIMENSION as f32
|
||||
} else {
|
||||
(bounds.height - padding * 2.0).max(0.0)
|
||||
},
|
||||
];
|
||||
}
|
||||
child_constraints(node, available)
|
||||
}
|
||||
|
||||
pub fn constrained(size: Size, constraints: [f32; 4]) -> Size {
|
||||
Size {
|
||||
width: size.width.clamp(constraints[0], constraints[2]),
|
||||
height: size.height.clamp(constraints[1], constraints[3]),
|
||||
}
|
||||
}
|
||||
|
||||
fn container(node: &UiNode) -> Option<(bool, f32, f32)> {
|
||||
match &node.kind {
|
||||
UiKind::Row { padding, gap, .. } => Some((true, *padding, *gap)),
|
||||
UiKind::Scroll { padding, gap, .. } => Some((false, *padding, *gap)),
|
||||
UiKind::Column { padding, gap, .. } | UiKind::Button { padding, gap, .. } => {
|
||||
Some((false, *padding, *gap))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn main_axis(node: &UiNode) -> Option<usize> {
|
||||
container(node).map(|(row, _, _)| usize::from(!row))
|
||||
}
|
||||
|
||||
fn measure_shape(shape: &Shape) -> Result<Size> {
|
||||
let size = match shape {
|
||||
Shape::Text(value, size, width) => {
|
||||
let style = TextStyle::ui(*size);
|
||||
let intrinsic = text::measure(value, style);
|
||||
let wrapped = text::measure_wrapped(value, style, *width);
|
||||
Size {
|
||||
width: intrinsic.width.min(*width),
|
||||
height: wrapped.height,
|
||||
}
|
||||
}
|
||||
Shape::Rect(width, height) => Size {
|
||||
width: *width,
|
||||
height: *height,
|
||||
},
|
||||
Shape::Container(row, padding, gap, children) => {
|
||||
let along = children
|
||||
.iter()
|
||||
.map(|s| if *row { s.width } else { s.height })
|
||||
.sum::<f32>()
|
||||
+ padding * 2.0
|
||||
+ gap * children.len().saturating_sub(1) as f32;
|
||||
let cross = children
|
||||
.iter()
|
||||
.map(|s| if *row { s.height } else { s.width })
|
||||
.fold(0.0_f32, f32::max)
|
||||
+ padding * 2.0;
|
||||
if *row {
|
||||
Size {
|
||||
width: along,
|
||||
height: cross,
|
||||
}
|
||||
} else {
|
||||
Size {
|
||||
width: cross,
|
||||
height: along,
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
bounded(size.width)?;
|
||||
bounded(size.height)?;
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
fn shape(node: &UiNode, children: Vec<Size>, constraints: [f32; 4]) -> Result<Shape> {
|
||||
Ok(match &node.kind {
|
||||
UiKind::Text { value, size, .. } => Shape::Text(value.clone(), *size, constraints[2]),
|
||||
UiKind::Rect { width, height, .. } => Shape::Rect(*width, *height),
|
||||
UiKind::Spacer(size) => Shape::Rect(*size, *size),
|
||||
UiKind::Scroll { width, height, .. } => Shape::Rect(*width, *height),
|
||||
_ => {
|
||||
let (row, padding, gap) = container(node).context("unknown native visual protocol")?;
|
||||
Shape::Container(row, padding, gap, children)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn measure_native(node: &UiNode, children: Vec<Size>, constraints: [f32; 4]) -> Result<Size> {
|
||||
measure_shape(&shape(node, children, constraints)?)
|
||||
}
|
||||
|
||||
/// Private derived scratch space for one occurrence during layout. Contains no
|
||||
/// managed references; source code cannot mutate it through heap attributes.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Context {
|
||||
pub node: Option<std::sync::Arc<UiNode>>,
|
||||
pub children: Vec<Size>,
|
||||
pub preferred: Vec<Size>,
|
||||
pub bounds: Option<[f32; 4]>,
|
||||
}
|
||||
|
||||
pub fn paint_native(node: &UiNode, x: f32, y: f32, size: Size) -> Option<RenderCommand> {
|
||||
let size_for_text = size;
|
||||
match &node.kind {
|
||||
UiKind::Text { value, size, color } => Some(RenderCommand::Text {
|
||||
x,
|
||||
y,
|
||||
value: value.clone(),
|
||||
size: *size,
|
||||
color: color.clone(),
|
||||
wrap_bounds: Some([size_for_text.width, size_for_text.height]),
|
||||
}),
|
||||
UiKind::Rect { radius, color, .. } => Some(RenderCommand::RoundedRect {
|
||||
x,
|
||||
y,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
radius: *radius,
|
||||
color: color.clone(),
|
||||
}),
|
||||
UiKind::Button { .. } => Some(RenderCommand::RoundedRect {
|
||||
x,
|
||||
y,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
radius: 7.0,
|
||||
color: "#E3EAF7".into(),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocate main-axis space with bounded growth and basis-weighted shrinking.
|
||||
/// Preferred sizes come from this occurrence's first measurement in the solve;
|
||||
/// remeasurement must not turn a prior allocation into a new intrinsic basis.
|
||||
pub fn flex_sizes(node: &UiNode, bounds: Size, children: &[Size], preferred: &[Size]) -> Vec<Size> {
|
||||
let Some((row, padding, gap)) = container(node) else {
|
||||
return children.to_vec();
|
||||
};
|
||||
let nodes = node.children();
|
||||
if !nodes.iter().any(|child| child.has_flex()) {
|
||||
return children.to_vec();
|
||||
}
|
||||
let space = ((if row { bounds.width } else { bounds.height }) as f64
|
||||
- padding as f64 * 2.0
|
||||
- gap as f64 * children.len().saturating_sub(1) as f64)
|
||||
.max(0.0);
|
||||
let bases: Vec<f64> = nodes
|
||||
.iter()
|
||||
.zip(preferred)
|
||||
.map(|(child, size)| {
|
||||
child.flex_policy.basis.unwrap_or_else(|| {
|
||||
if child.flex > 0.0 {
|
||||
0.0
|
||||
} else if row {
|
||||
size.width
|
||||
} else {
|
||||
size.height
|
||||
}
|
||||
}) as f64
|
||||
})
|
||||
.collect();
|
||||
let mut sizes: Vec<f64> = nodes
|
||||
.iter()
|
||||
.zip(&bases)
|
||||
.map(|(child, basis)| {
|
||||
basis.clamp(child.flex_policy.min as f64, child.flex_policy.max as f64)
|
||||
})
|
||||
.collect();
|
||||
let free = space - sizes.iter().sum::<f64>();
|
||||
let growing = free > 0.0;
|
||||
let weights: Vec<f64> = nodes
|
||||
.iter()
|
||||
.zip(&bases)
|
||||
.map(|(child, basis)| {
|
||||
if growing {
|
||||
child.flex as f64
|
||||
} else {
|
||||
child.flex_policy.shrink as f64 * basis
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let limits: Vec<f64> = nodes
|
||||
.iter()
|
||||
.map(|child| {
|
||||
if growing {
|
||||
child.flex_policy.max as f64
|
||||
} else {
|
||||
child.flex_policy.min as f64
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let mut active: Vec<usize> = (0..nodes.len())
|
||||
.filter(|&i| {
|
||||
weights[i] > 0.0
|
||||
&& if growing {
|
||||
sizes[i] < limits[i]
|
||||
} else {
|
||||
sizes[i] > limits[i]
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let mut remaining = free.abs();
|
||||
while remaining > 0.0 && !active.is_empty() {
|
||||
let total = active.iter().map(|&i| weights[i]).sum::<f64>();
|
||||
let mut spent = 0.0;
|
||||
let mut saturated = false;
|
||||
for &i in &active {
|
||||
let capacity = (limits[i] - sizes[i]).abs();
|
||||
let amount = (remaining * weights[i] / total).min(capacity);
|
||||
sizes[i] += if growing { amount } else { -amount };
|
||||
spent += amount;
|
||||
saturated |= amount >= capacity;
|
||||
}
|
||||
remaining = (remaining - spent).max(0.0);
|
||||
// Without saturation this round distributed all available space. Do not
|
||||
// spin on floating point residue; a saturated round freezes a child.
|
||||
if !saturated {
|
||||
break;
|
||||
}
|
||||
active.retain(|&i| {
|
||||
if growing {
|
||||
sizes[i] < limits[i]
|
||||
} else {
|
||||
sizes[i] > limits[i]
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut output = children.to_vec();
|
||||
for (size, along) in output.iter_mut().zip(sizes) {
|
||||
if row {
|
||||
size.width = along as f32;
|
||||
} else {
|
||||
size.height = along as f32;
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
pub fn arrange_native(
|
||||
node: &UiNode,
|
||||
x: f32,
|
||||
y: f32,
|
||||
bounds: Size,
|
||||
children: &[Size],
|
||||
) -> Result<Vec<(f32, f32)>> {
|
||||
let Some((row, padding, gap)) = container(node) else {
|
||||
return Ok(vec![]);
|
||||
};
|
||||
let occupied = children
|
||||
.iter()
|
||||
.map(|child| if row { child.width } else { child.height })
|
||||
.sum::<f32>()
|
||||
+ gap * children.len().saturating_sub(1) as f32;
|
||||
let available = if row { bounds.width } else { bounds.height };
|
||||
let spare = (available - padding * 2.0 - occupied).max(0.0);
|
||||
let offset = match node.main_align {
|
||||
MainAlign::Center => spare / 2.0,
|
||||
MainAlign::End => spare,
|
||||
_ => 0.0,
|
||||
};
|
||||
let distributed_gap = if node.main_align == MainAlign::SpaceBetween && children.len() > 1 {
|
||||
spare / (children.len() - 1) as f32
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let mut cursor = padding + offset;
|
||||
let mut points = Vec::with_capacity(children.len());
|
||||
for child in children {
|
||||
let point = if row {
|
||||
(x + cursor, y + padding)
|
||||
} else {
|
||||
(x + padding, y + cursor)
|
||||
};
|
||||
bounded(point.0)?;
|
||||
bounded(point.1)?;
|
||||
bounded(point.0 + child.width)?;
|
||||
bounded(point.1 + child.height)?;
|
||||
points.push(point);
|
||||
cursor += if row { child.width } else { child.height };
|
||||
cursor += gap + distributed_gap;
|
||||
}
|
||||
Ok(points)
|
||||
}
|
||||
|
||||
impl LayoutRuntime {
|
||||
pub fn invalidate(&mut self, block: &str) {
|
||||
self.sizes.remove(block);
|
||||
}
|
||||
pub fn reserve_identity_floor(&mut self, floor: u64) {
|
||||
self.next_id = self.next_id.max(floor);
|
||||
}
|
||||
pub fn identity_high_watermark(&self) -> u64 {
|
||||
self.next_id
|
||||
}
|
||||
|
||||
pub fn clear_occurrences(&mut self) {
|
||||
self.ids.clear();
|
||||
}
|
||||
pub fn frame(&mut self, root: &UiNode) -> Result<Frame> {
|
||||
// Stage all cache/identity changes; a rejected frame leaves the last
|
||||
// valid occurrence registry intact and never publishes partial geometry.
|
||||
let mut next = self.clone();
|
||||
let frame = next.build(root, false)?;
|
||||
*self = next;
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
/// Allocate stable occurrence identities without measuring or publishing geometry.
|
||||
pub fn structure(&mut self, root: &UiNode) -> Result<Frame> {
|
||||
let mut next = self.clone();
|
||||
let frame = next.build(root, true)?;
|
||||
*self = next;
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
pub fn measure_node(
|
||||
&mut self,
|
||||
node: &UiNode,
|
||||
children: Vec<Size>,
|
||||
constraints: [f32; 4],
|
||||
) -> Result<Size> {
|
||||
let shape = shape(node, children, constraints)?;
|
||||
if let Some((_, size)) = self
|
||||
.sizes
|
||||
.get(&node.block_id)
|
||||
.filter(|(old, _)| *old == shape)
|
||||
{
|
||||
return Ok(*size);
|
||||
}
|
||||
self.measured += 1;
|
||||
let size = measure_shape(&shape)?;
|
||||
self.sizes.insert(node.block_id.clone(), (shape, size));
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
fn build(&mut self, root: &UiNode, structural: bool) -> Result<Frame> {
|
||||
self.measured = 0;
|
||||
self.arranged = 0;
|
||||
self.settle_passes = usize::from(!structural);
|
||||
self.slices = 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();
|
||||
while let Some((node, parent, slot, constraints)) = work.pop() {
|
||||
if items.len() >= MAX_LAYOUT_VISITS {
|
||||
bail!("expanded UI layout exceeds 10000 nodes");
|
||||
}
|
||||
if node.slots.len() != node.children().len() {
|
||||
bail!("invalid child slot table");
|
||||
}
|
||||
let key = Key {
|
||||
parent: parent.map(|i| items[i].id),
|
||||
slot,
|
||||
block: node.block_id.clone(),
|
||||
};
|
||||
let id = if let Some(id) = self.ids.get(&key) {
|
||||
*id
|
||||
} else {
|
||||
self.next_id = self
|
||||
.next_id
|
||||
.checked_add(1)
|
||||
.context("Mount identity exhausted")?;
|
||||
self.ids.insert(key.clone(), self.next_id);
|
||||
self.next_id
|
||||
};
|
||||
if !used.insert(key) {
|
||||
bail!("duplicate child slot in one presentation");
|
||||
}
|
||||
let index = items.len();
|
||||
if let Some(parent) = parent {
|
||||
items[parent].children.push(index);
|
||||
}
|
||||
items.push(Item {
|
||||
node,
|
||||
parent,
|
||||
children: vec![],
|
||||
id,
|
||||
constraints,
|
||||
});
|
||||
for (child, slot) in node.children().iter().zip(&node.slots).rev() {
|
||||
work.push((
|
||||
child.as_ref(),
|
||||
Some(index),
|
||||
*slot,
|
||||
child_constraints(node, constraints),
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut sizes = vec![Size::default(); items.len()];
|
||||
if !structural {
|
||||
for (index, item) in items.iter().enumerate().rev() {
|
||||
sizes[index] = constrained(
|
||||
self.measure_node(
|
||||
item.node,
|
||||
item.children.iter().map(|i| sizes[*i]).collect(),
|
||||
item.constraints,
|
||||
)?,
|
||||
item.constraints,
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut points = vec![(0.0_f32, 0.0_f32); items.len()];
|
||||
let mut mounts = Vec::with_capacity(items.len());
|
||||
let mut commands = Vec::new();
|
||||
let mut siblings = vec![None; items.len()];
|
||||
for item in &items {
|
||||
for pair in item.children.windows(2) {
|
||||
siblings[pair[0]] = Some(items[pair[1]].id);
|
||||
}
|
||||
}
|
||||
for (index, item) in items.iter().enumerate() {
|
||||
self.arranged += usize::from(!structural);
|
||||
let (x, y) = points[index];
|
||||
let size = sizes[index];
|
||||
bounded(x)?;
|
||||
bounded(y)?;
|
||||
bounded(x + size.width)?;
|
||||
bounded(y + size.height)?;
|
||||
mounts.push(MountGeometry {
|
||||
id: item.id,
|
||||
clip: None,
|
||||
scroll: None,
|
||||
block_id: item.node.block_id.clone(),
|
||||
parent: item.parent.map(|i| items[i].id),
|
||||
first_child: item.children.first().map(|i| items[*i].id),
|
||||
next_sibling: siblings[index],
|
||||
x,
|
||||
y,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
interactive: item.node.interactive,
|
||||
});
|
||||
if !structural && let Some(command) = paint_native(item.node, x, y, size) {
|
||||
commands.push(command);
|
||||
}
|
||||
if structural {
|
||||
continue;
|
||||
}
|
||||
let child_sizes: Vec<_> = item.children.iter().map(|child| sizes[*child]).collect();
|
||||
let child_sizes = flex_sizes(item.node, size, &child_sizes, &child_sizes);
|
||||
for (child, allocated) in item.children.iter().zip(&child_sizes) {
|
||||
sizes[*child] = *allocated;
|
||||
}
|
||||
|
||||
for (child, point) in
|
||||
item.children
|
||||
.iter()
|
||||
.zip(arrange_native(item.node, x, y, size, &child_sizes)?)
|
||||
{
|
||||
points[*child] = point;
|
||||
}
|
||||
}
|
||||
self.ids.retain(|key, _| used.contains(key));
|
||||
let blocks: HashSet<_> = items
|
||||
.iter()
|
||||
.map(|item| item.node.block_id.as_str())
|
||||
.collect();
|
||||
self.sizes
|
||||
.retain(|block, _| blocks.contains(block.as_str()));
|
||||
self.version = self
|
||||
.version
|
||||
.checked_add(1)
|
||||
.context("layout version exhausted")?;
|
||||
Ok(Frame {
|
||||
commands,
|
||||
mounts,
|
||||
layout_version: self.version,
|
||||
..Frame::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn frame(root: &UiNode) -> Result<Frame> {
|
||||
LayoutRuntime::default().frame(root)
|
||||
}
|
||||
|
||||
pub fn frame_with_viewport(root: &UiNode, viewport: Size) -> Result<Frame> {
|
||||
LayoutRuntime {
|
||||
viewport: Some(viewport),
|
||||
..Default::default()
|
||||
}
|
||||
.frame(root)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Module ownership follows the directory; crate-root aliases keep internal call sites stable.
|
||||
pub(crate) mod display_list;
|
||||
pub(crate) mod geometry;
|
||||
pub(crate) mod layout;
|
||||
pub(crate) mod native_visual;
|
||||
pub(crate) mod scene;
|
||||
pub(crate) mod scroll;
|
||||
pub(crate) mod software_renderer;
|
||||
pub(crate) mod source_hit;
|
||||
pub(crate) mod source_layout;
|
||||
pub(crate) mod source_paint;
|
||||
pub(crate) mod text;
|
||||
@@ -0,0 +1,472 @@
|
||||
//! Native visual protocol entry points. Values are ordinary managed Endor
|
||||
//! objects; geometry is scoped to a live occurrence, never stored on a Block.
|
||||
use crate::{
|
||||
block,
|
||||
document::RenderCommand,
|
||||
layout::{self, Size},
|
||||
mount::Mount,
|
||||
ui_bridge::{MAX_DIMENSION, attach_desktop_type},
|
||||
};
|
||||
use endor_core::{
|
||||
AnnotationType, CallEffect, CallSignature, ContextNativeFunction, NativeCallable,
|
||||
NativeContext, NativeResult, ObjectRef, ObjectStore, Value, Vm, VmError,
|
||||
};
|
||||
|
||||
fn invalid(message: &'static str) -> VmError {
|
||||
VmError::InvalidArgument(message)
|
||||
}
|
||||
fn object(value: &Value) -> Result<ObjectRef, VmError> {
|
||||
if let Value::Object(object) = value {
|
||||
Ok(*object)
|
||||
} else {
|
||||
Err(invalid("visual protocol requires objects"))
|
||||
}
|
||||
}
|
||||
pub(crate) fn number(
|
||||
cx: &NativeContext<'_>,
|
||||
object: ObjectRef,
|
||||
name: &str,
|
||||
signed: bool,
|
||||
) -> Result<f32, VmError> {
|
||||
let Value::Number(value) = cx.store().get_attr(object, name)? else {
|
||||
return Err(invalid("visual field must be a Number"));
|
||||
};
|
||||
let value = value
|
||||
.to_string()
|
||||
.parse::<f32>()
|
||||
.map_err(|_| invalid("invalid visual number"))?;
|
||||
if !value.is_finite() || value.abs() > MAX_DIMENSION as f32 || (!signed && value < 0.0) {
|
||||
return Err(invalid("visual number exceeds bounds"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
pub(crate) fn value(value: f32) -> Value {
|
||||
Value::Number((value as f64).into())
|
||||
}
|
||||
pub(crate) fn record(
|
||||
cx: &mut NativeContext<'_>,
|
||||
desktop: ObjectRef,
|
||||
kind: &str,
|
||||
fields: Vec<(&str, Value)>,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
let object = cx.new_object()?;
|
||||
attach_desktop_type(cx, object, kind, desktop)?;
|
||||
for (key, value) in fields {
|
||||
cx.set_attr(object, key, value)?;
|
||||
}
|
||||
Ok(object)
|
||||
}
|
||||
fn size(node: &crate::ui_bridge::UiNode, constraints: [f32; 4]) -> Result<Size, VmError> {
|
||||
let frame = layout::frame_with_viewport(
|
||||
node,
|
||||
Size {
|
||||
width: constraints[2],
|
||||
height: constraints[3],
|
||||
},
|
||||
)
|
||||
.map_err(|_| invalid("native measurement exceeds layout limits"))?;
|
||||
let root = frame
|
||||
.mounts
|
||||
.first()
|
||||
.ok_or(invalid("empty native measurement"))?;
|
||||
Ok(Size {
|
||||
width: root.width,
|
||||
height: root.height,
|
||||
})
|
||||
}
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Query {
|
||||
Measure,
|
||||
Arrange,
|
||||
Paint,
|
||||
HitTest,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Method {
|
||||
query: Query,
|
||||
desktop: ObjectRef,
|
||||
signature: CallSignature,
|
||||
}
|
||||
/// Only this actual implementation can use the matching intrinsic fast path.
|
||||
pub(crate) fn is_intrinsic(
|
||||
store: &ObjectStore,
|
||||
function: ObjectRef,
|
||||
name: &str,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<bool, VmError> {
|
||||
let Some(function) = store
|
||||
.object(function)?
|
||||
.payload()
|
||||
.as_any()
|
||||
.downcast_ref::<ContextNativeFunction>()
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Some(method) = function.implementation::<Method>() else {
|
||||
return Ok(false);
|
||||
};
|
||||
// Per-window desktops share the same nominal registry and intrinsic bodies.
|
||||
let same_registry = method.desktop == desktop
|
||||
|| matches!(
|
||||
(store.get_attr(method.desktop, "types")?, store.get_attr(desktop, "types")?),
|
||||
(Value::Object(left), Value::Object(right)) if left == right
|
||||
);
|
||||
Ok(same_registry
|
||||
&& matches!(
|
||||
(name, method.query),
|
||||
("measure", Query::Measure)
|
||||
| ("arrange", Query::Arrange)
|
||||
| ("paint", Query::Paint)
|
||||
| ("hitTest", Query::HitTest)
|
||||
))
|
||||
}
|
||||
|
||||
impl NativeCallable for Method {
|
||||
fn signature(&self) -> Option<CallSignature> {
|
||||
Some(self.signature.clone())
|
||||
}
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(3))
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let [owner, context, input] = args else {
|
||||
return Err(invalid("visual method expects a Mount and an input value"));
|
||||
};
|
||||
let owner = object(owner)?;
|
||||
let mount = cx.store().payload::<Mount>(object(context)?, "Mount")?;
|
||||
if !mount.mounted || mount.block != owner {
|
||||
return Err(invalid(
|
||||
"visual context is detached or belongs to another Block",
|
||||
));
|
||||
}
|
||||
let geometry = mount.geometry.clone();
|
||||
let staged = mount
|
||||
.layout
|
||||
.as_ref()
|
||||
.map(|layout| {
|
||||
let layout = layout
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout context poisoned"))?;
|
||||
Ok::<_, VmError>((
|
||||
layout.node.clone(),
|
||||
layout.children.clone(),
|
||||
layout.preferred.clone(),
|
||||
))
|
||||
})
|
||||
.transpose()?;
|
||||
let input = object(input)?;
|
||||
if matches!(self.query, Query::HitTest) {
|
||||
if staged.is_some() {
|
||||
return Err(invalid("hitTest is unavailable during layout"));
|
||||
}
|
||||
let x = number(cx, input, "x", true)?;
|
||||
let y = number(cx, input, "y", true)?;
|
||||
return Ok(NativeResult::Return(Value::Bool(
|
||||
x >= 0.0 && y >= 0.0 && x < geometry.width && y < geometry.height,
|
||||
)));
|
||||
}
|
||||
if matches!(&staged, Some((None, _, _))) {
|
||||
return Err(invalid(
|
||||
"layout context is not prepared for this occurrence",
|
||||
));
|
||||
}
|
||||
let node = if let Some((Some(node), _, _)) = &staged {
|
||||
node.clone()
|
||||
} else {
|
||||
block::snapshot(cx.store(), owner)?
|
||||
};
|
||||
let result = match self.query {
|
||||
Query::Measure => {
|
||||
let min_w = number(cx, input, "minWidth", false)?;
|
||||
let min_h = number(cx, input, "minHeight", false)?;
|
||||
let max_w = number(cx, input, "maxWidth", false)?;
|
||||
let max_h = number(cx, input, "maxHeight", false)?;
|
||||
if min_w > max_w || min_h > max_h {
|
||||
return Err(invalid("minimum exceeds maximum constraint"));
|
||||
}
|
||||
let size = if let Some((_, children, _)) = &staged {
|
||||
layout::measure_native(&node, children.clone(), [min_w, min_h, max_w, max_h])
|
||||
.map_err(|_| invalid("native measurement exceeds layout limits"))?
|
||||
} else {
|
||||
size(&node, [min_w, min_h, max_w, max_h])?
|
||||
};
|
||||
Value::Object(record(
|
||||
cx,
|
||||
self.desktop,
|
||||
"MeasureResult",
|
||||
vec![
|
||||
("width", value(size.width.clamp(min_w, max_w))),
|
||||
("height", value(size.height.clamp(min_h, max_h))),
|
||||
],
|
||||
)?)
|
||||
}
|
||||
Query::Arrange => {
|
||||
let x = number(cx, input, "x", false)?;
|
||||
let y = number(cx, input, "y", false)?;
|
||||
let width = number(cx, input, "width", false)?;
|
||||
let height = number(cx, input, "height", false)?;
|
||||
if x + width > MAX_DIMENSION as f32 || y + height > MAX_DIMENSION as f32 {
|
||||
return Err(invalid("visual bounds exceed limits"));
|
||||
}
|
||||
let children = if let Some((_, children, _)) = &staged {
|
||||
children.clone()
|
||||
} else {
|
||||
node.children()
|
||||
.iter()
|
||||
.map(|child| {
|
||||
size(
|
||||
child,
|
||||
layout::arranged_child_constraints(
|
||||
&node,
|
||||
[0.0, 0.0, width, height],
|
||||
Size { width, height },
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
};
|
||||
let preferred = staged
|
||||
.as_ref()
|
||||
.map_or(children.as_slice(), |(_, _, preferred)| {
|
||||
preferred.as_slice()
|
||||
});
|
||||
let children =
|
||||
layout::flex_sizes(&node, Size { width, height }, &children, preferred);
|
||||
let points = layout::arrange_native(&node, x, y, Size { width, height }, &children)
|
||||
.map_err(|_| invalid("native arrangement exceeds limits"))?;
|
||||
let mut result = Vec::new();
|
||||
for ((slot, size), (x, y)) in node.slots.iter().zip(children).zip(points) {
|
||||
let bounds = record(
|
||||
cx,
|
||||
self.desktop,
|
||||
"Bounds",
|
||||
vec![
|
||||
("x", value(x)),
|
||||
("y", value(y)),
|
||||
("width", value(size.width)),
|
||||
("height", value(size.height)),
|
||||
],
|
||||
)?;
|
||||
cx.set_attr(bounds, "slot", Value::Number((*slot as i64).into()))?;
|
||||
result.push(bounds);
|
||||
}
|
||||
let result = crate::object_list::collection(cx, result, self.desktop)?;
|
||||
Value::Object(record(
|
||||
cx,
|
||||
self.desktop,
|
||||
"Arrangement",
|
||||
vec![("children", Value::Object(result))],
|
||||
)?)
|
||||
}
|
||||
Query::Paint => {
|
||||
let x = number(cx, input, "x", true)?;
|
||||
let y = number(cx, input, "y", true)?;
|
||||
let width = number(cx, input, "width", false)?;
|
||||
let height = number(cx, input, "height", false)?;
|
||||
if x + width > MAX_DIMENSION as f32 || y + height > MAX_DIMENSION as f32 {
|
||||
return Err(invalid("visual bounds exceed limits"));
|
||||
}
|
||||
let mut commands = Vec::new();
|
||||
if let Some(command) = layout::paint_native(&node, x, y, Size { width, height }) {
|
||||
let fields = match command {
|
||||
RenderCommand::Text {
|
||||
x,
|
||||
y,
|
||||
value: text,
|
||||
size,
|
||||
color,
|
||||
wrap_bounds,
|
||||
} => {
|
||||
let mut fields = vec![
|
||||
("kind", Value::Text("text".into())),
|
||||
("x", value(x)),
|
||||
("y", value(y)),
|
||||
("text", Value::Text(text)),
|
||||
("size", Value::Number((size as i64).into())),
|
||||
("color", Value::Text(color)),
|
||||
];
|
||||
if let Some([width, height]) = wrap_bounds {
|
||||
fields.push(("wrapWidth", value(width)));
|
||||
fields.push(("wrapHeight", value(height)));
|
||||
}
|
||||
fields
|
||||
}
|
||||
RenderCommand::RoundedRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
radius,
|
||||
color,
|
||||
} => vec![
|
||||
("kind", Value::Text("roundedRect".into())),
|
||||
("x", value(x)),
|
||||
("y", value(y)),
|
||||
("width", value(width)),
|
||||
("height", value(height)),
|
||||
("radius", value(radius)),
|
||||
("color", Value::Text(color)),
|
||||
],
|
||||
_ => return Err(invalid("unsupported native paint command")),
|
||||
};
|
||||
let command = record(cx, self.desktop, "PaintCommand", fields)?;
|
||||
commands.push(command);
|
||||
}
|
||||
let commands = crate::object_list::collection(cx, commands, self.desktop)?;
|
||||
Value::Object(record(
|
||||
cx,
|
||||
self.desktop,
|
||||
"DisplayList",
|
||||
vec![("commands", Value::Object(commands))],
|
||||
)?)
|
||||
}
|
||||
Query::HitTest => unreachable!("handled above"),
|
||||
};
|
||||
Ok(NativeResult::Return(result))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PointMethod {
|
||||
expected: ObjectRef,
|
||||
circle: bool,
|
||||
signature: CallSignature,
|
||||
}
|
||||
impl NativeCallable for PointMethod {
|
||||
fn signature(&self) -> Option<CallSignature> {
|
||||
Some(self.signature.clone())
|
||||
}
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(if self.circle {
|
||||
4
|
||||
} else {
|
||||
2
|
||||
}))
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let Some(Value::Object(point)) = args.first() else {
|
||||
return Err(invalid("Point method requires a Point"));
|
||||
};
|
||||
if !cx.store().is_instance(*point, self.expected)? {
|
||||
return Err(invalid("Point method requires a Point"));
|
||||
}
|
||||
let x = number(cx, *point, "x", true)?;
|
||||
let y = number(cx, *point, "y", true)?;
|
||||
let inside = if self.circle {
|
||||
let [
|
||||
_,
|
||||
Value::Number(cx_value),
|
||||
Value::Number(cy_value),
|
||||
Value::Number(radius),
|
||||
] = args
|
||||
else {
|
||||
return Err(invalid("inCircle requires center x/y and radius"));
|
||||
};
|
||||
let parse = |value: &endor_core::EndorNumber| -> Result<f64, VmError> {
|
||||
let value = value
|
||||
.to_string()
|
||||
.parse::<f64>()
|
||||
.map_err(|_| invalid("invalid circle number"))?;
|
||||
if !value.is_finite() || value.abs() > MAX_DIMENSION {
|
||||
return Err(invalid("circle number exceeds bounds"));
|
||||
}
|
||||
Ok(value)
|
||||
};
|
||||
let dx = x as f64 - parse(cx_value)?;
|
||||
let dy = y as f64 - parse(cy_value)?;
|
||||
let radius = parse(radius)?;
|
||||
if radius < 0.0 {
|
||||
return Err(invalid("circle radius must be nonnegative"));
|
||||
}
|
||||
dx * dx + dy * dy <= radius * radius
|
||||
} else {
|
||||
let [_, Value::Object(bounds)] = args else {
|
||||
return Err(invalid("inside requires Bounds"));
|
||||
};
|
||||
let left = number(cx, *bounds, "x", true)?;
|
||||
let top = number(cx, *bounds, "y", true)?;
|
||||
let width = number(cx, *bounds, "width", false)?;
|
||||
let height = number(cx, *bounds, "height", false)?;
|
||||
x >= left && y >= top && x < left + width && y < top + height
|
||||
};
|
||||
Ok(NativeResult::Return(Value::Bool(inside)))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn install(
|
||||
vm: &mut Vm,
|
||||
roots: &mut Vec<ObjectRef>,
|
||||
desktop: ObjectRef,
|
||||
block_type: ObjectRef,
|
||||
function_type: ObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
let nominal = |name| {
|
||||
crate::ui_bridge::desktop_type(vm.object_store(), name, desktop)
|
||||
.map(AnnotationType::Nominal)
|
||||
};
|
||||
let mount = nominal("Mount")?;
|
||||
let constraints = nominal("Constraints")?;
|
||||
let bounds = nominal("Bounds")?;
|
||||
let point = nominal("Point")?;
|
||||
let measure = nominal("MeasureResult")?;
|
||||
let arrangement = nominal("Arrangement")?;
|
||||
let display = nominal("DisplayList")?;
|
||||
for (name, query, input, returns) in [
|
||||
("measure", Query::Measure, constraints, measure),
|
||||
("arrange", Query::Arrange, bounds, arrangement),
|
||||
("paint", Query::Paint, bounds, display),
|
||||
("hitTest", Query::HitTest, point, AnnotationType::Bool),
|
||||
] {
|
||||
let function = vm.allocate(ContextNativeFunction::new(
|
||||
name,
|
||||
Method {
|
||||
query,
|
||||
desktop,
|
||||
signature: CallSignature::exact(
|
||||
vec![AnnotationType::Nominal(block_type), mount, input],
|
||||
returns,
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
},
|
||||
vec![desktop],
|
||||
))?;
|
||||
roots.push(function);
|
||||
vm.attach_type(function, function_type)?;
|
||||
vm.define_method(block_type, name, function)?;
|
||||
}
|
||||
let registry = object(&vm.get_attr(desktop, "types")?)?;
|
||||
let point_type = object(
|
||||
&vm.dict_get(registry, &Value::Text("Point".into()))?
|
||||
.ok_or(invalid("missing Point type"))?,
|
||||
)?;
|
||||
for (name, circle) in [("inside", false), ("inCircle", true)] {
|
||||
let function = vm.allocate(ContextNativeFunction::new(
|
||||
name,
|
||||
PointMethod {
|
||||
expected: point_type,
|
||||
circle,
|
||||
signature: CallSignature::exact(
|
||||
if circle {
|
||||
vec![
|
||||
point,
|
||||
AnnotationType::Number,
|
||||
AnnotationType::Number,
|
||||
AnnotationType::Number,
|
||||
]
|
||||
} else {
|
||||
vec![point, bounds]
|
||||
},
|
||||
AnnotationType::Bool,
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
},
|
||||
vec![point_type],
|
||||
))?;
|
||||
roots.push(function);
|
||||
vm.attach_type(function, function_type)?;
|
||||
vm.define_method(point_type, name, function)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
use crate::{
|
||||
activity::Activity,
|
||||
developer_tools::{self, DeveloperToolsLayout, Workspace as DeveloperToolsState},
|
||||
display_list::DisplayList,
|
||||
document::RenderDocument,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SceneLayout {
|
||||
pub developer_tools: DeveloperToolsLayout,
|
||||
}
|
||||
|
||||
pub fn build_scene(
|
||||
width: u32,
|
||||
height: u32,
|
||||
scale: f32,
|
||||
document: &RenderDocument,
|
||||
developer_tools_state: &mut DeveloperToolsState,
|
||||
activity: &Activity,
|
||||
tab_chrome: crate::tabs::Chrome,
|
||||
) -> DisplayScene {
|
||||
let tool = document
|
||||
.frame
|
||||
.tabs
|
||||
.iter()
|
||||
.find(|tab| tab.active)
|
||||
.and_then(|tab| tab.developer_tool.as_deref());
|
||||
developer_tools_state.select(tool);
|
||||
developer_tools_state.document_updated(document);
|
||||
let mut display_list = document.display_list(scale).unwrap_or_else(|_| {
|
||||
RenderDocument::default()
|
||||
.display_list(scale)
|
||||
.expect("default document is valid")
|
||||
});
|
||||
let offset = crate::tabs::height(&document.frame.tabs);
|
||||
let inset = crate::tabs::INSET;
|
||||
let left = crate::tabs::RAIL;
|
||||
let content = crate::geometry::Rect::new(
|
||||
left * scale,
|
||||
offset * scale,
|
||||
(width as f32 - (left + inset) * scale).max(0.0),
|
||||
(height as f32 - (offset + inset) * scale).max(0.0),
|
||||
);
|
||||
display_list.translate(crate::geometry::Point::new(left * scale, offset * scale));
|
||||
let mut framed = DisplayList::default();
|
||||
use crate::display_list::DrawCommand;
|
||||
framed.push(DrawCommand::Clear(crate::system_ui::theme::BAR));
|
||||
framed.push(DrawCommand::PushClip(content));
|
||||
for command in display_list.commands() {
|
||||
if let DrawCommand::Clear(color) = command {
|
||||
framed.push(DrawCommand::FillRoundedRect {
|
||||
rect: content,
|
||||
radius: 10.0 * scale,
|
||||
color: *color,
|
||||
});
|
||||
} else {
|
||||
framed.push(command.clone());
|
||||
}
|
||||
}
|
||||
framed.push(DrawCommand::PopClip);
|
||||
let mut display_list = framed;
|
||||
crate::tabs::draw(
|
||||
tab_chrome.offset,
|
||||
&mut display_list,
|
||||
&document.frame.tabs,
|
||||
width as f32 / scale,
|
||||
scale,
|
||||
tab_chrome.pointer,
|
||||
&tab_chrome.visual,
|
||||
);
|
||||
if let Some(index) = tab_chrome.insertion {
|
||||
crate::tabs::draw_insertion(
|
||||
tab_chrome.offset,
|
||||
&mut display_list,
|
||||
&document.frame.tabs,
|
||||
width as f32 / scale,
|
||||
index,
|
||||
scale,
|
||||
);
|
||||
}
|
||||
let (mut developer_list, mut developer_layout) = developer_tools::build(
|
||||
width.saturating_sub(((left + inset) * scale) as u32),
|
||||
height.saturating_sub(((offset + inset) * scale) as u32),
|
||||
scale,
|
||||
document,
|
||||
developer_tools_state,
|
||||
activity,
|
||||
);
|
||||
developer_list.translate(crate::geometry::Point::new(left * scale, offset * scale));
|
||||
developer_layout.translate(left, offset);
|
||||
display_list.extend(developer_list);
|
||||
|
||||
DisplayScene {
|
||||
display_list,
|
||||
layout: SceneLayout {
|
||||
developer_tools: developer_layout,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DisplayScene {
|
||||
pub display_list: DisplayList,
|
||||
pub layout: SceneLayout,
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! Per-occurrence scroll state and a single geometry/clip projection shared by
|
||||
//! native paint, source paint and input. No business object is copied.
|
||||
use crate::{
|
||||
document::Frame,
|
||||
geometry::Point,
|
||||
layout::{self, Size},
|
||||
mount::{Mount, MountTable},
|
||||
ui_bridge::{UiKind, UiNode},
|
||||
};
|
||||
use anyhow::{Result, bail};
|
||||
use endor_core::{NativeContext, ObjectRef, Value, Vm, VmError, WeakObjectRef};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Axis {
|
||||
#[default]
|
||||
Both,
|
||||
Vertical,
|
||||
Horizontal,
|
||||
}
|
||||
impl Axis {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Both => "both",
|
||||
Self::Vertical => "vertical",
|
||||
Self::Horizontal => "horizontal",
|
||||
}
|
||||
}
|
||||
pub fn parse(name: &str) -> Result<Self, VmError> {
|
||||
match name {
|
||||
"both" => Ok(Self::Both),
|
||||
"vertical" => Ok(Self::Vertical),
|
||||
"horizontal" => Ok(Self::Horizontal),
|
||||
_ => Err(VmError::InvalidArgument(
|
||||
"ScrollBlock.axis expects both, vertical or horizontal",
|
||||
)),
|
||||
}
|
||||
}
|
||||
pub fn horizontal(self) -> bool {
|
||||
self != Self::Vertical
|
||||
}
|
||||
pub fn vertical(self) -> bool {
|
||||
self != Self::Horizontal
|
||||
}
|
||||
}
|
||||
|
||||
fn intersection(a: [f32; 4], b: [f32; 4]) -> [f32; 4] {
|
||||
let x = a[0].max(b[0]);
|
||||
let y = a[1].max(b[1]);
|
||||
[
|
||||
x,
|
||||
y,
|
||||
(a[0] + a[2]).min(b[0] + b[2]).max(x) - x,
|
||||
(a[1] + a[3]).min(b[1] + b[3]).max(y) - y,
|
||||
]
|
||||
}
|
||||
pub fn project(vm: &mut Vm, table: &MountTable, root: &UiNode, frame: &mut Frame) -> Result<()> {
|
||||
let mut nodes = HashMap::new();
|
||||
let mut work = vec![root];
|
||||
while let Some(node) = work.pop() {
|
||||
nodes.insert(node.block_id.as_str(), node);
|
||||
work.extend(node.children().iter().map(|node| node.as_ref()));
|
||||
}
|
||||
let indices: HashMap<_, _> = frame
|
||||
.mounts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, m)| (m.id, i))
|
||||
.collect();
|
||||
let scrolling: Vec<_> = frame
|
||||
.mounts
|
||||
.iter()
|
||||
.map(|m| matches!(nodes[m.block_id.as_str()].kind, UiKind::Scroll { .. }))
|
||||
.collect();
|
||||
let mut extent: Vec<_> = frame
|
||||
.mounts
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let padding = match nodes[m.block_id.as_str()].kind {
|
||||
UiKind::Scroll { padding, .. } => padding,
|
||||
_ => 0.0,
|
||||
};
|
||||
(m.x + m.width - padding, m.y + m.height - padding)
|
||||
})
|
||||
.collect();
|
||||
for i in (0..frame.mounts.len()).rev() {
|
||||
let m = &frame.mounts[i];
|
||||
if let Some(parent) = m.parent {
|
||||
let parent = indices[&parent];
|
||||
let e = if scrolling[i] {
|
||||
(m.x + m.width, m.y + m.height)
|
||||
} else {
|
||||
extent[i]
|
||||
};
|
||||
extent[parent].0 = extent[parent].0.max(e.0);
|
||||
extent[parent].1 = extent[parent].1.max(e.1);
|
||||
}
|
||||
}
|
||||
let mut contexts = HashMap::<u64, (f32, f32, Option<[f32; 4]>)>::new();
|
||||
frame.commands.clear();
|
||||
frame.command_clips.clear();
|
||||
for (i, m) in frame.mounts.iter_mut().enumerate() {
|
||||
let (dx, dy, clip) = m
|
||||
.parent
|
||||
.and_then(|id| contexts.get(&id).copied())
|
||||
.unwrap_or_default();
|
||||
let padding = match nodes[m.block_id.as_str()].kind {
|
||||
UiKind::Scroll { padding, .. } => padding,
|
||||
_ => 0.0,
|
||||
};
|
||||
let axis = match nodes[m.block_id.as_str()].kind {
|
||||
UiKind::Scroll { axis, .. } => axis,
|
||||
_ => Axis::Both,
|
||||
};
|
||||
let limits = [
|
||||
if axis.horizontal() {
|
||||
(extent[i].0 + padding - m.x - m.width).max(0.0)
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
if axis.vertical() {
|
||||
(extent[i].1 + padding - m.y - m.height).max(0.0)
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
];
|
||||
m.x -= dx;
|
||||
m.y -= dy;
|
||||
m.clip = clip;
|
||||
let mut child = (dx, dy, clip);
|
||||
if scrolling[i] {
|
||||
let weak = table
|
||||
.active
|
||||
.get(&m.id)
|
||||
.ok_or_else(|| anyhow::anyhow!("missing scroll Mount"))?;
|
||||
let owner = vm
|
||||
.upgrade(*weak)?
|
||||
.ok_or_else(|| anyhow::anyhow!("expired scroll Mount"))?;
|
||||
let offset = vm
|
||||
.payload::<Mount>(owner, "Mount")
|
||||
.map(|mount| mount.scroll_offset);
|
||||
vm.release(owner)?;
|
||||
let offset = offset?;
|
||||
let x = offset[0].clamp(0.0, limits[0]);
|
||||
let y = offset[1].clamp(0.0, limits[1]);
|
||||
m.scroll = Some([x, y, limits[0], limits[1]]);
|
||||
let viewport = [m.x, m.y, m.width, m.height];
|
||||
child = (
|
||||
dx + x,
|
||||
dy + y,
|
||||
Some(
|
||||
clip.map(|clip| intersection(clip, viewport))
|
||||
.unwrap_or(viewport),
|
||||
),
|
||||
);
|
||||
}
|
||||
contexts.insert(m.id, child);
|
||||
if let Some(command) = layout::paint_native(
|
||||
nodes[m.block_id.as_str()],
|
||||
m.x,
|
||||
m.y,
|
||||
Size {
|
||||
width: m.width,
|
||||
height: m.height,
|
||||
},
|
||||
) {
|
||||
frame.commands.push(command);
|
||||
frame.command_clips.push(m.clip);
|
||||
}
|
||||
}
|
||||
if frame.commands.len() > 10_000 {
|
||||
bail!("scroll paint command budget exceeded");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn coordinate(value: &Value) -> Result<f32, VmError> {
|
||||
let Value::Number(value) = value else {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"scroll coordinates must be numbers",
|
||||
));
|
||||
};
|
||||
let n = value
|
||||
.to_string()
|
||||
.parse::<f32>()
|
||||
.map_err(|_| VmError::InvalidArgument("invalid scroll coordinate"))?;
|
||||
if !n.is_finite() || n.abs() > 1_000_000.0 {
|
||||
return Err(VmError::InvalidArgument("scroll coordinate exceeds limits"));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
pub fn set(
|
||||
cx: &mut NativeContext<'_>,
|
||||
owner: ObjectRef,
|
||||
desktop: WeakObjectRef,
|
||||
point: [f32; 2],
|
||||
relative: bool,
|
||||
) -> Result<(), VmError> {
|
||||
let mut mount = cx.store().payload::<Mount>(owner, "Mount")?.clone();
|
||||
if !mount.mounted || mount.layout.is_some() {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"scroll requires committed attached Mount",
|
||||
));
|
||||
}
|
||||
let bounds = mount
|
||||
.geometry
|
||||
.scroll
|
||||
.ok_or(VmError::InvalidArgument("Mount is not scrollable"))?;
|
||||
let next = if relative {
|
||||
[
|
||||
mount.scroll_offset[0] + point[0],
|
||||
mount.scroll_offset[1] + point[1],
|
||||
]
|
||||
} else {
|
||||
point
|
||||
};
|
||||
mount.scroll_offset = [next[0].clamp(0.0, bounds[2]), next[1].clamp(0.0, bounds[3])];
|
||||
let desktop = cx
|
||||
.upgrade(desktop)?
|
||||
.ok_or(VmError::InvalidArgument("Mount window expired"))?;
|
||||
// Check the normal mutation barrier even when the clamped result is equal.
|
||||
cx.replace_payload(owner, mount)?;
|
||||
cx.set_attr(desktop, "scrollRequested", Value::Bool(true))
|
||||
}
|
||||
pub fn into_view(
|
||||
cx: &mut NativeContext<'_>,
|
||||
owner: ObjectRef,
|
||||
desktop: WeakObjectRef,
|
||||
) -> Result<(), VmError> {
|
||||
let mount = cx.store().payload::<Mount>(owner, "Mount")?.clone();
|
||||
if !mount.mounted || mount.layout.is_some() {
|
||||
return Err(VmError::InvalidArgument(
|
||||
"scrollIntoView requires committed attached Mount",
|
||||
));
|
||||
}
|
||||
let mut rect = [
|
||||
mount.geometry.x,
|
||||
mount.geometry.y,
|
||||
mount.geometry.width,
|
||||
mount.geometry.height,
|
||||
];
|
||||
let mut parent = mount.parent;
|
||||
while let Some(weak) = parent {
|
||||
let Some(owner) = cx.upgrade(weak)? else {
|
||||
break;
|
||||
};
|
||||
let mount = cx.store().payload::<Mount>(owner, "Mount")?.clone();
|
||||
parent = mount.parent;
|
||||
if let Some(offset) = mount.geometry.scroll {
|
||||
let delta = |start: f32, length: f32, viewport: f32, size: f32| {
|
||||
if start < viewport {
|
||||
start - viewport
|
||||
} else {
|
||||
(start + length - viewport - size).max(0.0)
|
||||
}
|
||||
};
|
||||
let dx = delta(rect[0], rect[2], mount.geometry.x, mount.geometry.width);
|
||||
let dy = delta(rect[1], rect[3], mount.geometry.y, mount.geometry.height);
|
||||
let x = (offset[0] + dx).clamp(0.0, offset[2]);
|
||||
let y = (offset[1] + dy).clamp(0.0, offset[3]);
|
||||
rect[0] -= x - offset[0];
|
||||
rect[1] -= y - offset[1];
|
||||
if x != offset[0] || y != offset[1] {
|
||||
set(cx, owner, desktop, [x, y], false)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn wheel_target(frame: &Frame, point: Point, delta: [f32; 2]) -> Option<u64> {
|
||||
let indices: HashMap<_, _> = frame.mounts.iter().map(|mount| (mount.id, mount)).collect();
|
||||
let mut current = frame
|
||||
.mounts
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|mount| mount.contains(point));
|
||||
while let Some(mount) = current {
|
||||
if mount.scroll.is_some_and(|s| {
|
||||
(s[0] + delta[0]).clamp(0.0, s[2]) != s[0] || (s[1] + delta[1]).clamp(0.0, s[3]) != s[1]
|
||||
}) {
|
||||
return Some(mount.id);
|
||||
}
|
||||
current = mount.parent.and_then(|id| indices.get(&id).copied());
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
use crate::{
|
||||
display_list::{Color, DisplayList, DrawCommand},
|
||||
geometry::{Point, Rect},
|
||||
text::{self, TextStyle},
|
||||
};
|
||||
|
||||
pub struct SoftwareRenderer;
|
||||
|
||||
impl SoftwareRenderer {
|
||||
pub fn render(list: &DisplayList, target: &mut [u32], width: u32, height: u32) {
|
||||
let mut canvas = Canvas {
|
||||
pixels: target,
|
||||
width,
|
||||
height,
|
||||
clip: Rect::new(0.0, 0.0, width as f32, height as f32),
|
||||
};
|
||||
let mut clips = Vec::new();
|
||||
|
||||
for command in list.commands() {
|
||||
match command {
|
||||
DrawCommand::PushClip(rect) => {
|
||||
clips.push(canvas.clip);
|
||||
let x = canvas.clip.x.max(rect.x);
|
||||
let y = canvas.clip.y.max(rect.y);
|
||||
canvas.clip = Rect::new(
|
||||
x,
|
||||
y,
|
||||
(canvas.clip.x + canvas.clip.width)
|
||||
.min(rect.x + rect.width)
|
||||
.max(x)
|
||||
- x,
|
||||
(canvas.clip.y + canvas.clip.height)
|
||||
.min(rect.y + rect.height)
|
||||
.max(y)
|
||||
- y,
|
||||
);
|
||||
}
|
||||
DrawCommand::PopClip => {
|
||||
if let Some(clip) = clips.pop() {
|
||||
canvas.clip = clip;
|
||||
}
|
||||
}
|
||||
DrawCommand::Clear(color) => canvas.clear(*color),
|
||||
DrawCommand::FillRoundedRect {
|
||||
rect,
|
||||
radius,
|
||||
color,
|
||||
} => canvas.fill_rounded_rect(*rect, *radius, *color),
|
||||
DrawCommand::StrokeRoundedRect {
|
||||
rect,
|
||||
radius,
|
||||
width,
|
||||
color,
|
||||
} => canvas.stroke_rounded_rect(*rect, *radius, *width, *color),
|
||||
DrawCommand::WrappedText {
|
||||
rect,
|
||||
value,
|
||||
style,
|
||||
color,
|
||||
} => canvas.draw_wrapped_text(*rect, value, *style, *color),
|
||||
DrawCommand::Text {
|
||||
origin,
|
||||
value,
|
||||
style,
|
||||
color,
|
||||
} => canvas.draw_text(*origin, value, *style, *color),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Canvas<'a> {
|
||||
pixels: &'a mut [u32],
|
||||
width: u32,
|
||||
height: u32,
|
||||
clip: Rect,
|
||||
}
|
||||
|
||||
impl Canvas<'_> {
|
||||
fn clear(&mut self, color: Color) {
|
||||
self.pixels.fill(pack(color));
|
||||
}
|
||||
|
||||
fn fill_rounded_rect(&mut self, rect: Rect, radius: f32, color: Color) {
|
||||
let bounds = self.clamped_bounds(rect);
|
||||
let radius = radius.max(0.0).min(rect.width / 2.0).min(rect.height / 2.0);
|
||||
for y in bounds.1..bounds.3 {
|
||||
for x in bounds.0..bounds.2 {
|
||||
if rounded_rect_contains(rect, radius, x as f32 + 0.5, y as f32 + 0.5) {
|
||||
self.blend_pixel(x, y, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn stroke_rounded_rect(&mut self, rect: Rect, radius: f32, width: f32, color: Color) {
|
||||
let bounds = self.clamped_bounds(rect);
|
||||
let width = width.max(1.0).min(rect.width / 2.0).min(rect.height / 2.0);
|
||||
let outer_radius = radius.max(0.0).min(rect.width / 2.0).min(rect.height / 2.0);
|
||||
let inner = Rect::new(
|
||||
rect.x + width,
|
||||
rect.y + width,
|
||||
(rect.width - width * 2.0).max(0.0),
|
||||
(rect.height - width * 2.0).max(0.0),
|
||||
);
|
||||
let inner_radius = (outer_radius - width).max(0.0);
|
||||
|
||||
for y in bounds.1..bounds.3 {
|
||||
for x in bounds.0..bounds.2 {
|
||||
let px = x as f32 + 0.5;
|
||||
let py = y as f32 + 0.5;
|
||||
if rounded_rect_contains(rect, outer_radius, px, py)
|
||||
&& !rounded_rect_contains(inner, inner_radius, px, py)
|
||||
{
|
||||
self.blend_pixel(x, y, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_text(&mut self, origin: Point, value: &str, style: TextStyle, color: Color) {
|
||||
let x = origin.x.round() as i32;
|
||||
let y = origin.y.round() as i32;
|
||||
text::draw(value, style, color, |dx, dy, pixel| {
|
||||
self.blend_pixel(x + dx, y + dy, pixel)
|
||||
});
|
||||
}
|
||||
|
||||
fn draw_wrapped_text(&mut self, rect: Rect, value: &str, style: TextStyle, color: Color) {
|
||||
if rect.width <= 0.0 || rect.height <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let old = self.clip;
|
||||
let x = old.x.max(rect.x);
|
||||
let y = old.y.max(rect.y);
|
||||
self.clip = Rect::new(
|
||||
x,
|
||||
y,
|
||||
((old.x + old.width).min(rect.x + rect.width) - x).max(0.0),
|
||||
((old.y + old.height).min(rect.y + rect.height) - y).max(0.0),
|
||||
);
|
||||
let left = rect.x.round() as i32;
|
||||
let top = rect.y.round() as i32;
|
||||
text::draw_wrapped(value, style, color, rect.width, |dx, dy, pixel| {
|
||||
self.blend_pixel(left + dx, top + dy, pixel)
|
||||
});
|
||||
self.clip = old;
|
||||
}
|
||||
|
||||
fn clamped_bounds(&self, rect: Rect) -> (i32, i32, i32, i32) {
|
||||
(
|
||||
rect.x.max(self.clip.x).max(0.0).floor() as i32,
|
||||
rect.y.max(self.clip.y).max(0.0).floor() as i32,
|
||||
(rect.x + rect.width)
|
||||
.min(self.clip.x + self.clip.width)
|
||||
.min(self.width as f32)
|
||||
.ceil() as i32,
|
||||
(rect.y + rect.height)
|
||||
.min(self.clip.y + self.clip.height)
|
||||
.min(self.height as f32)
|
||||
.ceil() as i32,
|
||||
)
|
||||
}
|
||||
|
||||
fn blend_pixel(&mut self, x: i32, y: i32, source: Color) {
|
||||
if x < 0
|
||||
|| y < 0
|
||||
|| x >= self.width as i32
|
||||
|| y >= self.height as i32
|
||||
|| source.alpha == 0
|
||||
|| (x as f32) < self.clip.x
|
||||
|| (y as f32) < self.clip.y
|
||||
|| (x as f32) >= self.clip.x + self.clip.width
|
||||
|| (y as f32) >= self.clip.y + self.clip.height
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let index = y as usize * self.width as usize + x as usize;
|
||||
if source.alpha == 255 {
|
||||
self.pixels[index] = pack(source);
|
||||
return;
|
||||
}
|
||||
|
||||
let destination = self.pixels[index];
|
||||
let dst_red = (destination >> 16) & 0xff;
|
||||
let dst_green = (destination >> 8) & 0xff;
|
||||
let dst_blue = destination & 0xff;
|
||||
let alpha = source.alpha as u32;
|
||||
let inverse = 255 - alpha;
|
||||
let red = (source.red as u32 * alpha + dst_red * inverse) / 255;
|
||||
let green = (source.green as u32 * alpha + dst_green * inverse) / 255;
|
||||
let blue = (source.blue as u32 * alpha + dst_blue * inverse) / 255;
|
||||
self.pixels[index] = (red << 16) | (green << 8) | blue;
|
||||
}
|
||||
}
|
||||
|
||||
fn rounded_rect_contains(rect: Rect, radius: f32, x: f32, y: f32) -> bool {
|
||||
if rect.width <= 0.0 || rect.height <= 0.0 {
|
||||
return false;
|
||||
}
|
||||
if radius <= 0.0 {
|
||||
return x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y + rect.height;
|
||||
}
|
||||
|
||||
// Clamp in local coordinates: adding a large origin to a shrinking tab's
|
||||
// half-width can otherwise round the lower bound above the upper bound.
|
||||
let radius = radius.min(rect.width / 2.0).min(rect.height / 2.0);
|
||||
let local_x = x - rect.x;
|
||||
let local_y = y - rect.y;
|
||||
let dx = local_x - local_x.clamp(radius, rect.width - radius);
|
||||
let dy = local_y - local_y.clamp(radius, rect.height - radius);
|
||||
dx * dx + dy * dy <= radius * radius
|
||||
}
|
||||
|
||||
fn pack(color: Color) -> u32 {
|
||||
(color.red as u32) << 16 | (color.green as u32) << 8 | color.blue as u32
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wrapped_text_uses_multiple_lines_respects_nested_clips_and_restores_the_clip() {
|
||||
let mut list = DisplayList::default();
|
||||
list.push(DrawCommand::Clear(Color::rgb(255, 255, 255)));
|
||||
list.push(DrawCommand::PushClip(Rect::new(12.0, 5.0, 20.0, 40.0)));
|
||||
list.push(DrawCommand::WrappedText {
|
||||
rect: Rect::new(10.0, 5.0, 32.0, 40.0),
|
||||
value: "MMMMMMMMMMMMMMMM".into(),
|
||||
style: TextStyle::ui(1),
|
||||
color: Color::rgb(0, 0, 0),
|
||||
});
|
||||
list.push(DrawCommand::PopClip);
|
||||
list.push(DrawCommand::WrappedText {
|
||||
rect: Rect::new(60.0, 0.0, 0.0, 40.0),
|
||||
value: "invisible".into(),
|
||||
style: TextStyle::ui(1),
|
||||
color: Color::rgb(0, 0, 0),
|
||||
});
|
||||
list.push(DrawCommand::FillRoundedRect {
|
||||
rect: Rect::new(70.0, 50.0, 2.0, 2.0),
|
||||
radius: 0.0,
|
||||
color: Color::rgb(0, 0, 255),
|
||||
});
|
||||
let mut pixels = vec![0; 80 * 60];
|
||||
SoftwareRenderer::render(&list, &mut pixels, 80, 60);
|
||||
let mut second_line = false;
|
||||
for y in 0..60 {
|
||||
for x in 0..80 {
|
||||
let color = pixels[y * 80 + x];
|
||||
if color != 0xffffff && color != 0x0000ff {
|
||||
assert!((12..32).contains(&x) && (5..45).contains(&y));
|
||||
second_line |= y >= 25;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(second_line);
|
||||
assert_eq!(pixels[50 * 80 + 70], 0x0000ff);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renderer_changes_pixels_inside_a_rectangle() {
|
||||
let mut list = DisplayList::default();
|
||||
list.push(DrawCommand::Clear(Color::rgb(0, 0, 0)));
|
||||
list.push(DrawCommand::FillRoundedRect {
|
||||
rect: Rect::new(1.0, 1.0, 2.0, 2.0),
|
||||
radius: 0.0,
|
||||
color: Color::rgb(255, 0, 0),
|
||||
});
|
||||
let mut pixels = vec![0; 16];
|
||||
SoftwareRenderer::render(&list, &mut pixels, 4, 4);
|
||||
assert_eq!(pixels[5], 0x00ff0000);
|
||||
assert_eq!(pixels[0], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_edges_are_antialiased_and_respect_opacity() {
|
||||
let mut list = DisplayList::default();
|
||||
list.push(DrawCommand::Clear(Color::rgb(0, 0, 0)));
|
||||
list.push(DrawCommand::Text {
|
||||
origin: Point::new(2.0, 2.0),
|
||||
value: "Hello 中文".into(),
|
||||
style: TextStyle::ui(1).scaled(1.25),
|
||||
color: Color::rgba(255, 255, 255, 128),
|
||||
});
|
||||
let mut pixels = vec![0; 256 * 48];
|
||||
SoftwareRenderer::render(&list, &mut pixels, 256, 48);
|
||||
assert!(pixels.iter().any(|pixel| *pixel > 0));
|
||||
assert!(pixels.iter().all(|pixel| (pixel & 255) <= 128));
|
||||
assert!(pixels.iter().any(|pixel| (1..128).contains(&(pixel & 255))));
|
||||
|
||||
let mut invisible = DisplayList::default();
|
||||
invisible.push(DrawCommand::Text {
|
||||
origin: Point::new(2.0, 2.0),
|
||||
value: "Hello 中文".into(),
|
||||
style: TextStyle::ui(1),
|
||||
color: Color::rgba(255, 255, 255, 0),
|
||||
});
|
||||
let mut pixels = vec![0; 256 * 48];
|
||||
SoftwareRenderer::render(&invisible, &mut pixels, 256, 48);
|
||||
assert!(pixels.iter().all(|pixel| *pixel == 0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
//! Resolve pointer targets in paint order through source/native hitTest methods.
|
||||
//! Both press and release selectors share one read-only VM call and budget.
|
||||
use crate::{mount::Mount, ui_bridge::attach_desktop_type};
|
||||
use endor_core::{
|
||||
CodeLayout, ContextNativeFunction, EndorCode, EndorCodeObject, Instruction, NativeCallable,
|
||||
NativeContext, NativeResult, ObjectRef, Opcode, Value, Vm, VmError, WeakObjectRef,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Boolean;
|
||||
impl NativeCallable for Boolean {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(1))
|
||||
}
|
||||
|
||||
fn invoke(&self, _: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let [Value::Bool(value)] = args else {
|
||||
return Err(VmError::InvalidArgument("hitTest must return Bool"));
|
||||
};
|
||||
Ok(NativeResult::Return(Value::Bool(*value)))
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct SameTarget;
|
||||
impl NativeCallable for SameTarget {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(2))
|
||||
}
|
||||
|
||||
fn invoke(&self, _: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let value = match args {
|
||||
[Value::Object(first), Value::Object(second)] if first == second => {
|
||||
Value::Object(*first)
|
||||
}
|
||||
_ => Value::Nil,
|
||||
};
|
||||
Ok(NativeResult::Return(value))
|
||||
}
|
||||
}
|
||||
fn code(
|
||||
cx: &mut NativeContext<'_>,
|
||||
instructions: Vec<Instruction>,
|
||||
constants: Vec<Value>,
|
||||
layout: CodeLayout,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
let code = EndorCode::from_instructions(&instructions, constants, layout)?.with_location(
|
||||
"<pointer hitTest>",
|
||||
"<tessera>",
|
||||
1,
|
||||
);
|
||||
let code = cx.allocate(EndorCodeObject::new(code))?;
|
||||
let globals = cx.new_dict()?;
|
||||
cx.new_function("pointer hitTest", code, globals)
|
||||
}
|
||||
fn selector(
|
||||
cx: &mut NativeContext<'_>,
|
||||
candidates: &[WeakObjectRef],
|
||||
point: [f32; 2],
|
||||
desktop: ObjectRef,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
let validate = cx.allocate(ContextNativeFunction::new(
|
||||
"validate hitTest",
|
||||
Boolean,
|
||||
vec![],
|
||||
))?;
|
||||
let mut instructions = Vec::new();
|
||||
let mut constants = vec![Value::Object(validate)];
|
||||
for weak in candidates.iter().rev() {
|
||||
let mount = cx
|
||||
.upgrade(*weak)?
|
||||
.ok_or(VmError::InvalidArgument("pointer Mount expired"))?;
|
||||
let target = cx.store().payload::<Mount>(mount, "Mount")?.clone();
|
||||
if !target.mounted
|
||||
|| !target.geometry.interactive
|
||||
|| !target
|
||||
.geometry
|
||||
.contains(crate::geometry::Point::new(point[0], point[1]))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let geometry = &target.geometry;
|
||||
let x = point[0] - geometry.x;
|
||||
let y = point[1] - geometry.y;
|
||||
if x < 0.0 || y < 0.0 || x > geometry.width || y > geometry.height {
|
||||
continue;
|
||||
}
|
||||
let definition = cx
|
||||
.store()
|
||||
.type_of(target.block)?
|
||||
.ok_or(VmError::InvalidArgument("untyped hit target"))?;
|
||||
let function = cx
|
||||
.store()
|
||||
.lookup_method(definition, "hitTest")?
|
||||
.ok_or(VmError::InvalidArgument("missing hitTest method"))?;
|
||||
let local = cx.new_object()?;
|
||||
attach_desktop_type(cx, local, "Point", desktop)?;
|
||||
cx.set_attr(local, "x", Value::Number((x as f64).into()))?;
|
||||
cx.set_attr(local, "y", Value::Number((y as f64).into()))?;
|
||||
let start = constants.len() as u32;
|
||||
constants.extend([
|
||||
Value::Object(function),
|
||||
Value::Object(target.block),
|
||||
Value::Object(mount),
|
||||
Value::Object(local),
|
||||
]);
|
||||
let skip = (Instruction::encode_all(&[
|
||||
Instruction::new(Opcode::LoadConst, start + 2),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
])?
|
||||
.len()
|
||||
/ 2) as u32;
|
||||
instructions.extend([
|
||||
Instruction::new(Opcode::LoadConst, 0),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
Instruction::new(Opcode::LoadConst, start),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
Instruction::new(Opcode::LoadConst, start + 1),
|
||||
Instruction::new(Opcode::LoadConst, start + 2),
|
||||
Instruction::new(Opcode::LoadConst, start + 3),
|
||||
Instruction::new(Opcode::Call, 3),
|
||||
Instruction::new(Opcode::Call, 1),
|
||||
Instruction::new(Opcode::PopJumpIfFalse, skip),
|
||||
Instruction::new(Opcode::LoadConst, start + 2),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
]);
|
||||
}
|
||||
let end = constants.len() as u32;
|
||||
constants.push(Value::Nil);
|
||||
instructions.extend([
|
||||
Instruction::new(Opcode::LoadConst, end),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
]);
|
||||
code(cx, instructions, constants, CodeLayout::default())
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Prepare {
|
||||
candidates: Vec<WeakObjectRef>,
|
||||
press: [f32; 2],
|
||||
release: [f32; 2],
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for Prepare {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let down = selector(cx, &self.candidates, self.press, self.desktop)?;
|
||||
let up = selector(cx, &self.candidates, self.release, self.desktop)?;
|
||||
let compare = cx.allocate(ContextNativeFunction::new(
|
||||
"same pointer target",
|
||||
SameTarget,
|
||||
vec![],
|
||||
))?;
|
||||
let instructions = vec![
|
||||
Instruction::new(Opcode::LoadConst, 0),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
Instruction::new(Opcode::Call, 0),
|
||||
Instruction::new(Opcode::StoreFast, 0),
|
||||
Instruction::new(Opcode::LoadConst, 1),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
Instruction::new(Opcode::Call, 0),
|
||||
Instruction::new(Opcode::StoreFast, 1),
|
||||
Instruction::new(Opcode::LoadConst, 2),
|
||||
Instruction::simple(Opcode::PushNull),
|
||||
Instruction::new(Opcode::LoadFast, 0),
|
||||
Instruction::new(Opcode::LoadFast, 1),
|
||||
Instruction::new(Opcode::Call, 2),
|
||||
Instruction::simple(Opcode::ReturnValue),
|
||||
];
|
||||
let driver = code(
|
||||
cx,
|
||||
instructions,
|
||||
vec![
|
||||
Value::Object(down),
|
||||
Value::Object(up),
|
||||
Value::Object(compare),
|
||||
],
|
||||
CodeLayout {
|
||||
locals: vec!["press".into(), "release".into()],
|
||||
..CodeLayout::default()
|
||||
},
|
||||
)?;
|
||||
Ok(NativeResult::Invoke {
|
||||
function: driver,
|
||||
arguments: vec![],
|
||||
})
|
||||
}
|
||||
}
|
||||
/// Returned Mount owns one root. No-hit and mismatched targets return None.
|
||||
pub fn resolve(
|
||||
vm: &mut Vm,
|
||||
desktop: ObjectRef,
|
||||
candidates: Vec<WeakObjectRef>,
|
||||
press: [f32; 2],
|
||||
release: [f32; 2],
|
||||
) -> anyhow::Result<Option<ObjectRef>> {
|
||||
let prepare = vm.allocate(ContextNativeFunction::new(
|
||||
"prepare pointer hitTest",
|
||||
Prepare {
|
||||
candidates,
|
||||
press,
|
||||
release,
|
||||
desktop,
|
||||
},
|
||||
vec![desktop],
|
||||
))?;
|
||||
let result = vm.call_read_only_with_limits(
|
||||
prepare,
|
||||
&[],
|
||||
endor_core::ExecutionLimits {
|
||||
max_frames: 128,
|
||||
max_instructions: 1_000_000,
|
||||
},
|
||||
);
|
||||
vm.release(prepare)?;
|
||||
let (value, _) = result.map_err(|error| crate::endor_host::runtime_error(vm, error))?;
|
||||
match value {
|
||||
Value::Object(mount) => Ok(Some(mount)),
|
||||
Value::Nil => Ok(None),
|
||||
value => {
|
||||
vm.release_value(value)?;
|
||||
anyhow::bail!("invalid hitTest target")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,984 @@
|
||||
//! Bottom-up measurement and top-down arrangement share one read-only VM call.
|
||||
//! The host scratch plan contains derived data only, never a second business heap.
|
||||
use crate::{
|
||||
document::Frame,
|
||||
layout::{self, LayoutRuntime, Size},
|
||||
mount::Mount,
|
||||
native_visual::{number, record, value},
|
||||
object_list,
|
||||
ui_bridge::{MAX_DIMENSION, UiNode, desktop_type},
|
||||
};
|
||||
use anyhow::Result;
|
||||
use endor_core::{
|
||||
ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectRef, Value, Vm,
|
||||
VmError, WeakObjectRef,
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeSet, HashMap, HashSet},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
// Small native trees keep the allocation-free fast path. Larger trees use the
|
||||
// same per-occurrence VM driver so even intrinsic work can yield between nodes.
|
||||
const NATIVE_FAST_PATH_MAX_NODES: usize = 64;
|
||||
|
||||
fn invalid(message: &'static str) -> VmError {
|
||||
VmError::InvalidArgument(message)
|
||||
}
|
||||
fn desktop_type_registry(cx: &NativeContext<'_>, desktop: ObjectRef) -> Result<ObjectRef, VmError> {
|
||||
match cx.store().get_attr(desktop, "types")? {
|
||||
Value::Object(object) => Ok(object),
|
||||
_ => Err(invalid("missing type registry")),
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
struct Measurement {
|
||||
owner: ObjectRef,
|
||||
method: ObjectRef,
|
||||
children: Vec<Size>,
|
||||
constraints: [f32; 4],
|
||||
size: Size,
|
||||
reads: Vec<endor_core::ReadDependency>,
|
||||
}
|
||||
/// Borrowed identities and versions only: this cache adds no managed roots.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Cache {
|
||||
entries: HashMap<WeakObjectRef, Measurement>,
|
||||
pub hits: usize,
|
||||
pub misses: usize,
|
||||
}
|
||||
impl Cache {
|
||||
pub(crate) fn exclude_host_desktops(&mut self, desktops: &HashSet<ObjectRef>) {
|
||||
for entry in self.entries.values_mut() {
|
||||
entry
|
||||
.reads
|
||||
.retain(|read| !desktops.contains(&read.object()));
|
||||
}
|
||||
}
|
||||
pub fn invalidate(&mut self, owners: &HashSet<ObjectRef>) {
|
||||
self.entries
|
||||
.retain(|_, entry| !owners.contains(&entry.owner));
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.entries.clear();
|
||||
self.hits = 0;
|
||||
self.misses = 0;
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Pending {
|
||||
token: usize,
|
||||
owner: ObjectRef,
|
||||
method: ObjectRef,
|
||||
children: Vec<Size>,
|
||||
constraints: [f32; 4],
|
||||
key: WeakObjectRef,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Plan {
|
||||
nodes: Vec<Arc<UiNode>>,
|
||||
children: Vec<Vec<usize>>,
|
||||
sizes: Vec<Size>,
|
||||
preferred: Vec<Option<Size>>,
|
||||
bounds: Vec<Option<[f32; 4]>>,
|
||||
runtime: LayoutRuntime,
|
||||
custom: bool,
|
||||
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>,
|
||||
native_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)]
|
||||
enum Phase {
|
||||
Measure,
|
||||
Arrange,
|
||||
}
|
||||
impl Phase {
|
||||
fn method(self) -> &'static str {
|
||||
match self {
|
||||
Self::Measure => "measure",
|
||||
Self::Arrange => "arrange",
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Step {
|
||||
plan: Shared,
|
||||
index: usize,
|
||||
phase: Phase,
|
||||
mount: ObjectRef,
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for Step {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let mount = cx.store().payload::<Mount>(self.mount, "Mount")?.clone();
|
||||
let definition = cx
|
||||
.store()
|
||||
.type_of(mount.block)?
|
||||
.ok_or(invalid("untyped layout target"))?;
|
||||
let method = cx
|
||||
.store()
|
||||
.lookup_method(definition, self.phase.method())?
|
||||
.ok_or(invalid("missing layout method"))?;
|
||||
let intrinsic = crate::native_visual::is_intrinsic(
|
||||
cx.store(),
|
||||
method,
|
||||
self.phase.method(),
|
||||
self.desktop,
|
||||
)?;
|
||||
let (node, children, preferred, bounds, native_size) = {
|
||||
let mut plan = self
|
||||
.plan
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout plan poisoned"))?;
|
||||
let node = plan.nodes[self.index].clone();
|
||||
let children = plan.children[self.index]
|
||||
.iter()
|
||||
.map(|child| plan.sizes[*child])
|
||||
.collect::<Vec<_>>();
|
||||
let preferred = plan.children[self.index]
|
||||
.iter()
|
||||
.map(|child| plan.preferred[*child].unwrap_or(plan.sizes[*child]))
|
||||
.collect::<Vec<_>>();
|
||||
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] = !intrinsic;
|
||||
}
|
||||
let native_size = if matches!(self.phase, Phase::Measure) && intrinsic {
|
||||
let constraints = plan.constraints[self.index];
|
||||
Some(
|
||||
plan.runtime
|
||||
.measure_node(&node, children.clone(), constraints)
|
||||
.map_err(|_| invalid("native measurement exceeds layout limits"))?,
|
||||
)
|
||||
} else {
|
||||
if !intrinsic {
|
||||
plan.custom = true;
|
||||
}
|
||||
if matches!(self.phase, Phase::Measure) {
|
||||
let key = cx.store().downgrade(self.mount)?;
|
||||
let constraints = plan.constraints[self.index];
|
||||
let cached =
|
||||
plan.cache
|
||||
.entries
|
||||
.get(&key)
|
||||
.filter(|entry| {
|
||||
entry.owner == mount.block
|
||||
&& entry.method == method
|
||||
&& entry.children == children
|
||||
&& entry.constraints == constraints
|
||||
&& entry.reads.iter().all(|dependency| {
|
||||
cx.store().read_dependency_valid(dependency)
|
||||
})
|
||||
})
|
||||
.map(|entry| entry.size);
|
||||
if let Some(size) = cached {
|
||||
plan.cache.hits += 1;
|
||||
Some(size)
|
||||
} else {
|
||||
plan.cache.misses += 1;
|
||||
plan.runtime.measured += 1;
|
||||
plan.pending[self.index] = Some(Pending {
|
||||
token: 0,
|
||||
owner: mount.block,
|
||||
method,
|
||||
children: children.clone(),
|
||||
constraints,
|
||||
key,
|
||||
});
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if matches!(self.phase, Phase::Arrange) {
|
||||
plan.runtime.arranged += 1;
|
||||
plan.native_arrange[self.index] = intrinsic;
|
||||
plan.custom_arrange[self.index] =
|
||||
!intrinsic || node.children().iter().any(|child| child.has_flex());
|
||||
}
|
||||
(node, children, preferred, bounds, native_size)
|
||||
};
|
||||
let context = mount.layout.ok_or(invalid("missing pre-layout context"))?;
|
||||
{
|
||||
let mut context = context
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout context poisoned"))?;
|
||||
context.node = Some(node);
|
||||
context.children = children;
|
||||
context.preferred = preferred;
|
||||
context.bounds = bounds;
|
||||
}
|
||||
if let Some(size) = native_size {
|
||||
return Ok(NativeResult::Return(Value::Object(record(
|
||||
cx,
|
||||
self.desktop,
|
||||
"MeasureResult",
|
||||
vec![("width", value(size.width)), ("height", value(size.height))],
|
||||
)?)));
|
||||
}
|
||||
let input = match self.phase {
|
||||
Phase::Measure => {
|
||||
let constraints = self
|
||||
.plan
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout plan poisoned"))?
|
||||
.constraints[self.index];
|
||||
record(
|
||||
cx,
|
||||
self.desktop,
|
||||
"Constraints",
|
||||
vec![
|
||||
("minWidth", value(constraints[0])),
|
||||
("minHeight", value(constraints[1])),
|
||||
("maxWidth", value(constraints[2])),
|
||||
("maxHeight", value(constraints[3])),
|
||||
],
|
||||
)?
|
||||
}
|
||||
Phase::Arrange => {
|
||||
let [x, y, width, height] =
|
||||
bounds.ok_or(invalid("arrangement has no allocated bounds"))?;
|
||||
record(
|
||||
cx,
|
||||
self.desktop,
|
||||
"Bounds",
|
||||
vec![
|
||||
("x", value(x)),
|
||||
("y", value(y)),
|
||||
("width", value(width)),
|
||||
("height", value(height)),
|
||||
],
|
||||
)?
|
||||
}
|
||||
};
|
||||
if matches!(self.phase, Phase::Measure) {
|
||||
let token = cx.store().begin_read_tracking()?;
|
||||
self.plan
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout plan poisoned"))?
|
||||
.pending[self.index]
|
||||
.as_mut()
|
||||
.ok_or(invalid("missing measurement tracking state"))?
|
||||
.token = token;
|
||||
}
|
||||
Ok(NativeResult::Invoke {
|
||||
function: method,
|
||||
arguments: vec![
|
||||
Value::Object(mount.block),
|
||||
Value::Object(self.mount),
|
||||
Value::Object(input),
|
||||
],
|
||||
})
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Collect {
|
||||
plan: Shared,
|
||||
index: usize,
|
||||
phase: Phase,
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for Collect {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(1))
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let pending = if matches!(self.phase, Phase::Measure) {
|
||||
self.plan
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout plan poisoned"))?
|
||||
.pending[self.index]
|
||||
.take()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let [Value::Object(result)] = args else {
|
||||
return Err(invalid("layout must return a managed result"));
|
||||
};
|
||||
let expected = match self.phase {
|
||||
Phase::Measure => "MeasureResult",
|
||||
Phase::Arrange => "Arrangement",
|
||||
};
|
||||
if !cx
|
||||
.store()
|
||||
.is_instance(*result, desktop_type(cx.store(), expected, self.desktop)?)?
|
||||
{
|
||||
return Err(invalid("layout returned the wrong result type"));
|
||||
}
|
||||
let mut plan = self
|
||||
.plan
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout plan poisoned"))?;
|
||||
match self.phase {
|
||||
Phase::Measure => {
|
||||
let size = layout::constrained(
|
||||
Size {
|
||||
width: number(cx, *result, "width", false)?,
|
||||
height: number(cx, *result, "height", false)?,
|
||||
},
|
||||
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_precise(pending.token)
|
||||
.map(|reads| (pending, reads))
|
||||
})
|
||||
.transpose()?;
|
||||
if let Some((pending, reads)) = tracked {
|
||||
let mut volatile = false;
|
||||
let registry = desktop_type_registry(cx, self.desktop)?;
|
||||
for read in &reads.accesses {
|
||||
let object = read.object;
|
||||
if object == self.desktop || object == registry {
|
||||
continue;
|
||||
}
|
||||
// A Mount's layoutVersion/geometry may be observed by
|
||||
// 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 |= read.content_read;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if volatile {
|
||||
plan.cache.entries.remove(&pending.key);
|
||||
} else {
|
||||
plan.cache.entries.insert(
|
||||
pending.key,
|
||||
Measurement {
|
||||
owner: pending.owner,
|
||||
method: pending.method,
|
||||
children: pending.children,
|
||||
constraints: pending.constraints,
|
||||
size,
|
||||
reads: reads
|
||||
.dependencies
|
||||
.into_iter()
|
||||
.filter(|dependency| {
|
||||
let object = dependency.object();
|
||||
object != self.desktop
|
||||
&& object != registry
|
||||
&& cx.store().object(object).is_ok_and(|value| {
|
||||
!value.payload().as_any().is::<Mount>()
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
plan.preferred[self.index].get_or_insert(size);
|
||||
plan.sizes[self.index] = size;
|
||||
if self.index == 0 {
|
||||
plan.bounds[0] = Some([0.0, 0.0, size.width, size.height]);
|
||||
}
|
||||
}
|
||||
Phase::Arrange => {
|
||||
let Value::Object(list) = cx.store().get_attr(*result, "children")? else {
|
||||
return Err(invalid("Arrangement.children must be an ObjectList"));
|
||||
};
|
||||
let items = object_list::items(cx.store(), list)?;
|
||||
let children = plan.children[self.index].clone();
|
||||
if items.len() != children.len() {
|
||||
return Err(invalid(
|
||||
"Arrangement must assign every child slot exactly once",
|
||||
));
|
||||
}
|
||||
let slots: HashMap<_, _> = plan.nodes[self.index]
|
||||
.slots
|
||||
.iter()
|
||||
.copied()
|
||||
.enumerate()
|
||||
.map(|(index, slot)| (slot, index))
|
||||
.collect();
|
||||
let mut assigned = BTreeSet::new();
|
||||
let expected = desktop_type(cx.store(), "Bounds", self.desktop)?;
|
||||
for item in items {
|
||||
if !cx.store().is_instance(*item, expected)? {
|
||||
return Err(invalid("Arrangement child must be Bounds"));
|
||||
}
|
||||
let Value::Number(slot) = cx.store().get_attr(*item, "slot")? else {
|
||||
return Err(invalid("Arrangement child requires a slot"));
|
||||
};
|
||||
let slot = slot
|
||||
.as_i64()
|
||||
.and_then(|value| u64::try_from(value).ok())
|
||||
.ok_or(invalid("invalid arrangement slot"))?;
|
||||
let position = slots
|
||||
.get(&slot)
|
||||
.copied()
|
||||
.ok_or(invalid("Arrangement references a foreign child slot"))?;
|
||||
if !assigned.insert(slot) {
|
||||
return Err(invalid("duplicate arrangement slot"));
|
||||
}
|
||||
let bounds = [
|
||||
number(cx, *item, "x", false)?,
|
||||
number(cx, *item, "y", false)?,
|
||||
number(cx, *item, "width", false)?,
|
||||
number(cx, *item, "height", false)?,
|
||||
];
|
||||
if bounds[0] + bounds[2] > MAX_DIMENSION as f32
|
||||
|| bounds[1] + bounds[3] > MAX_DIMENSION as f32
|
||||
{
|
||||
return Err(invalid("arrangement bounds exceed limits"));
|
||||
}
|
||||
let child = children[position];
|
||||
if plan.custom_arrange[self.index] {
|
||||
if plan.native_arrange[self.index]
|
||||
&& let Some(main) = layout::main_axis(&plan.nodes[self.index])
|
||||
{
|
||||
// Keep an allocation explicit even if this pass's
|
||||
// natural size happens to match it. It must survive
|
||||
// the next parent-constraint propagation pass.
|
||||
plan.allocations[child][main] = Some(bounds[main + 2]);
|
||||
}
|
||||
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: Arc<[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 in 0..plan.nodes.len() {
|
||||
let children = plan.children[index].clone();
|
||||
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::arranged_child_constraints(
|
||||
&plan.nodes[index],
|
||||
available,
|
||||
Size { width, height },
|
||||
);
|
||||
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;
|
||||
}
|
||||
if let Some(main) = layout::main_axis(&plan.nodes[index]) {
|
||||
let cross = 1 - main;
|
||||
if constraints[cross] != plan.constraints[child][cross]
|
||||
|| constraints[cross + 2] != plan.constraints[child][cross + 2]
|
||||
{
|
||||
// Wrapping or other cross-dependent measurement
|
||||
// invalidates this occurrence's natural main size.
|
||||
plan.preferred[child] = None;
|
||||
if plan.native_arrange[index] {
|
||||
// Derived flex sizes must not constrain their
|
||||
// own replacement measurement. Source arrange
|
||||
// allocations remain authoritative.
|
||||
plan.allocations[child][main] = None;
|
||||
constraints[main] = base[main];
|
||||
constraints[main + 2] = base[main + 2];
|
||||
}
|
||||
}
|
||||
}
|
||||
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));
|
||||
}
|
||||
state.push(u32::from(plan.preferred[index].is_some()));
|
||||
if let Some(size) = plan.preferred[index] {
|
||||
state.extend([bits(size.width), bits(size.height)]);
|
||||
} else {
|
||||
state.extend([0, 0]);
|
||||
}
|
||||
}
|
||||
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.iter() {
|
||||
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,
|
||||
mounts: Vec<WeakObjectRef>,
|
||||
desktop: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for Prepare {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let advance = cx.allocate(ContextNativeFunction::new(
|
||||
"next layout occurrence",
|
||||
Advance {
|
||||
plan: self.plan.clone(),
|
||||
mounts: self.mounts.clone().into(),
|
||||
desktop: self.desktop,
|
||||
next: Mutex::new(0),
|
||||
},
|
||||
vec![self.desktop],
|
||||
))?;
|
||||
let function = crate::vm_sequence::repeat_call(cx, advance, "source layout", self.desktop)?;
|
||||
Ok(NativeResult::Invoke {
|
||||
function,
|
||||
arguments: vec![],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Advance {
|
||||
plan: Shared,
|
||||
mounts: Arc<[WeakObjectRef]>,
|
||||
desktop: ObjectRef,
|
||||
next: Mutex<usize>,
|
||||
}
|
||||
impl NativeCallable for Advance {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let count = self.mounts.len();
|
||||
let position = {
|
||||
let mut next = self
|
||||
.next
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout cursor poisoned"))?;
|
||||
let position = *next;
|
||||
if position < count * 2 {
|
||||
*next += 1;
|
||||
}
|
||||
position
|
||||
};
|
||||
if position == count * 2 {
|
||||
let settled = Settle {
|
||||
plan: self.plan.clone(),
|
||||
mounts: self.mounts.clone(),
|
||||
}
|
||||
.invoke(cx, &[])?;
|
||||
let NativeResult::Return(Value::Bool(repeat)) = settled else {
|
||||
return Err(invalid("invalid settling result"));
|
||||
};
|
||||
if repeat {
|
||||
*self
|
||||
.next
|
||||
.lock()
|
||||
.map_err(|_| invalid("layout cursor poisoned"))? = 0;
|
||||
}
|
||||
return Ok(NativeResult::Return(Value::Bool(repeat)));
|
||||
}
|
||||
let (phase, index) = if position < count {
|
||||
(Phase::Measure, count - position - 1)
|
||||
} else {
|
||||
(Phase::Arrange, position - count)
|
||||
};
|
||||
let mount = cx
|
||||
.upgrade(self.mounts[index])?
|
||||
.ok_or(invalid("layout Mount expired"))?;
|
||||
let step = cx.allocate(ContextNativeFunction::new(
|
||||
"layout step",
|
||||
Step {
|
||||
plan: self.plan.clone(),
|
||||
index,
|
||||
phase,
|
||||
mount,
|
||||
desktop: self.desktop,
|
||||
},
|
||||
vec![mount, self.desktop],
|
||||
))?;
|
||||
let collector = cx.allocate(ContextNativeFunction::new(
|
||||
"collect layout",
|
||||
Collect {
|
||||
plan: self.plan.clone(),
|
||||
index,
|
||||
phase,
|
||||
desktop: self.desktop,
|
||||
},
|
||||
vec![self.desktop],
|
||||
))?;
|
||||
let function = crate::vm_sequence::collect_and_continue(
|
||||
cx,
|
||||
collector,
|
||||
step,
|
||||
vec![],
|
||||
"layout occurrence",
|
||||
self.desktop,
|
||||
)?;
|
||||
Ok(NativeResult::Invoke {
|
||||
function,
|
||||
arguments: vec![],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An unpublished layout frame and derived caches. These are merged only after
|
||||
/// the driver completes; they are not another copy of application state.
|
||||
pub struct Draft {
|
||||
pub frame: Frame,
|
||||
pub runtime: LayoutRuntime,
|
||||
pub cache: Cache,
|
||||
pub reads: Vec<endor_core::ReadDependency>,
|
||||
}
|
||||
|
||||
#[must_use = "pending layout work must be resumed or cancelled with its owning VM"]
|
||||
pub enum Progress {
|
||||
Pending(Work),
|
||||
Complete(Draft),
|
||||
}
|
||||
|
||||
/// Host-owned continuation. No borrowed frame/cache references cross a pause.
|
||||
/// The prepare handle owns one root until completion or explicit cancellation.
|
||||
pub struct Work {
|
||||
state: Draft,
|
||||
plan: Shared,
|
||||
prepare: ObjectRef,
|
||||
desktop: ObjectRef,
|
||||
slices: usize,
|
||||
}
|
||||
|
||||
impl Work {
|
||||
pub fn resume(mut self, vm: &mut Vm, slice: usize) -> Result<Progress> {
|
||||
self.slices += 1;
|
||||
let progress = vm.resume_read_only_call(slice);
|
||||
self.accept(vm, progress)
|
||||
}
|
||||
|
||||
pub fn cancel(self, vm: &mut Vm) -> Result<()> {
|
||||
let cancelled = vm.cancel_read_only_call();
|
||||
let released = vm.release(self.prepare);
|
||||
cancelled?;
|
||||
released?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn accept(
|
||||
self,
|
||||
vm: &mut Vm,
|
||||
progress: Result<endor_core::ExecutionProgress, VmError>,
|
||||
) -> Result<Progress> {
|
||||
match progress {
|
||||
Ok(endor_core::ExecutionProgress::Pending { .. }) => Ok(Progress::Pending(self)),
|
||||
Ok(endor_core::ExecutionProgress::Complete {
|
||||
value,
|
||||
dependencies,
|
||||
..
|
||||
}) => {
|
||||
vm.release(self.prepare)?;
|
||||
finish(vm, self, value, dependencies)
|
||||
}
|
||||
Err(error) => {
|
||||
// An invalid quantum can fail without discarding the VM's
|
||||
// continuation. No failed job may strand a read-only scope.
|
||||
let diagnostic = crate::endor_host::runtime_error(vm, error);
|
||||
self.cancel(vm)?;
|
||||
Err(diagnostic)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(
|
||||
vm: &mut Vm,
|
||||
desktop: ObjectRef,
|
||||
mounts: Vec<WeakObjectRef>,
|
||||
root: Arc<UiNode>,
|
||||
mut state: Draft,
|
||||
slice: usize,
|
||||
) -> Result<Progress> {
|
||||
anyhow::ensure!(slice > 0, "layout slice must be positive");
|
||||
anyhow::ensure!(
|
||||
!vm.has_suspended_call() && !vm.object_store().is_read_only(),
|
||||
"cannot start layout while another read-only execution is active"
|
||||
);
|
||||
let frame = &mut state.frame;
|
||||
let runtime = &mut state.runtime;
|
||||
let cache = &mut state.cache;
|
||||
cache.hits = 0;
|
||||
cache.misses = 0;
|
||||
let live: HashSet<_> = mounts.iter().copied().collect();
|
||||
cache.entries.retain(|mount, _| live.contains(mount));
|
||||
// Preserve the existing native measurement cache and avoid VM/result
|
||||
// allocation for small trees without custom layout methods. Contexts already exist.
|
||||
let mut custom = false;
|
||||
for weak in &mounts {
|
||||
let mount = vm
|
||||
.upgrade(*weak)?
|
||||
.ok_or_else(|| anyhow::anyhow!("layout Mount expired"))?;
|
||||
let result = (|| {
|
||||
let block = vm.payload::<Mount>(mount, "Mount")?.block;
|
||||
let definition = vm
|
||||
.object_store()
|
||||
.type_of(block)?
|
||||
.ok_or(invalid("untyped layout target"))?;
|
||||
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.has_flex();
|
||||
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 && nodes.len() <= NATIVE_FAST_PATH_MAX_NODES {
|
||||
cache.clear();
|
||||
let mut native = runtime.frame(&root)?;
|
||||
// Only the structural pass consumes a published version.
|
||||
native.layout_version = frame.layout_version;
|
||||
runtime.version = frame.layout_version;
|
||||
*frame = native;
|
||||
state.reads.clear();
|
||||
return Ok(Progress::Complete(state));
|
||||
}
|
||||
anyhow::ensure!(
|
||||
nodes.len() == mounts.len() && nodes.len() == frame.mounts.len(),
|
||||
"layout structure does not match Mount contexts"
|
||||
);
|
||||
let indices: HashMap<_, _> = frame
|
||||
.mounts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, mount)| (mount.id, index))
|
||||
.collect();
|
||||
let mut children = vec![Vec::new(); nodes.len()];
|
||||
for (index, mount) in frame.mounts.iter().enumerate() {
|
||||
if let Some(parent) = mount.parent {
|
||||
children[indices[&parent]].push(index);
|
||||
}
|
||||
}
|
||||
let mut constraints = vec![layout::root_constraints(runtime.viewport); nodes.len()];
|
||||
for index in 0..nodes.len() {
|
||||
let next = layout::child_constraints(&nodes[index], constraints[index]);
|
||||
for child in &children[index] {
|
||||
constraints[*child] = next;
|
||||
}
|
||||
}
|
||||
let count = nodes.len();
|
||||
let plan = Arc::new(Mutex::new(Plan {
|
||||
sizes: vec![Size::default(); nodes.len()],
|
||||
preferred: vec![None; nodes.len()],
|
||||
bounds: vec![None; nodes.len()],
|
||||
nodes,
|
||||
children,
|
||||
runtime: runtime.clone(),
|
||||
custom: false,
|
||||
cache: cache.clone(),
|
||||
pending: (0..count).map(|_| None).collect(),
|
||||
constraints,
|
||||
allocations: vec![[None, None]; count],
|
||||
custom_arrange: vec![false; count],
|
||||
native_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",
|
||||
Prepare {
|
||||
plan: plan.clone(),
|
||||
mounts,
|
||||
desktop,
|
||||
},
|
||||
vec![desktop],
|
||||
))?;
|
||||
let work = Work {
|
||||
state,
|
||||
plan,
|
||||
prepare,
|
||||
desktop,
|
||||
slices: 1,
|
||||
};
|
||||
let progress = vm.start_read_only_call(
|
||||
prepare,
|
||||
&[],
|
||||
endor_core::ExecutionLimits {
|
||||
max_frames: 128,
|
||||
max_instructions: 1_000_000,
|
||||
},
|
||||
slice,
|
||||
);
|
||||
work.accept(vm, progress)
|
||||
}
|
||||
|
||||
fn finish(
|
||||
vm: &mut Vm,
|
||||
mut work: Work,
|
||||
value: Value,
|
||||
reads: Vec<endor_core::ReadDependency>,
|
||||
) -> Result<Progress> {
|
||||
vm.release_value(value)?;
|
||||
let mut plan = work
|
||||
.plan
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("layout plan poisoned"))?;
|
||||
plan.runtime.slices = work.slices;
|
||||
let frame = &mut work.state.frame;
|
||||
frame.commands.clear();
|
||||
for (index, mount) in frame.mounts.iter_mut().enumerate() {
|
||||
let [x, y, width, height] =
|
||||
plan.bounds[index].ok_or_else(|| anyhow::anyhow!("unarranged occurrence"))?;
|
||||
mount.x = x;
|
||||
mount.y = y;
|
||||
mount.width = width;
|
||||
mount.height = height;
|
||||
if let Some(command) =
|
||||
layout::paint_native(&plan.nodes[index], x, y, Size { width, height })
|
||||
{
|
||||
command.validate()?;
|
||||
frame.commands.push(command);
|
||||
}
|
||||
}
|
||||
work.state.runtime = plan.runtime.clone();
|
||||
work.state.cache = plan.cache.clone();
|
||||
if !plan.custom {
|
||||
work.state.reads.clear();
|
||||
return Ok(Progress::Complete(work.state));
|
||||
}
|
||||
let registry = match vm.get_attr(work.desktop, "types")? {
|
||||
Value::Object(object) => object,
|
||||
_ => anyhow::bail!("missing type registry"),
|
||||
};
|
||||
work.state.reads = reads
|
||||
.into_iter()
|
||||
.filter(|dependency| {
|
||||
let object = dependency.object();
|
||||
object != work.desktop
|
||||
&& object != registry
|
||||
&& vm
|
||||
.object(object)
|
||||
.is_ok_and(|object| !object.payload().as_any().is::<Mount>())
|
||||
})
|
||||
.collect();
|
||||
Ok(Progress::Complete(work.state))
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
//! Source paint dispatch produces checked immutable commands. One read-only VM
|
||||
//! resumable call sequences all overrides, sharing one instruction/frame budget.
|
||||
use crate::{
|
||||
document::{Frame, RenderCommand},
|
||||
layout::{self, Size},
|
||||
mount::Mount,
|
||||
object_list,
|
||||
ui_bridge::{MAX_DIMENSION, UiNode, attach_desktop_type},
|
||||
};
|
||||
use anyhow::{Result, bail};
|
||||
use endor_core::{
|
||||
ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectRef, ObjectStore,
|
||||
Value, Vm, VmError, WeakObjectRef,
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
fn invalid(message: &'static str) -> VmError {
|
||||
VmError::InvalidArgument(message)
|
||||
}
|
||||
fn object(value: Value) -> Result<ObjectRef, VmError> {
|
||||
if let Value::Object(object) = value {
|
||||
Ok(object)
|
||||
} else {
|
||||
Err(invalid("paint must return managed objects"))
|
||||
}
|
||||
}
|
||||
fn text(store: &ObjectStore, object: ObjectRef, name: &str) -> Result<String, VmError> {
|
||||
if let Value::Text(value) = store.get_attr(object, name)? {
|
||||
Ok(value)
|
||||
} else {
|
||||
Err(invalid("paint field must be text"))
|
||||
}
|
||||
}
|
||||
fn number(store: &ObjectStore, object: ObjectRef, name: &str) -> Result<f32, VmError> {
|
||||
let Value::Number(value) = store.get_attr(object, name)? else {
|
||||
return Err(invalid("paint field must be a Number"));
|
||||
};
|
||||
let value = value
|
||||
.to_string()
|
||||
.parse::<f32>()
|
||||
.map_err(|_| invalid("invalid paint number"))?;
|
||||
if !value.is_finite()
|
||||
|| value.abs() > MAX_DIMENSION as f32
|
||||
|| (!matches!(name, "x" | "y") && value < 0.0)
|
||||
{
|
||||
return Err(invalid("paint number exceeds bounds"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
fn named_type(store: &ObjectStore, desktop: ObjectRef, name: &str) -> Result<ObjectRef, VmError> {
|
||||
let registry = object(store.get_attr(desktop, "types")?)?;
|
||||
object(
|
||||
store
|
||||
.dict_get(registry, &Value::Text(name.into()))?
|
||||
.ok_or(invalid("missing paint type"))?,
|
||||
)
|
||||
}
|
||||
fn decode(
|
||||
store: &ObjectStore,
|
||||
command: ObjectRef,
|
||||
expected: ObjectRef,
|
||||
) -> Result<RenderCommand, VmError> {
|
||||
if !store.is_instance(command, expected)? {
|
||||
return Err(invalid("paint commands must be PaintCommand instances"));
|
||||
}
|
||||
let x = number(store, command, "x")?;
|
||||
let y = number(store, command, "y")?;
|
||||
let color = text(store, command, "color")?;
|
||||
let kind = text(store, command, "kind")?;
|
||||
let result = match kind.as_str() {
|
||||
"roundedRect" | "strokeRoundedRect" => {
|
||||
let width = number(store, command, "width")?;
|
||||
let height = number(store, command, "height")?;
|
||||
let radius = number(store, command, "radius")?;
|
||||
if x + width > MAX_DIMENSION as f32 || y + height > MAX_DIMENSION as f32 {
|
||||
return Err(invalid("paint rectangle exceeds bounds"));
|
||||
}
|
||||
if kind == "roundedRect" {
|
||||
RenderCommand::RoundedRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
radius,
|
||||
color,
|
||||
}
|
||||
} else {
|
||||
RenderCommand::StrokeRoundedRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
radius,
|
||||
color,
|
||||
stroke_width: number(store, command, "strokeWidth")?,
|
||||
}
|
||||
}
|
||||
}
|
||||
"text" => {
|
||||
let size = number(store, command, "size")?;
|
||||
if size.fract() != 0.0 || !(1.0..=8.0).contains(&size) {
|
||||
return Err(invalid("paint text size must be an integer from 1 to 8"));
|
||||
}
|
||||
let wrap_bounds = match (
|
||||
store.get_attr(command, "wrapWidth"),
|
||||
store.get_attr(command, "wrapHeight"),
|
||||
) {
|
||||
(Err(VmError::AttributeNotFound(_)), Err(VmError::AttributeNotFound(_))) => None,
|
||||
(Ok(_), Ok(_)) => Some([
|
||||
number(store, command, "wrapWidth")?,
|
||||
number(store, command, "wrapHeight")?,
|
||||
]),
|
||||
(Err(error), _) | (_, Err(error)) => return Err(error),
|
||||
};
|
||||
RenderCommand::Text {
|
||||
x,
|
||||
y,
|
||||
value: text(store, command, "text")?,
|
||||
size: size as u32,
|
||||
color,
|
||||
wrap_bounds,
|
||||
}
|
||||
}
|
||||
_ => return Err(invalid("unsupported paint command kind")),
|
||||
};
|
||||
result
|
||||
.validate()
|
||||
.map_err(|_| invalid("invalid paint command geometry, text or color"))?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct PaintOutput {
|
||||
commands: BTreeMap<u64, Vec<RenderCommand>>,
|
||||
count: usize,
|
||||
}
|
||||
type Output = Arc<Mutex<PaintOutput>>;
|
||||
#[derive(Debug)]
|
||||
struct Collect {
|
||||
desktop: ObjectRef,
|
||||
mount: u64,
|
||||
output: Output,
|
||||
}
|
||||
impl NativeCallable for Collect {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(1))
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let [Value::Object(result)] = args else {
|
||||
return Err(invalid("paint must return a DisplayList"));
|
||||
};
|
||||
if !cx.store().is_instance(
|
||||
*result,
|
||||
named_type(cx.store(), self.desktop, "DisplayList")?,
|
||||
)? {
|
||||
return Err(invalid("paint must return a DisplayList"));
|
||||
}
|
||||
let commands = object(cx.store().get_attr(*result, "commands")?)?;
|
||||
let expected = named_type(cx.store(), self.desktop, "PaintCommand")?;
|
||||
let commands = object_list::items(cx.store(), commands)?
|
||||
.iter()
|
||||
.map(|command| decode(cx.store(), *command, expected))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut output = self
|
||||
.output
|
||||
.lock()
|
||||
.map_err(|_| invalid("paint output poisoned"))?;
|
||||
if output.count + commands.len() > 10_000 {
|
||||
return Err(invalid("paint command budget exceeded"));
|
||||
}
|
||||
output.count += commands.len();
|
||||
output.commands.insert(self.mount, commands);
|
||||
Ok(NativeResult::Return(Value::Nil))
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Prepare {
|
||||
desktop: ObjectRef,
|
||||
mounts: Vec<(u64, WeakObjectRef)>,
|
||||
output: Output,
|
||||
}
|
||||
impl NativeCallable for Prepare {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let advance = cx.allocate(ContextNativeFunction::new(
|
||||
"next paint occurrence",
|
||||
Advance {
|
||||
desktop: self.desktop,
|
||||
mounts: self.mounts.clone().into(),
|
||||
next: Mutex::new(0),
|
||||
output: self.output.clone(),
|
||||
},
|
||||
vec![self.desktop],
|
||||
))?;
|
||||
let function = crate::vm_sequence::repeat_call(cx, advance, "source paint", self.desktop)?;
|
||||
Ok(NativeResult::Invoke {
|
||||
function,
|
||||
arguments: vec![],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Advance {
|
||||
desktop: ObjectRef,
|
||||
mounts: Arc<[(u64, WeakObjectRef)]>,
|
||||
next: Mutex<usize>,
|
||||
output: Output,
|
||||
}
|
||||
impl NativeCallable for Advance {
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(endor_core::CallArity::exact(0))
|
||||
}
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let occurrence = {
|
||||
let mut next = self
|
||||
.next
|
||||
.lock()
|
||||
.map_err(|_| invalid("paint cursor poisoned"))?;
|
||||
let occurrence = self.mounts.get(*next).copied();
|
||||
*next += usize::from(occurrence.is_some());
|
||||
occurrence
|
||||
};
|
||||
let Some((id, weak)) = occurrence else {
|
||||
return Ok(NativeResult::Return(Value::Bool(false)));
|
||||
};
|
||||
let mount = cx
|
||||
.upgrade(weak)?
|
||||
.ok_or(invalid("paint Mount has expired"))?;
|
||||
let data = cx.store().payload::<Mount>(mount, "Mount")?.clone();
|
||||
if !data.mounted {
|
||||
return Err(invalid("paint Mount is detached"));
|
||||
}
|
||||
let definition = cx
|
||||
.store()
|
||||
.type_of(data.block)?
|
||||
.ok_or(invalid("untyped paint target"))?;
|
||||
let function = cx
|
||||
.store()
|
||||
.lookup_method(definition, "paint")?
|
||||
.ok_or(invalid("missing paint method"))?;
|
||||
if crate::native_visual::is_intrinsic(cx.store(), function, "paint", self.desktop)? {
|
||||
return Ok(NativeResult::Return(Value::Bool(true)));
|
||||
}
|
||||
let bounds = cx.new_object()?;
|
||||
attach_desktop_type(cx, bounds, "Bounds", self.desktop)?;
|
||||
for (name, value) in [
|
||||
("x", data.geometry.x),
|
||||
("y", data.geometry.y),
|
||||
("width", data.geometry.width),
|
||||
("height", data.geometry.height),
|
||||
] {
|
||||
cx.set_attr(bounds, name, Value::Number((value as f64).into()))?;
|
||||
}
|
||||
let collector = cx.allocate(ContextNativeFunction::new(
|
||||
"collect source paint",
|
||||
Collect {
|
||||
desktop: self.desktop,
|
||||
mount: id,
|
||||
output: self.output.clone(),
|
||||
},
|
||||
vec![self.desktop],
|
||||
))?;
|
||||
let function = crate::vm_sequence::collect_and_continue(
|
||||
cx,
|
||||
collector,
|
||||
function,
|
||||
vec![
|
||||
Value::Object(data.block),
|
||||
Value::Object(mount),
|
||||
Value::Object(bounds),
|
||||
],
|
||||
"paint occurrence",
|
||||
self.desktop,
|
||||
)?;
|
||||
Ok(NativeResult::Invoke {
|
||||
function,
|
||||
arguments: vec![],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Draft {
|
||||
pub frame: Frame,
|
||||
pub reads: Vec<endor_core::ReadDependency>,
|
||||
pub slices: usize,
|
||||
}
|
||||
|
||||
#[must_use = "pending paint must be resumed or cancelled on its owning VM"]
|
||||
pub enum Progress {
|
||||
Pending(Box<Work>),
|
||||
Complete(Box<Draft>),
|
||||
}
|
||||
|
||||
/// Only unpublished native commands and an owning prepare root cross a pause.
|
||||
pub struct Work {
|
||||
desktop: ObjectRef,
|
||||
prepare: ObjectRef,
|
||||
output: Output,
|
||||
root: Option<Arc<UiNode>>,
|
||||
frame: Frame,
|
||||
slices: usize,
|
||||
}
|
||||
|
||||
impl Work {
|
||||
pub fn resume(mut self, vm: &mut Vm, slice: usize) -> Result<Progress> {
|
||||
self.slices += 1;
|
||||
let progress = vm.resume_read_only_call(slice);
|
||||
self.accept(vm, progress)
|
||||
}
|
||||
|
||||
pub fn cancel(self, vm: &mut Vm) -> Result<()> {
|
||||
let cancelled = vm.cancel_read_only_call();
|
||||
let released = vm.release(self.prepare);
|
||||
cancelled?;
|
||||
released?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn accept(
|
||||
self,
|
||||
vm: &mut Vm,
|
||||
progress: Result<endor_core::ExecutionProgress, VmError>,
|
||||
) -> Result<Progress> {
|
||||
match progress {
|
||||
Ok(endor_core::ExecutionProgress::Pending { .. }) => {
|
||||
Ok(Progress::Pending(Box::new(self)))
|
||||
}
|
||||
Ok(endor_core::ExecutionProgress::Complete {
|
||||
value,
|
||||
dependencies,
|
||||
..
|
||||
}) => {
|
||||
vm.release(self.prepare)?;
|
||||
vm.release_value(value)?;
|
||||
finish(vm, self, dependencies)
|
||||
}
|
||||
Err(error) => {
|
||||
let diagnostic = crate::endor_host::runtime_error(vm, error);
|
||||
self.cancel(vm)?;
|
||||
Err(diagnostic)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(
|
||||
vm: &mut Vm,
|
||||
desktop: ObjectRef,
|
||||
mounts: Vec<(u64, WeakObjectRef)>,
|
||||
root: Option<Arc<UiNode>>,
|
||||
frame: Frame,
|
||||
slice: usize,
|
||||
) -> Result<Progress> {
|
||||
anyhow::ensure!(slice > 0, "paint slice must be positive");
|
||||
anyhow::ensure!(
|
||||
!vm.has_suspended_call() && !vm.object_store().is_read_only(),
|
||||
"cannot start paint while another read-only execution is active"
|
||||
);
|
||||
let output = Arc::new(Mutex::new(PaintOutput::default()));
|
||||
let prepare = vm.allocate(ContextNativeFunction::new(
|
||||
"prepare source paint",
|
||||
Prepare {
|
||||
desktop,
|
||||
mounts,
|
||||
output: output.clone(),
|
||||
},
|
||||
vec![desktop],
|
||||
))?;
|
||||
let work = Work {
|
||||
desktop,
|
||||
prepare,
|
||||
output,
|
||||
root,
|
||||
frame,
|
||||
slices: 1,
|
||||
};
|
||||
let result = vm.start_read_only_call(
|
||||
prepare,
|
||||
&[],
|
||||
endor_core::ExecutionLimits {
|
||||
max_frames: 128,
|
||||
max_instructions: 1_000_000,
|
||||
},
|
||||
slice,
|
||||
);
|
||||
work.accept(vm, result)
|
||||
}
|
||||
|
||||
fn finish(vm: &mut Vm, mut work: Work, reads: Vec<endor_core::ReadDependency>) -> Result<Progress> {
|
||||
let output = work
|
||||
.output
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("paint output poisoned"))?;
|
||||
if output.commands.is_empty() {
|
||||
return Ok(Progress::Complete(Box::new(Draft {
|
||||
frame: work.frame,
|
||||
reads: Vec::new(),
|
||||
slices: work.slices,
|
||||
})));
|
||||
}
|
||||
let root = work.root.as_deref();
|
||||
let desktop = work.desktop;
|
||||
let frame = &mut work.frame;
|
||||
let mut nodes = HashMap::new();
|
||||
let mut pending: Vec<_> = root.into_iter().collect();
|
||||
while let Some(node) = pending.pop() {
|
||||
nodes.insert(node.block_id.as_str(), node);
|
||||
pending.extend(node.children().iter().map(|node| node.as_ref()));
|
||||
}
|
||||
let mut commands = Vec::new();
|
||||
let mut clips = Vec::new();
|
||||
for mount in &frame.mounts {
|
||||
let before = commands.len();
|
||||
if let Some(custom) = output.commands.get(&mount.id) {
|
||||
commands.extend(custom.iter().cloned());
|
||||
} else {
|
||||
let node = nodes
|
||||
.get(mount.block_id.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("paint projection has no node"))?;
|
||||
if let Some(command) = layout::paint_native(
|
||||
node,
|
||||
mount.x,
|
||||
mount.y,
|
||||
Size {
|
||||
width: mount.width,
|
||||
height: mount.height,
|
||||
},
|
||||
) {
|
||||
commands.push(command);
|
||||
}
|
||||
}
|
||||
clips.extend(std::iter::repeat_n(mount.clip, commands.len() - before));
|
||||
if commands.len() > 10_000 {
|
||||
bail!("paint command budget exceeded");
|
||||
}
|
||||
}
|
||||
frame.commands = commands;
|
||||
frame.command_clips = clips;
|
||||
let registry = object(vm.get_attr(desktop, "types")?)?;
|
||||
let reads = reads
|
||||
.into_iter()
|
||||
.filter(|dependency| {
|
||||
let object = dependency.object();
|
||||
object != desktop
|
||||
&& object != registry
|
||||
&& vm
|
||||
.object(object)
|
||||
.is_ok_and(|object| !object.payload().as_any().is::<Mount>())
|
||||
})
|
||||
.collect();
|
||||
Ok(Progress::Complete(Box::new(Draft {
|
||||
frame: work.frame,
|
||||
reads,
|
||||
slices: work.slices,
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
//! Shared font discovery, shaping, measurement and antialiased rasterization.
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Mutex, OnceLock},
|
||||
};
|
||||
|
||||
use cosmic_text::{Align, Attrs, Buffer, Family, FontSystem, Metrics, Shaping, SwashCache, Wrap};
|
||||
|
||||
use crate::display_list::Color;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
|
||||
pub enum TextFamily {
|
||||
Interface,
|
||||
Code,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TextStyle {
|
||||
pub font_size: f32,
|
||||
pub line_height: f32,
|
||||
pub family: TextFamily,
|
||||
}
|
||||
|
||||
impl TextStyle {
|
||||
pub fn ui(size: u32) -> Self {
|
||||
Self {
|
||||
font_size: 14.0 * size as f32,
|
||||
line_height: 20.0 * size as f32,
|
||||
family: TextFamily::Interface,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code() -> Self {
|
||||
Self {
|
||||
font_size: 13.0,
|
||||
line_height: 18.0,
|
||||
family: TextFamily::Code,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scaled(self, scale: f32) -> Self {
|
||||
Self {
|
||||
font_size: self.font_size * scale,
|
||||
line_height: self.line_height * scale,
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TextSize {
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Hash, PartialEq, Eq)]
|
||||
struct TextKey {
|
||||
value: String,
|
||||
font_size: u32,
|
||||
line_height: u32,
|
||||
family: TextFamily,
|
||||
wrap_width: Option<u32>,
|
||||
}
|
||||
|
||||
struct PreparedText {
|
||||
buffer: Buffer,
|
||||
size: TextSize,
|
||||
}
|
||||
|
||||
struct TextEngine {
|
||||
fonts: FontSystem,
|
||||
code_family: Option<String>,
|
||||
swash: SwashCache,
|
||||
buffers: HashMap<TextKey, PreparedText>,
|
||||
source_bytes: usize,
|
||||
}
|
||||
|
||||
impl TextEngine {
|
||||
fn new() -> Self {
|
||||
let mut fonts = FontSystem::new();
|
||||
// Select installed, readable families rather than assuming an OS font
|
||||
// name exists. COSMIC Text handles per-glyph fallback (including CJK).
|
||||
let choose = |choices: &[&str]| {
|
||||
choices.iter().find_map(|choice| {
|
||||
fonts
|
||||
.db()
|
||||
.faces()
|
||||
.any(|face| face.families.iter().any(|(name, _)| name == choice))
|
||||
.then(|| (*choice).to_owned())
|
||||
})
|
||||
};
|
||||
let sans = choose(&[
|
||||
".AppleSystemUIFont",
|
||||
"SF Pro Text",
|
||||
"Helvetica Neue",
|
||||
"Segoe UI",
|
||||
"Noto Sans",
|
||||
"DejaVu Sans",
|
||||
"Liberation Sans",
|
||||
]);
|
||||
let mono = choose(&["Menlo", "Consolas", "DejaVu Sans Mono", "Liberation Mono"]);
|
||||
if let Some(name) = sans {
|
||||
fonts.db_mut().set_sans_serif_family(name);
|
||||
}
|
||||
if let Some(name) = &mono {
|
||||
fonts.db_mut().set_monospace_family(name);
|
||||
}
|
||||
Self {
|
||||
fonts,
|
||||
code_family: mono,
|
||||
swash: SwashCache::new(),
|
||||
buffers: HashMap::new(),
|
||||
source_bytes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare(&mut self, value: &str, style: TextStyle) -> TextKey {
|
||||
self.prepare_width(value, style, None)
|
||||
}
|
||||
|
||||
fn prepare_width(&mut self, value: &str, style: TextStyle, wrap_width: Option<f32>) -> TextKey {
|
||||
let key = TextKey {
|
||||
value: value.to_owned(),
|
||||
font_size: style.font_size.to_bits(),
|
||||
line_height: style.line_height.to_bits(),
|
||||
family: style.family,
|
||||
wrap_width: wrap_width.map(f32::to_bits),
|
||||
};
|
||||
if self.buffers.contains_key(&key) {
|
||||
return key;
|
||||
}
|
||||
// Cache recent shaped strings, without retaining every submitted source.
|
||||
if self.buffers.len() >= 256 || self.source_bytes + value.len() > 524_288 {
|
||||
self.buffers.clear();
|
||||
self.source_bytes = 0;
|
||||
}
|
||||
let family = match style.family {
|
||||
TextFamily::Interface => Family::SansSerif,
|
||||
// Keep Latin source on the selected code face, and allow ordinary
|
||||
// script fallback for CJK instead of searching all monospace faces.
|
||||
TextFamily::Code => self
|
||||
.code_family
|
||||
.as_deref()
|
||||
.map_or(Family::Monospace, Family::Name),
|
||||
};
|
||||
let mut buffer = Buffer::new(
|
||||
&mut self.fonts,
|
||||
Metrics::new(style.font_size, style.line_height),
|
||||
);
|
||||
buffer.set_wrap(if wrap_width.is_some() {
|
||||
Wrap::WordOrGlyph
|
||||
} else {
|
||||
Wrap::None
|
||||
});
|
||||
buffer.set_size(wrap_width, None);
|
||||
buffer.set_text(
|
||||
value,
|
||||
&Attrs::new().family(family),
|
||||
Shaping::Advanced,
|
||||
Some(Align::Left),
|
||||
);
|
||||
buffer.shape_until_scroll(&mut self.fonts, false);
|
||||
let mut size = TextSize {
|
||||
width: 0.0,
|
||||
height: style.line_height,
|
||||
};
|
||||
for run in buffer.layout_runs() {
|
||||
size.width = size.width.max(run.line_w);
|
||||
size.height = size.height.max(run.line_top + run.line_height);
|
||||
}
|
||||
self.source_bytes += value.len();
|
||||
self.buffers
|
||||
.insert(key.clone(), PreparedText { buffer, size });
|
||||
key
|
||||
}
|
||||
}
|
||||
|
||||
fn engine() -> &'static Mutex<TextEngine> {
|
||||
static ENGINE: OnceLock<Mutex<TextEngine>> = OnceLock::new();
|
||||
ENGINE.get_or_init(|| Mutex::new(TextEngine::new()))
|
||||
}
|
||||
|
||||
pub fn measure(value: &str, style: TextStyle) -> TextSize {
|
||||
let mut engine = engine().lock().expect("text engine lock");
|
||||
let key = engine.prepare(value, style);
|
||||
engine.buffers[&key].size
|
||||
}
|
||||
|
||||
pub fn measure_wrapped(value: &str, style: TextStyle, width: f32) -> TextSize {
|
||||
if width <= 0.0 {
|
||||
return TextSize {
|
||||
width: 0.0,
|
||||
height: style.line_height,
|
||||
};
|
||||
}
|
||||
let mut engine = engine().lock().expect("text engine lock");
|
||||
let key = engine.prepare_width(value, style, Some(width));
|
||||
engine.buffers[&key].size
|
||||
}
|
||||
|
||||
/// Draw at the actual device font size; no scaling of an already rasterized bitmap.
|
||||
pub fn draw(value: &str, style: TextStyle, color: Color, pixel: impl FnMut(i32, i32, Color)) {
|
||||
draw_width(value, style, color, None, pixel)
|
||||
}
|
||||
|
||||
pub fn draw_wrapped(
|
||||
value: &str,
|
||||
style: TextStyle,
|
||||
color: Color,
|
||||
width: f32,
|
||||
pixel: impl FnMut(i32, i32, Color),
|
||||
) {
|
||||
if width > 0.0 {
|
||||
draw_width(value, style, color, Some(width), pixel)
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_width(
|
||||
value: &str,
|
||||
style: TextStyle,
|
||||
color: Color,
|
||||
width: Option<f32>,
|
||||
mut pixel: impl FnMut(i32, i32, Color),
|
||||
) {
|
||||
let mut engine = engine().lock().expect("text engine lock");
|
||||
let key = engine.prepare_width(value, style, width);
|
||||
let TextEngine {
|
||||
fonts,
|
||||
swash,
|
||||
buffers,
|
||||
..
|
||||
} = &mut *engine;
|
||||
let opacity = u16::from(color.alpha);
|
||||
buffers.get_mut(&key).expect("prepared text").buffer.draw(
|
||||
fonts,
|
||||
swash,
|
||||
cosmic_text::Color::rgb(color.red, color.green, color.blue),
|
||||
|x, y, width, height, color| {
|
||||
for dy in 0..height as i32 {
|
||||
for dx in 0..width as i32 {
|
||||
pixel(
|
||||
x + dx,
|
||||
y + dy,
|
||||
Color::rgba(
|
||||
color.r(),
|
||||
color.g(),
|
||||
color.b(),
|
||||
(u16::from(color.a()) * opacity / 255) as u8,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
// The cache is an optimization, never an archive of all submitted glyphs.
|
||||
if swash.image_cache.len() > 4096
|
||||
|| swash
|
||||
.image_cache
|
||||
.values()
|
||||
.flatten()
|
||||
.map(|image| image.data.len())
|
||||
.sum::<usize>()
|
||||
> 33_554_432
|
||||
{
|
||||
*swash = SwashCache::new();
|
||||
}
|
||||
}
|
||||
|
||||
/// Fit a single displayed source line without slicing a UTF-8/grapheme cluster.
|
||||
pub fn fit(value: &str, width: f32, style: TextStyle) -> String {
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
// A source line may include a very large comment. Only shape a bounded
|
||||
// preview for the sidebar; the stored source and its AST spans stay intact.
|
||||
let truncated = value.len() > 8192;
|
||||
let value = if truncated {
|
||||
let end = value
|
||||
.grapheme_indices(true)
|
||||
.map(|(index, _)| index)
|
||||
.take_while(|index| *index <= 8192)
|
||||
.last()
|
||||
.unwrap_or(0);
|
||||
&value[..end]
|
||||
} else {
|
||||
value
|
||||
};
|
||||
if !truncated && measure(value, style).width <= width {
|
||||
return value.to_owned();
|
||||
}
|
||||
let ellipsis = "…";
|
||||
if width <= 0.0 || measure(ellipsis, style).width > width {
|
||||
return String::new();
|
||||
}
|
||||
let ends: Vec<_> = value
|
||||
.grapheme_indices(true)
|
||||
.map(|(start, part)| start + part.len())
|
||||
.collect();
|
||||
let mut low = 0;
|
||||
let mut high = ends.len();
|
||||
while low < high {
|
||||
let count = (low + high).div_ceil(2);
|
||||
let end = ends[count - 1];
|
||||
let candidate = format!("{}{ellipsis}", &value[..end]);
|
||||
if measure(&candidate, style).width <= width {
|
||||
low = count;
|
||||
} else {
|
||||
high = count - 1;
|
||||
}
|
||||
}
|
||||
let end = low.checked_sub(1).map_or(0, |index| ends[index]);
|
||||
format!("{}{ellipsis}", &value[..end])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
#[test]
|
||||
fn width_sensitive_shaping_wraps_words_and_clusters_without_changing_intrinsic_metrics() {
|
||||
let style = TextStyle::ui(1);
|
||||
let text = "中文段落 with words and long_unbroken_identifier é 👩💻 中文段落";
|
||||
let intrinsic = measure(text, style);
|
||||
let narrow = measure_wrapped(text, style, 70.0);
|
||||
let wide = measure_wrapped(text, style, 240.0);
|
||||
assert!(narrow.height > wide.height);
|
||||
assert!(wide.height >= style.line_height);
|
||||
assert!(narrow.width <= 70.1);
|
||||
assert_eq!(measure(text, style).width, intrinsic.width);
|
||||
assert_eq!(measure_wrapped(text, style, 0.0).width, 0.0);
|
||||
let mut engine = engine().lock().unwrap();
|
||||
let narrow_key = engine.prepare_width(text, style, Some(70.0));
|
||||
let wide_key = engine.prepare_width(text, style, Some(240.0));
|
||||
assert!(narrow_key != wide_key);
|
||||
assert!(engine.buffers[&narrow_key].size.height > engine.buffers[&wide_key].size.height);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proportional_metrics_monospace_and_multiline_height_come_from_the_fonts() {
|
||||
let ui = TextStyle::ui(1);
|
||||
assert!(measure("WWWW", ui).width > measure("iiii", ui).width * 2.0);
|
||||
let mono = TextStyle::code();
|
||||
assert!((measure("WWWW", mono).width - measure("iiii", mono).width).abs() < 0.1);
|
||||
assert_eq!(measure("one\ntwo", ui).height, ui.line_height * 2.0);
|
||||
let width = measure("Hello Endor", ui).width;
|
||||
assert!((measure("Hello Endor", ui.scaled(1.25)).width - width * 1.25).abs() < 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_fallback_shapes_chinese_without_missing_glyphs() {
|
||||
let mut engine = engine().lock().unwrap();
|
||||
for style in [TextStyle::ui(1), TextStyle::code()] {
|
||||
let key = engine.prepare("中文字体", style);
|
||||
let glyphs: Vec<_> = engine.buffers[&key]
|
||||
.buffer
|
||||
.layout_runs()
|
||||
.flat_map(|run| run.glyphs)
|
||||
.collect();
|
||||
assert_eq!(glyphs.len(), 4);
|
||||
assert!(glyphs.iter().all(|glyph| glyph.glyph_id != 0));
|
||||
assert!(engine.buffers[&key].size.width <= style.font_size * 8.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipsis_fits_actual_width_and_preserves_graphemes() {
|
||||
let style = TextStyle::code();
|
||||
let short_source = "let s = ui.text(\"中文字体\")";
|
||||
assert_eq!(fit(short_source, 365.0, style), short_source);
|
||||
let value = "e\u{301}e\u{301}中文字体e\u{301}e\u{301}";
|
||||
let width = measure("e\u{301}e\u{301}中…", style).width + 0.01;
|
||||
let fitted = fit(value, width, style);
|
||||
let prefix = fitted.strip_suffix('…').unwrap();
|
||||
assert!(value.starts_with(prefix));
|
||||
assert!(
|
||||
value
|
||||
.grapheme_indices(true)
|
||||
.any(|(index, _)| index == prefix.len())
|
||||
);
|
||||
assert!(measure(&fitted, style).width <= width);
|
||||
assert_eq!(fit(value, 0.0, style), "");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user