Skip to main content

slint_interpreter/
popup.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 `ShowPopupWindow` / `ClosePopupWindow` /
5//! `SetupMenuBar` / `ShowPopupMenu` builtins: build the popup `Instance`,
6//! register it with the window, and wire the menu callbacks.
7
8use crate::eval::{
9    EvalContext, eval_expression, find_window_adapter, resolve_item_rc_from_ref, store_property,
10    try_walk_to,
11};
12use crate::instance::SubComponentInstance;
13use crate::prelude::*;
14use i_slint_compiler::llr::{Expression, LocalMemberIndex, MemberReference};
15use i_slint_core::model::Model;
16
17pub(crate) fn show_popup_window(ctx: &mut EvalContext, arguments: &[Expression]) -> Value {
18    // Expected args (from `BuiltinFunction::ShowPopupWindow`):
19    //   0: NumberLiteral(popup_index) into the declaring sub-component's popup_windows
20    //   1: close_policy expression
21    //   2: PropertyReference to the declaring component's root (`owner_ref`): its
22    //      `popup_id` and the popup's scope live here. Resolved through the full
23    //      reference (parent level *and* sub-component path) so a popup shown from
24    //      a nested sub-component or an inlined function resolves correctly.
25    //   3: PropertyReference to the parent item used for positioning (`anchor_ref`),
26    //      which may be a different (nested) item than the declaring component.
27    //   4 (optional): PropertyReference to the synthesized `is-open` property,
28    //      resolving in this call's own frame (see lower_show_popup_window)
29    let [
30        Expression::NumberLiteral(popup_index),
31        close_policy_expr,
32        Expression::PropertyReference(owner_ref),
33        Expression::PropertyReference(anchor_ref),
34        is_open_args @ ..,
35    ] = arguments
36    else {
37        return Value::Void;
38    };
39    let MemberReference::Relative { parent_level, local_reference } = owner_ref else {
40        return Value::Void;
41    };
42
43    let current = match ctx.current.as_ref() {
44        Some(c) => c.clone(),
45        None => return Value::Void,
46    };
47    let Some(owner) = try_walk_to(ctx, *parent_level, local_reference) else {
48        return Value::Void;
49    };
50    let cu = owner.compilation_unit.clone();
51    let sc = &cu.sub_components[owner.sub_component_idx];
52    let popup = match sc.popup_windows.get(*popup_index as usize) {
53        Some(p) => p,
54        None => return Value::Void,
55    };
56
57    let popup_vrc = new_popup_for(&owner, &popup.item_tree);
58
59    let close_policy: i_slint_core::items::PopupClosePolicy =
60        eval_expression(ctx, close_policy_expr).try_into().unwrap_or_default();
61
62    let Some((parent_instance, parent_flat)) = resolve_item_rc_from_ref(ctx, anchor_ref) else {
63        return Value::Void;
64    };
65    let parent_item_rc = i_slint_core::items::ItemRc::new(
66        VRc::into_dyn(parent_instance.clone()),
67        parent_flat as u32,
68    );
69    // The owner may itself be a popup without its own window adapter; walk
70    // the parent chain so a popup-in-popup registers with the root window's
71    // adapter instead of creating a fresh, headless one.
72    let Some(adapter) = find_window_adapter(ctx) else {
73        return Value::Void;
74    };
75
76    let window_kind = || {
77        if popup.is_tooltip {
78            i_slint_core::window::WindowKind::ToolTip
79        } else {
80            i_slint_core::window::WindowKind::Popup
81        }
82    };
83    // Give the popup its own window adapter when the backend can create
84    // one — `WindowInner::show_popup` then shows it as a native top-level
85    // popup instead of a child window rendered into the parent surface.
86    if let Some(child_adapter) = i_slint_core::window::WindowInner::from_pub(adapter.window())
87        .create_child_window_adapter(window_kind())
88    {
89        let _ = popup_vrc.window_adapter.set(child_adapter);
90    }
91
92    // Install bindings now but defer `init_code` until after `show_popup`,
93    // so `forward-focus` calls reach a popup the window adapter already
94    // considers active.
95    crate::instance::init_items_and_bindings(&popup_vrc);
96
97    // The position expression is evaluated lazily so the window can
98    // re-query it after measuring the popup.
99    let access_position: Box<dyn Fn() -> i_slint_core::api::LogicalPosition> = {
100        let pos_expr = popup.position.borrow().clone();
101        let popup_root = popup_vrc.root_sub_component.clone();
102        Box::new(move || {
103            let mut popup_ctx = EvalContext::new(popup_root.clone());
104            eval_expression(&mut popup_ctx, &pos_expr).try_into().unwrap_or_default()
105        })
106    };
107    // Keeps the caller's synthesized `is-open` property in sync:
108    // `show_popup` invokes this setter with `true` on show and `false` from
109    // every close path. The reference resolves in the show call's own frame.
110    let is_open_setter: Box<dyn Fn(bool)> = match is_open_args.first() {
111        Some(Expression::PropertyReference(is_open_ref)) => {
112            let is_open_ref = is_open_ref.clone();
113            let current_weak = Rc::downgrade(&Pin::into_inner(current.clone()));
114            Box::new(move |value: bool| {
115                if let Some(current) = current_weak.upgrade() {
116                    let ctx = EvalContext::new(Pin::new(current));
117                    store_property(&ctx, &is_open_ref, Value::Bool(value));
118                }
119            })
120        }
121        _ => Box::new(|_| {}),
122    };
123    let popup_dyn = VRc::into_dyn(popup_vrc.clone());
124    let popup_id = i_slint_core::window::WindowInner::from_pub(adapter.window()).show_popup(
125        &popup_dyn,
126        access_position,
127        close_policy,
128        &parent_item_rc,
129        window_kind(),
130        is_open_setter,
131    );
132    // Remember the id so `close_popup_window` can find it by popup index.
133    if let Some(slot) = owner.popup_ids.get(*popup_index as usize) {
134        slot.set(Some(popup_id));
135    }
136    // `init_code` runs now that the popup is registered, so `forward-focus`
137    // calls can target items in the popup.
138    crate::instance::finalize_instance(&popup_vrc);
139    Value::Void
140}
141
142pub(crate) fn close_popup_window(ctx: &mut EvalContext, arguments: &[Expression]) -> Value {
143    // Expected args (from `BuiltinFunction::ClosePopupWindow`):
144    //   0: NumberLiteral(popup_index) into the declaring sub-component's popup_windows
145    //   1: PropertyReference to the declaring component's root, where `popup_id`
146    //      lives — resolved through the full reference like `show_popup_window`.
147    let [Expression::NumberLiteral(popup_index), Expression::PropertyReference(parent_ref)] =
148        arguments
149    else {
150        return Value::Void;
151    };
152    let MemberReference::Relative { parent_level, local_reference } = parent_ref else {
153        return Value::Void;
154    };
155    // Resolve the declaring component through the full parent item reference,
156    // matching `show_popup_window` so the popup id stored there is found again.
157    let Some(owner) = try_walk_to(ctx, *parent_level, local_reference) else {
158        return Value::Void;
159    };
160    let id = owner.popup_ids.get(*popup_index as usize).and_then(|slot| slot.take());
161    if let Some(id) = id
162        && let Some(root_inst) = owner.root.get().and_then(|w| w.upgrade())
163        && let Some(adapter) = root_inst.window_adapter_or_default()
164    {
165        i_slint_core::window::WindowInner::from_pub(adapter.window()).close_popup(id);
166    }
167    Value::Void
168}
169
170pub(crate) fn setup_menubar(ctx: &mut EvalContext, arguments: &[Expression]) -> Value {
171    let [
172        Expression::PropertyReference(entries_ref),
173        Expression::PropertyReference(sub_menu_ref),
174        Expression::PropertyReference(activated_ref),
175        Expression::NumberLiteral(tree_index),
176        Expression::BoolLiteral(no_native),
177        condition,
178        visible,
179        ..,
180    ] = arguments
181    else {
182        return Value::Void;
183    };
184    let (tree_index, no_native) = (*tree_index as usize, *no_native);
185
186    let current = match ctx.current.as_ref() {
187        Some(c) => c.clone(),
188        None => return Value::Void,
189    };
190    let cu = current.compilation_unit.clone();
191    let sc = &cu.sub_components[current.sub_component_idx];
192    let Some(menu_tree) = sc.menu_item_trees.get(tree_index) else {
193        return Value::Void;
194    };
195
196    let menu_vrc = new_popup_for(&current, menu_tree);
197    crate::instance::finalize_instance(&menu_vrc);
198
199    let menu_dyn = VRc::into_dyn(menu_vrc);
200    let menu_item_tree =
201        VRc::new(i_slint_core::menus::MenuFromItemTree::new_with_condition_and_visible(
202            menu_dyn,
203            bool_binding(&current, condition),
204            bool_binding(&current, visible),
205        ));
206
207    let Some(adapter) = find_window_adapter(ctx) else { return Value::Void };
208    let window_inner = i_slint_core::window::WindowInner::from_pub(adapter.window());
209    let menubar = VRc::into_dyn(VRc::clone(&menu_item_tree));
210    window_inner.setup_menubar_shortcuts(VRc::clone(&menubar));
211
212    // Keep the menubar alive on the owning sub-component: the native menu bar only holds a weak
213    // reference to it.
214    *current.menubar.borrow_mut() = Some(VRc::clone(&menubar));
215
216    if !no_native && window_inner.supports_native_menu_bar() {
217        window_inner.setup_menubar(menubar);
218        return Value::Void;
219    }
220
221    // Wire up entries/sub_menu/activated for the fallback menu bar widget.
222    wire_menu_from_item_tree(ctx, entries_ref, sub_menu_ref, activated_ref, menu_item_tree);
223
224    Value::Void
225}
226
227pub(crate) fn setup_system_tray_icon(ctx: &mut EvalContext, arguments: &[Expression]) -> Value {
228    // Expected args (from `lower_menus`):
229    //   0: PropertyReference to the native `SystemTrayIcon` item
230    //   1: NumberLiteral(tree_index) into the owning sub-component's menu_item_trees
231    //   2 (optional): condition expression from `if cond : Menu { ... }`
232    let [
233        Expression::PropertyReference(system_tray_ref),
234        Expression::NumberLiteral(tree_index),
235        rest @ ..,
236    ] = arguments
237    else {
238        return Value::Void;
239    };
240
241    let current = match ctx.current.as_ref() {
242        Some(c) => c.clone(),
243        None => return Value::Void,
244    };
245    let cu = current.compilation_unit.clone();
246    let sc = &cu.sub_components[current.sub_component_idx];
247    let Some(menu_tree) = sc.menu_item_trees.get(*tree_index as usize) else {
248        return Value::Void;
249    };
250
251    let menu_vrc = new_popup_for(&current, menu_tree);
252    crate::instance::finalize_instance(&menu_vrc);
253
254    // `if cond : Menu { ... }` lowers the condition into a closure that
255    // gates the menu's shadow tree.
256    let condition: Box<dyn Fn() -> bool> = match rest.first() {
257        Some(expr) => Box::new(bool_binding(&current, expr)),
258        None => Box::new(|| true),
259    };
260    let menu_item_tree =
261        VRc::new(i_slint_core::menus::MenuFromItemTree::new_with_condition_and_visible(
262            VRc::into_dyn(menu_vrc),
263            condition,
264            || true,
265        ));
266
267    let Some((parent_inst, flat_idx)) = resolve_item_rc_from_ref(ctx, system_tray_ref) else {
268        return Value::Void;
269    };
270    let item_rc = i_slint_core::items::ItemRc::new(VRc::into_dyn(parent_inst), flat_idx as u32);
271    if let Some(tray) = item_rc.downcast::<i_slint_core::items::SystemTrayIcon>() {
272        tray.as_pin_ref().set_menu(&item_rc, VRc::into_dyn(menu_item_tree));
273    }
274    Value::Void
275}
276
277pub(crate) fn show_popup_menu(ctx: &mut EvalContext, arguments: &[Expression]) -> Value {
278    let [Expression::PropertyReference(context_menu_ref), entries_expr, position_expr] = arguments
279    else {
280        return Value::Void;
281    };
282
283    let position: i_slint_core::api::LogicalPosition =
284        eval_expression(ctx, position_expr).try_into().unwrap_or_default();
285
286    let Some((parent_inst, context_flat_idx)) = resolve_item_rc_from_ref(ctx, context_menu_ref)
287    else {
288        return Value::Void;
289    };
290    let context_item_rc = i_slint_core::items::ItemRc::new(
291        VRc::into_dyn(parent_inst.clone()),
292        context_flat_idx as u32,
293    );
294    let context_menu_item_weak = context_item_rc.downgrade();
295    let Some(adapter) = find_window_adapter(ctx) else {
296        return Value::Void;
297    };
298
299    let cu = ctx.current.as_ref().map(|c| c.compilation_unit.clone()).unwrap();
300    let Some(popup_menu) = cu.popup_menu.as_ref() else {
301        return Value::Void;
302    };
303
304    let current = ctx.current.as_ref().unwrap();
305    let popup_vrc = new_popup_for(current, &popup_menu.item_tree);
306    // Install bindings now but defer `init_code` until after `show_popup`,
307    // so `forward-focus` calls reach a popup the window adapter already
308    // considers active.
309    crate::instance::init_items_and_bindings(&popup_vrc);
310
311    // Wire entries/sub_menu/activated on the popup. Two flavors:
312    //
313    //   - `ShowPopupMenu` (regular `ContextMenuArea`): the entries come
314    //     from a `MenuItem` tree we walk via `MenuFromItemTree`.
315    //   - `ShowPopupMenuInternal` (`ContextMenuInternal`): the entries
316    //     come from an array property on the user's `ContextMenu` item,
317    //     and `sub_menu` / `activated` forward back to the user's
318    //     callbacks rather than a shadow tree.
319    let popup_ctx = crate::eval::EvalContext::new(popup_vrc.root_sub_component.clone());
320
321    if let Expression::NumberLiteral(tree_index) = entries_expr {
322        let sc = &cu.sub_components[current.sub_component_idx];
323        let Some(menu_tree) = sc.menu_item_trees.get(*tree_index as usize) else {
324            return Value::Void;
325        };
326        let menu_vrc = Instance::new_popup(
327            cu.clone(),
328            menu_tree,
329            Rc::downgrade(&Pin::into_inner(current.clone())),
330            popup_vrc.globals.clone(),
331        );
332        crate::instance::finalize_instance(&menu_vrc);
333        let menu_item_tree =
334            VRc::new(i_slint_core::menus::MenuFromItemTree::new(VRc::into_dyn(menu_vrc)));
335
336        // Prefer the platform's native context menu; fall back to the
337        // Slint-rendered popup below when the backend doesn't provide one.
338        if i_slint_core::window::WindowInner::from_pub(adapter.window()).show_native_popup_menu(
339            VRc::into_dyn(VRc::clone(&menu_item_tree)),
340            position,
341            &context_item_rc,
342        ) {
343            return Value::Void;
344        }
345
346        wire_menu_from_item_tree(
347            &popup_ctx,
348            &popup_menu.entries,
349            &popup_menu.sub_menu,
350            &popup_menu.activated,
351            menu_item_tree,
352        );
353    } else {
354        // ShowPopupMenuInternal: entries are an array property of the
355        // `ContextMenuInternal` item; sub_menu/activated forward to the
356        // user-defined callbacks on the same item.
357        let entries_value = eval_expression(ctx, entries_expr);
358        wire_popup_menu_prop(&popup_ctx, &popup_menu.entries, move || entries_value.clone());
359
360        if let MemberReference::Relative { parent_level, local_reference } = context_menu_ref {
361            let Some(sub_menu_owner) = try_walk_to(ctx, *parent_level, local_reference) else {
362                return Value::Void;
363            };
364            let LocalMemberIndex::Native { item_index, .. } = &local_reference.reference else {
365                return Value::Void;
366            };
367            let item_index_for_sub = *item_index;
368            let sub_menu_owner_weak = Rc::downgrade(&Pin::into_inner(sub_menu_owner.clone()));
369            wire_popup_menu_cb(&popup_ctx, &popup_menu.sub_menu, move |args| {
370                let Some(owner) = sub_menu_owner_weak.upgrade() else { return Value::Void };
371                let item = Pin::as_ref(&owner.items[item_index_for_sub]);
372                let entry: i_slint_core::items::MenuEntry =
373                    args.first().cloned().unwrap_or_default().try_into().unwrap_or_default();
374                let raw = item.as_item_ref();
375                use i_slint_core::items::ContextMenu;
376                let Some(cm) = vtable::VRef::downcast_pin::<ContextMenu>(raw) else {
377                    return Value::Void;
378                };
379                let mut out = i_slint_core::SharedVector::default();
380                cm.sub_menu.call(&(entry,)).iter().for_each(|e| out.push(e));
381                Value::Model(i_slint_core::model::ModelRc::new(
382                    i_slint_core::model::VecModel::from(
383                        out.into_iter().map(Value::from).collect::<Vec<_>>(),
384                    ),
385                ))
386            });
387
388            let activated_owner_weak = Rc::downgrade(&Pin::into_inner(sub_menu_owner.clone()));
389            let item_index_for_activated = *item_index;
390            wire_popup_menu_cb(&popup_ctx, &popup_menu.activated, move |args| {
391                let Some(owner) = activated_owner_weak.upgrade() else { return Value::Void };
392                let item = Pin::as_ref(&owner.items[item_index_for_activated]);
393                let entry: i_slint_core::items::MenuEntry =
394                    args.first().cloned().unwrap_or_default().try_into().unwrap_or_default();
395                let raw = item.as_item_ref();
396                use i_slint_core::items::ContextMenu;
397                let Some(cm) = vtable::VRef::downcast_pin::<ContextMenu>(raw) else {
398                    return Value::Void;
399                };
400                cm.activated.call(&(entry,));
401                Value::Void
402            });
403        }
404    }
405
406    // Wire the popup menu's `close` callback so a menu item that calls
407    // `root.close()` dismisses the popup. The shared `Cell` bridges the
408    // popup id (only known after `show_popup`) into the close handler
409    // installed before the show.
410    let popup_id_cell: Rc<Cell<Option<core::num::NonZeroU32>>> = Rc::new(Cell::new(None));
411    let id_cell_for_close = popup_id_cell.clone();
412    let adapter_for_close = adapter.clone();
413    wire_popup_menu_cb(&popup_ctx, &popup_menu.close, move |_args| {
414        if let Some(id) = id_cell_for_close.take() {
415            i_slint_core::window::WindowInner::from_pub(adapter_for_close.window()).close_popup(id);
416        }
417        Value::Void
418    });
419
420    let popup_dyn = VRc::into_dyn(popup_vrc.clone());
421    let window_inner = i_slint_core::window::WindowInner::from_pub(adapter.window());
422    let popup_id = window_inner.show_popup(
423        &popup_dyn,
424        Box::new(move || position),
425        i_slint_core::items::PopupClosePolicy::CloseOnClickOutside,
426        &context_item_rc,
427        i_slint_core::window::WindowKind::Menu,
428        Box::new(|_| {}),
429    );
430    popup_id_cell.set(Some(popup_id));
431    // Store the popup id on the native `ContextMenu` item, so its
432    // `is-open()` and `close()` member functions see this popup as the
433    // active one.
434    if let Some(item_rc) = context_menu_item_weak.upgrade()
435        && let Some(cm) = item_rc.downcast::<i_slint_core::items::ContextMenu>()
436    {
437        cm.as_pin_ref().popup_id.set(Some(popup_id));
438    }
439
440    // `init_code` runs now that the popup is registered, so `forward-focus`
441    // calls can target items in the popup.
442    crate::instance::finalize_instance(&popup_vrc);
443
444    Value::Void
445}
446
447/// Build a popup / menu `Instance` owned by `owner`, sharing the root
448/// instance's global storage (or fresh storage when the owner is already
449/// detached from a root).
450fn new_popup_for(
451    owner: &Pin<Rc<SubComponentInstance>>,
452    item_tree: &i_slint_compiler::llr::ItemTree,
453) -> VRc<ItemTreeVTable, Instance> {
454    let cu = owner.compilation_unit.clone();
455    let parent_weak = Rc::downgrade(&Pin::into_inner(owner.clone()));
456    let globals =
457        owner.root.get().and_then(|w| w.upgrade()).map(|inst| inst.globals.clone()).unwrap_or_else(
458            || {
459                let context = SlintContext::current()
460                    .expect("a component exists, so there is a current context");
461                Rc::new(crate::globals::GlobalStorage::new(&cu, context, Default::default()))
462            },
463        );
464    Instance::new_popup(cu, item_tree, parent_weak, globals)
465}
466
467/// A closure that evaluates `expr` in `owner`'s scope on each call;
468/// `false` once the owner is gone.
469fn bool_binding(
470    owner: &Pin<Rc<SubComponentInstance>>,
471    expr: &Expression,
472) -> impl Fn() -> bool + 'static {
473    let expr = expr.clone();
474    let weak = Rc::downgrade(&Pin::into_inner(owner.clone()));
475    move || {
476        let Some(owner) = weak.upgrade() else { return false };
477        let mut ctx = EvalContext::new(Pin::new(owner));
478        matches!(eval_expression(&mut ctx, &expr), Value::Bool(true))
479    }
480}
481
482/// Wire the `entries` property and the `sub-menu` / `activated` callbacks
483/// to a `MenuFromItemTree`. Shared by the menu bar fallback widget and the
484/// Slint-rendered context menu popup.
485fn wire_menu_from_item_tree(
486    ctx: &EvalContext,
487    entries: &MemberReference,
488    sub_menu: &MemberReference,
489    activated: &MemberReference,
490    menu_item_tree: VRc<i_slint_core::menus::MenuVTable, i_slint_core::menus::MenuFromItemTree>,
491) {
492    fn entries_model(
493        mt: &i_slint_core::menus::MenuFromItemTree,
494        parent: Option<&i_slint_core::items::MenuEntry>,
495    ) -> Value {
496        let mut entries = i_slint_core::SharedVector::default();
497        i_slint_core::menus::Menu::sub_menu(mt, parent, &mut entries);
498        Value::Model(i_slint_core::model::ModelRc::new(i_slint_core::model::VecModel::from(
499            entries.into_iter().map(Value::from).collect::<Vec<_>>(),
500        )))
501    }
502    let mt = VRc::clone(&menu_item_tree);
503    wire_popup_menu_prop(ctx, entries, move || entries_model(&mt, None));
504    let mt = VRc::clone(&menu_item_tree);
505    wire_popup_menu_cb(ctx, sub_menu, move |args| {
506        let entry = args.first().cloned().unwrap_or_default().try_into().unwrap_or_default();
507        entries_model(&mt, Some(&entry))
508    });
509    wire_popup_menu_cb(ctx, activated, move |args| {
510        let entry = args.first().cloned().unwrap_or_default().try_into().unwrap_or_default();
511        i_slint_core::menus::Menu::activate(&*menu_item_tree, &entry);
512        Value::Void
513    });
514}
515
516fn wire_popup_menu_prop(
517    ctx: &EvalContext,
518    mr: &MemberReference,
519    binding: impl Fn() -> Value + 'static,
520) {
521    if let MemberReference::Relative { parent_level, local_reference } = mr
522        && let Some(owner) = try_walk_to(ctx, *parent_level, local_reference)
523        && let LocalMemberIndex::Property(idx) = &local_reference.reference
524    {
525        Pin::as_ref(&owner.properties[*idx]).set_binding(binding);
526    }
527}
528
529fn wire_popup_menu_cb(
530    ctx: &EvalContext,
531    mr: &MemberReference,
532    handler: impl Fn(&[Value]) -> Value + 'static,
533) {
534    if let MemberReference::Relative { parent_level, local_reference } = mr
535        && let Some(owner) = try_walk_to(ctx, *parent_level, local_reference)
536        && let LocalMemberIndex::Callback(idx) = &local_reference.reference
537    {
538        Pin::as_ref(&owner.callbacks[*idx]).set_handler(handler);
539    }
540}