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, SELECT_ALL_SHORTCUT,
8 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 {
294 label: String,
295 shortcut: String,
296 message: Option<Message>,
297 },
298 Separator,
299}
300
301impl MenuEntry {
302 #[cfg(test)]
303 fn label(&self) -> Option<&str> {
304 match self {
305 Self::Item { label, .. } => Some(label),
306 Self::Separator => None,
307 }
308 }
309}
310
311fn custom_entries(entries: &[ContextMenuEntry]) -> Vec<MenuEntry> {
312 entries
313 .iter()
314 .map(|entry| match entry {
315 ContextMenuEntry::Item(item) => MenuEntry::Item {
316 label: item.label.clone(),
317 shortcut: item.shortcut.clone().unwrap_or_default(),
318 message: item.enabled.then(|| Message::CustomContextMenuAction(item.id.clone())),
319 },
320 ContextMenuEntry::Separator => MenuEntry::Separator,
321 })
322 .collect()
323}
324
325fn default_entries(context: ActionContext, translations: &Translations) -> Vec<MenuEntry> {
326 let mut entries = if context.reveal_in_file_manager_enabled {
327 vec![
328 MenuEntry::Item {
329 label: translations.context_menu_reveal_in_file_manager(),
330 shortcut: String::new(),
331 message: Some(Message::RevealInFileManager),
332 },
333 MenuEntry::Separator,
334 ]
335 } else {
336 Vec::new()
337 };
338 entries.extend([
339 MenuEntry::Item {
340 label: translations.context_menu_undo(),
341 shortcut: UNDO_SHORTCUT.to_string(),
342 message: context.can_undo.then_some(Message::Undo),
343 },
344 MenuEntry::Item {
345 label: translations.context_menu_redo(),
346 shortcut: REDO_SHORTCUT.to_string(),
347 message: context.can_redo.then_some(Message::Redo),
348 },
349 MenuEntry::Separator,
350 MenuEntry::Item {
351 label: translations.context_menu_cut(),
352 shortcut: CUT_SHORTCUT.to_string(),
353 message: context.has_selection.then_some(Message::Cut),
354 },
355 MenuEntry::Item {
356 label: translations.context_menu_copy(),
357 shortcut: COPY_SHORTCUT.to_string(),
358 message: context.has_selection.then_some(Message::Copy),
359 },
360 // Paste is always offered: whether the clipboard holds anything is
361 // only known once it has been read. The empty payload is what asks
362 // `CodeEditor::handle_paste_msg` to perform that read and send a
363 // second `Paste` carrying the result — it is not an empty paste.
364 MenuEntry::Item {
365 label: translations.context_menu_paste(),
366 shortcut: PASTE_SHORTCUT.to_string(),
367 message: Some(Message::Paste(String::new())),
368 },
369 MenuEntry::Separator,
370 MenuEntry::Item {
371 label: translations.context_menu_select_all(),
372 shortcut: SELECT_ALL_SHORTCUT.to_string(),
373 message: context.has_content.then_some(Message::SelectAll),
374 },
375 ]);
376 entries
377}
378
379fn build_entries(
380 custom: &[ContextMenuEntry],
381 default_context_menu_enabled: bool,
382 context: ActionContext,
383 translations: &Translations,
384) -> Vec<MenuEntry> {
385 let mut entries = custom_entries(custom);
386 if default_context_menu_enabled {
387 if !entries.is_empty() {
388 entries.push(MenuEntry::Separator);
389 }
390 entries.extend(default_entries(context, translations));
391 }
392 entries
393}
394
395/// Builds the context-menu contents.
396pub(crate) fn view(
397 custom: &[ContextMenuEntry],
398 default_context_menu_enabled: bool,
399 context: ActionContext,
400 translations: Translations,
401) -> Element<'static, Message> {
402 let items = build_entries(custom, default_context_menu_enabled, context, &translations)
403 .into_iter()
404 .map(|entry| match entry {
405 MenuEntry::Item {
406 label,
407 shortcut,
408 message,
409 } => menu_item(label, shortcut, message),
410 MenuEntry::Separator => separator(),
411 })
412 .collect::<Vec<_>>();
413
414 container(column(items).spacing(1).padding(4))
415 .width(Length::Fixed(MENU_WIDTH))
416 .style(|theme: &Theme| {
417 let palette = theme.extended_palette();
418 container::Style {
419 background: Some(Background::Color(palette.background.weak.color)),
420 text_color: Some(palette.background.weak.text),
421 border: Border {
422 color: palette.background.strong.color,
423 width: 1.0,
424 radius: 6.0.into(),
425 },
426 shadow: Shadow {
427 color: Color::BLACK.scale_alpha(0.35),
428 offset: Vector::new(0.0, 4.0),
429 blur_radius: 14.0,
430 },
431 ..container::Style::default()
432 }
433 })
434 .into()
435}
436
437fn menu_item(
438 label: String,
439 shortcut: String,
440 message: Option<Message>,
441) -> Element<'static, Message> {
442 let enabled = message.is_some();
443 let content = row![
444 text(label).size(13),
445 Space::new().width(Length::Fill),
446 text(shortcut).size(12),
447 ]
448 .align_y(iced::Alignment::Center);
449
450 button(content)
451 .width(Length::Fill)
452 .padding([6, 9])
453 .on_press_maybe(message)
454 .style(move |theme: &Theme, status| {
455 let palette = theme.extended_palette();
456 let text_color = if enabled {
457 palette.background.weak.text
458 } else {
459 palette.background.weak.text.scale_alpha(0.35)
460 };
461 let background = matches!(status, button::Status::Hovered | button::Status::Pressed)
462 .then_some(Background::Color(palette.background.strong.color));
463
464 button::Style {
465 background,
466 text_color,
467 border: Border {
468 radius: 4.0.into(),
469 ..Border::default()
470 },
471 ..button::Style::default()
472 }
473 })
474 .into()
475}
476
477fn separator() -> Element<'static, Message> {
478 let line = container(Space::new().width(Length::Fill).height(Length::Fixed(1.0))).style(
479 |theme: &Theme| {
480 let palette = theme.extended_palette();
481 container::Style {
482 background: Some(Background::Color(palette.background.strong.color)),
483 ..container::Style::default()
484 }
485 },
486 );
487
488 container(line).padding([3, 7]).into()
489}
490
491#[cfg(test)]
492mod tests {
493 use super::*;
494 use crate::{ContextMenuEntry, ContextMenuItem, Language, Translations};
495
496 #[test]
497 fn test_custom_context_menu_action_message_preserves_id() {
498 let entries = build_entries(
499 &[ContextMenuEntry::Item(ContextMenuItem::new(
500 "refactor.extract",
501 "Extract function",
502 ))],
503 false,
504 ActionContext::default(),
505 &Translations::default(),
506 );
507
508 assert!(matches!(
509 &entries[0],
510 MenuEntry::Item {
511 message: Some(Message::CustomContextMenuAction(id)),
512 ..
513 }
514 if id == "refactor.extract"
515 ));
516 }
517
518 #[test]
519 fn test_custom_entries_precede_default_entries() {
520 let entries = build_entries(
521 &[ContextMenuEntry::item("custom.format", "Format document")],
522 true,
523 ActionContext::default(),
524 &Translations::default(),
525 );
526
527 assert_eq!(entries[0].label(), Some("Format document"));
528 assert!(matches!(entries[1], MenuEntry::Separator));
529 assert_eq!(entries[2].label(), Some("Undo"));
530 }
531
532 #[test]
533 fn test_context_menu_uses_selected_language() {
534 let translations = Translations::new(Language::ChineseSimplified);
535 let entries = default_entries(ActionContext::default(), &translations);
536
537 assert_eq!(entries[0].label(), Some("撤消"));
538 assert_eq!(entries[1].label(), Some("恢复"));
539 assert_eq!(entries[3].label(), Some("剪切"));
540 assert_eq!(entries[4].label(), Some("复制"));
541 assert_eq!(entries[5].label(), Some("粘贴"));
542 assert_eq!(entries[7].label(), Some("选择全部"));
543
544 let custom = custom_entries(&[ContextMenuEntry::item("custom.format", "Format document")]);
545 assert_eq!(custom[0].label(), Some("Format document"));
546 }
547
548 #[test]
549 fn test_reveal_in_file_manager_entry_emits_request() {
550 let translations = Translations::new(Language::English);
551 let entries = build_entries(
552 &[],
553 true,
554 ActionContext {
555 reveal_in_file_manager_enabled: true,
556 ..ActionContext::default()
557 },
558 &translations,
559 );
560
561 assert!(matches!(
562 &entries[0],
563 MenuEntry::Item { label, shortcut, message }
564 if label == &translations.context_menu_reveal_in_file_manager()
565 && shortcut.is_empty()
566 && matches!(message, Some(Message::RevealInFileManager))
567 ));
568 assert!(matches!(entries[1], MenuEntry::Separator));
569 assert_eq!(entries[2].label(), Some("Undo"));
570 }
571
572 #[test]
573 fn test_reveal_in_file_manager_respects_default_menu_toggle() {
574 let entries = build_entries(
575 &[],
576 false,
577 ActionContext {
578 reveal_in_file_manager_enabled: true,
579 ..ActionContext::default()
580 },
581 &Translations::default(),
582 );
583
584 assert!(entries.is_empty());
585 }
586}