Skip to main content

iced_code_editor/canvas_editor/features/
context_menu.rs

1//! Right-click context menu for editor actions.
2
3use iced::widget::{Space, button, column, container, row, text};
4use iced::{Background, Border, Color, Element, Length, Shadow, Theme, Vector};
5
6use super::actions::{ActionContext, SharedAction};
7use crate::canvas_editor::Message;
8use crate::i18n::Translations;
9
10const MENU_WIDTH: f32 = 224.0;
11
12/// An actionable entry in the editor context menu.
13///
14/// The `id` is what the host receives when the item is selected, so it should
15/// be a stable identifier rather than the display text — renaming or
16/// translating a `label` then never breaks the action.
17///
18/// # Examples
19///
20/// ```
21/// use iced_code_editor::ContextMenuItem;
22///
23/// let item = ContextMenuItem::new("format", "Format Document")
24///     .with_shortcut("Ctrl+Shift+F");
25///
26/// assert_eq!(item.id, "format");
27/// assert_eq!(item.shortcut.as_deref(), Some("Ctrl+Shift+F"));
28/// assert!(item.enabled);
29/// ```
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct ContextMenuItem {
32    /// Stable action identifier emitted when the item is selected.
33    pub id: String,
34    /// Text displayed for the item.
35    pub label: String,
36    /// Optional keyboard shortcut hint displayed beside the label.
37    pub shortcut: Option<String>,
38    /// Whether the item can be selected.
39    pub enabled: bool,
40}
41
42impl ContextMenuItem {
43    /// Creates an enabled context-menu item without a shortcut hint.
44    ///
45    /// # Arguments
46    ///
47    /// * `id` - Stable action identifier emitted when the item is selected
48    /// * `label` - The text shown to the user
49    ///
50    /// # Returns
51    ///
52    /// An enabled item with no shortcut hint
53    ///
54    /// # Examples
55    ///
56    /// ```
57    /// use iced_code_editor::ContextMenuItem;
58    ///
59    /// let item = ContextMenuItem::new("rename", "Rename Symbol");
60    /// assert_eq!(item.label, "Rename Symbol");
61    /// assert!(item.shortcut.is_none());
62    /// assert!(item.enabled);
63    /// ```
64    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
65        Self {
66            id: id.into(),
67            label: label.into(),
68            shortcut: None,
69            enabled: true,
70        }
71    }
72
73    /// Sets the keyboard shortcut hint displayed beside this item.
74    ///
75    /// This is only a hint for the user: setting it does not bind the
76    /// shortcut, which the host application is responsible for handling.
77    ///
78    /// # Arguments
79    ///
80    /// * `shortcut` - The shortcut text to display, e.g. `Ctrl+Shift+F`
81    ///
82    /// # Returns
83    ///
84    /// Self for method chaining
85    ///
86    /// # Examples
87    ///
88    /// ```
89    /// use iced_code_editor::ContextMenuItem;
90    ///
91    /// let item = ContextMenuItem::new("format", "Format Document")
92    ///     .with_shortcut("Ctrl+Shift+F");
93    /// assert_eq!(item.shortcut.as_deref(), Some("Ctrl+Shift+F"));
94    /// ```
95    #[must_use]
96    pub fn with_shortcut(mut self, shortcut: impl Into<String>) -> Self {
97        self.shortcut = Some(shortcut.into());
98        self
99    }
100
101    /// Sets whether this item can be selected.
102    ///
103    /// A disabled item is still drawn, dimmed — use this for an action that is
104    /// unavailable right now but should stay visible so the menu does not
105    /// change shape between right-clicks.
106    ///
107    /// # Arguments
108    ///
109    /// * `enabled` - Whether the item can be selected
110    ///
111    /// # Returns
112    ///
113    /// Self for method chaining
114    ///
115    /// # Examples
116    ///
117    /// ```
118    /// use iced_code_editor::ContextMenuItem;
119    ///
120    /// let item = ContextMenuItem::new("rename", "Rename Symbol")
121    ///     .with_enabled(false);
122    /// assert!(!item.enabled);
123    /// ```
124    #[must_use]
125    pub fn with_enabled(mut self, enabled: bool) -> Self {
126        self.enabled = enabled;
127        self
128    }
129}
130
131/// A custom editor context-menu entry.
132///
133/// Pass a list of these to [`CodeEditor::set_custom_context_menu_entries`] to
134/// extend the menu, or to replace it entirely by also turning off the built-in
135/// actions with [`CodeEditor::set_default_context_menu_enabled`].
136///
137/// # Examples
138///
139/// ```
140/// use iced_code_editor::ContextMenuEntry;
141///
142/// let entries = vec![
143///     ContextMenuEntry::item("format", "Format Document")
144///         .with_shortcut("Ctrl+Shift+F"),
145///     ContextMenuEntry::separator(),
146///     ContextMenuEntry::item("rename", "Rename Symbol").with_enabled(false),
147/// ];
148/// assert_eq!(entries.len(), 3);
149/// ```
150///
151/// [`CodeEditor::set_custom_context_menu_entries`]: crate::CodeEditor::set_custom_context_menu_entries
152/// [`CodeEditor::set_default_context_menu_enabled`]: crate::CodeEditor::set_default_context_menu_enabled
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum ContextMenuEntry {
155    /// An actionable menu item.
156    Item(ContextMenuItem),
157    /// A visual separator between groups of items.
158    Separator,
159}
160
161impl ContextMenuEntry {
162    /// Creates an enabled action entry without a shortcut hint.
163    ///
164    /// Shorthand for wrapping [`ContextMenuItem::new`].
165    ///
166    /// # Arguments
167    ///
168    /// * `id` - Stable action identifier emitted when the entry is selected
169    /// * `label` - The text shown to the user
170    ///
171    /// # Returns
172    ///
173    /// An [`ContextMenuEntry::Item`] wrapping a new enabled item
174    ///
175    /// # Examples
176    ///
177    /// ```
178    /// use iced_code_editor::{ContextMenuEntry, ContextMenuItem};
179    ///
180    /// let entry = ContextMenuEntry::item("format", "Format Document");
181    /// assert_eq!(
182    ///     entry,
183    ///     ContextMenuEntry::Item(ContextMenuItem::new("format", "Format Document")),
184    /// );
185    /// ```
186    pub fn item(id: impl Into<String>, label: impl Into<String>) -> Self {
187        Self::Item(ContextMenuItem::new(id, label))
188    }
189
190    /// Creates a separator entry.
191    ///
192    /// # Returns
193    ///
194    /// A [`ContextMenuEntry::Separator`]
195    ///
196    /// # Examples
197    ///
198    /// ```
199    /// use iced_code_editor::ContextMenuEntry;
200    ///
201    /// assert_eq!(ContextMenuEntry::separator(), ContextMenuEntry::Separator);
202    /// ```
203    pub const fn separator() -> Self {
204        Self::Separator
205    }
206
207    /// Sets the keyboard shortcut hint when this is an action entry.
208    ///
209    /// A separator has no shortcut to set, so it is returned unchanged rather
210    /// than erroring — this keeps a chain of builder calls over a mixed list
211    /// of entries free of special cases.
212    ///
213    /// # Arguments
214    ///
215    /// * `shortcut` - The shortcut text to display, e.g. `Ctrl+Shift+F`
216    ///
217    /// # Returns
218    ///
219    /// Self for method chaining
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// use iced_code_editor::ContextMenuEntry;
225    ///
226    /// let entry = ContextMenuEntry::item("format", "Format Document")
227    ///     .with_shortcut("Ctrl+Shift+F");
228    /// assert!(matches!(entry, ContextMenuEntry::Item(_)));
229    ///
230    /// // A separator is unaffected.
231    /// let separator = ContextMenuEntry::separator().with_shortcut("Ctrl+K");
232    /// assert_eq!(separator, ContextMenuEntry::Separator);
233    /// ```
234    #[must_use]
235    pub fn with_shortcut(self, shortcut: impl Into<String>) -> Self {
236        match self {
237            Self::Item(item) => Self::Item(item.with_shortcut(shortcut)),
238            Self::Separator => Self::Separator,
239        }
240    }
241
242    /// Sets whether this entry can be selected when it is an action.
243    ///
244    /// A separator is returned unchanged, for the same reason as
245    /// [`Self::with_shortcut`].
246    ///
247    /// # Arguments
248    ///
249    /// * `enabled` - Whether the entry can be selected
250    ///
251    /// # Returns
252    ///
253    /// Self for method chaining
254    ///
255    /// # Examples
256    ///
257    /// ```
258    /// use iced_code_editor::{ContextMenuEntry, ContextMenuItem};
259    ///
260    /// let entry = ContextMenuEntry::item("rename", "Rename Symbol")
261    ///     .with_enabled(false);
262    /// assert_eq!(
263    ///     entry,
264    ///     ContextMenuEntry::Item(
265    ///         ContextMenuItem::new("rename", "Rename Symbol").with_enabled(false)
266    ///     ),
267    /// );
268    ///
269    /// // A separator is unaffected.
270    /// let separator = ContextMenuEntry::separator().with_enabled(false);
271    /// assert_eq!(separator, ContextMenuEntry::Separator);
272    /// ```
273    #[must_use]
274    pub fn with_enabled(self, enabled: bool) -> Self {
275        match self {
276            Self::Item(item) => Self::Item(item.with_enabled(enabled)),
277            Self::Separator => Self::Separator,
278        }
279    }
280}
281
282impl From<ContextMenuItem> for ContextMenuEntry {
283    fn from(item: ContextMenuItem) -> Self {
284        Self::Item(item)
285    }
286}
287
288#[derive(Debug, Clone)]
289enum MenuEntry {
290    Item { label: String, shortcut: String, message: Option<Message> },
291    Separator,
292}
293
294impl MenuEntry {
295    #[cfg(test)]
296    fn label(&self) -> Option<&str> {
297        match self {
298            Self::Item { label, .. } => Some(label),
299            Self::Separator => None,
300        }
301    }
302}
303
304fn custom_entries(entries: &[ContextMenuEntry]) -> Vec<MenuEntry> {
305    entries
306        .iter()
307        .map(|entry| match entry {
308            ContextMenuEntry::Item(item) => MenuEntry::Item {
309                label: item.label.clone(),
310                shortcut: item.shortcut.clone().unwrap_or_default(),
311                message: item
312                    .enabled
313                    .then(|| Message::CustomContextMenuAction(item.id.clone())),
314            },
315            ContextMenuEntry::Separator => MenuEntry::Separator,
316        })
317        .collect()
318}
319
320/// Builds the built-in half of the menu, in the order the menu shows it.
321///
322/// Every row's label, shortcut and message come from [`SharedAction`], which
323/// the command palette reads too; what belongs to the menu is the order, the
324/// separators, and the choice to *dim* an unavailable action rather than drop
325/// it. A menu with a fixed shape is what lets muscle memory work, so a row
326/// that cannot be run right now still holds its place.
327fn default_entries(
328    context: ActionContext,
329    translations: &Translations,
330) -> Vec<MenuEntry> {
331    /// Turns a shared action into a menu row, dimmed when unavailable.
332    fn row(
333        action: SharedAction,
334        context: ActionContext,
335        translations: &Translations,
336    ) -> MenuEntry {
337        MenuEntry::Item {
338            label: action.label(translations),
339            shortcut: action.shortcut().to_string(),
340            message: action.is_available(context).then(|| action.message()),
341        }
342    }
343
344    // Reveal sits above everything, separated: it acts on the file rather than
345    // on the text, and it is the only one the host can switch off entirely --
346    // so it is absent, not dimmed, when unavailable.
347    let mut entries = if SharedAction::RevealInFileManager.is_available(context)
348    {
349        vec![
350            row(SharedAction::RevealInFileManager, context, translations),
351            MenuEntry::Separator,
352        ]
353    } else {
354        Vec::new()
355    };
356
357    entries.extend([
358        row(SharedAction::Undo, context, translations),
359        row(SharedAction::Redo, context, translations),
360        MenuEntry::Separator,
361        row(SharedAction::Cut, context, translations),
362        row(SharedAction::Copy, context, translations),
363        row(SharedAction::Paste, context, translations),
364        MenuEntry::Separator,
365        row(SharedAction::SelectAll, context, translations),
366    ]);
367    entries
368}
369
370fn build_entries(
371    custom: &[ContextMenuEntry],
372    default_context_menu_enabled: bool,
373    context: ActionContext,
374    translations: &Translations,
375) -> Vec<MenuEntry> {
376    let mut entries = custom_entries(custom);
377    if default_context_menu_enabled {
378        if !entries.is_empty() {
379            entries.push(MenuEntry::Separator);
380        }
381        entries.extend(default_entries(context, translations));
382    }
383    entries
384}
385
386/// Builds the context-menu contents.
387pub(crate) fn view(
388    custom: &[ContextMenuEntry],
389    default_context_menu_enabled: bool,
390    context: ActionContext,
391    translations: Translations,
392) -> Element<'static, Message> {
393    let items = build_entries(
394        custom,
395        default_context_menu_enabled,
396        context,
397        &translations,
398    )
399    .into_iter()
400    .map(|entry| match entry {
401        MenuEntry::Item { label, shortcut, message } => {
402            menu_item(label, shortcut, message)
403        }
404        MenuEntry::Separator => separator(),
405    })
406    .collect::<Vec<_>>();
407
408    container(column(items).spacing(1).padding(4))
409        .width(Length::Fixed(MENU_WIDTH))
410        .style(|theme: &Theme| {
411            let palette = theme.extended_palette();
412            container::Style {
413                background: Some(Background::Color(
414                    palette.background.weak.color,
415                )),
416                text_color: Some(palette.background.weak.text),
417                border: Border {
418                    color: palette.background.strong.color,
419                    width: 1.0,
420                    radius: 6.0.into(),
421                },
422                shadow: Shadow {
423                    color: Color::BLACK.scale_alpha(0.35),
424                    offset: Vector::new(0.0, 4.0),
425                    blur_radius: 14.0,
426                },
427                ..container::Style::default()
428            }
429        })
430        .into()
431}
432
433fn menu_item(
434    label: String,
435    shortcut: String,
436    message: Option<Message>,
437) -> Element<'static, Message> {
438    let enabled = message.is_some();
439    let content = row![
440        text(label).size(13),
441        Space::new().width(Length::Fill),
442        text(shortcut).size(12),
443    ]
444    .align_y(iced::Alignment::Center);
445
446    button(content)
447        .width(Length::Fill)
448        .padding([6, 9])
449        .on_press_maybe(message)
450        .style(move |theme: &Theme, status| {
451            let palette = theme.extended_palette();
452            let text_color = if enabled {
453                palette.background.weak.text
454            } else {
455                palette.background.weak.text.scale_alpha(0.35)
456            };
457            let background = matches!(
458                status,
459                button::Status::Hovered | button::Status::Pressed
460            )
461            .then_some(Background::Color(palette.background.strong.color));
462
463            button::Style {
464                background,
465                text_color,
466                border: Border { radius: 4.0.into(), ..Border::default() },
467                ..button::Style::default()
468            }
469        })
470        .into()
471}
472
473fn separator() -> Element<'static, Message> {
474    let line =
475        container(Space::new().width(Length::Fill).height(Length::Fixed(1.0)))
476            .style(|theme: &Theme| {
477                let palette = theme.extended_palette();
478                container::Style {
479                    background: Some(Background::Color(
480                        palette.background.strong.color,
481                    )),
482                    ..container::Style::default()
483                }
484            });
485
486    container(line).padding([3, 7]).into()
487}
488
489#[cfg(test)]
490mod tests {
491    use super::*;
492    use crate::canvas_editor::CodeEditor;
493    use crate::canvas_editor::features::actions::SharedAction;
494    use crate::canvas_editor::features::command_palette::PaletteAction;
495    use crate::{ContextMenuEntry, ContextMenuItem, Language, Translations};
496
497    /// An editor in which every shared action is available, so both surfaces
498    /// offer all seven and the two lists can be compared row for row.
499    fn editor_with_everything_available() -> CodeEditor {
500        let mut editor = CodeEditor::new("hello", "rs");
501        editor.set_reveal_in_file_manager_enabled(true);
502        // Paste rather than type: typed characters stay in an open undo
503        // group, so nothing would be undoable yet. Two edits and one undo
504        // leaves both stacks non-empty at once, which is what makes Undo and
505        // Redo simultaneously available.
506        let _ = editor.update(&Message::Paste("a".to_string()));
507        let _ = editor.update(&Message::Paste("b".to_string()));
508        let _ = editor.update(&Message::Undo);
509        let _ = editor.update(&Message::SelectAll);
510
511        let context = editor.action_context();
512        assert!(context.can_undo && context.can_redo);
513        assert!(context.has_selection && context.has_content);
514        assert!(context.reveal_in_file_manager_enabled);
515
516        editor
517    }
518
519    // A missing row or a mismatched binding *is* the failure this test
520    // reports, so `panic!` is the report rather than a bug — the same reason
521    // the LSP protocol tests carry this allow.
522    #[test]
523    #[allow(clippy::panic)]
524    fn test_both_surfaces_render_every_shared_action_from_the_same_binding() {
525        // The drift this exists to prevent: the two surfaces used to spell out
526        // label / shortcut / message separately, so a relabelled action or a
527        // rebound key had to be edited in both, and nothing noticed when only
528        // one was. Reading them from `SharedAction` is what makes them equal;
529        // this walks all seven and checks that they really are.
530        let editor = editor_with_everything_available();
531        let translations = Translations::default();
532        let menu =
533            build_entries(&[], true, editor.action_context(), &translations);
534        let palette = editor.command_palette_entries();
535
536        for action in SharedAction::ALL {
537            let label = action.label(&translations);
538
539            let menu_row = menu
540                .iter()
541                .find_map(|entry| match entry {
542                    MenuEntry::Item { label: found, shortcut, message }
543                        if *found == label =>
544                    {
545                        Some((shortcut, message))
546                    }
547                    _ => None,
548                })
549                .unwrap_or_else(|| panic!("{label:?} missing from the menu"));
550
551            let palette_row = palette
552                .iter()
553                .find(|entry| entry.label == label)
554                .unwrap_or_else(|| {
555                    panic!("{label:?} missing from the palette")
556                });
557
558            assert_eq!(
559                menu_row.0, &palette_row.shortcut,
560                "{label:?}: the two surfaces show different shortcut hints"
561            );
562            assert_eq!(
563                menu_row.0,
564                action.shortcut(),
565                "{label:?}: neither matches `SharedAction::shortcut`"
566            );
567
568            // `Message` is not `PartialEq`; its `Debug` form is enough to tell
569            // two variants -- and two `Paste` payloads -- apart.
570            let expected = format!("{:?}", action.message());
571            assert_eq!(
572                menu_row.1.as_ref().map(|message| format!("{message:?}")),
573                Some(expected.clone()),
574                "{label:?}: the menu sends a different message"
575            );
576            let sent = match &palette_row.action {
577                PaletteAction::Builtin(message) => format!("{message:?}"),
578                other => panic!("{label:?} is not a built-in row: {other:?}"),
579            };
580            assert_eq!(
581                sent, expected,
582                "{label:?}: the palette sends a different message"
583            );
584        }
585    }
586
587    #[test]
588    fn test_an_unavailable_action_is_dimmed_in_the_menu_but_absent_from_the_palette()
589     {
590        // The one thing the two surfaces are *meant* to disagree on. A fresh
591        // editor has nothing to undo, and no file behind it to reveal.
592        let editor = CodeEditor::new("hello", "rs");
593        let translations = Translations::default();
594        let undo = SharedAction::Undo.label(&translations);
595        let reveal = SharedAction::RevealInFileManager.label(&translations);
596
597        let menu =
598            build_entries(&[], true, editor.action_context(), &translations);
599        let palette = editor.command_palette_entries();
600
601        assert!(
602            menu.iter().any(|entry| matches!(
603                entry,
604                MenuEntry::Item { label, message: None, .. } if *label == undo
605            )),
606            "the menu keeps Undo in place, dimmed"
607        );
608        assert!(
609            !palette.iter().any(|entry| entry.label == undo),
610            "the palette drops Undo entirely"
611        );
612
613        // Reveal is the exception: the host switched it off, so it is absent
614        // from both rather than dimmed in one.
615        assert!(!menu.iter().any(|entry| entry.label() == Some(&reveal)));
616        assert!(!palette.iter().any(|entry| entry.label == reveal));
617    }
618
619    #[test]
620    fn test_custom_context_menu_action_message_preserves_id() {
621        let entries = build_entries(
622            &[ContextMenuEntry::Item(ContextMenuItem::new(
623                "refactor.extract",
624                "Extract function",
625            ))],
626            false,
627            ActionContext::default(),
628            &Translations::default(),
629        );
630
631        assert!(matches!(
632            &entries[0],
633            MenuEntry::Item {
634                message: Some(Message::CustomContextMenuAction(id)),
635                ..
636            }
637                if id == "refactor.extract"
638        ));
639    }
640
641    #[test]
642    fn test_custom_entries_precede_default_entries() {
643        let entries = build_entries(
644            &[ContextMenuEntry::item("custom.format", "Format document")],
645            true,
646            ActionContext::default(),
647            &Translations::default(),
648        );
649
650        assert_eq!(entries[0].label(), Some("Format document"));
651        assert!(matches!(entries[1], MenuEntry::Separator));
652        assert_eq!(entries[2].label(), Some("Undo"));
653    }
654
655    #[test]
656    fn test_context_menu_uses_selected_language() {
657        let translations = Translations::new(Language::ChineseSimplified);
658        let entries = default_entries(ActionContext::default(), &translations);
659
660        assert_eq!(entries[0].label(), Some("撤消"));
661        assert_eq!(entries[1].label(), Some("恢复"));
662        assert_eq!(entries[3].label(), Some("剪切"));
663        assert_eq!(entries[4].label(), Some("复制"));
664        assert_eq!(entries[5].label(), Some("粘贴"));
665        assert_eq!(entries[7].label(), Some("选择全部"));
666
667        let custom = custom_entries(&[ContextMenuEntry::item(
668            "custom.format",
669            "Format document",
670        )]);
671        assert_eq!(custom[0].label(), Some("Format document"));
672    }
673
674    #[test]
675    fn test_reveal_in_file_manager_entry_emits_request() {
676        let translations = Translations::new(Language::English);
677        let entries = build_entries(
678            &[],
679            true,
680            ActionContext {
681                reveal_in_file_manager_enabled: true,
682                ..ActionContext::default()
683            },
684            &translations,
685        );
686
687        assert!(matches!(
688            &entries[0],
689            MenuEntry::Item { label, shortcut, message }
690                if label == &translations.context_menu_reveal_in_file_manager()
691                    && shortcut.is_empty()
692                    && matches!(message, Some(Message::RevealInFileManager))
693        ));
694        assert!(matches!(entries[1], MenuEntry::Separator));
695        assert_eq!(entries[2].label(), Some("Undo"));
696    }
697
698    #[test]
699    fn test_reveal_in_file_manager_respects_default_menu_toggle() {
700        let entries = build_entries(
701            &[],
702            false,
703            ActionContext {
704                reveal_in_file_manager_enabled: true,
705                ..ActionContext::default()
706            },
707            &Translations::default(),
708        );
709
710        assert!(entries.is_empty());
711    }
712}