mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
Merge branch 'area/app2' into area/app3
# Conflicts: # crates/ui-egui/src/chrome/control_bar.rs
This commit is contained in:
@@ -33,6 +33,9 @@ pub struct Interaction {
|
||||
/// The bounding box of `selection` in `doc`, measured once for a move drag
|
||||
/// ([`crate::Session::move_drag_box`]): each step offsets it by the drag's move.
|
||||
pub(crate) move_box: std::sync::OnceLock<Option<vectorcraft_doc::OrientedBox>>,
|
||||
/// A switch to another document keeps the previews as one undo step in this one, as a panel field's scrub keeps
|
||||
/// its edits; otherwise the switch cancels the interaction, as it does a drag.
|
||||
pub keep_on_switch: bool,
|
||||
}
|
||||
|
||||
/// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]).
|
||||
|
||||
@@ -218,9 +218,14 @@ impl Session {
|
||||
let _ = self.give_back_tool(view);
|
||||
let _ = self.deactivate_tool(view);
|
||||
// A batch leaves its interaction open in the document it leaves, to keep or roll back with
|
||||
// the rest of the batch; anything else in progress (a drag) is cancelled.
|
||||
// the rest of the batch; one that keeps on a switch is kept; anything else in progress (a
|
||||
// drag) is cancelled.
|
||||
if self.batch_stash.is_none() {
|
||||
let _ = self.cancel_interaction();
|
||||
let _ = if self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.keep_on_switch) {
|
||||
self.commit_interaction()
|
||||
} else {
|
||||
self.cancel_interaction()
|
||||
};
|
||||
}
|
||||
self.keep_tool_settings();
|
||||
self.tool = self.make_tool(self.tool.id());
|
||||
|
||||
@@ -320,6 +320,7 @@ impl Session {
|
||||
plane_placed: false,
|
||||
copies: None,
|
||||
move_box: std::sync::OnceLock::new(),
|
||||
keep_on_switch: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ impl FontDb {
|
||||
/// of its face nearest an upright Regular ([`regular_rank`]), read from the tables of that
|
||||
/// face's file as the face's own when loaded, without loading it. `None` when it isn't
|
||||
/// installed, and on wasm.
|
||||
// PLAN: decision q358 C reads these from the catalog's `FaceInfo::traits`, but `FaceTraits` (font-catalog scan.rs:115) carries no `FontClass`, whose name rule is `FontTraits::of` in traits.rs (outside this set); with the class in `FaceTraits` (type-w2) or a shared classifier, this reads `FaceInfo` and the file read goes.
|
||||
// PLAN: decision q358 C reads these from the catalog's scan records. `FaceInfo::family_class` and `panose` give the class's OS/2 inputs, but not the names, Unicode ranges and Thai characters `FontTraits::of` (traits.rs) also reads, nor the x-height, cap height, average width and italic angle of `FontLikeness`; once the records carry those, this reads `FaceInfo` and the file read goes.
|
||||
fn installed_traits(&self, family: &str) -> Option<FontTraits> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
|
||||
@@ -64,10 +64,24 @@ impl VectorcraftApp {
|
||||
let views = session.documents().iter().map(View::of).collect();
|
||||
let view_uids = session.documents().iter().map(|d| d.uid).collect();
|
||||
let known = session.documents().iter().map(|d| d.uid).collect();
|
||||
// Without a host clipboard (tests, the web before its host sets one) copies stay inside the app.
|
||||
// Without a host clipboard (tests, the web before its host sets one) a copy's text goes out through egui, as
|
||||
// a text field's does.
|
||||
let fallback_copy = Arc::new(std::sync::Mutex::new(None));
|
||||
let clipboard = match services.clipboard.take() {
|
||||
Some(backend) => Clipboard::new(backend),
|
||||
None => Clipboard::new(EventClipboard::new(|| 0, |_| Ok(0))),
|
||||
None => {
|
||||
let copied = Arc::clone(&fallback_copy);
|
||||
Clipboard::new(EventClipboard::new(
|
||||
|| 0,
|
||||
move |flavors: &[craft::platform::clipboard::Flavor]| {
|
||||
let text = flavors.iter().enumerate().find(|(_, f)| f.mime == craft::platform::clipboard::TEXT);
|
||||
if let (Some((_, f)), Ok(mut slot)) = (text, copied.lock()) {
|
||||
*slot = Some(String::from_utf8_lossy(&f.data).into_owned());
|
||||
}
|
||||
Ok(text.map_or(0, |(i, _)| i))
|
||||
},
|
||||
))
|
||||
}
|
||||
};
|
||||
// PLAN: the hosts (hub-w3) replace `host` with the one they build (files, settings, jobs); every frame installs it through `frame_input`.
|
||||
let host = Arc::new(Host::builder(APP_INFO).i18n(i18n::shared()).build());
|
||||
@@ -153,6 +167,7 @@ impl VectorcraftApp {
|
||||
character_focus: None,
|
||||
run_count: 0,
|
||||
channel: None,
|
||||
deferred_control: None,
|
||||
control_rotate_press: None,
|
||||
pointer_waits: Vec::new(),
|
||||
context: 0,
|
||||
@@ -161,6 +176,7 @@ impl VectorcraftApp {
|
||||
frame_rate: Default::default(),
|
||||
hover_doc: None,
|
||||
clipboard_out: None,
|
||||
fallback_copy,
|
||||
clipboard_in: None,
|
||||
clipboard_publishing: Default::default(),
|
||||
pending_url: None,
|
||||
|
||||
@@ -44,7 +44,19 @@ impl VectorcraftApp {
|
||||
});
|
||||
self.finish_captures(finished);
|
||||
let settle = settle_ms(ctx.global_style().animation_time);
|
||||
while let Some(req) = self.channel.as_mut().and_then(ControlChannel::next_request) {
|
||||
while let Some(req) = self.deferred_control.take().or_else(|| self.channel.as_mut().and_then(ControlChannel::next_request)) {
|
||||
// A request held past its deadline is answered as one still queued then.
|
||||
if req.deadline.is_some_and(|deadline| motion::now() >= deadline) {
|
||||
let _ = req.reply.send(json!({"ok": false, "error": craft::automation::control::expired_error()}));
|
||||
continue;
|
||||
}
|
||||
// `ui.pointer` and `ui.tool.select` act at once, while `ui.key` and other synthetic input reach the tool
|
||||
// in a later pass: they wait for that earlier input, so a key pressed during a drag reaches its tool first.
|
||||
if matches!(req.method.as_str(), "ui.pointer" | "ui.tool.select") && !host.injected_idle() {
|
||||
self.deferred_control = Some(req);
|
||||
ctx.request_repaint();
|
||||
break;
|
||||
}
|
||||
let roots = self.automation_roots.clone();
|
||||
self.ui.answering_control = true;
|
||||
// Guarded per request: a panic must not stop the requests behind it.
|
||||
|
||||
@@ -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.
|
||||
@@ -150,9 +150,9 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin
|
||||
queued.push(ViewRequest::Place(ViewCommands::FitArtboard));
|
||||
}
|
||||
let mut cv = view.canvas(scaling, area);
|
||||
let (x, y, mut zero) = rulers::texts(app, win);
|
||||
let (x, y, zero) = rulers::texts(app, win);
|
||||
let strips = if app.ui.view.rulers && !presenting {
|
||||
Some(rulers::strips(&mut zero, kind))
|
||||
Some(rulers::strips(zero, kind))
|
||||
} else {
|
||||
rulers::hidden(app);
|
||||
None
|
||||
@@ -256,12 +256,12 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O
|
||||
crate::dialogs::dimension::floating(app, ui, space.view.rect);
|
||||
}
|
||||
let editing = app.session.tool_wants_text();
|
||||
crate::type_editing::show(app, ui);
|
||||
crate::type_editing::show(app, ui, canvas_id(win));
|
||||
out.reply = pass.map(|pass| tool_adapter::run(app, ui, pass));
|
||||
// An edit the tool host started (a double-click on type) shows its editor in the same pass, so the keys of the
|
||||
// next frame are the edit's.
|
||||
if !editing {
|
||||
crate::type_editing::show(app, ui);
|
||||
crate::type_editing::show(app, ui, canvas_id(win));
|
||||
}
|
||||
}
|
||||
drops::show(app, ui, win, kind);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -129,9 +129,10 @@ pub(super) fn hidden(app: &mut VectorcraftApp) {
|
||||
app.session.end_ruler_origin_drag();
|
||||
}
|
||||
|
||||
/// The strips of a body's rulers, counting from `zero`. A pane's strips only paint.
|
||||
pub(super) fn strips(zero: &mut Point, kind: BodyKind) -> Rulers<'_> {
|
||||
Rulers::new(tl!("Rulers"), Bind::bound(zero)).units(units()).interactive(kind == BodyKind::Live)
|
||||
/// The strips of a body's rulers, counting from `zero`. A pane's strips only paint. The zero point is given: the
|
||||
/// document keeps it, and a drag edits it once, at its release ([`apply`]).
|
||||
pub(super) fn strips(zero: Point, kind: BodyKind) -> Rulers<'static> {
|
||||
Rulers::new(tl!("Rulers"), Bind::given(zero)).units(units()).interactive(kind == BodyKind::Live)
|
||||
}
|
||||
|
||||
/// A drag in progress, kept between passes: what it started in, and whether it no longer counts.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -26,8 +26,11 @@ 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;
|
||||
}
|
||||
|
||||
/// An anchor button: icon, tooltip, command and the convert command's `to`.
|
||||
@@ -298,7 +301,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);
|
||||
|
||||
@@ -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;
|
||||
@@ -80,18 +81,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();
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ use vectorcraft_engine::cmd::color_value;
|
||||
use vectorcraft_engine::cmd::swatchlib;
|
||||
|
||||
use super::preview::LivePreview;
|
||||
use crate::panels::color::{color_of_values, gamut, model_values};
|
||||
use crate::panels::color::{WorkingRgb, color_of_values, gamut, model_values};
|
||||
use crate::panels::swatches::{DOCUMENT_SWATCHES, colour_libraries};
|
||||
use crate::panels::{color_json, srgba};
|
||||
use crate::{VectorcraftApp, screen_color};
|
||||
@@ -163,6 +163,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
.eyedropper(true)
|
||||
.add_to_swatches(false)
|
||||
.gamut(gamut(app))
|
||||
.working_rgb(WorkingRgb)
|
||||
.swatch_view(swatch_view(app));
|
||||
if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk)
|
||||
&& let Some(converter) = working_cmyk()
|
||||
@@ -202,7 +203,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
while let Some((parent, request)) = dialogs.with(|h| h.take_color_request()) {
|
||||
let start = request.color.unwrap_or(Srgba { r: 1.0, g: 1.0, b: 1.0, a: 1.0 });
|
||||
let key = request.key.clone();
|
||||
let child = ColorPickerDialog::from_request(request).eyedropper(true).add_to_swatches(false).gamut(gamut(app));
|
||||
let child = ColorPickerDialog::from_request(request).eyedropper(true).add_to_swatches(false).gamut(gamut(app)).working_rgb(WorkingRgb);
|
||||
let id = dialogs.with(|h| h.open_child(child, parent));
|
||||
app.color_dialogs.pickers.push(Open { id, target: Target::Answer { parent, key }, start, keep: false, preview: LivePreview::default() });
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ use craft::ui::contract::Show as _;
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, Prompt, StackDialog, dialog_id};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog};
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use egui::Ui;
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -535,7 +536,8 @@ impl InstallPrompt {
|
||||
}
|
||||
|
||||
impl StackDialog for InstallPrompt {
|
||||
type Result = ();
|
||||
/// OK was pressed in a pass automation's injected input drove: the answer is read after that pass.
|
||||
type Result = bool;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
@@ -545,7 +547,7 @@ impl StackDialog for InstallPrompt {
|
||||
Some(INSTALL_KIND)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<bool>> {
|
||||
let mut prompt = Prompt::new(tl!("Install Plug-in"), self.message.clone()).paragraph(self.detail.clone());
|
||||
if self.automated {
|
||||
prompt = prompt.paragraph(automation_asked_note());
|
||||
@@ -558,7 +560,7 @@ impl StackDialog for InstallPrompt {
|
||||
])
|
||||
.show(ui);
|
||||
match shown.picked {
|
||||
Some(0) => Some(DialogResult::Ok(())),
|
||||
Some(0) => Some(DialogResult::Ok(WindowHost::of(ui.ctx()).injected_pass())),
|
||||
Some(1) => Some(DialogResult::Cancel),
|
||||
_ => None,
|
||||
}
|
||||
@@ -595,20 +597,21 @@ fn pump_install(app: &mut VectorcraftApp) {
|
||||
});
|
||||
let Some(answer) = answer else { return };
|
||||
match answer.ok() {
|
||||
Some(()) => approve(app),
|
||||
Some(injected) => approve(app, injected),
|
||||
None => app.pending_plugin_install = None,
|
||||
}
|
||||
}
|
||||
|
||||
/// OK of the install question. A question automation asked has no OK that installs, and automation
|
||||
/// can't press one: either asks again, a new question that waits its delay.
|
||||
fn approve(app: &mut VectorcraftApp) {
|
||||
/// OK of the install question, `injected` when automation's input pressed it. A question automation
|
||||
/// asked has no OK that installs, and automation can't press one: either asks again, a new question
|
||||
/// that waits its delay.
|
||||
fn approve(app: &mut VectorcraftApp, injected: bool) {
|
||||
let Some(pending) = app.pending_plugin_install.take() else { return };
|
||||
if pending.origin == InstallOrigin::Automation {
|
||||
ask_install(app, pending);
|
||||
return;
|
||||
}
|
||||
if app.automation_is_acting() {
|
||||
if injected || app.automation_is_acting() {
|
||||
app.status("Only the person at the keyboard can approve installing a plug-in".to_string());
|
||||
ask_install(app, pending);
|
||||
return;
|
||||
|
||||
@@ -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,28 @@ 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;
|
||||
// A move or resize of the fallback layer is where the window opens from now on.
|
||||
if let Some(placed) = out.placed {
|
||||
x.place = placed.translate(-origin);
|
||||
}
|
||||
}
|
||||
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 +422,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;
|
||||
|
||||
@@ -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::unique(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::unique(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
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -367,14 +367,18 @@ pub(crate) fn paint_family_sample(cx: &ContentPainterCx, rect: Rect, family: &st
|
||||
let loaded = db.face(family, style);
|
||||
let state = match catalog.resolve(family, style) {
|
||||
Some((face, _)) => cx.document_face(&format!("font-sample/{}/{}", face.family, face.style), || {
|
||||
let data = catalog.load(&face).ok()?;
|
||||
Some(FaceBytes::new(data.bytes, data.index).coords(face.variations.iter().copied()))
|
||||
let catalog = Arc::clone(catalog);
|
||||
move || {
|
||||
let data = catalog.load(&face).ok()?;
|
||||
Some(FaceBytes::new(data.bytes, data.index).coords(face.variations.iter().copied()))
|
||||
}
|
||||
}),
|
||||
// The catalog finds the installed fonts only: a bundled family is drawn from the database's own face.
|
||||
None => {
|
||||
let Some(face) = loaded.as_ref() else { return };
|
||||
cx.document_face(&format!("font-sample/{}/{}", face.family, face.style), || {
|
||||
Some(FaceBytes::new(Arc::from(face.file_data()), face.face_index()).coords(face.variations().iter().copied()))
|
||||
let face = Arc::clone(face);
|
||||
move || Some(FaceBytes::new(Arc::from(face.file_data()), face.face_index()).coords(face.variations().iter().copied()))
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
@@ -170,6 +170,8 @@ pub struct VectorcraftApp {
|
||||
run_count: u64,
|
||||
/// The control channel's requests and their replies, while the host opened one.
|
||||
pub(crate) channel: Option<ControlChannel>,
|
||||
/// A `ui.pointer` or `ui.tool.select` held until the synthetic input sent before it reached the tool.
|
||||
deferred_control: Option<ControlRequest>,
|
||||
/// Where a control-channel Rotate View drag began, kept between its requests.
|
||||
pub(crate) control_rotate_press: Option<control::RotateViewPress>,
|
||||
/// The `ui.pointer` replies that wait for the edit their gesture started on another thread.
|
||||
@@ -188,6 +190,9 @@ pub struct VectorcraftApp {
|
||||
/// Text to copy to the system clipboard next (`flush_clipboard_out`) and what came with a
|
||||
/// paste (a Paste event's text, a picture or file the host read: [`Self::paste_from_host`]).
|
||||
clipboard_out: Option<String>,
|
||||
/// The text of the latest copy the fallback clipboard took (no host clipboard: tests, the web before its host
|
||||
/// sets one); it goes out through egui ([`Self::flush_clipboard_out`]).
|
||||
fallback_copy: Arc<Mutex<Option<String>>>,
|
||||
pub(crate) clipboard_in: Option<vectorcraft_engine::cmd::clipboard::Flavour>,
|
||||
/// The Copy or Cut whose formats go to the system clipboard ([`Self::publish_clipboard`]).
|
||||
clipboard_publishing: sysclip::Publishing,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -461,6 +461,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 =
|
||||
@@ -812,6 +832,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);
|
||||
@@ -946,10 +969,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),
|
||||
@@ -959,11 +986,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
|
||||
@@ -1026,10 +1054,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)
|
||||
}
|
||||
@@ -1141,6 +1174,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> {
|
||||
@@ -1180,6 +1217,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) {
|
||||
|
||||
@@ -756,6 +756,10 @@ pub(crate) enum Live {
|
||||
/// it as one undo step. Falls back to a plain run when no document is open.
|
||||
pub(crate) fn live_run(app: &mut VectorcraftApp, label: &str, cmd: &str, params: Value, phase: Live) {
|
||||
if app.begin_interaction(label).is_ok() {
|
||||
// As the scrub's undo step was, the gesture's previews stay in their document when another becomes active.
|
||||
if let Some(it) = app.session.active_mut().and_then(|st| st.interaction.as_mut()) {
|
||||
it.keep_on_switch = true;
|
||||
}
|
||||
if let Err(e) = app.session.preview(cmd, ¶ms) {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ fn srgba(c: &Color) -> Srgba {
|
||||
|
||||
/// RGB in the active working space, 0 to 255: the panel's RGB rows show and edit the stored components, so a wide
|
||||
/// working space shows its own numbers rather than sRGB's.
|
||||
struct WorkingRgb;
|
||||
pub(crate) struct WorkingRgb;
|
||||
|
||||
impl ColorModel for WorkingRgb {
|
||||
fn id(&self) -> &'static str {
|
||||
|
||||
@@ -520,8 +520,9 @@ fn controls(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<egui::accesski
|
||||
out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The control named `label`: a row's side label carries the same name, in no set order among the nodes.
|
||||
fn named<'a>(nodes: &'a [egui::accesskit::Node], label: &str) -> &'a egui::accesskit::Node {
|
||||
nodes.iter().find(|n| n.label() == Some(label)).unwrap_or_else(|| panic!("no {label:?}"))
|
||||
nodes.iter().find(|n| n.role() != egui::accesskit::Role::Label && n.label() == Some(label)).unwrap_or_else(|| panic!("no {label:?}"))
|
||||
}
|
||||
|
||||
/// A checkbox setting the selected effects hold with different values shows a dash, leaves the
|
||||
|
||||
@@ -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, 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,15 +66,27 @@ 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`]).
|
||||
gesture_boards: Vec<Rect>,
|
||||
/// The selection's box when a field's running gesture began ([`gesture_start`]).
|
||||
gesture_start: Rect,
|
||||
}
|
||||
|
||||
impl Default for TransformUi {
|
||||
fn default() -> Self {
|
||||
TransformUi { reference_point: 4, popover: false, gesture_origin: Value::Null, gesture_boards: Vec::new() }
|
||||
TransformUi {
|
||||
reference_point: 4,
|
||||
popover: false,
|
||||
closed_by_press: false,
|
||||
gesture_origin: Value::Null,
|
||||
gesture_boards: Vec::new(),
|
||||
gesture_start: Rect::ZERO,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,6 +198,15 @@ fn gesture_origin(app: &mut VectorcraftApp) -> Value {
|
||||
app.ui.transform_panel.gesture_origin.clone()
|
||||
}
|
||||
|
||||
/// The box the selection's fields measure from, `now` outside a gesture: while one runs, the box as it began, since
|
||||
/// the fields read the gesture's values against the box before the transform and its previews move the selection's.
|
||||
fn gesture_start(app: &mut VectorcraftApp, now: Rect) -> Rect {
|
||||
if !app.session.in_interaction() {
|
||||
app.ui.transform_panel.gesture_start = now;
|
||||
}
|
||||
app.ui.transform_panel.gesture_start
|
||||
}
|
||||
|
||||
/// Where the registration point of the one selected symbol instance is on the page, while Use
|
||||
/// Registration Point for Symbol is on: the point of the symbol's art box on the 9-point grid,
|
||||
/// placed by the instance's transform.
|
||||
@@ -395,7 +417,7 @@ fn set_object_bounds(app: &mut VectorcraftApp, source: TransformSource, row: &Tr
|
||||
pub(crate) fn object_fields(app: &mut VectorcraftApp, ui: &mut Ui, groups: TransformGroups) {
|
||||
let bx = app.selection_box();
|
||||
let state = bx.as_ref().map(|b| box_state(app, b));
|
||||
let start = bx.map_or(Rect::ZERO, |b| b.rect);
|
||||
let start = gesture_start(app, bx.map_or(Rect::ZERO, |b| b.rect));
|
||||
let out = fields(app, state, start, groups, false).show(ui);
|
||||
apply_fields(app, &out, EditPath::Preview, set_object_bounds);
|
||||
}
|
||||
@@ -405,8 +427,14 @@ pub(crate) fn object_fields(app: &mut VectorcraftApp, ui: &mut Ui, groups: Trans
|
||||
pub(crate) fn object_bar_fields(app: &mut VectorcraftApp, ui: &mut Ui) -> Option<TransformFieldsOutput> {
|
||||
let bx = app.selection_box()?;
|
||||
let state = box_state(app, &bx);
|
||||
let out = fields(app, Some(state), bx.rect, panel_groups(), true).show(ui);
|
||||
let start = gesture_start(app, bx.rect);
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -656,8 +684,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.
|
||||
|
||||
@@ -74,7 +74,7 @@ fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value:
|
||||
let bind = Bind::given(value);
|
||||
let field = match quantity {
|
||||
Quantity::Length => NumberField::length(label, bind, general_lengths(app)),
|
||||
Quantity::Degrees => NumberField::new(label, bind).unit("°").fixed_decimals(1),
|
||||
Quantity::Degrees => NumberField::new(label, bind).unit("°").commit_decimals(1),
|
||||
Quantity::Sides => NumberField::new(label, bind).range(3.0..=1000.0).fixed_decimals(0),
|
||||
};
|
||||
edit = Some(field.show(ui).edit);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -334,13 +334,20 @@ impl VectorcraftApp {
|
||||
/// Copy needs, and `take` keeps it single-shot. A Copy or Cut that labels left to the next pass
|
||||
/// hands its text over as soon as it runs ([`crate::shortcuts::handle`]).
|
||||
pub(crate) fn flush_clipboard_out(&mut self) {
|
||||
let Some(text) = self.clipboard_out.take() else { return };
|
||||
// Something else is being copied: the formats of an earlier Copy not written yet would replace it.
|
||||
self.drop_unwritten_formats();
|
||||
// A fenced or failed write loses the text: nothing else carries it.
|
||||
if let Ok(Written::Written) = self.clipboard.write_text(&text) {
|
||||
// Text copied here is not the art in the internal clipboard: a paste takes it as another app's copy.
|
||||
self.clipboard.forget_ours();
|
||||
if let Some(text) = self.clipboard_out.take() {
|
||||
// Something else is being copied: the formats of an earlier Copy not written yet would replace it.
|
||||
self.drop_unwritten_formats();
|
||||
// A fenced or failed write loses the text: nothing else carries it.
|
||||
if let Ok(Written::Written) = self.clipboard.write_text(&text) {
|
||||
// Text copied here is not the art in the internal clipboard: a paste takes it as another app's copy.
|
||||
self.clipboard.forget_ours();
|
||||
}
|
||||
}
|
||||
// Without a host clipboard, what was copied goes out through egui.
|
||||
if let Some(text) = self.fallback_copy.lock().ok().and_then(|mut slot| slot.take())
|
||||
&& let Some(ctx) = &self.ui_ctx
|
||||
{
|
||||
ctx.copy_text(text);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,10 +8,13 @@ use std::path::PathBuf;
|
||||
pub(crate) struct Folder(PathBuf);
|
||||
|
||||
impl Folder {
|
||||
/// A new empty folder `vectorcraft-<name>-<process id>` in the system temporary folder. One
|
||||
/// left there by an earlier process with the same id is removed first.
|
||||
/// A new empty folder `vectorcraft-<name>-<process id>-<n>` in the system temporary folder,
|
||||
/// `n` counting this process's folders so two tests running at once under one name don't
|
||||
/// remove each other's. One left there by an earlier process with the same id is removed first.
|
||||
pub(crate) fn new(name: &str) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-{name}-{}", std::process::id()));
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-{name}-{}-{n}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
@@ -56,14 +59,25 @@ fn a_folder_is_removed_when_its_test_ends() {
|
||||
|
||||
#[test]
|
||||
fn a_folder_is_removed_when_its_test_panics() {
|
||||
let path = std::env::temp_dir().join(format!("vectorcraft-ui-folder-panics-{}", std::process::id()));
|
||||
let path = std::sync::Mutex::new(PathBuf::new());
|
||||
let r = vectorcraft_testkit::catch_quiet::<()>(|| {
|
||||
let folder = Folder::new("ui-folder-panics");
|
||||
folder.file("a.txt", b"a");
|
||||
*path.lock().unwrap() = folder.to_path_buf();
|
||||
panic!("the test fails");
|
||||
});
|
||||
assert_eq!(r.err().as_deref(), Some("the test fails"));
|
||||
assert!(!path.exists(), "{} is left", path.display());
|
||||
let path = path.into_inner().unwrap();
|
||||
assert!(path.is_absolute() && !path.exists(), "{} is left", path.display());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_folders_under_one_name_are_apart() {
|
||||
let a = Folder::new("ui-folder-twice");
|
||||
let b = Folder::new("ui-folder-twice");
|
||||
a.file("a.txt", b"a");
|
||||
drop(b);
|
||||
assert!(a.join("a.txt").is_file(), "dropping one folder removed the other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -198,6 +198,8 @@ fn save_a_copy_and_save_dont_ask_and_options_reach_the_file() {
|
||||
host(&mut app);
|
||||
// Save of an untitled document goes straight to the file, as before.
|
||||
app.run("file.save", Value::Null).unwrap();
|
||||
// The save panel's answer arrives as a frame's tick takes it.
|
||||
pass(&mut app);
|
||||
assert!(open_dialogs(&app).is_empty());
|
||||
assert_eq!(written.borrow().len(), 1);
|
||||
app.run("file.saveAs", Value::Null).unwrap();
|
||||
|
||||
@@ -99,12 +99,13 @@ fn a_press_on_the_canvas_commits_to_the_object_being_edited() {
|
||||
let app = Rc::new(RefCell::new(app));
|
||||
let shared = app.clone();
|
||||
let mut fixture = Fixture::new(move |ui| window(&mut shared.borrow_mut(), ui));
|
||||
fixture.settle();
|
||||
// The Transform panel's W field is named by its label, "W"; a click on it focuses the field.
|
||||
let label = fixture.by_label("W").expect("the Transform panel shows the W field");
|
||||
// A window as large as the scrub tests', with the docked Transform panel; the fixture's own room is too small for it.
|
||||
fixture.room(egui::vec2(1600.0, 900.0)).settle();
|
||||
// The W field shows the label "W" and is named "Width"; a click on it focuses the field.
|
||||
let label = fixture.by_label("Width").expect("the Transform panel shows the W field");
|
||||
fixture.click(&label).idle(2).key(Key::A, Modifiers::COMMAND).type_text("42").idle(1);
|
||||
// PLAN: assumed the artboard is centred in the window, so the window's centre is on the big rectangle only.
|
||||
let canvas = fixture.ctx().content_rect().center();
|
||||
// A point of the big rectangle away from the small one, where the canvas shows it.
|
||||
let canvas = app.borrow().canvas_view().expect("the canvas is laid out").to_screen(vectorcraft_geom::Point::new(250.0, 200.0));
|
||||
fixture.click_at(canvas).idle(3);
|
||||
|
||||
let app = app.borrow();
|
||||
|
||||
@@ -18,6 +18,9 @@ fn fill_hex(app: &VectorcraftApp) -> String {
|
||||
panels::current_paints(app).0.color().map(|c| c.to_hex()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The Red swatch's name in the swatch popover.
|
||||
const RED: &str = "Red, #ed1c24";
|
||||
|
||||
/// A point of the panel's room that holds no control.
|
||||
fn outside() -> Pos2 {
|
||||
Pos2::new(ROOM.x - 5.0, ROOM.y - 5.0)
|
||||
@@ -37,16 +40,19 @@ fn a_popover_tile_click_sets_the_fill() {
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
app.run("paint.toggleActive", json!({"fill": false})).unwrap();
|
||||
let mut panel = Panel::new(app, chrome::control_bar);
|
||||
// The Control bar ranks its groups out of a panel's width; a window's width shows Fill and Stroke.
|
||||
panel.room(egui::vec2(2200.0, 200.0));
|
||||
panel.click("Fill");
|
||||
assert!(panel.app().session.fill_active, "the Fill chip brings its proxy forward");
|
||||
panel.click("Red");
|
||||
// A colour swatch is named by its name and value.
|
||||
panel.click(RED);
|
||||
assert_eq!(fill_hex(&panel.app()), "#ed1c24");
|
||||
assert_eq!(panel.app().session.doc().unwrap().history.undo.last().unwrap().label, "Fill Color", "through paint.setFill");
|
||||
// The Stroke chip: its proxy comes forward; Shift-click shows the mixer instead of swatches.
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
panel.click_with("Stroke", Modifiers::SHIFT);
|
||||
assert!(!panel.app().session.fill_active);
|
||||
assert!(!panel.shows("Red"), "no swatches in the mixer");
|
||||
assert!(!panel.shows(RED), "no swatches in the mixer");
|
||||
assert!(panel.shows("Recent Colors"), "the Color panel's body");
|
||||
}
|
||||
|
||||
@@ -60,14 +66,14 @@ fn the_properties_panel_has_the_control_bars_fill_and_stroke() {
|
||||
}
|
||||
assert!(panel.rect("Stroke").top() > panel.rect("Fill").bottom(), "Fill above Stroke");
|
||||
panel.click("Fill");
|
||||
panel.click("Red");
|
||||
panel.click(RED);
|
||||
assert_eq!(fill_hex(&panel.app()), "#ed1c24", "the next object's fill");
|
||||
panel.app().run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
assert_eq!(fill_hex(&panel.app()), "#ed1c24", "the new rectangle (selected) has it");
|
||||
// With the rectangle selected: the same chips, under the Transform section.
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
panel.click("Fill");
|
||||
panel.click("Black");
|
||||
panel.click("Black, #000000");
|
||||
assert_eq!(fill_hex(&panel.app()), "#000000");
|
||||
assert_eq!(panel.app().session.doc().unwrap().history.undo.last().unwrap().label, "Fill Color");
|
||||
}
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -939,7 +939,8 @@ fn color_bars_select_edit_and_reorder_the_rows() {
|
||||
assert!(!has(&r, "Color 2"), "no bar for the excluded row");
|
||||
let first = rect(&r, "Color 1");
|
||||
let last = rect(&r, "Color 4");
|
||||
assert!(r.by_label("Color 3").is_some_and(|t| t.rect.top() > first.bottom() && t.rect.bottom() < last.top()), "in row order");
|
||||
// The List's rows touch: a row below another starts where the one above ends.
|
||||
assert!(r.by_label("Color 3").is_some_and(|t| t.rect.top() >= first.bottom() && t.rect.bottom() <= last.top()), "in row order");
|
||||
click(&mut r, last.center());
|
||||
assert_eq!(field(&r, "__sel"), json!([3]), "a click selects the bar's row");
|
||||
let unedited = field(&r, "rows");
|
||||
|
||||
@@ -178,7 +178,9 @@ fn ruler_origin_cancelled_drags_do_not_modify_either_document() {
|
||||
to
|
||||
}
|
||||
Cancel::Focus => {
|
||||
let mut out = ctx.run_ui(egui::RawInput { focused: false, ..Default::default() }, |ui| canvas::show(&mut app, ui));
|
||||
// As the host reports it: the window unfocused, and the event that says so.
|
||||
let lost = egui::RawInput { focused: false, events: vec![Event::WindowFocused(false)], ..Default::default() };
|
||||
let mut out = ctx.run_ui(lost, |ui| canvas::show(&mut app, ui));
|
||||
out.textures_delta.clear();
|
||||
to
|
||||
}
|
||||
|
||||
@@ -187,3 +187,24 @@ fn a_scrub_closes_its_group_in_its_own_document_after_a_switch() {
|
||||
assert_eq!(second.history.undo.len(), undo + 1, "one undo step for the drag");
|
||||
assert!(app.session.documents()[0].undo_group.is_some(), "the active document's group stays open");
|
||||
}
|
||||
|
||||
/// With the Artboard tool, a scrub of the W label resizes the active artboard live, runs to its release as one undo
|
||||
/// step, and Escape takes it back without a step.
|
||||
#[test]
|
||||
fn scrubbing_an_artboards_w_is_one_undo_step() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.select_tool("artboard");
|
||||
let ctx = crate::testing::ui_context();
|
||||
let board = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards[0].rect.width();
|
||||
let undo = undo_len(&app);
|
||||
drag_w(&mut app, &ctx, 40.0, false);
|
||||
assert!(board(&app) > 400.0, "the release keeps the scrub: {}", board(&app));
|
||||
assert_eq!(undo_len(&app), undo + 1, "one undo step for the drag");
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert!((board(&app) - 400.0).abs() < 1e-6);
|
||||
|
||||
drag_w(&mut app, &ctx, 40.0, true);
|
||||
assert!((board(&app) - 400.0).abs() < 1e-6, "Escape: {}", board(&app));
|
||||
assert_eq!(undo_len(&app), undo, "no step");
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@ use crate::{Services, VectorcraftApp, background};
|
||||
#[derive(Default)]
|
||||
pub(super) struct Board {
|
||||
flavours: Vec<Flavour>,
|
||||
/// The app wrote what the clipboard holds (the platform's owner marker): nothing was copied since.
|
||||
ours: bool,
|
||||
/// How many times the app wrote it.
|
||||
writes: usize,
|
||||
/// Another app has the clipboard open: the app's writes fail and change nothing, and reads
|
||||
@@ -79,13 +81,14 @@ impl ClipboardBackend for Fake {
|
||||
if b.race_with_our_formats {
|
||||
b.flavours.extend(ours.into_iter().filter(|f| f.mime != TEXT));
|
||||
}
|
||||
b.ours = false;
|
||||
return Err(ClipboardError::Other("another app has the clipboard open".into()));
|
||||
}
|
||||
if b.partial {
|
||||
b.flavours = if b.partial_keeps_others { ours.into_iter().filter(|f| f.mime != TEXT).collect() } else { vec![] };
|
||||
return Err(ClipboardError::Other("a format could not be written".into()));
|
||||
}
|
||||
*b = Board { flavours: ours, writes: b.writes + 1, ..std::mem::take(&mut *b) };
|
||||
*b = Board { flavours: ours, ours: true, writes: b.writes + 1, ..std::mem::take(&mut *b) };
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
@@ -109,6 +112,10 @@ impl ClipboardBackend for Fake {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn owns(&mut self) -> Option<bool> {
|
||||
Some(self.board().ours)
|
||||
}
|
||||
|
||||
fn has(&mut self, mimes: &[&str]) -> bool {
|
||||
if self.board().text_only_has {
|
||||
return mimes.contains(&TEXT) && self.find(&[TEXT]).is_some();
|
||||
@@ -145,7 +152,7 @@ pub(super) fn app() -> (VectorcraftApp, Arc<Mutex<Board>>) {
|
||||
pub(super) fn copy_elsewhere(board: &Arc<Mutex<Board>>, flavours: Vec<(&'static str, Vec<u8>)>) {
|
||||
let flavours = flavours.into_iter().map(|(mime, data)| Flavour { mime, data }).collect();
|
||||
let mut b = board.lock().unwrap();
|
||||
*b = Board { flavours, ..std::mem::take(&mut *b) };
|
||||
*b = Board { flavours, ours: false, ..std::mem::take(&mut *b) };
|
||||
}
|
||||
|
||||
/// Another app opens the clipboard (`true`) or closes it.
|
||||
@@ -332,18 +339,20 @@ fn app_with_worker() -> (VectorcraftApp, Arc<Mutex<Board>>) {
|
||||
}
|
||||
|
||||
/// [`app_with_worker`], its worker busy with a job labeled `label` (none: another Copy's formats)
|
||||
/// until the sender is dropped, or for 10 s.
|
||||
/// until the sender is dropped.
|
||||
pub(super) fn app_with_busy_worker(label: &str) -> (VectorcraftApp, Arc<Mutex<Board>>, Sender<()>) {
|
||||
let (mut app, board) = app_with_worker();
|
||||
let hold = hold_worker(&mut app, label);
|
||||
(app, board, hold)
|
||||
}
|
||||
|
||||
/// Start a job labeled `label` that holds the worker until the sender is dropped, or for 10 s.
|
||||
/// Start a job labeled `label` that holds the worker until the sender is dropped (also when the
|
||||
/// test panics). No time limit: a test slowed past one by a loaded machine would see the held
|
||||
/// work run early.
|
||||
fn hold_worker(app: &mut VectorcraftApp, label: &str) -> Sender<()> {
|
||||
let (hold, held) = channel::<()>();
|
||||
let work = move |_: background::Writer| {
|
||||
let _ = held.recv_timeout(std::time::Duration::from_secs(10));
|
||||
let _ = held.recv();
|
||||
Ok(Value::Null)
|
||||
};
|
||||
background::run(app, true, label.into(), None, work, |_, r| r).unwrap();
|
||||
|
||||
@@ -130,7 +130,9 @@ impl Rig {
|
||||
|
||||
fn enter_value(&mut self, at: Pos2, value: &str) {
|
||||
self.fx.click_at(at);
|
||||
// The click selected the whole field, so the text typed replaces it.
|
||||
// A click on a field that already has the keyboard (a popover gives its first field the keyboard as it
|
||||
// opens) places the caret: the whole field is selected, so the text typed replaces it.
|
||||
self.fx.key(Key::A, Modifiers::COMMAND);
|
||||
self.fx.type_text(value);
|
||||
self.fx.key(Key::Enter, Modifiers::NONE);
|
||||
self.settle();
|
||||
|
||||
@@ -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;
|
||||
@@ -733,18 +733,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)
|
||||
{
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
|
||||
@@ -348,8 +348,8 @@ impl Component for TypeEditor<'_> {
|
||||
}
|
||||
|
||||
/// Shows the editor part over the Type tool's caret while the tool edits text, before the tool host. A new edit target
|
||||
/// is a new IME owner, so a reloaded document interrupts its composition.
|
||||
pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
|
||||
/// is a new IME owner, so a reloaded document interrupts its composition. `canvas` is the document canvas's id.
|
||||
pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, canvas: egui::Id) {
|
||||
if !app.session.tool_wants_text() || app.viewport_hidden(ui.ctx()) {
|
||||
return;
|
||||
}
|
||||
@@ -359,8 +359,9 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
|
||||
let Some(canvas_view) = app.canvas_view() else { return };
|
||||
let caret = Rect::from_two_pos(canvas_view.to_screen(a), canvas_view.to_screen(b)).expand2(egui::vec2(1.0, 0.0));
|
||||
let out = ui.scope_builder(egui::UiBuilder::new().max_rect(caret), |ui| TypeEditor::new(app, caret).id_salt(target).show(ui)).inner;
|
||||
// Typing goes to the edit that starts, as a click on the part would take the keys.
|
||||
if out.unfocused_start {
|
||||
// Typing goes to the edit that starts, as a click on the part would take the keys. The press that started it
|
||||
// focuses the canvas as its pass ends, so the editor takes the keys back from its canvas in the next pass.
|
||||
if out.unfocused_start || focus::has(ui.ctx(), canvas) {
|
||||
focus::request(ui.ctx(), FocusTarget::Id(out.response.id));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user