Skip to content

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

Merge remote-tracking branch 'origin/main' into status-bar-parent-page-box

moppeeerc73f68bccf8e
diff --cc crates/ui-egui/src/canvas/view.rs
index 000000000,db3eebcc8..7f0e7768d
mode 000000,100644..100644
--- a/crates/ui-egui/src/canvas/view.rs
+++ b/crates/ui-egui/src/canvas/view.rs
@@@ -1,0 -1,344 +1,390 @@@
+ 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) {
+ let Some(st) = app.session.active() else { return };
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ let cur = current_slot(app, &layout).unwrap_or(0);
+ let Some(slot) = layout.slots.get(cur) else { return };
+ let mut b = slot.bounds;
+ if what == "page"
+ && let Some(sp) = st.doc.spread(slot.spread)
+ {
+ let center = app.view().map(|v| v.origin.x + rect.width() as f64 / 2.0 / v.zoom).unwrap_or(0.0);
+ let c = slot.to_spread(Point::new(center, slot.bounds.center().y));
+ let pi = sp.page_at_x(c.x).unwrap_or(0);
+ b = slot.xf.transform_rect_bbox(sp.pages[pi].bounds());
+ }
+ if what == "all" {
+ b = layout.slots.iter().map(|s| s.bounds).reduce(|a, b| a.union(b)).unwrap_or(b);
+ }
+ if what == "selection" {
+ // Fit Selection in Window: the selected objects (on their spread's slot).
+ let sel: Vec<designcraft_geom::Rect> = st
+ .selection
+ .items
+ .iter()
+ .filter_map(|id| {
+ let loc = st.doc.find(*id)?;
+ let slot = layout.slots.iter().find(|s| s.spread == loc.spread)?;
+ Some(slot.xf.transform_rect_bbox(st.doc.item(*id)?.bounds()))
+ })
+ .collect();
+ let Some(u) = sel.into_iter().reduce(|a, b| a.union(b)) else { return };
+ b = u.inflate(u.width().max(u.height()) * 0.05 + 1.0, u.width().max(u.height()) * 0.05 + 1.0);
+ }
+ fit_bounds(app, rect, b);
+ }
+
+ /// Zoom and scroll so canvas rectangle `b` fills the canvas `rect`.
+ fn fit_bounds(app: &mut DesignApp, rect: Rect, b: DRect) {
+ let pad = 40.0;
+ let zoom =
+ ((rect.width() as f64 - 2.0 * pad) / b.width().max(1e-6)).min((rect.height() as f64 - 2.0 * pad) / b.height().max(1e-6)).clamp(0.05, 40.0);
+ let origin = Point::new(b.center().x - rect.width() as f64 / 2.0 / zoom, b.center().y - rect.height() as f64 / 2.0 / zoom);
+ if let Some(v) = app.view_mut() {
+ *v = View { zoom, origin, fitted: true, rotation: v.rotation };
+ }
+ }
+
+ /// Fit spread `r` (a document or parent spread on the canvas as it is laid out now) in the canvas.
+ /// Before the canvas has a size, the next frame fits whatever spread is current.
+ pub fn show_spread(app: &mut DesignApp, r: SpreadRef) {
+ let Some(st) = app.session.active() else { return };
+ let Some(b) = CanvasLayout::new(&st.doc, st.editing_parents).slot(r).map(|s| s.bounds) else { return };
+ match app.canvas_rect {
+ Some(rect) => fit_bounds(app, rect, b),
+ None => {
+ if let Some(v) = app.view_mut() {
+ v.fitted = false;
+ }
+ }
+ }
+ }
+
+ /// Index of the slot nearest the view centre.
+ pub fn current_slot(app: &DesignApp, layout: &CanvasLayout) -> Option<usize> {
+ let v = app.view()?;
+ let r = app.canvas_rect?;
+ let c = Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom);
+ layout
+ .slots
+ .iter()
+ .enumerate()
+ .min_by(|a, b| {
+ let da = (a.1.bounds.center().y - c.y).abs();
+ let db = (b.1.bounds.center().y - c.y).abs();
+ da.total_cmp(&db)
+ })
+ .map(|(i, _)| i)
+ }
+
+ /// The spread under the view centre (a parent spread while parents are edited).
+ pub fn current_spread(app: &DesignApp) -> Option<SpreadRef> {
+ let st = app.session.active()?;
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ Some(layout.slots.get(current_slot(app, &layout)?)?.spread)
+ }
+
+ /// The spread nearest the view centre and the centre in that spread's coordinates.
+ pub fn view_centre(app: &DesignApp) -> Option<(SpreadRef, Point)> {
+ let st = app.session.active()?;
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ let slot = layout.slots.get(current_slot(app, &layout)?)?;
+ let v = app.view()?;
+ let r = app.canvas_rect?;
+ let c = Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom);
+ Some((slot.spread, slot.to_spread(c)))
+ }
+
+ /// Where a file dropped on the window lands: the spread under the pointer, or under the view
+ /// centre when the pointer isn't over the canvas, and that point in spread coordinates.
+ pub fn drop_point(app: &DesignApp, screen: Option<Pos2>) -> Option<(SpreadRef, Point)> {
+ let rect = app.canvas_rect?;
+ let Some(pos) = screen.filter(|p| rect.contains(*p)) else { return view_centre(app) };
+ let st = app.session.active()?;
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ layout.spread_at(Xf::new(rect, app.view()?).to_canvas(pos))
+ }
+
+ /// Absolute page index under the view centre.
+ pub fn current_page(app: &DesignApp) -> Option<usize> {
+ let st = app.session.active()?;
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ let i = current_slot(app, &layout)?;
+ let slot = layout.slots.get(i)?;
+ let SpreadRef::Doc(si) = slot.spread else { return Some(0) };
+ let v = app.view()?;
+ let r = app.canvas_rect?;
+ let c = slot.to_spread(Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, slot.bounds.center().y));
+ let pi = st.doc.spreads[si].page_at_x(c.x).unwrap_or(0);
+ Some(st.doc.first_page_of_spread(si) + pi)
+ }
+
+ /// The spread (document or parent) under the view centre and the page index within it: where
+ /// commands that act "on the page I am working on" should go.
+ pub fn current_spread_page(app: &DesignApp) -> Option<(SpreadRef, usize)> {
+ let st = app.session.active()?;
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ let i = current_slot(app, &layout)?;
+ let slot = layout.slots.get(i)?;
+ let v = app.view()?;
+ let r = app.canvas_rect?;
+ let c = slot.to_spread(Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, slot.bounds.center().y));
+ let pg = st.doc.spread(slot.spread)?.page_at_x(c.x).unwrap_or(0);
+ Some((slot.spread, pg))
+ }
+
+ /// While parent spreads are being edited: (parent spread index, page index within it) under the
+ /// view centre. `None` when document pages are shown.
+ pub fn current_parent_page(app: &DesignApp) -> Option<(usize, usize)> {
+ let st = app.session.active()?;
+ if !st.editing_parents {
+ return None;
+ }
+ let layout = CanvasLayout::new(&st.doc, true);
+ let i = current_slot(app, &layout)?;
+ let slot = layout.slots.get(i)?;
+ let SpreadRef::Parent(pi) = slot.spread else { return None };
+ let v = app.view()?;
+ let r = app.canvas_rect?;
+ let c = slot.to_spread(Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, slot.bounds.center().y));
+ let qi = st.doc.parents.get(pi)?.page_at_x(c.x).unwrap_or(0);
+ Some((pi, qi))
+ }
+
++/// The page box's entries (the status bar's, and Properties › Page), as InDesign's: the
++/// document's pages by name, then the parents by label ("A-Parent").
++pub struct PageBox {
++ pub names: Vec<String>,
++ /// The entry in view: the parent shown while parents are edited, else the page.
++ pub current: usize,
++ /// How many of `names` are pages; the parents follow.
++ pub pages: usize,
++ parents: Vec<designcraft_doc::SpreadId>,
++}
++
++impl PageBox {
++ /// The name of the entry in view ("3", "A-Parent").
++ pub fn current_name(&self) -> &str {
++ self.names.get(self.current).map_or("", String::as_str)
++ }
++}
++
++pub fn page_box(app: &DesignApp) -> Option<PageBox> {
++ let st = app.session.active()?;
++ let pages = st.doc.page_count();
++ let mut names: Vec<String> = (0..pages).map(|i| app.session.page_label(i)).collect();
++ names.extend(st.doc.parents.iter().map(|p| p.parent.as_ref().map(|i| i.label()).unwrap_or_default()));
++ let current = match current_parent_page(app) {
++ Some((pi, _)) => pages + pi,
++ None => current_page(app).unwrap_or(0).min(pages.saturating_sub(1)),
++ };
++ Some(PageBox { names, current, pages, parents: st.doc.parents.iter().map(|p| p.id).collect() })
++}
++
++/// Shows entry `i` of `b`: a page (leaving the parents, if they are shown) or a parent.
++pub fn page_box_go(app: &mut DesignApp, b: &PageBox, i: usize) {
++ if i < b.pages {
++ if app.session.active().is_some_and(|st| st.editing_parents) {
++ let _ = app.run("layout.parents.edit", json!({"on": false}));
++ // The canvas refits to the page's spread once it is centred.
++ if let Some(v) = app.view_mut() {
++ v.fitted = false;
++ }
++ }
++ go_to_page(app, i);
++ } else if let Some(id) = b.parents.get(i - b.pages) {
++ let _ = app.run("layout.parents.edit", json!({"parent": id.0}));
++ }
++}
++
+ /// Scroll so absolute page `abs` is centred (keeps zoom). A jump Go Back can return from.
+ pub fn go_to_page(app: &mut DesignApp, abs: usize) {
+ note_jump(app, false);
+ centre_page(app, abs);
+ note_jump(app, true);
+ }
+
+ fn centre_page(app: &mut DesignApp, abs: usize) {
+ let Some(st) = app.session.active() else { return };
+ let layout = CanvasLayout::new(&st.doc, false);
+ let Some(pr) = layout.page_rect(&st.doc, abs) else { return };
+ let Some(rect) = app.canvas_rect else { return };
+ if let Some(v) = app.view_mut() {
+ v.origin = Point::new(pr.center().x - rect.width() as f64 / 2.0 / v.zoom, pr.center().y - rect.height() as f64 / 2.0 / v.zoom);
+ }
+ }
+
+ /// The document's pages by id, in page order.
+ fn page_ids(doc: &Document) -> Vec<designcraft_doc::ids::PageId> {
+ doc.spreads.iter().flat_map(|s| s.pages.iter().map(|p| p.id)).collect()
+ }
+
+ /// The page in view and the view centre's offset from that page's centre. Parent pages have none,
+ /// nor has a view still waiting to be fitted (leaving parent pages for a document page).
+ pub(crate) fn page_in_view(app: &DesignApp) -> Option<(designcraft_doc::ids::PageId, DVec2)> {
+ let st = app.session.active().filter(|st| !st.editing_parents)?;
+ let (v, r) = (app.view().filter(|v| v.fitted)?, app.canvas_rect?);
+ let abs = current_page(app)?;
+ let id = st.doc.page(abs)?.id;
+ let pr = CanvasLayout::new(&st.doc, false).page_rect(&st.doc, abs)?;
+ let c = Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom);
+ Some((id, c - pr.center()))
+ }
+
+ /// Layout ▸ Go Back / Go Forward record jumps (Go to Page, the page and spread commands, the Pages
+ /// panel), not scrolling: where the view is when a jump starts, and where the jump took it.
+ fn note_jump(app: &mut DesignApp, to: bool) {
+ let Some((id, offset)) = page_in_view(app) else { return };
+ if let Some(h) = app.page_history_mut() {
+ if to { h.visit(id, offset) } else { h.leave(id, offset) }
+ }
+ }
+
+ /// Whether Layout ▸ Go Back (`step` < 0) or Go Forward has a page to go to from the view as it is.
+ pub fn can_go_through_history(app: &DesignApp, step: isize) -> bool {
+ let Some(st) = app.session.active().filter(|st| !st.editing_parents) else { return false };
+ // A view still waiting to be fitted is refitted next frame, which would replace the destination.
+ if !app.view().is_some_and(|v| v.fitted) {
+ return false;
+ }
+ let ids = page_ids(&st.doc);
+ let Some(mut h) = app.page_history().cloned() else { return false };
+ if let Some((id, offset)) = page_in_view(app) {
+ h.leave(id, offset);
+ }
+ h.can_go(step, |id| ids.contains(&id))
+ }
+
+ /// Layout ▸ Go Back (`step` < 0) or Go Forward: show the page viewed before or after this one, where
+ /// the view was on it (zoom kept).
+ pub fn go_through_history(app: &mut DesignApp, step: isize) {
+ if !app.view().is_some_and(|v| v.fitted) {
+ return;
+ }
+ note_jump(app, false);
+ let Some(ids) = app.session.active().filter(|st| !st.editing_parents).map(|st| page_ids(&st.doc)) else { return };
+ let Some((id, offset)) = app.page_history_mut().and_then(|h| h.go(step, |id| ids.contains(&id))) else { return };
+ let Some(st) = app.session.active() else { return };
+ let Some(pr) = ids.iter().position(|p| *p == id).and_then(|abs| CanvasLayout::new(&st.doc, false).page_rect(&st.doc, abs)) else { return };
+ let Some(rect) = app.canvas_rect else { return };
+ let c = pr.center() + offset;
+ if let Some(v) = app.view_mut() {
+ v.origin = Point::new(c.x - rect.width() as f64 / 2.0 / v.zoom, c.y - rect.height() as f64 / 2.0 / v.zoom);
+ }
+ }
+
+ /// Presentation: the spread in view, centred and as large as `rect` allows.
+ pub(super) fn present_fit(app: &mut DesignApp, rect: Rect) {
+ let Some(st) = app.session.active() else { return };
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ let Some(b) = current_slot(app, &layout).and_then(|i| layout.slots.get(i)).map(|s| s.bounds) else { return };
+ if b.width() <= 0.0 || b.height() <= 0.0 {
+ return;
+ }
+ let zoom = (rect.width() as f64 / b.width()).min(rect.height() as f64 / b.height()).clamp(0.05, 40.0);
+ let origin = Point::new(b.center().x - rect.width() as f64 / 2.0 / zoom, b.center().y - rect.height() as f64 / 2.0 / zoom);
+ if let Some(v) = app.view_mut() {
+ v.zoom = zoom;
+ v.origin = origin;
+ }
+ }
+
+ /// Centre the spread `delta` spreads after (or before) the one in view (keeps zoom); stops at the
+ /// first and last spread. Parent spreads while they are being edited.
+ pub fn step_spread(app: &mut DesignApp, delta: isize) {
+ // At the first or last spread only the view moves, within the spread: no jump for Go Back.
+ let jump = spread_step(app, delta).is_some_and(|(cur, to)| cur != to);
+ if jump {
+ note_jump(app, false);
+ }
+ centre_spread(app, delta);
+ if jump {
+ note_jump(app, true);
+ }
+ }
+
+ /// The slot in view and the one `delta` spreads after (or before) it, stopping at the ends.
+ fn spread_step(app: &DesignApp, delta: isize) -> Option<(usize, usize)> {
+ let st = app.session.active()?;
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ let cur = current_slot(app, &layout)?;
+ Some((cur, cur.saturating_add_signed(delta).min(layout.slots.len().saturating_sub(1))))
+ }
+
+ fn centre_spread(app: &mut DesignApp, delta: isize) {
+ let Some((_, to)) = spread_step(app, delta) else { return };
+ let Some(st) = app.session.active() else { return };
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ let Some(b) = layout.slots.get(to).map(|s| s.bounds) else { return };
+ let Some(rect) = app.canvas_rect else { return };
+ if let Some(v) = app.view_mut() {
+ v.origin = Point::new(b.center().x - rect.width() as f64 / 2.0 / v.zoom, b.center().y - rect.height() as f64 / 2.0 / v.zoom);
+ }
+ }
+
+ pub fn zoom_at(app: &mut DesignApp, screen: Pos2, factor: f64) {
+ let Some(rect) = app.canvas_rect else { return };
+ let Some(v) = app.view_mut() else { return };
+ let xf = Xf::new(rect, v);
+ let c = xf.to_canvas(screen);
+ let screen = xf.unrotate(screen);
+ let nz = (v.zoom * factor).clamp(0.05, 40.0);
+ v.zoom = nz;
+ v.origin = Point::new(c.x - (screen.x - rect.min.x) as f64 / nz, c.y - (screen.y - rect.min.y) as f64 / nz);
+ }
+
+ pub fn set_zoom(app: &mut DesignApp, z: f64) {
+ let Some(rect) = app.canvas_rect else { return };
+ let cur = app.view().map(|v| v.zoom).unwrap_or(1.0);
+ zoom_at(app, rect.center(), z / cur);
+ }
+
+ pub fn apply_view_request(app: &mut DesignApp, p: &Value) {
+ if let Some(r) = p.get("showSpread").and_then(|v| serde_json::from_value::<SpreadRef>(v.clone()).ok()) {
+ show_spread(app, r);
+ }
+ // Power Zoom (Hand tool, Alt-press): zoom out to the spread, aim a view-sized rectangle, zoom
+ // back in where it was released.
+ if let Some(phase) = p.get("powerZoom").and_then(Value::as_str) {
+ let at = p.get("at").and_then(Value::as_array).map(|a| Point::new(a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0)));
+ match phase {
+ "start" => {
+ if let (Some(v), Some(rect)) = (app.view().copied(), app.canvas_rect) {
+ let centre = Xf::new(rect, &v).to_canvas(rect.center());
+ app.power_zoom = Some((v.zoom, at.unwrap_or(centre)));
+ fit(app, rect, "spread");
+ }
+ }
+ "move" => {
+ if let (Some(pz), Some(a)) = (&mut app.power_zoom, at) {
+ pz.1 = a;
+ }
+ }
+ _ => {
+ if let (Some((z, c)), Some(rect)) = (app.power_zoom.take(), app.canvas_rect)
+ && let Some(v) = app.view_mut()
+ {
+ let c = at.unwrap_or(c);
+ v.zoom = z;
+ v.origin = Point::new(c.x - rect.width() as f64 / 2.0 / z, c.y - rect.height() as f64 / 2.0 / z);
+ }
+ }
+ }
+ }
+ if let Some(d) = p.get("pan").and_then(Value::as_array) {
+ let (dx, dy) = (d.first().and_then(Value::as_f64).unwrap_or(0.0), d.get(1).and_then(Value::as_f64).unwrap_or(0.0));
+ if let Some(v) = app.view_mut() {
+ v.origin = Point::new(v.origin.x - dx / v.zoom, v.origin.y - dy / v.zoom);
+ }
+ }
+ if let (Some(a), Some(rect)) = (p.get("zoomAt").and_then(Value::as_array), app.canvas_rect)
+ && let Some(v) = app.view()
+ {
+ let c = Point::new(a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0));
+ let xf = Xf::new(rect, v);
+ let s = xf.to_screen(c);
+ zoom_at(app, s, p.get("factor").and_then(Value::as_f64).unwrap_or(2.0));
+ }
+ }
diff --cc crates/ui-egui/src/chrome/status_bar.rs
index 000000000,e0a9d27e2..519830620
mode 000000,100644..100644
--- a/crates/ui-egui/src/chrome/status_bar.rs
+++ b/crates/ui-egui/src/chrome/status_bar.rs
@@@ -1,0 -1,180 +1,204 @@@
+ 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.
+ pub(super) const DOC_TAB_MAX_W: f32 = 260.0;
+
+ /// Close button and padding around a tab's title.
+ const DOC_TAB_PAD: f32 = 44.0;
+
+ /// Draw bounded document tabs with active, dirty, preview and zoom state, plus activation and close actions.
+ pub fn doc_tabs(app: &mut DesignApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), 28.0), Sense::hover());
+ let max_w = DOC_TAB_MAX_W.min(bar.width());
+ let close_label = crate::i18n::tr(&app.ui.language, "Close");
+ ui.painter().rect_filled(bar, 0.0, t.tab_strip);
+ ui.painter().line_segment([bar.left_bottom(), bar.right_bottom()], Stroke::new(1.0, t.border));
+ let mut x = bar.min.x;
+ let active = app.session.active_index();
+ let zoom = app.view().map(|v| v.zoom).unwrap_or(1.0);
+ let mut activate = None;
+ let mut close = None;
+ let titles: Vec<(String, bool)> = app.session.documents().iter().map(|d| (d.title(), d.is_dirty())).collect();
+ for (i, (title, dirty)) in titles.iter().enumerate() {
+ let is_active = Some(i) == active;
+ // `*` = unsaved; the view-mode suffix only in Preview (InDesign shows its GPU mode there).
+ let suffix = if is_active && app.ui.screen_mode == crate::ScreenMode::Preview { " [Preview]" } else { "" };
+ let color = if is_active { t.text_strong } else { t.text_dim };
+ // The name gives way first; the dirty marker and zoom stay readable.
+ let zoom_label = crate::rtl::plain(ui.ctx(), &format!(" @ {:.0}%{suffix}", zoom * 100.0), semibold(11.5), color);
+ let name = format!("{}{}", if *dirty { "*" } else { "" }, crate::rtl::isolate(title));
+ let name_max = max_w - DOC_TAB_PAD - zoom_label.size().x;
+ let galley = crate::rtl::truncated(ui.ctx(), &name, semibold(11.5), color, name_max);
+ let elided = galley.elided;
+ let w = (galley.size().x + zoom_label.size().x + DOC_TAB_PAD).max(if is_active { 210.0 } else { 150.0 }).min(max_w);
+ let r = egui::Rect::from_min_size(egui::pos2(x, bar.min.y), vec2(w, 28.0));
+ let resp = ui.interact(r, ui.scope_id().with(("doctab", i)), Sense::click());
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, title));
+ let resp = if elided {
+ resp.on_hover_ui(|ui| {
+ let _ = crate::rtl::label(ui, title);
+ })
+ } else {
+ resp
+ };
+ ui.painter().rect_filled(r, 0.0, if is_active { t.panel } else { t.tab_strip });
+ let cr = egui::Rect::from_center_size(egui::pos2(r.min.x + 18.0, r.center().y), vec2(14.0, 14.0));
+ let cresp = ui.interact(cr, ui.scope_id().with(("docclose", i)), Sense::click());
+ cresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{close_label} {title}")));
+ ui.painter().text(
+ cr.center(),
+ egui::Align2::CENTER_CENTER,
+ "×",
+ egui::FontId::proportional(14.0),
+ if cresp.hovered() { t.text_strong } else { t.text_dim },
+ );
+ let name_w = galley.size().x;
+ // Clipped too, for a window narrower than the zoom label.
+ let text = ui.painter().with_clip_rect(r);
+ text.galley(egui::pos2(r.min.x + 32.0, r.center().y - galley.size().y / 2.0), galley, Color32::WHITE);
+ text.galley(egui::pos2(r.min.x + 32.0 + name_w, r.center().y - zoom_label.size().y / 2.0), zoom_label, Color32::WHITE);
+ ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.border));
+ if cresp.clicked() {
+ close = Some(i);
+ } else if resp.clicked() {
+ activate = Some(i);
+ }
+ x += w;
+ }
+ if let Some(i) = close {
+ crate::menus::close_document(app, Some(i));
+ } else if let Some(i) = activate {
+ let _ = app.run("file.activate", json!({"index": i}));
+ }
+ }
+
+ /// Show the Preflight panel. An open Preflight flyout stays: `window.panel` would close it.
+ fn show_preflight(app: &mut DesignApp) {
+ if app.ui.docking_flyout.as_deref() != Some("preflight")
+ && let Err(e) = app.run("window.panel", json!({"panel": "preflight"}))
+ {
+ app.status(e);
+ }
+ }
+
+ pub fn status_bar(app: &mut DesignApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ let resp = egui::Panel::bottom("status_bar")
+ .exact_size(17.0)
+ .frame(egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(8, 0)))
+ .show(ui, |ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ ui.horizontal_centered(|ui| {
+ let small = egui::FontId::proportional(10.5);
+ if app.session.active().is_none() {
+ ui.label(egui::RichText::new(&app.ui.status).font(small).color(t.text_dim));
+ return;
+ }
+ let z = app.view().map(|v| v.zoom).unwrap_or(1.0);
+ crate::menus::menu_button(ui, egui::RichText::new(format!("{:.2}% ▾", z * 100.0)).font(small.clone()), |ui| {
+ for p in [0.05, 0.125, 0.25, 0.5, 0.75, 1.0, 2.0, 4.0, 8.0, 16.0] {
+ if ui.button(format!("{}%", p * 100.0)).clicked() {
+ let _ = app.run("view.zoom", json!({"zoom": p}));
+ ui.close();
+ }
+ }
+ });
+ ui.add_space(8.0);
+ let n = app.session.active().map(|d| d.doc.page_count()).unwrap_or(1);
+ let cur = crate::canvas::current_page(app).unwrap_or(0);
+ if icons::button(ui, "first", 14.0, false, crate::i18n::tr(&app.ui.language, "First Spread")).clicked() {
+ crate::canvas::go_to_page(app, 0);
+ }
+ if icons::button(ui, "prev", 14.0, false, crate::i18n::tr(&app.ui.language, "Previous Spread")).clicked() {
+ crate::canvas::go_to_page(app, cur.saturating_sub(1));
+ }
- let name = app.session.page_label(cur);
++ // The page box, as InDesign's: the page in view, or the parent while one is shown
++ // ("A-Parent"); its menu lists the pages, then the parents.
++ let pb = crate::canvas::page_box(app);
++ let name = pb.as_ref().map_or_else(String::new, |b| b.current_name().to_string());
+ let (fr, fresp) = ui.allocate_exact_size(vec2(80.0, 14.0), Sense::click());
+ ui.painter().rect(fr, 0.0, t.input, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
- ui.painter().text(fr.left_center() + vec2(5.0, 0.0), egui::Align2::LEFT_CENTER, &name, small.clone(), t.text);
++ // A long parent name is cut at the arrow.
++ ui.painter().with_clip_rect(egui::Rect::from_min_max(fr.min, egui::pos2(fr.max.x - 14.0, fr.max.y))).text(
++ fr.left_center() + vec2(5.0, 0.0),
++ egui::Align2::LEFT_CENTER,
++ &name,
++ small.clone(),
++ t.text,
++ );
+ ui.painter().text(fr.right_center() - vec2(5.0, 0.0), egui::Align2::RIGHT_CENTER, "▾", small.clone(), t.text);
- egui::Popup::menu(&fresp).show(|ui| {
- let names: Vec<String> = (0..n).map(|i| app.session.page_label(i)).collect();
- egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| {
- for (i, nm) in names.iter().enumerate() {
- if ui.button(nm).clicked() {
- crate::canvas::go_to_page(app, i);
- ui.close();
++ let label = crate::i18n::tr(&app.ui.language, "Page");
++ fresp.widget_info(|| {
++ let mut info = egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, true, label);
++ info.current_text_value = Some(name.clone());
++ info
++ });
++ let mut picked = None;
++ if let Some(b) = &pb {
++ egui::Popup::menu(&fresp).show(|ui| {
++ egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| {
++ for (i, nm) in b.names.iter().enumerate() {
++ if i == b.pages && i > 0 {
++ ui.separator();
++ }
++ if ui.selectable_label(i == b.current, nm).clicked() {
++ picked = Some(i);
++ ui.close();
++ }
+ }
- }
++ });
+ });
- });
++ }
++ if let (Some(b), Some(i)) = (&pb, picked) {
++ crate::canvas::page_box_go(app, b, i);
++ }
+ if icons::button(ui, "next", 14.0, false, crate::i18n::tr(&app.ui.language, "Next Spread")).clicked() {
+ crate::canvas::go_to_page(app, (cur + 1).min(n - 1));
+ }
+ if icons::button(ui, "last", 14.0, false, crate::i18n::tr(&app.ui.language, "Last Spread")).clicked() {
+ crate::canvas::go_to_page(app, n - 1);
+ }
+ ui.add_space(12.0);
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "[Basic] (working) ▾")).font(small.clone()));
+ ui.add_space(8.0);
+ // Preflight: overset text is an error.
+ let errors = panels::preflight_errors(app);
+ let (r, dot) = ui.allocate_exact_size(vec2(9.0, 9.0), Sense::click());
+ ui.painter().circle_filled(
+ r.center(),
+ 4.0,
+ if errors == 0 { Color32::from_rgb(60, 200, 90) } else { Color32::from_rgb(235, 50, 50) },
+ );
+ let count = if errors == 0 {
+ format!("{} ▾", crate::i18n::tr(&app.ui.language, "No errors"))
+ } else {
+ format!(
+ "{} ▾",
+ crate::i18n::count_label(
+ &app.ui.language,
+ if errors == 1 && !crate::i18n::category_first(&app.ui.language) { "error" } else { "errors" },
+ errors
+ )
+ )
+ };
+ // As in InDesign, the count opens a menu that leads to the Preflight panel.
+ let menu = crate::menus::menu_button(ui, egui::RichText::new(count).font(small.clone()), |ui| {
+ if ui.button(crate::i18n::tr(&app.ui.language, "Preflight Panel…")).clicked() {
+ show_preflight(app);
+ ui.close();
+ }
+ });
+ // Double-clicking the light or the count shows the panel straight away (the
+ // second click has closed the menu the first one opened).
+ if dot.double_clicked() || menu.response.double_clicked() {
+ show_preflight(app);
+ }
+ ui.add_space(12.0);
+ ui.label(egui::RichText::new(&app.ui.status).font(small).color(t.text_dim));
+ });
+ });
+ let r = resp.response.rect;
+ ui.painter().line_segment([r.left_top(), r.right_top()], Stroke::new(1.0, t.border));
+ }
diff --cc crates/ui-egui/src/chrome/tests.rs
index 000000000,5e420de98..48f79c819
mode 000000,100644..100644
--- a/crates/ui-egui/src/chrome/tests.rs
+++ b/crates/ui-egui/src/chrome/tests.rs
@@@ -1,0 -1,868 +1,911 @@@
+ /// A Control panel field is labelled by its icon, so assistive technology reads "Tracking"
+ /// (or "Font Size", …) with the value.
+ #[test]
+ fn icon_fields_are_labelled_by_their_icon() {
+ use egui::accesskit::Role;
+ let ctx = egui::Context::default();
+ crate::theme::install_fonts(&ctx, "en");
+ ctx.enable_accesskit();
+ let mut update = None;
+ for _ in 0..2 {
+ let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
+ icon_field(ui, "tracking", "Tracking", NumField::number("tracking_test", Some(0.0), "", 0));
+ });
+ out.textures_delta.clear();
+ update = out.platform_output.accesskit_update;
+ }
+ let update = update.expect("an AccessKit tree");
+ let named = |n: &egui::accesskit::Node| n.label() == Some("Tracking") || n.value() == Some("Tracking");
+ let icon = update.nodes.iter().find(|(_, n)| named(n)).map(|(id, _)| *id).expect("the icon's node");
+ assert!(update.nodes.iter().any(|(_, n)| n.role() == Role::TextInput && n.labelled_by().contains(&icon)), "the editor names its icon");
+ }
+ use egui::{pos2, vec2};
+ use egui_kittest::kittest::{NodeT, Queryable};
+
+ use super::*;
+ use crate::test_window::{self, wheel};
+
+ /// The Control panel's last control with no text frame selected.
+ const LAST_CONTROL: &str = "Align bottom edges";
+ const FIRST_CONTROL: &str = "Rotate 90° Counterclockwise";
+
+ /// The start screen and Open Recent menu look a recent file up on disk at most every few
+ /// seconds, not every frame.
+ #[test]
+ fn recent_files_are_looked_up_on_disk_every_few_seconds() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("a.designcraft");
+ std::fs::write(&path, b"x").unwrap();
+ let path = path.to_string_lossy().to_string();
+ let ctx = egui::Context::default();
+ let first = super::recent_file_stat_at(&ctx, &path, 10_000.0);
+ assert!(first.exists && first.modified.is_some());
+ std::fs::remove_file(&path).unwrap();
+ assert_eq!(super::recent_file_stat_at(&ctx, &path, 10_000.0 + super::RECENT_STAT_MS - 1.0), first, "cached");
+ assert!(!super::recent_file_stat_at(&ctx, &path, 10_000.0 + super::RECENT_STAT_MS).exists, "looked up again");
+ }
+
+ fn app() -> crate::DesignApp {
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.ui.control_bar = true;
+ app
+ }
+
+ /// A document with a rectangle selected, so the object controls are enabled.
+ fn app_with_selection() -> crate::DesignApp {
+ let mut app = app();
+ app.run("file.new", serde_json::json!({})).unwrap();
+ app.run("frame.create", serde_json::json!({"rect": [72, 72, 300, 200]})).unwrap();
+ app.run("edit.selectAll", serde_json::json!({})).unwrap();
+ app
+ }
+
+ /// The rect of an object Control panel group.
+ fn group(h: &egui_kittest::Harness<'static, test_window::Window>, id: &str) -> egui::Rect {
+ h.ctx.read_response(egui::Id::unique(("object_control", id))).unwrap().rect
+ }
+
+ /// The rect of the node with this label, preferring the one in the Control bar's row: the
+ /// Properties panel has buttons with the same names.
+ fn rect(h: &egui_kittest::Harness<'static, test_window::Window>, label: &str) -> egui::Rect {
+ let bar = test_window::panel_rect(h, "control_bar");
+ h.query_all_by_label(label).map(|n| n.rect()).find(|r| bar.y_range().contains(r.center().y)).unwrap_or_else(|| h.get_by_label(label).rect())
+ }
+
+ /// The application bar's search field (German interface).
+ fn search_node<'h>(h: &'h egui_kittest::Harness<'static, test_window::Window>) -> egui_kittest::Node<'h> {
+ h.get_by(|n| n.role() == egui::accesskit::Role::TextInput && n.placeholder() == Some(crate::i18n::tr("de", "Search")))
+ }
+
+ /// A document with two frames, the Selection tool, German menus, and the search field clicked.
+ fn searching() -> egui_kittest::Harness<'static, test_window::Window> {
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.ui.language = "de".into();
+ let mut h = test_window::open(app, vec2(1440.0, 900.0));
+ let app = &mut h.state_mut().app;
+ app.run("frame.create", serde_json::json!({"rect": [36, 36, 200, 200]})).unwrap();
+ app.run("frame.create", serde_json::json!({"rect": [236, 36, 400, 200]})).unwrap();
+ app.run("edit.deselectAll", serde_json::json!({})).unwrap();
+ h.run_steps(4);
+ let field = search_node(&h).rect();
+ test_window::click_at(&mut h, field.center());
+ assert!(h.ctx.memory(|m| m.has_focus(super::search_id())), "a click gives the field the keyboard");
+ h
+ }
+
+ /// A match in the search's list, whose accessible label ends in its shortcut.
+ fn row<'h>(h: &'h egui_kittest::Harness<'static, test_window::Window>, label: &'static str) -> Option<egui_kittest::Node<'h>> {
+ h.query_by(move |n| n.label().is_some_and(|l| l == label || l.starts_with(&format!("{label} "))))
+ }
+
+ fn items(h: &egui_kittest::Harness<'static, test_window::Window>) -> (usize, usize) {
+ let d = h.state().app.session.active().unwrap();
+ (d.doc.spreads.iter().flat_map(|sp| &sp.items).count(), d.selection.items.len())
+ }
+
+ #[test]
+ fn the_search_field_finds_and_runs_menu_commands() {
+ let mut h = searching();
+ let group = crate::i18n::tr("de", "Group");
+ h.event(egui::Event::Text(group.to_lowercase()));
+ h.run_steps(4);
+ assert!(row(&h, group).is_some(), "the German label is listed");
+ // Nothing is selected, so Group is off and Return doesn't run it.
+ assert!(row(&h, group).is_some_and(|n| n.accesskit_node().is_disabled()));
+ h.key_press(egui::Key::Enter);
+ h.run_steps(4);
+ assert_eq!(items(&h), (2, 0), "a disabled command doesn't run");
+ // Select both frames, then ↓ ↑ Return runs the first match, as Object › Group would.
+ h.state_mut().app.run("edit.selectAll", serde_json::json!({})).unwrap();
+ h.key_press(egui::Key::ArrowDown);
+ h.run_steps(2);
+ h.key_press(egui::Key::ArrowUp);
+ h.run_steps(2);
+ h.key_press(egui::Key::Enter);
+ h.run_steps(4);
+ assert_eq!(items(&h).0, 1, "the two frames are grouped");
+ assert!(row(&h, group).is_none(), "the matches closed");
+ assert!(!h.ctx.memory(|m| m.has_focus(super::search_id())), "the field gave the keyboard back");
+ }
+
+ #[test]
+ fn keys_typed_in_the_search_field_stay_out_of_the_document() {
+ let mut h = searching();
+ h.state_mut().app.run("edit.selectAll", serde_json::json!({})).unwrap();
+ // Escape would switch this tool back to the Selection tool.
+ h.state_mut().app.run("tool.select", serde_json::json!({"tool": "rectangleFrame"})).unwrap();
+ h.run_steps(2);
+ // Tool keys, Delete and Backspace edit the query; the tool and the frames stay.
+ for key in [egui::Key::P, egui::Key::T, egui::Key::M, egui::Key::Delete, egui::Key::Backspace] {
+ h.key_press(key);
+ h.run_steps(2);
+ }
+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
+ h.run_steps(2);
+ assert_eq!(h.state().app.session.tool_id(), "rectangleFrame");
+ assert_eq!(items(&h), (2, 2), "nothing was deleted or deselected");
+ h.event(egui::Event::Text("zz-no-such-command".into()));
+ h.run_steps(4);
+ assert!(h.query_by_label(crate::i18n::tr("de", "No matching commands")).is_some());
+ // Escape closes the matches and clears the field without touching the document.
+ h.key_press(egui::Key::Escape);
+ h.run_steps(4);
+ assert!(h.query_by_label(crate::i18n::tr("de", "No matching commands")).is_none());
+ assert!(!h.ctx.text_edit_focused());
+ assert_eq!(h.state().app.session.tool_id(), "rectangleFrame");
+ assert_eq!(items(&h), (2, 2));
+ let field = search_node(&h);
+ assert_eq!(field.value().unwrap_or_default(), "", "the query is cleared");
+ }
+
+ /// The status bar's preflight count is a menu; its Preflight Panel entry shows the panel.
+ #[test]
+ fn status_bar_error_count_opens_the_preflight_panel() {
+ let mut app = app();
+ app.run("file.new", serde_json::json!({})).unwrap();
+ app.ui.dock_tab = "properties".into();
+ let mut h = test_window::open(app, vec2(1200.0, 700.0));
+ h.get_by_label("No errors ▾").click();
+ h.run_steps(3);
+ h.get_by_label("Preflight Panel…").click();
+ h.run_steps(3);
+ // Preflight is in the iconic column: `window.panel` shows it.
+ assert!(crate::panel_docking::showing(&h.state().app, "preflight"));
+ assert!(h.query_all_by_label("Preflight").count() >= 2, "its icon and its tab in the flyout");
+ // With the panel already showing, the entry keeps it open.
+ h.get_by_label("No errors ▾").click();
+ h.run_steps(3);
+ h.get_by_label("Preflight Panel…").click();
+ h.run_steps(3);
+ assert!(crate::panel_docking::showing(&h.state().app, "preflight"));
+ }
+
++ /// The course's chapter 25: while a parent is shown, the status bar's page box names it
++ /// ("A-Parent"), as InDesign's. Its menu lists the pages, then the parents: a parent shows
++ /// that parent, a page leaves the parents for that page.
++ #[test]
++ fn the_page_box_names_the_parent_in_view_and_lists_the_parents() {
++ use egui::accesskit::Role;
++ let mut app = app();
++ app.run("file.new", serde_json::json!({"pages": 4, "facingPages": true})).unwrap();
++ app.run("layout.parents.new", serde_json::json!({"prefix": "B", "name": "Cover"})).unwrap();
++ app.ui.dock_tab = "properties".into();
++ let mut h = test_window::open(app, vec2(1200.0, 700.0));
++ let shown = |h: &egui_kittest::Harness<'static, test_window::Window>| {
++ let b = h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page"));
++ b.value().unwrap_or_default()
++ };
++ assert_eq!(shown(&h), "1");
++ h.state_mut().app.run("layout.parents.edit", serde_json::json!({"on": true})).unwrap();
++ h.run_steps(6);
++ assert_eq!(shown(&h), "A-Parent");
++ // The menu: a parent.
++ h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")).click();
++ h.run_steps(3);
++ for name in ["1", "2", "3", "4", "A-Parent"] {
++ assert!(h.query_by_label(name).is_some(), "{name} is listed");
++ }
++ h.get_by_label("B-Cover").click();
++ h.run_steps(6);
++ assert_eq!(shown(&h), "B-Cover");
++ assert_eq!(crate::canvas::current_parent_page(&h.state().app).map(|(i, _)| i), Some(1));
++ // A page: the parents are left.
++ h.get_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Page")).click();
++ h.run_steps(3);
++ h.get_by_label("3").click();
++ h.run_steps(6);
++ assert!(!h.state().app.session.active().unwrap().editing_parents);
++ assert_eq!(crate::canvas::current_page(&h.state().app), Some(2));
++ assert_eq!(shown(&h), "3");
++ // Its accessible name is in the interface's language.
++ h.state_mut().app.ui.language = "de".into();
++ h.run_steps(3);
++ assert!(h.query_by(|n| n.role() == Role::ComboBox && n.label().as_deref() == Some("Seite")).is_some(), "the page box is Seite");
++ }
++
+ /// As in InDesign, double-clicking the preflight count (or its light) shows the panel.
+ #[test]
+ fn double_clicking_the_status_bar_error_count_opens_the_preflight_panel() {
+ let mut app = app();
+ app.run("file.new", serde_json::json!({})).unwrap();
+ app.ui.dock_tab = "properties".into();
+ let mut h = test_window::open_stepped(app, vec2(1200.0, 700.0), 1.0, 1.0 / 60.0);
+ let count = h.get_by_label("No errors ▾");
+ count.click();
+ count.click();
+ h.run_steps(3);
+ assert!(crate::panel_docking::showing(&h.state().app, "preflight"));
+ assert!(h.query_all_by_label("Preflight").count() >= 2, "its icon and its tab in the flyout");
+ assert!(h.query_by_label("Preflight Panel…").is_none(), "the menu isn't left open");
+ // A double-click with the panel already showing keeps it open (the first click closes
+ // its flyout, the double-click opens it again). Past the double-click time, so the
+ // clicks are not counted with the ones before.
+ h.run_steps(30);
+ let count = h.get_by_label("No errors ▾");
+ count.click();
+ count.click();
+ h.run_steps(3);
+ assert!(crate::panel_docking::showing(&h.state().app, "preflight"));
+ }
+
+ /// A very long document name made its tab grow past the window, hiding the close button
+ /// and the tabs after it (#603).
+ #[test]
+ fn long_document_names_keep_tabs_short_and_close_buttons_visible() {
+ let latin = "Quarterly report with a very long file name ".repeat(6);
+ let hebrew = "דוח רבעוני עם שם קובץ ארוך מאוד ".repeat(6);
+ // Use the bundled or pinned test face; optional-input builds without either skip
+ // the Hebrew tab explicitly instead of rendering tofu under the strict glyph policy.
+ let hebrew_ok = test_window::install_test_hebrew_face();
+ if !hebrew_ok {
+ eprintln!("skipped the Hebrew tab: set DESIGNCRAFT_TEST_HEBREW_FONT to the pinned NotoSansHebrew.ttf");
+ }
+ let mut app = app();
+ app.run("file.new", serde_json::json!({ "title": latin })).unwrap();
+ if hebrew_ok {
+ app.run("file.new", serde_json::json!({ "title": hebrew })).unwrap();
+ }
+ app.run("file.new", serde_json::json!({ "title": "Short" })).unwrap();
+ let h = test_window::open(app, vec2(1200.0, 600.0));
+ let titles = if hebrew_ok { vec![latin.as_str(), hebrew.as_str()] } else { vec![latin.as_str()] };
+ for title in titles {
+ let tab = rect(&h, title);
+ assert!(tab.width() <= super::DOC_TAB_MAX_W, "{title:?} tab is {} wide", tab.width());
+ let close = rect(&h, &format!("Close {title}"));
+ assert!(tab.contains_rect(close), "close button {close:?} outside its tab {tab:?}");
+ }
+ let (first, short) = (rect(&h, &latin), rect(&h, "Short"));
+ assert!(short.min.x - first.min.x <= 2.0 * super::DOC_TAB_MAX_W, "the last tab {short:?} starts too far right");
+ }
+
+ /// Zero2Graphic's page layout video (0:48): with the Type tool, the Control panel's font size
+ /// has a list of sizes; the instructor picks 72 pt from it. Leading has the same list.
+ #[test]
+ fn the_type_control_panel_lists_font_sizes_and_leadings() {
+ let mut app = app();
+ app.run("file.new", serde_json::json!({})).unwrap();
+ let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Headline"})).unwrap();
+ app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 8})).unwrap();
+ app.session.set_tool("type");
+ let mut h = test_window::open(app, vec2(1800.0, 700.0));
+ let bar = test_window::panel_rect(&h, "control_bar");
+ let in_bar = |r: &egui::Rect| bar.y_range().contains(r.center().y);
+ let field = |h: &egui_kittest::Harness<'static, test_window::Window>, value: &str| {
+ h.query_all_by_value(value).map(|n| n.rect()).find(in_bar).unwrap_or_else(|| panic!("no {value:?} field in the Control panel"))
+ };
+ let press = |h: &mut egui_kittest::Harness<'static, test_window::Window>, p: egui::Pos2| {
+ h.hover_at(p);
+ h.drag_at(p);
+ h.drop_at(p);
+ };
+ let size_of = |h: &egui_kittest::Harness<'static, test_window::Window>| {
+ let st = h.state().app.session.doc().unwrap();
+ let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap());
+ st.doc.story(sid).unwrap().format_after(0).over.size
+ };
+ // The ⌄ segment right of the size field opens the list; choosing 72 pt sets the size.
+ let size = field(&h, "12 pt");
+ let chevron = pos2(size.max.x + 1.0 + crate::widgets::SEG_W / 2.0, size.center().y);
+ press(&mut h, chevron);
+ h.run_steps(3);
+ h.get_by_label("72 pt").click();
+ h.run_steps(3);
+ assert_eq!(size_of(&h), Some(72.0));
+ // Auto leading shows in parentheses, with the same list beside it.
+ let lead = field(&h, "(86.4 pt)");
+ press(&mut h, pos2(lead.max.x + 1.0 + crate::widgets::SEG_W / 2.0, lead.center().y));
+ h.run_steps(3);
+ h.get_by_label("60 pt").click();
+ h.run_steps(3);
+ let st = h.state().app.session.doc().unwrap();
+ let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap());
+ assert_eq!(st.doc.story(sid).unwrap().format_after(0).over.leading, Some(designcraft_doc::Leading::Points(60.0)));
+ // The spinner left of the size steps it by a point.
+ let size = field(&h, "72 pt");
+ press(&mut h, pos2(size.min.x - 5.0 - crate::widgets::SEG_W / 2.0, size.min.y + 3.0));
+ h.run_steps(3);
+ assert_eq!(size_of(&h), Some(73.0));
+ // Typing the automatic value itself over "(87.6 pt)" fixes the leading at it.
+ h.state_mut().app.run("type.char", serde_json::json!({"attrs": {"leading": {"kind": "auto"}}})).unwrap();
+ h.run_steps(3);
+ let lead = field(&h, "(87.6 pt)");
+ press(&mut h, lead.center());
+ h.run_steps(2);
+ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });
+ h.event(egui::Event::Text("87.6".into()));
+ h.key_press(egui::Key::Enter);
+ h.run_steps(3);
+ let st = h.state().app.session.doc().unwrap();
+ let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap());
+ assert_eq!(st.doc.story(sid).unwrap().format_after(0).over.leading, Some(designcraft_doc::Leading::Points(87.6)));
+ // Escape cancels: the same typing, then Escape, leaves the leading automatic.
+ h.state_mut().app.run("type.char", serde_json::json!({"attrs": {"leading": {"kind": "auto"}}})).unwrap();
+ h.run_steps(3);
+ let auto = h.state().app.session.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.leading;
+ let lead = field(&h, "(87.6 pt)");
+ press(&mut h, lead.center());
+ h.run_steps(2);
+ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });
+ h.event(egui::Event::Text("87.6".into()));
+ h.key_press(egui::Key::Escape);
+ h.run_steps(3);
+ assert_eq!(h.state().app.session.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.leading, auto, "Escape leaves it automatic");
+ // Escape also reverts a different number, in the leading field and in a plain one. (It
+ // leaves the text too, so each try selects it again.)
+ for (shown, typed) in [("(87.6 pt)", "20"), ("73 pt", "50")] {
+ h.state_mut().app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 8})).unwrap();
+ h.state_mut().app.session.set_tool("type");
+ h.run_steps(3);
+ let r = field(&h, shown);
+ press(&mut h, r.center());
+ h.run_steps(2);
+ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });
+ h.event(egui::Event::Text(typed.into()));
+ h.key_press(egui::Key::Escape);
+ h.run_steps(3);
+ }
+ assert_eq!(h.state().app.session.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.leading, auto, "still automatic");
+ assert_eq!(size_of(&h), Some(73.0), "the size is unchanged");
+ }
+
+ /// The Control panel's ¶ mode on a First Line Only paragraph: Align to Baseline Grid shows
+ /// pressed, and a click turns alignment off instead of making it All Lines.
+ #[test]
+ fn the_control_panel_grid_button_keeps_first_line_only() {
+ use egui_kittest::kittest::{NodeT, Queryable};
+ let mut app = app();
+ app.run("file.new", serde_json::json!({})).unwrap();
+ let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Bulbs"})).unwrap();
+ app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap();
+ app.run("type.para", serde_json::json!({"attrs": {"gridAlign": "firstLineOnly"}})).unwrap();
+ app.session.set_tool("type");
+ let mut h = test_window::open(app, vec2(2400.0, 700.0));
+ let bar = test_window::panel_rect(&h, "control_bar");
+ let in_bar = move |r: egui::Rect| bar.y_range().contains(r.center().y);
+ let click = |h: &mut egui_kittest::Harness<'static, test_window::Window>, label: &str| {
+ let r = h.query_all_by_label(label).map(|n| n.rect()).find(|r| in_bar(*r)).unwrap_or_else(|| panic!("no {label:?} in the Control panel"));
+ h.hover_at(r.center());
+ h.drag_at(r.center());
+ h.drop_at(r.center());
+ h.run_steps(3);
+ };
+ click(&mut h, "Paragraph Formatting Controls");
+ let pressed = h.query_all_by_label("Align to Baseline Grid").find(|n| in_bar(n.rect())).map(|n| n.accesskit_node().toggled());
+ assert_eq!(pressed, Some(Some(egui::accesskit::Toggled::True)));
+ assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["gridAlign"], "firstLineOnly");
+ click(&mut h, "Align to Baseline Grid");
+ assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["gridAlign"], "none");
+ }
+
+ /// The course's chapter 16: the text Control panel has InDesign's two modes. A shows the
+ /// Character Formatting Controls (the case buttons, kerning and tracking, the scales…), ¶ the
+ /// Paragraph Formatting Controls (alignment, indents, spacing, the drop cap…).
+ #[test]
+ fn the_type_control_panel_has_character_and_paragraph_modes() {
+ let mut app = app();
+ app.run("file.new", serde_json::json!({})).unwrap();
+ let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Bulbs"})).unwrap();
+ app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 5})).unwrap();
+ app.session.set_tool("type");
+ let mut h = test_window::open(app, vec2(2400.0, 700.0));
+ let bar = test_window::panel_rect(&h, "control_bar");
+ let in_bar = move |r: egui::Rect| bar.y_range().contains(r.center().y);
+ let click = |h: &mut egui_kittest::Harness<'static, test_window::Window>, label: &str| {
+ let r = h.query_all_by_label(label).map(|n| n.rect()).find(|r| in_bar(*r)).unwrap_or_else(|| panic!("no {label:?} in the Control panel"));
+ h.hover_at(r.center());
+ h.drag_at(r.center());
+ h.drop_at(r.center());
+ h.run_steps(3);
+ };
+ let has = |h: &egui_kittest::Harness<'static, test_window::Window>, label: &str| h.query_all_by_label(label).any(|n| in_bar(n.rect()));
+ assert!(has(&h, "Small Caps") && has(&h, "Vertical Scale") && !has(&h, "Drop Cap Number of Lines"));
+ click(&mut h, "Small Caps");
+ click(&mut h, "Paragraph Formatting Controls");
+ assert!(has(&h, "Drop Cap Number of Lines") && has(&h, "Space Before") && !has(&h, "Small Caps"));
+ click(&mut h, "Align to Baseline Grid");
+ click(&mut h, "Align center");
+ let a = crate::panels::text_attrs(&mut h.state_mut().app).unwrap();
+ assert_eq!(a["chars"]["capitalization"], "smallCaps");
+ assert_eq!(a["para"]["gridAlign"], "allLines");
+ assert_eq!(a["para"]["align"], "center");
+ click(&mut h, "Character Formatting Controls");
+ assert!(has(&h, "Small Caps"));
+ }
+
+ /// The course's chapter 21: the ¶ Control panel has InDesign's Bulleted and Numbered List
+ /// buttons (with the default hanging indent), and Shading and Border with their colours and
+ /// the Paragraph Borders and Shading dialog.
+ #[test]
+ fn the_paragraph_control_panel_has_lists_shading_and_border() {
+ let mut app = app();
+ app.run("file.new", serde_json::json!({})).unwrap();
+ let f = app
+ .run(
+ "frame.create",
+ serde_json::json!({"rect": [72, 72, 400, 300], "content": "text", "text": "4 eggs
+ 1 cup milk"}),
+ )
+ .unwrap();
+ app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 15})).unwrap();
+ app.session.set_tool("type");
+ let mut h = test_window::open(app, vec2(2400.0, 700.0));
+ let bar = test_window::panel_rect(&h, "control_bar");
+ let in_bar = move |r: egui::Rect| bar.y_range().contains(r.center().y);
+ let click = |h: &mut egui_kittest::Harness<'static, test_window::Window>, label: &str, nth: usize| {
+ let r = h
+ .query_all_by_label(label)
+ .map(|n| n.rect())
+ .filter(|r| in_bar(*r))
+ .nth(nth)
+ .unwrap_or_else(|| panic!("no {label:?} in the Control panel"));
+ h.hover_at(r.center());
+ h.drag_at(r.center());
+ h.drop_at(r.center());
+ h.run_steps(3);
+ };
+ click(&mut h, "Paragraph Formatting Controls", 0);
+ click(&mut h, "Bulleted List", 0);
+ let a = crate::panels::text_attrs(&mut h.state_mut().app).unwrap();
+ assert_eq!(
+ (a["para"]["listType"].as_str(), a["para"]["leftIndent"].as_f64(), a["para"]["firstLineIndent"].as_f64()),
+ (Some("bullets"), Some(18.0), Some(-18.0))
+ );
+ click(&mut h, "Numbered List", 0);
+ assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["listType"], "numbers");
+ click(&mut h, "Shading", 0);
+ click(&mut h, "Border", 0);
+ let a = crate::panels::text_attrs(&mut h.state_mut().app).unwrap();
+ assert_eq!((a["para"]["shadingOn"].as_bool(), a["para"]["borderOn"].as_bool()), (Some(true), Some(true)));
+ assert!(h.query_all_by_label("Paragraph Shading").any(|n| in_bar(n.rect())), "the shading colour");
+ // The icon beside Border opens the dialog on its Border tab.
+ click(&mut h, "Paragraph Borders and Shading…", 1);
+ let d = h.state().app.ui.dialog.clone().expect("the dialog");
+ assert_eq!((d.id.as_str(), d.s("section").as_str()), ("paragraphLocal", "border"));
+ // The Last Line Right Indent takes a negative value, as the First Line Left Indent does.
+ h.state_mut().app.ui.dialog = None;
+ h.state_mut().app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 15})).unwrap();
+ h.state_mut().app.session.set_tool("type");
+ h.run_steps(3);
+ // The field is labelled by its icon.
+ let at = h
+ .query_all_by_label("Last Line Right Indent")
+ .filter(|n| n.accesskit_node().role() == egui::accesskit::Role::TextInput)
+ .map(|n| n.rect())
+ .find(|r| in_bar(*r))
+ .expect("the last line indent")
+ .center();
+ h.hover_at(at);
+ h.drag_at(at);
+ h.drop_at(at);
+ h.run_steps(2);
+ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });
+ h.event(egui::Event::Text("-0p6".into()));
+ h.key_press(egui::Key::Enter);
+ h.run_steps(3);
+ assert_eq!(crate::panels::text_attrs(&mut h.state_mut().app).unwrap()["para"]["lastLineIndent"].as_f64(), Some(-6.0));
+ }
+
+ #[test]
+ fn the_page_tool_has_its_own_control_panel() {
+ // Chris Cicchino's Page Tool and Liquid Layout video (1:02): with the Page tool, the
+ // Control panel shows the page's size, preset, orientation and liquid page rule.
+ let mut app = app();
+ app.run("file.new", serde_json::json!({"width": 252, "height": 144, "facingPages": false})).unwrap();
+ app.session.set_tool("page");
+ let mut h = test_window::open(app, vec2(1800.0, 600.0));
+ let _ = h.get_by_label("Liquid Page Rule:");
+ // Pages don't move within their spread, so there is no "Objects Move with Page" option, and
+ // no "Controlled by Parent" rule until parent pages have rules of their own.
+ assert!(h.query_by_label("Objects Move with Page").is_none());
+ assert!(!crate::panels::interactive::LIQUID_RULES.iter().any(|(r, _)| *r == designcraft_doc::LiquidRule::ControlledByParent));
+ assert_eq!(crate::panels::properties::preset_name(252.0, 144.0), "US Business Card");
+ h.get_by_label("Show Parent Page Overlay").click();
+ h.run_steps(4);
+ assert!(h.state().app.session.doc().unwrap().doc.spreads[0].pages[0].show_parent_overlay);
+ }
+
+ #[test]
+ fn a_narrow_window_scrolls_the_control_bar() {
+ let w = 700.0;
+ let mut h = test_window::open(app_with_selection(), vec2(w, 600.0));
+ let bar = test_window::panel_rect(&h, "control_bar");
+ assert!(rect(&h, LAST_CONTROL).max.x > w, "the controls are wider than the window");
+ // A plain mouse wheel scrolls the bar sideways.
+ let first = rect(&h, FIRST_CONTROL).center();
+ wheel(&mut h, first, vec2(0.0, -3000.0));
+ let last = rect(&h, LAST_CONTROL);
+ let window = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(w, 600.0));
+ assert!(window.contains_rect(last) && bar.contains_rect(last), "{last:?} outside the bar {bar:?}");
+ assert_eq!(test_window::panel_rect(&h, "control_bar").height(), bar.height(), "the bar keeps its height");
+ // A popup opened from a scrolled control opens at that control.
+ let appearance = group(&h, "appearance");
+ let fill = egui::Rect::from_min_size(appearance.min, vec2(30.0, crate::widgets::FIELD_H));
+ let chip = pos2(fill.min.x + 9.0, fill.center().y);
+ h.hover_at(chip);
+ h.drag_at(chip);
+ h.drop_at(chip);
+ h.run_steps(4);
+ let item = rect(&h, "[Black]");
+ assert!(item.min.y > fill.max.y && (item.min.x - chip.x).abs() < 120.0, "popup item at {item:?}, control at {chip:?}");
+ }
+
+ #[test]
+ fn the_mac_app_bar_centres_and_clears_the_traffic_lights() {
+ use super::{MAC_APP_BAR, MAC_CONTENT_LEFT, MAC_LIGHT, MAC_LIGHT_PITCH, MAC_LIGHTS_LEFT};
+ // Content keeps the same gap after the lights as the lights keep from the top.
+ let margin = (MAC_APP_BAR - MAC_LIGHT) / 2.0;
+ assert_eq!(MAC_CONTENT_LEFT - (MAC_LIGHTS_LEFT + 2.0 * MAC_LIGHT_PITCH + MAC_LIGHT), margin);
+ // `egui::Margin` is in `i8`.
+ assert!(MAC_CONTENT_LEFT <= f32::from(i8::MAX));
+ let mut app = app();
+ app.integrated_titlebar = true;
+ let h = test_window::open(app, vec2(1400.0, 900.0));
+ // The bar's controls share the lights' centre line and start after them (relative to the
+ // bar, which the test window insets).
+ let bar = test_window::panel_rect(&h, "app_bar").min.to_vec2();
+ let home = rect(&h, "Home").translate(-bar);
+ assert_eq!(home.center().y, MAC_APP_BAR / 2.0, "{home:?}");
+ assert!(home.min.y >= 2.0 && home.min.x >= MAC_CONTENT_LEFT, "{home:?}");
+ for label in ["File", "Help", "Share"] {
+ let r = rect(&h, label).translate(-bar);
+ assert!((r.center().y - MAC_APP_BAR / 2.0).abs() <= 0.5 && r.max.y <= MAC_APP_BAR, "{label} at {r:?}");
+ }
+ }
+
+ fn press(h: &egui_kittest::Harness<'static, test_window::Window>, pos: egui::Pos2, pressed: bool) {
+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
+ }
+
+ /// The window commands the app sends over the next `steps` frames.
+ fn window_commands(h: &mut egui_kittest::Harness<'static, test_window::Window>, steps: usize) -> Vec<egui::ViewportCommand> {
+ let mut out = Vec::new();
+ for _ in 0..steps {
+ h.step();
+ if let Some(v) = h.output().viewport_output.get(&egui::ViewportId::ROOT) {
+ out.extend(v.commands.iter().cloned());
+ }
+ }
+ out
+ }
+
+ fn double_click(h: &mut egui_kittest::Harness<'static, test_window::Window>, pos: egui::Pos2) -> Vec<egui::ViewportCommand> {
+ h.hover_at(pos);
+ h.step();
+ // One frame: the harness gives each queued event a frame of its own, longer apart than a
+ // double-click allows.
+ for pressed in [true, false, true, false] {
+ h.input_mut().events.push(egui::Event::PointerButton {
+ pos,
+ button: egui::PointerButton::Primary,
+ pressed,
+ modifiers: egui::Modifiers::NONE,
+ });
+ }
+ window_commands(h, 3)
+ }
+
+ fn drag(h: &mut egui_kittest::Harness<'static, test_window::Window>, from: egui::Pos2) -> Vec<egui::ViewportCommand> {
+ h.hover_at(from);
+ h.step();
+ press(h, from, true);
+ let mut out = window_commands(h, 1);
+ for i in 1..=6 {
+ h.hover_at(from + vec2(8.0 * i as f32, 3.0));
+ out.extend(window_commands(h, 1));
+ }
+ press(h, from + vec2(48.0, 3.0), false);
+ out.extend(window_commands(h, 2));
+ out
+ }
+
+ #[test]
+ fn the_empty_mac_title_bar_zooms_and_moves_the_window() {
+ use super::{MAC_APP_BAR, MAC_CONTENT_LEFT};
+ use egui::ViewportCommand::{Maximized, Minimized, StartDrag};
+ let mut app = app();
+ app.integrated_titlebar = true;
+ let mut h = test_window::open(app, vec2(1400.0, 900.0));
+ let bar = test_window::panel_rect(&h, "app_bar");
+ // Under the centred title, and between the traffic lights and the Home button.
+ let empty = [pos2(bar.center().x, bar.min.y + MAC_APP_BAR / 2.0), pos2(bar.min.x + MAC_CONTENT_LEFT - 4.0, bar.min.y + 4.0)];
+ for at in empty {
+ // Tests read the setting as its default, zoom.
+ let cmds = double_click(&mut h, at);
+ assert_eq!(cmds, vec![Maximized(true)], "double-click at {at:?}");
+ let cmds = drag(&mut h, at);
+ assert_eq!(cmds, vec![StartDrag], "drag from {at:?}");
+ }
+ // The bar's controls keep their clicks and drags.
+ for label in ["Home", "Share", "File"] {
+ let at = rect(&h, label).center();
+ let cmds = double_click(&mut h, at);
+ assert!(!cmds.iter().any(|c| matches!(c, Maximized(_) | Minimized(_))), "double-click on {label}: {cmds:?}");
+ if label == "Home" {
+ assert_eq!(h.state().app.ui.status, "Home", "Home took its clicks");
+ }
+ h.key_press(egui::Key::Escape);
+ h.run_steps(2);
+ let cmds = drag(&mut h, at);
+ assert!(!cmds.contains(&StartDrag), "drag from {label}: {cmds:?}");
+ h.key_press(egui::Key::Escape);
+ h.run_steps(2);
+ }
+ }
+
+ #[test]
+ fn the_mac_window_is_not_movable_on_the_title_bar_controls() {
+ use super::{MAC_APP_BAR, MAC_CONTENT_LEFT};
+ let mut app = app();
+ app.integrated_titlebar = true;
+ let mut h = test_window::open(app, vec2(1400.0, 900.0));
+ let bar = test_window::panel_rect(&h, "app_bar");
+ let mid = bar.min.y + MAC_APP_BAR / 2.0;
+ // The search field is the bar's last control: 125 wide, 4 from the 10-wide right margin.
+ let search = pos2(bar.max.x - 10.0 - 4.0 - 60.0, mid);
+ let controls = [rect(&h, "Home").center(), rect(&h, "Share").center(), rect(&h, "File").center(), search];
+ let mut movable_at = |at: egui::Pos2| {
+ h.hover_at(at);
+ h.run_steps(2);
+ craft_window::title_bar::window_movable(&h.ctx)
+ };
+ for at in [pos2(bar.center().x, mid), pos2(bar.min.x + MAC_CONTENT_LEFT - 4.0, bar.min.y + 4.0), pos2(bar.center().x, 500.0)] {
+ assert!(movable_at(at), "empty title bar or the page at {at:?}");
+ }
+ for at in controls {
+ assert!(!movable_at(at), "control at {at:?}");
+ }
+ }
+
+ #[test]
+ fn a_narrow_window_scrolls_the_app_bar() {
+ let w = 640.0;
+ let mut h = test_window::open(app(), vec2(w, 600.0));
+ let (help, share) = (rect(&h, "Help"), rect(&h, "Share"));
+ assert!(help.max.x <= share.min.x, "the menus ({help:?}) and the workspace controls ({share:?}) overlap");
+ wheel(&mut h, help.center(), vec2(0.0, -3000.0));
+ let share = rect(&h, "Share");
+ let window = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(w, 600.0));
+ assert!(window.contains_rect(share), "{share:?} outside the window");
+ }
+
+ #[test]
+ fn a_wide_window_does_not_scroll_the_bars() {
+ let mut h = test_window::open(app(), vec2(1400.0, 900.0));
+ let before = [rect(&h, FIRST_CONTROL), rect(&h, LAST_CONTROL), rect(&h, "Help"), rect(&h, "Share")];
+ assert!(before.iter().all(|r| r.max.x <= 1400.0), "{before:?}");
+ wheel(&mut h, before[0].center(), vec2(0.0, -3000.0));
+ wheel(&mut h, before[2].center(), vec2(0.0, -3000.0));
+ let after = [rect(&h, FIRST_CONTROL), rect(&h, LAST_CONTROL), rect(&h, "Help"), rect(&h, "Share")];
+ assert_eq!(after, before);
+ }
+
+ /// At 115% the app bar fits a wide window exactly: it must not scroll sideways by a rounding error.
+ #[test]
+ fn the_app_bar_does_not_scroll_at_115_percent() {
+ let w = 1400.0;
+ let mut h = test_window::open_scaled(app(), vec2(w, 900.0), 1.15);
+ assert_eq!(h.ctx.pixels_per_point(), 1.15);
+ let before = [rect(&h, "Help"), rect(&h, "Share")];
+ assert!(before.iter().all(|r| r.max.x <= w), "{before:?}");
+ wheel(&mut h, before[0].center(), vec2(0.0, -3000.0));
+ wheel(&mut h, before[0].center(), vec2(-3000.0, 0.0));
+ let after = [rect(&h, "Help"), rect(&h, "Share")];
+ assert_eq!(after, before, "the app bar scrolled sideways although everything fits");
+ }
+
+ #[test]
+ fn a_scrolled_bar_keeps_its_captions_on_one_line() {
+ let mut app = app();
+ app.run("file.new", serde_json::json!({})).unwrap();
+ let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hello"})).unwrap();
+ app.run("selection.set", serde_json::json!({"ids": [f["id"]]})).unwrap();
+ let mut h = test_window::open(app, vec2(700.0, 600.0));
+ let bar = test_window::panel_rect(&h, "control_bar").center();
+ wheel(&mut h, bar, vec2(0.0, -3000.0));
+ // The text frame's last group keeps its full size, not only what is left of the row.
+ let columns = group(&h, "columns");
+ assert!(columns.width() >= 48.0 && columns.max.x <= 700.0, "Columns group squeezed or off screen: {columns:?}");
+ }
+
+ struct WindowHarness {
+ ctx: egui::Context,
+ app: DesignApp,
+ time: f64,
+ maximized: bool,
+ size: egui::Vec2,
+ }
+
+ impl WindowHarness {
+ fn new() -> Self {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.custom_titlebar = true;
+ let ctx = egui::Context::default();
+ crate::theme::install_fonts(&ctx, "");
+ let mut harness = Self { ctx, app, time: 0.0, maximized: false, size: vec2(1440.0, 900.0) };
+ harness.frame(vec![]);
+ harness.frame(vec![]);
+ harness
+ }
+
+ fn frame(&mut self, events: Vec<egui::Event>) -> Vec<egui::ViewportCommand> {
+ self.time += 0.1;
+ let mut input = egui::RawInput {
+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, self.size)),
+ time: Some(self.time),
+ events,
+ ..Default::default()
+ };
+ input.viewports.entry(egui::ViewportId::ROOT).or_default().maximized = Some(self.maximized);
+ let mut output = self.ctx.run_ui(input, |ui| {
+ app_bar(&mut self.app, ui);
+ resize_borders(&mut self.app, ui);
+ });
+ output.textures_delta.clear();
+ output.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.commands.clone()).unwrap_or_default()
+ }
+
+ fn press(&mut self, pos: egui::Pos2) -> Vec<egui::ViewportCommand> {
+ self.frame(vec![
+ egui::Event::PointerMoved(pos),
+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() },
+ ])
+ }
+
+ fn click(&mut self, pos: egui::Pos2) -> Vec<egui::ViewportCommand> {
+ let mut commands = self.press(pos);
+ commands.extend(self.frame(vec![egui::Event::PointerButton {
+ pos,
+ button: egui::PointerButton::Primary,
+ pressed: false,
+ modifiers: Default::default(),
+ }]));
+ commands
+ }
+
+ fn caption_center(&self, id: &str) -> egui::Pos2 {
+ self.ctx.read_response(egui::Id::unique(id)).unwrap().rect.center()
+ }
+ }
+
+ #[test]
+ fn caption_buttons_minimize_maximize_restore_and_close() {
+ let mut h = WindowHarness::new();
+ for (id, command) in [("window.minimize", egui::ViewportCommand::Minimized(true)), ("window.maximize", egui::ViewportCommand::Maximized(true))] {
+ let p = h.caption_center(id);
+ assert!(h.click(p).contains(&command), "{id}");
+ }
+ h.maximized = true;
+ h.frame(vec![]);
+ let p = h.caption_center("window.maximize");
+ assert!(h.click(p).contains(&egui::ViewportCommand::Maximized(false)));
+ let p = h.caption_center("window.close");
+ assert!(h.click(p).contains(&egui::ViewportCommand::Close));
+ }
+
+ #[test]
+ fn title_area_drags_and_double_clicks_but_menus_do_not_drag() {
+ let mut h = WindowHarness::new();
+ let title = h.ctx.read_response(egui::Id::unique("window_title_drag")).unwrap().rect;
+ assert!(title.width() > 0.0, "there is a drag region between menus and tools");
+ let p = title.center();
+ let mut commands = h.press(p);
+ commands.extend(h.frame(vec![egui::Event::PointerMoved(p + vec2(20.0, 0.0))]));
+ assert!(commands.contains(&egui::ViewportCommand::StartDrag));
+
+ let mut h = WindowHarness::new();
+ h.click(p);
+ assert!(h.click(p).contains(&egui::ViewportCommand::Maximized(true)));
+
+ let mut h = WindowHarness::new();
+ let p = egui::pos2(70.0, 18.0); // File menu, outside the title's drag region.
+ let mut commands = h.press(p);
+ commands.extend(h.frame(vec![egui::Event::PointerMoved(title.center())]));
+ assert!(!commands.contains(&egui::ViewportCommand::StartDrag));
+ }
+
+ #[test]
+ fn edges_resize_only_when_the_window_is_restored() {
+ let mut h = WindowHarness::new();
+ let p = egui::pos2(1438.0, 400.0);
+ let mut commands = h.press(p);
+ commands.extend(h.frame(vec![egui::Event::PointerMoved(p + vec2(-20.0, 0.0))]));
+ assert!(commands.contains(&egui::ViewportCommand::BeginResize(egui::ResizeDirection::East)));
+ let mut h = WindowHarness::new();
+ h.maximized = true;
+ h.frame(vec![]);
+ let mut commands = h.press(p);
+ commands.extend(h.frame(vec![egui::Event::PointerMoved(p + vec2(-20.0, 0.0))]));
+ assert!(!commands.iter().any(|c| matches!(c, egui::ViewportCommand::BeginResize(_))));
+ }
+
+ #[test]
+ fn native_window_actions_are_unavailable_without_custom_chrome() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ assert!(!crate::menus::enabled(&app, "window.close"));
+ assert!(app.run("window.close", json!({})).is_err());
+ assert!(app.pending_window_commands.is_empty());
+ app.custom_titlebar = true;
+ assert!(app.run("window.resize", json!({"edge": "invalid"})).is_err());
+ assert!(app.pending_window_commands.is_empty());
+ }
+
+ #[test]
+ fn caption_buttons_stay_put_while_a_narrow_app_bar_scrolls() {
+ let mut h = WindowHarness::new();
+ h.size = vec2(640.0, 560.0);
+ h.frame(vec![]);
+ h.frame(vec![]);
+ let rect = |h: &WindowHarness, id: &str| h.ctx.read_response(egui::Id::unique(id)).unwrap().rect;
+ let menus_end = |h: &WindowHarness| h.ctx.data(|d| d.get_temp::<f32>(egui::Id::unique("app_bar_menus_end"))).unwrap();
+ let (close, menus0) = (rect(&h, "window.close"), menus_end(&h));
+ assert!(close.left() >= 0.0 && close.right() <= h.size.x, "{close:?}");
+ let p = egui::pos2(200.0, 18.0);
+ h.frame(vec![
+ egui::Event::PointerMoved(p),
+ egui::Event::MouseWheel {
+ unit: egui::MouseWheelUnit::Point,
+ delta: vec2(0.0, -3000.0),
+ phase: egui::TouchPhase::Move,
+ modifiers: egui::Modifiers::NONE,
+ source: egui::MouseWheelSource::Unknown,
+ },
+ ]);
+ for _ in 0..10 {
+ h.frame(vec![]);
+ }
+ assert!(menus_end(&h) < menus0, "the menus scrolled");
+ assert_eq!(rect(&h, "window.close"), close, "the caption buttons did not");
+ assert!(h.click(close.center()).contains(&egui::ViewportCommand::Close));
+ }
+
+ #[test]
+ fn the_window_drags_from_its_lower_band_at_the_minimum_width() {
+ // At 900 px the menus and tools fill the bar's row; its lower band still moves the window,
+ // and it isn't drawn over the caption buttons.
+ let mut h = WindowHarness::new();
+ h.size = vec2(900.0, 560.0);
+ h.frame(vec![]);
+ h.frame(vec![]);
+ let drag = h.ctx.read_response(egui::Id::unique("window_title_drag")).unwrap().rect;
+ let close = h.ctx.read_response(egui::Id::unique("window.close")).unwrap().rect;
+ assert!(drag.right() <= close.left() + 0.5, "{drag:?} {close:?}");
+ let p = egui::pos2(450.0, APP_BAR + APP_BAR_BAND / 2.0);
+ assert!(drag.contains(p), "{drag:?}");
+ let mut commands = h.press(p);
+ commands.extend(h.frame(vec![egui::Event::PointerMoved(p + vec2(20.0, 0.0))]));
+ assert!(commands.contains(&egui::ViewportCommand::StartDrag));
+ }
+
+ #[test]
+ fn caption_buttons_fit_the_minimum_window_width() {
+ let mut h = WindowHarness::new();
+ h.size = vec2(900.0, 560.0);
+ h.frame(vec![]);
+ h.frame(vec![]);
+ for id in ["window.minimize", "window.maximize", "window.close"] {
+ let rect = h.ctx.read_response(egui::Id::unique(id)).unwrap().rect;
+ assert!(rect.left() >= 0.0 && rect.right() <= h.size.x, "{id}: {rect:?}");
+ let p = rect.center();
+ assert!(!h.click(p).is_empty(), "{id} remains clickable");
+ }
+ }
diff --cc crates/ui-egui/src/panels/properties/document.rs
index 000000000,0a7fdbc5a..f9ac002cb
mode 000000,100644..100644
--- a/crates/ui-egui/src/panels/properties/document.rs
+++ b/crates/ui-egui/src/panels/properties/document.rs
@@@ -1,0 -1,371 +1,372 @@@
+ 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
+
+ /// Page-size presets for the Document dropdown (portrait, points).
+ pub(crate) const PAGE_PRESETS: &[(&str, f64, f64)] = &[
+ ("Letter", 612.0, 792.0),
+ ("Legal", 612.0, 1008.0),
+ ("Tabloid", 792.0, 1224.0),
+ ("Letter - Half", 396.0, 612.0),
+ ("Legal - Half", 504.0, 612.0),
+ ("A0", 841.0 * units::PT_PER_MM, 1189.0 * units::PT_PER_MM),
+ ("A1", 594.0 * units::PT_PER_MM, 841.0 * units::PT_PER_MM),
+ ("A2", 420.0 * units::PT_PER_MM, 594.0 * units::PT_PER_MM),
+ ("A3", 841.89, 1190.55),
+ ("A4", 595.276, 841.89),
+ ("A5", 419.528, 595.276),
+ ("A6", 297.638, 419.528),
+ ("B5", 498.898, 708.661),
+ ("US Business Card", 144.0, 252.0),
+ ];
+
+ pub(crate) fn preset_name(w: f64, h: f64) -> &'static str {
+ let (a, b) = (w.min(h), w.max(h));
+ PAGE_PRESETS.iter().find(|p| (p.1 - a).abs() < 0.6 && (p.2 - b).abs() < 0.6).map(|p| p.0).unwrap_or("Custom")
+ }
+
+ /// The preset dropdown and orientation toggles for one page; the new (width, height) when one changed.
+ fn page_preset_row(ui: &mut Ui, lang: &str, w: f64, h: f64) -> Option<(f64, f64)> {
+ let landscape = w > h;
+ let b = block(ui, FIELD_H);
+ let mut size = None;
+ place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| {
+ let resp = dropdown(ui, crate::i18n::tr(lang, preset_name(w, h)), 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(w, h) == p.0, crate::i18n::tr(lang, p.0)).clicked() {
+ size = Some(if landscape { (p.2, p.1) } else { (p.1, p.2) });
+ ui.close();
+ }
+ }
+ });
+ });
+ place(ui, sub(b, 126.0, 0.0, 52.0, FIELD_H), |ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ if icon_toggle(ui, "orient-portrait", !landscape, crate::i18n::tr(lang, "Portrait")).clicked() && landscape {
+ size = Some((h, w));
+ }
+ if icon_toggle(ui, "orient-landscape", landscape, crate::i18n::tr(lang, "Landscape")).clicked() && !landscape {
+ size = Some((h, w));
+ }
+ });
+ size
+ }
+
+ /// Properties with the Page tool (Properties › Edit Page), as InDesign's: a "Page" band with Back,
+ /// Page Size for this page alone (which page, preset, orientation, W/H), Margins and Columns and
+ /// Quick Actions. Back returns to the Selection tool and the document's properties.
+ pub(super) fn page_sections(app: &mut DesignApp, ui: &mut Ui, page: usize) {
+ let u = units(app);
+ let lang = app.ui.language.clone();
+ let Some(st) = app.session.active() else { return };
+ let d = st.doc.clone();
+ let Some((si, pi)) = d.page_loc(page) else { return };
+ let Some(pg) = d.spreads.get(si).and_then(|s| s.pages.get(pi)).cloned() else { return };
+ let n = page + 1;
+ let t = Tokens::get(ui.ctx());
+ // The band: "Page", and Back at its end.
+ let band = block(ui, 33.0);
+ crate::rtl::paint(
+ ui.painter(),
+ pos2(band.min.x, band.center().y + 1.0),
+ egui::Align2::LEFT_CENTER,
+ crate::i18n::tr(&lang, "Page"),
+ crate::theme::semibold(11.5),
+ t.text_strong,
+ );
+ let back = place(ui, Rect::from_min_size(pos2(band.max.x - 58.0, band.center().y - 10.0), vec2(54.0, 20.0)), |ui| {
+ outline_button(ui, crate::i18n::tr(&lang, "Back"), 54.0).clicked()
+ });
+ rule(ui);
+ if back {
+ let _ = app.run("layout.selectPage", json!({"page": null}));
+ app.select_tool("selection");
+ return;
+ }
+ section(ui, crate::i18n::tr(&lang, "Page Size"), true);
+ // Which page.
+ let b = block(ui, FIELD_H);
+ let names: Vec<String> = (0..d.page_count()).map(|i| app.session.page_label(i)).collect();
+ let picked = place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| {
+ widgets::dropdown_list(ui, names.get(page).map_or("", String::as_str), 93.0, &names, Some(page))
+ });
+ if let Some(p) = picked {
+ let _ = app.run("layout.selectPage", json!({"page": p + 1}));
+ crate::canvas::go_to_page(app, p);
+ return;
+ }
+ ui.add_space(3.0);
+ // Preset and orientation: this page alone.
+ let (w, h) = (pg.width, pg.height);
+ let mut size = page_preset_row(ui, &lang, w, h);
+ ui.add_space(3.0);
+ let b = block(ui, 2.0 * FIELD_H + 5.0);
+ for (row, (label, v, key)) in [("W:", w, "width"), ("H:", h, "height")].into_iter().enumerate() {
+ let y = row as f32 * 26.0;
+ place(ui, sub(b, 0.0, y, 20.0, FIELD_H), |ui| widgets::caption_w(ui, label, 20.0));
+ let nv = place(ui, sub(b, 21.0, y, 72.0, FIELD_H), |ui| {
+ NumField::measure(&format!("page_{key}"), Some(v), u).width(72.0).spinner().range(1.0, 15552.0).show(ui)
+ });
+ if let Some(nv) = nv {
+ size = Some(if key == "width" { (nv, h) } else { (w, nv) });
+ }
+ }
+ if let Some((nw, nh)) = size {
+ let _ = app.run("layout.pageSize", json!({"pages": [n], "width": nw, "height": nh, "anchor": app.ui.ref_point.min(8)}));
+ }
+ ui.add_space(6.0);
+ let fw = full_width(ui);
+ if outline_button(ui, crate::i18n::tr(&lang, "Margins and Columns"), fw).clicked() {
+ crate::canvas::go_to_page(app, page);
+ crate::menus::activate(app, "layout.marginsAndColumns", &Value::Null);
+ }
+ divider(ui);
+ section(ui, crate::i18n::tr(&lang, "Quick Actions"), true);
+ if outline_button(ui, crate::i18n::tr(&lang, "Import File"), fw).clicked() {
+ let _ = app.run("app.placeDialog", json!({}));
+ }
+ }
+
+ /// 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 };
+ let d = st.doc.clone();
+ let (pw, ph) = (d.settings.page_width, d.settings.page_height);
+ section(ui, crate::i18n::tr(&app.ui.language, "Document"), true);
+ // Preset dropdown + orientation.
+ let b = block(ui, FIELD_H);
+ 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| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ if icon_toggle(ui, "orient-portrait", !landscape, crate::i18n::tr(&app.ui.language, "Portrait")).clicked() && landscape {
+ orient = Some(());
+ }
+ if icon_toggle(ui, "orient-landscape", landscape, crate::i18n::tr(&app.ui.language, "Landscape")).clicked() && !landscape {
+ orient = Some(());
+ }
+ });
+ if let Some((w, h)) = preset {
+ let (w, h) = if landscape { (h, w) } else { (w, h) };
+ let _ = app.run("layout.documentSetup", json!({"width": w, "height": h}));
+ }
+ if orient.is_some() {
+ let _ = app.run("layout.documentSetup", json!({"width": ph, "height": pw}));
+ }
+ ui.add_space(3.0);
+ // W / H, page count, facing pages.
+ let b = block(ui, 2.0 * FIELD_H + 5.0);
+ for (row, (label, v, key)) in [("W:", pw, "width"), ("H:", ph, "height")].into_iter().enumerate() {
+ let y = row as f32 * 26.0;
+ place(ui, sub(b, 0.0, y, 20.0, FIELD_H), |ui| widgets::caption_w(ui, label, 20.0));
+ let nv =
+ place(ui, sub(b, 21.0, y, 72.0, FIELD_H), |ui| NumField::measure(key, Some(v), u).width(72.0).spinner().range(1.0, 15552.0).show(ui));
+ if let Some(nv) = nv {
+ let _ = app.run("layout.documentSetup", json!({key: nv}));
+ }
+ }
+ let n = d.page_count();
+ let t = Tokens::get(ui.ctx());
+ 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 {
+ 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| {
+ widgets::checkbox(ui, &mut facing, crate::i18n::tr(&app.ui.language, "Facing Pages")).changed()
+ });
+ if changed {
+ let _ = app.run("layout.documentSetup", json!({"facingPages": facing}));
+ }
+ // Margins.
+ section(ui, crate::i18n::tr(&app.ui.language, "Margins"), true);
+ let cur = crate::canvas::current_page(app).unwrap_or(0);
+ // While parent spreads are edited the fields belong to the parent page in view; they used to
+ // show (and change) the document pages instead, so nothing changed on the parent.
+ let parent_target = crate::canvas::current_parent_page(app);
+ let shown = match parent_target {
+ Some((pi, qi)) => d.parents.get(pi).and_then(|s| s.pages.get(qi)).cloned(),
+ None => d.page(cur).cloned(),
+ };
+ if let Some(p) = shown {
+ let linked = temp_bool(ui, "margins_linked", true);
+ let b = block(ui, 2.0 * FIELD_H + 5.0);
+ let mut set: Option<designcraft_doc::Margins> = None;
+ let fields = [
+ ("margin-top", "Top", p.margins.top, 0.0, 0.0),
+ ("margin-bottom", "Bottom", p.margins.bottom, 0.0, 26.0),
+ ("margin-outside", if d.settings.facing_pages { "Outside" } else { "Right" }, p.margins.outside, 127.0, 0.0),
+ ("margin-inside", if d.settings.facing_pages { "Inside" } else { "Left" }, p.margins.inside, 127.0, 26.0),
+ ];
+ for (k, (icon, tip, v, x, y)) in fields.into_iter().enumerate() {
+ let ir = sub(b, x, y + 2.0, 17.0, 17.0);
+ icons::paint(ui.painter(), ir, icon, t.icon);
+ ui.interact(ir, ui.scope_id().with(("micon", k)), Sense::hover()).on_hover_ui(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, tip));
+ });
+ let nv = place(ui, sub(b, x + 20.0, y, 73.0, FIELD_H), |ui| {
+ NumField::measure(tip, Some(v), u).width(73.0).spinner().range(0.0, 8000.0).show(ui)
+ });
+ if let Some(nv) = nv {
+ set = Some(edited_margins(p.margins, linked, k, nv));
+ }
+ }
+ let lr = sub(b, 99.0, 12.5, 22.0, FIELD_H);
+ let clicked = place(ui, lr, |ui| {
+ widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, "Make all settings the same", vec2(22.0, 21.0))
+ .clicked()
+ });
+ if clicked {
+ set_temp_bool(ui, "margins_linked", !linked);
+ }
+ if let Some(m) = set {
+ let params = match parent_target {
+ // Both pages of a facing parent spread, so the margins show wherever the parent is used.
+ Some((pi, _)) => {
+ let n = app.session.active().and_then(|st| st.doc.parents.get(pi)).map_or(1, |sp| sp.pages.len());
+ json!({"margins": m, "parent": pi, "pages": (0..n).collect::<Vec<_>>()})
+ }
+ None => json!({"margins": m}),
+ };
+ let _ = app.run("layout.marginsAndColumns", params);
+ }
+ }
+ ui.add_space(6.0);
+ let fw = full_width(ui);
+ if outline_button(ui, crate::i18n::tr(&app.ui.language, "Adjust Layout"), fw).clicked() {
+ crate::dialogs::open_document_setup(app);
+ }
+ divider(ui);
+ // Page.
+ section(ui, crate::i18n::tr(&app.ui.language, "Page"), true);
+ let b = block(ui, FIELD_H);
- let names: Vec<String> = (0..d.page_count()).map(|i| app.session.page_label(i)).collect();
- let picked = place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| {
- widgets::dropdown_list(ui, &names[cur.min(names.len().saturating_sub(1))], 93.0, &names, Some(cur))
- });
- if let Some(pg) = picked {
- crate::canvas::go_to_page(app, pg);
++ // As the status bar's page box: the page, or the parent shown ("A-Parent"); then the parents.
++ if let Some(pb) = crate::canvas::page_box(app) {
++ let picked =
++ place(ui, sub(b, 0.0, 0.0, 93.0, FIELD_H), |ui| widgets::dropdown_list(ui, pb.current_name(), 93.0, &pb.names, Some(pb.current)));
++ if let Some(i) = picked {
++ crate::canvas::page_box_go(app, &pb, i);
++ }
+ }
+ let (add, del) = place(ui, sub(b, 172.0, 0.0, 50.0, FIELD_H), |ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ let a = widgets::icon_toggle_sized(ui, "style-new", false, "Insert Page", vec2(22.0, 21.0)).clicked();
+ let d = widgets::icon_toggle_sized(ui, "trash", false, "Delete Page", vec2(22.0, 21.0)).clicked();
+ (a, d)
+ });
+ if add {
+ let _ = app.run("layout.pages.insert", json!({"after": cur, "count": 1}));
+ }
+ if del {
+ let _ = crate::dialogs::delete_pages(app, vec![cur]);
+ }
+ ui.add_space(3.0);
+ if outline_button(ui, crate::i18n::tr(&app.ui.language, "Edit Page"), fw).clicked() {
+ // As in InDesign: the Page tool on this page; Properties shows the page's own settings.
+ app.select_tool("page");
+ let _ = app.run("layout.selectPage", json!({"page": cur + 1}));
+ }
+ divider(ui);
+ // Rulers & Grids / Guides: icon toggle rows.
+ let (mut rulers, mut bl, mut dg) = (app.ui.rulers, app.ui.baseline_grid, app.ui.document_grid);
+ section_row(ui, crate::i18n::tr(&app.ui.language, "Rulers & Grids"), |ui| {
+ ui.spacing_mut().item_spacing.x = 14.0;
+ if icon_toggle(ui, "grid-document", dg, crate::i18n::tr(&app.ui.language, "Show Document Grid")).clicked() {
+ dg = !dg;
+ }
+ if icon_toggle(ui, "grid-baseline", bl, crate::i18n::tr(&app.ui.language, "Show Baseline Grid")).clicked() {
+ bl = !bl;
+ }
+ if icon_toggle(ui, "rulers", rulers, crate::i18n::tr(&app.ui.language, "Show Rulers")).clicked() {
+ rulers = !rulers;
+ }
+ });
+ if rulers != app.ui.rulers {
+ let _ = app.run("view.rulers", json!({}));
+ }
+ if bl != app.ui.baseline_grid {
+ let _ = app.run("view.baselineGrid", json!({}));
+ }
+ if dg != app.ui.document_grid {
+ let _ = app.run("view.documentGrid", json!({}));
+ }
+ rule(ui);
+ let (mut guides, mut locked, mut smart) = (app.ui.guides, app.ui.guides_locked, app.ui.smart_guides);
+ section_row(ui, crate::i18n::tr(&app.ui.language, "Guides"), |ui| {
+ ui.spacing_mut().item_spacing.x = 14.0;
+ if icon_toggle(ui, "guides-smart", smart, crate::i18n::tr(&app.ui.language, "Smart Guides")).clicked() {
+ smart = !smart;
+ }
+ if icon_toggle(ui, "guides-lock", locked, crate::i18n::tr(&app.ui.language, "Lock Guides")).clicked() {
+ locked = !locked;
+ }
+ if icon_toggle(ui, "guides-show", guides, crate::i18n::tr(&app.ui.language, "Show Guides")).clicked() {
+ guides = !guides;
+ }
+ });
+ if guides != app.ui.guides {
+ let _ = app.run("view.guides", json!({}));
+ }
+ if smart != app.ui.smart_guides {
+ let _ = app.run("view.smartGuides", json!({}));
+ }
+ if locked != app.ui.guides_locked {
+ let _ = app.run("view.lockGuides", json!({"on": locked}));
+ }
+ rule(ui);
+ section(ui, crate::i18n::tr(&app.ui.language, "Quick Actions"), true);
+ let (a, b) = button_pair(ui, crate::i18n::tr(&app.ui.language, "Import File"), crate::i18n::tr(&app.ui.language, "Insert Page"));
+ if a {
+ let _ = app.run("app.placeDialog", json!({}));
+ }
+ if b {
+ let _ = app.run("layout.pages.insert", json!({"after": cur, "count": 1}));
+ }
+ }