Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Text fields: a right-click menu with Cut, Copy, Paste and Select All (#8875) (#8882)

HiroKenEz561336aab631
diff --git a/assets/locales/pending/text-field-menu.json b/assets/locales/pending/text-field-menu.json
new file mode 100644
index 0000000000..b004d662da
--- /dev/null
+++ b/assets/locales/pending/text-field-menu.json
@@ -0,0 +1,20 @@
+{
+ "ar": { "ui.select_all": "تحديد الكل" },
+ "de": { "ui.select_all": "Alles auswählen" },
+ "en": { "ui.select_all": "Select All" },
+ "es": { "ui.select_all": "Seleccionar todo" },
+ "fr": { "ui.select_all": "Tout sélectionner" },
+ "he": { "ui.select_all": "בחירת הכול" },
+ "it": { "ui.select_all": "Seleziona tutto" },
+ "ja": { "ui.select_all": "すべて選択" },
+ "ko": { "ui.select_all": "모두 선택" },
+ "nl": { "ui.select_all": "Alles selecteren" },
+ "pl": { "ui.select_all": "Zaznacz wszystko" },
+ "pt-BR": { "ui.select_all": "Selecionar tudo" },
+ "ru": { "ui.select_all": "Выделить всё" },
+ "tr": { "ui.select_all": "Tümünü seç" },
+ "uk": { "ui.select_all": "Виділити все" },
+ "vi": { "ui.select_all": "Chọn tất cả" },
+ "zh": { "ui.select_all": "全选" },
+ "zh-TW": { "ui.select_all": "全選" }
+}
diff --git a/crates/ui-egui/src/expression_complete.rs b/crates/ui-egui/src/expression_complete.rs
index b759b93611..c8f7f7725b 100644
--- a/crates/ui-egui/src/expression_complete.rs
+++ b/crates/ui-egui/src/expression_complete.rs
@@ -121,6 +121,10 @@ pub(crate) fn showing(ctx: &egui::Context, editor: egui::Id) -> bool {
pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut String) -> bool {
let ctx = ui.ctx().clone();
+ // The field's right-click menu is open (#8875): the suggestions wait rather than cover it.
+ if ui_kit::text_menu_open(&ctx, resp.id) {
+ return false;
+ }
// A press on a suggestion takes the focus from the editor before the list can see it
// clicked, and the editor then gives up what was typed (#3257). The press picks the
// suggestion under it, and the editor gets its focus back below.
diff --git a/crates/ui-egui/src/ui_kit/assistant.rs b/crates/ui-egui/src/ui_kit/assistant.rs
index 4e14456a7f..e20a333c01 100644
--- a/crates/ui-egui/src/ui_kit/assistant.rs
+++ b/crates/ui-egui/src/ui_kit/assistant.rs
@@ -232,7 +232,7 @@ pub(crate) fn assistant_approval<R>(ui: &mut Ui, title: &str, body: impl FnOnce(
#[cfg(any(not(target_arch = "wasm32"), test))]
pub(crate) fn assistant_input(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -> Response {
let t = Tokens::get();
- ui.add(
+ let mut response = ui.add(
super::fields::text_input(egui::TextEdit::multiline(value))
.id(id)
.frame(egui::Frame::NONE)
@@ -242,7 +242,9 @@ pub(crate) fn assistant_input(ui: &mut Ui, id: egui::Id, value: &mut String, hin
.desired_width(f32::INFINITY)
.min_size(vec2(0.0, t.control_height + t.space_8))
.font(egui::FontId::proportional(t.font_label)),
- )
+ );
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINES);
+ response
}
/// Compact right-aligned approval actions; wrapping grows by control rows, not the remaining card height.
diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs
index 44dec19835..0ecf16e93a 100644
--- a/crates/ui-egui/src/ui_kit/fields.rs
+++ b/crates/ui-egui/src/ui_kit/fields.rs
@@ -136,7 +136,7 @@ pub(crate) fn focused_text_field(ui: &mut Ui, value: &mut String, hint: &str) ->
pub(crate) fn multiline_text_field(ui: &mut Ui, label: &str, id: egui::Id, value: &mut String) -> Response {
super::layout::sized_row(ui, label, row_height() * 3.0, |ui| {
let t = Tokens::get();
- let response = ui.add_sized(
+ let mut response = ui.add_sized(
vec2(dimension(ui.available_width()), row_height() * 3.0),
text_input(egui::TextEdit::multiline(value))
.id(id)
@@ -144,6 +144,7 @@ pub(crate) fn multiline_text_field(ui: &mut Ui, label: &str, id: egui::Id, value
.font(egui::FontId::monospace(t.font_label))
.background_color(t.input_fill()),
);
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINES);
publish(ui, &response, egui::WidgetType::TextEdit);
response
})
@@ -263,7 +264,8 @@ fn editor_reserving(ui: &mut Ui, value: &mut String, hint: &str, completion: boo
let inset = t.form_inset.round() as i8;
edit = edit.margin(egui::Margin { left: inset, right: inset.saturating_add(reserve.round() as i8), top: 0, bottom: 0 });
}
- let response = ui.add_sized(vec2(width, row_height()), edit);
+ let mut response = ui.add_sized(vec2(width, row_height()), edit);
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINE);
if completion && ui.is_enabled() {
ui.ctx().data_mut(|data| {
let id = egui::Id::new("sc_value_fields");
@@ -525,7 +527,8 @@ fn cell_editor_frame(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str,
} else {
editor.frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(t.space_8 as i8, 0)))
};
- let response = ui.add_sized(vec2(dimension(ui.available_width()), row_height()), editor);
+ let mut response = ui.add_sized(vec2(dimension(ui.available_width()), row_height()), editor);
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINE.limited(limit));
if frame {
publish(ui, &response, egui::WidgetType::TextEdit);
} else {
@@ -555,7 +558,8 @@ pub(crate) fn search_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint:
.margin(egui::Margin { left: t.space_24 as i8, right: t.space_8 as i8, top: 0, bottom: 0 })
.font(egui::FontId::proportional(t.font_small))
.text_color(t.form_ink);
- let response = ui.add_sized(vec2(dimension(ui.available_width()), t.space_16 + t.space_2), editor);
+ let mut response = ui.add_sized(vec2(dimension(ui.available_width()), t.space_16 + t.space_2), editor);
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINE.limited(128));
let icon = egui::Rect::from_center_size(egui::pos2(response.rect.left() + t.space_12, response.rect.center().y), vec2(t.space_12, t.space_12));
crate::icons::paint_ink(ui.painter(), icon, "zoom", t.form_dim);
super::layout::publish_geometry(ui, &response);
@@ -628,7 +632,11 @@ pub(crate) fn read_only_text(ui: &mut Ui, text: &str) -> Response {
let mut source = text;
egui::ScrollArea::vertical()
.max_height(160.0)
- .show(ui, |ui| ui.add(egui::TextEdit::multiline(&mut source).code_editor().desired_width(ui.available_width()).desired_rows(8)))
+ .show(ui, |ui| {
+ let mut response = ui.add(egui::TextEdit::multiline(&mut source).code_editor().desired_width(ui.available_width()).desired_rows(8));
+ super::text_menu::menu(ui, &mut response, &mut source, super::text_menu::Field::LINES);
+ response
+ })
.inner
}
@@ -807,7 +815,7 @@ pub(crate) fn angle_field(ui: &mut Ui, value: &mut f64) -> Response {
/// Tokens: control_height/fill, form_inset, font_label.
pub(crate) fn text_area(ui: &mut Ui, label: &str, id: egui::Id, value: &mut String, rows: usize, limit: usize) -> Response {
let t = Tokens::get();
- let response = ui.add_sized(
+ let mut response = ui.add_sized(
vec2(dimension(ui.available_width()), row_height() * rows.clamp(1, 16) as f32),
text_input(egui::TextEdit::multiline(value))
.id(id)
@@ -816,6 +824,7 @@ pub(crate) fn text_area(ui: &mut Ui, label: &str, id: egui::Id, value: &mut Stri
.font(egui::FontId::monospace(t.font_label))
.background_color(t.input_fill()),
);
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINES.limited(limit));
t.input_bevel(ui, &response);
response.widget_info(|| {
let mut info = egui::WidgetInfo::labeled(egui::WidgetType::TextEdit, ui.is_enabled(), label);
@@ -829,7 +838,7 @@ pub(crate) fn text_area(ui: &mut Ui, label: &str, id: egui::Id, value: &mut Stri
/// Tokens: cell_editor tokens.
pub(crate) fn password_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -> Response {
let t = Tokens::get();
- let response = ui.add_sized(
+ let mut response = ui.add_sized(
vec2(dimension(ui.available_width()), row_height()),
text_input(egui::TextEdit::singleline(value))
.id(id)
@@ -838,6 +847,7 @@ pub(crate) fn password_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint
.font(egui::FontId::monospace(t.font_label))
.background_color(t.input_fill()),
);
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field { secret: true, ..super::text_menu::Field::LINE });
publish(ui, &response, egui::WidgetType::TextEdit);
response
}
@@ -918,7 +928,7 @@ pub(crate) fn number_fields<T: egui::emath::Numeric>(
#[cfg(any(not(target_arch = "wasm32"), test))]
pub(crate) fn message_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -> Response {
let t = Tokens::get();
- let response = ui.add(
+ let mut response = ui.add(
text_input(egui::TextEdit::multiline(value))
.id(id)
.hint_text(hint)
@@ -927,6 +937,7 @@ pub(crate) fn message_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint:
.font(egui::FontId::proportional(t.font_label))
.background_color(t.input_fill()),
);
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINES);
t.input_bevel(ui, &response);
response
}
@@ -954,7 +965,8 @@ pub(crate) fn canvas_value_field(ui: &mut Ui, id: egui::Id, value: &mut String,
if keep_tab {
edit = edit.event_filter(egui::EventFilter { tab: true, horizontal_arrows: true, ..Default::default() });
}
- let response = ui.add(edit);
+ let mut response = ui.add(edit);
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINE);
t.input_bevel(ui, &response);
let field = (ui.ctx().cumulative_pass_nr(), response.id, value.chars().count());
ui.ctx().data_mut(|data| data.insert_temp(egui::Id::new("sc_canvas_value_focus"), field));
@@ -978,7 +990,7 @@ pub(crate) fn placement_field(ui: &mut Ui, id: egui::Id, value: &mut String, hin
// sketch picks. Keep the former line + space_2 above/below, with shared galley alignment.
let height = ui.fonts_mut(|fonts| fonts.row_height(&font)) + ui.spacing().extra_text_line_spacing + t.space_4;
let width = grown_width(ui, value, &font, t.control_height * 3.0 - t.space_6);
- let response = ui.add(
+ let mut response = ui.add(
text_input(egui::TextEdit::singleline(value))
.id(id)
.min_size(vec2(width, height))
@@ -990,6 +1002,7 @@ pub(crate) fn placement_field(ui: &mut Ui, id: egui::Id, value: &mut String, hin
.text_color(t.form_ink)
.clip_text(true),
);
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINE);
publish(ui, &response, egui::WidgetType::TextEdit);
response.widget_info(|| {
let mut info = egui::WidgetInfo::labeled(egui::WidgetType::TextEdit, ui.is_enabled(), crate::i18n::tr_label(hint));
@@ -1032,5 +1045,10 @@ pub(crate) fn library_cell(ui: &mut Ui, id: egui::Id, value: &mut String, hint:
/// Inline tree-name editor in caller-owned geometry; preserves its native focus and selection ID.
/// Tokens: text. The caller retains commit/cancel and select-all behavior.
pub(crate) fn inline_name(ui: &mut Ui, rect: egui::Rect, id: egui::Id, value: &mut String) -> Response {
- ui.put(rect, egui::TextEdit::singleline(value).id(id).frame(egui::Frame::NONE).text_color(Tokens::get().text).vertical_align(egui::Align::Center))
+ let mut response = ui.put(
+ rect,
+ egui::TextEdit::singleline(value).id(id).frame(egui::Frame::NONE).text_color(Tokens::get().text).vertical_align(egui::Align::Center),
+ );
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINE);
+ response
}
diff --git a/crates/ui-egui/src/ui_kit/fields_tests.rs b/crates/ui-egui/src/ui_kit/fields_tests.rs
index c3376ef071..4cc2e3814a 100644
--- a/crates/ui-egui/src/ui_kit/fields_tests.rs
+++ b/crates/ui-egui/src/ui_kit/fields_tests.rs
@@ -389,3 +389,279 @@ fn selection_field_has_three_distinct_looks_in_every_theme() {
crate::theme::set_custom(None);
crate::theme::set_dark(previous);
}
+
+// The text fields' right-click menu (#8875).
+
+use super::super::text_menu::{self, Edit, Field, State, TEST_CLIPBOARD};
+use std::cell::{Cell, RefCell};
+
+/// A frame of the kit harness that hands back its output (copied text, the menu's handles).
+fn menu_frame(ctx: &egui::Context, events: Vec<egui::Event>, mut add: impl FnMut(&mut Ui)) -> egui::FullOutput {
+ scenario::clear_handles();
+ let input = egui::RawInput {
+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 400.0))),
+ events,
+ focused: true,
+ ..Default::default()
+ };
+ crate::test_support::frame(ctx, input, |ui| {
+ ui.set_width(280.0);
+ scope(ui, &mut add);
+ })
+}
+
+fn right(pos: egui::Pos2, pressed: bool) -> Vec<egui::Event> {
+ vec![
+ egui::Event::PointerMoved(pos),
+ egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() },
+ ]
+}
+
+/// Right-click at `at`: the menu is open after it, laid out (a popup's first frame only sizes it).
+fn right_click(ctx: &egui::Context, at: egui::Pos2, add: &mut impl FnMut(&mut Ui)) {
+ menu_frame(ctx, right(at, true), &mut *add);
+ menu_frame(ctx, right(at, false), &mut *add);
+ menu_frame(ctx, vec![], &mut *add);
+}
+
+/// Click the menu row `row` (`text_paste`, ...); returns what the click put on the clipboard.
+fn pick(ctx: &egui::Context, row: &str, add: &mut impl FnMut(&mut Ui)) -> Vec<String> {
+ let at = scenario::handle_at(&format!("menu:{row}")).unwrap_or_else(|| panic!("the menu shows {row}"));
+ menu_frame(ctx, pointer(at, true), &mut *add);
+ let output = menu_frame(ctx, pointer(at, false), &mut *add);
+ let copied = output
+ .platform_output
+ .commands
+ .iter()
+ .filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t.clone()) } else { None })
+ .collect();
+ // One more frame: the field shows the focus the menu gave back.
+ menu_frame(ctx, vec![], &mut *add);
+ copied
+}
+
+fn select(ctx: &egui::Context, id: egui::Id, from: usize, to: usize) {
+ let mut state = egui::text_edit::TextEditState::load(ctx, id).unwrap_or_default();
+ state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(from), egui::text::CCursor::new(to))));
+ state.store(ctx, id);
+}
+
+fn selection(ctx: &egui::Context, id: egui::Id) -> Option<(usize, usize)> {
+ let range = egui::text_edit::TextEditState::load(ctx, id)?.cursor.char_range()?;
+ let [a, b] = range.sorted_cursors();
+ Some((a.index.0, b.index.0))
+}
+
+fn set_clipboard(text: Option<&str>) {
+ TEST_CLIPBOARD.with(|c| *c.borrow_mut() = text.map(str::to_owned));
+}
+
+#[test]
+fn a_right_click_on_every_kind_of_text_field_opens_its_menu() {
+ set_clipboard(None);
+ for case in ["expression", "plain", "cell", "placement", "canvas", "password", "multiline", "area", "message", "read-only", "inline"] {
+ let ctx = crate::fonts::test_context();
+ let value = RefCell::new("12 mm".to_owned());
+ let rect = Cell::new(egui::Rect::NOTHING);
+ let mut draw = |ui: &mut Ui| {
+ let id = ui.id().with(case);
+ let value = &mut *value.borrow_mut();
+ rect.set(match case {
+ "expression" | "plain" => super::editor(ui, value, "", case == "expression").2.rect,
+ "cell" => cell_editor(ui, id, value, "", false).rect,
+ "placement" => placement_field(ui, id, value, "").rect,
+ "canvas" => canvas_value_field(ui, id, value, false).rect,
+ "password" => password_field(ui, id, value, "").rect,
+ "multiline" => multiline_text_field(ui, "Text", id, value).rect,
+ "area" => text_area(ui, "Text", id, value, 3, 100).rect,
+ "message" => message_field(ui, id, value, "").rect,
+ "read-only" => read_only_text(ui, "12 mm").rect,
+ _ => inline_name(ui, egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(200.0, 22.0)), id, value).rect,
+ });
+ };
+ menu_frame(&ctx, vec![], &mut draw);
+ assert!(scenario::handle_at("menu:text_paste").is_none(), "{case}: no menu before the click");
+ right_click(&ctx, rect.get().center(), &mut draw);
+ for row in ["text_cut", "text_copy", "text_paste", "text_select_all"] {
+ assert!(scenario::handle_at(&format!("menu:{row}")).is_some(), "{case}: the menu shows {row}");
+ }
+ assert_eq!(*value.borrow(), "12 mm", "{case}: opening the menu changes nothing");
+ }
+}
+
+#[test]
+fn paste_inserts_at_the_cursor_and_replaces_the_selection() {
+ let ctx = crate::fonts::test_context();
+ let id = egui::Id::new("paste_dimension");
+ let value = RefCell::new("12 mm".to_owned());
+ let rect = Cell::new(egui::Rect::NOTHING);
+ let changed = Cell::new(false);
+ let mut draw = |ui: &mut Ui| {
+ let r = cell_editor(ui, id, &mut value.borrow_mut(), "", false);
+ rect.set(r.rect);
+ changed.set(changed.get() | r.changed());
+ };
+ menu_frame(&ctx, vec![], &mut draw);
+ menu_frame(&ctx, pointer(rect.get().center(), true), &mut draw);
+ menu_frame(&ctx, pointer(rect.get().center(), false), &mut draw);
+ assert!(ctx.memory(|m| m.has_focus(id)));
+ select(&ctx, id, 2, 2);
+ menu_frame(&ctx, vec![], &mut draw);
+ set_clipboard(Some("3"));
+ let end = egui::pos2(rect.get().right() - 2.0, rect.get().center().y);
+ right_click(&ctx, end, &mut draw);
+ // A right press moves the caret, as a left press does: to the end of the text here.
+ assert_eq!(selection(&ctx, id), Some((5, 5)));
+ select(&ctx, id, 2, 2);
+ assert!(pick(&ctx, "text_paste", &mut draw).is_empty(), "Paste copies nothing");
+ assert_eq!(*value.borrow(), "123 mm", "Paste inserts the clipboard's text at the caret");
+ assert!(changed.get(), "the caller sees the paste as a change");
+ assert_eq!(selection(&ctx, id), Some((3, 3)), "the caret follows the pasted text");
+ assert!(ctx.memory(|m| m.has_focus(id)), "the field keeps the focus, so it neither commits nor closes");
+
+ // Select all, then right-click inside the selection: it stays, and Paste replaces it.
+ right_click(&ctx, rect.get().center(), &mut draw);
+ pick(&ctx, "text_select_all", &mut draw);
+ assert_eq!(selection(&ctx, id), Some((0, 6)));
+ set_clipboard(Some("4 mm\r\n"));
+ right_click(&ctx, rect.get().center(), &mut draw);
+ assert_eq!(selection(&ctx, id), Some((0, 6)), "a right press inside the selection keeps it");
+ pick(&ctx, "text_paste", &mut draw);
+ assert_eq!(*value.borrow(), "4 mm ", "Paste replaces the selection; a single line takes line breaks as spaces");
+ set_clipboard(None);
+}
+
+#[test]
+fn copy_and_cut_put_the_selection_on_the_clipboard() {
+ set_clipboard(None);
+ let ctx = crate::fonts::test_context();
+ let id = egui::Id::new("copy_cut");
+ let value = RefCell::new("width + 2 mm".to_owned());
+ let rect = Cell::new(egui::Rect::NOTHING);
+ let mut draw = |ui: &mut Ui| rect.set(cell_editor(ui, id, &mut value.borrow_mut(), "", false).rect);
+ menu_frame(&ctx, vec![], &mut draw);
+ menu_frame(&ctx, pointer(rect.get().center(), true), &mut draw);
+ menu_frame(&ctx, pointer(rect.get().center(), false), &mut draw);
+ select(&ctx, id, 0, 12);
+ menu_frame(&ctx, vec![], &mut draw);
+ right_click(&ctx, rect.get().center(), &mut draw);
+ assert_eq!(pick(&ctx, "text_copy", &mut draw), ["width + 2 mm"]);
+ assert_eq!(*value.borrow(), "width + 2 mm", "Copy leaves the text");
+ select(&ctx, id, 0, 5);
+ menu_frame(&ctx, vec![], &mut draw);
+ // The press lands inside "width", the first characters at the field's left.
+ right_click(&ctx, egui::pos2(rect.get().left() + 12.0, rect.get().center().y), &mut draw);
+ assert_eq!(pick(&ctx, "text_cut", &mut draw), ["width"]);
+ assert_eq!(*value.borrow(), " + 2 mm", "Cut removes the selection");
+ assert_eq!(selection(&ctx, id), Some((0, 0)));
+}
+
+#[test]
+fn the_menu_offers_only_what_the_field_and_its_selection_allow() {
+ set_clipboard(Some("5"));
+ let ctx = crate::fonts::test_context();
+ let id = egui::Id::new("nothing_selected");
+ let value = RefCell::new("12".to_owned());
+ let rect = Cell::new(egui::Rect::NOTHING);
+ let mut draw = |ui: &mut Ui| rect.set(cell_editor(ui, id, &mut value.borrow_mut(), "", false).rect);
+ menu_frame(&ctx, vec![], &mut draw);
+ // No selection: Cut and Copy do nothing.
+ right_click(&ctx, rect.get().center(), &mut draw);
+ assert!(pick(&ctx, "text_copy", &mut draw).is_empty());
+ right_click(&ctx, rect.get().center(), &mut draw);
+ assert!(pick(&ctx, "text_cut", &mut draw).is_empty());
+ assert_eq!(*value.borrow(), "12");
+
+ // Read-only text: Paste leaves it as it is; Select All and Copy still work.
+ let ctx = crate::fonts::test_context();
+ let rect = Cell::new(egui::Rect::NOTHING);
+ let mut draw = |ui: &mut Ui| rect.set(read_only_text(ui, "report line").rect);
+ menu_frame(&ctx, vec![], &mut draw);
+ right_click(&ctx, rect.get().center(), &mut draw);
+ pick(&ctx, "text_paste", &mut draw);
+ right_click(&ctx, rect.get().center(), &mut draw);
+ pick(&ctx, "text_select_all", &mut draw);
+ right_click(&ctx, rect.get().center(), &mut draw);
+ assert_eq!(pick(&ctx, "text_copy", &mut draw), ["report line"]);
+ set_clipboard(None);
+
+ let on = |state: State| Edit::ALL.map(|e| text_menu::enabled(e, state));
+ let all = State { editable: true, selected: true, secret: false, pastable: true, text: true };
+ assert_eq!(on(all), [true; 4]);
+ assert_eq!(on(State { selected: false, ..all }), [false, false, true, true], "nothing selected");
+ assert_eq!(on(State { editable: false, ..all }), [false, true, false, true], "read-only or disabled");
+ assert_eq!(on(State { secret: true, ..all }), [false, false, true, true], "a password is never copied");
+ assert_eq!(on(State { pastable: false, ..all }), [true, true, false, true], "an empty clipboard");
+ assert_eq!(on(State::default()), [false; 4], "an empty read-only field");
+
+ // The edits themselves, on the buffer.
+ let mut text = "abcdef".to_owned();
+ let range = |a: usize, b: usize| Some(egui::text::CCursorRange::two(egui::text::CCursor::new(a), egui::text::CCursor::new(b)));
+ let done = text_menu::apply(&mut text, range(1, 3), Edit::Paste, Some("XYZ"), Field::LINE.limited(6));
+ assert_eq!((text.as_str(), done.changed), ("aXYdef", true), "Paste replaces the selection within the character limit");
+ let done = text_menu::apply(&mut text, range(40, 90), Edit::Cut, None, Field::LINE);
+ assert_eq!((text.as_str(), done.copied), ("aXYdef", None), "a stale selection past the end selects nothing");
+ let done = text_menu::apply(&mut text, range(0, 2), Edit::Copy, None, Field { secret: true, ..Field::LINE });
+ assert_eq!(done.copied, None, "a password is never copied");
+ let done = text_menu::apply(&mut text, None, Edit::Paste, Some("a\nb"), Field::LINES);
+ assert_eq!(text, "aXYdefa\nb", "without a caret Paste appends; a multiline field keeps line breaks");
+ assert!(done.changed);
+}
+
+#[test]
+fn a_right_click_on_a_value_box_over_the_canvas_does_not_reach_the_canvas() {
+ set_clipboard(None);
+ let ctx = crate::fonts::test_context();
+ let id = egui::Id::new("canvas_box");
+ let value = RefCell::new("20".to_owned());
+ let (field, canvas_menu) = (Cell::new(egui::Rect::NOTHING), Cell::new(false));
+ let mut draw = |ui: &mut Ui| {
+ // The viewport: a right-click on it opens its own menu.
+ let canvas = ui.allocate_rect(ui.max_rect(), egui::Sense::click_and_drag());
+ canvas_menu.set(canvas_menu.get() | canvas.secondary_clicked());
+ let ctx = ui.ctx().clone();
+ let area = Container::new(&ctx, Surface::Canvas).area(egui::Id::new("canvas_box_area"));
+ area.fixed_pos(egui::pos2(60.0, 60.0)).order(egui::Order::Foreground).show(&ctx, |ui| {
+ field.set(canvas_value_field(ui, id, &mut value.borrow_mut(), false).rect);
+ });
+ };
+ menu_frame(&ctx, vec![], &mut draw);
+ menu_frame(&ctx, vec![], &mut draw);
+ right_click(&ctx, field.get().center(), &mut draw);
+ assert!(scenario::handle_at("menu:text_paste").is_some(), "the value box's menu opens");
+ assert!(!canvas_menu.get(), "the canvas does not see the right-click");
+ menu_frame(&ctx, key(egui::Key::Escape), &mut draw);
+ menu_frame(&ctx, vec![], &mut draw);
+ right_click(&ctx, egui::pos2(250.0, 300.0), &mut draw);
+ assert!(canvas_menu.get(), "a right-click beside the box still reaches the canvas");
+ assert!(scenario::handle_at("menu:text_paste").is_none(), "and opens no text menu");
+}
+
+#[test]
+fn esc_closes_the_text_menu_alone() {
+ set_clipboard(None);
+ let ctx = crate::fonts::test_context();
+ let id = egui::Id::new("esc_dimension");
+ let value = RefCell::new("12".to_owned());
+ let (rect, owner_saw_esc, open) = (Cell::new(egui::Rect::NOTHING), Cell::new(false), Cell::new(false));
+ let mut draw = |ui: &mut Ui| {
+ rect.set(cell_editor(ui, id, &mut value.borrow_mut(), "", false).rect);
+ // What an expression field's completion asks, right after the field.
+ open.set(text_menu::menu_open(ui.ctx(), id));
+ // A sketch dimension's box cancels on Esc.
+ owner_saw_esc.set(owner_saw_esc.get() | ui.input(|i| i.key_pressed(egui::Key::Escape)));
+ };
+ menu_frame(&ctx, vec![], &mut draw);
+ menu_frame(&ctx, pointer(rect.get().center(), true), &mut draw);
+ menu_frame(&ctx, pointer(rect.get().center(), false), &mut draw);
+ right_click(&ctx, rect.get().center(), &mut draw);
+ assert!(open.get(), "an expression field's suggestions wait while the menu is open");
+ menu_frame(&ctx, key(egui::Key::Escape), &mut draw);
+ menu_frame(&ctx, vec![], &mut draw);
+ assert!(scenario::handle_at("menu:text_paste").is_none(), "Esc closes the menu");
+ assert!(!open.get(), "and the suggestions may show again");
+ assert!(!owner_saw_esc.get(), "the field's owner doesn't see the Esc that closed the menu");
+ assert!(ctx.memory(|m| m.has_focus(id)), "and the field keeps the focus");
+ menu_frame(&ctx, key(egui::Key::Escape), &mut draw);
+ assert!(owner_saw_esc.get(), "with the menu closed, Esc reaches the owner again");
+}
diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rs
index 6aa6179385..6a10498d16 100644
--- a/crates/ui-egui/src/ui_kit/mod.rs
+++ b/crates/ui-egui/src/ui_kit/mod.rs
@@ -39,6 +39,7 @@ mod stages;
mod status;
mod table;
mod text;
+mod text_menu;
mod tree;
mod value_focus;
mod viewport_status;
@@ -93,6 +94,7 @@ pub(crate) use sphere::{SphereTile, sphere_cursor, sphere_grid, sphere_grid_drag
pub(crate) use stages::{StageAction, StageBar};
pub(crate) use status::*;
pub(crate) use table::*;
+pub(crate) use text_menu::menu_open as text_menu_open;
pub(crate) use tree::*;
pub(crate) use value_focus::*;
pub(crate) use viewport_status::*;
diff --git a/crates/ui-egui/src/ui_kit/shortcuts.rs b/crates/ui-egui/src/ui_kit/shortcuts.rs
index 51d1e4b413..e4b27f96ba 100644
--- a/crates/ui-egui/src/ui_kit/shortcuts.rs
+++ b/crates/ui-egui/src/ui_kit/shortcuts.rs
@@ -79,7 +79,7 @@ fn search_with_icon(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -
let response = ui
.scope_builder(egui::UiBuilder::new().max_rect(editor), |ui| {
ui.set_clip_rect(ui.clip_rect().intersect(editor));
- ui.add_sized(
+ let mut response = ui.add_sized(
editor.size(),
super::fields::text_input(egui::TextEdit::singleline(value))
.id(id)
@@ -89,7 +89,9 @@ fn search_with_icon(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -
.margin(vec2(t.space_4, 0.0))
.clip_text(true)
.frame(egui::Frame::NONE),
- )
+ );
+ super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINE);
+ response
})
.inner;
let mut cleared = false;
diff --git a/crates/ui-egui/src/ui_kit/text_menu.rs b/crates/ui-egui/src/ui_kit/text_menu.rs
new file mode 100644
index 0000000000..db70ec644f
--- /dev/null
+++ b/crates/ui-egui/src/ui_kit/text_menu.rs
@@ -0,0 +1,287 @@
+//! The right-click menu of the kit's text fields (#8875): Cut, Copy, Paste and Select All, the
+//! edits Ctrl+X, Ctrl+C, Ctrl+V and Ctrl+A make, for the mouse, a pen or a touch screen.
+//!
+//! Every kit text field calls [`menu`] right after drawing its editor, with the text it edits, so
+//! the menu acts on that text in the same frame: the caller sees the change in `changed()` as if
+//! it were typed, and a field that commits when it loses focus (a sketch dimension, a rename)
+//! keeps it, because the menu gives the focus back. Paste goes through the text buffer's own
+//! insert with the field's character limit, and a single-line field turns line breaks into
+//! spaces, as the keyboard's paste does. A password is never copied.
+//!
+//! A right press moves egui's cursor to the press, as a left press does; a press inside the
+//! selection keeps the selection instead, so Copy and Cut take what was selected.
+//!
+//! The clipboard's text is read once, when the menu opens, to know whether Paste has anything to
+//! paste. The browser only hands its clipboard to a paste the user makes (Ctrl+V), so in the web
+//! app Paste stays disabled and the shortcut beside it says how.
+
+use egui::text::{CCursor, CCursorRange};
+use egui::text_edit::TextEditState;
+use egui::{Response, TextBuffer, Ui};
+
+/// What a field's menu may do with its text, besides what the buffer itself allows
+/// (`TextBuffer::is_mutable`: a read-only text offers Copy and Select All only).
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct Field {
+ /// A password: its text is never copied or cut.
+ pub secret: bool,
+ /// More than one line: a pasted line break stays a line break.
+ pub multiline: bool,
+ /// The most characters the field holds (`TextEdit::char_limit`).
+ pub limit: usize,
+}
+
+impl Field {
+ /// A single-line field without a character limit.
+ pub(crate) const LINE: Self = Self { secret: false, multiline: false, limit: usize::MAX };
+ /// A multiline field without a character limit.
+ pub(crate) const LINES: Self = Self { secret: false, multiline: true, limit: usize::MAX };
+
+ /// This field, holding at most `limit` characters.
+ pub(crate) const fn limited(self, limit: usize) -> Self {
+ Self { limit, ..self }
+ }
+}
+
+/// One entry of the menu.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Edit {
+ Cut,
+ Copy,
+ Paste,
+ SelectAll,
+}
+
+impl Edit {
+ pub(crate) const ALL: [Self; 4] = [Self::Cut, Self::Copy, Self::Paste, Self::SelectAll];
+
+ /// The menu row's id (`menu:<id>` in scenarios), message, icon and shortcut.
+ fn row(self) -> (&'static str, &'static str, &'static str, &'static str) {
+ match self {
+ Self::Cut => ("text_cut", "ui.cut", "cut", "Ctrl+X"),
+ Self::Copy => ("text_copy", "ui.copy", "copy", "Ctrl+C"),
+ Self::Paste => ("text_paste", "ui.paste", "paste", "Ctrl+V"),
+ Self::SelectAll => ("text_select_all", "ui.select_all", "", "Ctrl+A"),
+ }
+ }
+}
+
+/// What the field's state allows now.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(crate) struct State {
+ /// The text can change (not read-only, not disabled).
+ pub editable: bool,
+ /// Some characters are selected.
+ pub selected: bool,
+ /// The text is a password.
+ pub secret: bool,
+ /// The clipboard holds text to paste.
+ pub pastable: bool,
+ /// The field holds some text.
+ pub text: bool,
+}
+
+/// Whether `edit` can be chosen in a field in `state`.
+pub(crate) fn enabled(edit: Edit, state: State) -> bool {
+ match edit {
+ Edit::Cut => state.editable && state.selected && !state.secret,
+ Edit::Copy => state.selected && !state.secret,
+ Edit::Paste => state.editable && state.pastable,
+ Edit::SelectAll => state.text,
+ }
+}
+
+/// The result of an [`apply`]: the selection after it, the text for the clipboard, and whether
+/// the text changed.
+#[derive(Clone, Debug, PartialEq)]
+pub(crate) struct Done {
+ pub range: CCursorRange,
+ pub copied: Option<String>,
+ pub changed: bool,
+}
+
+/// `range` within a text of `len` characters: a stale selection never reaches past the end.
+fn clamp(range: CCursorRange, len: usize) -> CCursorRange {
+ let at = |c: CCursor| CCursor::new(c.index.0.min(len));
+ CCursorRange { primary: at(range.primary), secondary: at(range.secondary), h_pos: None }
+}
+
+/// Make `edit` on `text` with `range` selected (None: the caret at the end), pasting `clip`.
+/// Does nothing that [`enabled`] would refuse.
+pub(crate) fn apply(text: &mut dyn TextBuffer, range: Option<CCursorRange>, edit: Edit, clip: Option<&str>, field: Field) -> Done {
+ let len = text.as_str().chars().count();
+ let range = range.map_or_else(|| CCursorRange::one(CCursor::new(len)), |r| clamp(r, len));
+ let selected = !range.is_empty();
+ let copyable = selected && !field.secret;
+ let unchanged = |range, copied| Done { range, copied, changed: false };
+ match edit {
+ Edit::SelectAll => unchanged(CCursorRange::two(CCursor::new(0), CCursor::new(len)), None),
+ Edit::Copy => unchanged(range, copyable.then(|| range.slice_str(text.as_str()).to_owned())),
+ Edit::Cut if copyable && text.is_mutable() => {
+ let copied = range.slice_str(text.as_str()).to_owned();
+ let at = text.delete_selected(&range);
+ Done { range: CCursorRange::one(at), copied: Some(copied), changed: true }
+ }
+ Edit::Paste if text.is_mutable() => {
+ let Some(clip) = clip.filter(|c| !c.is_empty()) else { return unchanged(range, None) };
+ let before = text.as_str().to_owned();
+ let mut at = text.delete_selected(&range);
+ let line;
+ let insert = if field.multiline {
+ clip
+ } else {
+ line = clip.replace(['\r', '\n'], " ");
+ &line
+ };
+ text.insert_text_at(&mut at, insert, field.limit);
+ let changed = text.as_str() != before;
+ Done { range: CCursorRange::one(at), copied: None, changed }
+ }
+ Edit::Cut | Edit::Paste => unchanged(range, None),
+ }
+}
+
+/// The field's selection a frame ago, while it has focus.
+const LAST: &str = "sc_text_menu_last";
+/// The selection a right press landed in, kept while the button is down.
+const KEPT: &str = "sc_text_menu_kept";
+/// The clipboard's text, read when the menu opened.
+const CLIP: &str = "sc_text_menu_clip";
+/// The field whose menu is open, and the pass that drew it.
+const OPEN: &str = "sc_text_menu_open";
+
+/// Whether `field`'s menu is open (drawn this pass). An expression field's suggestions wait
+/// meanwhile, rather than cover the menu.
+pub(crate) fn menu_open(ctx: &egui::Context, field: egui::Id) -> bool {
+ let pass = ctx.cumulative_pass_nr();
+ ctx.data(|d| d.get_temp::<(egui::Id, u64)>(egui::Id::new(OPEN))).is_some_and(|(id, drawn)| id == field && drawn == pass)
+}
+
+#[cfg(test)]
+thread_local! {
+ /// What the tests' clipboard holds: tests never read the system clipboard.
+ pub(crate) static TEST_CLIPBOARD: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
+}
+
+/// The system clipboard's text, if it holds any.
+fn clipboard_text() -> Option<String> {
+ #[cfg(test)]
+ {
+ TEST_CLIPBOARD.with(|c| c.borrow().clone())
+ }
+ #[cfg(all(not(test), not(target_arch = "wasm32")))]
+ {
+ arboard::Clipboard::new().and_then(|mut c| c.get_text()).ok().filter(|t| !t.is_empty())
+ }
+ #[cfg(all(not(test), target_arch = "wasm32"))]
+ {
+ None
+ }
+}
+
+/// The field's selection now, after keeping the one a right press landed in.
+fn keep_selection(ui: &Ui, response: &Response, len: usize) -> Option<CCursorRange> {
+ let (ctx, id) = (ui.ctx(), response.id);
+ let mut state = TextEditState::load(ctx, id)?;
+ let now = state.cursor.char_range().map(|r| clamp(r, len));
+ let (pressed, down) = ui.input(|i| (i.pointer.button_pressed(egui::PointerButton::Secondary), i.pointer.secondary_down()));
+ let last = ctx.data(|d| d.get_temp::<CCursorRange>(id.with(LAST))).map(|r| clamp(r, len));
+ let mut kept = ctx.data(|d| d.get_temp::<CCursorRange>(id.with(KEPT)));
+ if pressed && response.contains_pointer() {
+ // The press put the caret where it landed; inside the selection, the selection stays.
+ let inside = |selection: &CCursorRange| {
+ let [min, max] = selection.sorted_cursors();
+ now.is_some_and(|n| (min.index..=max.index).contains(&n.primary.index))
+ };
+ kept = last.filter(|l| !l.is_empty() && inside(l));
+ }
+ if !down {
+ kept = None;
+ }
+ let range = match kept {
+ Some(keep) => {
+ state.cursor.set_char_range(Some(keep));
+ state.store(ctx, id);
+ Some(keep)
+ }
+ None => now,
+ };
+ // Read before `data_mut`: both lock the context's memory.
+ let focused = response.has_focus();
+ ctx.data_mut(|d| {
+ match kept {
+ Some(keep) => {
+ d.insert_temp(id.with(KEPT), keep);
+ }
+ None => d.remove::<CCursorRange>(id.with(KEPT)),
+ }
+ match range.filter(|_| focused) {
+ Some(range) => {
+ d.insert_temp(id.with(LAST), range);
+ }
+ None => d.remove::<CCursorRange>(id.with(LAST)),
+ }
+ });
+ range
+}
+
+/// The right-click menu of the text field `response` draws, editing `text`: call it right after
+/// adding the field's `TextEdit`. A change made from the menu marks `response` changed.
+pub(crate) fn menu(ui: &Ui, response: &mut Response, text: &mut dyn TextBuffer, field: Field) {
+ let id = response.id;
+ let len = text.as_str().chars().count();
+ let range = keep_selection(ui, response, len);
+ if response.secondary_clicked() {
+ let clip = clipboard_text();
+ ui.ctx().data_mut(|d| d.insert_temp(id.with(CLIP), clip));
+ }
+ let clip = || ui.ctx().data(|d| d.get_temp::<Option<String>>(id.with(CLIP))).flatten();
+ let state = State {
+ editable: text.is_mutable() && ui.is_enabled(),
+ selected: range.is_some_and(|r| !r.is_empty()),
+ secret: field.secret,
+ pastable: clip().is_some_and(|c| !c.is_empty()),
+ text: len > 0,
+ };
+ let mut picked = None;
+ let open = super::Menu::context(response, |ui| {
+ super::Menu::show(ui, crate::context_menu::LIST_W, |ui| {
+ for edit in Edit::ALL {
+ let (row, message, icon, key) = edit.row();
+ let shortcut = crate::keymap::display(key);
+ let mut item = super::MenuItem::new(row, crate::i18n::tr(message), icon);
+ item.shortcut = &shortcut;
+ item.enabled = enabled(edit, state);
+ if item.show(ui).clicked() && item.enabled {
+ picked = Some(edit);
+ ui.close();
+ }
+ }
+ });
+ })
+ .is_some();
+ if open {
+ let pass = ui.ctx().cumulative_pass_nr();
+ ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new(OPEN), (id, pass)));
+ }
+ if open && ui.ctx().input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
+ // Esc closes the menu alone: the field keeps its focus, and its owner (a dimension's box,
+ // a dialog) never sees the key that would cancel it.
+ ui.ctx().memory_mut(|m| m.request_focus(id));
+ }
+ let Some(edit) = picked else { return };
+ let done = apply(text, range, edit, clip().as_deref(), field);
+ let ctx = ui.ctx();
+ if let Some(copied) = done.copied {
+ ctx.copy_text(copied);
+ }
+ let mut state = TextEditState::load(ctx, id).unwrap_or_default();
+ state.cursor.set_char_range(Some(done.range));
+ state.store(ctx, id);
+ ctx.data_mut(|d| d.insert_temp(id.with(LAST), done.range));
+ // The menu's click took the focus: give it back, so the field neither commits nor closes.
+ ctx.memory_mut(|m| m.request_focus(id));
+ if done.changed {
+ response.mark_changed();
+ }
+}
diff --git a/docs/ui-kit.md b/docs/ui-kit.md
index 8f0fb555ad..1a59b8d3f7 100644
--- a/docs/ui-kit.md
+++ b/docs/ui-kit.md
@@ -121,6 +121,14 @@ rules. Its compass is 110 pt; the 48 pt Shots strip clears the docks by 8 pt.
including invalid and attached Library fields, without per-caller offsets.
Canvas placement editors retain their native line-height plus `space_4` hit
target so nearby sketch picks are not intercepted; alignment stays shared.
+- Every kit text field has one right-click menu, `text_menu::menu` (#8875): Cut,
+ Copy, Paste and Select All, disabled when there is nothing selected, the text is
+ read-only or a password, or the clipboard holds no text (always in the web app,
+ where Ctrl+V pastes). A kit helper calls it right after adding its `TextEdit`;
+ the edit marks the response changed and gives the focus back, so owners that
+ commit on lost focus keep the field. Filters inside menus and drop-downs have no
+ menu of their own. Rows publish `menu:text_cut`, `menu:text_copy`,
+ `menu:text_paste` and `menu:text_select_all`.
- Scenario handles and accessible labels are API. Consolidated options preserve
the former geometry, wrapping, native metadata and publication keys.