Merge branch 'area/app1' into area/app2

# Conflicts:
#	crates/ui-egui/src/panels/transform.rs
This commit is contained in:
bflatastic
2026-11-23 16:28:23 +07:00
22 changed files with 382 additions and 145 deletions
+1 -1
View File
@@ -52,7 +52,7 @@ pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
pub(crate) use rulers::{general_lengths, stroke_lengths};
pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, has_colors, is_task_bar_action, read_hidden_task_bar_actions};
pub use tool_adapter::{apply_requests, dispatch, mods};
pub(crate) use tool_adapter::{busy_tool, in_gesture, pose_on_page};
pub(crate) use tool_adapter::{busy_tool, in_gesture, pose_on_page, tool_enter};
/// Which body a document's canvas runs: the current window's interactive one, or a display-only
/// pane of a tiled or floating window.
+11 -6
View File
@@ -378,12 +378,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
super::drops::show(app, &mut catcher, w, BodyKind::Pane);
}
drop_released(app);
// Note the fits this frame made, for `refit_resized`.
for ((w, area), was_unfitted) in areas.iter().zip(unfitted) {
if let (true, Some(v), Some(s)) = (was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) {
app.canvas.panes.fits.insert(s, (area.size(), v.zoom, v.center));
}
}
note_fits(app, &areas, &unfitted);
});
let activated = split.output.activated;
app.canvas.panes.at = lines;
@@ -434,6 +429,16 @@ pub(crate) fn refit_resized(app: &mut VectorcraftApp, areas: &[(Win, egui::Rect)
.collect()
}
/// Note the fits this frame made, for [`refit_resized`]: each of `areas`' views that was unfitted
/// (`unfitted`, as `refit_resized` returned) and is fitted now, with its area's size.
pub(crate) fn note_fits(app: &mut VectorcraftApp, areas: &[(Win, egui::Rect)], unfitted: &[bool]) {
for ((w, area), was_unfitted) in areas.iter().zip(unfitted) {
if let (true, Some(v), Some(s)) = (*was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) {
app.canvas.panes.fits.insert(s, (area.size(), v.zoom, v.center));
}
}
}
/// Fit `v` to show its artboard (the first if it has gone) in `area`, with the interface zoomed by
/// `ui_zoom` on a screen of `pixels_per_point`, as Fit Artboard in Window does.
fn fit_pane(v: &mut View, doc: &vectorcraft_doc::Document, area: egui::Rect, (ui_zoom, pixels_per_point): (f32, f32), scheme: &ZoomScheme) {
+33 -26
View File
@@ -109,6 +109,30 @@ fn sync_artboard(app: &mut VectorcraftApp) {
}
}
/// Enter that the tool does not claim, while no gesture runs: it takes what the tool asks of the UI (Rotate, Scale,
/// Reflect and Shear open their dialog), and with a selection tool it opens the Move dialog, as a double-click on the
/// tool's button does. Taken only when a dialog opened, so that Enter is not also its OK.
pub(crate) fn tool_enter(app: &mut VectorcraftApp, mods: Mods, view: ViewInfo) -> bool {
if app.session.tool_busy() {
return false;
}
let open = |app: &VectorcraftApp| app.dialogs().map_or(0, |d| d.with(|h| h.open_dialogs().len()));
let before = open(app);
let r = app.session.tool_key(EngineKey::Enter, mods, view);
apply_requests(app, r);
let tool = app.session.tool_id().to_owned();
if open(app) == before && vectorcraft_tools::catalog::is_selection_tool(&tool) {
// Nothing selected: it fails and nothing opens (the menu item is disabled then too).
let _ = crate::toolbar::open_options(app, &tool);
}
let opened = open(app) > before;
// The dialog uses the tool a held key chose.
if opened {
crate::shortcuts::note_tool_use(app);
}
opened
}
/// The session as a tool for one pass. The host's trait takes `&self` for the cursor and the claims, which the
/// session answers through `&mut`, so the app sits in a cell.
struct SessionTool<'a> {
@@ -126,9 +150,10 @@ impl<'a> SessionTool<'a> {
Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id() }
}
/// Whether another window covers the canvas at `pointer`, so art moved there leaves the canvas.
/// Whether another window covers the canvas at `pointer`, so art moved there leaves the canvas: a floating
/// document's or a floating panel's OS window.
fn covered(&self, pointer: &ToolPointer) -> bool {
self.ctx.layer_id_at(pointer.pos).is_some_and(|l| l != self.layer)
self.ctx.layer_id_at(pointer.pos).is_some_and(|l| l != self.layer) || crate::panel_docking::os_window_at(&self.app(), &self.ctx, pointer.pos)
}
fn app(&self) -> RefMut<'_, &'a mut VectorcraftApp> {
@@ -153,29 +178,9 @@ impl<'a> SessionTool<'a> {
true
}
/// Enter that the tool does not claim, while no gesture runs: it takes what the tool asks of the UI (Rotate,
/// Scale, Reflect and Shear open their dialog), and with a selection tool it opens the Move dialog, as a
/// double-click on the tool's button does. Taken only when a dialog opened, so that Enter is not also its OK.
/// [`tool_enter`] in this canvas's view.
fn enter(&self, mods: Mods) -> bool {
let mut app = self.app();
if app.session.tool_busy() {
return false;
}
let open = |app: &VectorcraftApp| app.dialogs().map_or(0, |d| d.with(|h| h.open_dialogs().len()));
let before = open(&app);
let r = app.session.tool_key(EngineKey::Enter, mods, self.view);
apply_requests(&mut app, r);
let tool = app.session.tool_id().to_owned();
if open(&app) == before && vectorcraft_tools::catalog::is_selection_tool(&tool) {
// Nothing selected: it fails and nothing opens (the menu item is disabled then too).
let _ = crate::toolbar::open_options(&mut app, &tool);
}
let opened = open(&app) > before;
// The dialog uses the tool a held key chose.
if opened {
crate::shortcuts::note_tool_use(&mut app);
}
opened
tool_enter(&mut self.app(), mods, self.view)
}
/// A key the tool does not claim while its gesture runs: arrows and digits still reach it, with no modifier (a
@@ -286,7 +291,8 @@ impl CanvasTool for SessionTool<'_> {
return;
}
// Art carried off the canvas waits where it last moved; back on the canvas the move goes on.
let carried = super::drops::carry_out(&mut self.app(), cx, pointer, self.covered(pointer));
let covered = self.covered(pointer);
let carried = super::drops::carry_out(&mut self.app(), cx, pointer, covered);
if !carried {
let ev = pointer_event(PointerKind::Drag, pointer, cx);
dispatch(&mut self.app(), &ev, self.view);
@@ -306,7 +312,8 @@ impl CanvasTool for SessionTool<'_> {
return;
}
drop(app);
let carried = super::drops::carried(&self.app(), cx, pointer, self.covered(pointer));
let covered = self.covered(pointer);
let carried = super::drops::carried(&self.app(), cx, pointer, covered);
self.app().canvas.panes.released_from = carried.as_ref().map(|art| (art.document, art.revision));
if cx.over_drop_target() || carried.is_some() {
// The art goes to the drop target, or nowhere off the canvas: the move is given up where it started.
+6 -3
View File
@@ -26,10 +26,13 @@ pub(crate) mod rank {
/// The parts of a group that its other members work without: the width profile, Recolor Artwork, Global Edit
/// Options, Document Setup, an image's Edit Original.
pub const DETAIL: u8 = 3;
/// The Opacity link and field: they leave before the groups, so the narrower Style link and picker after them
/// can show without them.
pub const OPACITY: u8 = 4;
/// Every other member of the bar.
pub const GROUP: u8 = 4;
pub const GROUP: u8 = 5;
/// A section's link that stays after its fields leave.
pub const LINK: u8 = 6;
pub const LINK: u8 = 7;
}
/// An anchor button: icon, tooltip, command and the convert command's `to`.
@@ -300,7 +303,7 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui) {
fn opacity_field(app: &mut VectorcraftApp, ui: &mut Ui, opacity: f32, selected: bool) {
let label = tl!("Opacity:");
let (mut link, mut typed) = (false, None);
group(ui, rank::GROUP, |ui| {
group(ui, rank::OPACITY, |ui| {
Field::new(label).side(SideLabel::new().link().scrub(true)).show(ui, |ui, _| {
let number =
NumberField::new(label, Bind::given(Some(f64::from(opacity) * 100.0))).range(0.0..=100.0).unit("%").scrub_by_label().show(ui);
+16 -10
View File
@@ -3,9 +3,10 @@ use craft::behavior::IconId;
use craft::behavior::kurbo::Size;
use craft::ui::bars::{Bar, BarKind, StatusMessage, StatusProgress};
use craft::ui::buttons::{Button, IconButton};
use craft::ui::contract::{Bind, Entry, LabelKind, Outcome as _, Props as _, Show as _, ShowContainer as _, SideLabel, Trigger};
use craft::ui::contract::{Bind, Entry, Gap, LabelKind, Outcome as _, Props as _, Show as _, ShowContainer as _, SideLabel, Trigger};
use craft::ui::display::{Divider, Elide, Shade, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::Row;
use craft::ui::menu::Menu;
use craft::ui::pickers::Select;
use craft::ui::style::TypeRole;
@@ -83,18 +84,23 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
Text::new(shown.to_owned()).shade(Shade::Muted).elide(Elide::End).show(ui);
let more = IconButton::new(IconId::new("chevron_down")).label(tl!("Show")).show(ui);
show_pick = Menu::new(tl!("Show")).values().opened_by(more.response(), Trigger::Press).pick(ui, &shows).picked;
// A narrow bar leaves out the timings first, then the pointer's position, before the message.
let readout = |text: String, sample: String| Text::new(text).shade(Shade::Faint).sample(sample);
readout(format!("{render} {:.1} ms", app.perf.render_ms), format!("{render} 8888.8 ms")).show(ui);
readout(format!("{ui_name} {:.1} ms", app.perf.frame_ms), format!("{ui_name} 8888.8 ms")).show(ui);
// No rate until the window has drawn continuously for a moment (`frame_rate`).
let fps = if app.perf.fps > 0.0 { format!("{:.0} fps", app.perf.fps) } else { "\u{2013} fps".into() };
readout(fps, "8888 fps".into()).show(ui);
Row::new().gap(Gap::Item).fit_rank(1).show(ui, |ui, _| {
readout(format!("{render} {:.1} ms", app.perf.render_ms), format!("{render} 8888.8 ms")).show(ui);
readout(format!("{ui_name} {:.1} ms", app.perf.frame_ms), format!("{ui_name} 8888.8 ms")).show(ui);
// No rate until the window has drawn continuously for a moment (`frame_rate`).
let fps = if app.perf.fps > 0.0 { format!("{:.0} fps", app.perf.fps) } else { "\u{2013} fps".into() };
readout(fps, "8888 fps".into()).show(ui);
});
// With no hover point the axes stay empty and keep their width.
let origin = app.ruler_origin();
for (axis, value) in [("X", app.hover_doc.map(|p| p.x - origin.x)), ("Y", app.hover_doc.map(|p| p.y - origin.y))] {
let text = value.map(|v| format!("{axis}: {}", unit.readout(v))).unwrap_or_default();
Text::new(text).role(TypeRole::Mono).shade(Shade::Muted).sample(format!("{axis}: -8888.88 {}", unit.suffix())).show(ui);
}
Row::new().gap(Gap::Item).fit_rank(2).show(ui, |ui, _| {
for (axis, value) in [("X", app.hover_doc.map(|p| p.x - origin.x)), ("Y", app.hover_doc.map(|p| p.y - origin.y))] {
let text = value.map(|v| format!("{axis}: {}", unit.readout(v))).unwrap_or_default();
Text::new(text).role(TypeRole::Mono).shade(Shade::Muted).sample(format!("{axis}: -8888.88 {}", unit.suffix())).show(ui);
}
});
if app.session.script_running() {
stop = Button::new(tl!("Stop")).show(ui).response().clicked();
}
+8 -2
View File
@@ -101,7 +101,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
}
let held = !carrying && ui.input(|i| i.pointer.primary_down());
for event in strip.show(ui).events {
if matches!(event, DocumentTabsEvent::Reordered { .. } | DocumentTabsEvent::TornOff { .. }) {
if matches!(event, DocumentTabsEvent::Reordered { .. } | DocumentTabsEvent::TornOff { .. } | DocumentTabsEvent::DroppedInto { .. }) {
ui.data_mut(|d| d.remove::<Win>(pressed));
}
match event {
@@ -134,7 +134,9 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
DocumentTabsEvent::DroppedInto { documents, .. } => {
for (index, view) in documents {
// A tab of this strip dropped back on it past the tabs is already docked.
let floating: Vec<Win> = documents.into_iter().filter(|w| doc_windows::floats(app, *w)).collect();
for (index, view) in floating {
run_reporting(app, "window.arrange.consolidateAllWindows", json!({"index": index, "view": view}));
}
}
@@ -142,6 +144,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
_ => {}
}
}
// A press that moved past a click's reach is a drag, whether or not it reordered the tabs.
if held && ui.input(|i| i.pointer.is_decidedly_dragging()) {
ui.data_mut(|d| d.remove::<Win>(pressed));
}
if !held && let Some(w) = ui.data_mut(|d| d.remove_temp::<Win>(pressed)) {
doc_windows::show_window(app, w);
}
+20 -14
View File
@@ -1141,10 +1141,12 @@ fn isolation_shown(app: crate::VectorcraftApp) -> Shown {
})
}
/// A point on the isolation bar's own surface, right of every control on it.
/// A point on the isolation bar's own surface: right of its crumbs, at the end of the path, which fills the bar up
/// to the pattern editing buttons at its right.
fn isolation_bar_surface(bar: &mut Shown) -> egui::Pos2 {
let back = bar.named("Back");
egui::pos2(1200.0 - 40.0, back.center().y)
let path = bar.named("Isolation path");
egui::pos2(path.rect.right() - 8.0, back.center().y)
}
/// #4468: In nested isolation, clicking the back button steps up one level in the hierarchy,
@@ -2235,7 +2237,7 @@ fn the_control_bar_keeps_its_label_and_menu_with_every_group_off() {
let mut bar = control_shown(app);
bar.room(egui::vec2(1400.0, 900.0)).settle();
assert!(bar.shows(&label), "the label stays: {:?}", bar.names());
for s in ["Snapping", "Stroke:", "Opacity:", "Style:", "Transform", "X:"] {
for s in ["Snapping", "Stroke:", "Opacity:", "Style:", "Transform", BAR_FIELDS[0]] {
assert!(!bar.shows(s), "{s} is off");
}
open_control_bar_menu(&mut bar);
@@ -2326,20 +2328,20 @@ fn the_artboard_tool_s_control_bar_follows_its_two_groups() {
let freed = (40..=240).map(|w| w as f32 * 10.0).any(|w| {
bar.room(egui::vec2(w, 300.0));
options(&mut bar, true);
let on = bar.settle().shows("X:");
let on = bar.settle().shows(BAR_FIELDS[0]);
options(&mut bar, false);
let off = bar.settle().shows("X:");
let off = bar.settle().shows(BAR_FIELDS[0]);
!on && off
});
assert!(freed, "with Artboard Options off the fields find room in a window too narrow for them otherwise");
options(&mut bar, false);
bar.room(egui::vec2(2400.0, 300.0)).settle();
assert!(!bar.shows("Name:") && !bar.shows("Move Artwork with Artboard"), "{:?}", bar.names());
assert!(bar.shows("Artboard") && bar.shows("Transform") && bar.shows("X:"), "{:?}", bar.names());
assert!(bar.shows("Artboard") && bar.shows("Transform") && bar.shows(BAR_FIELDS[0]), "{:?}", bar.names());
options(&mut bar, true);
bar.app().run("window.control.options", json!({"group": "transform", "visible": false})).unwrap();
bar.settle();
assert!(!bar.shows("Transform") && !bar.shows("X:"), "{:?}", bar.names());
assert!(!bar.shows("Transform") && !bar.shows(BAR_FIELDS[0]), "{:?}", bar.names());
assert!(bar.shows("Name:") && bar.shows("Move Artwork with Artboard"), "{:?}", bar.names());
}
@@ -2423,16 +2425,20 @@ fn the_control_bar_leaves_members_out_in_its_priority_order() {
groups(&mut bar, &ahead, true);
select(&mut bar, json!([rect]));
let seen = control_bar_widths(&mut bar, &["Horizontal Align Left", "X:", "Y:", "W:", "H:"]);
let [x, y, w, h] = BAR_FIELDS;
let seen = control_bar_widths(&mut bar, &["Horizontal Align Left", x, y, w, h]);
assert!(seen.iter().all(|s| s[2..].iter().all(|f| *f == s[1])), "the four fields show or go together");
assert!(seen.iter().any(|s| s[0] && s[1]), "a wide bar shows the fields and the Align buttons");
assert!(seen.iter().any(|s| s[0] && !s[1]), "some width shows the Align buttons without the fields");
}
/// The caption `name` of a field on the bar: the label, not the field it names.
fn caption(bar: &Shown, name: &str) -> Option<Target> {
/// The names of the bar's X, Y, W and H fields, in their order.
const BAR_FIELDS: [&str; 4] = ["X position", "Y position", "Width", "Height"];
/// The caption of the bar's field named `field`: the link that names it, not the field.
fn caption(bar: &Shown, field: &str) -> Option<Target> {
let tree = bar.tree();
bar.fixture.by_role(Role::LABEL).into_iter().find(|t| tree.name_of(t.node) == Some(name) || tree.value_of(t.node) == Some(name))
bar.fixture.by_role(Role::LINK).into_iter().find(|t| tree.name_of(t.node) == Some(field))
}
/// The Control bar's labels that open a panel: a click on the Linked File or Embedded label shows the Links panel
@@ -2490,7 +2496,7 @@ fn label_links_open_their_panels() {
// The Transform panel's Rotate field is not on the bar itself.
let open = |bar: &Shown| bar.find("Rotate").is_some();
let before = state(&bar);
for name in ["X:", "Y:", "W:", "H:"] {
for name in BAR_FIELDS {
bar.settle();
assert!(!open(&bar), "{name}: the Transform panel is closed at first");
let at = caption(&bar, name).unwrap_or_else(|| panic!("no {name} caption: {:?}", bar.names()));
@@ -2704,8 +2710,8 @@ fn the_control_bar_shows_the_global_edit_options() {
assert_eq!(ge, Some(2), "Start Global Edit takes the two rectangles of the same size");
let button = bar.named("Global Edit Options");
assert!(bar.tree().is_disabled_key(button.node), "the options are off while Global Edit is on");
assert!(!results(&bar), "Global Edit starting closes the open options");
assert!(!results(bar.settle()));
// The closed popover's body still runs through its exit fade, so the options are looked for once it ends.
assert!(!results(bar.advance(1.0).settle()), "Global Edit starting closes the open options");
bar.app().run("select.globalEdit", json!({})).unwrap();
assert!(!results(bar.settle()), "the options stay closed once Global Edit stops");
}
+15 -4
View File
@@ -348,6 +348,8 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
for w in wins {
if let Some(v) = view_mut(app, w) {
v.fitted = false;
// The area it last showed its art in is the main window's: it fits its window's.
v.rect = egui::Rect::NOTHING;
}
}
}
@@ -381,21 +383,24 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
let window = DocumentWindow::new(title).id_salt((w.uid, w.number, w.generation)).first_placed(w.place.translate(origin));
let window = if raise == Some((w.uid, w.view)) { window.raise() } else { window };
let out = window.show(ui, |ui, _| {
// A press anywhere on the window, its title bar and tab included, makes its document current.
pressed = pressed_on_layer(ui);
crate::chrome::window_tab(app, ui, win);
let rect = ui.available_rect_before_wrap();
crate::canvas::panes::refit_resized(app, &[(win, rect)]);
let areas = [(win, ui.available_rect_before_wrap())];
let unfitted = crate::canvas::panes::refit_resized(app, &areas);
if live {
show_document(app, ui, win, BodyKind::Live);
} else {
pressed = crate::canvas::pane(app, ui, win, rect);
pressed |= crate::canvas::pane(app, ui, win, areas[0].1);
}
crate::canvas::panes::note_fits(app, &areas, &unfitted);
});
if let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid && x.view == w.view) {
x.focused = out.focused;
}
if out.close_requested.is_some() {
close = Some(win);
} else if (out.focus_gained || pressed) && !is_current {
} else if (out.focus_gained || pressed) && !is_current && !app.any_dialog_open() {
activate = Some(win);
}
}
@@ -413,5 +418,11 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
}
}
/// Whether the primary button went down over `ui`'s layer in this pass.
fn pressed_on_layer(ui: &egui::Ui) -> bool {
let at = ui.ctx().input(|i| i.pointer.primary_pressed().then_some(i.pointer.interact_pos()).flatten());
at.is_some_and(|at| ui.ctx().layer_id_at(at) == Some(ui.layer_id()))
}
#[cfg(test)]
mod tests;
+54 -24
View File
@@ -23,19 +23,54 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>
s => out.push(s),
}
}
let out = run_frame(app, ctx, events);
let mut shapes = vec![];
out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes));
shapes
}
/// One headless frame of the canvas panel's body and the floating document windows on a 1200 ×
/// 800 window. The windows' access nodes, by name, are kept for [`window_of`].
fn run_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> egui::FullOutput {
let raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))),
max_texture_side: Some(8192),
events,
..Default::default()
};
ctx.enable_accesskit();
let out = crate::testing::part_frame(app, ctx, raw, |app, ui| {
app.canvas_area(ui);
show(app, ui);
});
let mut shapes = vec![];
out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes));
shapes
let nodes = out.platform_output.accesskit_update.as_ref().map_or(&[][..], |u| &u.nodes[..]);
let named: Vec<Named> = nodes
.iter()
.filter(|(_, n)| matches!(n.role(), egui::accesskit::Role::Group | egui::accesskit::Role::TabList))
.filter_map(|(_, n)| {
let b = n.bounds()?;
Some((n.role(), n.label()?.to_owned(), egui::Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))))
})
.collect();
ctx.data_mut(|d| d.insert_temp(egui::Id::new(NAMED), std::sync::Arc::new(named)));
out
}
/// A group or tab list of the last frame's accessibility tree: its role, name and bounds.
type Named = (egui::accesskit::Role, String, egui::Rect);
/// Where [`run_frame`] keeps the last frame's [`Named`] nodes.
const NAMED: &str = "doc-window-tests-named";
/// The last frame's [`Named`] nodes of `role` whose name `matches`.
fn named(ctx: &egui::Context, role: egui::accesskit::Role, matches: impl Fn(&str) -> bool) -> Option<egui::Rect> {
let nodes: std::sync::Arc<Vec<Named>> = ctx.data(|d| d.get_temp(egui::Id::new(NAMED))).unwrap_or_default();
nodes.iter().find(|(r, name, _)| *r == role && matches(name)).map(|(_, _, rect)| *rect)
}
/// The main window's document tab strip, as the last frame drew it.
fn strip(ctx: &egui::Context) -> egui::Rect {
named(ctx, egui::accesskit::Role::TabList, |name| name == "Documents").expect("the tab strip was drawn")
}
fn button(pos: Pos2, pressed: bool) -> egui::Event {
@@ -61,11 +96,15 @@ fn canvas_rect(app: &VectorcraftApp) -> egui::Rect {
app.view().unwrap().rect
}
/// The whole of document `i`'s window, title bar included.
fn window_of(app: &VectorcraftApp, _ctx: &egui::Context, i: usize) -> egui::Rect {
let uid = app.session.documents()[i].uid;
// PLAN: the window's bounds come from its access node (canvas-w27's kit driver); the placed rect stands in until then.
app.ui.floating.iter().find(|w| w.uid == uid).unwrap().place
/// The whole of document `i`'s window, title bar included, as the last frame drew it: the bounds
/// of its access node, named by its title.
fn window_of(app: &VectorcraftApp, ctx: &egui::Context, i: usize) -> egui::Rect {
let title = app.session.documents()[i].title();
// The name is the title, a `*` while it has unsaved changes, then the zoom and color mode.
let window = |name: &str| {
name.strip_prefix(title.as_str()).map(|rest| rest.trim_start_matches('*')).is_some_and(|rest| rest.is_empty() || rest.starts_with(' '))
};
named(ctx, egui::accesskit::Role::Group, window).unwrap_or_else(|| panic!("document {i}'s window, {title}, was drawn"))
}
/// Where the last frame drew the tab of the window `window` at the top of its body (the title text
@@ -488,8 +527,8 @@ fn dragging_a_tab_off_the_strip_floats_its_document_at_the_pointer() {
let tab = tab_at(&shapes, &title);
// A short drag, and a drag along the strip short of the next tab's middle, leave the tabs as
// they are.
// The strip is 35 points tall: a drag that stays within its height is no tear-off.
drag(&mut app, &ctx, tab, tab + vec2(0.0, 35.0 - tab.y));
// A drag that stays within the strip's height is no tear-off.
drag(&mut app, &ctx, tab, pos2(tab.x, strip(&ctx).bottom()));
drag(&mut app, &ctx, tab, tab + vec2(40.0, 0.0));
assert!(app.ui.floating.is_empty(), "the document stays under its tab");
assert_eq!(app.session.active_index(), Some(2), "a drag is not a click");
@@ -530,7 +569,7 @@ fn a_window_dragged_by_its_tab_onto_the_strip_goes_back_under_the_tabs() {
assert!(tab_drawn(&shapes, &app.session.documents()[2].title()), "it has its tab again");
assert!(app.views[2].fitted, "it fits the canvas under the tabs");
let canvas = canvas_rect(&app);
assert!(canvas.top() >= 35.0 && canvas.width() > 1000.0, "the canvas under the tabs shows it: {canvas:?}");
assert!(canvas.top() >= strip(&ctx).bottom() && canvas.width() > 1000.0, "the canvas under the tabs shows it: {canvas:?}");
// Torn off again, it opens where its tab is dropped, not where its last window was.
let to = pos2(200.0, 300.0);
let tab = tab_at(&shapes, &app.session.documents()[2].title());
@@ -694,8 +733,9 @@ fn an_os_windows_tab_docks_on_the_strip() {
};
// The tab at the top of the window.
let tab = pos2(20.0, 15.0);
// Released over the main window's tab strip (y 0 to 35 on the screen), it docks.
os_drag(&mut app, tab, pos2(20.0, -280.0));
// Released over the main window's tab strip, it docks.
let over_strip = strip(&ctx).center().y - 300.0;
os_drag(&mut app, tab, pos2(20.0, over_strip));
assert!(app.ui.floating.is_empty(), "the document is back under the tabs");
assert_eq!(docked(&app), [0, 1]);
assert_eq!(app.session.active_index(), Some(1));
@@ -861,17 +901,7 @@ fn switching_views_targets_the_artboard_the_view_shows() {
/// ([`crate::canvas::release_over_panel`]), then the tabs and the canvas or panes, then the floating
/// document windows. → the cursor.
fn app_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> egui::CursorIcon {
let raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))),
max_texture_side: Some(8192),
events,
..Default::default()
};
let out = crate::testing::part_frame(app, ctx, raw, |app, ui| {
app.canvas_area(ui);
show(app, ui);
});
out.platform_output.cursor_icon
run_frame(app, ctx, events).platform_output.cursor_icon
}
/// Two 400 × 300 pt documents on `ctx`: the first, current under its tab, holds a 50 pt square at
+15 -7
View File
@@ -71,6 +71,11 @@ fn inside(nodes: &Nodes, name: &str, within: Rect) -> Rect {
named(nodes, name).into_iter().find(|r| within.contains(r.center())).unwrap_or_else(|| panic!("no `{name}` inside {within:?}"))
}
/// The open drawer: the Edit Toolbar node that holds its cells, larger than the ••• buttons of that name.
fn drawer(nodes: &Nodes) -> Rect {
named(nodes, EDIT).into_iter().max_by(|a, b| a.area().total_cmp(&b.area())).expect("the drawer is open")
}
/// The toolbar button of `tool`: the rail names a tool by its label (its shortcut is in its tip).
fn button_name(tool: &str) -> String {
tl!(tool_info(tool).unwrap().label).to_string()
@@ -283,18 +288,18 @@ fn a_new_toolbar_fills_from_the_drawer_beside_it() {
// Dragged onto the blank toolbar, a tool is added to it.
let nodes = settle(&mut app, &ctx, 2.0);
let bar = one(&nodes, "Mine");
drag(&mut app, &ctx, 3.0, one(&nodes, "Ellipse Tool").center(), bar.center());
drag(&mut app, &ctx, 3.0, inside(&nodes, "Ellipse Tool", drawer(&nodes)).center(), bar.center());
assert_eq!(held(&app, "Mine"), [["ellipse"]]);
assert_eq!(slots(&app), shipped, "the Tools panel's toolbar is untouched");
// Onto the lower third of its tool: a slot of its own after it.
let nodes = settle(&mut app, &ctx, 4.0);
let tool = inside(&nodes, &button_name("ellipse"), one(&nodes, "Mine"));
drag(&mut app, &ctx, 5.0, one(&nodes, "Artboard Tool").center(), pos2(tool.center().x, tool.top() + 0.85 * tool.height()));
drag(&mut app, &ctx, 5.0, inside(&nodes, "Artboard Tool", drawer(&nodes)).center(), pos2(tool.center().x, tool.top() + 0.85 * tool.height()));
assert_eq!(held(&app, "Mine"), [["ellipse"], ["artboard"]]);
// Onto the middle of the first tool: into its group.
let nodes = settle(&mut app, &ctx, 6.0);
let tool = inside(&nodes, &button_name("ellipse"), one(&nodes, "Mine"));
drag(&mut app, &ctx, 7.0, one(&nodes, "Slice Tool").center(), tool.center());
drag(&mut app, &ctx, 7.0, inside(&nodes, "Slice Tool", drawer(&nodes)).center(), tool.center());
assert_eq!(held(&app, "Mine"), [vec!["ellipse", "slice"], vec!["artboard"]]);
// A click on a tool picks it; the drawer stays open.
let nodes = settle(&mut app, &ctx, 8.0);
@@ -304,7 +309,7 @@ fn a_new_toolbar_fills_from_the_drawer_beside_it() {
assert!(app.ui.tools_drawer);
// Dragged from the toolbar into the drawer, a tool leaves it.
let artboard = inside(&nodes, &button_name("artboard"), one(&nodes, "Mine"));
drag(&mut app, &ctx, 10.0, artboard.center(), one(&nodes, "Ellipse Tool").center());
drag(&mut app, &ctx, 10.0, artboard.center(), inside(&nodes, "Ellipse Tool", drawer(&nodes)).center());
assert_eq!(held(&app, "Mine"), [["ellipse", "slice"]]);
assert_eq!(slots(&app), shipped, "the Tools panel's toolbar is untouched");
// The Tools panel's ••• button takes the drawer back beside its toolbar.
@@ -324,10 +329,10 @@ fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() {
let ctx = ctx();
let shipped = slots(&app);
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
// The menu's items called `name`, top first (the toolbar's own buttons aside).
// The menu's items called `name`, top first: inside the menu, the Add Tool… node larger than the + button.
let items = |nodes: &Nodes, name: &str| -> Vec<Rect> {
let bar = one(nodes, "Mine");
named(nodes, name).into_iter().filter(|r| !bar.contains(r.center())).collect()
let menu = named(nodes, ADD).into_iter().max_by(|a, b| a.area().total_cmp(&b.area())).expect("the menu is open");
named(nodes, name).into_iter().filter(|r| menu.contains(r.center())).collect()
};
// The menu at `time`, opened with a click on the + button unless it is open.
let open = |app: &mut VectorcraftApp, time: f64| -> Nodes {
@@ -373,6 +378,9 @@ fn the_drawer_moves_between_new_toolbars() {
for name in ["A", "B"] {
app.run("window.toolbar.new", json!({"name": name})).unwrap();
}
// B away from A, which the cascade puts it over.
let b = crate::custom_toolbars::panel_id(crate::custom_toolbars::find(&app.ui, "B").unwrap().id);
crate::panel_docking::place_floating(&mut app, &b, pos2(600.0, 900.0), 0.0).unwrap();
for (k, name) in ["B", "A", "B"].into_iter().enumerate() {
let nodes = settle(&mut app, &ctx, 1.0 + 2.0 * k as f64);
let edit = inside(&nodes, EDIT, one(&nodes, name));
+19 -4
View File
@@ -1025,6 +1025,19 @@ mod tests {
// PLAN: files-w11 owns Missing Fonts' hosted type; its test asserts the search there
}
/// `f`'s answer, read while the font menu held still: tests running alongside add fonts to
/// the shared database and lend it composite fonts.
fn while_fonts_hold<T>(mut f: impl FnMut() -> T) -> T {
let db = vectorcraft_text::FontDb::global();
loop {
let before = db.menu_family_list();
let out = f();
if before == db.menu_family_list() {
return out;
}
}
}
/// A document set in Inter and Source Serif 4 (Inter twice), with Inter the one recent font.
fn two_font_document() -> VectorcraftApp {
let mut app = new_app();
@@ -1160,12 +1173,11 @@ mod tests {
assert!(recent.iter().all(|r| r.family == "Inter"), "{recent:?}");
assert_eq!(recent.len(), db.styles("Inter").len(), "each style once, the closest not repeated");
assert!(recent.iter().all(|r| !r.style.is_empty()), "every row names its style: {recent:?}");
let system = replacement_rows(&app, "system", &used);
let (system, menu) = while_fonts_hold(|| (replacement_rows(&app, "system", &used), db.menu_family_list()));
assert!(system.iter().any(|r| r.family == "Source Sans 3" && r.style == "Regular"), "{system:?}");
assert!(!system.iter().any(|r| r.family.starts_with('.')), "the font menu's hidden families stay out");
// A composite font is a family without styles of its own, listed by its name alone.
assert!(system.iter().all(|r| !r.style.is_empty() || db.styles(&r.family).is_empty()), "no nameless rows: {system:?}");
let menu = db.menu_family_list();
let listed: std::collections::BTreeSet<&str> = system.iter().map(|r| r.family.as_str()).collect();
assert_eq!(listed.len(), menu.len(), "every family the font menu shows is listed");
let mut unique = system.clone();
@@ -1173,8 +1185,11 @@ mod tests {
assert_eq!(unique.len(), system.len(), "no family and style is listed twice");
// The dialog stores the rows when it opens and when the source changes, and a picked row
// sets both fields Change then uses.
open(&mut app);
assert_eq!(opened(&app).rows.len(), system.len());
let (rows, system) = while_fonts_hold(|| {
open(&mut app);
(opened(&app).rows, replacement_rows(&app, "system", &used))
});
assert_eq!(rows.len(), system.len());
let mut d = opened(&app);
set_source(&app, &mut d, "document", &used);
assert_eq!(d.rows.len(), document.len());
+21 -5
View File
@@ -152,9 +152,13 @@ fn help_f1_opens_discover_without_a_document() {
/// shows, marks nothing and the status bar says why.
#[test]
fn discover_says_why_a_tool_cannot_be_marked() {
fn texts(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
fn pass(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> egui::FullOutput {
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::panels::discover::show(app, ui));
out.textures_delta.clear();
out
}
fn texts(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
let out = pass(ctx, app, events);
fn collect(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
@@ -172,11 +176,23 @@ fn discover_says_why_a_tool_cannot_be_marked() {
texts(ctx, app, vec![]);
let drawn = texts(ctx, app, vec![]);
let pos = drawn.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("`{label}` not drawn: {drawn:?}")).1.center();
press_at(ctx, app, pos);
}
fn press_at(ctx: &egui::Context, app: &mut VectorcraftApp, pos: egui::Pos2) {
let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
for e in [egui::Event::PointerMoved(pos), button(true), button(false)] {
texts(ctx, app, vec![e]);
pass(ctx, app, vec![e]);
}
}
// A step's tool name is a link inside its sentence: the Link node named by its words.
fn click_link(ctx: &egui::Context, app: &mut VectorcraftApp, name: &str) {
ctx.enable_accesskit();
pass(ctx, app, vec![]);
let nodes = pass(ctx, app, vec![]).platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
let link = nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::Link && n.label().is_some_and(|l| l == name));
let b = link.and_then(|n| n.bounds()).unwrap_or_else(|| panic!("no link `{name}`"));
press_at(ctx, app, egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32));
}
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
let ctx = crate::testing::ui_context();
@@ -195,16 +211,16 @@ fn discover_says_why_a_tool_cannot_be_marked() {
assert!(app.ui.learn_locate.is_none());
assert_eq!(app.ui.status, reason);
let (tutorial, tool) = crate::panels::learn::catalog::SKILLS
let (tutorial, link) = crate::panels::learn::catalog::SKILLS
.iter()
.flat_map(|skill| skill.tutorials.iter())
.find_map(|t| t.steps.iter().find_map(|s| s.tool).map(|tool| (t, tool)))
.find_map(|t| t.steps.iter().find_map(|s| s.tool_name()).map(|(_, name, _)| (t, name)))
.unwrap();
let found = app.run("help.discover.search", json!({"query": tutorial.title})).unwrap();
let index = found["results"].as_array().unwrap().iter().position(|hit| hit["kind"] == "tutorial" && hit["id"] == tutorial.id).unwrap();
app.run("help.discover.choose", json!({"index": index})).unwrap();
app.status("");
click(&ctx, &mut app, vectorcraft_tools::tool_info(tool).unwrap().label);
click_link(&ctx, &mut app, link);
assert!(app.ui.learn_locate.is_none());
assert_eq!(app.ui.status, reason);
}
+21 -4
View File
@@ -1382,8 +1382,10 @@ mod tests {
assert_eq!(window.app.ui.recent_commands, recorded);
// Cancel closes the dialog without running the command.
close_dialogs(&mut window.app, false);
assert!(!window.app.any_dialog_open());
assert!(crate::tests::picks::open_dialogs(&window.app).is_empty());
// The window's next pass draws it gone: until then its layer, last drawn, is still up.
window.frame(vec![]);
assert!(!window.app.any_dialog_open());
assert_eq!(window.app.ui.recent_commands, recorded);
assert_eq!(window.app.ui.command_uses.count_of(&clean_up.key_text()), 1, "counted once, at the pick");
}
@@ -1587,8 +1589,10 @@ mod tests {
// selected tool), the status line aside.
let look = |app: &VectorcraftApp| {
let mut ui = serde_json::to_value(&app.ui).unwrap_or_default();
// The pick's count is the palette's record of the pick ([`record_pick`]), not the command's doing.
if let Some(o) = ui.as_object_mut() {
o.remove("status");
o.remove("command_uses");
}
let doc = app.session.active().map(|st| {
(st.doc.clone(), format!("{:?}", st.selection), st.history.undo.len(), st.revision, st.active_layer, st.layer_rows.clone())
@@ -2024,9 +2028,20 @@ mod tests {
window.app.ui.recent_commands = vec![CommandRef::new("object.ungroup"), CommandRef::new("select.all")];
window.app.ui.palette_open = true;
window.frame(vec![]);
assert!(!window.resolved("object.ungroup").enabled);
let all = window.resolved("select.all");
assert!(all.enabled && hint_of(&all).is_none());
// The rows are judged from the window under the palette, where a pick runs; a command read from
// inside the open palette is under its modal layer.
let nodes = window.frame(vec![]);
let names = names(Lang::EN);
let row = |id: &str| {
// A row shows the result's label; its name's menu path is the row's path.
let name =
names.iter().find(|(at, _)| at == id).and_then(|(_, name)| name.rsplit(" › ").next()).unwrap_or_else(|| panic!("{id} has a name"));
let option =
|n: &&egui::accesskit::Node| n.role() == egui::accesskit::Role::ListBoxOption && n.label().is_some_and(|l| l.starts_with(name));
nodes.iter().find(option).unwrap_or_else(|| panic!("a row for {name}"))
};
assert!(row("object.ungroup").is_disabled());
assert!(!row("select.all").is_disabled());
}
/// Paste is dimmed while the clipboard is empty and nothing can be pasted from the system
@@ -2034,6 +2049,8 @@ mod tests {
#[test]
fn paste_is_dimmed_only_while_nothing_can_be_pasted() {
let mut window = Window::on(Fixture::Multi.session());
// A still clock: the tick's next look at the (empty) system clipboard would undo the flag.
window.app.now_override = Some(window.app.system_paste_at.max(0.0));
window.app.system_paste = false;
window.frame(vec![]);
let hint = hint_of(&window.resolved("edit.paste")).expect("Paste is dimmed");
+56 -7
View File
@@ -459,6 +459,26 @@ pub(crate) fn hide_group(app: &mut VectorcraftApp, panel: &str) -> Result<Value,
Ok(result(app, closed))
}
/// A tab a panel shortcut hid with its group comes back alone when a command shows it: the
/// workspace would bring back the tabs closed with it, which only the shortcut restores
/// ([`restore_hidden_group`]).
fn show_alone(app: &mut VectorcraftApp, panel: &str) {
let ws = &app.ui.dock_workspace;
let grouped = app.ui.docking_hidden_groups.iter().any(|group| group.iter().any(|p| p == panel));
if !grouped || !ws.hidden().iter().any(|(p, place)| p == panel && !place.closed_with.is_empty()) {
return;
}
let hidden = ws.hidden().iter().map(|(p, place)| {
let mut place = place.clone();
if p == panel {
place.closed_with.clear();
}
(p.clone(), place)
});
let next = Workspace::from_parts(ws.layout().clone(), hidden.collect(), ws.floated().to_vec());
Arc::make_mut(&mut app.ui.dock_workspace).replace(next);
}
/// Reopens the tabs hidden together with `panel` and brings it to the front.
fn restore_hidden_group(app: &mut VectorcraftApp, panel: &str) -> Result<Value, String> {
let members =
@@ -810,6 +830,9 @@ fn shared_command_with(app: &mut VectorcraftApp, id: &str, params: &Value, extra
return run(app, vec![action], reveal);
}
let panel = p.panel.clone().ok_or("panel is required")?;
if !matches!(id, "window.panel.close" | "window.panel.minimize") {
show_alone(app, &panel);
}
let space = command_space(app);
let ws: &Workspace<String> = &app.ui.dock_workspace;
let shown = ws.layout().contains(&panel);
@@ -944,10 +967,14 @@ fn float_actions(
DragUnit::Group(_) => Some(DockCommands::FloatGroup),
_ => None,
};
if let Some(command) = framework.filter(|_| geometry.iter().all(Option::is_none)) {
return command_actions(scene, command, panel).map_err(|e| e.to_string());
}
let window = floating_window(layout, panel);
// A panel or group floated out of an icon column opens expanded; the dock floats a dragged icon collapsed.
let expand = (framework.is_some() && window.is_none() && layout.opens_in_flyout(panel)).then(|| Action::set_iconic(panel.clone(), false));
if let Some(command) = framework.filter(|_| geometry.iter().all(Option::is_none)) {
let mut actions = command_actions(scene, command, panel).map_err(|e| e.to_string())?;
actions.extend(expand);
return Ok(actions);
}
let whole = match unit {
DragUnit::Panel(_) => window.is_some_and(|w| w.panels().count() == 1),
DragUnit::Group(_) => window.is_some_and(|w| w.groups().len() == 1),
@@ -957,11 +984,12 @@ fn float_actions(
let base = kept.unwrap_or_else(|| space.place(space.size_of(unit, None)));
let min = egui::pos2(p.x.unwrap_or(base.min.x), p.y.unwrap_or(base.min.y));
let rect = egui::Rect::from_min_size(min, egui::vec2(p.width.unwrap_or(base.width()), p.height.unwrap_or(base.height())));
Ok(vec![match (kept, unit) {
let float = match (kept, unit) {
(Some(_), _) => Action::move_floating(panel.clone(), rect),
(None, DragUnit::Panel(_)) => Action::float(panel.clone(), rect),
(None, _) => unit_action(unit, Target::float(rect)),
}])
};
Ok(std::iter::once(float).chain(expand).collect())
}
/// Applies `actions` ([`apply`]) and reveals `reveal`, the panel the command showed: the panels
@@ -1024,10 +1052,15 @@ pub(crate) fn place_floating(app: &mut VectorcraftApp, panel: &str, pos: egui::P
if !layout.contains(&id) {
actions.push(Action::open(id.clone(), None));
}
// A rail's window is a stepped column, which the dock fits to the rail's grid; it keeps the steps it had.
let steps = is_rail(&id).then(|| column_of(layout, &id).and_then(|(_, column)| column.steps).unwrap_or(1));
actions.push(match floating_window(layout, &id) {
Some(window) if window.panels().count() == 1 => Action::move_floating(id, rect),
_ => Action::float(id, rect),
Some(window) if window.panels().count() == 1 => Action::move_floating(id.clone(), rect),
_ => Action::float(id.clone(), rect),
});
if let Some(steps) = steps {
actions.push(Action::set_column_steps(id, steps));
}
let ctx = app.ui_ctx.clone();
apply(app, ctx.as_ref(), actions).map(drop)
}
@@ -1139,6 +1172,10 @@ pub(crate) struct Panels<'a> {
impl DockPanels<String> for Panels<'_> {
fn body(&mut self, panel: &String, ui: &mut egui::Ui, _cx: &mut BodyCx<'_>) {
crate::dock::panel_body(self.app, ui, panel);
// A floating panel's OS window runs a pass of its own, whose leftover keys the main window's pass never sees.
if ui.ctx().viewport_id() != egui::ViewportId::ROOT {
crate::shortcuts::palette_window_keys(self.app, ui.ctx());
}
}
fn group_view(&mut self, panels: &[String], _active: usize, ui: &mut egui::Ui, at: GroupAt, cx: &mut BodyCx<'_>) -> Option<f32> {
@@ -1178,6 +1215,18 @@ fn window_viewport(app: &VectorcraftApp, panel: &str) -> Option<egui::ViewportId
app.dock_rt.windows.iter().find(|(p, _)| p == first).map(|(_, viewport)| *viewport)
}
/// Whether the OS window of a floating panel lies at `pos`, a point of the main window: a palette
/// window stays in front of the main window.
pub(crate) fn os_window_at(app: &VectorcraftApp, ctx: &egui::Context, pos: egui::Pos2) -> bool {
if app.dock_rt.windows.is_empty() {
return false;
}
let origin = ctx.input(|i| i.raw.viewports.get(&i.raw.viewport_id).and_then(|v| v.inner_rect).map(|r| r.min.to_vec2()));
let Some(origin) = origin else { return false };
let under = craft::ui::runtime::windows::WindowHost::of(ctx).viewports_at(pos + origin);
under.iter().any(|viewport| app.dock_rt.windows.iter().any(|(_, shown)| shown == viewport))
}
/// Brings the OS window of the floating window holding `panel` forward, as it was last drawn.
fn raise(app: &VectorcraftApp, ctx: &egui::Context, panel: &str) {
if let Some(viewport) = window_viewport(app, panel) {
+24 -5
View File
@@ -15,7 +15,7 @@ use craft::draw::ui::transform::{
use craft::keymap::CommandRef;
use craft::ui::buttons::{IconButton, Link};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Entry, Props, Show, ShowContainer, SideLabel};
use craft::ui::contract::{Bind, Entry, LabelPress, Props, Show, ShowContainer, SideLabel};
use craft::ui::display::{Shade, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::Row;
@@ -23,6 +23,7 @@ use craft::ui::menu::PanelRow;
use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook};
use craft::ui::popover::Popover;
use craft::ui::runtime::commands::{CommandState, CommandStates};
use craft::ui::runtime::overlay::CloseReason;
use craft::ui::text::{NumberField, NumberOutput, NumberPick, StepArrows};
use egui::Ui;
use serde_json::{Value, json};
@@ -65,6 +66,9 @@ pub struct TransformUi {
pub reference_point: usize,
/// Whether the Transform popover under the Control bar's link is open.
pub popover: bool,
/// The popover closed at the press of the click still running: a click on an X:, Y:, W: or H: caption that
/// closed it at its press leaves it closed.
closed_by_press: bool,
/// The point a field's running gesture turns or shears about ([`gesture_origin`]).
gesture_origin: Value,
/// The artboards' rectangles when a field's running gesture began ([`live_artboard`]).
@@ -75,7 +79,14 @@ pub struct TransformUi {
impl Default for TransformUi {
fn default() -> Self {
TransformUi { reference_point: 4, popover: false, gesture_origin: Value::Null, gesture_boards: Vec::new(), gesture_start: Rect::ZERO }
TransformUi {
reference_point: 4,
popover: false,
closed_by_press: false,
gesture_origin: Value::Null,
gesture_boards: Vec::new(),
gesture_start: Rect::ZERO,
}
}
}
@@ -422,8 +433,13 @@ pub(crate) fn object_bar_fields(app: &mut VectorcraftApp, ui: &mut Ui) -> Option
let bx = app.selection_box()?;
let state = box_state(app, &bx);
let start = gesture_start(app, bx.rect);
let out = fields(app, Some(state), start, panel_groups(), true).show(ui);
let out = fields(app, Some(state), start, panel_groups(), true).caption_press(LabelPress::Link).show(ui);
apply_fields(app, &out, EditPath::Preview, set_object_bounds);
// A click on a caption opens the Transform popover as the Transform link does, or closes it.
if out.link.is_some() {
let panel = &mut app.ui.transform_panel;
panel.popover = !panel.closed_by_press;
}
Some(out)
}
@@ -684,8 +700,11 @@ pub(crate) fn popover(app: &mut VectorcraftApp, ui: &mut Ui, opener: &egui::Resp
if opener.clicked() {
open = !open;
}
Popover::new(tl!("Transform"), Bind::bound(&mut open)).opened_by(opener).show(ui, |ui, _| show(app, ui));
app.ui.transform_panel.popover = open;
let shown = Popover::new(tl!("Transform"), Bind::bound(&mut open)).opened_by(opener).show(ui, |ui, _| show(app, ui));
let clicking = ui.input(|i| i.pointer.any_down() || i.pointer.any_released());
let panel = &mut app.ui.transform_panel;
panel.closed_by_press = shown.output.closed == Some(CloseReason::Outside) || (panel.closed_by_press && clicking);
panel.popover = open;
}
/// Set a boolean preference (through `prefs.set`, as agents do) and return the command's result.
+6 -4
View File
@@ -131,10 +131,12 @@ fn saved_scheme_accent_and_canvas_color_show_from_the_first_frame() {
for _ in 0..2 {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx()));
out.textures_delta.clear();
let (theme, _, accent) = crate::theme::root_theme(&app.session.prefs);
let (default_theme, _, default_accent) = crate::theme::root_theme(&Prefs::default());
assert_ne!(theme, default_theme, "the saved scheme");
assert!(accent.is_some() && accent != default_accent, "the saved accent");
let shown = crate::theme::root_theme(&app.session.prefs);
assert_ne!(shown.0, crate::theme::root_theme(&Prefs::default()).0, "the saved scheme");
// Classic keeps its own accent whatever accent is saved, as production's Classic tokens did.
let classic = Prefs { ui_color_scheme: "classic".into(), ui_brightness: app.session.prefs.ui_brightness.clone(), ..Prefs::default() };
let want = crate::theme::root_theme(&classic);
assert!(shown.0 == want.0 && shown.2 == want.2, "the saved accent");
assert_eq!(canvas_color(&app.session.prefs.canvas_color), Some(egui::Color32::WHITE));
}
}
+14 -3
View File
@@ -92,10 +92,10 @@ pub(crate) fn run_fired(app: &mut VectorcraftApp, ctx: &egui::Context, fired: &F
}
/// A key bound only to commands that can't run now (`FrameOutput::dimmed`) does what production's key did, its menu
/// item's action, which says why it can't run or does nothing; nothing while the gate holds the commands (a file dialog,
/// a shortcut being recorded, Presentation Mode).
/// item's action, which says why it can't run or does nothing; nothing while a dialog or a text field has the keys or the
/// gate holds the commands (a file dialog, a shortcut being recorded, Presentation Mode).
pub(crate) fn run_dimmed(app: &mut VectorcraftApp, ctx: &egui::Context, fired: &Fired) {
if crate::menus::model::gate_lets(app, &fired.command) {
if !app.any_dialog_open() && !ctx.egui_wants_keyboard_input() && crate::menus::model::gate_lets(app, &fired.command) {
run_fired(app, ctx, fired);
}
}
@@ -160,6 +160,17 @@ pub(crate) fn escape(app: &mut VectorcraftApp, ctx: &egui::Context) {
escape_ends_one_thing(app, ctx);
}
/// In a floating panel's OS window, the keys none of its controls took, which production's palette windows passed
/// on to the main window: Escape ends one thing as there ([`escape`]), and Enter is the canvas's tool's (in
/// Presentation Mode it opens nothing).
pub(crate) fn palette_window_keys(app: &mut VectorcraftApp, ctx: &egui::Context) {
escape(app, ctx);
if keys::with_window_intents(ctx, false, |window| window.take(Intent::Submit)) && app.ui.screen_mode != 3 {
let view = app.view_info();
crate::canvas::tool_enter(app, vectorcraft_tools::Mods::default(), view);
}
}
/// An Escape that nothing else took ends the first of these that is on.
fn escape_ends_one_thing(app: &mut VectorcraftApp, ctx: &egui::Context) {
if app.session.active().is_some_and(|d| d.doc.pattern_edit.is_some()) {
@@ -27,6 +27,17 @@ impl Keyboard {
crate::testing::app_frame(app, &self.ctx, egui::RawInput { events, screen_rect, time: Some(time), focused, ..Default::default() });
}
/// [`Self::frame`] without the window's parts: the app's tick and its held tools' returns only, so a
/// pointer press reaches no canvas.
fn off_canvas(&self, app: &mut VectorcraftApp, time: f64, events: Vec<egui::Event>) {
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)));
let raw = egui::RawInput { events, screen_rect, time: Some(time), focused: true, ..Default::default() };
crate::testing::part_frame(app, &self.ctx, raw, |app, ui| {
app.tick(ui.ctx());
crate::shortcuts::follow_holds(app, ui.ctx());
});
}
/// `key` pressed (or repeated while it is down) at `time`, typing `letter`.
fn press(&self, app: &mut VectorcraftApp, time: f64, key: Key, letter: &str) {
let press = egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
@@ -226,7 +237,8 @@ fn a_press_in_the_frame_that_lets_go_waits_for_the_canvas() {
let at = egui::pos2(150.0, 125.0);
let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE };
let release = egui::Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE };
keys.frame(&mut app, 0.1, vec![egui::Event::PointerMoved(at), press, release]);
// The press reaches no canvas in these frames: the canvas's own press is dispatched here.
keys.off_canvas(&mut app, 0.1, vec![egui::Event::PointerMoved(at), press, release]);
assert_eq!(app.session.tool_id(), "scale", "canvas {canvas}: no decision before the canvas");
if canvas {
let view = app.view_info();
@@ -234,7 +246,7 @@ fn a_press_in_the_frame_that_lets_go_waits_for_the_canvas() {
crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, 150.0, 125.0), view);
}
}
keys.frame(&mut app, 2.0, vec![]);
keys.off_canvas(&mut app, 2.0, vec![]);
assert_eq!(app.session.tool_id(), if canvas { "pen" } else { "scale" }, "canvas {canvas}");
}
}
+3 -2
View File
@@ -1463,7 +1463,6 @@ fn enter_after_a_drag_repeats_its_offset() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 800, "height": 300})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let ctx = ready(&mut app);
let enter = || tap(Key::Enter, Modifiers::NONE);
let lefts = |app: &VectorcraftApp| {
let kids = app.session.doc().unwrap().doc.layers[0].children().unwrap();
@@ -1479,7 +1478,9 @@ fn enter_after_a_drag_repeats_its_offset() {
let [moved] = lefts(&app)[..] else { panic!("one rectangle") };
let step = moved - 10.0;
assert!(step > 0.0);
key_frame(&mut app, &ctx, vec![]);
// The window's first frame comes after the drag, which the view before it measures: one fitted to the window
// would put the press on a corner handle.
let ctx = ready(&mut app);
key_frame(&mut app, &ctx, enter());
assert_eq!(dialog_kind(&app).as_deref(), Some("object.move"), "Enter opens Move");
assert_eq!(dialog_field(&app, "dx").and_then(|v| v.as_f64()).map(f64::round), Some(step));
+9 -2
View File
@@ -88,9 +88,16 @@ impl Panel {
tree.keys().into_iter().filter_map(|key| tree.name_of(key)).map(str::to_owned).collect()
}
/// The control named `name` in the latest frame.
/// The control named `name` in the latest frame. A caption link takes the name of the number field it captions
/// (the Control bar's X, Y, W and H): the field is the control.
fn look(&self, name: &str) -> Target {
self.fixture.by_label(name).unwrap_or_else(|| panic!("no {name:?} in {:?}", self.names()))
use craft::ui::contract::Role;
let found = self.fixture.by_label(name).unwrap_or_else(|| panic!("no {name:?} in {:?}", self.names()));
let tree = self.fixture.tree();
if tree.role_of(found.node) != Some(Role::LINK) {
return found;
}
self.fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|t| tree.name_of(t.node) == Some(name)).unwrap_or(found)
}
/// A fresh frame, then the control named `name`.
+12 -7
View File
@@ -17,7 +17,7 @@ use craft::draw::ui::transform::{SizeUnit, TransformField, TransformFields, Tran
use craft::theme::{ControlSize, Size};
use craft::ui::buttons::{Button, IconButton};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, BodyCx, Entry, Props as _, Show as _, ShowContainer as _, ThemeScope, Tracked};
use craft::ui::contract::{Bind, BodyCx, Entry, Gap, Props as _, Show as _, ShowContainer as _, ThemeScope, Tracked};
use craft::ui::display::Divider;
use craft::ui::docking::{DockGrid, DockSizes, GroupAt};
use craft::ui::form::Field;
@@ -732,18 +732,23 @@ fn bottom_controls(app: &mut VectorcraftApp, ui: &mut Ui, footer: RailFooter) {
];
let mode_button = |ui: &mut Ui, icon: &'static str, name: &str, on: bool| {
let tip = format!("{} (Shift+D)", tl!(name));
IconButton::new(IconId::new(icon)).label(tip.clone()).tooltip(tip).selected(on).show(ui).clicked()
let button = IconButton::new(IconId::new(icon)).label(tip.clone()).tooltip(tip).selected(on);
// Small in two columns, where the three sit side by side in the rail's width.
let button = if two { button.size(ControlSize::Sm) } else { button };
button.show(ui).clicked()
};
let mut run = None;
Row::new().wrap(true).show(ui, |ui, _| {
if show.draw_mode {
if two {
// Side by side, each one a click away.
for (mode, icon, name, id) in modes {
if mode_button(ui, icon, name, app.session.draw_mode == mode) {
run = Some(("view.drawMode", json!({ "mode": id })));
// Side by side, each one a click away, a tight gap apart to fit the rail's width.
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
for (mode, icon, name, id) in modes {
if mode_button(ui, icon, name, app.session.draw_mode == mode) {
run = Some(("view.drawMode", json!({ "mode": id })));
}
}
}
});
} else if let Some((mode, icon, name, _)) = modes.into_iter().find(|m| m.0 == app.session.draw_mode)
&& mode_button(ui, icon, name, mode != vectorcraft_engine::DrawMode::Normal)
{
+4 -3
View File
@@ -258,8 +258,9 @@ fn polygon_and_star_canvas_counts_persist_without_new_toolbar_dialogs() {
}
}
/// The paint chips, drawing modes and the rest of the footer lie inside the rail at one and at two columns, and in two
/// columns the three drawing modes sit side by side, each setting its mode (#1129).
/// The paint chips, drawing modes and the rest of the footer lie inside the rail at one and at two columns (one column
/// shows the current drawing mode alone), and in two columns the three drawing modes sit side by side, each setting
/// its mode (#1129).
#[test]
fn the_paint_and_drawing_mode_buttons_fit_the_toolbar_width() {
let mut app = app_with(200, 200);
@@ -271,7 +272,7 @@ fn the_paint_and_drawing_mode_buttons_fit_the_toolbar_width() {
app.run("window.toolbarColumns", json!({ "double": double })).unwrap();
nodes = settled(&mut app, &ctx, k as f64 * 10.0, 900.0);
let rail = named_rect(&nodes, "Tools");
for label in footer {
for label in &footer[..if double { 6 } else { 4 }] {
let r = named_rect(&nodes, label);
assert!(rail.expand(0.5).contains_rect(r), "double {double}: {label} {r:?} in {rail:?}");
}