//! Native Block operations executed on the owning VM worker. use super::*; impl NativeCallable for Function { fn signature(&self) -> Option { self.signature.clone() } fn arity(&self) -> Option { Some(self.operation.arity()) } fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { 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::(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::(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::(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::(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::>() .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::>()?, 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::() && 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", "", 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::(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::(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::(*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)) } }