Skip to main content

slint_interpreter/
debug_hook.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//! Runtime side of the `debug_hooks` compiler feature: evaluating an
5//! `Expression::DebugHook` calls the callback installed with
6//! `ComponentInstance::set_debug_hook_callback`, which may override the value.
7
8use crate::eval::EvalContext;
9use crate::prelude::*;
10
11pub type DebugHookCallback = Box<dyn Fn(&str) -> Option<Value>>;
12
13#[cfg(feature = "internal")]
14pub(crate) fn set_debug_hook_callback(
15    instance: &VRc<ItemTreeVTable, Instance>,
16    func: Option<DebugHookCallback>,
17) {
18    *instance.globals.debug_hook_callback.borrow_mut() = func;
19}
20
21/// `Some` when the installed callback overrides the value, `None` to evaluate the binding.
22pub(crate) fn trigger_debug_hook(ctx: &EvalContext, id: &SmolStr) -> Option<Value> {
23    let globals = ctx.globals.upgrade()?;
24    let callback = globals.debug_hook_callback.borrow();
25    callback.as_ref().and_then(|callback| callback(id))
26}
27
28#[cfg(all(test, feature = "internal", feature = "internal-highlight"))]
29pub(crate) mod tests {
30    use super::*;
31    use crate::{Compiler, ComponentInstance};
32    use i_slint_compiler::source_path::SourcePath;
33    use i_slint_core::{Property, graphics::ApproxEq};
34    use std::{cell::RefCell, collections::HashMap, pin::Pin, rc::Rc};
35
36    pub fn compile_with_debug_hooks(code: &str) -> ComponentInstance {
37        i_slint_backend_testing::init_no_event_loop();
38
39        let mut compiler = Compiler::default();
40        compiler.compiler_configuration(i_slint_core::InternalToken).debug_hooks =
41            Some(std::hash::RandomState::new());
42        let compile_result = spin_on::spin_on(compiler.build_from_source_path(
43            Some(code.to_string()),
44            test_path(),
45            i_slint_core::InternalToken,
46        ));
47        assert!(!compile_result.has_errors(), "{:?}", compile_result.diagnostics);
48        compile_result.components().next().unwrap().create().unwrap()
49    }
50
51    fn install_debug_hook_store(instance: &ComponentInstance) -> Store {
52        let store: Store = Default::default();
53        {
54            let store = Rc::clone(&store);
55            instance.set_debug_hook_callback(Some(Box::new(move |id: &str| -> Option<Value> {
56                let mut m = (*store).borrow_mut();
57                let p = m.entry(SmolStr::from(id)).or_insert_with(|| Box::pin(Property::new(None)));
58                p.as_ref().get()
59            })));
60        }
61        store
62    }
63
64    fn set_override(store: &Store, element_hash: u64, name: &str, value: Option<Value>) {
65        let id = i_slint_compiler::passes::property_id(element_hash, &SmolStr::from(name));
66        let mut store = (*store).borrow_mut();
67        let override_property = store.entry(id).or_insert_with(|| Box::pin(Property::new(None)));
68        (&**override_property).set(value);
69    }
70
71    // Make sure to not actually write this file, it's just a synthetic path
72    pub fn test_path() -> SourcePath {
73        SourcePath::new("/tmp/test.slint")
74    }
75
76    fn find_element_hash(instance: &ComponentInstance, code: &str, search_term: &str) -> u64 {
77        let offset = code.find(search_term).unwrap() as u32;
78        let (element, debug_index) = instance
79            .element_node_at_source_code_position(&test_path(), offset)
80            .first()
81            .cloned()
82            .expect("element resolved");
83        let element_hash = element.borrow().debug[debug_index].element_hash;
84        assert_ne!(element_hash, 0, "debug_hooks should populate element_hash");
85        element_hash
86    }
87
88    fn geometry_at(
89        instance: &ComponentInstance,
90        code: &str,
91        search_term: &str,
92    ) -> i_slint_core::lengths::LogicalRect {
93        let offset = code.find(search_term).unwrap() as u32;
94        instance.component_positions(&test_path(), offset).first().expect("geometry").rect
95    }
96
97    // Editor-style override store + callback (must be installed before the first evaluation so
98    // the hooked bindings register a dependency on the override properties while still `None`).
99    type Store = Rc<RefCell<HashMap<SmolStr, Pin<Box<Property<Option<Value>>>>>>>;
100
101    // Validates the "live drag" mechanism the visual editor relies on: with `debug_hooks`
102    // enabled, a `set_debug_hook_callback` that reads a per-id `Property<Option<Value>>` lets the
103    // editor reactively override a property's value (and revert it) without touching the source.
104    // Setting the override property re-evaluates the hooked binding via Slint's dependency tracker.
105    #[test]
106    fn debug_hook_live_override() {
107        let code = r#"
108export component Win inherits Window {
109    width: 300px;
110    height: 300px;
111    rect := Rectangle {
112        x: 10px;
113        y: 20px;
114        width: 30px;
115        height: 40px;
116    }
117}"#;
118
119        let instance = compile_with_debug_hooks(code);
120
121        let element_hash = find_element_hash(&instance, code, "Rectangle");
122
123        let store = install_debug_hook_store(&instance);
124
125        let base = geometry_at(&instance, code, "Rectangle");
126
127        set_override(&store, element_hash, "x", Some(Value::Number(100.0)));
128        set_override(&store, element_hash, "width", Some(Value::Number(70.0)));
129        let after = geometry_at(&instance, code, "Rectangle");
130        assert!(
131            after.origin.x.approx_eq(&(base.origin.x + 90.0)),
132            "x override should shift the element by 90px (base {}, after {})",
133            base.origin.x,
134            after.origin.x
135        );
136        assert!(
137            after.size.width.approx_eq(&(base.size.width + 40.0)),
138            "width override should grow the element by 40px (base {}, after {})",
139            base.size.width,
140            after.size.width
141        );
142
143        set_override(&store, element_hash, "x", None);
144        set_override(&store, element_hash, "width", None);
145        let reverted = geometry_at(&instance, code, "Rectangle");
146        assert!(reverted.origin.x.approx_eq(&base.origin.x), "x should revert");
147        assert!(reverted.size.width.approx_eq(&base.size.width), "width should revert");
148    }
149
150    #[test]
151    fn debug_hook_component_instance_override() {
152        let code = r#"
153component Sub inherits Rectangle {
154    in property <color> tint: blue;
155    background: tint;
156}
157export component Win inherits Window {
158    width: 300px;
159    height: 300px;
160    sub := Sub { x: 10px; y: 20px; width: 50px; height: 50px; }
161    for _idx in 2: Sub { width: 10px; height: 10px; }
162    out property <brush> sub-background: sub.background;
163}"#;
164        let instance = compile_with_debug_hooks(code);
165
166        let store = install_debug_hook_store(&instance);
167
168        let blue = Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_rgb_u8(
169            0, 0, 255,
170        )));
171        assert_eq!(instance.get_property("sub-background").unwrap(), blue);
172
173        let element_hash = find_element_hash(&instance, code, "Sub {");
174
175        let red = Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_rgb_u8(
176            255, 0, 0,
177        )));
178        set_override(&store, element_hash, "background", Some(red.clone()));
179        assert_eq!(instance.get_property("sub-background").unwrap(), red);
180        set_override(&store, element_hash, "background", None);
181        assert_eq!(instance.get_property("sub-background").unwrap(), blue);
182
183        let base = geometry_at(&instance, code, "Sub {");
184        set_override(&store, element_hash, "x", Some(Value::Number(110.0)));
185        let after = geometry_at(&instance, code, "Sub {");
186        assert!(
187            (after.origin.x - base.origin.x - 100.0).abs() < 0.5,
188            "x override should shift the instance by 100px (base {}, after {})",
189            base.origin.x,
190            after.origin.x
191        );
192        set_override(&store, element_hash, "x", None);
193
194        // Overriding the injected transform-rotation hook must be possible (the Transform
195        // wrapper element is reified around the instance) and must not affect the geometry.
196        set_override(&store, element_hash, "transform-rotation", Some(Value::Number(45.0)));
197        let rotated = geometry_at(&instance, code, "Sub {");
198        assert!(
199            (rotated.origin.x - base.origin.x).abs() < 0.5,
200            "rotation must not move the origin"
201        );
202        set_override(&store, element_hash, "transform-rotation", None);
203    }
204
205    #[test]
206    fn debug_hook_forwards_live_private_state_per_instance() {
207        let code = r#"
208component Sub inherits Rectangle {
209    in property <length> seed;
210    in property <bool> active;
211    in-out property <length> inherited-value: private-child.x;
212    private-child := Rectangle { x: root.seed; }
213    states [
214        active when root.active: {
215            private-child.x: 50px;
216        }
217    ]
218}
219export component Win inherits Window {
220    in-out property <length> first-seed: 10px;
221    in-out property <bool> first-active;
222    first := Sub { seed: root.first-seed; active: root.first-active; }
223    second := Sub { seed: 20px; }
224    out property <length> first-value: first.inherited-value;
225    out property <length> second-value: second.inherited-value;
226}"#;
227        let instance = compile_with_debug_hooks(code);
228        let store = install_debug_hook_store(&instance);
229        let first_hash = find_element_hash(&instance, code, "Sub { seed: root.first-seed");
230
231        assert_eq!(instance.get_property("first-value").unwrap(), Value::Number(10.0));
232        assert_eq!(instance.get_property("second-value").unwrap(), Value::Number(20.0));
233
234        instance.set_property("first-seed", Value::Number(15.0)).unwrap();
235        assert_eq!(instance.get_property("first-value").unwrap(), Value::Number(15.0));
236        assert_eq!(instance.get_property("second-value").unwrap(), Value::Number(20.0));
237
238        instance.set_property("first-active", Value::Bool(true)).unwrap();
239        assert_eq!(instance.get_property("first-value").unwrap(), Value::Number(50.0));
240
241        set_override(&store, first_hash, "inherited-value", Some(Value::Number(90.0)));
242        instance.set_property("first-active", Value::Bool(false)).unwrap();
243        instance.set_property("first-seed", Value::Number(25.0)).unwrap();
244        assert_eq!(instance.get_property("first-value").unwrap(), Value::Number(90.0));
245        assert_eq!(instance.get_property("second-value").unwrap(), Value::Number(20.0));
246
247        set_override(&store, first_hash, "inherited-value", None);
248        assert_eq!(instance.get_property("first-value").unwrap(), Value::Number(25.0));
249        assert_eq!(instance.get_property("second-value").unwrap(), Value::Number(20.0));
250    }
251
252    // Regression test: debug hooks inject bindings for properties the element may not have
253    // natively (geometry, transform-rotation). Every injected binding must end up on a property
254    // that actually exists at runtime, for every kind of element — otherwise instantiation
255    // aborts with "unknown property ... in ...". Exercise the special cases: the root element,
256    // plain items, elements that become component roots later (PopupWindow — plain or through
257    // component inheritance), non-item types (Timer), repeated and conditional elements,
258    // layouts, menus, style widgets, and tooltips with custom content.
259    #[test]
260    fn debug_hooks_instantiate_special_elements() {
261        let code = r#"
262import { Button } from "std-widgets.slint";
263
264component MyPopup inherits PopupWindow {
265    Rectangle { background: yellow; }
266}
267
268export component Win inherits Window {
269    width: 300px;
270    height: 300px;
271
272    MenuBar {
273        Menu {
274            title: "File";
275            MenuItem { title: "Quit"; }
276        }
277    }
278
279    rect := Rectangle {
280        rotated := Rectangle { transform-rotation: 45deg; }
281        scaled := Rectangle { transform-scale: 150%; }
282        plain := Rectangle { }
283    }
284
285    covered := Rectangle {
286        Tooltip {
287            Rectangle { background: #222; }
288        }
289    }
290
291    Button { text: "a widget"; }
292
293    popup := PopupWindow {
294        Text { text: "popup content"; }
295    }
296    my-popup := MyPopup { }
297    callback show-the-popups();
298    show-the-popups() => { popup.show(); my-popup.show(); }
299
300    Timer { interval: 1s; running: false; }
301
302    for _ in 3: Rectangle { width: 10px; }
303    if true: Rectangle { height: 5px; }
304
305    VerticalLayout {
306        Rectangle { }
307    }
308}"#;
309
310        let instance = compile_with_debug_hooks(code);
311
312        // Showing the popups instantiates the popup components (their bindings are only set up then).
313        instance.invoke("show-the-popups", &[]).unwrap();
314    }
315
316    // Enabling debug_hooks now also materializes hooked default bindings for unbound properties.
317    // This must NOT change the rendered result when no override is set: wrapping default-geometry
318    // bindings must preserve fill/implicit sizing, and injecting the type-default for unbound props
319    // must equal their unbound value (e.g. the font sentinel that drives Window inheritance).
320    #[test]
321    fn debug_hooks_preserve_geometry() {
322        i_slint_backend_testing::init_no_event_loop();
323
324        let code = r#"
325export component Win inherits Window {
326    width: 300px;
327    height: 200px;
328    rect := Rectangle { }            // no explicit geometry -> fills the parent
329    txt := Text { text: "Hello"; }   // implicit (font-dependent) size, inherited font
330}"#;
331        let geometries = |debug_hooks: bool| -> Vec<(f32, f32, f32, f32)> {
332            let mut compiler = Compiler::default();
333            if debug_hooks {
334                compiler.compiler_configuration(i_slint_core::InternalToken).debug_hooks =
335                    Some(std::hash::RandomState::new());
336            }
337            let r = spin_on::spin_on(compiler.build_from_source_path(
338                Some(code.to_string()),
339                test_path(),
340                i_slint_core::InternalToken,
341            ));
342            assert!(!r.has_errors(), "{:?}", r.diagnostics);
343            let instance = r.components().next().unwrap().create().unwrap();
344            [code.find("Rectangle").unwrap(), code.find("Text").unwrap()]
345                .into_iter()
346                .map(|offset| {
347                    let geometry = instance
348                        .component_positions(&test_path(), offset as u32)
349                        .first()
350                        .expect("geometry")
351                        .rect;
352                    (
353                        geometry.origin.x,
354                        geometry.origin.y,
355                        geometry.size.width,
356                        geometry.size.height,
357                    )
358                })
359                .collect()
360        };
361
362        let without = geometries(false);
363        let with = geometries(true);
364        for (a, b) in without.iter().zip(with.iter()) {
365            assert!(
366                (a.0 - b.0).abs() < 0.5
367                    && (a.1 - b.1).abs() < 0.5
368                    && (a.2 - b.2).abs() < 0.5
369                    && (a.3 - b.3).abs() < 0.5,
370                "geometry differs with vs without debug_hooks: {a:?} vs {b:?}"
371            );
372        }
373        // Sanity: the Rectangle actually filled the 300x200 window (so we know we compared real sizes).
374        assert!((with[0].2 - 300.0).abs() < 0.5);
375        assert!((with[0].3 - 200.0).abs() < 0.5);
376    }
377}