Skip to content

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

Refactor ui-egui for strict Clippy checks

Dylan M. Taylord04c8b2e5834
diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs
index 59540390a..85c9264ec 100644
--- a/crates/ui-egui/src/app.rs
+++ b/crates/ui-egui/src/app.rs
@@ -1,9 +1,14 @@
+#[cfg(not(target_arch = "wasm32"))]
+use super::PendingDrop;
use super::clock::now_ms;
-#[cfg(test)]
-use super::services::Inbox;
use super::services::Services;
use super::state::{CanvasCache, ImportRequest, ImportedFile, Perf, ScreenMode, UiState, View, second_window_viewport};
-use super::*;
+use super::{
+ ControlRequest, ControlResponse, DesignApp, HashMap, InputGeneration, LivePreview, QuitState, Receiver, SCREENSHOT_MAX_AGGREGATE_BYTES,
+ SCREENSHOT_MAX_IMAGE_BYTES, SCREENSHOT_MAX_REQUESTS, ScreenshotGeometry, Sender, Session, ShotRequest, UiRequest, Value, ViewInfo, about, canvas,
+ chrome, cursors, dialogs, dock, json, menus, new_document, page_history, panel_docking, shortcut_import, story_editor, theme, toolbar,
+ updates_ui,
+};
mod clipboard;
mod commands;
diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs
index 8e385ba73..4b813dd5c 100644
--- a/crates/ui-egui/src/app/clipboard.rs
+++ b/crates/ui-egui/src/app/clipboard.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{DesignApp, Value, canvas, json};
impl DesignApp {
/// Paste without the clipboard's text (a menu, not the paste keys): read it here. With no
diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs
index cec2bf869..44e35ef15 100644
--- a/crates/ui-egui/src/app/commands.rs
+++ b/crates/ui-egui/src/app/commands.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{DesignApp, UiRequest, Value, canvas, dialogs, json, menus};
impl DesignApp {
/// THE entry point for every action (menus, shortcuts, palette, panels, control channel).
diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs
index 3666bdcb8..3c29ca9af 100644
--- a/crates/ui-egui/src/app/control.rs
+++ b/crates/ui-egui/src/app/control.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{ControlRequest, DesignApp, Receiver};
impl DesignApp {
pub fn with_control(mut self, rx: Receiver<ControlRequest>) -> Self {
diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs
index 40f91ba39..916a47317 100644
--- a/crates/ui-egui/src/app/files.rs
+++ b/crates/ui-egui/src/app/files.rs
@@ -1,4 +1,10 @@
-use super::*;
+use super::{DesignApp, ImportRequest, ImportedFile, Value, canvas, dialogs, json, shortcut_import};
+#[cfg(test)]
+use super::{Services, Session};
+#[cfg(test)]
+use crate::Inbox;
+#[cfg(test)]
+use crate::test_window;
impl DesignApp {
/// The host's save dialog for `name`, started beside the active document once it has been
diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs
index f446e2dab..66274d709 100644
--- a/crates/ui-egui/src/app/frame.rs
+++ b/crates/ui-egui/src/app/frame.rs
@@ -1,4 +1,6 @@
-use super::*;
+#[cfg(not(target_arch = "wasm32"))]
+use super::json;
+use super::{DesignApp, canvas, chrome, new_document, now_ms, theme, updates_ui};
impl DesignApp {
/// Install the UI fonts on the first frame, and again when the language or the system fonts change.
diff --git a/crates/ui-egui/src/app/ime.rs b/crates/ui-egui/src/app/ime.rs
index 2f098e013..6f36d7235 100644
--- a/crates/ui-egui/src/app/ime.rs
+++ b/crates/ui-egui/src/app/ime.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::DesignApp;
impl DesignApp {
/// Did an IME composition end outside the IME this frame (a click, a tool switch)? egui's
diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs
index a17fe69ce..8d248561c 100644
--- a/crates/ui-egui/src/app/input.rs
+++ b/crates/ui-egui/src/app/input.rs
@@ -1,4 +1,6 @@
-use super::*;
+#[cfg(not(target_arch = "wasm32"))]
+use super::PendingDrop;
+use super::{DesignApp, InputGeneration, Value, menus};
impl DesignApp {
/// Keep pending synthetic input and screenshot settlement repainting while the window may be
diff --git a/crates/ui-egui/src/app/keys.rs b/crates/ui-egui/src/app/keys.rs
index e2beeafb5..79e6ab73a 100644
--- a/crates/ui-egui/src/app/keys.rs
+++ b/crates/ui-egui/src/app/keys.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::DesignApp;
impl DesignApp {
/// Applies `ui.shortcuts` to the keymap when they differ, e.g. after preferences were loaded,
diff --git a/crates/ui-egui/src/app/quit.rs b/crates/ui-egui/src/app/quit.rs
index 2852020d1..7e3686ac6 100644
--- a/crates/ui-egui/src/app/quit.rs
+++ b/crates/ui-egui/src/app/quit.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{DesignApp, HashMap, QuitState, Value, json, menus};
impl DesignApp {
/// Quit: close the window the way its close button does, so unsaved documents ask first.
diff --git a/crates/ui-egui/src/app/screenshot.rs b/crates/ui-egui/src/app/screenshot.rs
index a621eb9e3..90422c1c8 100644
--- a/crates/ui-egui/src/app/screenshot.rs
+++ b/crates/ui-egui/src/app/screenshot.rs
@@ -1,4 +1,7 @@
-use super::*;
+use super::{
+ ControlResponse, DesignApp, SCREENSHOT_MAX_AGGREGATE_BYTES, SCREENSHOT_MAX_IMAGE_BYTES, SCREENSHOT_MAX_REQUESTS, ScreenshotGeometry, Sender,
+ ShotRequest, json, now_ms,
+};
impl DesignApp {
/// Advance the screenshot geometry epoch whenever size, DPI, zoom or surface change.
diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs
index 64cb11ccb..a229fa598 100644
--- a/crates/ui-egui/src/app/view.rs
+++ b/crates/ui-egui/src/app/view.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{DesignApp, LivePreview, Value, View, ViewInfo, json, page_history};
impl DesignApp {
/// The view key of the active document in the current pane.
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 4fc09248a..de4331c7d 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -133,6 +133,81 @@ impl Xf {
}
}
+/// A guide being dragged out or moved: its line, what caught it, and where it is beside the pointer (#1282).
+fn draw_guide_drag(app: &DesignApp, painter: &egui::Painter, xf: &Xf, g: &GuideDrag, p: Pos2, rect: Rect, t: &Tokens) {
+ let col = Color32::from_rgb(74, 227, 255);
+ let spot = guide_spot(app, xf, g);
+ let line = spot.as_ref().map_or(p, |s| s.screen);
+ let (a, b) = match g.orientation {
+ designcraft_doc::Orientation::Horizontal => (pos2(rect.min.x, line.y), pos2(rect.max.x, line.y)),
+ designcraft_doc::Orientation::Vertical => (pos2(line.x, rect.min.y), pos2(line.x, rect.max.y)),
+ };
+ // What caught it, as for a moved object.
+ for mark in spot.iter().flat_map(|s| &s.marks) {
+ if let Overlay::Guide { a, b } = mark {
+ painter.line_segment([xf.to_screen(*a), xf.to_screen(*b)], Stroke::new(1.0, t.smart_guide));
+ }
+ }
+ // A new guide from the rulers with the Page tool is a liquid guide: dashed.
+ if g.from.is_none() && app.session.tool_id() == "page" {
+ dashed(painter, a, b, Stroke::new(1.0, col), 6.0, 3.0);
+ } else {
+ painter.line_segment([a, b], Stroke::new(1.0, col));
+ }
+ // Where it is, beside the pointer (#1282).
+ if let Some(text) = guide_readout(app, xf, g) {
+ let galley = painter.layout_no_wrap(text, egui::FontId::proportional(11.0), t.text);
+ let at = readout_at(p, galley.size(), rect);
+ let bg = Rect::from_min_size(at, galley.size()).expand(3.0);
+ painter.rect_filled(bg, 2.0, t.panel);
+ painter.rect_stroke(bg, 2.0, Stroke::new(1.0, t.border), StrokeKind::Inside);
+ painter.galley(at, galley, t.text);
+ }
+}
+
+/// The rendered texture, placed where its region is in the current view.
+fn paint_render(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document, layout: &CanvasLayout, screen: Rect, preview: bool) {
+ if let (Some(tex), Some(sh)) = (&app.canvas.texture, app.canvas.shown) {
+ // Place the texture where its region is in the current view (shifted while panning,
+ // scaled while a zoom re-render is pending).
+ // The texture's corners in canvas space, placed through the view (rotation included).
+ let (w, h) = (sh.size.0 as f64 / sh.zoom, sh.size.1 as f64 / sh.zoom);
+ let o = sh.origin;
+ let corners = [
+ (o, pos2(0.0, 0.0)),
+ (Point::new(o.x + w, o.y), pos2(1.0, 0.0)),
+ (Point::new(o.x + w, o.y + h), pos2(1.0, 1.0)),
+ (Point::new(o.x, o.y + h), pos2(0.0, 1.0)),
+ ];
+ let mut mesh = egui::Mesh::with_texture(tex.id());
+ for (c, uv) in corners {
+ mesh.vertices.push(egui::epaint::Vertex { pos: xf.to_screen(c), uv, color: Color32::WHITE });
+ }
+ mesh.indices.extend([0, 1, 2, 0, 2, 3]);
+ if preview {
+ // Preview: only the shown area of each spread keeps its content.
+ for slot in &layout.slots {
+ let r = shown_area(app, doc, xf, slot);
+ painter.with_clip_rect(r.intersect(screen)).add(egui::Shape::mesh(mesh.clone()));
+ }
+ } else {
+ painter.add(egui::Shape::mesh(mesh));
+ }
+ }
+}
+
+/// Presentation: a click shows the next spread, Shift-click the previous one.
+fn present_click(app: &mut DesignApp, ui: &egui::Ui, resp: &egui::Response, rect: Rect) {
+ if resp.clicked() {
+ // The release that made the click says whether Shift was down.
+ let shift = ui.input(|i| {
+ i.modifiers.shift || i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, modifiers, .. } if modifiers.shift))
+ });
+ step_spread(app, if shift { -1 } else { 1 });
+ present_fit(app, rect);
+ }
+}
+
/// Lay out the canvas, scrollbars and rulers, presentation mode, fit/view state, input handling and painting.
pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
@@ -152,15 +227,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
// One spread at a time, as large as the screen allows; a click shows the next one,
// Shift-click the previous one. Tools and selection don't see the input.
present_fit(app, rect);
- if resp.clicked() {
- // The release that made the click says whether Shift was down.
- let shift = ui.input(|i| {
- i.modifiers.shift
- || i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, modifiers, .. } if modifiers.shift))
- });
- step_spread(app, if shift { -1 } else { 1 });
- present_fit(app, rect);
- }
+ present_click(app, ui, &resp, rect);
} else {
if !app.view().is_some_and(|v| v.fitted) {
fit(app, rect, "spread");
@@ -201,33 +268,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
}
// Rendered content.
render_texture(app, ui.ctx(), rect, &xf, &layout, preview);
- if let (Some(tex), Some(sh)) = (&app.canvas.texture, app.canvas.shown) {
- // Place the texture where its region is in the current view (shifted while panning,
- // scaled while a zoom re-render is pending).
- // The texture's corners in canvas space, placed through the view (rotation included).
- let (w, h) = (sh.size.0 as f64 / sh.zoom, sh.size.1 as f64 / sh.zoom);
- let o = sh.origin;
- let corners = [
- (o, pos2(0.0, 0.0)),
- (Point::new(o.x + w, o.y), pos2(1.0, 0.0)),
- (Point::new(o.x + w, o.y + h), pos2(1.0, 1.0)),
- (Point::new(o.x, o.y + h), pos2(0.0, 1.0)),
- ];
- let mut mesh = egui::Mesh::with_texture(tex.id());
- for (c, uv) in corners {
- mesh.vertices.push(egui::epaint::Vertex { pos: xf.to_screen(c), uv, color: Color32::WHITE });
- }
- mesh.indices.extend([0, 1, 2, 0, 2, 3]);
- if preview {
- // Preview: only the shown area of each spread keeps its content.
- for slot in &layout.slots {
- let r = shown_area(app, &doc, &xf, slot);
- painter.with_clip_rect(r.intersect(screen)).add(egui::Shape::mesh(mesh.clone()));
- }
- } else {
- painter.add(egui::Shape::mesh(mesh));
- }
- }
+ paint_render(app, &painter, &xf, &doc, &layout, screen, preview);
crate::separations::paint(app, ui.ctx(), &painter, &xf, &layout, screen);
let hair = 1.0 / ui.ctx().pixels_per_point();
for slot in &layout.slots {
@@ -241,34 +282,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
if let Some(g) = drag
&& let Some(p) = g.at
{
- let col = Color32::from_rgb(74, 227, 255);
- let spot = guide_spot(app, &xf, &g);
- let line = spot.as_ref().map_or(p, |s| s.screen);
- let (a, b) = match g.orientation {
- designcraft_doc::Orientation::Horizontal => (pos2(rect.min.x, line.y), pos2(rect.max.x, line.y)),
- designcraft_doc::Orientation::Vertical => (pos2(line.x, rect.min.y), pos2(line.x, rect.max.y)),
- };
- // What caught it, as for a moved object.
- for mark in spot.iter().flat_map(|s| &s.marks) {
- if let Overlay::Guide { a, b } = mark {
- painter.line_segment([xf.to_screen(*a), xf.to_screen(*b)], Stroke::new(1.0, t.smart_guide));
- }
- }
- // A new guide from the rulers with the Page tool is a liquid guide: dashed.
- if g.from.is_none() && app.session.tool_id() == "page" {
- dashed(&painter, a, b, Stroke::new(1.0, col), 6.0, 3.0);
- } else {
- painter.line_segment([a, b], Stroke::new(1.0, col));
- }
- // Where it is, beside the pointer (#1282).
- if let Some(text) = guide_readout(app, &xf, &g) {
- let galley = painter.layout_no_wrap(text, egui::FontId::proportional(11.0), t.text);
- let at = readout_at(p, galley.size(), rect);
- let bg = Rect::from_min_size(at, galley.size()).expand(3.0);
- painter.rect_filled(bg, 2.0, t.panel);
- painter.rect_stroke(bg, 2.0, Stroke::new(1.0, t.border), StrokeKind::Inside);
- painter.galley(at, galley, t.text);
- }
+ draw_guide_drag(app, &painter, &xf, &g, p, rect, &t);
}
draw_frames(app, &painter, &xf, &doc, &layout);
if app.ui.hidden_characters {
diff --git a/crates/ui-egui/src/canvas/column_guides.rs b/crates/ui-egui/src/canvas/column_guides.rs
index f301be34c..34d995fda 100644
--- a/crates/ui-egui/src/canvas/column_guides.rs
+++ b/crates/ui-egui/src/canvas/column_guides.rs
@@ -1,6 +1,6 @@
use super::guides::{guide_at, over_item};
use super::rulers::ruler_pieces;
-use super::*;
+use super::{CanvasLayout, DRect, DesignApp, Document, Point, Pos2, Rect, ScreenMode, SpreadRef, Xf, json};
pub(super) const COLUMN_DRAG: &str = "canvas_column_drag";
diff --git a/crates/ui-egui/src/canvas/frames.rs b/crates/ui-egui/src/canvas/frames.rs
index fdaf67872..4ff09ab98 100644
--- a/crates/ui-egui/src/canvas/frames.rs
+++ b/crates/ui-egui/src/canvas/frames.rs
@@ -2,7 +2,10 @@ use super::page_decor::dashed;
use super::render::c32;
use super::rulers::hair;
use super::text_overlay::draw_text_selection;
-use super::*;
+use super::{
+ Affine, CanvasLayout, Color32, Content, DRect, DesignApp, Document, Item, Point, Pos2, Rect, Selection, Stroke, StrokeKind, Xf, compose, pos2,
+ vec2,
+};
/// Spread-space → canvas transform for an item at `loc`.
pub(super) fn item_canvas_xf(doc: &Document, layout: &CanvasLayout, id: designcraft_doc::ItemId) -> Option<(Affine, &'static str)> {
diff --git a/crates/ui-egui/src/canvas/guides.rs b/crates/ui-egui/src/canvas/guides.rs
index 5536068dd..eebd41208 100644
--- a/crates/ui-egui/src/canvas/guides.rs
+++ b/crates/ui-egui/src/canvas/guides.rs
@@ -1,6 +1,6 @@
use super::rulers::ruler_pieces_of;
use super::view::current_slot;
-use super::*;
+use super::{CanvasLayout, DRect, DesignApp, Document, GuideSel, Overlay, Point, Pos2, Rect, SpreadRef, SpreadSlot, Xf, json, pos2};
pub(super) const GUIDE_DRAG: &str = "canvas_guide_drag";
diff --git a/crates/ui-egui/src/canvas/ime.rs b/crates/ui-egui/src/canvas/ime.rs
index 52bb10640..418d1f25a 100644
--- a/crates/ui-egui/src/canvas/ime.rs
+++ b/crates/ui-egui/src/canvas/ime.rs
@@ -1,5 +1,5 @@
use super::input::{keyboard_pane, modal_open};
-use super::*;
+use super::{CommittedText, DesignApp, IMESurroundingText, ImeMutation, ImeMutationStamp, ImeObservation, ImeTarget, ImeTextContext, Rect, Xf};
/// Has the composition these events belong to already ended outside the IME in this batch?
///
diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs
index 51ce0d17c..3e2f32659 100644
--- a/crates/ui-egui/src/canvas/input.rs
+++ b/crates/ui-egui/src/canvas/input.rs
@@ -4,7 +4,10 @@ use super::ime::{finish_pending_ime_delete, ime_event};
use super::rulers::zero_point_drag;
use super::scroll::{mods, navigation_space, pan, spring_zoom_input, spring_zoom_mode, wheel_alt};
use super::view::zoom_at;
-use super::*;
+use super::{
+ CanvasLayout, Clicks, Cursor, DVec2, DesignApp, Item, Mods, Point, PointerEvent, PointerKind, Pos2, Rect, ScreenMode, SpreadRef, Stroke,
+ StrokeKind, Tokens, ToolKey, Xf, json, pos2, vec2,
+};
/// Whether the pointer this canvas's window last saw is in another of the app's windows: a
/// floating panel's OS window, or the other window of New Window.
@@ -166,15 +169,8 @@ fn item_at(app: &DesignApp, p: Point, zoom: f64) -> Option<(designcraft_doc::Ite
Some((id, sp))
}
-/// Give an open menu priority, then handle wheel/zoom/pan, spring Zoom, guide drags and primary pointer routing.
-pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rect: Rect) {
- // While a context menu is open (in either pane), the click that closes it and the keys go to the menu.
- let menu_open = context_menu_open(ui.ctx());
- let Some(v) = app.view().copied() else { return };
- let xf = Xf::new(rect, &v);
- let wants_text = app.session.wants_text();
- let space = navigation_space(app, ui.ctx());
- // Scroll / zoom.
+/// Wheel, pinch and Alt/Ctrl/Cmd + wheel over the canvas: zoom at the pointer, else scroll.
+fn wheel_navigate(app: &mut DesignApp, ui: &egui::Ui, resp: &egui::Response, xf: &Xf) {
let alt = wheel_alt(ui);
if resp.hovered() {
let (scroll, zoom_delta, m, hover) = ui.input(|i| (i.smooth_scroll_delta, i.zoom_delta(), i.modifiers, i.pointer.hover_pos()));
@@ -195,18 +191,64 @@ pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::
}
}
}
- let zoom = spring_zoom_mode(app, ui.ctx(), space);
- if spring_zoom_input(app, ui, resp, &xf, zoom) {
- return;
+}
+
+/// Where the primary button went down this pass, if egui no longer holds the press origin.
+fn recent_primary_press(ui: &egui::Ui) -> Option<Pos2> {
+ ui.input(|i| {
+ i.events
+ .iter()
+ .rev()
+ .find_map(|event| match event {
+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos),
+ _ => None,
+ })
+ .filter(|pos| pos.is_finite())
+ })
+}
+
+/// Power Zoom: whether a press held still with the Hand tool (`active`) has now lasted half a
+/// second. Keeps the hold's state under `hold_id`, and clears it when the hold ends.
+fn power_zoom_fires(ui: &egui::Ui, hold_id: egui::Id, active: bool, latest: Option<Pos2>) -> bool {
+ if !active {
+ ui.data_mut(|d| d.remove::<(f64, bool)>(hold_id));
+ return false;
}
- // Space-drag = hand (unless a tool drag is under way: then Space is a modifier, e.g. Live
- // Distribute while resizing). Middle-drag pans too, with any tool; tools only
- // see the primary button.
- // A column guide drag keeps the pointer until the button is up, whatever Space or a menu does
- // meanwhile.
- if ui.data(|d| d.get_temp::<ColumnDrag>(egui::Id::unique((COLUMN_DRAG, app.pane)))).is_some() && column_guide_drag(app, ui, resp, rect, &xf) {
- return;
+ let (now, origin_pos) = ui.input(|i| (i.time, i.pointer.press_origin()));
+ let (start, fired): (f64, bool) = ui.data(|d| d.get_temp(hold_id)).unwrap_or((now, false));
+ let still = origin_pos.zip(latest).is_some_and(|(o, l)| (o - l).length() < 3.0);
+ if !fired && still && now - start >= 0.5 {
+ ui.data_mut(|d| d.insert_temp(hold_id, (start, true)));
+ return true;
}
+ ui.data_mut(|d| d.insert_temp(hold_id, (start, fired)));
+ if !fired {
+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
+ }
+ false
+}
+
+/// The zero point, ruler guide and column guide drags; whether one took this pass.
+fn ruler_drags(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rect: Rect, xf: &Xf, space: bool, menu_open: bool) -> bool {
+ // The zero point and ruler guides need the rulers (hidden while the view is rotated).
+ if !space && !menu_open && xf.rot == 0 && zero_point_drag(app, ui, resp, rect, xf) {
+ return true;
+ }
+ // Hidden or locked guides can't stay selected.
+ if (!app.ui.guides || app.ui.guides_locked) && app.session.active().is_some_and(|st| !st.selection.guides.is_empty()) {
+ let _ = app.run("guide.deselect", json!({}));
+ }
+ if !space && !menu_open && xf.rot == 0 && guide_drag(app, ui, resp, rect, xf) {
+ return true;
+ }
+ if !space && !menu_open && xf.rot == 0 && column_guide_drag(app, ui, resp, rect, xf) {
+ return true;
+ }
+ false
+}
+
+/// Hand-tool panning (Space-drag, middle drag, or Alt held at a text press); whether it took this pass.
+fn hand_pan(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, xf: &Xf, space: bool, wants_text: bool, menu_open: bool) -> bool {
let tool_drag: bool = ui.data(|d| d.get_temp(egui::Id::unique(("canvas_pointer_down", app.pane)))).unwrap_or(false);
let hand = space && !ui.input(|i| i.modifiers.command);
if !tool_drag && ((hand && resp.dragged()) || resp.dragged_by(egui::PointerButton::Middle)) {
@@ -214,7 +256,7 @@ pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::
if let Some(v) = app.view_mut() {
v.origin = Point::new(v.origin.x - d.x as f64 / v.zoom, v.origin.y - d.y as f64 / v.zoom);
}
- return;
+ return true;
}
// Editing text (Space types a space): Alt held at the press gives the Hand tool until the
// button is released, and the caret stays. Alt pressed later in a text drag copies the text.
@@ -226,23 +268,47 @@ pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::
}
if alt_hand {
if resp.dragged() {
- pan(app, &xf, resp.drag_delta());
+ pan(app, xf, resp.drag_delta());
}
ui.data_mut(|d| d.insert_temp(alt_hand_id, primary_down));
- return;
+ return true;
}
- // The zero point and ruler guides need the rulers (hidden while the view is rotated).
- if !space && !menu_open && xf.rot == 0 && zero_point_drag(app, ui, resp, rect, &xf) {
+ false
+}
+
+/// A release ends the press run's last click; remembers where and when for the next press.
+fn note_release(ui: &egui::Ui, clicks_id: egui::Id, latest: Option<Pos2>, now: f64) {
+ if let Some(c) = ui.data(|d| d.get_temp::<Clicks>(clicks_id)) {
+ let dist = ui.ctx().options(|o| o.input_options.max_click_dist);
+ ui.data_mut(|d| d.insert_temp(clicks_id, release_clicks(c, latest.unwrap_or(c.pos), now, dist)));
+ }
+}
+
+/// Give an open menu priority, then handle wheel/zoom/pan, spring Zoom, guide drags and primary pointer routing.
+pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rect: Rect) {
+ // While a context menu is open (in either pane), the click that closes it and the keys go to the menu.
+ let menu_open = context_menu_open(ui.ctx());
+ let Some(v) = app.view().copied() else { return };
+ let xf = Xf::new(rect, &v);
+ let wants_text = app.session.wants_text();
+ let space = navigation_space(app, ui.ctx());
+ wheel_navigate(app, ui, resp, &xf);
+ let zoom = spring_zoom_mode(app, ui.ctx(), space);
+ if spring_zoom_input(app, ui, resp, &xf, zoom) {
return;
}
- // Hidden or locked guides can't stay selected.
- if (!app.ui.guides || app.ui.guides_locked) && app.session.active().is_some_and(|st| !st.selection.guides.is_empty()) {
- let _ = app.run("guide.deselect", json!({}));
+ // Space-drag = hand (unless a tool drag is under way: then Space is a modifier, e.g. Live
+ // Distribute while resizing). Middle-drag pans too, with any tool; tools only
+ // see the primary button.
+ // A column guide drag keeps the pointer until the button is up, whatever Space or a menu does
+ // meanwhile.
+ if ui.data(|d| d.get_temp::<ColumnDrag>(egui::Id::unique((COLUMN_DRAG, app.pane)))).is_some() && column_guide_drag(app, ui, resp, rect, &xf) {
+ return;
}
- if !space && !menu_open && xf.rot == 0 && guide_drag(app, ui, resp, rect, &xf) {
+ if hand_pan(app, ui, resp, &xf, space, wants_text, menu_open) {
return;
}
- if !space && !menu_open && xf.rot == 0 && column_guide_drag(app, ui, resp, rect, &xf) {
+ if ruler_drags(app, ui, resp, rect, &xf, space, menu_open) {
return;
}
let m = ui.input(|i| mods(i, space));
@@ -256,18 +322,7 @@ pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::
ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.press_origin(), i.pointer.latest_pos(), i.time));
// A complete click can arrive in one pass: release clears egui's held origin.
// Recover the actual primary press position, preserving the origin for held gestures.
- let origin = origin.or_else(|| {
- ui.input(|i| {
- i.events
- .iter()
- .rev()
- .find_map(|event| match event {
- egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos),
- _ => None,
- })
- .filter(|pos| pos.is_finite())
- })
- });
+ let origin = origin.or_else(|| recent_primary_press(ui));
let in_view = |o: Pos2| if xf.rot == 0 { rect.contains(o) } else { resp.rect.contains(o) };
if pressed
&& !space
@@ -291,29 +346,13 @@ pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::
}
// Power Zoom: holding the Hand tool still for half a second turns the press into one.
let hold_id = egui::Id::unique(("canvas_hold", app.pane));
- if down && !released && app.session.tool_id() == "hand" && !m.alt {
- let (now, origin_pos) = ui.input(|i| (i.time, i.pointer.press_origin()));
- let (start, fired): (f64, bool) = ui.data(|d| d.get_temp(hold_id)).unwrap_or((now, false));
- let still = origin_pos.zip(latest).is_some_and(|(o, l)| (o - l).length() < 3.0);
- if !fired && still && now - start >= 0.5 {
- let p = pos(latest.unwrap_or(rect.center()));
- events.push(PointerEvent { kind: PointerKind::Up, pos: p, mods: m, clicks: 1 });
- events.push(PointerEvent { kind: PointerKind::Down, pos: p, mods: Mods { alt: true, ..m }, clicks: 1 });
- ui.data_mut(|d| d.insert_temp(hold_id, (start, true)));
- } else {
- ui.data_mut(|d| d.insert_temp(hold_id, (start, fired)));
- if !fired {
- ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
- }
- }
- } else {
- ui.data_mut(|d| d.remove::<(f64, bool)>(hold_id));
+ if power_zoom_fires(ui, hold_id, down && !released && app.session.tool_id() == "hand" && !m.alt, latest) {
+ let p = pos(latest.unwrap_or(rect.center()));
+ events.push(PointerEvent { kind: PointerKind::Up, pos: p, mods: m, clicks: 1 });
+ events.push(PointerEvent { kind: PointerKind::Down, pos: p, mods: Mods { alt: true, ..m }, clicks: 1 });
}
if down && released {
- if let Some(c) = ui.data(|d| d.get_temp::<Clicks>(clicks_id)) {
- let dist = ui.ctx().options(|o| o.input_options.max_click_dist);
- ui.data_mut(|d| d.insert_temp(clicks_id, release_clicks(c, latest.unwrap_or(c.pos), now, dist)));
- }
+ note_release(ui, clicks_id, latest, now);
let p = latest.unwrap_or(rect.center());
events.push(PointerEvent { kind: PointerKind::Up, pos: pos(p), mods: m, clicks: 1 });
down = false;
diff --git a/crates/ui-egui/src/canvas/page_decor.rs b/crates/ui-egui/src/canvas/page_decor.rs
index 11ce97dbf..af2bec79b 100644
--- a/crates/ui-egui/src/canvas/page_decor.rs
+++ b/crates/ui-egui/src/canvas/page_decor.rs
@@ -1,7 +1,10 @@
use super::guides::MovingGuides;
use super::render::c32;
use super::rulers::hair;
-use super::*;
+use super::{
+ CanvasLayout, Color32, DRect, DesignApp, Document, GuideSel, Item, Point, Pos2, Rect, ScreenMode, SpreadRef, SpreadSlot, Stroke, StrokeKind,
+ Tokens, Xf,
+};
pub(super) fn dashed(painter: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke, dash: f32, gap: f32) {
painter.extend(egui::Shape::dashed_line(&[a, b], stroke, dash, gap));
@@ -58,7 +61,8 @@ pub(super) fn draw_guides(
continue;
}
draw_page_grids(painter, xf, doc, slot, p, pr, app.ui.baseline_grid);
- draw_page_guides(painter, xf, doc, slot, sp, pi, p, pr, pasteboard, moving, &selection);
+ let cx = GuideCtx { painter, xf, doc, slot, sp, pasteboard };
+ draw_page_guides(&cx, (pi, p, pr), moving, &selection);
}
}
let _ = t;
@@ -123,21 +127,26 @@ fn draw_page_grids(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: &Spre
}
}
+/// What one page's guides are drawn against.
+struct GuideCtx<'a> {
+ painter: &'a egui::Painter,
+ xf: &'a Xf,
+ doc: &'a Document,
+ slot: &'a SpreadSlot,
+ sp: &'a designcraft_doc::Spread,
+ pasteboard: DRect,
+}
+
/// The page's own guides, then those it shows from its parent page. `moving` draws dragged
-/// guides where they would be dropped.
+/// guides where they would be dropped. `page`: its index in the spread, the page, and its bounds.
fn draw_page_guides(
- painter: &egui::Painter,
- xf: &Xf,
- doc: &Document,
- slot: &SpreadSlot,
- sp: &designcraft_doc::Spread,
- pi: usize,
- p: &designcraft_doc::Page,
- pr: DRect,
- pasteboard: DRect,
+ cx: &GuideCtx,
+ page: (usize, &designcraft_doc::Page, DRect),
moving: Option<&MovingGuides>,
selection: &std::collections::HashSet<GuideSel>,
) {
+ let GuideCtx { doc, slot, .. } = *cx;
+ let (pi, p, pr) = page;
let own = p.guides.len();
for (gi, mut g) in p.guides.iter().cloned().chain(doc.parent_guides(p)).enumerate().filter(|(_, g)| g.visible_in(doc)) {
let key = GuideSel { spread: slot.spread, page: pi, index: gi };
@@ -152,22 +161,13 @@ fn draw_page_guides(
designcraft_doc::Orientation::Horizontal => m.dy,
};
}
- draw_guide(painter, xf, doc, slot, sp, pr, pasteboard, &g, selected);
+ draw_guide(cx, pr, &g, selected);
}
}
/// One guide as a line: across the pasteboard for a spread guide, across its page otherwise.
-fn draw_guide(
- painter: &egui::Painter,
- xf: &Xf,
- doc: &Document,
- slot: &SpreadSlot,
- sp: &designcraft_doc::Spread,
- pr: DRect,
- pasteboard: DRect,
- g: &designcraft_doc::Guide,
- selected: bool,
-) {
+fn draw_guide(cx: &GuideCtx, pr: DRect, g: &designcraft_doc::Guide, selected: bool) {
+ let GuideCtx { painter, xf, doc, slot, sp, pasteboard } = *cx;
let pt = |q: Point| xf.to_screen(slot.xf * q);
// Spread guides cross the pasteboard; page guides their page.
let span = if g.spread { pasteboard } else { pr };
diff --git a/crates/ui-egui/src/canvas/render.rs b/crates/ui-egui/src/canvas/render.rs
index dcace3e29..642694b8a 100644
--- a/crates/ui-egui/src/canvas/render.rs
+++ b/crates/ui-egui/src/canvas/render.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{Affine, CanvasLayout, Color32, DRect, DesignApp, Point, Rect, Xf};
pub(super) fn c32(c: [u8; 3]) -> Color32 {
Color32::from_rgb(c[0], c[1], c[2])
@@ -165,7 +165,7 @@ pub(super) fn render_texture(app: &mut DesignApp, ctx: &egui::Context, rect: Rec
if !has_worker || app.canvas.shown.is_none() || mode_changed || (doc_changed && zoom_same) {
let t0 = crate::now_ms();
let Some((doc, placed, w, h, view, opts)) = job(app) else { return };
- let img = app.canvas.renderer.render(&doc, &app.session.cache, &placed, w, h, view, &opts);
+ let img = app.canvas.renderer.render(&doc, &app.session.cache, &placed, (w, h), view, &opts);
upload(app, ctx, img);
app.canvas.shown = Some(target);
app.canvas.shown_doc = Some(doc);
@@ -249,7 +249,7 @@ fn patch_texture(app: &mut DesignApp, layout: &CanvasLayout, ppp: f64, doc_key:
* Affine::scale(sh.zoom)
* Affine::translate((-sh.origin.x, -sh.origin.y));
let opts = screen_options(app, layout, preview, ppp);
- let img = app.canvas.patcher.render(&new, &app.session.cache, &placed, (x1 - x0) as u32, (y1 - y0) as u32, view, &opts);
+ let img = app.canvas.patcher.render(&new, &app.session.cache, &placed, ((x1 - x0) as u32, (y1 - y0) as u32), view, &opts);
let ci = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels);
if let Some(tex) = app.canvas.texture.as_mut() {
tex.set_partial([x0 as usize, y0 as usize], ci, egui::TextureOptions::LINEAR);
diff --git a/crates/ui-egui/src/canvas/rulers.rs b/crates/ui-egui/src/canvas/rulers.rs
index 96353cb1b..4aae485ec 100644
--- a/crates/ui-egui/src/canvas/rulers.rs
+++ b/crates/ui-egui/src/canvas/rulers.rs
@@ -1,7 +1,7 @@
use super::input::pointer_elsewhere;
use super::page_decor::dashed;
use super::view::current_slot;
-use super::*;
+use super::{CanvasLayout, DesignApp, Document, Point, Pos2, RULER, Rect, SpreadSlot, Stroke, Tokens, Value, Xf, json, pos2, vec2};
/// Paint ruler bands and ticks, the zero-point crosshair, guide previews, and ticks restarted at each page origin.
#[allow(clippy::too_many_arguments)]
diff --git a/crates/ui-egui/src/canvas/scroll.rs b/crates/ui-egui/src/canvas/scroll.rs
index 6d14c4bec..e70785a97 100644
--- a/crates/ui-egui/src/canvas/scroll.rs
+++ b/crates/ui-egui/src/canvas/scroll.rs
@@ -1,6 +1,10 @@
#[cfg(test)]
+use super::json;
+#[cfg(test)]
use super::view::set_zoom;
-use super::*;
+use super::{CanvasLayout, DesignApp, Mods, Point, PointerEvent, PointerKind, Rect, SCROLLBAR, Sense, Tokens, Xf, pos2, vec2};
+#[cfg(test)]
+use egui::Pos2;
/// Shortest scrollbar thumb.
const MIN_THUMB: f32 = 18.0;
diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs
index ce68f3c12..01300bdd0 100644
--- a/crates/ui-egui/src/canvas/tests.rs
+++ b/crates/ui-egui/src/canvas/tests.rs
@@ -1782,7 +1782,7 @@ fn document_grid_is_drawn_where_points_snap_to_it() {
let placed: Vec<_> = layout.slots.iter().map(|s| designcraft_render::Placed { spread: s.spread, xf: s.xf }).collect();
let render = |app: &DesignApp| {
let opts = screen_options(app, &layout, false, 1.0);
- designcraft_render::Renderer::new().render(&doc, &app.session.cache, &placed, 160, 160, view, &opts)
+ designcraft_render::Renderer::new().render(&doc, &app.session.cache, &placed, (160, 160), view, &opts)
};
// The snapped point is at pixel (80, 80); halfway to the next line is 18 px further.
let darkest = |img: &designcraft_render::Rendered, xs: [u32; 2], ys: [u32; 2]| {
diff --git a/crates/ui-egui/src/canvas/text_overlay.rs b/crates/ui-egui/src/canvas/text_overlay.rs
index f825275f8..dc48ae720 100644
--- a/crates/ui-egui/src/canvas/text_overlay.rs
+++ b/crates/ui-egui/src/canvas/text_overlay.rs
@@ -1,5 +1,5 @@
use super::frames::{item_canvas_xf, layer_color, path_screen};
-use super::*;
+use super::{Affine, CanvasLayout, Color32, DesignApp, Document, Point, Pos2, Rect, Stroke, Xf, compose, pos2};
pub(super) fn draw_text_selection(
app: &DesignApp,
diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs
index 509fd5cd1..5720ba030 100644
--- a/crates/ui-egui/src/canvas/tool_overlays.rs
+++ b/crates/ui-egui/src/canvas/tool_overlays.rs
@@ -1,7 +1,7 @@
use super::frames::{item_canvas_xf, selection_color};
use super::page_decor::dashed;
use super::render::c32;
-use super::*;
+use super::{CanvasLayout, Color32, Content, DesignApp, Document, Overlay, Point, Pos2, Rect, Stroke, StrokeKind, Tokens, Xf, pos2, vec2};
pub(super) fn draw_tool_overlays(app: &mut DesignApp, painter: &egui::Painter, xf: &Xf) {
if let (Some((z, c)), Some(rect)) = (app.power_zoom, app.canvas_rect) {
diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs
index ebf6e0ba2..db3eebcc8 100644
--- a/crates/ui-egui/src/canvas/view.rs
+++ b/crates/ui-egui/src/canvas/view.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{CanvasLayout, DRect, DVec2, DesignApp, Document, Point, Pos2, Rect, SpreadRef, Value, View, Xf};
/// Fit the current spread (or page) in the canvas.
pub fn fit(app: &mut DesignApp, rect: Rect, what: &str) {
diff --git a/crates/ui-egui/src/chrome/app_bar.rs b/crates/ui-egui/src/chrome/app_bar.rs
index 8c910ddfd..b93113d05 100644
--- a/crates/ui-egui/src/chrome/app_bar.rs
+++ b/crates/ui-egui/src/chrome/app_bar.rs
@@ -1,4 +1,6 @@
-use super::*;
+use super::{
+ APP_BAR, APP_BAR_BAND, Color32, DesignApp, MAC_APP_BAR, MAC_CONTENT_LEFT, SEPARATOR, Sense, Stroke, Tokens, icons, json, semibold, vec2,
+};
pub(super) fn search_id() -> egui::Id {
egui::Id::unique("app_bar_search")
diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs
index 331caa446..36a7521fe 100644
--- a/crates/ui-egui/src/chrome/control_bar.rs
+++ b/crates/ui-egui/src/chrome/control_bar.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{Align, Color32, DesignApp, NumField, Sense, Stroke, Tokens, Unit, caption, icons, json, measure, panels, semibold, vec2};
fn vsep(ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
diff --git a/crates/ui-egui/src/chrome/start_screen.rs b/crates/ui-egui/src/chrome/start_screen.rs
index 60e9ddcb8..6e5248724 100644
--- a/crates/ui-egui/src/chrome/start_screen.rs
+++ b/crates/ui-egui/src/chrome/start_screen.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{Color32, Content, DesignApp, Sense, Stroke, Tokens, json, semibold, vec2};
pub fn start_screen(app: &mut DesignApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs
index 3e2882d52..e0a9d27e2 100644
--- a/crates/ui-egui/src/chrome/status_bar.rs
+++ b/crates/ui-egui/src/chrome/status_bar.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{Color32, DesignApp, Sense, Stroke, Tokens, icons, json, panels, semibold, vec2};
/// The widest a document tab grows: a longer name is shortened so its close button and the
/// tabs after it stay in view.
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 890eea3ce..e4c6fe723 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -149,6 +149,83 @@ pub fn handle(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) ->
out
}
+/// `ui.pointer`: canvas-space pointer events straight to the tool.
+fn control_pointer(app: &mut DesignApp, ctx: &egui::Context, p: &Value) -> Outcome {
+ let Some(events) = p.get("events").and_then(Value::as_array) else { return err("missing `events`") };
+ let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default();
+ let view = app.view_info();
+ let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v));
+ let mut last = None;
+ for e in events {
+ let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") {
+ "down" => PointerKind::Down,
+ "drag" => PointerKind::Drag,
+ "up" => PointerKind::Up,
+ "move" => PointerKind::Move,
+ "doubleclick" | "dblclick" => PointerKind::DoubleClick,
+ other => return err(format!("unknown pointer kind `{other}`")),
+ };
+ let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.0);
+ let y = e.get("y").and_then(Value::as_f64).unwrap_or(0.0);
+ let pos = if e.get("space").and_then(Value::as_str) == Some("screen") {
+ match xf {
+ Some(xf) => xf.to_canvas(egui::pos2(x as f32, y as f32)),
+ None => return err("no canvas yet"),
+ }
+ } else {
+ designcraft_geom::Point::new(x, y)
+ };
+ let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base_mods);
+ let clicks = e.get("clicks").and_then(Value::as_u64).map_or(1, |n| n.clamp(1, 255) as u8);
+ if let Err(e) = app.session.pointer(&PointerEvent { kind, pos, mods, clicks }, view) {
+ return err(e);
+ }
+ app.after_engine();
+ last = Some((pos, mods));
+ }
+ ctx.request_repaint();
+ // The tool's cursor where the last event was.
+ let cursor = last.map(|(pos, mods)| app.session.cursor(pos, mods, view));
+ wrap(app.run("document.inspect", json!({})).map(|d| json!({"selection": d["selection"], "tool": app.session.tool_id(), "cursor": cursor})))
+}
+
+/// `ui.click` and `ui.drag`: screen-space pointer input through egui itself, which reaches every widget.
+fn control_click(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
+ let p = &req.params;
+ let s = |k: &str| p.get(k).and_then(Value::as_str);
+ // Screen-space (egui points) pointer input through egui itself: reaches every widget.
+ let (count, steps) = match pointer_counts(p, req.method == "ui.drag", app.control_synthetic.len().saturating_add(app.synthetic.len())) {
+ Ok(counts) => counts,
+ Err(e) => return err(e),
+ };
+ let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32;
+ let button = match s("button") {
+ Some("right") | Some("secondary") => egui::PointerButton::Secondary,
+ Some("middle") => egui::PointerButton::Middle,
+ _ => egui::PointerButton::Primary,
+ };
+ let b = |n: &str| p.get(n).and_then(Value::as_bool).unwrap_or(false);
+ let modifiers =
+ egui::Modifiers { alt: b("alt"), ctrl: b("ctrl"), shift: b("shift"), mac_cmd: b("cmd") && cfg!(target_os = "macos"), command: b("cmd") };
+ let a = egui::pos2(f("x"), f("y"));
+ let end = if req.method == "ui.drag" { egui::pos2(f("toX"), f("toY")) } else { a };
+ app.control_synthetic.push(egui::Event::PointerMoved(a));
+ app.control_synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers });
+ if req.method == "ui.drag" {
+ for i in 1..=steps {
+ let t = i as f32 / steps as f32;
+ app.control_synthetic.push(egui::Event::PointerMoved(a + (end - a) * t));
+ }
+ }
+ app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });
+ for _ in 1..count {
+ app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: true, modifiers });
+ app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });
+ }
+ ctx.request_repaint();
+ ok(Value::Null)
+}
+
fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
let p = &req.params;
let s = |k: &str| p.get(k).and_then(Value::as_str);
@@ -176,46 +253,7 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest
"ui.menu.list" => ok(serde_json::to_value(menus::MENUS).unwrap_or_default()),
"ui.tool.select" => wrap(app.run("tool.select", json!({"tool": s("tool").unwrap_or("")}))),
"ui.tool.list" => ok(serde_json::to_value(designcraft_tools::TOOL_GROUPS).unwrap_or_default()),
- "ui.pointer" => {
- let Some(events) = p.get("events").and_then(Value::as_array) else { return err("missing `events`") };
- let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default();
- let view = app.view_info();
- let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v));
- let mut last = None;
- for e in events {
- let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") {
- "down" => PointerKind::Down,
- "drag" => PointerKind::Drag,
- "up" => PointerKind::Up,
- "move" => PointerKind::Move,
- "doubleclick" | "dblclick" => PointerKind::DoubleClick,
- other => return err(format!("unknown pointer kind `{other}`")),
- };
- let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.0);
- let y = e.get("y").and_then(Value::as_f64).unwrap_or(0.0);
- let pos = if e.get("space").and_then(Value::as_str) == Some("screen") {
- match xf {
- Some(xf) => xf.to_canvas(egui::pos2(x as f32, y as f32)),
- None => return err("no canvas yet"),
- }
- } else {
- designcraft_geom::Point::new(x, y)
- };
- let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base_mods);
- let clicks = e.get("clicks").and_then(Value::as_u64).map_or(1, |n| n.clamp(1, 255) as u8);
- if let Err(e) = app.session.pointer(&PointerEvent { kind, pos, mods, clicks }, view) {
- return err(e);
- }
- app.after_engine();
- last = Some((pos, mods));
- }
- ctx.request_repaint();
- // The tool's cursor where the last event was.
- let cursor = last.map(|(pos, mods)| app.session.cursor(pos, mods, view));
- wrap(
- app.run("document.inspect", json!({})).map(|d| json!({"selection": d["selection"], "tool": app.session.tool_id(), "cursor": cursor})),
- )
- }
+ "ui.pointer" => control_pointer(app, ctx, p),
"ui.key" => {
let Some(k) = s("key").and_then(key_from) else { return err("unknown or missing `key`") };
let b = |n: &str| p.get(n).and_then(Value::as_bool).unwrap_or(false);
@@ -248,44 +286,7 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest
ctx.request_repaint();
ok(Value::Null)
}
- "ui.click" | "ui.drag" => {
- // Screen-space (egui points) pointer input through egui itself: reaches every widget.
- let (count, steps) = match pointer_counts(p, req.method == "ui.drag", app.control_synthetic.len().saturating_add(app.synthetic.len())) {
- Ok(counts) => counts,
- Err(e) => return err(e),
- };
- let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32;
- let button = match s("button") {
- Some("right") | Some("secondary") => egui::PointerButton::Secondary,
- Some("middle") => egui::PointerButton::Middle,
- _ => egui::PointerButton::Primary,
- };
- let b = |n: &str| p.get(n).and_then(Value::as_bool).unwrap_or(false);
- let modifiers = egui::Modifiers {
- alt: b("alt"),
- ctrl: b("ctrl"),
- shift: b("shift"),
- mac_cmd: b("cmd") && cfg!(target_os = "macos"),
- command: b("cmd"),
- };
- let a = egui::pos2(f("x"), f("y"));
- let end = if req.method == "ui.drag" { egui::pos2(f("toX"), f("toY")) } else { a };
- app.control_synthetic.push(egui::Event::PointerMoved(a));
- app.control_synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers });
- if req.method == "ui.drag" {
- for i in 1..=steps {
- let t = i as f32 / steps as f32;
- app.control_synthetic.push(egui::Event::PointerMoved(a + (end - a) * t));
- }
- }
- app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });
- for _ in 1..count {
- app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: true, modifiers });
- app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });
- }
- ctx.request_repaint();
- ok(Value::Null)
- }
+ "ui.click" | "ui.drag" => control_click(app, ctx, req),
"ui.text" => {
let Some(text) = s("text") else { return err("missing `text`") };
// Focused widgets retain the synthetic keyboard route. Document automation uses
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 3fb6a657d..c46a2d343 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -799,6 +799,33 @@ fn edited(d: &Dialog, key: &str) -> bool {
d.fields.contains_key(key) && d.s(key).trim() != shown.trim()
}
+/// The custom baseline grid of Text Frame Options: `None` if nothing about it was edited, else off
+/// (null) or the fields the user changed.
+fn text_frame_baseline_grid(d: &Dialog, bad: &dyn Fn(&str) -> String) -> Result<Option<Value>, String> {
+ let grid_keys = ["customGrid", "gridStart", "gridIncrement", "gridRelativeTo"];
+ if !grid_keys.iter().any(|k| edited(d, k)) {
+ return Ok(None);
+ }
+ if !d.b("customGrid") {
+ return Ok(Some(Value::Null));
+ }
+ let all = edited(d, "customGrid");
+ let mut g = Map::new();
+ if all || edited(d, "gridStart") {
+ g.insert("start".into(), json!(d.m("gridStart").ok_or_else(|| bad("the baseline grid start is not a measure"))?));
+ }
+ if all || edited(d, "gridIncrement") {
+ g.insert(
+ "increment".into(),
+ json!(d.m("gridIncrement").filter(|v| *v > 0.0).ok_or_else(|| bad("the baseline grid increment must be a measure greater than zero"))?),
+ );
+ }
+ if all || edited(d, "gridRelativeTo") {
+ g.insert("relativeTo".into(), json!(d.s("gridRelativeTo")));
+ }
+ Ok(Some(Value::Object(g)))
+}
+
fn confirm_text_frame_options(app: &mut DesignApp, d: &mut Dialog) -> Result<Value, String> {
seed_text_frame_options(app, d);
let d = &*d;
@@ -884,31 +911,8 @@ fn confirm_text_frame_options(app: &mut DesignApp, d: &mut Dialog) -> Result<Val
}
// The custom baseline grid: off, or the fields the user changed (all of them when it is
// turned on, since it shows the document grid's).
- let grid_keys = ["customGrid", "gridStart", "gridIncrement", "gridRelativeTo"];
- if grid_keys.iter().any(|k| edited(d, k)) {
- if d.b("customGrid") {
- let all = edited(d, "customGrid");
- let mut g = Map::new();
- if all || edited(d, "gridStart") {
- g.insert("start".into(), json!(d.m("gridStart").ok_or_else(|| bad("the baseline grid start is not a measure"))?));
- }
- if all || edited(d, "gridIncrement") {
- g.insert(
- "increment".into(),
- json!(
- d.m("gridIncrement")
- .filter(|v| *v > 0.0)
- .ok_or_else(|| bad("the baseline grid increment must be a measure greater than zero"))?
- ),
- );
- }
- if all || edited(d, "gridRelativeTo") {
- g.insert("relativeTo".into(), json!(d.s("gridRelativeTo")));
- }
- p.insert("baselineGrid".into(), Value::Object(g));
- } else {
- p.insert("baselineGrid".into(), Value::Null);
- }
+ if let Some(grid) = text_frame_baseline_grid(d, &bad)? {
+ p.insert("baselineGrid".into(), grid);
}
if p.is_empty() {
return Ok(Value::Null);
@@ -3245,6 +3249,11 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
if d.id != "pdfImport" || !d.b("async") {
app.cancel_pdf_import();
}
+ confirm_part1(app, d)
+}
+
+/// One slice of the dialogs' Apply; later slices take the ids this one doesn't.
+fn confirm_part1(app: &mut DesignApp, d: Dialog) -> Result<Value, String> {
match d.id.as_str() {
"colorTheme" => {
let result = app.run("swatch.addColorTheme", json!({"name": d.s("name"), "colors": d.fields.get("colors")}));
@@ -3361,6 +3370,13 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
}
r
}
+ _ => confirm_part2(app, d),
+ }
+}
+
+/// One slice of the dialogs' Apply; later slices take the ids this one doesn't.
+fn confirm_part2(app: &mut DesignApp, d: Dialog) -> Result<Value, String> {
+ match d.id.as_str() {
"deleteParagraphStyle" => {
let name = d.s("name");
let replace = d.s("replaceWith");
@@ -3476,6 +3492,13 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
}
r
}
+ _ => confirm_part3(app, d),
+ }
+}
+
+/// One slice of the dialogs' Apply; later slices take the ids this one doesn't.
+fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result<Value, String> {
+ match d.id.as_str() {
// Nothing edited: OK leaves the fill or stroke as it was (its swatch and tint).
"colorPicker" if !d.b("edited") => Ok(Value::Null),
"colorPicker" => {
@@ -3489,7 +3512,12 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
app.run("object.color", json!({"color": color, "target": d.s("target"), "text": d.b("text")}))
}
"layerOptions" => {
- let hidden: Vec<Value> = d.fields.get("layers").and_then(Value::as_array).map(|a| a.iter().filter(|l| l["visible"] == false).map(|l| l["name"].clone()).collect()).unwrap_or_default();
+ let hidden: Vec<Value> = d
+ .fields
+ .get("layers")
+ .and_then(Value::as_array)
+ .map(|a| a.iter().filter(|l| l["visible"] == false).map(|l| l["name"].clone()).collect())
+ .unwrap_or_default();
// A dialog opened without the menu's fields has no `useDefaults` at all: confirming it
// with no layer unticked resets file defaults, as it did before all-on existed, rather
// than making every layer explicitly visible. Only an explicit `false` means all-on.
@@ -3538,7 +3566,11 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
"pages": pages, "spreads": d.b("spreads"), "marks": d.b("marks"), "bleed": d.b("bleed")}),
)?;
let printer = r["printer"].as_str().unwrap_or_else(|| crate::i18n::tr(&app.ui.language, "the default printer"));
- app.status(crate::i18n::tr(&app.ui.language, "Sent {count} page(s) to {printer}").replace("{count}", &r["pages"].to_string()).replace("{printer}", printer));
+ app.status(
+ crate::i18n::tr(&app.ui.language, "Sent {count} page(s) to {printer}")
+ .replace("{count}", &r["pages"].to_string())
+ .replace("{printer}", printer),
+ );
Ok(r)
}
"epubExport" => {
@@ -3605,6 +3637,13 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
None => Ok(Value::Null),
}
}
+ _ => confirm_part4(app, d),
+ }
+}
+
+/// One slice of the dialogs' Apply; later slices take the ids this one doesn't.
+fn confirm_part4(app: &mut DesignApp, d: Dialog) -> Result<Value, String> {
+ match d.id.as_str() {
"preferences" => {
let mut prefs = json!({"scaleStrokes": d.b("scaleStrokes"), "dimensionsIncludeStroke": d.b("dimensionsIncludeStroke"), "transformationsAreTotals": d.b("transformationsAreTotals"), "absolutePageNumbers": d.b("absolutePageNumbers"), "highlightHj": d.b("highlightHj"), "highlightKeeps": d.b("highlightKeeps"), "highlightCustomTracking": d.b("highlightCustomTracking"), "highlightSubstitutedFonts": d.b("highlightSubstitutedFonts"), "richBlackOutput": d.b("richBlackOutput"), "typographersQuotes": d.b("typographersQuotes"), "showFontNamesInEnglish": d.b("showFontNamesInEnglish"), "smartTextReflow": d.b("smartTextReflow"),
"autocorrect": d.b("autocorrect"), "showAddedText": d.b("showAddedText"), "showNoteAnchors": d.b("showNoteAnchors"),
@@ -3710,6 +3749,13 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
doc["glyphFallback"] = json!(d.b("glyphFallback"));
app.run("document.preferences", doc)
}
+ _ => confirm_part5(app, d),
+ }
+}
+
+/// One slice of the dialogs' Apply; later slices take the ids this one doesn't.
+fn confirm_part5(app: &mut DesignApp, d: Dialog) -> Result<Value, String> {
+ match d.id.as_str() {
"newWorkspace" => app.run(
"window.newWorkspace",
json!({"name": d.s("name"), "panelLocations": d.b("panelLocations"), "menuCustomization": d.b("menuCustomization")}),
@@ -3804,6 +3850,13 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
app.ui.dialog = Some(d);
result
}
+ _ => confirm_part6(app, d),
+ }
+}
+
+/// One slice of the dialogs' Apply; later slices take the ids this one doesn't.
+fn confirm_part6(app: &mut DesignApp, d: Dialog) -> Result<Value, String> {
+ match d.id.as_str() {
"insertXref" => {
let format = d.s("format");
let target = d.s("target");
diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs
index f0486b97c..7ffbbee5a 100644
--- a/crates/ui-egui/src/icons.rs
+++ b/crates/ui-egui/src/icons.rs
@@ -74,12 +74,11 @@ fn arrow(pen: &Pen, hollow: bool) {
}
}
-/// Paint icon `name` into `r`.
-pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {
- let mut pen = Pen { p, r, c, w: 1.3 };
+/// Icons of one family: paints `name` and says whether it is one of them.
+fn paint_tools(pen: &mut Pen, name: &str) -> bool {
match name {
- "tool-selection" => arrow(&pen, false),
- "tool-direct" => arrow(&pen, true),
+ "tool-selection" => arrow(pen, false),
+ "tool-direct" => arrow(pen, true),
"tool-page" => {
pen.closed(&[(5.0, 3.0), (12.0, 3.0), (15.0, 6.0), (15.0, 17.0), (5.0, 17.0)]);
pen.line(&[(12.0, 3.0), (12.0, 6.0), (15.0, 6.0)]);
@@ -156,14 +155,14 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {
}
"tool-scale" => {
// A small square grown into a larger one from their shared corner.
- Pen { p, r, c: c.gamma_multiply(0.45), w: 1.0 }.rect(3.0, 3.0, 17.0, 17.0);
+ Pen { p: pen.p, r: pen.r, c: pen.c.gamma_multiply(0.45), w: 1.0 }.rect(3.0, 3.0, 17.0, 17.0);
pen.rect(3.0, 10.0, 10.0, 17.0);
pen.line(&[(10.0, 10.0), (15.0, 5.0)]);
pen.line(&[(11.5, 5.0), (15.0, 5.0), (15.0, 8.5)]);
}
"tool-shear" => {
// A rectangle slanted into a parallelogram along its base.
- Pen { p, r, c: c.gamma_multiply(0.45), w: 1.0 }.rect(3.0, 8.0, 13.0, 17.0);
+ Pen { p: pen.p, r: pen.r, c: pen.c.gamma_multiply(0.45), w: 1.0 }.rect(3.0, 8.0, 13.0, 17.0);
pen.closed(&[(7.0, 8.0), (17.0, 8.0), (13.0, 17.0), (3.0, 17.0)]);
pen.line(&[(7.0, 4.0), (16.0, 4.0)]);
pen.line(&[(13.5, 2.0), (16.0, 4.0), (13.5, 6.0)]);
@@ -192,7 +191,7 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {
"tool-gradient" | "tool-gradient-feather" => {
for i in 0..6 {
let a = 30 + i * 35;
- let pc = Pen { p, r, c: c.gamma_multiply(a as f32 / 255.0 * 1.2), w: 1.0 };
+ let pc = Pen { p: pen.p, r: pen.r, c: pen.c.gamma_multiply(a as f32 / 255.0 * 1.2), w: 1.0 };
pc.frect(3.0 + i as f32 * 2.33, 4.0, 3.0 + (i + 1) as f32 * 2.33, 16.0);
}
pen.rect(3.0, 4.0, 17.0, 16.0);
@@ -283,7 +282,7 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {
}
"panel-gradient" => {
for i in 0..7 {
- let pc = Pen { p, r, c: c.gamma_multiply(0.15 + i as f32 * 0.14), w: 1.0 };
+ let pc = Pen { p: pen.p, r: pen.r, c: pen.c.gamma_multiply(0.15 + i as f32 * 0.14), w: 1.0 };
pc.frect(3.0 + i as f32 * 2.0, 5.0, 5.0 + i as f32 * 2.0, 15.0);
}
}
@@ -331,6 +330,14 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {
pen.line(&[(12.5, 10.0), (11.0, 8.5)]);
pen.line(&[(12.5, 10.0), (11.0, 11.5)]);
}
+ _ => return false,
+ }
+ true
+}
+
+/// Icons of one family: paints `name` and says whether it is one of them.
+fn paint_panels(pen: &mut Pen, name: &str) -> bool {
+ match name {
"objdistribute-v" => {
pen.frect(5.0, 2.5, 15.0, 6.0);
pen.frect(5.0, 14.0, 15.0, 17.5);
@@ -600,6 +607,14 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {
}
}
}
+ _ => return false,
+ }
+ true
+}
+
+/// Icons of one family: paints `name` and says whether it is one of them.
+fn paint_shapes(pen: &mut Pen, name: &str) -> bool {
+ match name {
// Flex Layout panel (original drawings): direction arrows, wrap, justification, spacing.
"flex-right" | "flex-left" | "flex-down" | "flex-up" => {
let pts: [(f32, f32); 5] = match name {
@@ -748,6 +763,14 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {
pen.line(&[(10.0, 3.0), (10.0, 13.0)]);
pen.line(&[(6.5, 9.5), (10.0, 13.0), (13.5, 9.5)]);
}
+ _ => return false,
+ }
+ true
+}
+
+/// Icons of one family: paints `name` and says whether it is one of them.
+fn paint_page(pen: &mut Pen, name: &str) -> bool {
+ match name {
"orient-portrait" => {
pen.rect(5.5, 3.0, 14.5, 17.0);
pen.fcircle(10.0, 8.0, 1.8);
@@ -911,6 +934,14 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {
pen.line(&[(15.5, 2.0), (15.5, 18.0)]);
}
}
+ _ => return false,
+ }
+ true
+}
+
+/// Icons of one family: paints `name` and says whether it is one of them.
+fn paint_text(pen: &mut Pen, name: &str) -> bool {
+ match name {
"text-columns" => {
pen.rect(2.5, 3.5, 17.5, 16.5);
pen.line(&[(7.5, 3.5), (7.5, 16.5)]);
@@ -1147,9 +1178,21 @@ pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {
pen.rect(3.0, 4.0, 17.0, 16.0);
pen.line(&[(3.0, 7.0), (17.0, 7.0)]);
}
- _ => {
- pen.rect(4.0, 4.0, 16.0, 16.0);
- }
+ _ => return false,
+ }
+ true
+}
+
+/// Paint icon `name` into `r`.
+pub fn paint(p: &Painter, r: Rect, name: &str, c: Color32) {
+ let mut pen = Pen { p, r, c, w: 1.3 };
+ if !(paint_tools(&mut pen, name)
+ || paint_panels(&mut pen, name)
+ || paint_shapes(&mut pen, name)
+ || paint_page(&mut pen, name)
+ || paint_text(&mut pen, name))
+ {
+ pen.rect(4.0, 4.0, 16.0, 16.0);
}
}
diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs
index 4784ff32f..6a85d6fa9 100644
--- a/crates/ui-egui/src/menus/bar.rs
+++ b/crates/ui-egui/src/menus/bar.rs
@@ -1,5 +1,5 @@
use super::tree::{menu_items, menu_tree};
-use super::*;
+use super::{DesignApp, Item};
/// 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.
diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs
index fa4076418..a8ce474df 100644
--- a/crates/ui-egui/src/menus/context.rs
+++ b/crates/ui-egui/src/menus/context.rs
@@ -1,6 +1,6 @@
use super::bar::{menu_bar_submenu, menu_column, menu_max_height};
use super::tree::{menu_tree, parse_entries};
-use super::*;
+use super::{DesignApp, Item};
/// What a right-click on the canvas opens a menu for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
diff --git a/crates/ui-egui/src/menus/export.rs b/crates/ui-egui/src/menus/export.rs
index 4f3222aa3..56014c25c 100644
--- a/crates/ui-egui/src/menus/export.rs
+++ b/crates/ui-egui/src/menus/export.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{DesignApp, Value, json};
pub(super) fn download_document(app: &mut DesignApp) -> Result<Value, String> {
let name = app.session.active().map(|d| format!("{}.designcraft", d.doc.title)).ok_or("no document")?;
diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs
index 32d82be8f..d11b8deaa 100644
--- a/crates/ui-egui/src/menus/invoke.rs
+++ b/crates/ui-egui/src/menus/invoke.rs
@@ -1,6 +1,6 @@
use super::state::waits_for_ime;
use super::ui_commands::ui_label;
-use super::*;
+use super::{DesignApp, Value, json};
/// Close document `index` (the active one when `None`) the way the user asks for it: with the
/// tab's ×, File ▸ Close or its shortcut. A document with unsaved changes asks first, because
diff --git a/crates/ui-egui/src/menus/keys.rs b/crates/ui-egui/src/menus/keys.rs
index bb7203168..b7e1fa539 100644
--- a/crates/ui-egui/src/menus/keys.rs
+++ b/crates/ui-egui/src/menus/keys.rs
@@ -1,5 +1,5 @@
use super::invoke::activate;
-use super::*;
+use super::{DesignApp, ScreenMode, Value, json};
/// The command a paste event stands for besides plain Paste. egui-winit turns every ⌘+V chord into
/// `Event::Paste` with the clipboard's text and drops the key press, and the keymap reads the chord
diff --git a/crates/ui-egui/src/menus/quick_apply.rs b/crates/ui-egui/src/menus/quick_apply.rs
index a7656b1f4..ec91a2c8a 100644
--- a/crates/ui-egui/src/menus/quick_apply.rs
+++ b/crates/ui-egui/src/menus/quick_apply.rs
@@ -1,6 +1,6 @@
use super::state::{shortcut_of, shortcut_text};
use super::ui_commands::{CJK_ONLY, UI_COMMANDS, shown};
-use super::*;
+use super::{DesignApp, Value, json};
/// Quick Apply (⌘Return): the document's styles and every command, searched by name.
pub fn palette(app: &mut DesignApp, ctx: &egui::Context) {
diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs
index b0bacc00c..1c6d56366 100644
--- a/crates/ui-egui/src/menus/run.rs
+++ b/crates/ui-egui/src/menus/run.rs
@@ -3,7 +3,7 @@ use super::invoke::guide_spread;
use super::state::{is_window_control, window_control_available};
use super::tables::{CLASSIC_GROUPS, TYPOGRAPHY_GROUPS, workspace_open_panel};
use super::tree::recent_label;
-use super::*;
+use super::{DesignApp, ScreenMode, Value, json};
/// Type › Tabs: float the Tabs panel (placed above the selected text frame) or close it.
fn toggle_tabs_panel(app: &mut DesignApp) {
@@ -33,11 +33,21 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value
if let Some(result) = crate::panel_docking::command(app, id, p) {
return Some(result);
}
- let rect = app.canvas_rect;
- let flag = |b: &mut bool| {
- *b = !*b;
- Ok(json!(*b))
- };
+ run_ui_part1(app, id, p)
+ .or_else(|| run_ui_part2(app, id, p))
+ .or_else(|| run_ui_part3(app, id, p))
+ .or_else(|| run_ui_part4(app, id, p))
+ .or_else(|| run_ui_part5(app, id, p))
+}
+
+/// Toggle `b`, answering its new value.
+fn flag(b: &mut bool) -> Result<Value, String> {
+ *b = !*b;
+ Ok(json!(*b))
+}
+
+/// One slice of the UI commands: `None` if `id` isn't one of them.
+fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
Some(match id {
"window.minimize" => {
app.pending_window_commands.push(egui::ViewportCommand::Minimized(true));
@@ -254,6 +264,13 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value
}
Ok(Value::Null)
}
+ _ => return None,
+ })
+}
+
+/// One slice of the UI commands: `None` if `id` isn't one of them.
+fn run_ui_part2(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
+ Some(match id {
"app.loadParagraphStyles" => app.pick_styles("paragraph"),
"app.loadCharacterStyles" => app.pick_styles("character"),
"app.loadTextStyles" => app.pick_styles(""),
@@ -488,6 +505,14 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value
app.ui.dialog = Some(crate::dialogs::Dialog::new("preferences", f));
Ok(Value::Null)
}
+ _ => return None,
+ })
+}
+
+/// One slice of the UI commands: `None` if `id` isn't one of them.
+fn run_ui_part3(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
+ let rect = app.canvas_rect;
+ Some(match id {
"view.zoomIn" | "view.zoomOut" => {
if let Some(r) = rect {
crate::canvas::zoom_at(app, r.center(), if id == "view.zoomIn" { 1.5 } else { 1.0 / 1.5 });
@@ -639,6 +664,13 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value
app.canvas.shown = None;
r.map(|v| v["rotation"].clone())
}
+ _ => return None,
+ })
+}
+
+/// One slice of the UI commands: `None` if `id` isn't one of them.
+fn run_ui_part4(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
+ Some(match id {
"view.proofColors" => {
app.ui.proof_colors = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.proof_colors);
app.canvas.shown = None;
@@ -817,6 +849,13 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value
"zone": ui.snap_zone,
}))
}
+ _ => return None,
+ })
+}
+
+/// One slice of the UI commands: `None` if `id` isn't one of them.
+fn run_ui_part5(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
+ Some(match id {
"app.formattingAffectsText" => {
app.ui.formatting_affects_text = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.formatting_affects_text);
Ok(json!({"on": app.ui.formatting_affects_text}))
diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs
index 1dcade4a3..f9e78c28f 100644
--- a/crates/ui-egui/src/menus/state.rs
+++ b/crates/ui-egui/src/menus/state.rs
@@ -1,6 +1,6 @@
use super::invoke::TEXT_FIELD_COMMANDS;
use super::ui_commands::ui_label;
-use super::*;
+use super::{DesignApp, Value};
/// Commands that act on the text being typed wait while an IME composes at the caret (its marked
/// text isn't typed yet): Undo and Redo (the native menu takes ⌘Z ahead of the IME), the clipboard
diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs
index 06fdcb30c..b711b8376 100644
--- a/crates/ui-egui/src/menus/tree.rs
+++ b/crates/ui-egui/src/menus/tree.rs
@@ -3,7 +3,7 @@ use super::invoke::activate;
use super::state::{checked, menu_enabled, shortcut_label};
use super::tables::{MENUS, WORKSPACES};
use super::ui_commands::shown;
-use super::*;
+use super::{DesignApp, Item, Value, cmd_item, json};
pub(super) fn parse_entries(entries: &[&str]) -> Vec<Item> {
let mut out = Vec::new();
diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs
index 6d14db1c8..eb4094e37 100644
--- a/crates/ui-egui/src/menus/ui_commands.rs
+++ b/crates/ui-egui/src/menus/ui_commands.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::DesignApp;
/// Menu and Quick Apply entries that only CJK typesetting uses: hidden unless
/// [`crate::cjk_features`]. The commands still run from scripts, the control channel and MCP.
diff --git a/crates/ui-egui/src/panels/font_menu.rs b/crates/ui-egui/src/panels/font_menu.rs
index 1ce58506f..5f349b2e4 100644
--- a/crates/ui-egui/src/panels/font_menu.rs
+++ b/crates/ui-egui/src/panels/font_menu.rs
@@ -217,8 +217,7 @@ fn preview(
ui: &Ui,
fonts: &designcraft_fonts::ScopedFonts<'static>,
scope: u32,
- family: &str,
- style: &str,
+ (family, style): (&str, &str),
text: &str,
size: f32,
color: Color32,
@@ -536,6 +535,51 @@ pub fn font_menu_header<'a>(app: &'a mut DesignApp, ui: &mut Ui, menu: &'a [Fami
FontMenu { app, menu, current, st, rows, highlighted_row, loading, sample, row_h, sample_size, down, up, escape, pick }
}
+/// A family row's favourite star and (for a family of several styles) its open/close arrow.
+/// `flags`: favourite, expanded, has an arrow. Says which of the two was clicked.
+fn star_and_arrow(
+ ui: &Ui,
+ p: &egui::Painter,
+ r: Rect,
+ (f, recent): (&String, bool),
+ (fav, open, has_arrow): (bool, bool, bool),
+ t: &Tokens,
+ arrow_label: &str,
+) -> (bool, bool) {
+ let cy = r.center().y;
+ let star = Rect::from_center_size(pos2(r.min.x + 10.0, cy), vec2(16.0, 16.0));
+ let sr = ui.interact(star, ui.scope_id().with(("fav", f, recent)), Sense::click());
+ paint_star(p, star.center(), 6.5, fav, if fav { t.accent } else { t.text_dim });
+ let mut arrow_hit = false;
+ // The arrow opens a family of several styles.
+ if has_arrow {
+ let arrow = Rect::from_center_size(pos2(r.min.x + 28.0, cy), vec2(16.0, 16.0));
+ let ar = ui.interact(arrow, ui.scope_id().with(("open", f)), Sense::click());
+ ar.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, arrow_label));
+ crate::icons::paint(p, arrow.shrink(2.0), if open { "chevron-down" } else { "chevron-right" }, t.icon);
+ arrow_hit = ar.clicked();
+ }
+ (sr.clicked(), arrow_hit)
+}
+
+/// Removes `f` from the favourites if it is one, else adds it.
+fn toggle_favorite(favs: &mut Vec<String>, f: String) {
+ if favs.contains(&f) {
+ favs.retain(|x| *x != f);
+ } else {
+ favs.push(f);
+ }
+}
+
+/// Recently used fonts, newest first.
+fn remember_recent(app: &mut DesignApp, family: &str) {
+ let mut recent = app.session.prefs.recent_fonts.clone();
+ recent.retain(|f| f != family);
+ recent.insert(0, family.to_string());
+ recent.truncate(RECENT);
+ let _ = app.run("prefs.set", json!({ "recentFonts": recent }));
+}
+
/// The Font menu's rows, under [`font_menu_header`]. Returns the font picked.
pub fn font_menu_list(ui: &mut Ui, m: FontMenu<'_>) -> Option<FontPick> {
let FontMenu { app, menu, current, mut st, rows, highlighted_row, loading, sample, row_h, sample_size, down, up, escape, mut pick } = m;
@@ -550,10 +594,8 @@ pub fn font_menu_list(ui: &mut Ui, m: FontMenu<'_>) -> Option<FontPick> {
let mut toggle_expand = None;
let mut toggle_fav = None;
let mut similar = None;
- if loading {
- crate::rtl::label(ui, egui::RichText::new(tr("Loading fonts…")).color(t.text_dim));
- } else if rows.is_empty() {
- crate::rtl::label(ui, egui::RichText::new(tr("No fonts match")).color(t.text_dim));
+ if let Some(note) = if loading { Some("Loading fonts…") } else { rows.is_empty().then_some("No fonts match") } {
+ crate::rtl::label(ui, egui::RichText::new(tr(note)).color(t.text_dim));
}
for (i, row) in rows.iter().enumerate() {
let (family, style, recent) = match row {
@@ -597,28 +639,17 @@ pub fn font_menu_list(ui: &mut Ui, m: FontMenu<'_>) -> Option<FontPick> {
let cy = r.center().y;
let mut handled = false;
if style.is_none() {
- // Favourite star.
- let star = Rect::from_center_size(pos2(r.min.x + 10.0, cy), vec2(16.0, 16.0));
- let fav = favs.contains(f);
- let sr = ui.interact(star, ui.scope_id().with(("fav", f, recent)), Sense::click());
- paint_star(&p, star.center(), 6.5, fav, if fav { t.accent } else { t.text_dim });
- if sr.clicked() {
+ let expanded = st.expanded.contains(f);
+ let arrow_label = tr(if expanded { "Hide Styles" } else { "Show Styles" });
+ let flags = (favs.contains(f), expanded, m.styles.len() > 1 && !recent);
+ let (star_hit, arrow_hit) = star_and_arrow(ui, &p, r, (f, recent), flags, &t, arrow_label);
+ if star_hit {
toggle_fav = Some(f.clone());
handled = true;
}
- // The arrow opens a family of several styles.
- if m.styles.len() > 1 && !recent {
- let arrow = Rect::from_center_size(pos2(r.min.x + 28.0, cy), vec2(16.0, 16.0));
- let ar = ui.interact(arrow, ui.scope_id().with(("open", f)), Sense::click());
- ar.widget_info(|| {
- egui::WidgetInfo::labeled(egui::Role::Button, true, tr(if st.expanded.contains(f) { "Hide Styles" } else { "Show Styles" }))
- });
- let open = st.expanded.contains(f);
- crate::icons::paint(&p, arrow.shrink(2.0), if open { "chevron-down" } else { "chevron-right" }, t.icon);
- if ar.clicked() {
- toggle_expand = Some(f.clone());
- handled = true;
- }
+ if arrow_hit {
+ toggle_expand = Some(f.clone());
+ handled = true;
}
}
// Name (and how many styles), then the sample in the face, then the format.
@@ -628,7 +659,7 @@ pub fn font_menu_list(ui: &mut Ui, m: FontMenu<'_>) -> Option<FontPick> {
let preview_x = r.min.x + (r.width() * 0.42).max(190.0);
let icons_x = r.max.x - 52.0;
let face_style = style.map_or_else(|| regular(&m.styles), str::to_string);
- let tex = preview(ui, &fonts, scope, f, &face_style, &sample, sample_size, t.text);
+ let tex = preview(ui, &fonts, scope, (f, &face_style), &sample, sample_size, t.text);
let size = tex.size_vec2() / ui.ctx().pixels_per_point();
let shown = Rect::from_min_size(pos2(preview_x, cy - size.y / 2.0), size);
let clip = Rect::from_min_max(pos2(preview_x, r.min.y), pos2(icons_x - 6.0, r.max.y));
@@ -659,11 +690,7 @@ pub fn font_menu_list(ui: &mut Ui, m: FontMenu<'_>) -> Option<FontPick> {
st.expanded.insert(f);
}
if let Some(f) = toggle_fav {
- if favs.contains(&f) {
- favs.retain(|x| *x != f);
- } else {
- favs.push(f);
- }
+ toggle_favorite(&mut favs, f);
favs_changed = true;
}
if let Some(f) = similar {
@@ -675,12 +702,7 @@ pub fn font_menu_list(ui: &mut Ui, m: FontMenu<'_>) -> Option<FontPick> {
let _ = app.run("prefs.set", json!({ "favoriteFonts": favs }));
}
if let Some(p) = &pick {
- // Recently used, newest first.
- let mut recent = app.session.prefs.recent_fonts.clone();
- recent.retain(|f| *f != p.family);
- recent.insert(0, p.family.clone());
- recent.truncate(RECENT);
- let _ = app.run("prefs.set", json!({ "recentFonts": recent }));
+ remember_recent(app, &p.family);
ui.close();
} else if escape {
ui.close();
diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs
index 856c53e90..22f93ae8c 100644
--- a/crates/ui-egui/src/panels/pages.rs
+++ b/crates/ui-egui/src/panels/pages.rs
@@ -54,7 +54,7 @@ fn thumb(app: &mut DesignApp, ctx: &egui::Context, of: ThumbOf, h: f32) -> Optio
let view = designcraft_geom::Affine::scale(scale) * designcraft_geom::Affine::translate(-b.origin().to_vec2());
let o = designcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..opts };
let placed = [designcraft_render::Placed { spread: SpreadRef::Parent(i), xf: designcraft_geom::Affine::IDENTITY }];
- (r.render(&st.doc, &app.session.cache, &placed, w, h, view, &o), format!("thumbp{}", id.0))
+ (r.render(&st.doc, &app.session.cache, &placed, (w, h), view, &o), format!("thumbp{}", id.0))
}
};
let ci = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels);
diff --git a/crates/ui-egui/src/panels/properties/document.rs b/crates/ui-egui/src/panels/properties/document.rs
index 2e15324e7..0a7fdbc5a 100644
--- a/crates/ui-egui/src/panels/properties/document.rs
+++ b/crates/ui-egui/src/panels/properties/document.rs
@@ -1,4 +1,7 @@
-use super::*;
+use super::{
+ DesignApp, FIELD_H, NumField, Rect, Sense, Tokens, Ui, Value, block, button_pair, divider, dropdown, full_width, icon_toggle, icons, json,
+ number, outline_button, place, pos2, rule, section, section_row, set_temp_bool, sub, temp_bool, units, vec2, widgets,
+};
// ---------------------------------------------------------------- No Selection
@@ -129,6 +132,46 @@ pub(super) fn page_sections(app: &mut DesignApp, ui: &mut Ui, page: usize) {
}
}
+/// Page count field: add pages after the last one, or delete from the end, to reach `nv` (from `n`).
+fn resize_document(app: &mut DesignApp, n: usize, nv: f64) {
+ let want = (nv.round() as usize).clamp(1, 9999);
+ if want > n {
+ let _ = app.run("layout.pages.insert", json!({"count": want - n, "after": n - 1}));
+ } else if want < n {
+ let _ = app.run("layout.pages.delete", json!({"pages": (want..n).collect::<Vec<_>>()}));
+ }
+}
+
+/// The margins after field `k` (top, bottom, outside, inside) is set to `nv`; all four when linked.
+fn edited_margins(mut m: designcraft_doc::Margins, linked: bool, k: usize, nv: f64) -> designcraft_doc::Margins {
+ if linked {
+ return designcraft_doc::Margins { top: nv, bottom: nv, inside: nv, outside: nv };
+ }
+ match k {
+ 0 => m.top = nv,
+ 1 => m.bottom = nv,
+ 2 => m.outside = nv,
+ _ => m.inside = nv,
+ }
+ m
+}
+
+/// The page-size preset menu; the width and height of the preset chosen.
+fn page_preset_menu(ui: &mut Ui, pw: f64, ph: f64) -> Option<(f64, f64)> {
+ let mut preset = None;
+ let resp = dropdown(ui, preset_name(pw, ph), 93.0);
+ egui::Popup::menu(&resp).show(|ui| {
+ ui.set_min_width(140.0);
+ for p in PAGE_PRESETS {
+ if ui.selectable_label(preset_name(pw, ph) == p.0, p.0).clicked() {
+ preset = Some((p.1, p.2));
+ ui.close();
+ }
+ }
+ });
+ preset
+}
+
pub(super) fn document_sections(app: &mut DesignApp, ui: &mut Ui) {
let u = units(app);
let Some(st) = app.session.active() else { return };
@@ -137,19 +180,7 @@ pub(super) fn document_sections(app: &mut DesignApp, ui: &mut Ui) {
section(ui, crate::i18n::tr(&app.ui.language, "Document"), true);
// Preset dropdown + orientation.
let b = block(ui, FIELD_H);
- let mut preset = None;
- place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| {
- let resp = dropdown(ui, preset_name(pw, ph), 93.0);
- egui::Popup::menu(&resp).show(|ui| {
- ui.set_min_width(140.0);
- for p in PAGE_PRESETS {
- if ui.selectable_label(preset_name(pw, ph) == p.0, p.0).clicked() {
- preset = Some((p.1, p.2));
- ui.close();
- }
- }
- });
- });
+ let preset = place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| page_preset_menu(ui, pw, ph));
let landscape = pw > ph;
let mut orient = None;
place(ui, sub(b, 126.0, 0.0, 52.0, FIELD_H), |ui| {
@@ -185,12 +216,7 @@ pub(super) fn document_sections(app: &mut DesignApp, ui: &mut Ui) {
icons::paint(ui.painter(), sub(b, 127.0, 2.0, 17.0, 17.0), "page-count", t.icon);
let nv = place(ui, sub(b, 150.0, 0.0, 68.0, FIELD_H), |ui| number(ui, "pagecount", Some(n as f64), "", 68.0, 0));
if let Some(nv) = nv {
- let want = (nv.round() as usize).clamp(1, 9999);
- if want > n {
- let _ = app.run("layout.pages.insert", json!({"count": want - n, "after": n - 1}));
- } else if want < n {
- let _ = app.run("layout.pages.delete", json!({"pages": (want..n).collect::<Vec<_>>()}));
- }
+ resize_document(app, n, nv);
}
let mut facing = d.settings.facing_pages;
let changed = place(ui, sub(b, 126.0, 26.0, 100.0, FIELD_H), |ui| {
@@ -229,18 +255,7 @@ pub(super) fn document_sections(app: &mut DesignApp, ui: &mut Ui) {
NumField::measure(tip, Some(v), u).width(73.0).spinner().range(0.0, 8000.0).show(ui)
});
if let Some(nv) = nv {
- let mut m = p.margins;
- if linked {
- m = designcraft_doc::Margins { top: nv, bottom: nv, inside: nv, outside: nv };
- } else {
- match k {
- 0 => m.top = nv,
- 1 => m.bottom = nv,
- 2 => m.outside = nv,
- _ => m.inside = nv,
- }
- }
- set = Some(m);
+ set = Some(edited_margins(p.margins, linked, k, nv));
}
}
let lr = sub(b, 99.0, 12.5, 22.0, FIELD_H);
diff --git a/crates/ui-egui/src/panels/properties/flex.rs b/crates/ui-egui/src/panels/properties/flex.rs
index ec4c95762..591ce4cfd 100644
--- a/crates/ui-egui/src/panels/properties/flex.rs
+++ b/crates/ui-egui/src/panels/properties/flex.rs
@@ -1,5 +1,8 @@
use super::object::preview_dropdown;
-use super::*;
+use super::{
+ DesignApp, FIELD_H, NumField, Rect, Sense, Stroke, StrokeKind, Tokens, Ui, Value, block, icons, json, place, section, set_temp_bool, sub,
+ temp_bool, units, vec2, widgets,
+};
// ---------------------------------------------------------------- Flex Layout
diff --git a/crates/ui-egui/src/panels/properties/links.rs b/crates/ui-egui/src/panels/properties/links.rs
index 3909f3094..5084b6cf1 100644
--- a/crates/ui-egui/src/panels/properties/links.rs
+++ b/crates/ui-egui/src/panels/properties/links.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{DesignApp, Sense, Tokens, Value, divider, json, sel_info, units, vec2};
/// Links: status (missing / modified / embedded), page and effective resolution of every placed
/// graphic and linked text file; Relink, Go To Link, Update Link, Embed Link for the chosen row.
diff --git a/crates/ui-egui/src/panels/properties/object.rs b/crates/ui-egui/src/panels/properties/object.rs
index af750f511..3819894fe 100644
--- a/crates/ui-egui/src/panels/properties/object.rs
+++ b/crates/ui-egui/src/panels/properties/object.rs
@@ -1,4 +1,7 @@
-use super::*;
+use super::{
+ CornerShape, DesignApp, FIELD_H, NumField, Rect, SelInfo, Sense, Stroke, StrokeKind, Tokens, Ui, Unit, Value, block, full_width, icon_toggle,
+ icons, json, link_label, measure, more_options, outline_button, place, pos2, set_temp_bool, show_panel, sub, temp_bool, units, vec2, widgets,
+};
// ---------------------------------------------------------------- Objects
diff --git a/crates/ui-egui/src/panels/properties/object_panels.rs b/crates/ui-egui/src/panels/properties/object_panels.rs
index 6de8daaaf..9d02bec3f 100644
--- a/crates/ui-egui/src/panels/properties/object_panels.rs
+++ b/crates/ui-egui/src/panels/properties/object_panels.rs
@@ -1,4 +1,7 @@
-use super::*;
+use super::{
+ Arrowhead, Cap, DesignApp, Join, Sense, Stroke, StrokeAlign, StrokeType, Tokens, Ui, Value, caption, divider, icon_toggle, icons, json, measure,
+ number, pos2, sel_info, text_attrs, units, vec2, widgets,
+};
/// Stroke panel: weight, cap, miter limit, join, alignment, type, arrowheads, gap colour.
pub fn stroke_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
diff --git a/crates/ui-egui/src/panels/properties/text.rs b/crates/ui-egui/src/panels/properties/text.rs
index 96c0a7e69..342ad8dda 100644
--- a/crates/ui-egui/src/panels/properties/text.rs
+++ b/crates/ui-egui/src/panels/properties/text.rs
@@ -1,6 +1,9 @@
use super::object::swatch_menu;
use super::typography::{para_field_min, show_typography_panel};
-use super::*;
+use super::{
+ Align, DesignApp, FIELD_H, NumField, Rect, Sense, Stroke, StrokeKind, Tokens, Ui, Value, block, full_width, icon_toggle, icons, json, link_label,
+ more_options, outline_button, place, pos2, section, set_temp_bool, show_panel, sub, temp_bool, text_attrs, units, vec2, widgets,
+};
// ---------------------------------------------------------------- Text
diff --git a/crates/ui-egui/src/panels/properties/typography.rs b/crates/ui-egui/src/panels/properties/typography.rs
index ce823f5db..d4959c406 100644
--- a/crates/ui-egui/src/panels/properties/typography.rs
+++ b/crates/ui-egui/src/panels/properties/typography.rs
@@ -1,5 +1,8 @@
use super::text::{half_field, half_field_or_clear, kerning_control, language_menu};
-use super::*;
+use super::{
+ Align, DesignApp, FIELD_H, NumField, Sense, Tokens, Ui, Value, block, caption, full_width, json, number, place, pos2, sub, text_attrs, units,
+ vec2, widgets,
+};
pub fn character_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
let Some(a) = text_attrs(app) else {
diff --git a/crates/ui-egui/src/panels/styles.rs b/crates/ui-egui/src/panels/styles.rs
index ea13bdb40..ff45e6327 100644
--- a/crates/ui-egui/src/panels/styles.rs
+++ b/crates/ui-egui/src/panels/styles.rs
@@ -46,12 +46,12 @@ fn list(app: &mut DesignApp, ui: &mut egui::Ui, para: bool) {
if para && n == designcraft_doc::NO_PARA_STYLE {
continue;
}
- style_row(app, ui, para, n, current.as_deref(), overrides > 0, &groups, &t);
+ style_row(app, ui, para, n, (current.as_deref(), overrides > 0), &groups, &t);
}
for g in &groups {
egui::CollapsingHeader::new(g.as_str()).id_salt(("style_group", para, g)).default_open(true).show(ui, |ui| {
for n in names.iter().filter(|n| n.rsplit_once('/').is_some_and(|(x, _)| x == g)) {
- style_row(app, ui, para, n, current.as_deref(), overrides > 0, &groups, &t);
+ style_row(app, ui, para, n, (current.as_deref(), overrides > 0), &groups, &t);
}
});
}
@@ -107,7 +107,15 @@ pub fn character(app: &mut DesignApp, ui: &mut egui::Ui) {
/// One style in the list: click applies (⌥ clears overrides), double-click edits,
/// right-click: edit, apply, break link, move to group.
-fn style_row(app: &mut DesignApp, ui: &mut egui::Ui, para: bool, n: &str, current: Option<&str>, overridden: bool, groups: &[String], t: &Tokens) {
+fn style_row(
+ app: &mut DesignApp,
+ ui: &mut egui::Ui,
+ para: bool,
+ n: &str,
+ (current, overridden): (Option<&str>, bool),
+ groups: &[String],
+ t: &Tokens,
+) {
let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
if current == Some(n) {
ui.painter().rect_filled(row, 0.0, t.row_selected);
@@ -219,7 +227,7 @@ mod tests {
let mut h = Harness::builder().with_size(vec2(360.0, 240.0)).build_ui_state(
|ui, app: &mut DesignApp| {
let tokens = Tokens::get(ui.ctx());
- style_row(app, ui, true, "Header", Some("Header"), true, &[], &tokens);
+ style_row(app, ui, true, "Header", (Some("Header"), true), &[], &tokens);
},
app,
);
diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs
index 1c6f41b27..fba3eb5b7 100644
--- a/crates/ui-egui/src/panels/swatches.rs
+++ b/crates/ui-egui/src/panels/swatches.rs
@@ -659,6 +659,62 @@ fn thumbnail(p: &egui::Painter, r: egui::Rect, g: &designcraft_color::Gradient,
p.rect_stroke(r, 0.0, egui::Stroke::new(1.0, border), egui::StrokeKind::Outside);
}
+/// The gradient across `ramp`, sampled in bands.
+fn paint_ramp(painter: &egui::Painter, ramp: egui::Rect, g: &designcraft_color::Gradient) {
+ let n = 96;
+ for i in 0..n {
+ let (a, b) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);
+ let (c, alpha) = g.sample((a + b) / 2.0);
+ let x0 = ramp.left() + ramp.width() * a;
+ let x1 = ramp.left() + ramp.width() * b + 0.5;
+ painter.rect_filled(egui::Rect::from_x_y_ranges(x0..=x1, ramp.y_range()), 0.0, color32(&c, alpha));
+ }
+}
+
+/// The stops after dragging marker `h` to `o` (`off`: dropped off the ramp, which removes a stop),
+/// and the selection to move to if the drop changed it.
+fn ramp_release(g: &designcraft_color::Gradient, h: RampSel, o: f32, off: bool) -> (Vec<serde_json::Value>, Option<RampSel>) {
+ let mut stops = stops_json(g);
+ let mut sel = None;
+ match h {
+ RampSel::Stop(i) if off => {
+ if i < stops.len() {
+ stops.remove(i);
+ }
+ sel = Some(RampSel::Stop(0));
+ }
+ RampSel::Stop(i) => set_stop(&mut stops, i, "location", json!(o as f64 * 100.0)),
+ RampSel::Mid(i) => set_stop(&mut stops, i, "midpoint", json!(o as f64 * 100.0)),
+ }
+ (stops, sel)
+}
+
+/// Dragging the gradient's thumbnail: its swatch is the payload, and a thumbnail follows the pointer.
+fn drag_gradient_thumbnail(ui: &egui::Ui, resp: &egui::Response, g: &designcraft_color::Gradient, swatch: &str, t: &Tokens) {
+ resp.dnd_set_drag_payload(GradientDrag(swatch.to_string()));
+ if resp.dragged()
+ && let Some(p) = ui.ctx().pointer_interact_pos()
+ {
+ let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("gradient_drag")));
+ thumbnail(&painter, egui::Rect::from_min_size(p + vec2(8.0, 8.0), vec2(18.0, 18.0)), g, t.field_border);
+ }
+}
+
+/// The Gradient panel's Type menu; the kind chosen, as the command's parameters.
+fn gradient_type_combo(ui: &mut egui::Ui, lang: &str, g: &designcraft_color::Gradient, is_gradient: bool) -> Option<serde_json::Value> {
+ let mut send = None;
+ let shown = if is_gradient { crate::i18n::tr(lang, g.kind.label()) } else { "" };
+ let combo = craft_ui::ComboBox::from_id_salt("grad_type").selected_text(crate::rtl::widget(ui, shown)).width(104.0).show_ui(ui, |ui| {
+ for (k, v) in [("Linear", "linear"), ("Radial", "radial")] {
+ if ui.selectable_label(is_gradient && g.kind.label() == k, crate::rtl::widget(ui, crate::i18n::tr(lang, k))).clicked() {
+ send = Some(json!({"kind": v}));
+ }
+ }
+ });
+ let _ = crate::widgets::name_combo(combo, crate::i18n::tr(lang, "Type"));
+ send
+}
+
/// What's selected on the ramp: a stop, or the midpoint after a stop.
#[derive(Clone, Copy, PartialEq, Debug)]
enum RampSel {
@@ -722,13 +778,7 @@ pub fn gradient_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
thumbnail(ui.painter(), r.shrink(1.0), &g, t.field_border);
// Drag the gradient onto the Swatches panel to keep it as a swatch.
if is_gradient {
- resp.dnd_set_drag_payload(GradientDrag(fill.swatch.clone()));
- if resp.dragged()
- && let Some(p) = ui.ctx().pointer_interact_pos()
- {
- let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("gradient_drag")));
- thumbnail(&painter, egui::Rect::from_min_size(p + vec2(8.0, 8.0), vec2(18.0, 18.0)), &g, t.field_border);
- }
+ drag_gradient_thumbnail(ui, &resp, &g, &fill.swatch, &t);
}
// Clicking the thumbnail applies the gradient shown (InDesign's way to start one).
if resp.clicked() && !is_gradient {
@@ -739,19 +789,7 @@ pub fn gradient_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
ui.spacing_mut().item_spacing.x = 4.0;
ui.horizontal(|ui| {
crate::widgets::caption_w(ui, crate::i18n::tr(&lang, "Type:"), 52.0);
- let shown = if is_gradient { crate::i18n::tr(&lang, g.kind.label()) } else { "" };
- let combo =
- craft_ui::ComboBox::from_id_salt("grad_type").selected_text(crate::rtl::widget(ui, shown)).width(104.0).show_ui(ui, |ui| {
- for (k, v) in [("Linear", "linear"), ("Radial", "radial")] {
- if ui
- .selectable_label(is_gradient && g.kind.label() == k, crate::rtl::widget(ui, crate::i18n::tr(&lang, k)))
- .clicked()
- {
- send = Some(json!({"kind": v}));
- }
- }
- });
- let _ = crate::widgets::name_combo(combo, crate::i18n::tr(&lang, "Type"));
+ send = gradient_type_combo(ui, &lang, &g, is_gradient).or(send.take());
});
ui.horizontal(|ui| {
crate::widgets::caption_w(ui, crate::i18n::tr(&lang, "Location:"), 52.0);
@@ -792,14 +830,7 @@ pub fn gradient_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
let (area, resp) = ui.allocate_exact_size(vec2(w, 40.0), Sense::click_and_drag());
let ramp = egui::Rect::from_min_size(area.min + vec2(6.0, 10.0), vec2(w - 12.0, 14.0));
let painter = ui.painter();
- let n = 96;
- for i in 0..n {
- let (a, b) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);
- let (c, alpha) = g.sample((a + b) / 2.0);
- let x0 = ramp.left() + ramp.width() * a;
- let x1 = ramp.left() + ramp.width() * b + 0.5;
- painter.rect_filled(egui::Rect::from_x_y_ranges(x0..=x1, ramp.y_range()), 0.0, color32(&c, alpha));
- }
+ paint_ramp(painter, ramp, &g);
painter.rect_stroke(ramp, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);
let x_of = |o: f32| ramp.left() + ramp.width() * o;
let o_of = |x: f32| ((x - ramp.left()) / ramp.width()).clamp(0.0, 1.0);
@@ -854,16 +885,9 @@ pub fn gradient_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
if resp.drag_stopped()
&& let Some((h, o, off)) = dragging.take()
{
- let mut stops = stops_json(&g);
- match h {
- RampSel::Stop(i) if off => {
- if i < stops.len() {
- stops.remove(i);
- }
- sel = RampSel::Stop(0);
- }
- RampSel::Stop(i) => set_stop(&mut stops, i, "location", json!(o as f64 * 100.0)),
- RampSel::Mid(i) => set_stop(&mut stops, i, "midpoint", json!(o as f64 * 100.0)),
+ let (stops, kept) = ramp_release(&g, h, o, off);
+ if let Some(kept) = kept {
+ sel = kept;
}
send = Some(json!({"stops": stops}));
}
diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs
index 36c8016d6..f916e01b5 100644
--- a/crates/ui-egui/src/render_worker.rs
+++ b/crates/ui-egui/src/render_worker.rs
@@ -47,7 +47,7 @@ impl Worker {
job = newer;
}
let t0 = crate::now_ms();
- let image = r.render(&job.doc, &job.cache, &job.placed, job.w, job.h, job.view, &job.opts);
+ let image = r.render(&job.doc, &job.cache, &job.placed, (job.w, job.h), job.view, &job.opts);
if done_tx.send(Done { token: job.token, image, ms: crate::now_ms() - t0 }).is_err() {
break;
}
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 85d4663d8..bd038090a 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -1,4 +1,6 @@
-use super::*;
+#[cfg(not(target_arch = "wasm32"))]
+use super::render_worker;
+use super::{Deserialize, Point, Serialize, SnapView, Unit, canvas, dialogs, page_history, panels, prefs, separations, theme};
/// Context captured before any host file-picker or read await.
#[derive(Clone, Debug)]
diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs
index 8fc1e1229..4c6965ffc 100644
--- a/crates/ui-egui/src/toolbar.rs
+++ b/crates/ui-egui/src/toolbar.rs
@@ -219,24 +219,8 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
}
}
-/// The area under the tools (InDesign 2026 §3 group 5): mini Default Fill/Stroke and Swap, the
-/// overlapping Fill/Stroke proxy, Formatting affects container / text, the Apply None well, a
-/// utility button and the Screen Mode well.
-fn fill_stroke_proxy(app: &mut DesignApp, ui: &mut egui::Ui, width: f32, cols: usize) {
- let t = Tokens::get(ui.ctx());
- let target = crate::panels::color_target(app);
- let doc = app.session.active().map(|d| d.doc.clone());
- let stroke_front = app.ui.stroke_front;
- let text_mode = crate::panels::colors_affect_text(app) || app.ui.formatting_affects_text;
- let (fill_sw, stroke_sw) = match &target {
- Some((fill, _, stroke, _)) => (fill.clone(), stroke.clone()),
- // Nothing selected: the colours new shapes are drawn with.
- None => doc
- .as_ref()
- .map_or(("[None]".to_string(), "[Black]".to_string()), |d| (d.settings.new_object.fill.clone(), d.settings.new_object.stroke.clone())),
- };
- let x0 = ui.max_rect().min.x + (width - 30.0) / 2.0;
- // Row 1: default colours + swap.
+/// Row 1 of the proxy: the default-colours and swap buttons.
+fn proxy_default_swap(app: &mut DesignApp, ui: &mut egui::Ui, t: &Tokens, x0: f32, width: f32) {
let (row, _) = ui.allocate_exact_size(vec2(width, 11.0), Sense::hover());
let def = egui::Rect::from_min_size(egui::pos2(x0, row.min.y), vec2(10.0, 10.0));
icons::paint(ui.painter(), def, "default-colors", t.icon);
@@ -260,6 +244,26 @@ fn fill_stroke_proxy(app: &mut DesignApp, ui: &mut egui::Ui, width: f32, cols: u
{
let _ = app.run("color.swapFillStroke", json!({}));
}
+}
+
+/// The area under the tools (InDesign 2026 §3 group 5): mini Default Fill/Stroke and Swap, the
+/// overlapping Fill/Stroke proxy, Formatting affects container / text, the Apply None well, a
+/// utility button and the Screen Mode well.
+fn fill_stroke_proxy(app: &mut DesignApp, ui: &mut egui::Ui, width: f32, cols: usize) {
+ let t = Tokens::get(ui.ctx());
+ let target = crate::panels::color_target(app);
+ let doc = app.session.active().map(|d| d.doc.clone());
+ let stroke_front = app.ui.stroke_front;
+ let text_mode = crate::panels::colors_affect_text(app) || app.ui.formatting_affects_text;
+ let (fill_sw, stroke_sw) = match &target {
+ Some((fill, _, stroke, _)) => (fill.clone(), stroke.clone()),
+ // Nothing selected: the colours new shapes are drawn with.
+ None => doc
+ .as_ref()
+ .map_or(("[None]".to_string(), "[Black]".to_string()), |d| (d.settings.new_object.fill.clone(), d.settings.new_object.stroke.clone())),
+ };
+ let x0 = ui.max_rect().min.x + (width - 30.0) / 2.0;
+ proxy_default_swap(app, ui, &t, x0, width);
ui.add_space(2.0);
// Proxy: 19.5 pt squares, fill top-left, stroke bottom-right.
let (r, _) = ui.allocate_exact_size(vec2(width, 31.0), Sense::hover());
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 8e72a0bb3..a286afccf 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -174,6 +174,40 @@ impl<'a> NumField<'a> {
self.show_or_clear(ui).flatten()
}
+ /// The spinner segment's up and down buttons; the value a click on one gives.
+ fn spinner_segment(&self, ui: &mut Ui, rect: Rect, key: egui::Id, enabled: bool, t: &Tokens) -> Option<f64> {
+ let name = self.name.unwrap_or(self.id);
+ let step = self.step.unwrap_or_else(|| self.kind.step());
+ let clamp = |v: f64| v.clamp(self.range.0, self.range.1);
+ let mut out = None;
+ let seg = Rect::from_min_size(rect.min, vec2(SEG_W, FIELD_H));
+ ui.painter().rect_filled(seg, 0.0, t.input);
+ let up = Rect::from_min_max(seg.min, pos2(seg.max.x, seg.center().y));
+ let down = Rect::from_min_max(pos2(seg.min.x, seg.center().y), seg.max);
+ for (r, dir) in [(up, 1.0), (down, -1.0)] {
+ let resp = ui.interact(r, key.with(("spin", dir as i32)), if enabled { Sense::click() } else { Sense::hover() });
+ if resp.hovered() && enabled {
+ ui.painter().rect_filled(r.shrink(1.0), 0.0, t.hover);
+ }
+ let c = r.center();
+ let (a, b) = if dir > 0.0 { (2.5, -1.5) } else { (-2.5, 1.5) };
+ ui.painter()
+ .line_segment([pos2(c.x - 4.0, c.y + a * 0.6), pos2(c.x, c.y + b)], Stroke::new(1.0, if enabled { t.icon } else { t.text_disabled }));
+ ui.painter()
+ .line_segment([pos2(c.x, c.y + b), pos2(c.x + 4.0, c.y + a * 0.6)], Stroke::new(1.0, if enabled { t.icon } else { t.text_disabled }));
+ // The two spinner halves are real inputs: name them for screen readers and strict
+ // accessibility checks, which would otherwise see unnamed clickable nodes.
+ resp.widget_info(|| {
+ egui::WidgetInfo::labeled(egui::Role::Button, enabled, format!("{} {}", if dir > 0.0 { "Increase" } else { "Decrease" }, name))
+ });
+ if resp.clicked() {
+ let mul = if ui.input(|i| i.modifiers.shift) { 10.0 } else { 1.0 };
+ out = Some(clamp(self.value.unwrap_or(0.0) + dir * step * mul));
+ }
+ }
+ out
+ }
+
/// Like [`NumField::show`]; a field emptied while it had a value commits `Some(None)` (for
/// values that may be unset, like a character style's attributes).
pub fn show_or_clear(self, ui: &mut Ui) -> Option<Option<f64>> {
@@ -194,36 +228,8 @@ impl<'a> NumField<'a> {
let fg = if enabled { fg } else { t.text_disabled };
// Spinner segment.
if self.spinner {
- let seg = Rect::from_min_size(rect.min, vec2(SEG_W, FIELD_H));
- text_rect.min.x = seg.max.x;
- ui.painter().rect_filled(seg, 0.0, t.input);
- let up = Rect::from_min_max(seg.min, pos2(seg.max.x, seg.center().y));
- let down = Rect::from_min_max(pos2(seg.min.x, seg.center().y), seg.max);
- for (r, dir) in [(up, 1.0), (down, -1.0)] {
- let resp = ui.interact(r, key.with(("spin", dir as i32)), if enabled { Sense::click() } else { Sense::hover() });
- if resp.hovered() && enabled {
- ui.painter().rect_filled(r.shrink(1.0), 0.0, t.hover);
- }
- let c = r.center();
- let (a, b) = if dir > 0.0 { (2.5, -1.5) } else { (-2.5, 1.5) };
- ui.painter().line_segment(
- [pos2(c.x - 4.0, c.y + a * 0.6), pos2(c.x, c.y + b)],
- Stroke::new(1.0, if enabled { t.icon } else { t.text_disabled }),
- );
- ui.painter().line_segment(
- [pos2(c.x, c.y + b), pos2(c.x + 4.0, c.y + a * 0.6)],
- Stroke::new(1.0, if enabled { t.icon } else { t.text_disabled }),
- );
- // The two spinner halves are real inputs: name them for screen readers and strict
- // accessibility checks, which would otherwise see unnamed clickable nodes.
- resp.widget_info(|| {
- egui::WidgetInfo::labeled(egui::Role::Button, enabled, format!("{} {}", if dir > 0.0 { "Increase" } else { "Decrease" }, name))
- });
- if resp.clicked() {
- let mul = if ui.input(|i| i.modifiers.shift) { 10.0 } else { 1.0 };
- out = Some(clamp(self.value.unwrap_or(0.0) + dir * step * mul));
- }
- }
+ text_rect.min.x = rect.min.x + SEG_W;
+ out = self.spinner_segment(ui, rect, key, enabled, &t).or(out);
}
// Preset segment.
let mut preset_resp = None;