#[cfg(feature = "canvas")]
use super::resolve::{Visibility, intersect, visible_clip};
use super::{
inspect::InspectCtx,
read_tree::SnapshotCtx,
semantics::{attr, semantic_actions, token, truncate_text},
};
use crate::{app::Tree, core::NodeId, mcp::shared::RefRecord, node::node::Node};
const ITEM_TAG: &str = "CanvasItem";
pub(super) struct ItemHit {
pub(super) node_id: NodeId,
pub(super) record: ItemRecord,
}
pub(super) struct ItemRecord {
id: String,
role: String,
label: Option<String>,
value: Option<String>,
bounds: Option<[f32; 4]>,
invoke: bool,
hover: bool,
}
pub(super) fn canvas_attrs(node: &Node) -> Option<(String, String)> {
#[cfg(feature = "canvas")]
{
let count = node.canvas_handle()?.items().len();
let reachable = super::semantics::can_invoke(node) || super::semantics::can_hover(node);
(count > 0 || reachable).then(|| ("items".to_owned(), count.to_string()))
}
#[cfg(not(feature = "canvas"))]
{
let _ = node;
None
}
}
fn item_records(tree: &Tree, node: &Node) -> Vec<ItemRecord> {
#[cfg(feature = "canvas")]
{
let Some(canvas) = node.canvas_handle() else {
return Vec::new();
};
let clip = visible_clip(tree, node.node_id());
canvas
.items_in_window()
.into_iter()
.map(|(item, bounds)| to_item_record(node, item, visible(bounds, clip)))
.collect()
}
#[cfg(not(feature = "canvas"))]
{
let _ = (tree, node);
Vec::new()
}
}
#[cfg(feature = "canvas")]
fn to_item_record(node: &Node, item: crate::canvas::CanvasItem, bounds: Option<[f32; 4]>) -> ItemRecord {
ItemRecord {
id: item.id,
role: item.role,
label: item.label,
value: item.value,
bounds,
invoke: super::semantics::can_invoke(node),
hover: super::semantics::can_hover(node),
}
}
#[cfg(feature = "canvas")]
fn visible(bounds: Option<[f32; 4]>, clip: Visibility) -> Option<[f32; 4]> {
match clip {
Visibility::Region(clip) => intersect(bounds?, clip),
Visibility::Hidden => None,
Visibility::Unknown => bounds,
}
}
fn live_item(tree: &Tree, node: &Node, item_id: &str, on_screen: bool) -> Option<ItemRecord> {
#[cfg(feature = "canvas")]
{
let (item, bounds) = node.canvas_handle()?.item_in_window(item_id)?;
let bounds = if on_screen {
visible(bounds, visible_clip(tree, node.node_id()))
} else {
bounds
};
Some(to_item_record(node, item, bounds))
}
#[cfg(not(feature = "canvas"))]
{
let _ = (tree, node, item_id, on_screen);
None
}
}
pub(super) fn snapshot_item_lines(ctx: &mut SnapshotCtx<'_>, node: &Node, depth: usize) -> Vec<String> {
if ctx.max_depth != 0 && depth >= ctx.max_depth {
return Vec::new();
}
let records = item_records(ctx.tree, node);
let hidden = records.len().saturating_sub(ctx.max_items);
let mut lines = Vec::with_capacity(records.len().min(ctx.max_items) + 1);
for item in records.into_iter().take(ctx.max_items) {
let record = to_ref_record((ctx.mint)(), &ctx.window, node.node_id(), item, ctx.scale);
let mut line = format!(
"{}- {} item:{} [{}]",
" ".repeat(depth + 1),
token(&record.role),
token(record.canvas_item.as_deref().unwrap_or_default()),
record.id
);
if let Some(label) = &record.name {
line.push_str(&format!(" {:?}", truncate_text(label, 80)));
}
if let Some([x, y, width, height]) = record.bounds {
line.push_str(&format!(" @{x:.0},{y:.0} {width:.0}x{height:.0}"));
} else {
line.push_str(" (not visible)");
}
for (name, value) in &record.attrs {
line.push_str(&attr(name, value));
}
lines.push(line);
ctx.records.push(record);
}
if hidden > 0 {
lines.push(format!(
"{}- … +{hidden} more items (raise max_items, or lurq_inspect with role or query)",
" ".repeat(depth + 1)
));
}
lines
}
pub(super) fn inspect_items(ctx: &mut InspectCtx<'_>, node: &Node, path: &[String]) -> Vec<serde_json::Value> {
let searching = ctx.searching();
let mut values = Vec::new();
for item in item_records(ctx.tree, node) {
if searching {
if !ctx.matches(&item.role, item.label.as_deref(), Some(&item.id), &[]) {
continue;
}
if ctx.matches_full() {
break;
}
} else if ctx.visited >= ctx.max_nodes {
ctx.truncated = true;
break;
} else {
ctx.visited += 1;
}
let has_bounds = item.bounds.is_some();
let actions = semantic_actions(item.invoke, item.hover);
let mut state = serde_json::Map::new();
if let Some(value) = &item.value {
state.insert("value".into(), serde_json::json!(value));
}
if !has_bounds {
state.insert("hidden".into(), serde_json::json!(true));
}
let record = to_ref_record((ctx.mint)(), ctx.window, node.node_id(), item, ctx.scale);
let value = serde_json::json!({
"ref": record.id,
"role": record.role,
"name": record.name,
"id": record.canvas_item,
"canvas_item": true,
"state": state,
"actions": actions,
"bounds": record.bounds,
});
ctx.record_match(
&value,
&record.role,
record.name.as_deref(),
record.canvas_item.as_deref(),
&[],
path,
);
ctx.records.push(record);
if !searching {
values.push(value);
}
}
values
}
fn to_ref_record(ref_id: String, window: &str, node_id: NodeId, item: ItemRecord, scale: f32) -> RefRecord {
RefRecord {
id: ref_id,
window: window.to_owned(),
node_id,
tag: ITEM_TAG.to_owned(),
text: None,
role: item.role,
name: item.label,
element_id: Some(item.id.clone()),
classes: Vec::new(),
attrs: item
.value
.map(|value| vec![("value".to_owned(), value)])
.unwrap_or_default(),
bounds: item.bounds.map(|bounds| bounds.map(|value| (value * scale).round())),
interactive: item.invoke || item.hover,
canvas_item: Some(item.id),
}
}
pub(super) fn find_item_by_id(tree: &Tree, id: &str) -> Option<ItemHit> {
fn walk(tree: &Tree, node: &Node, id: &str) -> Option<ItemHit> {
if let Some(record) = live_item(tree, node, id, true) {
return Some(ItemHit {
node_id: node.node_id(),
record,
});
}
node.children().iter().find_map(|child| walk(tree, child, id))
}
walk(tree, tree.root()?.node, id)
}
pub(super) fn lookup_record(ref_id: String, window: &str, hit: ItemHit, scale: f32) -> RefRecord {
to_ref_record(ref_id, window, hit.node_id, hit.record, scale)
}
pub(super) fn item_bounds(
tree: &Tree,
canvas: &Node,
item_id: &str,
on_screen: bool,
ref_id: &str,
) -> Result<[f32; 4], String> {
let item = live_item(tree, canvas, item_id, on_screen)
.ok_or_else(|| format!("ref {ref_id:?} no longer resolves to a live canvas item; read the tree again"))?;
item.bounds.ok_or_else(|| {
if on_screen {
format!("canvas item ref {ref_id:?} is not visible (outside its canvas or scrolled away); use scroll_to")
} else {
format!("canvas item ref {ref_id:?} lies outside its canvas")
}
})
}
pub(super) fn item_identity(tree: &Tree, node: &Node, item_id: &str) -> Option<(String, Option<String>)> {
live_item(tree, node, item_id, false).map(|record| (record.role, record.label))
}