Skip to main content

egui_pop_api/workbench/
panel_menu.rs

1//! The panel menu: one context menu for a panel wherever it is, docked
2//! (its tab, which `egui_stack` opens), floating (its title and its tabs)
3//! or detached (its window's tabs).
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! It is a declared menu
9//! ([`MENU_PANEL`]), its entries made when it opens by list providers that
10//! read where the panel is, each running a workbench command with the
11//! panel in its arguments:
12//!
13//! - docked: Move to each area its rules allow, and Float when it may;
14//!   floating or detached: Dock back (where it floated from); floating:
15//!   Dock in each side bar and the bottom panel (`palette.dock`);
16//! - Detach into a window; Move to window ▸ (the detached windows, by
17//!   their panels' titles); Move group to window ▸ (its tab group whole,
18//!   to a window or a new one);
19//! - Move to group ▸ (the docked tab groups, by their panels' titles);
20//! - Zen this panel: the panel alone, full size, in its window
21//!   (`workbench.zen` with the panel);
22//! - Close.
23//!
24//! A floating panel's menu opens through [`crate::menus::context_menu`],
25//! so it is a `pop.popup.open` on the bus like every context menu.
26//!
27//! A tab group has two more ways to open a panel in it, both asking
28//! `pop.panel.open` with `here` (the `workbench.panel.open` command):
29//!
30//! - the group menu ([`MENU_GROUP`], a right click on the empty part of
31//!   its tab bar): Open panel ▸, every panel its place allows that is not
32//!   one of its tabs, an open one moving there;
33//! - the "+" at the end of its tab bar
34//!   ([`DockControls::add_buttons`](super::DockControls::add_buttons)):
35//!   the closed panels its place allows ([`MENU_GROUP_ADD`]).
36//!
37//! Both list first "New `<panel>`" for each panel declared with several
38//! instances its place allows (`pop.panel.open` with `instance: "new"`).
39//! The same entries, opening where the panel's area is, are the list
40//! [`LIST_NEW_INSTANCES`], in the View menu and for an application's own
41//! Window menu (`MenuItem::list`).
42
43use egui::Response;
44use egui_pop_core::strings;
45use egui_pop_model::commands::CommandSpec;
46use egui_pop_model::ids::{CommandId, MenuId, PanelId};
47use egui_pop_model::menus::MenuItem;
48use egui_pop_model::panels::{Area, Place};
49use egui_pop_model::when::WhenContext;
50use serde_json::{Value as Json, json};
51
52use super::{Change, area_name, area_text};
53use crate::app::AppHandle;
54use crate::menus::{self, ListItem};
55use crate::steps::Outcome;
56use crate::strings as txt;
57use crate::{Ctx, CtxError};
58
59/// The panel menu (`args.panel`: the panel it acts on).
60pub const MENU_PANEL: MenuId = MenuId::from_static("workbench.panel");
61/// Its submenu listing the detached windows the panel may join.
62pub const MENU_PANEL_WINDOWS: MenuId = MenuId::from_static("workbench.panel.windows");
63/// Its submenu moving the panel's tab group into a window.
64pub const MENU_PANEL_GROUP_WINDOWS: MenuId = MenuId::from_static("workbench.panel.group_windows");
65/// Its submenu listing the docked tab groups the panel may join.
66pub const MENU_PANEL_GROUPS: MenuId = MenuId::from_static("workbench.panel.groups");
67
68/// A tab group's menu (`args.group`: a panel of the group): Open panel ▸.
69pub const MENU_GROUP: MenuId = MenuId::from_static("workbench.group");
70/// Its submenu listing the panels that may open in the group.
71pub const MENU_GROUP_OPEN: MenuId = MenuId::from_static("workbench.group.open");
72/// The menu under a tab bar's "+" (`args.group`): the closed panels that
73/// may open in the group.
74pub const MENU_GROUP_ADD: MenuId = MenuId::from_static("workbench.group.add");
75
76/// Opens a panel through `pop.panel.open` (`panel`; `place`: `last`, the
77/// default, `here` or an area's name; `group`: a panel of the tab group
78/// `here` means, else the focused panel's).
79pub const CMD_PANEL_OPEN: CommandId = CommandId::from_static("workbench.panel.open");
80/// "Open panel…": a quick pick in the command palette of every declared
81/// panel (and "New `<panel>`" for those declared with several), the
82/// chosen one opened where it was (`workbench.panel.open`, `place:
83/// "last"`). `Ctrl+Shift+O`.
84pub const CMD_PANEL_PICK: CommandId = CommandId::from_static("workbench.panel.pick");
85/// Docks a panel in an area (`panel`, `area`).
86pub const CMD_PANEL_MOVE: CommandId = CommandId::from_static("workbench.panel.move");
87/// Floats a docked panel, where its area is (`panel`; `group`: its tab
88/// group whole).
89pub const CMD_PANEL_FLOAT: CommandId = CommandId::from_static("workbench.panel.float");
90/// Moves a panel into a window of its own (`panel`; `group`: its tab
91/// group whole).
92pub const CMD_PANEL_DETACH: CommandId = CommandId::from_static("workbench.panel.detach");
93/// Docks a panel in the tab group holding `group` (`panel`, `group`).
94pub const CMD_PANEL_MOVE_TO_GROUP: CommandId =
95    CommandId::from_static("workbench.panel.move_to_group");
96/// Docks a floating or detached panel back where it floated from
97/// (`panel`).
98pub const CMD_PANEL_DOCK_BACK: CommandId = CommandId::from_static("workbench.panel.dock_back");
99/// Closes a panel (`panel`).
100pub const CMD_PANEL_CLOSE: CommandId = CommandId::from_static("workbench.panel.close");
101
102const LIST_PLACE: &str = "workbench.panel.place";
103const LIST_DETACH: &str = "workbench.panel.detach";
104const LIST_WINDOWS: &str = "workbench.panel.windows";
105const LIST_GROUP_WINDOWS: &str = "workbench.panel.group_windows";
106const LIST_GROUPS: &str = "workbench.panel.groups";
107const LIST_CLOSE: &str = "workbench.panel.close";
108const LIST_FLOAT_GROUP: &str = "workbench.group.float";
109const LIST_ZEN: &str = "workbench.panel.zen";
110const LIST_OPEN_HERE: &str = "workbench.group.open";
111const LIST_ADD_HERE: &str = "workbench.group.add";
112/// "New `<panel>`" for each panel declared with several instances, opening
113/// a new one in the panel's area: in the View menu, and for an
114/// application's Window menu.
115pub const LIST_NEW_INSTANCES: &str = "workbench.panel.new";
116
117/// Declares the panel menu: its commands, its items and their lists.
118pub(crate) fn declare(ctx: &mut Ctx<'_>) -> Result<(), CtxError> {
119    let example = json!({ "panel": "app.inspector" });
120    ctx.command(
121        CommandSpec::new(CMD_PANEL_OPEN, "Open panel", "View")
122            .description("Opens `panel` through `pop.panel.open`: where it was when it closed (`place`: `last`, the default; that place gone, in the focused panel's tab group when its areas allow it, else its own area), `here` (the tab group holding `group`, else the focused panel's) or in an area (`center`, `start_side`, `end_side`, `bottom`). For a panel declared with several, `instance`: `new` opens a new instance (its id in `instance`), an instance's id opens that one.")
123            .when("!modalOpen")
124            .hidden()
125            .args(json!({ "panel": "app.outline", "place": "here", "group": "app.inspector" })),
126        |call| {
127            let panel = call
128                .args
129                .get("panel")
130                .and_then(Json::as_str)
131                .ok_or("`panel` is missing")?;
132            let place = match call.args.get("place").and_then(Json::as_str) {
133                Some(name) => crate::bus::OpenPlace::parse(name).ok_or_else(|| {
134                    format!("no place `{name}` (`last`, `here` or an area's name)")
135                })?,
136                None => crate::bus::OpenPlace::Last,
137            };
138            let mut ask = crate::bus::PanelOpenAsk::new(panel, place, CMD_PANEL_OPEN.as_str());
139            if let Some(g) = call.args.get("group").and_then(Json::as_str) {
140                ask = ask.group(g);
141            }
142            let instance = call.args.get("instance").and_then(Json::as_str);
143            if let Some(i) = instance {
144                ask = ask.instance(i);
145            }
146            let did = call.app.open_panel(ask)?;
147            let mut out = json!({ "panel": panel, "place": place.as_str(), "did": did });
148            // The new instance, by its id (the last one of its kind).
149            if instance == Some("new") {
150                let kind = PanelId::new(panel).map_err(|e| e.to_string())?;
151                if let Some(id) = call.app.panel_instances(&kind).last() {
152                    out["instance"] = json!(id);
153                }
154            }
155            Ok(out)
156        },
157    )?
158    .command(
159        CommandSpec::new(CMD_PANEL_PICK, "Open panel…", "View")
160            .description("Lists every panel in the command palette; the one chosen opens where it was when it closed (`workbench.panel.open`, `place: last`).")
161            .icon("layout")
162            .when("!modalOpen")
163            .key("Ctrl+Shift+O"),
164        |call| {
165            let p = call
166                .app
167                .service(&crate::palette::PALETTE)
168                .ok_or("no palette")?;
169            let pick = panel_pick(call.app);
170            let count = pick.items.len();
171            let group = call.app.current_window_group();
172            p.pick_in(group, call.app.when_context(), pick);
173            Ok(json!({ "open": true, "items": count }))
174        },
175    )?
176    .command(
177        CommandSpec::new(CMD_PANEL_MOVE, "Move panel to area", "View")
178            .description("Docks the focused panel, or `panel`, in an area (`area`: `center`, `start_side`, `end_side` or `bottom`).")
179            .when("!modalOpen")
180            .hidden()
181            .args(json!({ "panel": "app.inspector", "area": "bottom" })),
182        |call| {
183            let panel = panel_of(call.app, call.args)?;
184            let name = call
185                .args
186                .get("area")
187                .and_then(Json::as_str)
188                .ok_or("`area` is missing")?;
189            let area = super::area_from(name).ok_or_else(|| format!("no area `{name}`"))?;
190            let floating = call.app.layout().floating_of(&panel).is_some();
191            run(
192                call.app,
193                if floating {
194                    Change::Dock(panel, area)
195                } else {
196                    Change::Move(panel, area)
197                },
198            )
199        },
200    )?
201    .command(
202        CommandSpec::new(CMD_PANEL_FLOAT, "Float panel", "View")
203            .description("Floats the focused panel, or `panel`, over the interface, where its area is; with `group`, its docked tab group whole, as one floating group of tabs (Dock back puts it back).")
204            .when("!modalOpen")
205            .hidden()
206            .args(example.clone()),
207        |call| {
208            let panel = panel_of(call.app, call.args)?;
209            // Where its area is, a little in.
210            let pos = {
211                let wb = call.app.workbench_mut();
212                let at = wb
213                    .layout
214                    .area_of(&panel)
215                    .and_then(|a| wb.rects.get(&a))
216                    .map_or(wb.content.min, |r| r.min);
217                let off = at - wb.content.min;
218                [off.x + 24.0, off.y + 24.0]
219            };
220            // `group`: true, or a panel of the group (the group menu's
221            // own argument, which its entries' arguments give way to).
222            let group = matches!(
223                call.args.get("group"),
224                Some(Json::Bool(true) | Json::String(_))
225            );
226            run(
227                call.app,
228                if group {
229                    Change::FloatGroup(panel, pos)
230                } else {
231                    Change::Float(panel, pos)
232                },
233            )
234        },
235    )?
236    .command(
237        CommandSpec::new(CMD_PANEL_DETACH, "Detach panel into a window", "View")
238            .description("Moves the focused panel, or `panel`, into a window of its own; with `group`, its tab group whole.")
239            .when("!modalOpen")
240            .hidden()
241            .args(example.clone()),
242        |call| {
243            let panel = panel_of(call.app, call.args)?;
244            let group = call.args.get("group").and_then(Json::as_bool) == Some(true);
245            run(
246                call.app,
247                if group {
248                    Change::DetachGroup(panel)
249                } else {
250                    Change::Detach(panel)
251                },
252            )
253        },
254    )?
255    .command(
256        CommandSpec::new(CMD_PANEL_MOVE_TO_GROUP, "Move panel to group", "View")
257            .description("Docks the focused panel, or `panel`, in the tab group holding `group`, after its tabs: out of where it was, floating, detached or docked.")
258            .when("!modalOpen")
259            .hidden()
260            .args(json!({ "panel": "app.outline", "group": "app.inspector" })),
261        |call| {
262            let panel = panel_of(call.app, call.args)?;
263            let group = call
264                .args
265                .get("group")
266                .and_then(Json::as_str)
267                .ok_or("`group` is missing: a docked panel of the group")?;
268            let group = PanelId::new(group).map_err(|e| e.to_string())?;
269            run(call.app, Change::JoinGroup(panel, group))
270        },
271    )?
272    .command(
273        CommandSpec::new(CMD_PANEL_DOCK_BACK, "Dock panel back", "View")
274            .description("Docks the focused panel, or `panel`, floating or detached, back where it floated from (else in its own area).")
275            .when("!modalOpen")
276            .key("Ctrl+Shift+D")
277            .hidden()
278            .args(example.clone()),
279        |call| {
280            let panel = panel_of(call.app, call.args)?;
281            run(call.app, Change::DockBack(panel))
282        },
283    )?
284    .command(
285        CommandSpec::new(CMD_PANEL_CLOSE, "Close panel", "View")
286            .description("Closes the focused panel, or `panel`.")
287            .when("!modalOpen")
288            .hidden()
289            .args(example),
290        |call| {
291            let panel = panel_of(call.app, call.args)?;
292            run(call.app, Change::Hide(panel))
293        },
294    )?;
295    ctx.menu_item(MenuItem::list(MENU_PANEL, "1_place", 0, LIST_PLACE))?
296        .menu_item(MenuItem::list(MENU_PANEL, "2_window", 0, LIST_DETACH))?
297        .menu_item(
298            MenuItem::submenu(
299                MENU_PANEL,
300                "2_window",
301                1,
302                MENU_PANEL_WINDOWS,
303                "Move to window",
304            )
305            .when("args.has_windows", false),
306        )?
307        .menu_item(
308            MenuItem::submenu(
309                MENU_PANEL,
310                "2_window",
311                2,
312                MENU_PANEL_GROUP_WINDOWS,
313                "Move group to window",
314            )
315            .when("args.group_moves", false),
316        )?
317        .menu_item(
318            MenuItem::submenu(MENU_PANEL, "3_group", 0, MENU_PANEL_GROUPS, "Move to group")
319                .when("args.has_groups", false),
320        )?
321        .menu_item(MenuItem::list(MENU_PANEL, "8_zen", 0, LIST_ZEN))?
322        .menu_item(MenuItem::list(MENU_PANEL, "9_close", 0, LIST_CLOSE))?
323        .menu_item(MenuItem::list(MENU_PANEL_WINDOWS, "1", 0, LIST_WINDOWS))?
324        .menu_item(MenuItem::list(
325            MENU_PANEL_GROUP_WINDOWS,
326            "1",
327            0,
328            LIST_GROUP_WINDOWS,
329        ))?
330        .menu_item(MenuItem::list(MENU_PANEL_GROUPS, "1", 0, LIST_GROUPS))?
331        .menu_item(
332            MenuItem::submenu(MENU_GROUP, "1_open", 0, MENU_GROUP_OPEN, "Open panel")
333                .when("args.can_open", false),
334        )?
335        .menu_item(MenuItem::list(MENU_GROUP, "2_float", 0, LIST_FLOAT_GROUP))?
336        .menu_item(MenuItem::list(MENU_GROUP_OPEN, "1", 0, LIST_OPEN_HERE))?
337        .menu_item(MenuItem::list(MENU_GROUP_ADD, "1", 0, LIST_ADD_HERE))?
338        .menu_item(MenuItem::list(
339            crate::app::MENU_VIEW,
340            "4_new",
341            0,
342            LIST_NEW_INSTANCES,
343        ))?;
344    ctx.list_provider(LIST_PLACE, |app, cx| with_panel(app, cx, place_entries))
345        .list_provider(LIST_DETACH, |app, cx| with_panel(app, cx, detach_entries))
346        .list_provider(LIST_WINDOWS, |app, cx| {
347            with_panel(app, cx, |app, panel| window_entries(app, panel, false))
348        })
349        .list_provider(LIST_GROUP_WINDOWS, |app, cx| {
350            with_panel(app, cx, |app, panel| window_entries(app, panel, true))
351        })
352        .list_provider(LIST_GROUPS, |app, cx| with_panel(app, cx, group_entries))
353        .list_provider(LIST_OPEN_HERE, |app, cx| {
354            with_group(app, cx, |app, group| open_entries(app, group, false))
355        })
356        .list_provider(LIST_ADD_HERE, |app, cx| {
357            with_group(app, cx, |app, group| {
358                let entries = open_entries(app, group, true);
359                if !entries.is_empty() {
360                    return entries;
361                }
362                // Said, rather than an empty menu.
363                vec![
364                    ListItem::new(
365                        &strings::tr(&app.egui(), &txt::WORKBENCH_NOTHING_TO_OPEN),
366                        CMD_PANEL_OPEN,
367                        Json::Null,
368                    )
369                    .disabled(),
370                ]
371            })
372        })
373        .list_provider(LIST_FLOAT_GROUP, |app, cx| {
374            with_group(app, cx, |app, group| {
375                float_group_entry(app, group).into_iter().collect()
376            })
377        })
378        .list_provider(LIST_NEW_INSTANCES, |app, _| new_entries(app, None))
379        .list_provider(LIST_ZEN, |app, cx| {
380            with_panel(app, cx, |app, panel| {
381                vec![ListItem::new(
382                    &strings::tr(&app.egui(), &txt::WORKBENCH_ZEN_PANEL),
383                    super::CMD_ZEN,
384                    json!({ "panel": panel }),
385                )]
386            })
387        })
388        .list_provider(LIST_CLOSE, |app, cx| {
389            with_panel(app, cx, |app, panel| {
390                let ctx = app.egui();
391                let title = app.panel_title(&ctx, panel);
392                vec![ListItem::new(
393                    &strings::tr_args(&ctx, &txt::WORKBENCH_CLOSE_PANEL, &[("panel", &title)]),
394                    CMD_PANEL_CLOSE,
395                    json!({ "panel": panel }),
396                )]
397            })
398        });
399    Ok(())
400}
401
402/// Opens the panel menu on a widget's secondary click (or Shift+F10 and
403/// the `Menu` key while it has the focus), as a context menu: a floating
404/// panel's title, a tab of a floating group.
405pub fn context_menu(response: &Response, app: &AppHandle, panel: &PanelId) {
406    let by_key =
407        response.has_focus() && egui_pop_core::pointer::claim::menu_key(&response.ctx, true);
408    // Where the panel is, read only as the menu opens.
409    let opening = by_key || egui_pop_core::pointer::claim::opens_context_menu(response);
410    let args = if opening {
411        menu_args(app, panel)
412    } else {
413        Json::Null
414    };
415    menus::context_menu_opened(response, app, &MENU_PANEL, args, by_key);
416}
417
418/// Draws the panel menu's items in an open menu: a docked tab's, which
419/// `egui_stack` opens.
420pub(crate) fn show(ui: &mut egui::Ui, app: &AppHandle, panel: &PanelId) {
421    menus::show_args(ui, app, &MENU_PANEL, &menu_args(app, panel));
422}
423
424/// Draws a tab group's menu items (Open panel ▸) in an open menu, the
425/// group named by one of its panels: the group menu `egui_stack` opens on
426/// its bar.
427pub(crate) fn show_group(ui: &mut egui::Ui, app: &AppHandle, group: &PanelId) {
428    let args = json!({
429        "group": group,
430        "can_open": !open_entries(app, group, false).is_empty(),
431    });
432    menus::show_args(ui, app, &MENU_GROUP, &args);
433}
434
435/// The menu's arguments for a panel: the panel, and which submenus have
436/// entries (`has_windows`, `group_moves`, `has_groups`).
437pub fn menu_args(app: &AppHandle, panel: &PanelId) -> Json {
438    json!({
439        "panel": panel,
440        "has_windows": !window_entries(app, panel, false).is_empty(),
441        "group_moves": !window_entries(app, panel, true).is_empty(),
442        "has_groups": !group_entries(app, panel).is_empty(),
443    })
444}
445
446/// The panel a command names (`panel`), else the focused one.
447fn panel_of(app: &AppHandle, args: &Json) -> Result<PanelId, String> {
448    match args.get("panel").and_then(Json::as_str) {
449        Some(p) => PanelId::new(p).map_err(|e| e.to_string()),
450        None => app
451            .try_workbench()
452            .and_then(|wb| wb.focused.clone())
453            .ok_or_else(|| "no panel is focused: name one (`panel`)".into()),
454    }
455}
456
457/// Runs a workbench change as a command's result.
458fn run(app: &AppHandle, change: Change) -> Result<Json, String> {
459    match app.change_workbench(change) {
460        Some(Outcome::Done(r)) => r,
461        Some(Outcome::Vetoed { by, reason }) => Err(format!("stopped by `{by}`: {reason}")),
462        None => Ok(json!({ "queued": true })),
463    }
464}
465
466/// A list's entries for the menu's panel (`args.panel`), none without one.
467fn with_panel(
468    app: &AppHandle,
469    cx: &WhenContext,
470    f: impl FnOnce(&AppHandle, &PanelId) -> Vec<ListItem>,
471) -> Vec<ListItem> {
472    match PanelId::new(cx.get("args.panel")) {
473        Ok(panel) => f(app, &panel),
474        Err(_) => Vec::new(),
475    }
476}
477
478/// A list's entries for the menu's tab group (`args.group`, one of its
479/// panels), none without one.
480fn with_group(
481    app: &AppHandle,
482    cx: &WhenContext,
483    f: impl FnOnce(&AppHandle, &PanelId) -> Vec<ListItem>,
484) -> Vec<ListItem> {
485    match PanelId::new(cx.get("args.group")) {
486        Ok(group) => f(app, &group),
487        Err(_) => Vec::new(),
488    }
489}
490
491/// The panels that may open in the tab group holding `group`, by title:
492/// those its place (an area, a float, a window) allows that are not
493/// among its tabs; `closed`: only the closed ones (the "+"). Each opens
494/// there through `pop.panel.open` with `here`.
495fn open_entries(app: &AppHandle, group: &PanelId, closed: bool) -> Vec<ListItem> {
496    let ctx = app.egui();
497    let panels: Vec<PanelId> = {
498        let wb = app.workbench_mut();
499        let place = if let Some(area) = wb.layout.area_of(group) {
500            Place::Area(area)
501        } else if wb.layout.window_of(group).is_some() {
502            Place::Window
503        } else if wb.layout.floating_of(group).is_some() {
504            Place::Floating
505        } else {
506            return Vec::new();
507        };
508        let host = crate::mounts::panel_host(place);
509        let mates: Vec<PanelId> = match wb.layout.floating_of(group) {
510            Some(g) => g.panels().cloned().collect(),
511            None => wb
512                .layout
513                .group_of(group)
514                .map(|(panels, _)| panels)
515                .unwrap_or_default(),
516        };
517        wb.specs
518            .iter()
519            .filter(|s| !s.bare && !mates.contains(&s.id) && s.refuses(&host).is_none())
520            .filter(|s| !closed || !wb.layout.shows(&s.id))
521            .map(|s| s.id.clone())
522            .collect()
523    };
524    let mut out: Vec<(String, ListItem)> = panels
525        .into_iter()
526        .map(|p| {
527            let title = app.panel_title(&ctx, &p);
528            let item = ListItem::new(
529                &title,
530                CMD_PANEL_OPEN,
531                json!({ "panel": p, "place": "here", "group": group }),
532            );
533            (title, item)
534        })
535        .collect();
536    out.sort_by_key(|(title, _)| title.to_lowercase());
537    let mut entries = new_entries(app, Some(group));
538    entries.extend(out.into_iter().map(|(_, item)| item));
539    entries
540}
541
542/// "Open panel…"'s quick pick: "New `<panel>`" for each panel declared
543/// with several instances, then every declared panel by title, each
544/// opening where it was.
545pub fn panel_pick(app: &AppHandle) -> crate::palette::QuickPick {
546    let ctx = app.egui();
547    let panels: Vec<PanelId> = app
548        .workbench_mut()
549        .specs
550        .iter()
551        .filter(|s| !s.bare && !s.id.is_instance())
552        .map(|s| s.id.clone())
553        .collect();
554    let mut named: Vec<(String, PanelId)> = panels
555        .into_iter()
556        .map(|p| (app.panel_title(&ctx, &p), p))
557        .collect();
558    named.sort_by_key(|(title, _)| title.to_lowercase());
559    let mut pick = crate::palette::QuickPick::new(
560        strings::tr(&ctx, &txt::WORKBENCH_PICK_TITLE),
561        strings::tr(&ctx, &txt::WORKBENCH_PICK_HINT),
562    );
563    for item in new_entries(app, None) {
564        pick = pick.item(crate::palette::PickItem::new(
565            item.label,
566            item.command,
567            item.args,
568        ));
569    }
570    for (title, p) in named {
571        pick = pick.item(crate::palette::PickItem::new(
572            title,
573            CMD_PANEL_OPEN,
574            json!({ "panel": p, "place": "last" }),
575        ));
576    }
577    pick
578}
579
580/// "New `<panel>`" for each panel declared with several instances, by
581/// title: in the tab group holding `group` (those its place allows), else
582/// in the panel's own area.
583fn new_entries(app: &AppHandle, group: Option<&PanelId>) -> Vec<ListItem> {
584    let ctx = app.egui();
585    let kinds: Vec<PanelId> = {
586        let wb = app.workbench_mut();
587        let host = match group {
588            None => None,
589            Some(g) => {
590                let place = if let Some(area) = wb.layout.area_of(g) {
591                    Place::Area(area)
592                } else if wb.layout.window_of(g).is_some() {
593                    Place::Window
594                } else if wb.layout.floating_of(g).is_some() {
595                    Place::Floating
596                } else {
597                    return Vec::new();
598                };
599                Some(crate::mounts::panel_host(place))
600            }
601        };
602        wb.specs
603            .iter()
604            .filter(|s| {
605                !s.id.is_instance()
606                    && !s.bare
607                    && s.instances == egui_pop_model::panels::Instances::Multiple
608            })
609            .filter(|s| host.as_ref().is_none_or(|h| s.refuses(h).is_none()))
610            .map(|s| s.id.clone())
611            .collect()
612    };
613    let mut out: Vec<(String, ListItem)> = kinds
614        .into_iter()
615        .map(|kind| {
616            let title = app.panel_title(&ctx, &kind);
617            let args = match group {
618                Some(g) => json!({ "panel": kind, "instance": "new", "place": "here", "group": g }),
619                None => json!({ "panel": kind, "instance": "new" }),
620            };
621            let label = strings::tr_args(&ctx, &txt::WORKBENCH_NEW_INSTANCE, &[("panel", &title)]);
622            (title, ListItem::new(&label, CMD_PANEL_OPEN, args))
623        })
624        .collect();
625    out.sort_by_key(|(title, _)| title.to_lowercase());
626    out.into_iter().map(|(_, item)| item).collect()
627}
628
629/// Docked: Move to each area (greyed where its rules keep it out), and
630/// Float when it may float; floating or detached: Dock back; floating:
631/// Dock in each side and the bottom (greyed where its rules keep it out).
632fn place_entries(app: &AppHandle, panel: &PanelId) -> Vec<ListItem> {
633    let Some(spec) = app.workbench_mut().spec(panel).cloned() else {
634        return Vec::new();
635    };
636    let ctx = app.egui();
637    let layout = app.workbench_mut().layout.clone();
638    if layout.area_of(panel).is_none() {
639        if layout.floating_of(panel).is_none() && layout.window_of(panel).is_none() {
640            return Vec::new();
641        }
642        let mut out = vec![ListItem::new(
643            &strings::tr(&ctx, &txt::WORKBENCH_DOCK_BACK),
644            CMD_PANEL_DOCK_BACK,
645            json!({ "panel": panel }),
646        )];
647        // Floating: Dock in each side and the bottom, the way to dock
648        // for a pointer whose drag cannot hold the dock keys.
649        if layout.floating_of(panel).is_some() {
650            out.extend(
651                [Area::StartSide, Area::EndSide, Area::Bottom]
652                    .into_iter()
653                    .map(|area| {
654                        let item = ListItem::new(
655                            &strings::tr_args(
656                                &ctx,
657                                &txt::WORKBENCH_DOCK_IN,
658                                &[("area", &area_text(&ctx, area))],
659                            ),
660                            CMD_PANEL_MOVE,
661                            json!({ "panel": panel, "area": area_name(area) }),
662                        );
663                        if spec.allows(area) {
664                            item
665                        } else {
666                            item.disabled()
667                        }
668                    }),
669            );
670        }
671        return out;
672    }
673    let mut out: Vec<ListItem> = Area::ALL
674        .into_iter()
675        .map(|area| {
676            let item = ListItem::new(
677                &strings::tr_args(
678                    &ctx,
679                    &txt::WORKBENCH_MOVE_TO,
680                    &[("area", &area_text(&ctx, area))],
681                ),
682                CMD_PANEL_MOVE,
683                json!({ "panel": panel, "area": area_name(area) }),
684            );
685            if spec.allows(area) {
686                item
687            } else {
688                item.disabled()
689            }
690        })
691        .collect();
692    out.push(float_entry(app, &ctx, panel, &spec));
693    out.extend(float_group_entry(app, panel));
694    out
695}
696
697/// Float, for a docked panel: greyed, saying why, when it may not float
698/// (its spec opts out, or the setting lets only palettes float).
699fn float_entry(
700    app: &AppHandle,
701    ctx: &egui::Context,
702    panel: &PanelId,
703    spec: &egui_pop_model::panels::PanelSpec,
704) -> ListItem {
705    let args = json!({ "panel": panel });
706    if spec
707        .refuses(&crate::mounts::panel_host(Place::Floating))
708        .is_some()
709    {
710        let title = app.panel_title(ctx, panel);
711        let label = strings::tr_args(ctx, &txt::WORKBENCH_FLOAT_REFUSED, &[("panel", &title)]);
712        return ListItem::new(&label, CMD_PANEL_FLOAT, args).disabled();
713    }
714    let scope = super::float_scope(app);
715    let narrowed = {
716        let mut wb = app.workbench_mut();
717        wb.float_scope = scope;
718        wb.float_refusal(spec).is_some()
719    };
720    if narrowed {
721        let label = strings::tr(ctx, &txt::WORKBENCH_FLOAT_PALETTES_ONLY);
722        return ListItem::new(&label, CMD_PANEL_FLOAT, args).disabled();
723    }
724    ListItem::new(
725        &strings::tr(ctx, &txt::WORKBENCH_FLOAT),
726        CMD_PANEL_FLOAT,
727        args,
728    )
729}
730
731/// Float group, for a panel docked in a tab group of several, when the
732/// group menu is allowed ([`GroupHandles::MENU`](super::GroupHandles)):
733/// greyed when one of its panels may not float.
734fn float_group_entry(app: &AppHandle, panel: &PanelId) -> Option<ListItem> {
735    if !super::group_handles(app).contains(super::GroupHandles::MENU) {
736        return None;
737    }
738    let scope = super::float_scope(app);
739    let floats = {
740        let mut wb = app.workbench_mut();
741        wb.layout.area_of(panel)?;
742        let (panels, _) = wb.layout.group_of(panel)?;
743        if panels.len() < 2 {
744            return None;
745        }
746        wb.float_scope = scope;
747        panels
748            .iter()
749            .all(|p| wb.spec(p).is_some_and(|s| wb.float_refusal(s).is_none()))
750    };
751    let item = ListItem::new(
752        &strings::tr(&app.egui(), &txt::WORKBENCH_FLOAT_GROUP),
753        CMD_PANEL_FLOAT,
754        json!({ "panel": panel, "group": true }),
755    );
756    Some(if floats { item } else { item.disabled() })
757}
758
759/// Detach into a window, for a panel that may go into one and is not
760/// alone in a window already.
761fn detach_entries(app: &AppHandle, panel: &PanelId) -> Vec<ListItem> {
762    let Some(spec) = app.workbench_mut().spec(panel).cloned() else {
763        return Vec::new();
764    };
765    let alone = app
766        .workbench_mut()
767        .layout
768        .window_of(panel)
769        .is_some_and(|a| a.tabs.is_empty());
770    if !spec.detachable || alone {
771        return Vec::new();
772    }
773    vec![ListItem::new(
774        &strings::tr(&app.egui(), &txt::WORKBENCH_DETACH),
775        CMD_PANEL_DETACH,
776        json!({ "panel": panel }),
777    )]
778}
779
780/// The detached windows a panel may join, by their panels' titles (the
781/// way into a window where a drag cannot reach it, `window_pointer`); for
782/// `group`, the windows its tab group may join whole, then a new window.
783fn window_entries(app: &AppHandle, panel: &PanelId, group: bool) -> Vec<ListItem> {
784    let ctx = app.egui();
785    let (windows, in_window) = {
786        let wb = app.workbench_mut();
787        let host = crate::mounts::panel_host(Place::Window);
788        let movable = if group {
789            wb.layout.floating_of(panel).is_none()
790                && wb.layout.group_of(panel).is_some_and(|(panels, _)| {
791                    panels.len() > 1
792                        && panels
793                            .iter()
794                            .all(|p| wb.spec(p).is_some_and(|s| s.refuses(&host).is_none()))
795                })
796        } else {
797            wb.spec(panel).is_some_and(|s| s.refuses(&host).is_none())
798        };
799        if !movable {
800            return Vec::new();
801        }
802        let windows: Vec<(PanelId, Vec<PanelId>)> = (wb.layout.auxiliary.iter())
803            .filter(|a| !a.holds(panel))
804            .map(|a| (a.panel.clone(), a.panels().cloned().collect()))
805            .collect();
806        (windows, wb.layout.window_of(panel).is_some())
807    };
808    let mut out: Vec<ListItem> = windows
809        .into_iter()
810        .map(|(window, panels)| {
811            let mut args = json!({ "panel": panel, "window": window });
812            if group {
813                args["group"] = json!(true);
814            }
815            ListItem::new(&titles(app, &ctx, &panels), super::CMD_MOVE_TO_WINDOW, args)
816        })
817        .collect();
818    // A group in a window is one already.
819    if group && !in_window {
820        out.push(ListItem::new(
821            &strings::tr(&ctx, &txt::WORKBENCH_NEW_WINDOW),
822            CMD_PANEL_DETACH,
823            json!({ "panel": panel, "group": true }),
824        ));
825    }
826    out
827}
828
829/// The docked tab groups a panel may join, by their panels' titles, in
830/// the areas' order (not its own group; greyed where its rules keep it
831/// out of the group's area).
832fn group_entries(app: &AppHandle, panel: &PanelId) -> Vec<ListItem> {
833    let ctx = app.egui();
834    let (groups, spec) = {
835        let wb = app.workbench_mut();
836        let Some(spec) = wb.spec(panel).cloned() else {
837            return Vec::new();
838        };
839        let mut groups: Vec<(Area, Vec<PanelId>)> = Vec::new();
840        for (area, node) in &wb.layout.areas {
841            for p in node.panels() {
842                if groups.iter().any(|(_, g)| g.contains(p)) {
843                    continue;
844                }
845                if let Some((panels, _)) = wb.layout.group_of(p)
846                    && !panels.contains(panel)
847                {
848                    groups.push((*area, panels));
849                }
850            }
851        }
852        (groups, spec)
853    };
854    groups
855        .into_iter()
856        .map(|(area, panels)| {
857            let host = crate::mounts::panel_host(Place::Area(area));
858            let item = ListItem::new(
859                &titles(app, &ctx, &panels),
860                CMD_PANEL_MOVE_TO_GROUP,
861                json!({ "panel": panel, "group": panels[0] }),
862            );
863            if spec.refuses(&host).is_none() {
864                item
865            } else {
866                item.disabled()
867            }
868        })
869        .collect()
870}
871
872/// Panels' titles, joined.
873fn titles(app: &AppHandle, ctx: &egui::Context, panels: &[PanelId]) -> String {
874    panels
875        .iter()
876        .map(|p| app.panel_title(ctx, p))
877        .collect::<Vec<_>>()
878        .join(", ")
879}