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