mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-18 16:28:21 +00:00
Part of #5941: dialogs too large for the window scroll instead of running off the screen
A dialog taller than the app window was drawn past the window's edges with no scroll bar. In a 1024 by 480 window, SVG, EPS and DXF Options, Save PDF, Export for Screens, Print, Keyboard Shortcuts and Find Font ran past the top, so their heading and first options could not be seen. Save for Web, Preferences and New Document also ran past the bottom, with their buttons out of reach. - The body of a shared dialog scrolls while the dialog would be taller than the window, and its heading and buttons stay in view. - A dialog window without such a body scrolls as a whole on each axis on which it is taller or wider than the window. Its buttons can then sit below or beside the part in view until it is scrolled. - A dialog that sizes its lists from the window's height (Import Shortcut Set, Character and Paragraph Style Options, the Color Picker) is not scrolled vertically again, but it scrolls sideways when it is wider than the window. - A list with its own scroll bar inside a scrolling body (the Save for Web settings, the Print and Save PDF sections) is no taller than the body shows, so the list and its bar can be scrolled into view whole. - A dialog that closes and opens again starts at its top. A dialog that was only hidden while another opened over it (Keyboard Shortcuts under Import Shortcut Set) keeps where it was scrolled to. - A field being edited keeps its text and focus when a resize makes the dialog start or stop scrolling. - Save for Web in a window narrower than its full layout draws its preview panes narrower, down to 240 pt, so the settings column and the buttons stay in view. Reported by erolkarino in #5941.
This commit is contained in:
@@ -831,6 +831,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
let focus_first = focus_first && !clicked;
|
||||
let spec = spec(&d.kind);
|
||||
// Opened over another dialog, which Cancel shows again: that one keeps where it was scrolled to.
|
||||
if d.fields.get(PARENT).is_some_and(|p| !p.is_null()) {
|
||||
modal::over_parent(ctx);
|
||||
}
|
||||
if let Some(window) = spec.window {
|
||||
return window(app, ctx);
|
||||
}
|
||||
@@ -873,14 +877,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
if focus_first {
|
||||
ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true));
|
||||
}
|
||||
// When the dialog is taller than the window, its body scrolls, and the heading and the
|
||||
// buttons stay in view.
|
||||
if let Some(body) = spec.body_with_actions {
|
||||
match body(app, ui, &mut d) {
|
||||
match modal::body_rows(ui, |ui| body(app, ui, &mut d)) {
|
||||
DialogAction::None => {}
|
||||
DialogAction::Confirm => ok = true,
|
||||
DialogAction::Cancel => cancel = true,
|
||||
}
|
||||
} else {
|
||||
cancel = (spec.body)(app, ui, &mut d);
|
||||
cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d));
|
||||
}
|
||||
// Taken (the flag is gone): done. Still there (the window's measuring frame): next frame.
|
||||
if focus_first && ui.data_mut(|m| m.remove_temp::<bool>(widgets::dialog_focus_flag())).is_none() {
|
||||
@@ -1059,6 +1065,9 @@ mod tests_perspective;
|
||||
#[cfg(test)]
|
||||
mod tests_modal;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_scroll;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_rectangular_grid;
|
||||
|
||||
|
||||
@@ -1036,6 +1036,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id {
|
||||
/// (as drawn last frame). The section list stays put while the content scrolls. Returns whether
|
||||
/// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`).
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
super::modal::fits_itself(ui);
|
||||
let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height());
|
||||
let content = ui.ctx().data(|m| m.get_temp::<f32>(content_id(ui))).unwrap_or(0.0);
|
||||
let rest = (window - content).max(0.0);
|
||||
|
||||
@@ -365,6 +365,7 @@ fn header(ui: &mut Ui, title: &str) {
|
||||
/// Draws the responsive picker and updates its color fields and live preview.
|
||||
/// Returns the requested action for the shared frame to confirm or cancel.
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction {
|
||||
super::modal::fits_itself(ui);
|
||||
let channel = Channel::parse(&d.str("channel")).unwrap_or_default();
|
||||
let web = d.bool("webOnly");
|
||||
let swatches = d.bool("swatches");
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//! window with no title bar that opens centred and moves by dragging its heading (the band from its
|
||||
//! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where
|
||||
//! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows
|
||||
//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons
|
||||
//! stay in view.
|
||||
//! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its
|
||||
//! heading and buttons stay in view. A window without such rows that is still too tall or too wide
|
||||
//! for the screen scrolls as a whole on that axis.
|
||||
|
||||
use egui::{Id, Rect, Vec2};
|
||||
|
||||
@@ -33,11 +34,89 @@ pub(crate) fn show_at<R>(ctx: &egui::Context, title: &str, id: Id, initial: Vec2
|
||||
.title_bar(false)
|
||||
.anchor(egui::Align2::CENTER_CENTER, offset(ctx, id, initial))
|
||||
.frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(margin)))
|
||||
.show(ctx, add)?;
|
||||
keep_rest(ctx, id, shown.response.rect.height());
|
||||
.show(ctx, |ui| {
|
||||
// Just opened: what scrolls in the window starts at its top, wherever it was left when
|
||||
// the window last closed.
|
||||
if opened(ctx, id) {
|
||||
ctx.data_mut(|m| {
|
||||
m.insert_temp(id.with(TOP_ROWS_KEY), true);
|
||||
m.insert_temp(id.with(TOP_WHOLE_KEY), true);
|
||||
});
|
||||
}
|
||||
// A window whose contents are wider than the screen has room for, or taller without
|
||||
// rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis,
|
||||
// so none of it is out of reach. The contents keep their ids whether the window scrolls
|
||||
// or not, so a field being edited keeps its text when that changes.
|
||||
let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default();
|
||||
let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents"));
|
||||
let (r, contents) = if wide || tall {
|
||||
let room = whole_room(ctx, margin);
|
||||
let mut area = egui::ScrollArea::new([wide, tall]);
|
||||
if ctx.data_mut(|m| m.remove_temp::<bool>(id.with(TOP_WHOLE_KEY))).is_some() {
|
||||
area = area.scroll_offset(Vec2::ZERO);
|
||||
}
|
||||
let out = area
|
||||
.id_salt("modal-whole")
|
||||
.max_width(room.x)
|
||||
.max_height(room.y)
|
||||
.min_scrolled_width(room.x)
|
||||
.min_scrolled_height(room.y)
|
||||
.show(ui, |ui| ui.scope_builder(scope, add).inner);
|
||||
(out.inner, out.content_size)
|
||||
} else {
|
||||
let r = ui.scope_builder(scope, add).inner;
|
||||
(r, ui.min_rect().size())
|
||||
};
|
||||
ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents));
|
||||
r
|
||||
})?;
|
||||
keep_rest(ctx, id, shown.response.rect.height(), margin);
|
||||
shown.inner
|
||||
}
|
||||
|
||||
/// Mark the modal window drawn next in this pass as opened over the one drawn in the pass before,
|
||||
/// which it hides until it closes and shows that one again (Import Shortcut Set over Keyboard
|
||||
/// Shortcuts). The window under it keeps where it was scrolled to.
|
||||
pub(crate) fn over_parent(ctx: &egui::Context) {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
ctx.data_mut(|m| m.insert_temp(Id::unique(OVER_KEY), pass));
|
||||
}
|
||||
|
||||
/// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before,
|
||||
/// and the window drawn in the pass before was not one opened over it ([`over_parent`]).
|
||||
fn opened(ctx: &egui::Context, id: Id) -> bool {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
ctx.data_mut(|m| {
|
||||
// The window drawn in the pass before, if another.
|
||||
let before =
|
||||
m.get_temp::<(u64, Id)>(Id::unique(LAST_KEY)).filter(|&(at, other)| other != id && at.saturating_add(1) == pass).map(|(_, other)| other);
|
||||
m.insert_temp(Id::unique(LAST_KEY), (pass, id));
|
||||
let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass);
|
||||
if last != u64::MAX && last.saturating_add(1) >= pass {
|
||||
return false;
|
||||
}
|
||||
// Shown again as the window opened over it closed.
|
||||
if before.is_some_and(|over| m.get_temp::<Id>(over.with(HOLDS_KEY)) == Some(id)) {
|
||||
return false;
|
||||
}
|
||||
// Opened over the window drawn in the pass before, it holds that one; otherwise none.
|
||||
match before.filter(|_| m.get_temp::<u64>(Id::unique(OVER_KEY)) == Some(pass)) {
|
||||
Some(under) => {
|
||||
m.insert_temp(id.with(HOLDS_KEY), under);
|
||||
}
|
||||
None => {
|
||||
m.remove::<Id>(id.with(HOLDS_KEY));
|
||||
}
|
||||
}
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// The room for the contents of a modal window with `margin` inside its frame.
|
||||
fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 {
|
||||
(ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO)
|
||||
}
|
||||
|
||||
/// The layer of the backdrop behind a modal dialog window, which takes the clicks the rest of
|
||||
/// the app would get.
|
||||
pub(crate) fn backdrop() -> egui::LayerId {
|
||||
@@ -73,34 +152,157 @@ pub(super) fn handle(id: Id) -> Id {
|
||||
id.with("modal-drag")
|
||||
}
|
||||
|
||||
/// Under a modal window's id: how tall its [`scrolled_rows`] were drawn this frame, and how tall
|
||||
/// the rest of it was when last drawn.
|
||||
/// Under a modal window's id: how tall its [`scrolled_rows`] (or [`body_rows`]) were drawn this
|
||||
/// frame, and how tall the rest of it was when last drawn.
|
||||
const ROWS_KEY: &str = "modal-rows";
|
||||
const REST_KEY: &str = "modal-rest";
|
||||
/// Under a modal window's id: its contents drew [`scrolled_rows`] of their own or fit themselves to
|
||||
/// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`).
|
||||
const OWN_ROWS_KEY: &str = "modal-own-rows";
|
||||
const OWN_BEFORE_KEY: &str = "modal-own-before";
|
||||
/// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame.
|
||||
const BODY_KEY: &str = "modal-body";
|
||||
/// Under a modal window's id: how large its contents would be without scrolling as a whole, this
|
||||
/// frame.
|
||||
const CONTENTS_KEY: &str = "modal-contents";
|
||||
/// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on
|
||||
/// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`).
|
||||
const TALL_KEY: &str = "modal-tall";
|
||||
const WHOLE_KEY: &str = "modal-whole";
|
||||
/// Under a modal window's id: the pass it was last drawn in (`SHOWN_KEY`), and, since it opened,
|
||||
/// its rows (`TOP_ROWS_KEY`) or the window as a whole (`TOP_WHOLE_KEY`) have not scrolled yet, so
|
||||
/// they start at the top when they first do.
|
||||
const SHOWN_KEY: &str = "modal-shown";
|
||||
const TOP_ROWS_KEY: &str = "modal-top-rows";
|
||||
const TOP_WHOLE_KEY: &str = "modal-top-whole";
|
||||
/// For all modal windows: the pass the last one was drawn in and its id (`LAST_KEY`), and the pass
|
||||
/// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`).
|
||||
/// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`).
|
||||
const LAST_KEY: &str = "modal-last";
|
||||
const OVER_KEY: &str = "modal-over";
|
||||
const HOLDS_KEY: &str = "modal-holds";
|
||||
|
||||
/// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window
|
||||
/// would be taller than the screen. Their height is the screen's less the rest of the window as
|
||||
/// last drawn (a frame late, as only the drawn window knows its height).
|
||||
/// Rows that fit are as tall as they are.
|
||||
pub(crate) fn scrolled_rows<R>(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
|
||||
let id = ui.layer_id().id;
|
||||
let rest = ui.ctx().data(|m| m.get_temp::<f32>(id.with(REST_KEY))).unwrap_or(0.0);
|
||||
let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0);
|
||||
// As tall as the room at once: by itself a scroll area grows a frame at a time with the window.
|
||||
let rows = ui.scope(|ui| egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room).show(ui, add).inner);
|
||||
ui.ctx().data_mut(|m| m.insert_temp(id.with(ROWS_KEY), rows.response.rect.height()));
|
||||
rows.inner
|
||||
fits_itself(ui);
|
||||
let (r, drawn, _) = rows(ui, salt, true, add);
|
||||
ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn));
|
||||
r
|
||||
}
|
||||
|
||||
/// After modal window `id` is drawn `height` tall: keep the height of all of it but its
|
||||
/// [`scrolled_rows`] for the next frame. If the rows were sized by a different one (the window just
|
||||
/// opened, or what is around them changed), the next frame is drawn at once, for the rows to fit
|
||||
/// without waiting for input.
|
||||
fn keep_rest(ctx: &egui::Context, id: Id, height: f32) {
|
||||
let Some(rows) = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(ROWS_KEY))) else { return };
|
||||
let rest = (height - rows).max(0.0);
|
||||
let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest));
|
||||
if (used - rest).abs() > 0.5 {
|
||||
/// Mark the contents of the modal window `ui` is in as fitting themselves to the screen (sizing
|
||||
/// what scrolls in them from the screen's height), so neither [`body_rows`] nor the window
|
||||
/// scroll them again.
|
||||
pub(crate) fn fits_itself(ui: &egui::Ui) {
|
||||
ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true));
|
||||
}
|
||||
|
||||
/// The body of a shared dialog window. While the window would be taller than the screen has room
|
||||
/// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view;
|
||||
/// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is.
|
||||
pub(crate) fn body_rows<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
|
||||
let id = ui.layer_id().id;
|
||||
let (r, drawn, body) = rows(ui, "dialog-body", body_scrolls(ui.ctx(), id), add);
|
||||
if !ui.ctx().data(|m| m.get_temp::<bool>(id.with(OWN_ROWS_KEY))).unwrap_or(false) {
|
||||
ui.ctx().data_mut(|m| {
|
||||
m.insert_temp(id.with(ROWS_KEY), drawn);
|
||||
m.insert_temp(id.with(BODY_KEY), body);
|
||||
});
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Whether the [`body_rows`] of modal window `id` scroll in this frame.
|
||||
fn body_scrolls(ctx: &egui::Context, id: Id) -> bool {
|
||||
let own = ctx.data(|m| m.get_temp::<bool>(id.with(OWN_BEFORE_KEY))).unwrap_or(false);
|
||||
!own && ctx.data(|m| m.get_temp::<bool>(id.with(TALL_KEY))).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// While the [`body_rows`] of the modal window `ui` is in scroll: how tall they are drawn.
|
||||
pub(crate) fn body_view(ui: &egui::Ui) -> Option<f32> {
|
||||
let id = ui.layer_id().id;
|
||||
body_scrolls(ui.ctx(), id).then(|| rows_room(ui.ctx(), id))
|
||||
}
|
||||
|
||||
/// How modal window `id` scrolls: while its [`body_rows`] scroll, how tall they are drawn; and on
|
||||
/// which axes ([wide, tall]) the window scrolls as a whole.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn scrolling(ctx: &egui::Context, id: Id) -> (Option<f32>, [bool; 2]) {
|
||||
let body = body_scrolls(ctx, id).then(|| rows_room(ctx, id));
|
||||
(body, ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The height of a list `height` tall at most, with a scroll bar of its own, in the [`body_rows`]
|
||||
/// of the modal window `ui` is in: while the body scrolls, no taller than the body is drawn, so
|
||||
/// the list and its bar can be scrolled into view whole.
|
||||
pub(crate) fn list_height(ui: &egui::Ui, height: f32) -> f32 {
|
||||
body_view(ui).map_or(height, |view| view.min(height))
|
||||
}
|
||||
|
||||
/// The height rows that scroll in modal window `id` are drawn: the screen's less the rest of the
|
||||
/// window as last drawn.
|
||||
fn rows_room(ctx: &egui::Context, id: Id) -> f32 {
|
||||
let rest = ctx.data(|m| m.get_temp::<f32>(id.with(REST_KEY))).unwrap_or(0.0);
|
||||
(ctx.content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0)
|
||||
}
|
||||
|
||||
/// [`scrolled_rows`] without marking the window's body as having rows of its own or keeping their
|
||||
/// height. Also returns how tall the rows were drawn and how tall they would be without scrolling.
|
||||
/// Rows that do not `scroll` are as tall as they are, with no
|
||||
/// scroll area (which would take the scroll requests of their fields from the window's). The rows
|
||||
/// keep their ids either way, so a field being edited keeps its text when they start or stop
|
||||
/// scrolling.
|
||||
fn rows<R>(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) {
|
||||
let id = ui.layer_id().id;
|
||||
let room = rows_room(ui.ctx(), id);
|
||||
let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows"));
|
||||
if !scroll {
|
||||
let rows = ui.scope_builder(scope, add);
|
||||
let height = rows.response.rect.height();
|
||||
return (rows.inner, height, height);
|
||||
}
|
||||
// As tall as the room at once: by itself a scroll area grows a frame at a time with the window.
|
||||
let mut area = egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room);
|
||||
if ui.ctx().data_mut(|m| m.remove_temp::<bool>(id.with(TOP_ROWS_KEY))).is_some() {
|
||||
area = area.scroll_offset(Vec2::ZERO);
|
||||
}
|
||||
let rows = ui.scope(|ui| area.show(ui, |ui| ui.scope_builder(scope, add).inner));
|
||||
(rows.inner.inner, rows.response.rect.height(), rows.inner.content_size.y)
|
||||
}
|
||||
|
||||
/// After modal window `id` (with `margin` inside its frame) is drawn `height` tall: keep the height
|
||||
/// of all of it but its [`scrolled_rows`] for the next frame. If the rows were sized by a different
|
||||
/// one (the window just opened, or what is around them changed), the next frame is drawn at once,
|
||||
/// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll
|
||||
/// while the window would be taller than the screen has room for without them scrolling; a window
|
||||
/// without rows that scroll scrolls as a whole while its contents would be taller than the room,
|
||||
/// and any window scrolls sideways while its contents would be wider.
|
||||
fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) {
|
||||
let rows = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(ROWS_KEY)));
|
||||
let body = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(BODY_KEY)));
|
||||
let contents = ctx.data_mut(|m| m.remove_temp::<Vec2>(id.with(CONTENTS_KEY))).unwrap_or_default();
|
||||
let own = ctx.data_mut(|m| m.remove_temp::<bool>(id.with(OWN_ROWS_KEY))).unwrap_or(false);
|
||||
ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own));
|
||||
let room = whole_room(ctx, margin);
|
||||
let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP;
|
||||
let tall = match (rows, body) {
|
||||
(Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5,
|
||||
_ => false,
|
||||
};
|
||||
// A window that fits itself to the screen's height can still be too wide for it.
|
||||
let whole = [contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5];
|
||||
let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall));
|
||||
let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole));
|
||||
let mut repaint = tall != was_tall || whole != was_whole;
|
||||
if let Some(rows) = rows {
|
||||
let rest = (height - rows).max(0.0);
|
||||
let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest));
|
||||
repaint |= (used - rest).abs() > 0.5;
|
||||
}
|
||||
if repaint {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
@@ -146,4 +348,150 @@ mod tests {
|
||||
// Larger than the screen: its top left stays in view.
|
||||
assert_eq!(on_screen(r(-10.0, -10.0, 900.0, 700.0), screen), r(0.0, 0.0, 900.0, 700.0));
|
||||
}
|
||||
|
||||
/// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with the modal
|
||||
/// window named `open` open, if any: a heading and 60 rows, in [`scrolled_rows`] when
|
||||
/// `in_rows`. A window named "over …" is opened over the one before it ([`over_parent`]).
|
||||
/// Returns whether a first row could be seen in the last frame (inside the screen and its clip).
|
||||
fn first_row_seen(ctx: &egui::Context, open: Option<&str>, in_rows: bool, events: Vec<egui::Event>, time: &mut f64, frames: usize) -> bool {
|
||||
let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0));
|
||||
let add = |ui: &mut egui::Ui| {
|
||||
for i in 0..60 {
|
||||
ui.label(format!("Row {i}"));
|
||||
}
|
||||
};
|
||||
let mut events = Some(events);
|
||||
let mut seen = false;
|
||||
for _ in 0..frames {
|
||||
*time += 1.0 / 60.0;
|
||||
let input =
|
||||
egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(*time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
if let Some(name) = open {
|
||||
if name.starts_with("over ") {
|
||||
over_parent(ui.ctx());
|
||||
}
|
||||
show(ui.ctx(), name, Id::unique(("modal-reopen-test", name)), 0.0, 8, |ui| {
|
||||
heading(ui, "Top");
|
||||
if in_rows {
|
||||
scrolled_rows(ui, "rows", add);
|
||||
} else {
|
||||
add(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
seen = out.shapes.iter().any(|c| match &c.shape {
|
||||
egui::Shape::Text(t) => {
|
||||
let r = t.visual_bounding_rect();
|
||||
t.galley.text() == "Row 0" && screen.contains_rect(r) && c.clip_rect.contains_rect(r)
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// A wheel turn far down, at the middle of the 400×300 screen.
|
||||
fn wheel_down() -> Vec<egui::Event> {
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: egui::vec2(0.0, -3000.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
};
|
||||
vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0)), wheel]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_scrolled_opens_again_at_its_top() {
|
||||
for in_rows in [false, true] {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let mut time = 0.0;
|
||||
assert!(first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top");
|
||||
assert!(!first_row_seen(&ctx, Some("A"), in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away");
|
||||
first_row_seen(&ctx, None, in_rows, vec![], &mut time, 2);
|
||||
assert!(first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() {
|
||||
// As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it
|
||||
// did not close. A window that another replaced did close.
|
||||
let mut wrong = vec![];
|
||||
for in_rows in [false, true] {
|
||||
for (other, kept) in [("over B", true), ("C", false)] {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let mut time = 0.0;
|
||||
first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4);
|
||||
if first_row_seen(&ctx, Some("A"), in_rows, wheel_down(), &mut time, 60) {
|
||||
wrong.push(format!("rows {in_rows}: the wheel does not scroll A"));
|
||||
}
|
||||
if !first_row_seen(&ctx, Some(other), in_rows, vec![], &mut time, 4) {
|
||||
wrong.push(format!("rows {in_rows}: {other} does not open at its top"));
|
||||
}
|
||||
if first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4) == kept {
|
||||
wrong.push(format!("rows {in_rows}: after {other}, A {} where it was scrolled to", if kept { "is not" } else { "is still" }));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_keeps_its_text_and_focus_when_the_window_starts_or_stops_scrolling() {
|
||||
// A field's edit state and the keyboard focus are kept under its id, so typing goes on into
|
||||
// the same field when the screen's height changes whether the body or the window scrolls.
|
||||
let mut wrong = vec![];
|
||||
for in_body in [false, true] {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let window = Id::unique("modal-field-id-test");
|
||||
let mut text = String::from("12");
|
||||
let mut time = 0.0;
|
||||
let mut field = None;
|
||||
let mut seen = vec![];
|
||||
for (height, typed) in [(900.0, "3"), (300.0, "4"), (900.0, "5")] {
|
||||
let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height));
|
||||
for i in 0..4 {
|
||||
time += 1.0 / 60.0;
|
||||
// Typed once the window has settled at this height.
|
||||
let events = if i == 3 { vec![egui::Event::Text(typed.into())] } else { vec![] };
|
||||
let input = egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
show(ui.ctx(), "Test", window, 0.0, 8, |ui| {
|
||||
heading(ui, "Top");
|
||||
let mut add = |ui: &mut egui::Ui| {
|
||||
let r = ui.text_edit_singleline(&mut text);
|
||||
for i in 0..30 {
|
||||
ui.label(format!("Row {i}"));
|
||||
}
|
||||
r.id
|
||||
};
|
||||
field = Some(if in_body { body_rows(ui, add) } else { add(ui) });
|
||||
});
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
if let Some(id) = field.filter(|_| ctx.memory(|m| m.focused()).is_none()) {
|
||||
ctx.memory_mut(|m| m.request_focus(id));
|
||||
}
|
||||
}
|
||||
let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) };
|
||||
let scrolls = ctx.data(|m| m.get_temp::<bool>(key).unwrap_or(false) || m.get_temp::<[bool; 2]>(key).is_some_and(|a| a[1]));
|
||||
seen.push((scrolls, text.clone(), ctx.memory(|m| m.focused()) == field && field.is_some()));
|
||||
}
|
||||
let want = [(false, "123", true), (true, "1234", true), (false, "12345", true)];
|
||||
let want: Vec<_> = want.iter().map(|&(s, t, f)| (s, t.to_string(), f)).collect();
|
||||
if seen != want {
|
||||
wrong.push((in_body, seen));
|
||||
}
|
||||
}
|
||||
// Only the short screen scrolls, and the field keeps its focus and takes each key.
|
||||
assert_eq!(wrong, vec![], "(body, [(scrolls, text, focused)]) that went wrong");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -982,6 +982,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id {
|
||||
/// (as drawn last frame). The section list stays put while the content scrolls. Returns whether
|
||||
/// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`).
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
super::modal::fits_itself(ui);
|
||||
let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height());
|
||||
let content = ui.ctx().data(|m| m.get_temp::<f32>(content_id(ui))).unwrap_or(0.0);
|
||||
let rest = (window - content).max(0.0);
|
||||
|
||||
@@ -251,7 +251,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(500.0);
|
||||
ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong));
|
||||
egui::ScrollArea::vertical().id_salt(("print", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
let list_h = super::modal::list_height(ui, 360.0);
|
||||
egui::ScrollArea::vertical().id_salt(("print", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
"Marks and Bleed" => super::save_pdf::marks_and_bleeds(app, ui, d),
|
||||
"Output" => output(ui, d, &preview),
|
||||
"Graphics" => graphics(ui, d),
|
||||
|
||||
@@ -52,6 +52,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
|
||||
/// The preview area (panes and their captions) and the settings column.
|
||||
const PREVIEW_W: f32 = 620.0;
|
||||
/// The narrowest the panes get in a narrow window.
|
||||
const MIN_PREVIEW_W: f32 = 240.0;
|
||||
const PREVIEW_H: f32 = 470.0;
|
||||
const SIDE_W: f32 = 296.0;
|
||||
const GAP: f32 = 16.0;
|
||||
@@ -532,10 +534,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
}
|
||||
let settings = settings_of(app, d);
|
||||
let mut browser = false;
|
||||
ui.horizontal_top(|ui| {
|
||||
// In a window too narrow for both, the panes are narrower, so the settings beside them and the
|
||||
// buttons below stay in view. The room is the screen's (the window's own width follows what it
|
||||
// drew last), less a column for the bar of the body while it scrolls; the settings column is as
|
||||
// wide as it was drawn last.
|
||||
let bar = if super::modal::body_view(ui).is_some() { ui.spacing().scroll.allocated_width() } else { 0.0 };
|
||||
let room = ui.ctx().content_rect().width() - 2.0 * (f32::from(super::MARGIN) + super::EDGE_GAP) - bar;
|
||||
let rest_id = egui::Id::unique("save-for-web-beside-panes");
|
||||
let rest = ui.ctx().data(|m| m.get_temp::<f32>(rest_id)).unwrap_or(ui.spacing().item_spacing.x + GAP + SIDE_W);
|
||||
let preview_w = (room.min(ui.available_width()) - rest).clamp(MIN_PREVIEW_W, PREVIEW_W);
|
||||
let row = ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(PREVIEW_W);
|
||||
browser = preview_area(app, ui, d, &settings);
|
||||
ui.set_width(preview_w);
|
||||
browser = preview_area(app, ui, d, &settings, preview_w);
|
||||
});
|
||||
ui.add_space(GAP);
|
||||
ui.vertical(|ui| {
|
||||
@@ -543,6 +554,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
side(app, ui, d, settings.as_ref().ok());
|
||||
});
|
||||
});
|
||||
let drawn = row.response.rect.width() - preview_w;
|
||||
if (ui.ctx().data_mut(|m| std::mem::replace(m.get_temp_mut_or(rest_id, rest), drawn)) - drawn).abs() > 0.5 {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
optimize_on_enter(ui.ctx(), d);
|
||||
if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) {
|
||||
app.status(e);
|
||||
@@ -550,16 +565,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The view tabs, the panes and the zoom and speed row. Returns whether Preview in Browser was
|
||||
/// clicked.
|
||||
fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result<WebSettings, String>) -> bool {
|
||||
/// The view tabs, the panes (`width` wide) and the zoom and speed row. Returns whether Preview in
|
||||
/// Browser was clicked.
|
||||
fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result<WebSettings, String>, width: f32) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let view = VIEWS.iter().position(|v| *v == d.str("__view")).unwrap_or(2);
|
||||
if let Some(i) = widgets::tab_bar(ui, &VIEW_LABELS, view) {
|
||||
d.fields.insert("__view".into(), json!(VIEWS[i]));
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let (area, resp) = ui.allocate_exact_size(egui::vec2(PREVIEW_W, PREVIEW_H), egui::Sense::click_and_drag());
|
||||
let (area, resp) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_H), egui::Sense::click_and_drag());
|
||||
let pan_id = egui::Id::unique("save-for-web-pan");
|
||||
let mut pan: egui::Vec2 = ui.ctx().data(|m| m.get_temp(pan_id)).unwrap_or_default();
|
||||
if resp.dragged() {
|
||||
@@ -729,7 +744,8 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<&
|
||||
presets_row(app, ui, d, s);
|
||||
optimize_rows(ui, d, s, &art_key(app));
|
||||
widgets::divider(ui);
|
||||
egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(PREVIEW_H - 40.0).auto_shrink([false, true]).show(ui, |ui| {
|
||||
let list_h = super::modal::list_height(ui, PREVIEW_H - 40.0);
|
||||
egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| {
|
||||
let choice = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, options: &[(&str, &str)]| {
|
||||
form::choice(ui, d, key, label, (LABEL_W, FIELD_W), options);
|
||||
};
|
||||
|
||||
@@ -408,7 +408,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(500.0);
|
||||
ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong));
|
||||
egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
let list_h = super::modal::list_height(ui, 360.0);
|
||||
egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
"Compression" => compression(ui, d),
|
||||
"Marks and Bleeds" => marks_and_bleeds(app, ui, d),
|
||||
"Output" => output(ui, d),
|
||||
|
||||
@@ -670,6 +670,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open);
|
||||
let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0);
|
||||
crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| {
|
||||
crate::dialogs::modal::fits_itself(ui);
|
||||
ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0);
|
||||
crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set"));
|
||||
ui.add_space(10.0);
|
||||
|
||||
@@ -428,13 +428,17 @@ fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId
|
||||
egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None })
|
||||
}
|
||||
|
||||
/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out.
|
||||
/// Type `typed` into Scale W, which shows `shown` (the leftmost field that does, before H), and Tab out.
|
||||
fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) {
|
||||
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
|
||||
screen.run(app, vec![]);
|
||||
let out = screen.run(app, vec![]);
|
||||
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
|
||||
let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown)));
|
||||
// W is left of H on their row (the tree lists its nodes in no particular order).
|
||||
let w = nodes
|
||||
.iter()
|
||||
.filter(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown)))
|
||||
.min_by(|(_, a), (_, b)| a.bounds().map_or(f64::MAX, |r| r.x0).total_cmp(&b.bounds().map_or(f64::MAX, |r| r.x0)));
|
||||
screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]);
|
||||
screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]);
|
||||
screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]);
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
//! Dialogs in a short or narrow window: a dialog too large for the window scrolls instead of
|
||||
//! running off the screen. Every scroll bar here is drawn at rest (a solid bar style), so the tests
|
||||
//! can find it.
|
||||
use egui::{Pos2, Rect, Shape, vec2};
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::*;
|
||||
|
||||
type Open = fn(&mut VectorcraftApp);
|
||||
|
||||
/// What a dialog drew: the shapes, the dialog window's rectangle, and how it scrolls
|
||||
/// ([`modal::scrolling`]).
|
||||
struct Shown {
|
||||
shapes: Vec<egui::epaint::ClippedShape>,
|
||||
window: Rect,
|
||||
body: Option<f32>,
|
||||
whole: [bool; 2],
|
||||
}
|
||||
|
||||
/// Open a dialog with `open` in a `size` window, with the pointer in the window's corner (away
|
||||
/// from the dialog), and draw it until it settles. With `scroll`, then scroll far down and right
|
||||
/// near the dialog's right edge (on the bar of a window that scrolls as a whole, beside the lists
|
||||
/// inside it) and draw it until it settles again.
|
||||
fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
ctx.global_style_mut(|s| s.spacing.scroll = egui::style::ScrollStyle::solid());
|
||||
open(&mut app);
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, size);
|
||||
let window = |ctx: &egui::Context| {
|
||||
ctx.memory(|m| {
|
||||
m.areas()
|
||||
.visible_layer_ids()
|
||||
.into_iter()
|
||||
.filter(|l| l.order == egui::Order::Foreground)
|
||||
.filter_map(|l| Some((l.id, m.area_rect(l.id)?)))
|
||||
.max_by(|a, b| a.1.area().total_cmp(&b.1.area()))
|
||||
})
|
||||
.unwrap_or((egui::Id::NULL, Rect::NOTHING))
|
||||
};
|
||||
let mut time = 0.0;
|
||||
let mut frames = |app: &mut VectorcraftApp, first: Vec<egui::Event>| {
|
||||
let mut first = Some(first);
|
||||
let mut shapes = vec![];
|
||||
for _ in 0..12 {
|
||||
time += 1.0;
|
||||
let input =
|
||||
egui::RawInput { screen_rect: Some(screen), events: first.take().unwrap_or_default(), time: Some(time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
shapes = std::mem::take(&mut out.shapes);
|
||||
}
|
||||
shapes
|
||||
};
|
||||
let mut shapes = frames(&mut app, vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))]);
|
||||
if scroll {
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(-5000.0, -5000.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
};
|
||||
let (_, w) = window(&ctx);
|
||||
let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body: None, whole: [false; 2] };
|
||||
let at = whole_bar(&before).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center());
|
||||
shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel]);
|
||||
}
|
||||
let (id, window) = window(&ctx);
|
||||
let (body, whole) = modal::scrolling(&ctx, id);
|
||||
Shown { shapes, window, body, whole }
|
||||
}
|
||||
|
||||
/// Filled bars 4 to 10 pt across and longer than 12 pt (scroll bars and their handles), upright or
|
||||
/// (`sideways`) flat, inside the dialog window; with `seen`, only those inside their clip.
|
||||
fn bars(shown: &Shown, sideways: bool, seen: bool) -> Vec<Rect> {
|
||||
fn walk(s: &Shape, clip: Rect, sideways: bool, seen: bool, out: &mut Vec<Rect>) {
|
||||
match s {
|
||||
Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT => {
|
||||
let (across, along) = if sideways { (r.rect.height(), r.rect.width()) } else { (r.rect.width(), r.rect.height()) };
|
||||
if (4.0..=10.0).contains(&across) && along > 12.0 && (!seen || clip.contains_rect(r.rect)) {
|
||||
out.push(r.rect);
|
||||
}
|
||||
}
|
||||
Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, sideways, seen, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, sideways, seen, &mut out));
|
||||
out.retain(|r| shown.window.expand(0.5).contains_rect(*r));
|
||||
out
|
||||
}
|
||||
|
||||
/// The bar of a shared dialog's scrolling body: the rightmost upright bar as tall as the body is
|
||||
/// drawn (a list inside the body draws its bar further left).
|
||||
fn body_bar(shown: &Shown) -> Option<Rect> {
|
||||
let view = shown.body?;
|
||||
bars(shown, false, true).into_iter().filter(|r| (r.height() - view).abs() <= 1.0).max_by(|a, b| a.right().total_cmp(&b.right()))
|
||||
}
|
||||
|
||||
/// The bar of a window that scrolls as a whole: an upright bar at the window's right edge that
|
||||
/// runs most of the window's height (lists inside it are shorter).
|
||||
fn whole_bar(shown: &Shown) -> Option<Rect> {
|
||||
let w = shown.window;
|
||||
bars(shown, false, true)
|
||||
.into_iter()
|
||||
.filter(|r| r.right() >= w.right() - 24.0 && r.height() >= 0.8 * w.height())
|
||||
.max_by(|a, b| a.height().total_cmp(&b.height()))
|
||||
}
|
||||
|
||||
/// The texts `labels` the dialog drew, each with whether it can be seen (inside the screen and
|
||||
/// its clip).
|
||||
fn buttons(shown: &Shown, screen: Rect, labels: &[&str]) -> Vec<(String, bool)> {
|
||||
fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) {
|
||||
match s {
|
||||
Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)),
|
||||
Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut texts = vec![];
|
||||
shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts));
|
||||
texts
|
||||
.into_iter()
|
||||
.filter(|(s, ..)| labels.contains(&s.as_str()))
|
||||
.map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_taller_than_the_window_scrolls_its_body_and_keeps_its_buttons_in_view() {
|
||||
let opens: [(&str, Open, &[&str]); 7] = [
|
||||
("SVG Options", |app| svg_options::open(app, svg_options::Mode::Export, Some("/tmp/x.svg")), &["OK", "Cancel"]),
|
||||
("EPS Options", |app| eps_options::open(app, &json!({"format": "eps", "path": "/tmp/x.eps"})), &["Export", "Cancel"]),
|
||||
("DXF Options", |app| dxf_options::open(app, &json!({"format": "dxf", "path": "/tmp/x.dxf"})), &["Export", "Cancel"]),
|
||||
(
|
||||
"Save PDF",
|
||||
|app| {
|
||||
save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap();
|
||||
},
|
||||
&["Cancel"],
|
||||
),
|
||||
(
|
||||
"Save for Web",
|
||||
|app| {
|
||||
save_for_web::open(app).unwrap();
|
||||
},
|
||||
&["Cancel", "Done"],
|
||||
),
|
||||
("Export for Screens", export_for_screens::open, &["Cancel"]),
|
||||
(
|
||||
"Print",
|
||||
|app| {
|
||||
print::open(app).unwrap();
|
||||
},
|
||||
&["Cancel", "Done"],
|
||||
),
|
||||
];
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 480.0));
|
||||
for (name, open, labels) in opens {
|
||||
let tall = show_in(open, vec2(1280.0, 900.0), false);
|
||||
assert!(tall.window.height() > screen.height(), "{name}: the dialog is taller than the short window ({:?})", tall.window);
|
||||
assert_eq!((tall.body, tall.whole), (None, [false; 2]), "{name}: in a tall window nothing scrolls");
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window);
|
||||
let found = buttons(&shown, screen, labels);
|
||||
assert_eq!(found.len(), labels.len(), "{name}: {found:?}");
|
||||
assert!(found.iter().all(|(_, seen)| *seen), "{name}: the buttons stay in view: {found:?}");
|
||||
assert_eq!(shown.whole, [false; 2], "{name}: the window does not scroll as a whole");
|
||||
let bar = body_bar(&shown);
|
||||
assert!(bar.is_some(), "{name}: the body scrolls ({:?}) and its bar is drawn: {:?}", shown.body, bars(&shown, false, true));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_list_in_a_scrolling_body_is_no_taller_than_the_body() {
|
||||
// The settings of Save for Web and the sections of Print and Save PDF scroll in lists of their
|
||||
// own; in a short window those lists are no taller than the body shows, so each list and its
|
||||
// bar can be scrolled into view whole.
|
||||
let opens: [(&str, Open); 3] = [
|
||||
("Save for Web", |app| {
|
||||
save_for_web::open(app).unwrap();
|
||||
}),
|
||||
("Print", |app| {
|
||||
print::open(app).unwrap();
|
||||
if let Some(d) = app.ui.dialog.as_mut() {
|
||||
d.fields.insert("__section".into(), json!("Marks and Bleed"));
|
||||
}
|
||||
}),
|
||||
("Save PDF", |app| {
|
||||
save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap();
|
||||
if let Some(d) = app.ui.dialog.as_mut() {
|
||||
d.fields.insert("__section".into(), json!("Marks and Bleeds"));
|
||||
}
|
||||
}),
|
||||
];
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 400.0));
|
||||
let mut wrong = vec![];
|
||||
for (name, open) in opens {
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
let Some(body) = body_bar(&shown) else {
|
||||
wrong.push(format!("{name}: the body does not scroll ({:?}): {:?}", shown.body, bars(&shown, false, false)));
|
||||
continue;
|
||||
};
|
||||
// The tracks of the lists' bars, seen or not: left of the body's bar and inside the window
|
||||
// (a list taller than the body runs past the window's bottom).
|
||||
let lists: Vec<Rect> = bars(&shown, false, false).into_iter().filter(|r| r.right() < body.left()).collect();
|
||||
let tallest = lists.iter().map(|r| r.height()).fold(0.0, f32::max);
|
||||
if tallest == 0.0 || tallest > body.height() + 0.5 {
|
||||
wrong.push(format!("{name}: no list bar no taller than the body ({}): {:?}", body.height(), bars(&shown, false, false)));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_for_web_in_the_smallest_window_keeps_its_settings_and_buttons_in_view() {
|
||||
let open: Open = |app| {
|
||||
save_for_web::open(app).unwrap();
|
||||
};
|
||||
// The app window's smallest size, 800 by 500 pixels, at a UI scale of 100%, 110% and 125%.
|
||||
let mut wrong = vec![];
|
||||
for size in [vec2(800.0, 500.0), vec2(727.0, 454.0), vec2(640.0, 400.0)] {
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, size);
|
||||
let shown = show_in(open, size, false);
|
||||
let labels = ["Format:", "Optimize to File Size…", "Cancel", "Done"];
|
||||
let found = buttons(&shown, screen, &labels);
|
||||
if !screen.contains_rect(shown.window) || found.len() != labels.len() || !found.iter().all(|(_, seen)| *seen) {
|
||||
wrong.push(format!("{size:?}: the dialog ({:?}) leaves its settings and buttons in view: {found:?}", shown.window));
|
||||
}
|
||||
if body_bar(&shown).is_none() || shown.whole != [false; 2] {
|
||||
wrong.push(format!("{size:?}: only the body scrolls ({:?}, {:?})", shown.body, shown.whole));
|
||||
}
|
||||
// The controls under the narrower panes stay in their column, left of the settings.
|
||||
let controls = text_rects(&shown, "Preview in Browser").first().map(|r| r.right());
|
||||
let settings = text_rects(&shown, "Format:").first().map(|r| r.left());
|
||||
if !matches!((controls, settings), (Some(c), Some(s)) if c < s) {
|
||||
wrong.push(format!("{size:?}: Preview in Browser ({controls:?}) is left of the settings ({settings:?})"));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// The rectangles of the texts `label` the dialog drew.
|
||||
fn text_rects(shown: &Shown, label: &str) -> Vec<Rect> {
|
||||
fn walk(s: &Shape, label: &str, out: &mut Vec<Rect>) {
|
||||
match s {
|
||||
Shape::Text(t) if t.galley.text() == label => out.push(t.visual_bounding_rect()),
|
||||
Shape::Vec(v) => v.iter().for_each(|s| walk(s, label, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
shown.shapes.iter().for_each(|c| walk(&c.shape, label, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_too_large_for_the_screen_scrolls_as_a_whole() {
|
||||
let opens: [(&str, Open, &[&str]); 4] = [
|
||||
("Preferences", |app| crate::prefs_dialog::open(app, None), &["OK", "Cancel"]),
|
||||
("Keyboard Shortcuts", crate::shortcut_editor::open, &["OK", "Cancel"]),
|
||||
("New Document", new_document::open, &["Create", "Close"]),
|
||||
("Find Font", crate::find_font::open, &["Done"]),
|
||||
];
|
||||
// The app window's smallest size.
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
|
||||
for (name, open, labels) in opens {
|
||||
let tall = show_in(open, vec2(1280.0, 900.0), false);
|
||||
assert!(
|
||||
tall.window.height() > screen.height() || tall.window.width() > screen.width(),
|
||||
"{name}: the dialog is larger than the small window ({:?})",
|
||||
tall.window
|
||||
);
|
||||
assert_eq!(tall.whole, [false; 2], "{name}: in a large window the dialog does not scroll as a whole");
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window);
|
||||
assert!(shown.whole[1], "{name}: the dialog scrolls as a whole");
|
||||
assert!(whole_bar(&shown).is_some(), "{name}: the window's bar is drawn: {:?}", bars(&shown, false, true));
|
||||
// The buttons can sit outside the part in view; each is in view at the top or scrolled to
|
||||
// the end.
|
||||
let scrolled = show_in(open, screen.size(), true);
|
||||
let (top, end) = (buttons(&shown, screen, labels), buttons(&scrolled, screen, labels));
|
||||
for label in labels {
|
||||
let seen = |found: &[(String, bool)]| found.iter().any(|(s, seen)| s == label && *seen);
|
||||
assert!(seen(&top) || seen(&end), "{name}: {label} can be scrolled into view: {top:?} {end:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_shortcuts_keeps_its_scroll_under_import_shortcut_set() {
|
||||
// Scrolled down in the smallest window, Keyboard Shortcuts is where it was left when Import
|
||||
// Shortcut Set, opened over it, is canceled; closed and opened again, it starts at its top.
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
|
||||
let mut time = 0.0;
|
||||
// Draws 12 frames, the first with `events`; returns whether the heading can be seen.
|
||||
let mut heading_seen = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let mut events = Some(events);
|
||||
let mut seen = false;
|
||||
for _ in 0..12 {
|
||||
time += 1.0;
|
||||
let input =
|
||||
egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
let shown = Shown { shapes: out.shapes, window: screen, body: None, whole: [false; 2] };
|
||||
seen = buttons(&shown, screen, &["Keyboard Shortcuts"]).iter().any(|(_, seen)| *seen);
|
||||
}
|
||||
seen
|
||||
};
|
||||
let wheel = |at: Pos2| {
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -5000.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
};
|
||||
vec![egui::Event::PointerMoved(at), wheel]
|
||||
};
|
||||
crate::shortcut_editor::open(&mut app);
|
||||
assert!(heading_seen(&mut app, vec![]), "Keyboard Shortcuts opens at its top");
|
||||
// On the window's bar, inside its 20 pt margin.
|
||||
let window = ctx.memory(|m| m.area_rect(egui::Id::unique("dialog-shortcuts"))).unwrap_or(screen);
|
||||
assert!(!heading_seen(&mut app, wheel(egui::pos2(window.right() - 23.0, window.center().y))), "the wheel scrolls the heading away");
|
||||
let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n}\n";
|
||||
crate::io::open_bytes(&mut app, "Keys.kys", kys.as_bytes(), None).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(shortcut_import::KIND));
|
||||
heading_seen(&mut app, vec![]);
|
||||
cancel(&mut app);
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "Cancel shows Keyboard Shortcuts again");
|
||||
assert!(!heading_seen(&mut app, vec![]), "shown again, Keyboard Shortcuts is where it was scrolled to");
|
||||
cancel(&mut app);
|
||||
heading_seen(&mut app, vec![]);
|
||||
crate::shortcut_editor::open(&mut app);
|
||||
assert!(heading_seen(&mut app, vec![]), "opened again, Keyboard Shortcuts starts at its top");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_fits_itself_but_is_too_wide_scrolls_sideways() {
|
||||
// Import Shortcut Set sizes its lists from the window's height and is about 780 pt wide. An
|
||||
// 800 by 600 pixel window at a UI scale of 125% is 640 by 480 pt.
|
||||
let open: Open = |app| {
|
||||
let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n";
|
||||
crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap();
|
||||
};
|
||||
let wide = show_in(open, vec2(1280.0, 900.0), false);
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 480.0));
|
||||
assert!(wide.window.width() > screen.width(), "Import Shortcut Set is wider than the window: {:?}", wide.window);
|
||||
assert_eq!(wide.whole, [false; 2], "in a large window it does not scroll");
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window);
|
||||
assert_eq!(shown.whole, [true, false], "it scrolls sideways only");
|
||||
let sideways: Vec<Rect> = bars(&shown, true, true).into_iter().filter(|r| r.width() >= 0.5 * shown.window.width()).collect();
|
||||
assert!(!sideways.is_empty(), "its sideways bar is drawn: {:?}", bars(&shown, true, false));
|
||||
}
|
||||
Reference in New Issue
Block a user