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 crate::canvas_editor::Message;
7use crate::i18n::Translations;
8
9const MENU_WIDTH: f32 = 224.0;
10
11/// An actionable entry in the editor context menu.
12///
13/// The `id` is what the host receives when the item is selected, so it should
14/// be a stable identifier rather than the display text — renaming or
15/// translating a `label` then never breaks the action.
16///
17/// # Examples
18///
19/// ```
20/// use iced_code_editor::ContextMenuItem;
21///
22/// let item = ContextMenuItem::new("format", "Format Document")
23///     .with_shortcut("Ctrl+Shift+F");
24///
25/// assert_eq!(item.id, "format");
26/// assert_eq!(item.shortcut.as_deref(), Some("Ctrl+Shift+F"));
27/// assert!(item.enabled);
28/// ```
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ContextMenuItem {
31    /// Stable action identifier emitted when the item is selected.
32    pub id: String,
33    /// Text displayed for the item.
34    pub label: String,
35    /// Optional keyboard shortcut hint displayed beside the label.
36    pub shortcut: Option<String>,
37    /// Whether the item can be selected.
38    pub enabled: bool,
39}
40
41impl ContextMenuItem {
42    /// Creates an enabled context-menu item without a shortcut hint.
43    ///
44    /// # Arguments
45    ///
46    /// * `id` - Stable action identifier emitted when the item is selected
47    /// * `label` - The text shown to the user
48    ///
49    /// # Returns
50    ///
51    /// An enabled item with no shortcut hint
52    ///
53    /// # Examples
54    ///
55    /// ```
56    /// use iced_code_editor::ContextMenuItem;
57    ///
58    /// let item = ContextMenuItem::new("rename", "Rename Symbol");
59    /// assert_eq!(item.label, "Rename Symbol");
60    /// assert!(item.shortcut.is_none());
61    /// assert!(item.enabled);
62    /// ```
63    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
64        Self {
65            id: id.into(),
66            label: label.into(),
67            shortcut: None,
68            enabled: true,
69        }
70    }
71
72    /// Sets the keyboard shortcut hint displayed beside this item.
73    ///
74    /// This is only a hint for the user: setting it does not bind the
75    /// shortcut, which the host application is responsible for handling.
76    ///
77    /// # Arguments
78    ///
79    /// * `shortcut` - The shortcut text to display, e.g. `Ctrl+Shift+F`
80    ///
81    /// # Returns
82    ///
83    /// Self for method chaining
84    ///
85    /// # Examples
86    ///
87    /// ```
88    /// use iced_code_editor::ContextMenuItem;
89    ///
90    /// let item = ContextMenuItem::new("format", "Format Document")
91    ///     .with_shortcut("Ctrl+Shift+F");
92    /// assert_eq!(item.shortcut.as_deref(), Some("Ctrl+Shift+F"));
93    /// ```
94    #[must_use]
95    pub fn with_shortcut(mut self, shortcut: impl Into<String>) -> Self {
96        self.shortcut = Some(shortcut.into());
97        self
98    }
99
100    /// Sets whether this item can be selected.
101    ///
102    /// A disabled item is still drawn, dimmed — use this for an action that is
103    /// unavailable right now but should stay visible so the menu does not
104    /// change shape between right-clicks.
105    ///
106    /// # Arguments
107    ///
108    /// * `enabled` - Whether the item can be selected
109    ///
110    /// # Returns
111    ///
112    /// Self for method chaining
113    ///
114    /// # Examples
115    ///
116    /// ```
117    /// use iced_code_editor::ContextMenuItem;
118    ///
119    /// let item = ContextMenuItem::new("rename", "Rename Symbol")
120    ///     .with_enabled(false);
121    /// assert!(!item.enabled);
122    /// ```
123    #[must_use]
124    pub fn with_enabled(mut self, enabled: bool) -> Self {
125        self.enabled = enabled;
126        self
127    }
128}
129
130/// A custom editor context-menu entry.
131///
132/// Pass a list of these to [`CodeEditor::set_custom_context_menu_entries`] to
133/// extend the menu, or to replace it entirely by also turning off the built-in
134/// actions with [`CodeEditor::set_default_context_menu_enabled`].
135///
136/// # Examples
137///
138/// ```
139/// use iced_code_editor::ContextMenuEntry;
140///
141/// let entries = vec![
142///     ContextMenuEntry::item("format", "Format Document")
143///         .with_shortcut("Ctrl+Shift+F"),
144///     ContextMenuEntry::separator(),
145///     ContextMenuEntry::item("rename", "Rename Symbol").with_enabled(false),
146/// ];
147/// assert_eq!(entries.len(), 3);
148/// ```
149///
150/// [`CodeEditor::set_custom_context_menu_entries`]: crate::CodeEditor::set_custom_context_menu_entries
151/// [`CodeEditor::set_default_context_menu_enabled`]: crate::CodeEditor::set_default_context_menu_enabled
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub enum ContextMenuEntry {
154    /// An actionable menu item.
155    Item(ContextMenuItem),
156    /// A visual separator between groups of items.
157    Separator,
158}
159
160impl ContextMenuEntry {
161    /// Creates an enabled action entry without a shortcut hint.
162    ///
163    /// Shorthand for wrapping [`ContextMenuItem::new`].
164    ///
165    /// # Arguments
166    ///
167    /// * `id` - Stable action identifier emitted when the entry is selected
168    /// * `label` - The text shown to the user
169    ///
170    /// # Returns
171    ///
172    /// An [`ContextMenuEntry::Item`] wrapping a new enabled item
173    ///
174    /// # Examples
175    ///
176    /// ```
177    /// use iced_code_editor::{ContextMenuEntry, ContextMenuItem};
178    ///
179    /// let entry = ContextMenuEntry::item("format", "Format Document");
180    /// assert_eq!(
181    ///     entry,
182    ///     ContextMenuEntry::Item(ContextMenuItem::new("format", "Format Document")),
183    /// );
184    /// ```
185    pub fn item(id: impl Into<String>, label: impl Into<String>) -> Self {
186        Self::Item(ContextMenuItem::new(id, label))
187    }
188
189    /// Creates a separator entry.
190    ///
191    /// # Returns
192    ///
193    /// A [`ContextMenuEntry::Separator`]
194    ///
195    /// # Examples
196    ///
197    /// ```
198    /// use iced_code_editor::ContextMenuEntry;
199    ///
200    /// assert_eq!(ContextMenuEntry::separator(), ContextMenuEntry::Separator);
201    /// ```
202    pub const fn separator() -> Self {
203        Self::Separator
204    }
205
206    /// Sets the keyboard shortcut hint when this is an action entry.
207    ///
208    /// A separator has no shortcut to set, so it is returned unchanged rather
209    /// than erroring — this keeps a chain of builder calls over a mixed list
210    /// of entries free of special cases.
211    ///
212    /// # Arguments
213    ///
214    /// * `shortcut` - The shortcut text to display, e.g. `Ctrl+Shift+F`
215    ///
216    /// # Returns
217    ///
218    /// Self for method chaining
219    ///
220    /// # Examples
221    ///
222    /// ```
223    /// use iced_code_editor::ContextMenuEntry;
224    ///
225    /// let entry = ContextMenuEntry::item("format", "Format Document")
226    ///     .with_shortcut("Ctrl+Shift+F");
227    /// assert!(matches!(entry, ContextMenuEntry::Item(_)));
228    ///
229    /// // A separator is unaffected.
230    /// let separator = ContextMenuEntry::separator().with_shortcut("Ctrl+K");
231    /// assert_eq!(separator, ContextMenuEntry::Separator);
232    /// ```
233    #[must_use]
234    pub fn with_shortcut(self, shortcut: impl Into<String>) -> Self {
235        match self {
236            Self::Item(item) => Self::Item(item.with_shortcut(shortcut)),
237            Self::Separator => Self::Separator,
238        }
239    }
240
241    /// Sets whether this entry can be selected when it is an action.
242    ///
243    /// A separator is returned unchanged, for the same reason as
244    /// [`Self::with_shortcut`].
245    ///
246    /// # Arguments
247    ///
248    /// * `enabled` - Whether the entry can be selected
249    ///
250    /// # Returns
251    ///
252    /// Self for method chaining
253    ///
254    /// # Examples
255    ///
256    /// ```
257    /// use iced_code_editor::{ContextMenuEntry, ContextMenuItem};
258    ///
259    /// let entry = ContextMenuEntry::item("rename", "Rename Symbol")
260    ///     .with_enabled(false);
261    /// assert_eq!(
262    ///     entry,
263    ///     ContextMenuEntry::Item(
264    ///         ContextMenuItem::new("rename", "Rename Symbol").with_enabled(false)
265    ///     ),
266    /// );
267    ///
268    /// // A separator is unaffected.
269    /// let separator = ContextMenuEntry::separator().with_enabled(false);
270    /// assert_eq!(separator, ContextMenuEntry::Separator);
271    /// ```
272    #[must_use]
273    pub fn with_enabled(self, enabled: bool) -> Self {
274        match self {
275            Self::Item(item) => Self::Item(item.with_enabled(enabled)),
276            Self::Separator => Self::Separator,
277        }
278    }
279}
280
281impl From<ContextMenuItem> for ContextMenuEntry {
282    fn from(item: ContextMenuItem) -> Self {
283        Self::Item(item)
284    }
285}
286
287#[cfg(target_os = "macos")]
288const UNDO_SHORTCUT: &str = "⌘Z";
289#[cfg(not(target_os = "macos"))]
290const UNDO_SHORTCUT: &str = "Ctrl+Z";
291
292#[cfg(target_os = "macos")]
293const REDO_SHORTCUT: &str = "⇧⌘Z";
294#[cfg(not(target_os = "macos"))]
295const REDO_SHORTCUT: &str = "Ctrl+Y";
296
297#[cfg(target_os = "macos")]
298const CUT_SHORTCUT: &str = "⌘X";
299#[cfg(not(target_os = "macos"))]
300const CUT_SHORTCUT: &str = "Ctrl+X";
301
302#[cfg(target_os = "macos")]
303const COPY_SHORTCUT: &str = "⌘C";
304#[cfg(not(target_os = "macos"))]
305const COPY_SHORTCUT: &str = "Ctrl+C";
306
307#[cfg(target_os = "macos")]
308const PASTE_SHORTCUT: &str = "⌘V";
309#[cfg(not(target_os = "macos"))]
310const PASTE_SHORTCUT: &str = "Ctrl+V";
311
312#[cfg(target_os = "macos")]
313const SELECT_ALL_SHORTCUT: &str = "⌘A";
314#[cfg(not(target_os = "macos"))]
315const SELECT_ALL_SHORTCUT: &str = "Ctrl+A";
316
317#[derive(Debug, Clone, Copy, Default)]
318pub(crate) struct MenuState {
319    pub(crate) can_undo: bool,
320    pub(crate) can_redo: bool,
321    pub(crate) has_selection: bool,
322    pub(crate) has_content: bool,
323    pub(crate) reveal_in_file_manager_enabled: bool,
324}
325
326#[derive(Debug, Clone)]
327enum MenuEntry {
328    Item { label: String, shortcut: String, message: Option<Message> },
329    Separator,
330}
331
332impl MenuEntry {
333    #[cfg(test)]
334    fn label(&self) -> Option<&str> {
335        match self {
336            Self::Item { label, .. } => Some(label),
337            Self::Separator => None,
338        }
339    }
340}
341
342fn custom_entries(entries: &[ContextMenuEntry]) -> Vec<MenuEntry> {
343    entries
344        .iter()
345        .map(|entry| match entry {
346            ContextMenuEntry::Item(item) => MenuEntry::Item {
347                label: item.label.clone(),
348                shortcut: item.shortcut.clone().unwrap_or_default(),
349                message: item
350                    .enabled
351                    .then(|| Message::CustomContextMenuAction(item.id.clone())),
352            },
353            ContextMenuEntry::Separator => MenuEntry::Separator,
354        })
355        .collect()
356}
357
358fn default_entries(
359    state: MenuState,
360    translations: &Translations,
361) -> Vec<MenuEntry> {
362    let mut entries = if state.reveal_in_file_manager_enabled {
363        vec![
364            MenuEntry::Item {
365                label: translations.context_menu_reveal_in_file_manager(),
366                shortcut: String::new(),
367                message: Some(Message::RevealInFileManager),
368            },
369            MenuEntry::Separator,
370        ]
371    } else {
372        Vec::new()
373    };
374    entries.extend([
375        MenuEntry::Item {
376            label: translations.context_menu_undo(),
377            shortcut: UNDO_SHORTCUT.to_string(),
378            message: state.can_undo.then_some(Message::Undo),
379        },
380        MenuEntry::Item {
381            label: translations.context_menu_redo(),
382            shortcut: REDO_SHORTCUT.to_string(),
383            message: state.can_redo.then_some(Message::Redo),
384        },
385        MenuEntry::Separator,
386        MenuEntry::Item {
387            label: translations.context_menu_cut(),
388            shortcut: CUT_SHORTCUT.to_string(),
389            message: state.has_selection.then_some(Message::Cut),
390        },
391        MenuEntry::Item {
392            label: translations.context_menu_copy(),
393            shortcut: COPY_SHORTCUT.to_string(),
394            message: state.has_selection.then_some(Message::Copy),
395        },
396        MenuEntry::Item {
397            label: translations.context_menu_paste(),
398            shortcut: PASTE_SHORTCUT.to_string(),
399            message: Some(Message::Paste(String::new())),
400        },
401        MenuEntry::Separator,
402        MenuEntry::Item {
403            label: translations.context_menu_select_all(),
404            shortcut: SELECT_ALL_SHORTCUT.to_string(),
405            message: state.has_content.then_some(Message::SelectAll),
406        },
407    ]);
408    entries
409}
410
411fn build_entries(
412    custom: &[ContextMenuEntry],
413    default_context_menu_enabled: bool,
414    state: MenuState,
415    translations: &Translations,
416) -> Vec<MenuEntry> {
417    let mut entries = custom_entries(custom);
418    if default_context_menu_enabled {
419        if !entries.is_empty() {
420            entries.push(MenuEntry::Separator);
421        }
422        entries.extend(default_entries(state, translations));
423    }
424    entries
425}
426
427/// Builds the context-menu contents.
428pub(crate) fn view(
429    custom: &[ContextMenuEntry],
430    default_context_menu_enabled: bool,
431    state: MenuState,
432    translations: Translations,
433) -> Element<'static, Message> {
434    let items = build_entries(
435        custom,
436        default_context_menu_enabled,
437        state,
438        &translations,
439    )
440    .into_iter()
441    .map(|entry| match entry {
442        MenuEntry::Item { label, shortcut, message } => {
443            menu_item(label, shortcut, message)
444        }
445        MenuEntry::Separator => separator(),
446    })
447    .collect::<Vec<_>>();
448
449    container(column(items).spacing(1).padding(4))
450        .width(Length::Fixed(MENU_WIDTH))
451        .style(|theme: &Theme| {
452            let palette = theme.extended_palette();
453            container::Style {
454                background: Some(Background::Color(
455                    palette.background.weak.color,
456                )),
457                text_color: Some(palette.background.weak.text),
458                border: Border {
459                    color: palette.background.strong.color,
460                    width: 1.0,
461                    radius: 6.0.into(),
462                },
463                shadow: Shadow {
464                    color: Color::BLACK.scale_alpha(0.35),
465                    offset: Vector::new(0.0, 4.0),
466                    blur_radius: 14.0,
467                },
468                ..container::Style::default()
469            }
470        })
471        .into()
472}
473
474fn menu_item(
475    label: String,
476    shortcut: String,
477    message: Option<Message>,
478) -> Element<'static, Message> {
479    let enabled = message.is_some();
480    let content = row![
481        text(label).size(13),
482        Space::new().width(Length::Fill),
483        text(shortcut).size(12),
484    ]
485    .align_y(iced::Alignment::Center);
486
487    button(content)
488        .width(Length::Fill)
489        .padding([6, 9])
490        .on_press_maybe(message)
491        .style(move |theme: &Theme, status| {
492            let palette = theme.extended_palette();
493            let text_color = if enabled {
494                palette.background.weak.text
495            } else {
496                palette.background.weak.text.scale_alpha(0.35)
497            };
498            let background = matches!(
499                status,
500                button::Status::Hovered | button::Status::Pressed
501            )
502            .then_some(Background::Color(palette.background.strong.color));
503
504            button::Style {
505                background,
506                text_color,
507                border: Border { radius: 4.0.into(), ..Border::default() },
508                ..button::Style::default()
509            }
510        })
511        .into()
512}
513
514fn separator() -> Element<'static, Message> {
515    let line =
516        container(Space::new().width(Length::Fill).height(Length::Fixed(1.0)))
517            .style(|theme: &Theme| {
518                let palette = theme.extended_palette();
519                container::Style {
520                    background: Some(Background::Color(
521                        palette.background.strong.color,
522                    )),
523                    ..container::Style::default()
524                }
525            });
526
527    container(line).padding([3, 7]).into()
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533    use crate::{ContextMenuEntry, ContextMenuItem, Language, Translations};
534
535    #[test]
536    fn test_custom_context_menu_action_message_preserves_id() {
537        let entries = build_entries(
538            &[ContextMenuEntry::Item(ContextMenuItem::new(
539                "refactor.extract",
540                "Extract function",
541            ))],
542            false,
543            MenuState::default(),
544            &Translations::default(),
545        );
546
547        assert!(matches!(
548            &entries[0],
549            MenuEntry::Item {
550                message: Some(Message::CustomContextMenuAction(id)),
551                ..
552            }
553                if id == "refactor.extract"
554        ));
555    }
556
557    #[test]
558    fn test_custom_entries_precede_default_entries() {
559        let entries = build_entries(
560            &[ContextMenuEntry::item("custom.format", "Format document")],
561            true,
562            MenuState::default(),
563            &Translations::default(),
564        );
565
566        assert_eq!(entries[0].label(), Some("Format document"));
567        assert!(matches!(entries[1], MenuEntry::Separator));
568        assert_eq!(entries[2].label(), Some("Undo"));
569    }
570
571    #[test]
572    fn test_context_menu_uses_selected_language() {
573        let translations = Translations::new(Language::ChineseSimplified);
574        let entries = default_entries(MenuState::default(), &translations);
575
576        assert_eq!(entries[0].label(), Some("撤消"));
577        assert_eq!(entries[1].label(), Some("恢复"));
578        assert_eq!(entries[3].label(), Some("剪切"));
579        assert_eq!(entries[4].label(), Some("复制"));
580        assert_eq!(entries[5].label(), Some("粘贴"));
581        assert_eq!(entries[7].label(), Some("选择全部"));
582
583        let custom = custom_entries(&[ContextMenuEntry::item(
584            "custom.format",
585            "Format document",
586        )]);
587        assert_eq!(custom[0].label(), Some("Format document"));
588    }
589
590    #[test]
591    fn test_reveal_in_file_manager_entry_emits_request() {
592        let translations = Translations::new(Language::English);
593        let entries = build_entries(
594            &[],
595            true,
596            MenuState {
597                reveal_in_file_manager_enabled: true,
598                ..MenuState::default()
599            },
600            &translations,
601        );
602
603        assert!(matches!(
604            &entries[0],
605            MenuEntry::Item { label, shortcut, message }
606                if label == &translations.context_menu_reveal_in_file_manager()
607                    && shortcut.is_empty()
608                    && matches!(message, Some(Message::RevealInFileManager))
609        ));
610        assert!(matches!(entries[1], MenuEntry::Separator));
611        assert_eq!(entries[2].label(), Some("Undo"));
612    }
613
614    #[test]
615    fn test_reveal_in_file_manager_respects_default_menu_toggle() {
616        let entries = build_entries(
617            &[],
618            false,
619            MenuState {
620                reveal_in_file_manager_enabled: true,
621                ..MenuState::default()
622            },
623            &Translations::default(),
624        );
625
626        assert!(entries.is_empty());
627    }
628}