Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge #281 (d5c1755): UI: share viewport-aware scrolling across menus

aiongg7108d3e77de6
diff --cc crates/ui-egui/src/chrome.rs
index 2a52134b7,1aeb879f9..09a578e10
--- a/crates/ui-egui/src/chrome.rs
+++ b/crates/ui-egui/src/chrome.rs
@@@ -21,105 -21,96 +21,120 @@@ pub fn app_bar(app: &mut DesignApp, ui
let full = ui.max_rect();
let mut menus_end = full.min.x;
let mut tools_start = full.max.x;
- ui.horizontal_centered(|ui| {
- if icons::button(ui, "home", 24.0, app.session.active().is_none(), crate::i18n::tr(&app.ui.language, "Home")).clicked() {
- app.session_home();
- }
- ui.add_space(6.0);
- if !app.native_menu {
- ui.style_mut().visuals.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT;
- ui.style_mut().visuals.widgets.inactive.bg_stroke = Stroke::NONE;
- ui.style_mut().visuals.widgets.hovered.bg_stroke = Stroke::NONE;
- ui.style_mut().spacing.button_padding = vec2(7.0, 3.0);
- crate::menus::menu_bar(app, ui);
- }
- menus_end = ui.min_rect().max.x;
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- ui.add_space(4.0);
- // Search field.
- let (r, _) = ui.allocate_exact_size(vec2(125.0, 18.0), Sense::click());
- ui.painter().rect(r, 1.0, t.input, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
- icons::paint(ui.painter(), egui::Rect::from_min_size(r.min + vec2(3.0, 2.0), vec2(14.0, 14.0)), "search", t.icon);
- crate::rtl::paint(
- ui.painter(),
- r.min + vec2(20.0, 9.0),
- egui::Align2::LEFT_CENTER,
- crate::i18n::tr(&app.ui.language, "Search"),
- egui::FontId::proportional(11.0),
- t.text_dim,
- );
- ui.add_space(8.0);
- let current = app.ui.workspace.clone();
- let shown = crate::i18n::workspace_name(&app.ui.language, &current);
- crate::menus::menu_button(
- ui,
- crate::rtl::widget(ui, egui::RichText::new(format!("{shown} ▾")).font(semibold(11.5)).color(t.text)),
- |ui| {
- let customs: Vec<String> = app.ui.custom_workspaces.iter().map(|w| w.name.clone()).collect();
- for w in
- ["Essentials", "Advanced", "Book", "Digital Publishing", "Interactive for PDF", "Printing and Proofing", "Typography"]
- .into_iter()
- .map(str::to_string)
- .chain(customs.iter().cloned())
- {
+ // The right-hand controls' width, measured last frame: in a window too narrow for them
+ // and the menus they follow the menus, and the bar scrolls sideways.
+ let tools_w_id = ui.id().with("tools_width");
+ let tools_w: f32 = ui.data(|d| d.get_temp(tools_w_id)).unwrap_or(0.0);
+ crate::widgets::overflow_scrolling(ui);
+ egui::ScrollArea::horizontal().id_salt("app_bar_scroll").auto_shrink([false, false]).show(ui, |ui| {
+ ui.horizontal_centered(|ui| {
+ if icons::button(ui, "home", 24.0, app.session.active().is_none(), crate::i18n::tr(&app.ui.language, "Home")).clicked() {
+ app.session_home();
+ }
+ ui.add_space(6.0);
+ if !app.native_menu {
+ ui.style_mut().visuals.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT;
+ ui.style_mut().visuals.widgets.inactive.bg_stroke = Stroke::NONE;
+ ui.style_mut().visuals.widgets.hovered.bg_stroke = Stroke::NONE;
+ ui.style_mut().spacing.button_padding = vec2(7.0, 3.0);
+ crate::menus::menu_bar(app, ui);
+ }
+ menus_end = ui.min_rect().max.x;
+ let size = vec2(ui.available_width().max(tools_w), ui.available_height());
+ let tools = ui.allocate_ui_with_layout(size, egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ ui.add_space(4.0);
+ // Search field.
+ let (r, _) = ui.allocate_exact_size(vec2(125.0, 18.0), Sense::click());
+ ui.painter().rect(r, 1.0, t.input, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
+ icons::paint(ui.painter(), egui::Rect::from_min_size(r.min + vec2(3.0, 2.0), vec2(14.0, 14.0)), "search", t.icon);
+ crate::rtl::paint(
+ ui.painter(),
+ r.min + vec2(20.0, 9.0),
+ egui::Align2::LEFT_CENTER,
+ crate::i18n::tr(&app.ui.language, "Search"),
+ egui::FontId::proportional(11.0),
+ t.text_dim,
+ );
+ ui.add_space(8.0);
+ let current = app.ui.workspace.clone();
+ let shown = crate::i18n::workspace_name(&app.ui.language, &current);
- ui.menu_button(crate::rtl::widget(ui, egui::RichText::new(format!("{shown} ▾")).font(semibold(11.5)).color(t.text)), |ui| {
- let customs: Vec<String> = app.ui.custom_workspaces.iter().map(|w| w.name.clone()).collect();
- for w in
- ["Essentials", "Advanced", "Book", "Digital Publishing", "Interactive for PDF", "Printing and Proofing", "Typography"]
- .into_iter()
- .map(str::to_string)
- .chain(customs.iter().cloned())
- {
++ crate::menus::menu_button(
++ ui,
++ crate::rtl::widget(ui, egui::RichText::new(format!("{shown} ▾")).font(semibold(11.5)).color(t.text)),
++ |ui| {
++ let customs: Vec<String> = app.ui.custom_workspaces.iter().map(|w| w.name.clone()).collect();
++ for w in [
++ "Essentials",
++ "Advanced",
++ "Book",
++ "Digital Publishing",
++ "Interactive for PDF",
++ "Printing and Proofing",
++ "Typography",
++ ]
++ .into_iter()
++ .map(str::to_string)
++ .chain(customs.iter().cloned())
++ {
++ if ui
++ .selectable_label(w == current, crate::rtl::widget(ui, crate::i18n::workspace_name(&app.ui.language, &w)))
++ .clicked()
++ {
++ let _ = app.run("window.workspace", json!({"name": w}));
++ ui.close();
++ }
++ }
++ ui.separator();
if ui
-- .selectable_label(w == current, crate::rtl::widget(ui, crate::i18n::workspace_name(&app.ui.language, &w)))
++ .button(crate::rtl::widget(
++ ui,
++ format!(
++ "{} {}",
++ crate::i18n::tr(&app.ui.language, "Reset"),
++ crate::i18n::workspace_name(&app.ui.language, &current)
++ ),
++ ))
.clicked()
{
-- let _ = app.run("window.workspace", json!({"name": w}));
++ let _ = app.run("window.resetWorkspace", json!({}));
ui.close();
}
-- }
-- ui.separator();
-- if ui
-- .button(crate::rtl::widget(
-- ui,
-- format!(
-- "{} {}",
-- crate::i18n::tr(&app.ui.language, "Reset"),
-- crate::i18n::workspace_name(&app.ui.language, &current)
-- ),
-- ))
-- .clicked()
-- {
-- let _ = app.run("window.resetWorkspace", json!({}));
-- ui.close();
-- }
-- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "New Workspace…"))).clicked() {
-- let _ = app.run("window.newWorkspace", json!({}));
-- ui.close();
-- }
-- if !customs.is_empty() {
- ui.menu_button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Delete Workspace")), |ui| {
- crate::menus::menu_button(ui, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Delete Workspace")), |ui| {
-- for w in &customs {
-- if ui.button(w).clicked() {
-- let _ = app.run("window.deleteWorkspace", json!({"name": w}));
-- ui.close();
-- }
-- }
-- });
-- }
- });
- },
- );
- ui.add_space(6.0);
- if icons::button(ui, "share", 22.0, false, crate::i18n::tr(&app.ui.language, "Share")).clicked() {
- app.status("Export a PDF, IDML or package to share — no cloud account needed.");
- }
- ui.add_space(8.0);
- // Always one click away: the ArtCraft community Discord.
- if crate::about::discord_button(ui, "Discord", vec2(78.0, 22.0)) {
- let _ = app.run("help.discord", json!({}));
++ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "New Workspace…"))).clicked() {
++ let _ = app.run("window.newWorkspace", json!({}));
++ ui.close();
++ }
++ if !customs.is_empty() {
++ crate::menus::menu_button(
++ ui,
++ crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Delete Workspace")),
++ |ui| {
++ for w in &customs {
++ if ui.button(w).clicked() {
++ let _ = app.run("window.deleteWorkspace", json!({"name": w}));
++ ui.close();
++ }
++ }
++ },
++ );
++ }
++ },
++ );
+ ui.add_space(6.0);
+ if icons::button(ui, "share", 22.0, false, crate::i18n::tr(&app.ui.language, "Share")).clicked() {
+ app.status("Export a PDF, IDML or package to share — no cloud account needed.");
+ }
+ ui.add_space(8.0);
+ // Always one click away: the ArtCraft community Discord.
+ if crate::about::discord_button(ui, "Discord", vec2(78.0, 22.0)) {
+ let _ = app.run("help.discord", json!({}));
+ }
+ tools_start = ui.min_rect().min.x;
+ ui.min_rect().width()
+ });
+ if (tools.inner - tools_w).abs() > 0.5 {
+ ui.data_mut(|d| d.insert_temp(tools_w_id, tools.inner));
+ ui.ctx().request_discard("app bar: the right-hand controls changed width");
}
- tools_start = ui.min_rect().min.x;
});
});
// Centred title.
diff --cc crates/ui-egui/src/menus.rs
index dba47e1cc,f95fcb83e..5be6f5625
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@@ -1846,86 -1743,59 +1846,97 @@@ pub fn activate(app: &mut DesignApp, id
let _ = app.run(id, p);
}
+/// A native menu bar item was chosen (macOS): like [`activate`], except that the menu bar takes
+/// ⌘A, ⌘C, ⌘X, ⌘V, ⌘Z and ⇧⌘Z before the window sees them, so while a text field has keyboard
+/// focus, Select All, Copy, Cut, Paste, Undo and Redo act on that field, as in any Mac app.
+pub fn activate_native(app: &mut DesignApp, ctx: &egui::Context, id: &str, params: &Value) {
+ if !(ctx.text_edit_focused() && params.is_null() && forward_to_text_field(app, ctx, id)) {
+ activate(app, id, params);
+ }
+}
+
+/// Whether a native menu bar item can be chosen: as in the in-window menus, but the editing
+/// commands a focused text field takes are always available to it.
+pub fn native_menu_enabled(app: &DesignApp, ctx: &egui::Context, id: &str) -> bool {
+ (ctx.text_edit_focused() && TEXT_FIELD_COMMANDS.contains(&id)) || menu_enabled(app, id)
+}
+
+/// The editing commands a focused text field takes from the native menu bar.
+const TEXT_FIELD_COMMANDS: [&str; 6] = ["edit.selectAll", "edit.copy", "edit.cut", "edit.paste", "edit.undo", "edit.redo"];
+
+/// Hand a standard editing command to the focused text field as next frame's input; false when
+/// `id` isn't one of them.
+fn forward_to_text_field(app: &mut DesignApp, ctx: &egui::Context, id: &str) -> bool {
+ let key = |key: egui::Key, modifiers: egui::Modifiers| {
+ [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers })
+ };
+ match id {
+ "edit.selectAll" => app.synthetic.extend(key(egui::Key::A, egui::Modifiers::COMMAND)),
+ "edit.undo" => app.synthetic.extend(key(egui::Key::Z, egui::Modifiers::COMMAND)),
+ "edit.redo" => app.synthetic.extend(key(egui::Key::Z, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT)),
+ "edit.copy" => app.synthetic.push(egui::Event::Copy),
+ "edit.cut" => app.synthetic.push(egui::Event::Cut),
+ // Only the integration reads the system clipboard: it answers with an `Event::Paste`.
+ "edit.paste" => ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste),
+ _ => return false,
+ }
+ ctx.request_repaint();
+ true
+}
+
- /// The menu bar contents (inside the app bar; macOS uses the native menu instead).
- pub fn menu_bar(app: &mut DesignApp, ui: &mut egui::Ui) {
- let lang = app.ui.language.clone();
- let mut menus = menu_tree();
- if crate::i18n::is_rtl(&lang) {
- menus.reverse();
- }
- for (menu, entries) in menus {
- egui::containers::menu::MenuButton::new(crate::rtl::widget(ui, crate::i18n::tr(&lang, menu)))
- .config(egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside))
- .ui(ui, |ui| {
- if crate::i18n::is_rtl(&lang) {
- ui.set_max_width(320.0);
- }
- scroll_menu(ui, |ui| {
- ui.with_layout(
- egui::Layout::top_down_justified(if crate::i18n::is_rtl(&lang) { egui::Align::Max } else { egui::Align::Min }),
- |ui| {
- ui.set_min_width(240.0);
- let hidden = menu_items(app, ui, &entries, menu);
- if hidden > 0 && !app.ui.show_full_menus {
- ui.separator();
- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&lang, "Show All Menu Items"))).clicked() {
- app.ui.show_full_menus = true;
- }
- }
- },
- );
- });
- });
- }
+ /// A menu button whose popup stays within the viewport and scrolls when needed.
+ /// All menu buttons share this wrapper, including workspace, zoom and panel menus.
+ pub fn menu_button<'a, R>(
+ ui: &mut egui::Ui,
+ atoms: impl egui::IntoAtoms<'a>,
+ add_contents: impl FnOnce(&mut egui::Ui) -> R,
+ ) -> egui::InnerResponse<Option<R>> {
+ use egui::containers::menu::{MenuButton, MenuConfig};
+
+ // A menu opens from a button already shown in the previous frame. Base its height on
+ // that anchor, not the popup's eventual position, so placement cannot oscillate.
+ let button = ui.ctx().read_response(ui.next_auto_id()).map(|response| response.rect);
+ let max_height = menu_max_height(ui, button);
+ let contents = |ui: &mut egui::Ui| {
+ // Override the popup's initial available height, including when it opens upwards.
+ ui.set_max_height(max_height);
+ let mut scroll = egui::ScrollArea::vertical().max_height(max_height).min_scrolled_height(1.0);
+ if ui.is_sizing_pass() {
+ // Closing and reopening a menu starts at its first command again.
+ scroll = scroll.vertical_scroll_offset(0.0);
+ }
+ scroll.show(ui, add_contents).inner
+ };
+ // Scrollbar clicks must not dismiss the popup; command rows close it explicitly.
+ let config = MenuConfig::find(ui).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside);
+ let (response, inner) = if egui::containers::menu::is_in_menu(ui) {
+ clipped_submenu(ui, atoms, config, contents)
+ } else {
+ MenuButton::new(atoms).config(config).ui(ui, contents)
+ };
+ egui::InnerResponse { response, inner: inner.map(|response| response.inner) }
}
- /// Keep every command reachable when the viewport is short or the UI is enlarged.
- fn scroll_menu<R>(ui: &mut egui::Ui, contents: impl FnOnce(&mut egui::Ui) -> R) -> R {
- let frame_margin = egui::Frame::popup(ui.style()).total_margin().sum().y;
- let max_height = (ui.ctx().content_rect().height() - frame_margin).max(1.0);
- ui.set_max_height(max_height);
- egui::ScrollArea::vertical().max_height(max_height).show(ui, contents).inner
+ /// The tallest menu that fits on either side of its anchor, including the popup frame.
+ fn menu_max_height(ui: &egui::Ui, button: Option<egui::Rect>) -> f32 {
+ let screen = ui.ctx().content_rect();
+ let space = match button {
+ // Submenus open beside their row, aligned with its top or bottom.
+ Some(rect) if egui::containers::menu::is_in_menu(ui) => (screen.bottom() - rect.top()).max(rect.bottom() - screen.top()),
+ Some(rect) => (screen.bottom() - rect.bottom()).max(rect.top() - screen.top()),
+ None => screen.height(),
+ };
+ let chrome = egui::Frame::menu(ui.style()).total_margin().sum().y + 8.0;
+ (space.min(screen.height()) - chrome).max(1.0)
}
- fn clipped_submenu<R>(ui: &mut egui::Ui, label: egui::WidgetText, contents: impl FnOnce(&mut egui::Ui) -> R) -> Option<R> {
+ /// egui's submenu hover test uses the full row rect, even outside a scroll area's clip.
+ fn clipped_submenu<'a, R>(
+ ui: &mut egui::Ui,
+ atoms: impl egui::IntoAtoms<'a>,
+ config: egui::containers::menu::MenuConfig,
+ contents: impl FnOnce(&mut egui::Ui) -> R,
+ ) -> (egui::Response, Option<egui::InnerResponse<R>>) {
use egui::containers::menu::{MenuState, SubMenu, SubMenuButton};
let id = SubMenu::id_from_widget_id(ui.next_auto_id());
@@@ -1942,13 -1812,41 +1953,41 @@@
if open {
MenuState::from_ui(ui, |state, _| state.open_item = None);
}
- return None;
+ return (response, None);
}
- // egui expands an unclipped hover rectangle by half the item spacing.
+ // Undo the half-spacing expansion used by SubMenu::show after clamping to the clip.
let hover_margin = ui.spacing().item_spacing / 2.0;
- response.rect = response.rect.expand2(hover_margin).intersect(clip).shrink2(hover_margin);
- response.interact_rect = response.interact_rect.intersect(clip);
- button.sub_menu.show(ui, &response, contents).map(|response| response.inner)
+ let mut clipped = response.clone();
+ clipped.rect = response.rect.expand2(hover_margin).intersect(clip).shrink2(hover_margin);
+ clipped.interact_rect = response.interact_rect.intersect(clip);
+ let inner = button.sub_menu.show(ui, &clipped, contents);
+ (response, inner)
+ }
+
+ /// The menu bar contents (inside the app bar; macOS uses the native menu instead).
+ pub fn menu_bar(app: &mut DesignApp, ui: &mut egui::Ui) {
+ let lang = app.ui.language.clone();
+ let mut menus = menu_tree();
+ if crate::i18n::is_rtl(&lang) {
+ menus.reverse();
+ }
+ for (menu, entries) in menus {
+ menu_button(ui, crate::rtl::widget(ui, crate::i18n::tr(&lang, menu)), |ui| {
+ if crate::i18n::is_rtl(&lang) {
+ ui.set_max_width(320.0);
+ }
- ui.with_layout(egui::Layout::top_down(if crate::i18n::is_rtl(&lang) { egui::Align::Max } else { egui::Align::Min }), |ui| {
++ ui.with_layout(egui::Layout::top_down_justified(if crate::i18n::is_rtl(&lang) { egui::Align::Max } else { egui::Align::Min }), |ui| {
+ ui.set_min_width(240.0);
+ let hidden = menu_items(app, ui, &entries, menu);
+ if hidden > 0 && !app.ui.show_full_menus {
+ ui.separator();
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&lang, "Show All Menu Items"))).clicked() {
+ app.ui.show_full_menus = true;
+ }
+ }
+ });
+ });
+ }
}
/// The key a menu item is hidden by (Edit › Menus).