Skip to main content

slint_interpreter/
public_api.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4//! Name-based bridge between the public API (`get_property`, `invoke`,
5//! `set_callback`, …) and the LLR's index-based `MemberReference`s.
6//!
7//! Each `PublicComponent::public_properties` entry carries a
8//! `MemberReference`; dispatch forwards to the evaluator helpers in
9//! [`crate::eval`].
10
11use crate::api::SetPropertyError;
12use crate::eval::{EvalContext, invoke_callback, invoke_function, load_property, store_property};
13use crate::instance::SubComponentInstance;
14use crate::prelude::*;
15use i_slint_compiler::langtype::Type;
16use i_slint_compiler::llr::{MemberReference, PublicComponent, PublicProperty};
17use i_slint_core::model::Model;
18
19/// Look up a public property by name on the given public component.
20/// Normalizes `name` through `normalize_identifier` so
21/// snake_case and kebab-case both work.
22pub fn find_public_property<'a>(
23    public: &'a PublicComponent,
24    name: &str,
25) -> Option<&'a PublicProperty> {
26    let normalized = i_slint_compiler::names::normalize_identifier(name);
27    public.public_properties.get(normalized.as_str())
28}
29
30/// Read the value of a public property on `instance`.
31pub fn get(instance: &VRc<ItemTreeVTable, Instance>, name: &str) -> Option<Value> {
32    let (public, sub) = resolve(instance)?;
33    let prop = find_public_property(public, name)?;
34    if !prop.ty.is_property_type() {
35        return None;
36    }
37    let ctx = EvalContext::new(sub);
38    Some(load_property(&ctx, &prop.prop))
39}
40
41/// Write a public property on `instance`.
42pub fn set(
43    instance: &VRc<ItemTreeVTable, Instance>,
44    name: &str,
45    mut value: Value,
46) -> Result<(), SetPropertyError> {
47    let (public, sub) = resolve(instance).ok_or(SetPropertyError::NoSuchProperty)?;
48    let prop = find_public_property(public, name).ok_or(SetPropertyError::NoSuchProperty)?;
49    if !prop.ty.is_property_type() {
50        return Err(SetPropertyError::NoSuchProperty);
51    }
52    if prop.read_only() {
53        return Err(SetPropertyError::AccessDenied);
54    }
55    if !check_and_coerce(&mut value, &prop.ty) {
56        return Err(SetPropertyError::WrongType);
57    }
58    let ctx = EvalContext::new(sub);
59    store_property(&ctx, &prop.prop, value);
60    Ok(())
61}
62
63/// Return true if `value` matches `ty` — and coerce it in place when useful
64/// (struct values get missing fields filled with the type's defaults).
65pub(crate) fn check_and_coerce(value: &mut Value, ty: &Type) -> bool {
66    match ty {
67        Type::Void => true,
68        Type::Invalid
69        | Type::InferredProperty
70        | Type::InferredCallback
71        | Type::Callback(_)
72        | Type::Function(_)
73        | Type::ElementReference
74        | Type::Closure => false,
75        Type::Float32 | Type::Int32 => matches!(value, Value::Number(_)),
76        Type::String => matches!(value, Value::String(_)),
77        Type::Color | Type::Brush => matches!(value, Value::Brush(_)),
78        Type::UnitProduct(_)
79        | Type::Duration
80        | Type::PhysicalLength
81        | Type::LogicalLength
82        | Type::Rem
83        | Type::Angle
84        | Type::Percent => matches!(value, Value::Number(_)),
85        Type::Image => matches!(value, Value::Image(_)),
86        Type::Bool => matches!(value, Value::Bool(_)),
87        Type::Model => matches!(value, Value::Model(_) | Value::Bool(_) | Value::Number(_)),
88        Type::PathData => matches!(value, Value::PathData(_)),
89        Type::DataTransfer => matches!(value, Value::DataTransfer(_)),
90        Type::Easing => matches!(value, Value::EasingCurve(_)),
91        Type::MouseCursor => matches!(value, Value::MouseCursorInner(_)),
92        Type::Array(inner) => match value {
93            Value::Model(m) => {
94                let mut ok = true;
95                for i in 0..m.row_count() {
96                    if let Some(mut v) = m.row_data(i)
97                        && !check_and_coerce(&mut v, inner)
98                    {
99                        ok = false;
100                        break;
101                    }
102                }
103                ok
104            }
105            _ => false,
106        },
107        Type::Struct(s) => {
108            let Value::Struct(str_value) = value else { return false };
109            // Every provided key must be declared on the struct and have the
110            // right type.
111            let keys: Vec<String> = str_value.iter().map(|(k, _)| k.to_string()).collect();
112            for k in keys {
113                let Some(field_ty) = s.fields.get(k.as_str()) else {
114                    return false;
115                };
116                let Some(v) = str_value.get_field(&k).cloned() else { continue };
117                let mut v = v;
118                if !check_and_coerce(&mut v, field_ty) {
119                    return false;
120                }
121                str_value.set_field(k, v);
122            }
123            crate::eval::fill_missing_struct_fields(str_value, s);
124            true
125        }
126        Type::Enumeration(en) => {
127            matches!(value, Value::EnumerationValue(name, _) if name == en.name.as_str())
128        }
129        Type::Keys => matches!(value, Value::Keys(_)),
130        Type::ArrayOfCoord => matches!(value, Value::ArrayOfCoord(_)),
131        Type::ArrayOfU16 => matches!(value, Value::ArrayOfU16(_)),
132        Type::ComponentFactory => matches!(value, Value::ComponentFactory(_)),
133        Type::StyledText => matches!(value, Value::StyledText(_)),
134    }
135}
136
137/// Invoke a public callback or function by name.
138pub fn invoke(
139    instance: &VRc<ItemTreeVTable, Instance>,
140    name: &str,
141    args: &[Value],
142) -> Option<Value> {
143    use i_slint_compiler::langtype::Type;
144    let (public, sub) = resolve(instance)?;
145    let prop = find_public_property(public, name)?;
146    // Only callbacks and functions are callable; propagate a miss for
147    // anything else so the public API surfaces a `NoSuchCallable` error.
148    if !matches!(&prop.ty, Type::Callback(_) | Type::Function(_)) {
149        return None;
150    }
151    let ctx = EvalContext::new(sub);
152    Some(if matches!(&prop.ty, Type::Function(_)) || prop.prop.is_function() {
153        invoke_function(&ctx, &prop.prop, args.to_vec())
154    } else {
155        invoke_callback(&ctx, &prop.prop, args)
156    })
157}
158
159/// Install a host-side handler on a public callback.
160///
161/// Host handlers take the callback args as a flat `&[Value]` and return a
162/// `Value`; they're adapted to the sub-component's
163/// `Callback<[Value], Value>` shape before being installed.
164pub fn set_callback(
165    instance: &VRc<ItemTreeVTable, Instance>,
166    name: &str,
167    handler: Box<dyn Fn(&[Value]) -> Value>,
168) -> Result<(), ()> {
169    let (public, sub) = resolve(instance).ok_or(())?;
170    let prop = find_public_property(public, name).ok_or(())?;
171    match &prop.prop {
172        MemberReference::Relative { parent_level, local_reference } => {
173            let target = walk_to(sub, *parent_level, local_reference).ok_or(())?;
174            match &local_reference.reference {
175                i_slint_compiler::llr::LocalMemberIndex::Callback(idx) => {
176                    let cb = Pin::as_ref(&target.callbacks[*idx]);
177                    cb.set_handler(handler);
178                    if let Some(tracker) = target.callback_trackers[*idx].as_ref() {
179                        Pin::as_ref(tracker).mark_dirty();
180                    }
181                    Ok(())
182                }
183                i_slint_compiler::llr::LocalMemberIndex::Native {
184                    item_index, prop_name, ..
185                } => {
186                    Pin::as_ref(&target.items[*item_index]).set_callback_handler(prop_name, handler)
187                }
188                _ => Err(()),
189            }
190        }
191        MemberReference::Global { global_index, member } => {
192            // An alias like `callback foo <=> Glo.bar` surfaces as a
193            // public property whose `prop` is a global reference. Route
194            // directly to the matching `GlobalInstance::callbacks` slot.
195            let global_inst = instance.globals.get(*global_index).ok_or(())?;
196            let i_slint_compiler::llr::LocalMemberIndex::Callback(idx) = member else {
197                return Err(());
198            };
199            let cb = Pin::as_ref(&global_inst.callbacks[*idx]);
200            cb.set_handler(handler);
201            if let Some(tracker) = global_inst.callback_trackers[*idx].as_ref() {
202                Pin::as_ref(tracker).mark_dirty();
203            }
204            Ok(())
205        }
206    }
207}
208
209fn resolve(
210    instance: &VRc<ItemTreeVTable, Instance>,
211) -> Option<(&PublicComponent, Pin<Rc<SubComponentInstance>>)> {
212    let cu = &instance.root_sub_component.compilation_unit;
213    let public_index = instance.public_component_index?;
214    let public = cu.public_components.get(public_index)?;
215    Some((public, instance.root_sub_component.clone()))
216}
217
218/// Name-based lookup of a public property on an exported global singleton.
219/// Returns the looked-up property plus the runtime `GlobalInstance`.
220fn resolve_global<'a>(
221    instance: &'a VRc<ItemTreeVTable, Instance>,
222    global_name: &str,
223    prop_name: &str,
224) -> Option<(&'a PublicProperty, Rc<crate::globals::GlobalInstance>)> {
225    let cu = &instance.root_sub_component.compilation_unit;
226    let (_global, global_instance) = instance.globals.find_by_name(cu, global_name)?;
227    let global_instance = global_instance.clone();
228    let needle = i_slint_compiler::names::normalize_identifier(prop_name);
229    let global = &cu.globals[global_instance.global_idx];
230    let prop = global.public_properties.get(needle.as_str())?;
231    Some((prop, global_instance))
232}
233
234/// Resolve a public global property to its underlying `(GlobalInstance,
235/// LocalMemberIndex)`. A `data <=> G1.data` alias surfaces as
236/// `MemberReference::Global` pointing at a *different* global from the one
237/// whose `public_properties` map carries the entry, so the member index
238/// must be resolved against the target global, not the source.
239fn resolve_global_property(
240    instance: &VRc<ItemTreeVTable, Instance>,
241    source_inst: Rc<crate::globals::GlobalInstance>,
242    prop: &PublicProperty,
243) -> Option<(Rc<crate::globals::GlobalInstance>, i_slint_compiler::llr::LocalMemberIndex)> {
244    match &prop.prop {
245        MemberReference::Global { global_index, member } => {
246            let target = instance.globals.get(*global_index)?.clone();
247            Some((target, member.clone()))
248        }
249        MemberReference::Relative { local_reference, .. } => {
250            Some((source_inst, local_reference.reference.clone()))
251        }
252    }
253}
254
255/// Read a property on a public global singleton.
256pub fn get_global(
257    instance: &VRc<ItemTreeVTable, Instance>,
258    global_name: &str,
259    prop_name: &str,
260) -> Option<Value> {
261    let (prop, source_inst) = resolve_global(instance, global_name, prop_name)?;
262    let (target_inst, member) = resolve_global_property(instance, source_inst, prop)?;
263    match member {
264        i_slint_compiler::llr::LocalMemberIndex::Property(idx) => {
265            Some(Pin::as_ref(&target_inst.properties[idx]).get())
266        }
267        _ => None,
268    }
269}
270
271/// Write a property on a public global singleton.
272pub fn set_global(
273    instance: &VRc<ItemTreeVTable, Instance>,
274    global_name: &str,
275    prop_name: &str,
276    mut value: Value,
277) -> Result<(), SetPropertyError> {
278    let (prop, source_inst) =
279        resolve_global(instance, global_name, prop_name).ok_or(SetPropertyError::NoSuchProperty)?;
280    if prop.read_only() {
281        return Err(SetPropertyError::AccessDenied);
282    }
283    if !check_and_coerce(&mut value, &prop.ty) {
284        return Err(SetPropertyError::WrongType);
285    }
286    let (target_inst, member) = resolve_global_property(instance, source_inst, prop)
287        .ok_or(SetPropertyError::NoSuchProperty)?;
288    match member {
289        i_slint_compiler::llr::LocalMemberIndex::Property(_) => {
290            crate::eval::store_global(&target_inst, &member, value);
291            Ok(())
292        }
293        _ => Err(SetPropertyError::NoSuchProperty),
294    }
295}
296
297/// Install a handler on a public callback declared on an exported global
298/// singleton.
299pub fn set_global_callback(
300    instance: &VRc<ItemTreeVTable, Instance>,
301    global_name: &str,
302    callback_name: &str,
303    handler: Box<dyn Fn(&[Value]) -> Value>,
304) -> Result<(), ()> {
305    let (prop, source_inst) = resolve_global(instance, global_name, callback_name).ok_or(())?;
306    let (target_inst, member) = resolve_global_property(instance, source_inst, prop).ok_or(())?;
307    match member {
308        i_slint_compiler::llr::LocalMemberIndex::Callback(idx) => {
309            if let Some(native) = &target_inst.native {
310                let g = &target_inst.compilation_unit.globals[target_inst.global_idx];
311                return native.as_ref().set_callback_handler(&g.callbacks[idx].name, handler);
312            }
313            let cb = Pin::as_ref(&target_inst.callbacks[idx]);
314            cb.set_handler(handler);
315            if let Some(tracker) = target_inst.callback_trackers[idx].as_ref() {
316                Pin::as_ref(tracker).mark_dirty();
317            }
318            Ok(())
319        }
320        _ => Err(()),
321    }
322}
323
324/// Invoke a public callback or function on an exported global singleton.
325pub fn invoke_global(
326    instance: &VRc<ItemTreeVTable, Instance>,
327    global_name: &str,
328    name: &str,
329    args: &[Value],
330) -> Option<Value> {
331    use i_slint_compiler::llr::LocalMemberIndex;
332    let (prop, source_inst) = resolve_global(instance, global_name, name)?;
333    let (target_inst, member) = resolve_global_property(instance, source_inst, prop)?;
334    match member {
335        LocalMemberIndex::Callback(idx) => {
336            let cu = &target_inst.compilation_unit;
337            let cb_decl = &cu.globals[target_inst.global_idx].callbacks[idx];
338            if let Some(native) = &target_inst.native {
339                let res =
340                    native.as_ref().invoke_callback(&cb_decl.name, args).unwrap_or(Value::Void);
341                return Some(crate::eval::ensure_typed_default(res, &cb_decl.ret_ty));
342            }
343            let cb = Pin::as_ref(&target_inst.callbacks[idx]);
344            Some(crate::eval::ensure_typed_default(cb.call(args), &cb_decl.ret_ty))
345        }
346        LocalMemberIndex::Function(fn_idx) => {
347            let cu = &instance.root_sub_component.compilation_unit;
348            let global = &cu.globals[target_inst.global_idx];
349            let function = &global.functions[fn_idx];
350            let expr = function.code.borrow().clone();
351            let mut ctx =
352                crate::eval::EvalContext::for_global(Rc::downgrade(&instance.globals), cu.clone());
353            ctx.function_arg_types = function.args.clone();
354            ctx.function_arguments = args.to_vec();
355            Some(crate::eval::eval_expression(&mut ctx, &expr))
356        }
357        _ => None,
358    }
359}
360
361fn walk_to(
362    start: Pin<Rc<SubComponentInstance>>,
363    parent_level: usize,
364    local_reference: &i_slint_compiler::llr::LocalMemberReference,
365) -> Option<Pin<Rc<SubComponentInstance>>> {
366    let base = crate::eval::try_walk_parent(&start, parent_level)?;
367    Some(crate::eval::walk_sub_path(base, &local_reference.sub_component_path))
368}