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,2 @@
|
||||
// Module ownership follows the directory; crate-root aliases keep internal call sites stable.
|
||||
pub(crate) mod ui_bridge;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,397 @@
|
||||
//! Allocate and connect the managed desktop, type tables and host globals.
|
||||
use super::*;
|
||||
|
||||
pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
|
||||
let desktop = vm.new_object()?;
|
||||
roots.push(desktop);
|
||||
vm.set_attr(desktop, "viewport", Value::Nil)?;
|
||||
let tabs = vm.new_dict()?;
|
||||
roots.push(tabs);
|
||||
vm.set_attr(desktop, "tabs", Value::Object(tabs))?;
|
||||
let ui = vm.new_object()?;
|
||||
roots.push(ui);
|
||||
let session = Arc::new(Mutex::new(Session {
|
||||
nodes: Vec::new(),
|
||||
presentations: std::collections::BTreeMap::from([(
|
||||
crate::window::MAIN_WINDOW,
|
||||
crate::presentation::Presentation::new(desktop, tabs),
|
||||
)]),
|
||||
current: crate::window::MAIN_WINDOW,
|
||||
master: desktop,
|
||||
next_window: crate::window::MAIN_WINDOW,
|
||||
next_mount: 0,
|
||||
retired_commands: Vec::new(),
|
||||
refresh_yields: 0,
|
||||
refresh_restarts: 0,
|
||||
layout_cancels: 0,
|
||||
paint_cancels: 0,
|
||||
paint_slices: 0,
|
||||
binding_evaluations: 0,
|
||||
exiting: false,
|
||||
}));
|
||||
let mut public_functions = Vec::new();
|
||||
let mut factories = Vec::new();
|
||||
for (name, operation) in [
|
||||
("implement", Operation::Implement),
|
||||
("implements", Operation::Implements),
|
||||
("supports", Operation::Supports),
|
||||
("isInstance", Operation::IsInstance),
|
||||
("isSubtype", Operation::IsSubtype),
|
||||
("open", Operation::OpenValue),
|
||||
("text", Operation::Text),
|
||||
("rect", Operation::Rect),
|
||||
("spacer", Operation::Spacer),
|
||||
("row", Operation::Row),
|
||||
("column", Operation::Column),
|
||||
("button", Operation::Button),
|
||||
("page", Operation::Page),
|
||||
("present", Operation::Present),
|
||||
("state", Operation::State),
|
||||
("textOf", Operation::TextOf),
|
||||
("stats", Operation::Stats),
|
||||
("viewport", Operation::Viewport),
|
||||
("window", Operation::Window),
|
||||
] {
|
||||
let function = vm.allocate(ContextNativeFunction::new(
|
||||
name,
|
||||
Function {
|
||||
signature: None,
|
||||
operation,
|
||||
owner: None,
|
||||
session: session.clone(),
|
||||
requested_type: None,
|
||||
},
|
||||
vec![desktop],
|
||||
))?;
|
||||
roots.push(function);
|
||||
vm.set_attr(ui, name, Value::Object(function))?;
|
||||
public_functions.push((name, function, operation));
|
||||
}
|
||||
let root_types = vm.bootstrap_types()?;
|
||||
roots.extend([root_types.object, root_types.type_type]);
|
||||
vm.set_attr(ui, "Object", Value::Object(root_types.object))?;
|
||||
vm.set_attr(ui, "Type", Value::Object(root_types.type_type))?;
|
||||
let mut definitions = vec![
|
||||
("Object", root_types.object),
|
||||
("Type", root_types.type_type),
|
||||
];
|
||||
for (name, base_name, constructor_name) in [
|
||||
("Trait", "Object", None),
|
||||
("Function", "Object", None),
|
||||
("Block", "Object", None),
|
||||
("ContainerBlock", "Block", None),
|
||||
("TextBlock", "Block", Some("text")),
|
||||
("RectBlock", "Block", Some("rect")),
|
||||
("Spacer", "Block", Some("spacer")),
|
||||
("ScrollBlock", "ContainerBlock", Some("scroll")),
|
||||
("Row", "ContainerBlock", Some("row")),
|
||||
("Column", "ContainerBlock", Some("column")),
|
||||
("Button", "ContainerBlock", Some("button")),
|
||||
("Page", "ContainerBlock", Some("page")),
|
||||
("Window", "Object", Some("window-create")),
|
||||
("Mount", "Object", None),
|
||||
("Event", "Object", Some("event")),
|
||||
("Subscription", "Object", None),
|
||||
("Task", "Object", None),
|
||||
("ObjectList", "Object", Some("object-list")),
|
||||
] {
|
||||
let base = object(Some(&vm.get_attr(ui, base_name)?))?;
|
||||
let constructor = match constructor_name {
|
||||
Some("object-list") => {
|
||||
let factory = vm.allocate(ContextNativeFunction::new(
|
||||
"object-list",
|
||||
crate::object_list::Constructor {
|
||||
desktop,
|
||||
signature: None,
|
||||
},
|
||||
vec![desktop],
|
||||
))?;
|
||||
roots.push(factory);
|
||||
let function_type = object(Some(&vm.get_attr(ui, "Function")?))?;
|
||||
vm.attach_type(factory, function_type)?;
|
||||
TypeConstructor::NativeTyped(factory)
|
||||
}
|
||||
Some("event") => {
|
||||
let factory = vm.allocate(ContextNativeFunction::new(
|
||||
"event",
|
||||
crate::event_dispatch::Constructor { signature: None },
|
||||
vec![],
|
||||
))?;
|
||||
roots.push(factory);
|
||||
let function_type = object(Some(&vm.get_attr(ui, "Function")?))?;
|
||||
vm.attach_type(factory, function_type)?;
|
||||
TypeConstructor::NativeTyped(factory)
|
||||
}
|
||||
Some(constructor_name) => {
|
||||
let operation = match constructor_name {
|
||||
"text" => Operation::Text,
|
||||
"rect" => Operation::Rect,
|
||||
"spacer" => Operation::Spacer,
|
||||
"scroll" => Operation::Scroll,
|
||||
"row" => Operation::Row,
|
||||
"column" => Operation::Column,
|
||||
"button" => Operation::Button,
|
||||
"page" => Operation::Page,
|
||||
"window-create" => Operation::NewWindow,
|
||||
_ => return Err(invalid("unknown native type allocator").into()),
|
||||
};
|
||||
let factory = vm.allocate(ContextNativeFunction::new(
|
||||
constructor_name,
|
||||
NativeFactory {
|
||||
signature: None,
|
||||
options: None,
|
||||
operation,
|
||||
session: session.clone(),
|
||||
},
|
||||
vec![desktop],
|
||||
))?;
|
||||
roots.push(factory);
|
||||
let function_type = object(Some(&vm.get_attr(ui, "Function")?))?;
|
||||
vm.attach_type(factory, function_type)?;
|
||||
TypeConstructor::NativeTyped(factory)
|
||||
}
|
||||
None => TypeConstructor::Abstract,
|
||||
};
|
||||
if let (Some(tag), TypeConstructor::NativeTyped(factory)) = (constructor_name, constructor)
|
||||
{
|
||||
factories.push((tag, factory));
|
||||
}
|
||||
let definition = vm.new_type(name, base, constructor)?;
|
||||
roots.push(definition);
|
||||
vm.set_attr(ui, name, Value::Object(definition))?;
|
||||
definitions.push((name, definition));
|
||||
}
|
||||
for (name, fields) in [
|
||||
(
|
||||
"Constraints",
|
||||
vec!["minWidth", "minHeight", "maxWidth", "maxHeight"],
|
||||
),
|
||||
("MeasureResult", vec!["width", "height"]),
|
||||
("Bounds", vec!["x", "y", "width", "height"]),
|
||||
("Point", vec!["x", "y"]),
|
||||
("Arrangement", vec!["children"]),
|
||||
("DisplayList", vec!["commands"]),
|
||||
("PaintCommand", vec![]),
|
||||
] {
|
||||
let fields = fields
|
||||
.into_iter()
|
||||
.map(|name| endor_core::ClassField {
|
||||
name: name.into(),
|
||||
type_name: if matches!(name, "children" | "commands") {
|
||||
"Object"
|
||||
} else {
|
||||
"Number"
|
||||
}
|
||||
.into(),
|
||||
})
|
||||
.collect();
|
||||
let definition = vm.new_class(
|
||||
name,
|
||||
root_types.object,
|
||||
fields,
|
||||
std::collections::BTreeMap::new(),
|
||||
)?;
|
||||
roots.push(definition);
|
||||
vm.set_attr(ui, name, Value::Object(definition))?;
|
||||
definitions.push((name, definition));
|
||||
}
|
||||
// The desktop owns the registry through ordinary traced attributes. The
|
||||
// Rust session only borrows handles and adds no hidden lifetime roots.
|
||||
let types = vm.new_dict()?;
|
||||
roots.push(types);
|
||||
for (name, definition) in definitions {
|
||||
vm.dict_set(types, Value::Text(name.into()), Value::Object(definition))?;
|
||||
}
|
||||
vm.set_attr(desktop, "types", Value::Object(types))?;
|
||||
vm.attach_type(desktop, root_types.object)?;
|
||||
vm.attach_type(ui, root_types.object)?;
|
||||
let function_type = object(Some(&vm.get_attr(ui, "Function")?))?;
|
||||
vm.set_function_type(function_type)?;
|
||||
vm.set_source_type_checks(true)?;
|
||||
for (name, function, operation) in public_functions {
|
||||
vm.replace_payload(
|
||||
function,
|
||||
ContextNativeFunction::new(
|
||||
name,
|
||||
Function {
|
||||
signature: Some(operation_signature(vm.object_store(), desktop, operation)?),
|
||||
operation,
|
||||
owner: None,
|
||||
session: session.clone(),
|
||||
requested_type: None,
|
||||
},
|
||||
vec![desktop],
|
||||
),
|
||||
)?;
|
||||
}
|
||||
for (name, function) in factories {
|
||||
let operation = match name {
|
||||
"text" => Some(Operation::Text),
|
||||
"rect" => Some(Operation::Rect),
|
||||
"spacer" => Some(Operation::Spacer),
|
||||
"scroll" => Some(Operation::Scroll),
|
||||
"row" => Some(Operation::Row),
|
||||
"column" => Some(Operation::Column),
|
||||
"button" => Some(Operation::Button),
|
||||
"page" => Some(Operation::Page),
|
||||
"window-create" => Some(Operation::NewWindow),
|
||||
"event" | "object-list" => None,
|
||||
_ => return Err(invalid("unknown deferred factory").into()),
|
||||
};
|
||||
if let Some(operation) = operation {
|
||||
let options = operation_signature(vm.object_store(), desktop, operation)?;
|
||||
let envelope = CallSignature {
|
||||
arity: endor_core::CallArity::range(options.arity.required + 1, usize::MAX),
|
||||
parameters: vec![AnnotationType::Type.into()],
|
||||
variadic: Some(AnnotationType::Any.into()),
|
||||
returns: options.returns.clone(),
|
||||
effect: options.effect,
|
||||
};
|
||||
let mut captures = vec![desktop];
|
||||
captures.extend(options.references());
|
||||
vm.replace_payload(
|
||||
function,
|
||||
ContextNativeFunction::new(
|
||||
name,
|
||||
NativeFactory {
|
||||
signature: Some(envelope),
|
||||
options: Some(options),
|
||||
operation,
|
||||
session: session.clone(),
|
||||
},
|
||||
captures,
|
||||
),
|
||||
)?;
|
||||
} else {
|
||||
let kind = if name == "event" {
|
||||
"Event"
|
||||
} else {
|
||||
"ObjectList"
|
||||
};
|
||||
let signature = CallSignature {
|
||||
arity: endor_core::CallArity::range(
|
||||
if name == "event" { 2 } else { 1 },
|
||||
usize::MAX,
|
||||
),
|
||||
parameters: if name == "event" {
|
||||
vec![AnnotationType::Type.into(), AnnotationType::String.into()]
|
||||
} else {
|
||||
vec![AnnotationType::Type.into()]
|
||||
},
|
||||
variadic: Some(AnnotationType::Any.into()),
|
||||
returns: AnnotationType::Nominal(desktop_type(vm.object_store(), kind, desktop)?)
|
||||
.into(),
|
||||
effect: CallEffect::ReadOnly,
|
||||
};
|
||||
if name == "event" {
|
||||
vm.replace_payload(
|
||||
function,
|
||||
ContextNativeFunction::new(
|
||||
name,
|
||||
crate::event_dispatch::Constructor {
|
||||
signature: Some(signature),
|
||||
},
|
||||
vec![],
|
||||
),
|
||||
)?;
|
||||
} else {
|
||||
vm.replace_payload(
|
||||
function,
|
||||
ContextNativeFunction::new(
|
||||
name,
|
||||
crate::object_list::Constructor {
|
||||
desktop,
|
||||
signature: Some(signature),
|
||||
},
|
||||
vec![desktop],
|
||||
),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
for name in [
|
||||
"open",
|
||||
"text",
|
||||
"rect",
|
||||
"spacer",
|
||||
"row",
|
||||
"column",
|
||||
"button",
|
||||
"page",
|
||||
"present",
|
||||
"state",
|
||||
"textOf",
|
||||
"stats",
|
||||
"viewport",
|
||||
"window",
|
||||
"isInstance",
|
||||
"isSubtype",
|
||||
"implement",
|
||||
"implements",
|
||||
"supports",
|
||||
] {
|
||||
let function = object(Some(&vm.get_attr(ui, name)?))?;
|
||||
vm.attach_type(function, function_type)?;
|
||||
}
|
||||
for (type_name, name, operation) in [
|
||||
("Block", "bind", Operation::Bind),
|
||||
("Block", "mounts", Operation::Mounts),
|
||||
("Block", "invalidate", Operation::Invalidate),
|
||||
("Block", "onClick", Operation::OnClick),
|
||||
("Block", "on", Operation::On),
|
||||
("Block", "dispatch", Operation::Dispatch),
|
||||
("Block", "onEvent", Operation::OnEvent),
|
||||
("Block", "onMount", Operation::OnMount),
|
||||
("Block", "onUnmount", Operation::OnUnmount),
|
||||
("Block", "click", Operation::Click),
|
||||
("TextBlock", "setText", Operation::SetText),
|
||||
("TextBlock", "setColor", Operation::SetColor),
|
||||
("RectBlock", "setColor", Operation::SetColor),
|
||||
("ContainerBlock", "append", Operation::Append),
|
||||
("ContainerBlock", "insert", Operation::Insert),
|
||||
("ContainerBlock", "remove", Operation::Remove),
|
||||
("ContainerBlock", "replace", Operation::Replace),
|
||||
("ContainerBlock", "move", Operation::Move),
|
||||
("ContainerBlock", "children", Operation::Children),
|
||||
("Window", "close", Operation::CloseWindow),
|
||||
("Page", "moveToWindow", Operation::MoveWindow),
|
||||
("Page", "moveTab", Operation::MoveTab),
|
||||
("Page", "detachToWindow", Operation::Detach),
|
||||
("Page", "render", Operation::Render),
|
||||
("Page", "unmount", Operation::Unmount),
|
||||
("Page", "open", Operation::Open),
|
||||
("Page", "window", Operation::PageWindow),
|
||||
("Page", "close", Operation::Close),
|
||||
("Page", "activate", Operation::Activate),
|
||||
("Page", "navigate", Operation::Navigate),
|
||||
("Page", "back", Operation::Back),
|
||||
("Page", "forward", Operation::Forward),
|
||||
] {
|
||||
let expected = object(Some(&vm.get_attr(ui, type_name)?))?;
|
||||
let method = vm.allocate(ContextNativeFunction::new(
|
||||
name,
|
||||
TypeMethod {
|
||||
signature: method_signature(vm.object_store(), desktop, expected, operation)?,
|
||||
operation,
|
||||
expected,
|
||||
session: session.clone(),
|
||||
},
|
||||
vec![expected, desktop],
|
||||
))?;
|
||||
roots.push(method);
|
||||
vm.attach_type(method, function_type)?;
|
||||
vm.define_method(expected, name, method)?;
|
||||
}
|
||||
crate::window::install(vm, roots, desktop, tabs)?;
|
||||
let block_type = object(Some(&vm.get_attr(ui, "Block")?))?;
|
||||
crate::native_visual::install(vm, roots, desktop, block_type, function_type)?;
|
||||
let event_type = object(Some(&vm.get_attr(ui, "Event")?))?;
|
||||
let token_type = object(Some(&vm.get_attr(ui, "Subscription")?))?;
|
||||
crate::event_dispatch::install(vm, roots, event_type, token_type, function_type)?;
|
||||
crate::protocols::install(vm, roots, desktop, ui)?;
|
||||
let tasks = crate::tasks::install(vm, roots, ui, desktop)?;
|
||||
developer_pages::install(vm, ui, &session)?;
|
||||
let bridge = UiBridge { ui, session, tasks };
|
||||
developer_pages::install_start_page(vm, &bridge)?;
|
||||
Ok(bridge)
|
||||
}
|
||||
@@ -0,0 +1,789 @@
|
||||
//! Native Block operations executed on the owning VM worker.
|
||||
use super::*;
|
||||
|
||||
impl NativeCallable for Function {
|
||||
fn signature(&self) -> Option<CallSignature> {
|
||||
self.signature.clone()
|
||||
}
|
||||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||||
Some(self.operation.arity())
|
||||
}
|
||||
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
use Operation::*;
|
||||
let arity = self.operation.arity();
|
||||
let (minimum, maximum) = (arity.required, arity.maximum);
|
||||
if !(minimum..=maximum).contains(&args.len()) {
|
||||
return Err(invalid("incorrect UI method argument count"));
|
||||
}
|
||||
if matches!(self.operation, Implement | Implements | Supports) {
|
||||
let capability = object(args.get(1))?;
|
||||
let value = match self.operation {
|
||||
Implement => {
|
||||
cx.implement_trait(object(args.first())?, capability)?;
|
||||
Value::Nil
|
||||
}
|
||||
Implements => Value::Bool(
|
||||
cx.store()
|
||||
.implements_trait(object(args.first())?, capability)?,
|
||||
),
|
||||
Supports => {
|
||||
// Validate the contract even for immediate scalar values.
|
||||
cx.store()
|
||||
.payload::<endor_core::EndorTraitObject>(capability, "Trait")?;
|
||||
Value::Bool(match args[0] {
|
||||
Value::Object(value) => cx.store().supports(value, capability)?,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
return Ok(NativeResult::Return(value));
|
||||
}
|
||||
if matches!(self.operation, IsInstance | IsSubtype) {
|
||||
let candidate = object(args.first())?;
|
||||
let expected = object(args.get(1))?;
|
||||
let value = if matches!(self.operation, IsInstance) {
|
||||
cx.store().is_instance(candidate, expected)?
|
||||
} else {
|
||||
cx.store().is_subtype(candidate, expected)?
|
||||
};
|
||||
return Ok(NativeResult::Return(Value::Bool(value)));
|
||||
}
|
||||
if matches!(self.operation, Invalidate) {
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid(
|
||||
"invalidation is forbidden during read-only rendering",
|
||||
));
|
||||
}
|
||||
let reason = args
|
||||
.first()
|
||||
.map(|value| text(Some(value)))
|
||||
.transpose()?
|
||||
.unwrap_or_else(|| "layout".into());
|
||||
if !matches!(reason.as_str(), "paint" | "layout" | "content") {
|
||||
return Err(invalid(
|
||||
"invalidation reason must be paint, layout or content",
|
||||
));
|
||||
}
|
||||
let owner = self.owner.ok_or(invalid("invalidation requires a Block"))?;
|
||||
let (data, _) = block::resolve(cx.store(), owner)?;
|
||||
let mut session = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
let mut affected = std::collections::HashSet::new();
|
||||
for weak in &session.nodes {
|
||||
if let Some(block) = cx.upgrade(*weak)?
|
||||
&& block::resolve(cx.store(), block)?.0 == data
|
||||
{
|
||||
affected.insert(block);
|
||||
}
|
||||
}
|
||||
for presentation in session.presentations.values_mut() {
|
||||
presentation.invalidate(cx, &affected, &reason)?;
|
||||
}
|
||||
return Ok(NativeResult::Return(Value::Nil));
|
||||
}
|
||||
if matches!(self.operation, Mounts) {
|
||||
let owner = self.owner.ok_or(invalid("mount query requires a Block"))?;
|
||||
let session = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
let mut positions = Vec::new();
|
||||
for (window, presentation) in &session.presentations {
|
||||
for (id, weak) in &presentation.mounts.active {
|
||||
if let Some(object) = cx.upgrade(*weak)?
|
||||
&& cx
|
||||
.store()
|
||||
.payload::<crate::mount::Mount>(object, "Mount")?
|
||||
.block
|
||||
== owner
|
||||
{
|
||||
positions.push((*window, *id, object));
|
||||
}
|
||||
}
|
||||
}
|
||||
positions.sort_unstable_by_key(|(window, id, _)| (*window, *id));
|
||||
let set = crate::mount::collection(
|
||||
cx,
|
||||
positions.into_iter().map(|(_, _, object)| object).collect(),
|
||||
session.desktop,
|
||||
)?;
|
||||
return Ok(NativeResult::Return(Value::Object(set)));
|
||||
}
|
||||
if matches!(self.operation, NewWindow) {
|
||||
let mut state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
let definition = self
|
||||
.requested_type
|
||||
.ok_or(invalid("Window constructor requires a type"))?;
|
||||
let window = create_window(cx, &mut state, definition)?;
|
||||
return Ok(NativeResult::Return(Value::Object(window)));
|
||||
}
|
||||
if matches!(self.operation, CloseWindow) {
|
||||
let window = self
|
||||
.owner
|
||||
.ok_or(invalid("window close requires a receiver"))?;
|
||||
let id = cx
|
||||
.store()
|
||||
.payload::<crate::window::ManagedWindow>(window, "Window")?
|
||||
.id;
|
||||
crate::window::close(cx, window)?;
|
||||
let mut state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
if let Some(view) = state.presentations.get_mut(&id) {
|
||||
cx.set_attr(view.desktop, "pending", Value::Nil)?;
|
||||
view.pending = Some(None);
|
||||
view.force_frame = true;
|
||||
view.closing = true;
|
||||
}
|
||||
return Ok(NativeResult::Return(Value::Nil));
|
||||
}
|
||||
if matches!(self.operation, Window) {
|
||||
let desktop = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?
|
||||
.desktop;
|
||||
return Ok(NativeResult::Return(
|
||||
cx.store().get_attr(desktop, "window")?,
|
||||
));
|
||||
}
|
||||
if matches!(self.operation, Viewport) {
|
||||
let desktop = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?
|
||||
.desktop;
|
||||
let Value::Object(input) = cx.store().get_attr(desktop, "viewport")? else {
|
||||
return Err(invalid("window viewport is unavailable"));
|
||||
};
|
||||
let width = cx.store().get_attr(input, "width")?;
|
||||
let height = cx.store().get_attr(input, "height")?;
|
||||
return Ok(NativeResult::Return(Value::Object(
|
||||
crate::native_visual::record(
|
||||
cx,
|
||||
desktop,
|
||||
"MeasureResult",
|
||||
vec![("width", width), ("height", height)],
|
||||
)?,
|
||||
)));
|
||||
}
|
||||
if matches!(self.operation, Stats) {
|
||||
if cx.store().is_read_only() {
|
||||
return Err(invalid(
|
||||
"runtime statistics are unavailable during read-only rendering",
|
||||
));
|
||||
}
|
||||
let session = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
let mut blocks = 0_i64;
|
||||
let mut pages = 0_i64;
|
||||
for weak in &session.nodes {
|
||||
if let Some(object) = cx.upgrade(*weak)? {
|
||||
blocks += 1;
|
||||
if cx.store().payload::<block::Block>(object, "Block")?.page {
|
||||
pages += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let objects = cx.store().object_count() as i64;
|
||||
let tabs = cx.store().dict_items(session.tabs)?.len() as i64;
|
||||
let stats = cx.new_object()?;
|
||||
for (name, value) in [
|
||||
("objects", objects),
|
||||
("blocks", blocks),
|
||||
("pages", pages),
|
||||
("tabs", tabs),
|
||||
("mounts", session.mounts.active.len() as i64),
|
||||
("snapshotVisited", session.snapshot_visited as i64),
|
||||
("snapshotReused", session.snapshot_reused as i64),
|
||||
("measured", session.layout.measured as i64),
|
||||
("sourceMeasureHits", session.measure_cache.hits as i64),
|
||||
("sourceMeasureMisses", session.measure_cache.misses as i64),
|
||||
("arranged", session.layout.arranged as i64),
|
||||
("layoutPasses", session.layout.settle_passes as i64),
|
||||
("layoutSlices", session.layout.slices as i64),
|
||||
("refreshYields", session.refresh_yields as i64),
|
||||
("refreshRestarts", session.refresh_restarts as i64),
|
||||
("layoutCancels", session.layout_cancels as i64),
|
||||
("paintCancels", session.paint_cancels as i64),
|
||||
("paintSlices", session.paint_slices as i64),
|
||||
("bindingEvaluations", session.binding_evaluations as i64),
|
||||
(
|
||||
"dependencyInvalidations",
|
||||
session.dependency_invalidations as i64,
|
||||
),
|
||||
] {
|
||||
cx.set_attr(stats, name, Value::Number(value.into()))?;
|
||||
}
|
||||
cx.set_attr(
|
||||
stats,
|
||||
"lastInvalidDependency",
|
||||
Value::Text(session.last_invalid_dependency.clone()),
|
||||
)?;
|
||||
cx.set_attr(
|
||||
stats,
|
||||
"windowDependencyDiagnostics",
|
||||
Value::Text(
|
||||
session
|
||||
.presentations
|
||||
.iter()
|
||||
.filter(|(_, view)| !view.last_invalid_dependency.is_empty())
|
||||
.map(|(id, view)| format!("{id}: {}", view.last_invalid_dependency))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; "),
|
||||
),
|
||||
)?;
|
||||
return Ok(NativeResult::Return(Value::Object(stats)));
|
||||
}
|
||||
if matches!(self.operation, State) {
|
||||
let state = cx.new_object()?;
|
||||
attach_named_type(cx, state, "Object", &self.session)?;
|
||||
cx.set_attr(state, "value", args[0].clone())?;
|
||||
bind(cx, state, "set", StateSet, &self.session)?;
|
||||
bind(cx, state, "increment", Increment, &self.session)?;
|
||||
return Ok(NativeResult::Return(Value::Object(state)));
|
||||
}
|
||||
if matches!(self.operation, StateSet | Increment) {
|
||||
let owner = self.owner.ok_or(invalid("state method has no owner"))?;
|
||||
let value = if matches!(self.operation, StateSet) {
|
||||
args[0].clone()
|
||||
} else {
|
||||
let Value::Number(value) = cx.store().get_attr(owner, "value")? else {
|
||||
return Err(invalid("increment requires an integer state"));
|
||||
};
|
||||
let next = value
|
||||
.as_i64()
|
||||
.and_then(|n| n.checked_add(1))
|
||||
.ok_or(invalid("integer state increment exceeds its range"))?;
|
||||
Value::Number(next.into())
|
||||
};
|
||||
cx.set_attr(owner, "value", value)?;
|
||||
return Ok(NativeResult::Return(Value::Nil));
|
||||
}
|
||||
if matches!(self.operation, TextOf) {
|
||||
let source = object(args.first())?;
|
||||
let field = text(args.get(1))?;
|
||||
cx.store().get_attr(source, &field)?;
|
||||
let size = args
|
||||
.get(2)
|
||||
.map(|v| integer(Some(v)))
|
||||
.transpose()?
|
||||
.unwrap_or(1);
|
||||
if !(1..=8).contains(&size) {
|
||||
return Err(invalid("text size must be 1 through 8"));
|
||||
}
|
||||
let mut data = Data::new(
|
||||
Kind::Text {
|
||||
value: String::new(),
|
||||
size: size as u32,
|
||||
color: color(args.get(3), "#242422")?,
|
||||
},
|
||||
vec![],
|
||||
0.0,
|
||||
0.0,
|
||||
);
|
||||
data.text_binding = Some((source, field));
|
||||
return Ok(NativeResult::Return(Value::Object(new_block(
|
||||
cx,
|
||||
data,
|
||||
&self.session,
|
||||
)?)));
|
||||
}
|
||||
let constructor = match self.operation {
|
||||
Scroll => Some(Data::new(
|
||||
Kind::Scroll {
|
||||
width: dimension(args.first())?,
|
||||
height: dimension(args.get(1))?,
|
||||
},
|
||||
vec![object(args.get(2))?],
|
||||
0.0,
|
||||
0.0,
|
||||
)),
|
||||
Text => Some(Data::new(
|
||||
Kind::Text {
|
||||
value: text(args.first())?,
|
||||
size: args
|
||||
.get(1)
|
||||
.map(|v| integer(Some(v)))
|
||||
.transpose()?
|
||||
.unwrap_or(1)
|
||||
.try_into()
|
||||
.map_err(|_| invalid("text size exceeds limits"))?,
|
||||
color: color(args.get(2), "#242422")?,
|
||||
},
|
||||
vec![],
|
||||
0.0,
|
||||
0.0,
|
||||
)),
|
||||
Rect => Some(Data::new(
|
||||
Kind::Rect {
|
||||
width: dimension(args.first())?,
|
||||
height: dimension(args.get(1))?,
|
||||
radius: args
|
||||
.get(2)
|
||||
.map(|v| dimension(Some(v)))
|
||||
.transpose()?
|
||||
.unwrap_or(0.0),
|
||||
color: color(args.get(3), "#DCE8FF")?,
|
||||
},
|
||||
vec![],
|
||||
0.0,
|
||||
0.0,
|
||||
)),
|
||||
Spacer => Some(Data::new(
|
||||
Kind::Spacer(dimension(args.first())?),
|
||||
vec![],
|
||||
0.0,
|
||||
0.0,
|
||||
)),
|
||||
Row | Column => Some(Data::new(
|
||||
if matches!(self.operation, Row) {
|
||||
Kind::Row
|
||||
} else {
|
||||
Kind::Column
|
||||
},
|
||||
args[2..]
|
||||
.iter()
|
||||
.map(|v| object(Some(v)))
|
||||
.collect::<Result<_, _>>()?,
|
||||
dimension(args.first())?,
|
||||
dimension(args.get(1))?,
|
||||
)),
|
||||
Page => Some(Data::new(Kind::Page, vec![], 0.0, 0.0)),
|
||||
Button => {
|
||||
let label = new_block(
|
||||
cx,
|
||||
Data::new(
|
||||
Kind::Text {
|
||||
value: text(args.first())?,
|
||||
size: 1,
|
||||
color: "#243047".into(),
|
||||
},
|
||||
vec![],
|
||||
0.0,
|
||||
0.0,
|
||||
),
|
||||
&self.session,
|
||||
)?;
|
||||
Some(Data::new(Kind::Button, vec![label], 10.0, 0.0))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(data) = constructor {
|
||||
if let Kind::Text { size, value, .. } = &data.kind
|
||||
&& (!(1..=8).contains(size) || value.len() > 16_384)
|
||||
{
|
||||
return Err(invalid("text exceeds size limits"));
|
||||
}
|
||||
return Ok(NativeResult::Return(Value::Object(new_typed_block(
|
||||
cx,
|
||||
data,
|
||||
&self.session,
|
||||
self.requested_type,
|
||||
)?)));
|
||||
}
|
||||
if matches!(self.operation, OpenValue | Present)
|
||||
&& let Value::Object(value) = args[0]
|
||||
{
|
||||
let (desktop, current) = {
|
||||
let state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
(state.master, state.desktop)
|
||||
};
|
||||
let capability = desktop_type(cx.store(), "Presentable", desktop)?;
|
||||
if !cx
|
||||
.store()
|
||||
.object(value)?
|
||||
.payload()
|
||||
.as_any()
|
||||
.is::<block::Block>()
|
||||
&& cx.store().supports(value, capability)?
|
||||
{
|
||||
let definition = cx
|
||||
.store()
|
||||
.type_of(value)?
|
||||
.ok_or(invalid("untyped Presentable"))?;
|
||||
let function = cx
|
||||
.store()
|
||||
.lookup_method(definition, "present")?
|
||||
.ok_or(invalid("missing present method"))?;
|
||||
let window = object(Some(&cx.store().get_attr(current, "window")?))?;
|
||||
let complete = cx.allocate(ContextNativeFunction::new(
|
||||
"validate presentation",
|
||||
PresentResult {
|
||||
open: matches!(self.operation, OpenValue),
|
||||
session: self.session.clone(),
|
||||
},
|
||||
vec![desktop],
|
||||
))?;
|
||||
let instructions = [
|
||||
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 0),
|
||||
endor_core::Instruction::simple(endor_core::Opcode::PushNull),
|
||||
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 1),
|
||||
endor_core::Instruction::simple(endor_core::Opcode::PushNull),
|
||||
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 2),
|
||||
endor_core::Instruction::new(endor_core::Opcode::LoadConst, 3),
|
||||
endor_core::Instruction::new(endor_core::Opcode::Call, 2),
|
||||
endor_core::Instruction::new(endor_core::Opcode::Call, 1),
|
||||
endor_core::Instruction::simple(endor_core::Opcode::ReturnValue),
|
||||
];
|
||||
let code = endor_core::EndorCode::from_instructions(
|
||||
&instructions,
|
||||
vec![
|
||||
Value::Object(complete),
|
||||
Value::Object(function),
|
||||
Value::Object(value),
|
||||
Value::Object(window),
|
||||
],
|
||||
endor_core::CodeLayout::default(),
|
||||
)?
|
||||
.with_location("Presentable.present", "<tessera>", 1);
|
||||
let code = cx.allocate(endor_core::EndorCodeObject::new(code))?;
|
||||
let globals = cx.new_dict()?;
|
||||
let driver = cx.new_function("Presentable.present", code, globals)?;
|
||||
attach_desktop_type(cx, driver, "Function", desktop)?;
|
||||
return Ok(NativeResult::Invoke {
|
||||
function: driver,
|
||||
arguments: vec![],
|
||||
});
|
||||
}
|
||||
}
|
||||
if matches!(self.operation, OpenValue) {
|
||||
let root = present_value(cx, &args[0], &self.session)?;
|
||||
let page = if cx.store().payload::<block::Block>(root, "Block")?.page {
|
||||
root
|
||||
} else {
|
||||
new_block(
|
||||
cx,
|
||||
Data::new(Kind::Page, vec![root], 0.0, 0.0),
|
||||
&self.session,
|
||||
)?
|
||||
};
|
||||
show(cx, page, &self.session)?;
|
||||
return Ok(NativeResult::Return(Value::Object(page)));
|
||||
}
|
||||
if matches!(self.operation, Present) {
|
||||
return Ok(NativeResult::Return(Value::Object(present_value(
|
||||
cx,
|
||||
&args[0],
|
||||
&self.session,
|
||||
)?)));
|
||||
}
|
||||
let owner = self.owner.ok_or(invalid("method has no owner"))?;
|
||||
if matches!(self.operation, Bind) {
|
||||
let field = text(args.first())?;
|
||||
let compute = object(args.get(1))?;
|
||||
return Ok(NativeResult::Return(Value::Object(
|
||||
crate::binding::connect(
|
||||
cx,
|
||||
owner,
|
||||
&field,
|
||||
compute,
|
||||
self.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?
|
||||
.master,
|
||||
)?,
|
||||
)));
|
||||
}
|
||||
if matches!(self.operation, MoveTab) {
|
||||
let position = usize::try_from(integer(args.first())?)
|
||||
.map_err(|_| invalid("tab position out of range"))?;
|
||||
let mut state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
let id = page_window(cx.store(), &state, owner)?.ok_or(invalid("Page is not open"))?;
|
||||
let view = state
|
||||
.presentations
|
||||
.get_mut(&id)
|
||||
.ok_or(invalid("missing window"))?;
|
||||
let window = object(Some(&cx.store().get_attr(view.desktop, "window")?))?;
|
||||
crate::window::move_page(cx, window, owner, position)?;
|
||||
view.force_frame = true;
|
||||
return Ok(NativeResult::Return(Value::Object(owner)));
|
||||
}
|
||||
let (data_ref, data) = block::resolve(cx.store(), owner)?;
|
||||
let mut data = data.clone();
|
||||
let mut result = Value::Nil;
|
||||
match self.operation {
|
||||
SetText => match &mut data.kind {
|
||||
Kind::Text { value, .. } => {
|
||||
let next = text(args.first())?;
|
||||
if next.len() > 16_384 {
|
||||
return Err(invalid("text exceeds 16 KiB"));
|
||||
}
|
||||
*value = next;
|
||||
data.text_binding = None;
|
||||
cx.set_attr(owner, "text", args[0].clone())?;
|
||||
}
|
||||
_ => return Err(invalid("setText requires a text Block")),
|
||||
},
|
||||
SetColor => match &mut data.kind {
|
||||
Kind::Text { color: value, .. } | Kind::Rect { color: value, .. } => {
|
||||
*value = color(args.first(), "#242422")?;
|
||||
cx.set_attr(owner, "color", Value::Text(value.clone()))?;
|
||||
}
|
||||
_ => return Err(invalid("this Block has no color")),
|
||||
},
|
||||
Append | Insert | Remove | Replace | Move => {
|
||||
if !data.is_container() {
|
||||
return Err(invalid("expected a container Block"));
|
||||
}
|
||||
if matches!(self.operation, Append | Insert) {
|
||||
let (position, argument) = if matches!(self.operation, Insert) {
|
||||
let position = usize::try_from(integer(args.first())?)
|
||||
.map_err(|_| invalid("child position out of range"))?;
|
||||
if position > data.children.len() {
|
||||
return Err(invalid("child position out of range"));
|
||||
}
|
||||
(position, args.get(1))
|
||||
} else {
|
||||
(data.children.len(), args.first())
|
||||
};
|
||||
let child = object(argument)?;
|
||||
block::validate(cx.store(), child, Some(data_ref))?;
|
||||
let slot = data.next_slot;
|
||||
data.next_slot = slot
|
||||
.checked_add(1)
|
||||
.filter(|next| *next <= i64::MAX as u64)
|
||||
.ok_or(VmError::IdentityExhausted)?;
|
||||
data.children.insert(position, Child { slot, block: child });
|
||||
result = Value::Number((slot as i64).into());
|
||||
} else {
|
||||
let slot = integer(args.first())?;
|
||||
let index = data
|
||||
.children
|
||||
.iter()
|
||||
.position(|v| v.slot == slot)
|
||||
.ok_or(invalid("child slot does not exist"))?;
|
||||
match self.operation {
|
||||
Remove => {
|
||||
data.children.remove(index);
|
||||
}
|
||||
Replace => {
|
||||
let child = object(args.get(1))?;
|
||||
block::validate(cx.store(), child, Some(data_ref))?;
|
||||
data.children[index].block = child;
|
||||
}
|
||||
Move => {
|
||||
let to = usize::try_from(integer(args.get(1))?)
|
||||
.map_err(|_| invalid("child position out of range"))?;
|
||||
if to >= data.children.len() {
|
||||
return Err(invalid("child position out of range"));
|
||||
}
|
||||
let child = data.children.remove(index);
|
||||
data.children.insert(to, child);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Children => {
|
||||
let result = cx.new_dict()?;
|
||||
for child in data.children {
|
||||
cx.dict_set(
|
||||
result,
|
||||
Value::Text(child.slot.to_string()),
|
||||
Value::Object(child.block),
|
||||
)?;
|
||||
}
|
||||
return Ok(NativeResult::Return(Value::Object(result)));
|
||||
}
|
||||
Render | Navigate => {
|
||||
if !matches!(data.kind, Kind::Page) {
|
||||
return Err(invalid("expected a Page"));
|
||||
}
|
||||
let root = object(args.first())?;
|
||||
block::validate(cx.store(), root, Some(data_ref))?;
|
||||
if matches!(self.operation, Navigate) {
|
||||
if data.history.is_empty() {
|
||||
if let Some(old) = data.children.first() {
|
||||
data.history.push(old.block);
|
||||
}
|
||||
} else {
|
||||
data.history.truncate(data.history_index + 1);
|
||||
}
|
||||
data.history.push(root);
|
||||
data.history_index = data.history.len() - 1;
|
||||
}
|
||||
data.children = vec![Child {
|
||||
slot: 0,
|
||||
block: root,
|
||||
}];
|
||||
data.next_slot = data.next_slot.max(1);
|
||||
show(cx, owner, &self.session)?;
|
||||
}
|
||||
Back | Forward => {
|
||||
if data.history.is_empty() {
|
||||
return Ok(NativeResult::Return(Value::Nil));
|
||||
}
|
||||
let next = if matches!(self.operation, Back) {
|
||||
data.history_index.saturating_sub(1)
|
||||
} else {
|
||||
(data.history_index + 1).min(data.history.len() - 1)
|
||||
};
|
||||
data.history_index = next;
|
||||
data.children = vec![Child {
|
||||
slot: 0,
|
||||
block: data.history[next],
|
||||
}];
|
||||
show(cx, owner, &self.session)?;
|
||||
}
|
||||
Detach => {
|
||||
let window = {
|
||||
let mut state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
let definition = desktop_type(cx.store(), "Window", state.master)?;
|
||||
create_window(cx, &mut state, definition)?
|
||||
};
|
||||
show_in(cx, owner, &self.session, Some(window))?;
|
||||
return Ok(NativeResult::Return(Value::Object(window)));
|
||||
}
|
||||
PageWindow => {
|
||||
let state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
let value = if let Some(id) = page_window(cx.store(), &state, owner)? {
|
||||
cx.store()
|
||||
.get_attr(state.presentations[&id].desktop, "window")?
|
||||
} else {
|
||||
Value::Nil
|
||||
};
|
||||
return Ok(NativeResult::Return(value));
|
||||
}
|
||||
Open | Activate | MoveWindow => {
|
||||
if matches!(self.operation, MoveWindow)
|
||||
&& matches!(args.first(), None | Some(Value::Nil))
|
||||
{
|
||||
return Err(invalid("Page.moveToWindow requires a Window"));
|
||||
}
|
||||
let target = match args.first() {
|
||||
None | Some(Value::Nil) => None,
|
||||
Some(value) => Some(object(Some(value))?),
|
||||
};
|
||||
show_in(cx, owner, &self.session, target)?;
|
||||
return Ok(NativeResult::Return(Value::Object(owner)));
|
||||
}
|
||||
Unmount => {
|
||||
data.children.clear();
|
||||
}
|
||||
Close => {
|
||||
crate::tasks::cancel_owner(cx, owner)?;
|
||||
let mut state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
if let Some(id) = page_window(cx.store(), &state, owner)? {
|
||||
// Closing the tab ends its presentation even if source
|
||||
// reopens it before the next layout can detach the Mounts.
|
||||
let page = cx.store().downgrade(owner)?;
|
||||
for weak in state.presentations[&id].mounts.ordered() {
|
||||
if let Some(mount) = cx.upgrade(weak)?
|
||||
&& cx
|
||||
.store()
|
||||
.payload::<crate::mount::Mount>(mount, "Mount")?
|
||||
.page
|
||||
== Some(page)
|
||||
{
|
||||
crate::tasks::cancel_owner(cx, mount)?;
|
||||
}
|
||||
}
|
||||
remove_page(
|
||||
cx,
|
||||
state
|
||||
.presentations
|
||||
.get_mut(&id)
|
||||
.ok_or(invalid("missing window"))?,
|
||||
owner,
|
||||
)?;
|
||||
}
|
||||
return Ok(NativeResult::Return(Value::Nil));
|
||||
}
|
||||
OnClick => {
|
||||
let handler = object(args.first())?;
|
||||
crate::event_dispatch::validate_handler(cx.store(), handler)?;
|
||||
data.click = Some(handler);
|
||||
result = Value::Object(owner);
|
||||
}
|
||||
On => {
|
||||
let kind = text(args.first())?;
|
||||
if kind.is_empty() || kind.len() > 128 {
|
||||
return Err(invalid("invalid event kind"));
|
||||
}
|
||||
let handler = object(args.get(1))?;
|
||||
crate::event_dispatch::validate_handler(cx.store(), handler)?;
|
||||
let capture = match args.get(2) {
|
||||
None | Some(Value::Bool(false)) => false,
|
||||
Some(Value::Bool(true)) => true,
|
||||
Some(Value::Text(phase)) if phase == "capture" => true,
|
||||
Some(Value::Text(phase)) if phase == "bubble" => false,
|
||||
_ => return Err(invalid("phase must be capture or bubble")),
|
||||
};
|
||||
let mut active = Vec::new();
|
||||
for token in &data.subscriptions {
|
||||
if cx
|
||||
.store()
|
||||
.payload::<crate::event_dispatch::Connection>(*token, "Connection")?
|
||||
.handler
|
||||
.is_some()
|
||||
{
|
||||
active.push(*token);
|
||||
}
|
||||
}
|
||||
if active.len() >= MAX_UI_NODES {
|
||||
return Err(invalid("too many event subscriptions"));
|
||||
}
|
||||
let connection = cx.allocate(crate::event_dispatch::Connection {
|
||||
kind,
|
||||
handler: Some(handler),
|
||||
capture,
|
||||
})?;
|
||||
let token = cx.allocate(crate::event_dispatch::Subscription {
|
||||
connection: cx.store().downgrade(connection)?,
|
||||
})?;
|
||||
attach_named_type(cx, token, "Subscription", &self.session)?;
|
||||
active.push(connection);
|
||||
data.subscriptions = active;
|
||||
result = Value::Object(token);
|
||||
}
|
||||
OnEvent | OnMount | OnUnmount => return Ok(NativeResult::Return(Value::Nil)),
|
||||
Click | Dispatch => {
|
||||
let desktop = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?
|
||||
.desktop;
|
||||
let (event, mount) = if matches!(self.operation, Click) {
|
||||
let definition = desktop_type(cx.store(), "Event", desktop)?;
|
||||
(
|
||||
crate::event_dispatch::new_event(cx, definition, "click")?,
|
||||
args.first(),
|
||||
)
|
||||
} else {
|
||||
(object(args.first())?, args.get(1))
|
||||
};
|
||||
let mount = mount.map(|value| object(Some(value))).transpose()?;
|
||||
return crate::event_dispatch::dispatch(cx, owner, event, mount, desktop);
|
||||
}
|
||||
_ => return Err(invalid("unsupported Block operation")),
|
||||
}
|
||||
cx.replace_payload(data_ref, data)?;
|
||||
Ok(NativeResult::Return(result))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Developer workspaces are managed Pages, using the same roots and placement API.
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct OpenTool {
|
||||
session: Shared,
|
||||
ui: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for OpenTool {
|
||||
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::Text(name)] = args else {
|
||||
return Err(invalid("developerTools requires a tool name"));
|
||||
};
|
||||
if !["Console", "Sources", "Network", "Settings", "New tab"].contains(&name.as_str()) {
|
||||
return Err(invalid("unknown developer tool"));
|
||||
}
|
||||
if name == "New tab" {
|
||||
let factory = object(Some(&cx.store().get_attr(self.ui, "newTab")?))?;
|
||||
return Ok(NativeResult::Invoke {
|
||||
function: factory,
|
||||
arguments: vec![],
|
||||
});
|
||||
}
|
||||
let nodes = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?
|
||||
.nodes
|
||||
.clone();
|
||||
for weak in nodes {
|
||||
if let Some(page) = cx.upgrade(weak)?
|
||||
&& cx.store().get_attr(page, "_tesseraTool").ok() == Some(Value::Text(name.clone()))
|
||||
{
|
||||
show(cx, page, &self.session)?;
|
||||
let window = {
|
||||
let state = self
|
||||
.session
|
||||
.lock()
|
||||
.map_err(|_| invalid("UI session poisoned"))?;
|
||||
let id = page_window(cx.store(), &state, page)?
|
||||
.ok_or(invalid("tool is not open"))?;
|
||||
object(Some(
|
||||
&cx.store()
|
||||
.get_attr(state.presentations[&id].desktop, "window")?,
|
||||
))?
|
||||
};
|
||||
crate::window::enqueue(cx, window, crate::window::Action::Focus)?;
|
||||
return Ok(NativeResult::Return(Value::Object(page)));
|
||||
}
|
||||
}
|
||||
let page = new_typed_block(
|
||||
cx,
|
||||
Data::new(Kind::Page, vec![], 0.0, 0.0),
|
||||
&self.session,
|
||||
None,
|
||||
)?;
|
||||
cx.set_attr(page, "title", Value::Text(name.clone()))?;
|
||||
cx.set_attr(page, "_tesseraTool", Value::Text(name.clone()))?;
|
||||
show(cx, page, &self.session)?;
|
||||
Ok(NativeResult::Return(Value::Object(page)))
|
||||
}
|
||||
}
|
||||
pub(super) fn install(vm: &mut Vm, ui: ObjectRef, session: &Shared) -> Result<()> {
|
||||
let function = vm.allocate(ContextNativeFunction::new(
|
||||
"developerTools",
|
||||
OpenTool {
|
||||
session: session.clone(),
|
||||
ui,
|
||||
},
|
||||
vec![ui],
|
||||
))?;
|
||||
vm.set_attr(ui, "developerTools", Value::Object(function))?;
|
||||
vm.release(function)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compile the bundled Endor page once per VM, in a private module namespace.
|
||||
/// Its functions/classes and callbacks remain ordinary managed VM objects.
|
||||
pub(super) fn install_start_page(vm: &mut Vm, bridge: &UiBridge) -> Result<()> {
|
||||
let source = frontend::EndorReader::from_text(
|
||||
"tessera:start-page.endor",
|
||||
include_str!("start_page.endor"),
|
||||
);
|
||||
let ast = frontend::parse_source_ast(&source, frontend::ParseMode::Module)?;
|
||||
let compiled = compiler::compile_ast(
|
||||
&ast,
|
||||
&source,
|
||||
&compiler::CompileOptions {
|
||||
globals: std::iter::once("ui")
|
||||
.chain(TYPE_NAMES.iter().copied())
|
||||
.map(str::to_owned)
|
||||
.collect(),
|
||||
},
|
||||
)
|
||||
.map_err(|error| source.annotate(error))?;
|
||||
let globals = vm.new_dict()?;
|
||||
let result = (|| -> Result<()> {
|
||||
bridge.install_globals(vm, globals)?;
|
||||
let code = compiled.load(vm)?;
|
||||
let value = vm.execute_with_limits(
|
||||
code,
|
||||
globals,
|
||||
endor_core::ExecutionLimits {
|
||||
max_frames: 128,
|
||||
max_instructions: 100_000,
|
||||
},
|
||||
);
|
||||
vm.release(code)?;
|
||||
vm.release_value(value?)?;
|
||||
let factory = vm
|
||||
.dict_get(globals, &Value::Text("newTab".into()))?
|
||||
.ok_or_else(|| anyhow::anyhow!("start page module requires newTab"))?;
|
||||
vm.set_attr(bridge.ui, "newTab", factory)?;
|
||||
Ok(())
|
||||
})();
|
||||
vm.release(globals)?;
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Canonical contracts for native Block methods and constructors.
|
||||
use super::*;
|
||||
|
||||
pub(super) fn method_signature(
|
||||
store: &endor_core::ObjectStore,
|
||||
desktop: ObjectRef,
|
||||
receiver: ObjectRef,
|
||||
operation: Operation,
|
||||
) -> Result<CallSignature, VmError> {
|
||||
use AnnotationType::{Any, Function, Nominal, Number, String as TextType, Unit};
|
||||
use Operation::*;
|
||||
let nominal = |name| desktop_type(store, name, desktop).map(Nominal);
|
||||
let (arguments, returns, effect) = match operation {
|
||||
Bind => (
|
||||
vec![TextType, Function],
|
||||
nominal("Subscription")?,
|
||||
CallEffect::Mutating,
|
||||
),
|
||||
Mounts => (vec![], nominal("ObjectList")?, CallEffect::ReadOnly),
|
||||
Children => (vec![], Any, CallEffect::ReadOnly),
|
||||
Invalidate => (vec![TextType], Unit, CallEffect::Mutating),
|
||||
SetText | SetColor => (vec![TextType], Unit, CallEffect::Mutating),
|
||||
Append => (vec![nominal("Block")?], Number, CallEffect::Mutating),
|
||||
Insert => (
|
||||
vec![Number, nominal("Block")?],
|
||||
Number,
|
||||
CallEffect::Mutating,
|
||||
),
|
||||
Remove => (vec![Number], Unit, CallEffect::Mutating),
|
||||
Replace => (vec![Number, nominal("Block")?], Unit, CallEffect::Mutating),
|
||||
Move => (vec![Number, Number], Unit, CallEffect::Mutating),
|
||||
Render | Navigate => (vec![nominal("Block")?], Unit, CallEffect::Mutating),
|
||||
OnClick => (vec![Function], Nominal(receiver), CallEffect::Mutating),
|
||||
OnEvent => (vec![nominal("Event")?], Unit, CallEffect::External),
|
||||
OnMount | OnUnmount => (vec![nominal("Mount")?], Unit, CallEffect::External),
|
||||
Click => (
|
||||
vec![nominal("Mount")?],
|
||||
nominal("Event")?,
|
||||
CallEffect::External,
|
||||
),
|
||||
Dispatch => (
|
||||
vec![nominal("Event")?, nominal("Mount")?],
|
||||
nominal("Event")?,
|
||||
CallEffect::External,
|
||||
),
|
||||
MoveWindow => (
|
||||
vec![nominal("Window")?],
|
||||
Nominal(receiver),
|
||||
CallEffect::Mutating,
|
||||
),
|
||||
MoveTab => (vec![Number], Nominal(receiver), CallEffect::Mutating),
|
||||
Activate => (vec![], Nominal(receiver), CallEffect::Mutating),
|
||||
Detach => (vec![], nominal("Window")?, CallEffect::Mutating),
|
||||
Unmount | Close | CloseWindow | Back | Forward => (vec![], Unit, CallEffect::Mutating),
|
||||
Open => (vec![Any], Nominal(receiver), CallEffect::Mutating),
|
||||
PageWindow => (vec![], Any, CallEffect::ReadOnly),
|
||||
On => (
|
||||
vec![TextType, Function, Any],
|
||||
nominal("Subscription")?,
|
||||
CallEffect::Mutating,
|
||||
),
|
||||
_ => return Err(invalid("unsupported native method signature")),
|
||||
};
|
||||
let arity = operation.arity();
|
||||
let mut parameters = vec![Nominal(receiver)];
|
||||
parameters.extend(arguments);
|
||||
let mut signature = CallSignature {
|
||||
arity: endor_core::CallArity::range(arity.required + 1, arity.maximum + 1),
|
||||
parameters: parameters.into_iter().map(CallType::from).collect(),
|
||||
variadic: None,
|
||||
returns: returns.into(),
|
||||
effect,
|
||||
};
|
||||
match operation {
|
||||
Open => signature.parameters[1] = CallType::nullable(nominal("Window")?),
|
||||
PageWindow => signature.returns = CallType::nullable(nominal("Window")?),
|
||||
On => signature.parameters[3] = CallType::Union(vec![AnnotationType::Bool, TextType]),
|
||||
_ => {}
|
||||
}
|
||||
Ok(signature)
|
||||
}
|
||||
|
||||
pub(super) fn operation_signature(
|
||||
store: &endor_core::ObjectStore,
|
||||
desktop: ObjectRef,
|
||||
operation: Operation,
|
||||
) -> Result<CallSignature, VmError> {
|
||||
use AnnotationType::{Any, Bool, Number, String as TextType, Trait, Type, Unit};
|
||||
use Operation::*;
|
||||
let nominal = |name| desktop_type(store, name, desktop).map(AnnotationType::Nominal);
|
||||
let (parameters, variadic, returns, effect) = match operation {
|
||||
IsInstance => (vec![Any, Type], None, Bool, CallEffect::ReadOnly),
|
||||
IsSubtype => (vec![Type, Type], None, Bool, CallEffect::ReadOnly),
|
||||
Implement => (vec![Type, Trait], None, Unit, CallEffect::Mutating),
|
||||
Implements => (vec![Type, Trait], None, Bool, CallEffect::ReadOnly),
|
||||
Supports => (vec![Any, Trait], None, Bool, CallEffect::ReadOnly),
|
||||
OpenValue => (vec![Any], None, nominal("Page")?, CallEffect::Mutating),
|
||||
Present => (vec![Any], None, nominal("Block")?, CallEffect::Delegated),
|
||||
State => (vec![Any], None, Any, CallEffect::ReadOnly),
|
||||
StateSet => (vec![Any], None, Unit, CallEffect::Mutating),
|
||||
Increment => (vec![], None, Unit, CallEffect::Mutating),
|
||||
Stats => (vec![], None, Any, CallEffect::External),
|
||||
Viewport => (
|
||||
vec![],
|
||||
None,
|
||||
nominal("MeasureResult")?,
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
Window => (vec![], None, nominal("Window")?, CallEffect::ReadOnly),
|
||||
NewWindow => (vec![], None, nominal("Window")?, CallEffect::Mutating),
|
||||
TextOf => (
|
||||
vec![Any, TextType, Number, TextType],
|
||||
None,
|
||||
nominal("TextBlock")?,
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
Text => (
|
||||
vec![TextType, Number, TextType],
|
||||
None,
|
||||
nominal("TextBlock")?,
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
Rect => (
|
||||
vec![Number, Number, Number, TextType],
|
||||
None,
|
||||
nominal("RectBlock")?,
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
Spacer => (vec![Number], None, nominal("Spacer")?, CallEffect::ReadOnly),
|
||||
Scroll => (
|
||||
vec![Number, Number, nominal("Block")?],
|
||||
None,
|
||||
nominal("ScrollBlock")?,
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
Row | Column => (
|
||||
vec![Number, Number],
|
||||
Some(nominal("Block")?),
|
||||
nominal(if matches!(operation, Row) {
|
||||
"Row"
|
||||
} else {
|
||||
"Column"
|
||||
})?,
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
Button => (
|
||||
vec![TextType],
|
||||
None,
|
||||
nominal("Button")?,
|
||||
CallEffect::ReadOnly,
|
||||
),
|
||||
Page => (vec![], None, nominal("Page")?, CallEffect::ReadOnly),
|
||||
_ => return Err(invalid("unsupported UI function signature")),
|
||||
};
|
||||
Ok(CallSignature {
|
||||
arity: operation.arity(),
|
||||
parameters: parameters.into_iter().map(CallType::from).collect(),
|
||||
variadic: variadic.map(CallType::from),
|
||||
returns: returns.into(),
|
||||
effect,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Tessera's start page is an ordinary Endor Page, including its layout and actions.
|
||||
// This module has its own globals; creating tabs does not replace user bindings.
|
||||
class StartPage: Page {
|
||||
function measure(self: StartPage, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
return MeasureResult(constraints.maxWidth, constraints.maxHeight)
|
||||
}
|
||||
}
|
||||
class StartRow: Row {
|
||||
function measure(self: StartRow, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
measured = Row.measure(self, mount, constraints)
|
||||
return MeasureResult(constraints.maxWidth, measured.height)
|
||||
}
|
||||
}
|
||||
// Quiet action rows retain native hit targets and keyboard focus without card chrome.
|
||||
class StartButton: Button {
|
||||
function measure(self: StartButton, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
return MeasureResult(360, 40)
|
||||
}
|
||||
function paint(self: StartButton, mount: Mount, geometry: Bounds): DisplayList {
|
||||
return DisplayList(ObjectList())
|
||||
}
|
||||
}
|
||||
class StartLine: Row {
|
||||
function measure(self: StartLine, mount: Mount, constraints: Constraints): MeasureResult {
|
||||
measured = Row.measure(self, mount, constraints)
|
||||
return MeasureResult(360, measured.height)
|
||||
}
|
||||
}
|
||||
class StartActions {
|
||||
home: Page
|
||||
function blank(self: StartActions, event: Event): Unit {
|
||||
page = Page()
|
||||
page.title = "未命名页面"
|
||||
back = Button("返回开始页")
|
||||
back.onClick(self.home.activate)
|
||||
page.render(Column(32, 16, TextBlock("未命名页面", 2), TextBlock("一个新的 Page 对象,已加入当前窗口。"), TextBlock("用 Endor 的 page.render(...) 组织内容。"), back))
|
||||
}
|
||||
function counter(self: StartActions, event: Event): Unit {
|
||||
count = ui.state(0)
|
||||
add = Button("增加计数")
|
||||
add.onClick(count.increment)
|
||||
page = Page()
|
||||
page.title = "共享对象"
|
||||
page.render(Column(32, 16, TextBlock("一个对象,两个视图", 2), TextBlock("点击一次,两处展示同时更新。切换标签后,状态仍然保留。"), Row(0, 32, ui.textOf(count, "value", 3), ui.textOf(count, "value", 3)), add))
|
||||
}
|
||||
function compose(self: StartActions, event: Event): Unit {
|
||||
label = TextBlock("对象可以被多处引用")
|
||||
page = Page()
|
||||
page.title = "组合页面"
|
||||
page.render(Column(32, 20, TextBlock("把对象组合成界面", 2), TextBlock("Column 组织纵向内容,Row 组织横向内容。"), Row(0, 16, RectBlock(100, 64, 12, "#DCE8FF"), RectBlock(100, 64, 12, "#E3ECDC"), RectBlock(100, 64, 12, "#F3E4DB")), label, Row(0, 24, label, label)))
|
||||
}
|
||||
}
|
||||
function newTab(): Page {
|
||||
page = StartPage()
|
||||
page.title = "新标签页"
|
||||
actions = StartActions(page)
|
||||
blank = StartButton("+ 创建页面")
|
||||
counter = StartButton("↗ 共享对象示例")
|
||||
compose = StartButton("◇ 界面组合示例")
|
||||
blank.on("click", actions.blank)
|
||||
counter.on("click", actions.counter)
|
||||
compose.on("click", actions.compose)
|
||||
heading = StartLine(0, 0, TextBlock("Endor", 2, "#30343B"))
|
||||
heading.mainAlign = "center"
|
||||
subtitle = StartLine(0, 0, TextBlock("创建页面,或从一个示例开始。", 1, "#80858D"))
|
||||
subtitle.mainAlign = "center"
|
||||
newHint = StartLine(0, 0, TextBlock("新建标签页", 1, "#8A8F97"), TextBlock("⌘ T / Ctrl + T", 1, "#747B85"))
|
||||
newHint.mainAlign = "space-between"
|
||||
closeHint = StartLine(0, 0, TextBlock("关闭标签页", 1, "#8A8F97"), TextBlock("⌘ W / Ctrl + W", 1, "#747B85"))
|
||||
closeHint.mainAlign = "space-between"
|
||||
content = Column(0, 8,
|
||||
heading, subtitle, Spacer(20),
|
||||
blank, counter, compose, Spacer(20),
|
||||
newHint, closeHint)
|
||||
row = StartRow(24, 0, content)
|
||||
row.mainAlign = "center"
|
||||
page.mainAlign = "center"
|
||||
page.render(row)
|
||||
return page
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Owned immutable visual derivation; no managed VM handles.
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UiNode {
|
||||
pub flex: f32,
|
||||
pub flex_policy: crate::layout::FlexPolicy,
|
||||
pub main_align: crate::layout::MainAlign,
|
||||
pub block_id: String,
|
||||
pub protocol_key: String,
|
||||
pub slots: Vec<u64>,
|
||||
pub interactive: bool,
|
||||
pub kind: UiKind,
|
||||
}
|
||||
|
||||
impl UiNode {
|
||||
pub fn children(&self) -> &[Arc<UiNode>] {
|
||||
match &self.kind {
|
||||
UiKind::Column { children, .. }
|
||||
| UiKind::Row { children, .. }
|
||||
| UiKind::Button { children, .. }
|
||||
| UiKind::Scroll { children, .. } => children,
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_flex(&self) -> bool {
|
||||
self.flex > 0.0 || self.flex_policy != crate::layout::FlexPolicy::default()
|
||||
}
|
||||
|
||||
pub fn shallow_eq(&self, other: &Self) -> bool {
|
||||
if self.flex_policy != other.flex_policy
|
||||
|| self.flex != other.flex
|
||||
|| self.main_align != other.main_align
|
||||
|| self.block_id != other.block_id
|
||||
|| self.protocol_key != other.protocol_key
|
||||
|| self.slots != other.slots
|
||||
|| self.interactive != other.interactive
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let same_children = || {
|
||||
self.children().len() == other.children().len()
|
||||
&& self
|
||||
.children()
|
||||
.iter()
|
||||
.zip(other.children())
|
||||
.all(|(a, b)| Arc::ptr_eq(a, b))
|
||||
};
|
||||
match (&self.kind, &other.kind) {
|
||||
(
|
||||
UiKind::Text {
|
||||
value: a,
|
||||
size: sa,
|
||||
color: ca,
|
||||
},
|
||||
UiKind::Text {
|
||||
value: b,
|
||||
size: sb,
|
||||
color: cb,
|
||||
},
|
||||
) => a == b && sa == sb && ca == cb,
|
||||
(
|
||||
UiKind::Rect {
|
||||
width: a,
|
||||
height: b,
|
||||
radius: c,
|
||||
color: d,
|
||||
},
|
||||
UiKind::Rect {
|
||||
width: e,
|
||||
height: f,
|
||||
radius: g,
|
||||
color: h,
|
||||
},
|
||||
) => (a, b, c, d) == (e, f, g, h),
|
||||
(UiKind::Spacer(a), UiKind::Spacer(b)) => a == b,
|
||||
(
|
||||
UiKind::Scroll {
|
||||
axis: aa,
|
||||
width: a,
|
||||
height: b,
|
||||
padding: pa,
|
||||
gap: ga,
|
||||
children: _,
|
||||
},
|
||||
UiKind::Scroll {
|
||||
axis: ab,
|
||||
width: c,
|
||||
height: d,
|
||||
padding: pb,
|
||||
gap: gb,
|
||||
children: _,
|
||||
},
|
||||
) => aa == ab && a == c && b == d && pa == pb && ga == gb && same_children(),
|
||||
(
|
||||
UiKind::Column {
|
||||
padding: a, gap: b, ..
|
||||
},
|
||||
UiKind::Column {
|
||||
padding: c, gap: d, ..
|
||||
},
|
||||
)
|
||||
| (
|
||||
UiKind::Row {
|
||||
padding: a, gap: b, ..
|
||||
},
|
||||
UiKind::Row {
|
||||
padding: c, gap: d, ..
|
||||
},
|
||||
)
|
||||
| (
|
||||
UiKind::Button {
|
||||
padding: a, gap: b, ..
|
||||
},
|
||||
UiKind::Button {
|
||||
padding: c, gap: d, ..
|
||||
},
|
||||
) => a == c && b == d && same_children(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum UiKind {
|
||||
Button {
|
||||
padding: f32,
|
||||
gap: f32,
|
||||
children: Vec<Arc<UiNode>>,
|
||||
},
|
||||
Text {
|
||||
value: String,
|
||||
size: u32,
|
||||
color: String,
|
||||
},
|
||||
Rect {
|
||||
width: f32,
|
||||
height: f32,
|
||||
radius: f32,
|
||||
color: String,
|
||||
},
|
||||
Column {
|
||||
padding: f32,
|
||||
gap: f32,
|
||||
children: Vec<Arc<UiNode>>,
|
||||
},
|
||||
Row {
|
||||
padding: f32,
|
||||
gap: f32,
|
||||
children: Vec<Arc<UiNode>>,
|
||||
},
|
||||
Spacer(f32),
|
||||
Scroll {
|
||||
axis: crate::scroll::Axis,
|
||||
width: f32,
|
||||
height: f32,
|
||||
padding: f32,
|
||||
gap: f32,
|
||||
children: Vec<Arc<UiNode>>,
|
||||
},
|
||||
}
|
||||
Reference in New Issue
Block a user