Merge main into perf/layer-highlight-set

This commit is contained in:
dotCooCoo committed 2026-11-18 07:39:22 -08:00
commit bf2ca2cf80
680 files changed
+65906 -4204

No files matched your search

+2
View File
@@ -16,6 +16,7 @@ pub mod polygonal_lasso;
pub mod select;
pub mod shapes;
pub mod typetools;
pub mod units;
use crate::menus::Item;
@@ -38,6 +39,7 @@ pub fn plugin_menu() -> Vec<Item> {
Item::Sub("Selection Tools", select::menu()),
Item::Sub("Smart Pen", pen::menu()),
Item::Sub("Type Tools", typetools::menu()),
Item::Sub("Unit Converter", units::menu()),
Item::Sep,
]
}
+13 -1
View File
@@ -4,7 +4,8 @@
//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that
//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu
//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each
//! with a Select button; each document's list is kept until that document changes.
//! with a Select button; each document's list is kept until that document changes. Its Fold Preview
//! button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`], `ui.foldPreview`).
use std::collections::HashMap;
use std::sync::{Arc, Weak};
@@ -26,6 +27,8 @@ pub const SET_ROLE: &str = "addon.packaging.setRole";
pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
/// The command that checks the fold lines.
pub const CHECK: &str = "addon.packaging.check";
/// The command that shows the Fold Preview window.
pub const PREVIEW: &str = "ui.foldPreview";
/// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them.
pub const ROLES: &[(&str, &str)] =
&[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")];
@@ -47,6 +50,8 @@ pub fn menu() -> Vec<Item> {
make("Make Perforation Line", "perforation"),
Item::Sep,
Item::Cmd("Check Fold Lines", CHECK, Value::Null),
Item::Sep,
Item::Cmd("Fold Preview", PREVIEW, json!({})),
]
}
@@ -160,6 +165,11 @@ fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) {
if widgets::flat_button(ui, tl!("Check"), width).clicked() {
run_check(app, ui.ctx(), json!({}));
}
if widgets::flat_button(ui, tl!("Fold Preview"), width).clicked()
&& let Err(e) = app.run(PREVIEW, json!({}))
{
app.status(e);
}
let Some(checked) = last_check(app, ui.ctx()) else { return };
ui.add_space(4.0);
dim_label(ui, &crate::i18n::msg(&checked.summary()));
@@ -285,5 +295,7 @@ pub fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
pub mod preview;
#[cfg(test)]
mod tests;
@@ -0,0 +1,705 @@
//! The Fold Preview window: the document's blank folded into its 3D shape
//! ([`vectorcraft_three_d::fold::fold`]), with the printed art on the outside of each panel and the
//! board's inside color on the back, drawn by [`vectorcraft_three_d::fold::raster::render`].
//!
//! The window folds the blank that the document's shown fold lines make, about its largest panel
//! or the panel the user double-clicked. Its print is a raster of the document with the fold lines
//! and the layers that do not print left out ([`vectorcraft_engine::cmd::print_hidden`]), rendered
//! once per document revision, off the UI thread on native builds ([`crate::thumb_worker`]), and
//! sampled through each panel's projective map when the fold, the view or the print changes. Dragging turns the view, a Shift-drag
//! keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a
//! panel makes it the base, and the arrow keys turn the view by 5° when it has the keyboard focus.
//! The settings live in `UiState::fold_preview` (`ui.inspect`); `ui.foldPreview` sets them.
use std::sync::Arc;
use egui::{Color32, Rect, Sense, Ui, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_geom::{Point, Rect as DRect};
use vectorcraft_three_d::fold::raster::{self, Camera, Image, MAX_PIXELS, MAX_SIDE, Print};
use vectorcraft_three_d::fold::{Blank, Folded, fold, pick};
use crate::VectorcraftApp;
use crate::thumb_worker::{Settle, ThumbWorker};
use crate::widgets::{self, dim_label};
/// The window's id (`window.panel {panel: "foldPreview"}`).
pub const ID: &str = "foldPreview";
/// The view presets: label, id, the turn about x (the top toward the viewer) and about y (the
/// right side toward the viewer), in degrees.
pub const VIEWS: [(&str, &str, f64, f64); 7] = [
("Front", "front", 0.0, 0.0),
("Back", "back", 0.0, 180.0),
("Left", "left", 0.0, -90.0),
("Right", "right", 0.0, 90.0),
("Top", "top", 90.0, 0.0),
("Bottom", "bottom", -90.0, 0.0),
("Three-Quarter", "threeQuarter", 25.0, 35.0),
];
/// The tolerance the window folds with (points), as Check Fold Lines' default.
const TOLERANCE: f64 = 0.1;
/// The share of the view's shorter side the folded blank fills at a zoom of 1.
const FIT: f64 = 0.45;
/// The print raster's longest side, in pixels, and the fewest pixels it gives a point.
const PRINT_SIDE: f64 = 2048.0;
/// Degrees the view turns for each point dragged, and for each arrow key press.
const DRAG_TURN: f64 = 0.5;
const KEY_TURN: f64 = 5.0;
/// The window's settings (kept with the UI state).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Settings {
/// How far the blank is folded: 0 flat, 1 every hinge at its angle.
pub amount: f64,
/// The view's turn, in degrees (see [`VIEWS`]).
pub rotate_x: f64,
pub rotate_y: f64,
/// The zoom: 1 fits the folded blank in the view.
pub zoom: f64,
/// How far the view is moved, in points.
pub pan: [f64; 2],
/// The field of view in degrees; 0 for none.
pub perspective: f64,
/// The board's inside color: `#rrggbb`, the name of a swatch, or empty for white.
pub inside: String,
/// Draw the fold lines on the print.
pub show_fold_lines: bool,
/// The base panel: the one under this point (document coordinates); the largest when `None`.
pub base: Option<[f64; 2]>,
}
impl Default for Settings {
fn default() -> Self {
let (_, _, rotate_x, rotate_y) = VIEWS[6];
Self {
amount: 1.0,
rotate_x,
rotate_y,
zoom: 1.0,
pan: [0.0; 2],
perspective: 0.0,
inside: String::new(),
show_fold_lines: false,
base: None,
}
}
}
impl Settings {
/// The view preset these settings show, if any.
fn view(&self) -> Option<&'static (&'static str, &'static str, f64, f64)> {
VIEWS.iter().find(|v| (v.2 - self.rotate_x).abs() < 1e-9 && (v.3 - self.rotate_y).abs() < 1e-9)
}
/// These settings with every value in the range `ui.foldPreview` allows: saved UI state is read
/// as it was stored. A value that is not a number takes its default.
fn clamped(mut self) -> Self {
let within = |v: f64, lo: f64, hi: f64, or: f64| if v.is_finite() { v.clamp(lo, hi) } else { or };
let turn = |v: f64| if (-180.0..=180.0).contains(&v) { v } else { wrapped(v) };
let fresh = Settings::default();
self.amount = within(self.amount, 0.0, 1.0, fresh.amount);
self.zoom = within(self.zoom, 0.1, 8.0, fresh.zoom);
self.perspective = within(self.perspective, 0.0, 160.0, fresh.perspective);
(self.rotate_x, self.rotate_y) = (turn(self.rotate_x), turn(self.rotate_y));
self.pan = self.pan.map(|v| if v.is_finite() { v } else { 0.0 });
self.base = self.base.filter(|b| b.iter().all(|v| v.is_finite()));
self
}
}
/// `angle` (degrees) brought into -180 to 180.
fn wrapped(angle: f64) -> f64 {
let a = (angle + 180.0).rem_euclid(360.0) - 180.0;
if a.is_finite() { a } else { 0.0 }
}
/// What the print raster shows: the document, its revision, whether the fold lines are drawn, and
/// the region and size.
#[derive(Clone, Copy, Debug, PartialEq)]
struct PrintKey {
uid: u64,
revision: u64,
fold_lines: bool,
region: [u64; 4],
width: u32,
height: u32,
}
/// The last frame drawn: its size in pixels and how long the fold and the drawing took (ms).
#[derive(Clone, Copy, Debug, Default)]
struct Frame {
width: u32,
height: u32,
fold_ms: f64,
draw_ms: f64,
}
/// A document's blanks and whether its fold lines have an error, by (uid, revision).
type Blanks = ((u64, u64), Arc<Vec<Blank>>, bool);
/// What a fold folds: the document (uid, revision), the blank, the base panel and the amount's bits.
type FoldKey = (u64, u64, usize, usize, u64);
/// What the last image shows: the fold, the camera, the inside color and the print.
#[derive(Clone, Copy, Debug, PartialEq)]
struct DrawKey {
fold: FoldKey,
camera: Camera,
inside: [u8; 4],
print: Option<PrintKey>,
}
#[derive(Default)]
struct Cache {
blanks: Option<Blanks>,
/// The last fold, what it folds and how long it took (ms).
folded: Option<(FoldKey, Arc<Folded>, f64)>,
/// What the texture shows.
drawn: Option<DrawKey>,
/// Folds worked out and images rendered (tests count them).
folds: u64,
renders: u64,
/// The print shown and what it shows.
print: Option<(PrintKey, Arc<Print>)>,
/// Renders the print off the UI thread (None: on this thread).
worker: Option<ThumbWorker<(), PrintKey>>,
worker_started: bool,
pending: Option<PrintKey>,
settle: Settle,
tex: Option<egui::TextureHandle>,
/// The last frame's image, for double-click picking, and the screen rect it filled.
image: Option<(Image, Rect)>,
frame: Option<Frame>,
/// Prints rendered (tests count them).
prints: u64,
}
thread_local! {
static CACHE: crate::graphics::TexCache<Cache> = crate::graphics::TexCache::default();
static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new());
}
/// The board's inside color (straight RGBA) for `inside`: white when it is empty, a swatch of `d`
/// with a plain color, or else `#rrggbb`; `None` for anything else.
fn inside_color(d: &vectorcraft_engine::doc::Document, inside: &str) -> Option<[u8; 4]> {
if inside.is_empty() {
return Some([255; 4]);
}
match d.swatch(inside).map(|s| &s.paint) {
Some(vectorcraft_color::Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)),
_ if inside.starts_with('#') => vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)),
_ => None,
}
}
/// The document rect a print of `blank` covers: its panels' bounds, with a point to spare.
fn print_region(blank: &Blank) -> Option<DRect> {
let r = blank.panels.iter().filter_map(|p| p.outline.bounds()).reduce(|a, b| a.union(b))?;
let r = r.inflate(1.0, 1.0);
(r.width() > 0.0 && r.height() > 0.0 && r.is_finite()).then_some(r)
}
/// The pixel size of the print of `region`: its longest side [`PRINT_SIDE`].
fn print_size(region: DRect) -> (u32, u32, f64) {
let scale = PRINT_SIDE / region.width().max(region.height());
let side = |len: f64| ((len * scale).ceil() as u32).clamp(1, MAX_SIDE);
(side(region.width()), side(region.height()), scale)
}
impl Cache {
/// The blanks of document `uid` at `revision`, worked out again only when it changed.
fn blanks(&mut self, uid: u64, revision: u64, d: &vectorcraft_engine::doc::Document) -> (Arc<Vec<Blank>>, bool) {
if let Some((key, blanks, errors)) = &self.blanks
&& *key == (uid, revision)
{
return (blanks.clone(), *errors);
}
let (blanks, issues) = vectorcraft_engine::cmd::fold_source(d);
let errors = issues.iter().any(|i| i.code.is_error());
let blanks = Arc::new(blanks);
self.blanks = Some(((uid, revision), blanks.clone(), errors));
(blanks, errors)
}
/// `blank` folded about `panel` by `amount` (what `key` names), worked out again only when the
/// key changed, and how long that took (ms).
fn fold(&mut self, key: FoldKey, blank: &Blank, panel: usize, amount: f64) -> Option<(Arc<Folded>, f64)> {
if let Some((k, f, ms)) = &self.folded
&& *k == key
{
return Some((f.clone(), *ms));
}
let t0 = crate::now_ms();
let f = Arc::new(fold(blank, Some(panel), amount, TOLERANCE)?);
let ms = crate::now_ms() - t0;
self.folded = Some((key, f.clone(), ms));
self.folds += 1;
Some((f, ms))
}
/// Bring the print up to `key`: on the worker when there is one, else here, and not before the
/// document has settled unless there is no print of it yet.
fn update_print(&mut self, ctx: &egui::Context, doc: &Arc<vectorcraft_engine::doc::Document>, key: PrintKey, region: DRect, scale: f64) {
if !self.worker_started {
self.worker_started = true;
self.worker = ThumbWorker::spawn(ctx, "fold-preview");
}
let done = match self.worker.as_ref().map(ThumbWorker::poll) {
Some(Some(done)) => done,
Some(None) => {
(self.worker, self.pending) = (None, None);
vec![]
}
None => vec![],
};
for d in done {
if self.pending == Some(d.key) {
self.pending = None;
}
if let Some(img) = d.img {
self.keep_print(d.key, img);
}
}
let shown = self.print.as_ref().map(|(k, _)| *k);
if shown == Some(key) || self.pending == Some(key) {
return;
}
let have = shown.is_some_and(|k| k.uid == key.uid);
if have && !self.settle.settled(ctx, key.uid, key.revision, ctx.input(|i| i.time)) {
return;
}
let opts = vectorcraft_render::RenderOptions {
skip_templates: true,
image_mips: true,
hidden: vectorcraft_engine::cmd::print_hidden(doc, key.fold_lines),
..Default::default()
};
if let Some(w) = &self.worker {
let (doc, opts) = (doc.clone(), opts.clone());
if w.submit((), key, Box::new(move |r| Some(r.render_region_with(&doc, region, scale, &opts)))) {
self.pending = Some(key);
return;
}
self.worker = None;
}
let img = RENDERER.with(|r| r.borrow_mut().render_region_with(doc, region, scale, &opts));
self.keep_print(key, img);
}
/// The print to draw for `want`: the one shown when it is of the same document, blank region and
/// Show Fold Lines setting (an older revision while the new one renders), else none.
fn print_for(&self, want: &PrintKey) -> Option<(PrintKey, Arc<Print>)> {
let same = |k: &PrintKey| (k.uid, k.fold_lines, k.region) == (want.uid, want.fold_lines, want.region);
self.print.as_ref().filter(|(k, _)| same(k)).map(|(k, p)| (*k, p.clone()))
}
fn keep_print(&mut self, key: PrintKey, img: vectorcraft_render::Rendered) {
let region =
DRect::new(f64::from_bits(key.region[0]), f64::from_bits(key.region[1]), f64::from_bits(key.region[2]), f64::from_bits(key.region[3]));
if let Some(print) = Print::new(region, img.width, img.height, img.pixels) {
self.print = Some((key, Arc::new(print)));
self.prints += 1;
}
}
}
/// `ui.foldPreview {amount?, view?, rotateX?, rotateY?, zoom?, perspective?, inside?,
/// showFoldLines?, base?}`: set the window's settings, show it, and answer with them and the last
/// frame's size and times. A value of the wrong kind or out of range is an error, and nothing is
/// set.
pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let mut set = app.ui.fold_preview.clone();
let number = |key: &str, lo: f64, hi: f64| -> Result<Option<f64>, String> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => match v.as_f64() {
Some(n) if (lo..=hi).contains(&n) => Ok(Some(n)),
_ => Err(format!("`{key}` must be a number from {lo} to {hi}")),
},
}
};
if let Some(a) = number("amount", 0.0, 1.0)? {
set.amount = a;
}
match p.get("view") {
None | Some(Value::Null) => {}
Some(v) => {
let (_, _, x, y) = v
.as_str()
.and_then(|v| VIEWS.iter().find(|view| view.1 == v))
.ok_or_else(|| format!("`view` must be one of {}", VIEWS.iter().map(|v| v.1).collect::<Vec<_>>().join(", ")))?;
(set.rotate_x, set.rotate_y) = (*x, *y);
}
}
if let Some(x) = number("rotateX", -180.0, 180.0)? {
set.rotate_x = x;
}
if let Some(y) = number("rotateY", -180.0, 180.0)? {
set.rotate_y = y;
}
if let Some(z) = number("zoom", 0.1, 8.0)? {
set.zoom = z;
}
if let Some(v) = number("perspective", 0.0, 160.0)? {
set.perspective = v;
}
match p.get("inside") {
None | Some(Value::Null) => {}
Some(v) => {
let inside = v.as_str().filter(|inside| {
inside.is_empty()
|| app.session.active().and_then(|st| inside_color(&st.doc, inside)).is_some()
|| (inside.starts_with('#') && vectorcraft_color::Color::from_hex(inside).is_some())
});
let Some(inside) = inside else {
return Err(format!("`inside` must be #rrggbb, the name of a swatch with a plain color, or empty for white, not {v}"));
};
set.inside = inside.to_string();
}
}
match p.get("showFoldLines") {
None | Some(Value::Null) => {}
Some(v) => set.show_fold_lines = v.as_bool().ok_or("`showFoldLines` must be true or false")?,
}
match p.get("base") {
None => {}
Some(Value::Null) => set.base = None,
Some(v) => {
let a = v.as_array().filter(|a| a.len() == 2);
let xy: Option<Vec<f64>> = a.map(|a| a.iter().filter_map(Value::as_f64).filter(|n| n.is_finite()).collect());
let Some(&[x, y]) = xy.as_deref() else { return Err("`base` must be a point: [x, y], or null".into()) };
let blanks = app.session.active().map(|st| vectorcraft_engine::cmd::fold_source(&st.doc).0).unwrap_or_default();
if pick(&blanks, Some(Point::new(x, y))).is_none() {
return Err("`base` is in no panel".into());
}
set.base = Some([x, y]);
}
}
if p.get("view").is_some_and(|v| !v.is_null()) || p.get("zoom").is_some_and(|v| !v.is_null()) {
set.pan = [0.0; 2];
}
app.ui.fold_preview = set;
crate::panel_docking::reveal_panel(app, ID)?;
if let Some(ctx) = &app.ui_ctx {
ctx.request_repaint();
}
Ok(state(app))
}
/// The window's settings and the last frame's size and times.
fn state(app: &VectorcraftApp) -> Value {
let frame = CACHE.with(|c| c.borrow().frame);
let mut out = serde_json::to_value(&app.ui.fold_preview).unwrap_or_default();
if let Some(o) = out.as_object_mut() {
o.insert(
"frame".into(),
frame.map_or(Value::Null, |f| json!({"width": f.width, "height": f.height, "foldMs": f.fold_ms, "drawMs": f.draw_ms})),
);
}
out
}
/// The toolbar: the view presets, Perspective, Inside, Show Fold Lines and Reset.
fn toolbar(app: &VectorcraftApp, ui: &mut Ui, set: &mut Settings) {
ui.horizontal_wrapped(|ui| {
let labels: Vec<&str> = VIEWS.iter().map(|v| v.0).collect();
let current = set.view().map_or("", |v| v.0);
if let Some(i) = widgets::dropdown_named(ui, "fold-preview-view", Some(tl!("View")), current, &labels, 120.0)
&& let Some(&(_, _, x, y)) = VIEWS.get(i)
{
(set.rotate_x, set.rotate_y, set.pan) = (x, y, [0.0; 2]);
}
let swatches: Vec<String> = app.session.active().map_or_else(Vec::new, |st| {
st.doc.swatches.iter().filter(|s| matches!(s.paint, vectorcraft_color::Paint::Solid { .. })).map(|s| s.name.clone()).collect()
});
let mut names: Vec<&str> = vec![tl!("White")];
names.extend(swatches.iter().map(String::as_str));
let shown = if set.inside.is_empty() { tl!("White") } else { set.inside.as_str() };
ui.label(tl!("Inside"));
if let Some(i) = widgets::dropdown_names_named(ui, "fold-preview-inside", Some(tl!("Inside")), shown, &names, 110.0) {
set.inside = swatches.get(i.wrapping_sub(1)).cloned().unwrap_or_default();
}
if widgets::check(ui, tl!("Show Fold Lines"), set.show_fold_lines, true) {
set.show_fold_lines = !set.show_fold_lines;
}
if widgets::flat_button_fit(ui, tl!("Reset"), 48.0).clicked() {
let fresh = Settings::default();
(set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective) = (fresh.rotate_x, fresh.rotate_y, 1.0, [0.0; 2], 0.0);
}
});
ui.horizontal(|ui| {
ui.label(tl!("Perspective"));
widgets::slider(ui, egui::Slider::new(&mut set.perspective, 0.0..=160.0).suffix("°").fixed_decimals(0));
});
}
/// The Fold and Zoom sliders.
fn sliders(ui: &mut Ui, set: &mut Settings) {
ui.horizontal(|ui| {
ui.label(tl!("Fold"));
let mut percent = set.amount * 100.0;
if widgets::slider(ui, egui::Slider::new(&mut percent, 0.0..=100.0).suffix("%").fixed_decimals(0)).changed() {
set.amount = (percent / 100.0).clamp(0.0, 1.0);
}
});
ui.horizontal(|ui| {
ui.label(tl!("Zoom"));
let mut percent = set.zoom * 100.0;
if widgets::slider(ui, egui::Slider::new(&mut percent, 10.0..=800.0).suffix("%").fixed_decimals(0).logarithmic(true)).changed() {
set.zoom = (percent / 100.0).clamp(0.1, 8.0);
}
});
}
/// Turns, moves and zooms the view with the pointer, the wheel and the arrow keys, and picks the
/// base panel of `blank` (the blank `key` folds) on a double-click.
fn interact(ui: &Ui, response: &egui::Response, set: &mut Settings, blank: Option<(&Blank, FoldKey)>) {
if response.clicked() || response.drag_started() {
response.request_focus();
}
let (shift, space) = ui.input(|i| (i.modifiers.shift, i.key_down(egui::Key::Space)));
let delta = response.drag_delta();
if delta != egui::Vec2::ZERO {
if response.dragged_by(egui::PointerButton::Middle) || (space && response.dragged_by(egui::PointerButton::Primary)) {
set.pan[0] += f64::from(delta.x);
set.pan[1] += f64::from(delta.y);
} else if response.dragged_by(egui::PointerButton::Primary) {
let (mut dx, mut dy) = (f64::from(delta.x), f64::from(delta.y));
if shift {
if dx.abs() >= dy.abs() {
dy = 0.0;
} else {
dx = 0.0;
}
}
set.rotate_y = wrapped(set.rotate_y + dx * DRAG_TURN);
set.rotate_x = wrapped(set.rotate_x + dy * DRAG_TURN);
}
}
if response.hovered() {
let scroll = f64::from(ui.input(|i| i.smooth_scroll_delta.y + (i.zoom_delta() - 1.0) * 200.0));
if scroll != 0.0 {
set.zoom = (set.zoom * (scroll * 0.002).exp()).clamp(0.1, 8.0);
}
}
if response.has_focus() {
// The view keeps the arrow keys, so they turn it rather than move the focus on.
ui.memory_mut(|m| {
m.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() })
});
let presses = |key| ui.input_mut(|i| i.count_and_consume_key(egui::Modifiers::NONE, key)) as f64 * KEY_TURN;
let (left, right, up, down) =
(presses(egui::Key::ArrowLeft), presses(egui::Key::ArrowRight), presses(egui::Key::ArrowUp), presses(egui::Key::ArrowDown));
if left + right + up + down > 0.0 {
set.rotate_y = wrapped(set.rotate_y + right - left);
set.rotate_x = wrapped(set.rotate_x + down - up);
}
}
if response.double_clicked()
&& let Some(pos) = response.interact_pointer_pos()
&& let Some((blank, key)) = blank
{
// The image on screen is the last one drawn; its panel numbers are used only while it shows
// the same blank of the same document revision.
let picked = CACHE.with(|c| {
let c = c.borrow();
let shown = c.drawn.map(|d| (d.fold.0, d.fold.1, d.fold.2));
if shown != Some((key.0, key.1, key.2)) {
return None;
}
let (img, rect) = c.image.as_ref()?;
let x = (pos.x - rect.left()) / rect.width() * img.width as f32;
let y = (pos.y - rect.top()) / rect.height() * img.height as f32;
img.panel_at(x.max(0.0) as u32, y.max(0.0) as u32)
});
if let Some(p) = picked.and_then(|i| blank.panels.get(i)).and_then(|p| p.point_inside()) {
set.base = Some([p.x, p.y]);
}
}
}
/// The status line under the view, in English (shown translated).
fn status(blanks: usize, folded: Option<(&Blank, &Folded)>, errors: bool) -> Vec<String> {
let Some((blank, f)) = folded else {
return vec!["Check the fold lines first.".into()];
};
let mut out = vec![crate::i18n::fmt(
"Panels: {panels}, hinges: {hinges}",
&[("panels", &blank.panels.len().to_string()), ("hinges", &blank.hinges.len().to_string())],
)];
if errors {
out.push("Check the fold lines first.".into());
}
if blanks > 1 {
out.push(crate::i18n::fmt("Other blanks not shown: {count}", &[("count", &(blanks - 1).to_string())]));
}
if let Some(gap) = f.hinges.iter().filter(|h| !h.closes).map(|h| h.gap).reduce(f64::max) {
out.push(crate::i18n::fmt("A joint does not close by {gap} pt.", &[("gap", &format!("{gap:.1}"))]));
}
if !f.collisions.is_empty() {
out.push("Two panels pass through each other.".into());
}
out
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some(st) = app.session.active() else {
crate::panels::empty_state(ui, "box", tl!("No document"), tl!("Open a document to preview its folded shape."));
return;
};
let (uid, revision, doc) = (st.uid, st.revision, st.doc.clone());
let mut set = app.ui.fold_preview.clone().clamped();
toolbar(app, ui, &mut set);
let (blanks, errors) = CACHE.with(|c| c.borrow_mut().blanks(uid, revision, &doc));
let base_point = set.base.map(|[x, y]| Point::new(x, y));
let picked = pick(&blanks, base_point).or_else(|| pick(&blanks, None));
let folded = picked.and_then(|(b, panel)| {
let blank = blanks.get(b)?;
let key = (uid, revision, b, panel, set.amount.to_bits());
let (f, ms) = CACHE.with(|c| c.borrow_mut().fold(key, blank, panel, set.amount))?;
Some((blank, f, key, ms))
});
let bottom = ui.spacing().interact_size.y * 3.0 + 12.0;
let size = vec2(ui.available_width().max(64.0), (ui.available_height() - bottom).max(64.0));
let (rect, response) = ui.allocate_exact_size(size, Sense::click_and_drag());
let view_name = set.view().map_or("", |v| v.0);
response.widget_info(|| {
let mut info = egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Fold Preview"));
info.current_text_value = Some(crate::i18n::t(view_name).to_string());
info
});
interact(ui, &response, &mut set, folded.as_ref().map(|(b, _, key, _)| (*b, *key)));
let t = crate::theme::Tokens::get(ui.ctx());
ui.painter().rect_filled(rect, 2.0, t.pasteboard);
if let Some((blank, f, key, fold_ms)) = &folded {
draw(ui, rect, &doc, *key, blank, f, &set, *fold_ms);
}
if response.has_focus() {
ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside);
}
for line in status(blanks.len(), folded.as_ref().map(|(b, f, ..)| (*b, &**f)), errors) {
dim_label(ui, &crate::i18n::msg(&line));
}
sliders(ui, &mut set);
if set != app.ui.fold_preview {
app.ui.fold_preview = set;
}
}
/// Draws `blank` folded as `f` (the fold `key` names) into `rect`, with the print of `doc`. The image
/// is rendered again only when the fold, the view, the inside color or the print changed.
#[allow(clippy::too_many_arguments)]
fn draw(ui: &Ui, rect: Rect, doc: &Arc<vectorcraft_engine::doc::Document>, key: FoldKey, blank: &Blank, f: &Folded, set: &Settings, fold_ms: f64) {
// Pixels per point of the view, lowered when the window has more pixels than the view may have
// in all or along either side, so the image keeps the window's proportions.
let (w, h) = (f64::from(rect.width()), f64::from(rect.height()));
let mut ppp = f64::from(ui.ctx().pixels_per_point());
let area = w * h * ppp * ppp;
if area > f64::from(MAX_PIXELS) {
ppp *= (f64::from(MAX_PIXELS) / area).sqrt();
}
ppp = ppp.min(f64::from(MAX_SIDE) / w.max(h).max(1.0));
let width = ((w * ppp).floor() as u32).clamp(1, MAX_SIDE);
let height = ((h * ppp).floor() as u32).clamp(1, MAX_SIDE);
let Some((lo, hi)) = raster::bounds(blank, f) else { return };
let center = [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0, (lo[2] + hi[2]) / 2.0];
let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() / 2.0;
let mut fit = FIT * f64::from(width.min(height)) / radius.max(1e-6);
if set.perspective > 0.0 {
// The eye at two radii from the middle or farther, so at a zoom of 1 the whole blank is in
// front of it.
let focal = f64::from(width.min(height)) / 2.0 / (set.perspective.to_radians() / 2.0).tan();
fit = fit.min(focal / (2.0 * radius.max(1e-6)));
}
let camera = Camera {
width,
height,
rotate_x: set.rotate_x,
rotate_y: set.rotate_y,
scale: fit * set.zoom,
pan: [set.pan[0] * ppp, set.pan[1] * ppp],
perspective: set.perspective,
center,
};
let inside = inside_color(doc, &set.inside).unwrap_or([255; 4]);
// While the print of a new revision renders, the last one of the same blank and setting is
// drawn; a print of another document, blank or Show Fold Lines setting is not.
let print = CACHE.with(|c| {
let mut c = c.borrow_mut();
let region = print_region(blank)?;
let (pw, ph, scale) = print_size(region);
let pkey = PrintKey {
uid: key.0,
revision: key.1,
fold_lines: set.show_fold_lines,
region: [region.x0.to_bits(), region.y0.to_bits(), region.x1.to_bits(), region.y1.to_bits()],
width: pw,
height: ph,
};
c.update_print(ui.ctx(), doc, pkey, region, scale);
c.print_for(&pkey)
});
let draw_key = DrawKey { fold: key, camera, inside, print: print.as_ref().map(|(k, _)| *k) };
let kept = CACHE.with(|c| {
let mut c = c.borrow_mut();
let Some(tex) = c.tex.as_ref().filter(|_| c.drawn == Some(draw_key)).map(|t| t.id()) else { return false };
ui.painter().image(tex, rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
if let Some((_, at)) = &mut c.image {
*at = rect;
}
true
});
if kept {
return;
}
let t0 = crate::now_ms();
let scene = raster::Scene { blank, folded: f, print: print.as_ref().map(|(_, p)| &**p), inside, outside: [255; 4], camera };
let Some(img) = raster::render(&scene) else { return };
let draw_ms = crate::now_ms() - t0;
let color = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels);
CACHE.with(|c| {
let mut c = c.borrow_mut();
c.drawn = Some(draw_key);
c.renders += 1;
match &mut c.tex {
Some(tex) => tex.set(color, egui::TextureOptions::LINEAR),
None => c.tex = Some(ui.ctx().load_texture("fold-preview", color, egui::TextureOptions::LINEAR)),
}
if let Some(tex) = &c.tex {
let uv = Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0));
ui.painter().image(tex.id(), rect, uv, Color32::WHITE);
}
c.frame = Some(Frame { width: img.width, height: img.height, fold_ms, draw_ms });
c.image = Some((img, rect));
});
}
#[cfg(test)]
pub(crate) fn prints_rendered() -> u64 {
CACHE.with(|c| c.borrow().prints)
}
#[cfg(test)]
pub(crate) fn last_image() -> Option<Image> {
CACHE.with(|c| c.borrow().image.as_ref().map(|(i, _)| i.clone()))
}
/// The folds worked out and the images rendered so far.
#[cfg(test)]
pub(crate) fn work_done() -> (u64, u64) {
CACHE.with(|c| (c.borrow().folds, c.borrow().renders))
}
/// The screen rect the last image filled.
#[cfg(test)]
pub(crate) fn last_rect() -> Option<Rect> {
CACHE.with(|c| c.borrow().image.as_ref().map(|(_, r)| *r))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,505 @@
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use std::sync::Arc;
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use super::{Cache, ID, PrintKey, Settings, inside_color, last_image, last_rect, prints_rendered, show, status, work_done};
use crate::{VectorcraftApp, menus};
/// An app with a tray blank (a 100 pt base at x 140 to 240, y 140 to 240, and a 40 pt wall on each
/// side) and a red square printed on the base, nothing selected → (app, the red square's id).
fn app() -> (VectorcraftApp, u64) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap();
let outline = path(&mut app, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
let creases = [
path(&mut app, "M140 140 L240 140"),
path(&mut app, "M240 140 L240 240"),
path(&mut app, "M240 240 L140 240"),
path(&mut app, "M140 240 L140 140"),
];
app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap();
app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap();
let red = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 180, "height": 180})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({ "ids": [red] })).unwrap();
app.run("paint.setFill", json!({ "color": "#ff0000" })).unwrap();
app.run("paint.setStroke", json!({ "none": true })).unwrap();
app.run("object.arrange.sendToBack", json!({})).unwrap();
app.run("select.none", json!({})).unwrap();
(app, red)
}
/// Draws the window in a 520 × 440 frame, twice (egui lays out on the first).
fn frame(app: &mut VectorcraftApp) {
frame_at(app, 1.0);
}
/// [`frame`] at `zoom` pixels per point.
fn frame_at(app: &mut VectorcraftApp, zoom: f32) {
crate::i18n::set_current(crate::i18n::Lang::EN);
let ctx = egui::Context::default();
ctx.set_pixels_per_point(zoom);
crate::theme::install_fonts(&ctx);
for time in [0.0, 1.0] {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(520.0, 440.0));
let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| show(app, ui));
out.textures_delta.clear();
}
}
fn color_at(img: &vectorcraft_three_d::fold::raster::Image, x: u32, y: u32) -> [u8; 4] {
let i = (y * img.width + x) as usize * 4;
[img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]]
}
/// The color at the middle of the window's last image.
fn middle(img: &vectorcraft_three_d::fold::raster::Image) -> [u8; 4] {
color_at(img, img.width / 2, img.height / 2)
}
#[test]
fn the_menu_item_and_the_panel_button_show_the_window_and_a_second_run_keeps_it() {
let (mut app, _) = app();
let entries = menus::menu_entries(&app);
let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Fold Preview").expect("listed");
assert_eq!((item.command.as_deref(), &item.params), (Some("ui.foldPreview"), &json!({})));
assert!(!crate::panel_docking::showing(&app.ui, ID));
menus::invoke(&mut app, "ui.foldPreview", json!({}));
assert!(crate::panel_docking::visible(&app.ui, ID), "the window opens");
menus::invoke(&mut app, "ui.foldPreview", json!({}));
assert!(crate::panel_docking::visible(&app.ui, ID), "a second run leaves it open");
let text = crate::tests_labels::painted_text(&mut app, super::super::show);
assert!(text.contains("Fold Preview"), "the Fold Lines panel has the button: {text}");
}
#[test]
fn ui_fold_preview_sets_the_window_and_refuses_bad_values() {
let (mut app, _) = app();
let r = app
.run(
"ui.foldPreview",
json!({"amount": 0.5, "view": "top", "zoom": 2, "perspective": 40, "inside": "#00ff00", "showFoldLines": true, "base": [120, 190]}),
)
.unwrap();
let want = Settings {
amount: 0.5,
rotate_x: 90.0,
rotate_y: 0.0,
zoom: 2.0,
pan: [0.0; 2],
perspective: 40.0,
inside: "#00ff00".into(),
show_fold_lines: true,
base: Some([120.0, 190.0]),
};
assert_eq!(app.ui.fold_preview, want);
assert_eq!(r["rotateX"], 90.0, "{r}");
assert!(r.get("frame").is_some(), "{r}");
app.run("ui.foldPreview", json!({"rotateX": -30, "rotateY": 170, "base": null})).unwrap();
assert_eq!((app.ui.fold_preview.rotate_x, app.ui.fold_preview.rotate_y, app.ui.fold_preview.base), (-30.0, 170.0, None));
let kept = app.ui.fold_preview.clone();
for (p, want) in [
(json!({"amount": 2}), "`amount` must be a number from 0 to 1"),
(json!({"amount": "half"}), "`amount` must be a number from 0 to 1"),
(json!({"view": "sideways"}), "`view` must be one of"),
(json!({"rotateX": 200}), "`rotateX` must be a number from -180 to 180"),
(json!({"zoom": 0}), "`zoom` must be a number from 0.1 to 8"),
(json!({"perspective": 170}), "`perspective` must be a number from 0 to 160"),
(json!({"inside": "no such swatch"}), "`inside` must be #rrggbb"),
(json!({"inside": 7}), "`inside` must be #rrggbb"),
(json!({"showFoldLines": "yes"}), "`showFoldLines` must be true or false"),
(json!({"base": [1, "2"]}), "`base` must be a point"),
(json!({"base": [5, 5]}), "`base` is in no panel"),
(json!({"amount": 0.2, "zoom": 99}), "`zoom` must be a number"),
] {
let e = app.run("ui.foldPreview", p.clone()).unwrap_err().to_string();
assert!(e.contains(want), "{p}: {e}");
assert_eq!(app.ui.fold_preview, kept, "{p} sets nothing");
}
// A swatch with a plain color names the inside.
app.run("ui.foldPreview", json!({"inside": "White"})).unwrap();
assert_eq!(app.ui.fold_preview.inside, "White");
// So does one whose name starts with #, and a swatch's name comes before a #rrggbb that reads the same.
app.run("swatch.new", json!({"name": "#brand", "color": "#0000ff"})).unwrap();
app.run("swatch.new", json!({"name": "#00ff00", "color": "#0000ff"})).unwrap();
app.run("ui.foldPreview", json!({"inside": "#brand"})).unwrap();
assert_eq!(app.ui.fold_preview.inside, "#brand");
let doc = &app.session.active().expect("a document").doc;
assert_eq!(inside_color(doc, "#brand"), Some([0, 0, 255, 255]));
assert_eq!(inside_color(doc, "#00ff00"), Some([0, 0, 255, 255]));
assert_eq!(inside_color(doc, "#ff0000"), Some([255, 0, 0, 255]));
// White, the default, stays white beside a swatch named #ffffff.
app.run("swatch.new", json!({"name": "#ffffff", "color": "#0000ff"})).unwrap();
let doc = &app.session.active().expect("a document").doc;
assert_eq!(inside_color(doc, &Settings::default().inside), Some([255; 4]));
assert_eq!(inside_color(doc, "#ffffff"), Some([0, 0, 255, 255]));
app.run("ui.foldPreview", json!({"inside": ""})).unwrap();
assert_eq!(app.ui.fold_preview.inside, "");
}
#[test]
fn the_window_draws_the_print_on_the_folded_panels_and_the_inside_on_their_backs() {
let (mut app, _) = app();
// Flat, from the front: the base's print, red, fills the middle.
app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap();
let before = prints_rendered();
frame(&mut app);
assert!(prints_rendered() > before, "the print is rendered on this thread without a worker");
let img = last_image().expect("a frame");
let [r, g, b, a] = middle(&img);
assert!(r > 150 && g < 40 && b < 40 && a == 255, "red print: {:?}", [r, g, b, a]);
let state = app.run("ui.foldPreview", json!({})).unwrap();
assert_eq!((state["frame"]["width"].as_u64(), state["frame"]["height"].as_u64()), (Some(u64::from(img.width)), Some(u64::from(img.height))));
// From the back, the base's inside shows in the inside color.
app.run("ui.foldPreview", json!({"view": "back", "inside": "#00ff00"})).unwrap();
frame(&mut app);
let [r, g, b, _] = middle(&last_image().expect("a frame"));
assert!(r < 40 && g > 150 && b < 40, "green inside: {:?}", [r, g, b]);
// Folded and seen from the front, the walls stand edge on: the base fills the same place.
app.run("ui.foldPreview", json!({"amount": 1, "view": "front"})).unwrap();
frame(&mut app);
let img = last_image().expect("a frame");
let [r, ..] = middle(&img);
assert!(r > 150, "the base still shows its print: {:?}", middle(&img));
// The same print is not rendered again while the document does not change.
let prints = prints_rendered();
frame(&mut app);
assert_eq!(prints_rendered(), prints);
}
#[test]
fn a_wide_perspective_still_fits_the_whole_folded_blank_in_the_view() {
let (mut app, _) = app();
// Without perspective, the base and the two walls behind it that face the viewer show.
let mut flat = None;
for perspective in [0, 60, 160] {
app.run("ui.foldPreview", json!({"amount": 1, "view": "threeQuarter", "zoom": 1, "perspective": perspective})).unwrap();
frame(&mut app);
let img = last_image().expect("a frame");
let mut shown: Vec<usize> =
(0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter_map(|(x, y)| img.panel_at(x, y)).collect();
shown.sort_unstable();
shown.dedup();
let flat = flat.get_or_insert_with(|| shown.clone());
assert_eq!(flat.len(), 3);
assert_eq!(&shown, flat, "{perspective}°: the same panels show");
let edge = (0..img.width).flat_map(|x| [(x, 0), (x, img.height - 1)]).chain((0..img.height).flat_map(|y| [(0, y), (img.width - 1, y)]));
assert!(edge.into_iter().all(|(x, y)| img.panel_at(x, y).is_none()), "{perspective}°: nothing reaches the edge of the view");
}
}
#[test]
fn a_window_with_more_pixels_than_the_view_may_have_is_drawn_smaller() {
let (mut app, _) = app();
app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap();
frame_at(&mut app, 8.0);
let img = last_image().expect("a frame");
assert!(u64::from(img.width) * u64::from(img.height) <= u64::from(vectorcraft_three_d::fold::raster::MAX_PIXELS), "{}×{}", img.width, img.height);
assert!(img.width > 1000, "still sharper than one pixel a point: {}", img.width);
let [r, ..] = middle(&img);
assert!(r > 150, "the base's print shows: {:?}", middle(&img));
}
#[test]
fn the_print_leaves_out_the_fold_lines_unless_they_are_shown() {
let (mut app, red) = app();
// Without the red square, the base's middle shows the board with no art; with a crease drawn
// across the middle and the fold lines shown, the crease's color shows there.
app.run("select.set", json!({ "ids": [red] })).unwrap();
app.run("edit.clear", json!({})).unwrap();
let mid = app.run("path.create", json!({ "d": "M140 190 L240 190" })).unwrap()["id"].as_u64().unwrap();
app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": [mid] })).unwrap();
app.run("select.set", json!({ "ids": [mid] })).unwrap();
app.run("stroke.set", json!({ "weight": 20 })).unwrap();
app.run("select.none", json!({})).unwrap();
app.run("ui.foldPreview", json!({"amount": 0, "view": "front", "zoom": 1})).unwrap();
frame(&mut app);
let plain = middle(&last_image().expect("a frame"));
app.run("ui.foldPreview", json!({"showFoldLines": true})).unwrap();
frame(&mut app);
let lined = middle(&last_image().expect("a frame"));
assert_ne!(plain, lined, "the crease shows only with Show Fold Lines on");
assert!(plain[0] > 200 && plain[1] > 200 && plain[2] > 200, "the board is white where the print has no art: {plain:?}");
}
#[test]
fn the_window_says_when_there_is_nothing_to_fold() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let text = crate::tests_labels::painted_text(&mut app, show);
assert!(text.contains("Check the fold lines first."), "{text}");
let mut none = VectorcraftApp::new(Session::new(), Default::default());
let text = crate::tests_labels::painted_text(&mut none, show);
assert!(text.contains("Open a document to preview its folded shape."), "{text}");
}
#[test]
fn the_settings_are_kept_with_the_ui_state() {
let (mut app, _) = app();
app.run("ui.foldPreview", json!({"amount": 0.25, "view": "left"})).unwrap();
let saved: Value = serde_json::to_value(&app.ui).unwrap();
assert_eq!(saved["fold_preview"]["amount"], 0.25, "{}", saved["fold_preview"]);
let back: crate::state::UiState = serde_json::from_value(saved).unwrap();
assert_eq!(back.fold_preview, app.ui.fold_preview);
}
#[test]
fn saved_settings_out_of_range_are_brought_into_range() {
let (mut app, _) = app();
app.ui.fold_preview = Settings {
amount: 3.0,
rotate_x: 200.0,
rotate_y: 180.0,
zoom: 0.0,
pan: [f64::NAN, 4.0],
perspective: -5.0,
base: Some([f64::INFINITY, 0.0]),
..Settings::default()
};
frame(&mut app);
let set = &app.ui.fold_preview;
assert_eq!(
(set.amount, set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective, set.base),
(1.0, -160.0, 180.0, 0.1, [0.0, 4.0], 0.0, None)
);
let text = crate::tests_labels::painted_text(&mut app, show);
assert!(!text.contains("Check the fold lines first."), "the blank folds: {text}");
assert!(last_image().is_some(), "and is drawn");
}
/// A window kept open over frames, as the app draws it.
struct View {
ctx: egui::Context,
time: f64,
}
impl View {
fn new(app: &mut VectorcraftApp) -> Self {
crate::i18n::set_current(crate::i18n::Lang::EN);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let mut v = View { ctx, time: 0.0 };
v.idle(app);
v
}
fn step(&mut self, app: &mut VectorcraftApp, events: Vec<Event>, modifiers: Modifiers) {
self.time += 0.05;
let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(520.0, 440.0));
let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect();
let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() };
let mut out = self.ctx.run_ui(input, |ui| show(app, ui));
out.textures_delta.clear();
}
fn idle(&mut self, app: &mut VectorcraftApp) {
for _ in 0..3 {
self.step(app, vec![], Modifiers::NONE);
}
}
/// Presses `button` at `at`, drags by `by` in four steps and lets go, holding `modifiers`.
fn drag(&mut self, app: &mut VectorcraftApp, at: Pos2, by: egui::Vec2, button: PointerButton, modifiers: Modifiers) {
let press = |pos, pressed| Event::PointerButton { pos, button, pressed, modifiers };
self.step(app, vec![Event::PointerMoved(at)], modifiers);
self.step(app, vec![press(at, true)], modifiers);
for k in 1..=4 {
self.step(app, vec![Event::PointerMoved(at + by * (k as f32 / 4.0))], modifiers);
}
self.step(app, vec![press(at + by, false)], modifiers);
self.idle(app);
}
fn click(&mut self, app: &mut VectorcraftApp, at: Pos2) {
let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
self.step(app, vec![Event::PointerMoved(at)], Modifiers::NONE);
self.step(app, vec![press(true)], Modifiers::NONE);
self.step(app, vec![press(false)], Modifiers::NONE);
}
fn key(&mut self, app: &mut VectorcraftApp, key: egui::Key) {
let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE };
self.step(app, vec![press], Modifiers::NONE);
self.step(app, vec![], Modifiers::NONE);
}
}
/// The app showing the tray flat from the front, in a [`View`], and the middle of the view.
fn front_view() -> (VectorcraftApp, View, Pos2) {
let (mut app, _) = app();
app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap();
let view = View::new(&mut app);
let at = last_rect().expect("the view is drawn").center();
(app, view, at)
}
#[test]
fn a_drag_turns_the_view_and_a_shift_drag_keeps_to_one_axis() {
let (mut app, mut view, at) = front_view();
view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::NONE);
let set = app.ui.fold_preview.clone();
assert!(set.rotate_y > 5.0 && set.rotate_y <= 20.0 + 1e-9, "{set:?}");
assert!(set.rotate_x > 2.0 && set.rotate_x <= 10.0 + 1e-9, "{set:?}");
app.run("ui.foldPreview", json!({"view": "front"})).unwrap();
view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::SHIFT);
let set = app.ui.fold_preview.clone();
assert!(set.rotate_y > 5.0 && set.rotate_x == 0.0, "only the larger move turns the view: {set:?}");
}
#[test]
fn a_middle_drag_moves_the_view_and_the_wheel_zooms_it() {
let (mut app, mut view, at) = front_view();
view.drag(&mut app, at, vec2(30.0, -10.0), PointerButton::Middle, Modifiers::NONE);
let set = app.ui.fold_preview.clone();
assert!(set.pan[0] > 0.0 && set.pan[1] < 0.0, "{set:?}");
assert_eq!((set.rotate_x, set.rotate_y), (0.0, 0.0), "the view does not turn");
let wheel = Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: vec2(0.0, 60.0),
phase: egui::TouchPhase::Move,
modifiers: Modifiers::NONE,
source: egui::MouseWheelSource::Unknown,
};
view.step(&mut app, vec![Event::PointerMoved(at), wheel], Modifiers::NONE);
for _ in 0..20 {
view.step(&mut app, vec![], Modifiers::NONE);
}
assert!(app.ui.fold_preview.zoom > 1.05, "{:?}", app.ui.fold_preview);
}
#[test]
fn the_arrow_keys_turn_the_focused_view_and_keep_the_focus() {
let (mut app, mut view, at) = front_view();
view.click(&mut app, at);
view.idle(&mut app);
// Up first: the toolbar is above the view, where the focus would go if the view let it.
view.key(&mut app, egui::Key::ArrowUp);
view.key(&mut app, egui::Key::ArrowRight);
view.key(&mut app, egui::Key::ArrowRight);
let set = &app.ui.fold_preview;
assert_eq!((set.rotate_x, set.rotate_y), (-5.0, 10.0), "every press turns the view by 5°");
// A focused view seen from the back stays there until a key turns it.
app.run("ui.foldPreview", json!({"view": "back"})).unwrap();
view.idle(&mut app);
assert_eq!(app.ui.fold_preview.rotate_y, 180.0);
}
#[test]
fn a_double_click_on_a_panel_makes_it_the_base() {
let (mut app, mut view, at) = front_view();
// The left wall is the base; the middle of the view shows the tray's base panel.
app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap();
view.idle(&mut app);
view.click(&mut app, at);
view.click(&mut app, at);
let [x, y] = app.ui.fold_preview.base.expect("a base");
assert!((140.0..240.0).contains(&x) && (140.0..240.0).contains(&y), "the base panel is picked: {x}, {y}");
}
#[test]
fn a_double_click_as_the_document_changes_picks_nothing_from_the_old_image() {
let (mut app, mut view, at) = front_view();
app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap();
view.idle(&mut app);
view.click(&mut app, at);
let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
view.step(&mut app, vec![press(true)], Modifiers::NONE);
// The document changes between the image on screen and the release that ends the double-click.
app.run("shape.rectangle", json!({"x": 350, "y": 350, "width": 10, "height": 10})).unwrap();
view.step(&mut app, vec![press(false)], Modifiers::NONE);
assert_eq!(app.ui.fold_preview.base, Some([120.0, 190.0]), "the base is kept");
}
#[test]
fn the_view_is_folded_and_drawn_again_only_when_something_changes() {
let (mut app, mut view, _) = front_view();
let (folds, renders) = work_done();
view.idle(&mut app);
assert_eq!(work_done(), (folds, renders), "nothing changed: no fold and no render");
app.run("ui.foldPreview", json!({"rotateY": 10})).unwrap();
view.idle(&mut app);
assert_eq!(work_done(), (folds, renders + 1), "a turn renders once and does not fold again");
app.run("ui.foldPreview", json!({"amount": 0.5})).unwrap();
view.idle(&mut app);
assert_eq!(work_done(), (folds + 1, renders + 2), "a new amount folds and renders once");
}
#[test]
fn a_short_wide_window_keeps_its_proportions() {
let (mut app, _) = app();
app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap();
crate::i18n::set_current(crate::i18n::Lang::EN);
let ctx = egui::Context::default();
ctx.set_pixels_per_point(2.0);
crate::theme::install_fonts(&ctx);
for time in [0.0, 1.0] {
let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(2200.0, 260.0));
let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| show(&mut app, ui));
out.textures_delta.clear();
}
let (img, rect) = (last_image().expect("a frame"), last_rect().expect("a rect"));
let (image, window) = (f64::from(img.width) / f64::from(img.height), f64::from(rect.width() / rect.height()));
assert!(img.width <= vectorcraft_three_d::fold::raster::MAX_SIDE, "{}", img.width);
assert!((image - window).abs() / window < 0.02, "image {image}, window {window}");
}
#[test]
fn a_print_of_another_blank_or_setting_is_not_drawn_while_the_new_one_renders() {
let key = PrintKey { uid: 1, revision: 5, fold_lines: false, region: [0, 0, 10, 10], width: 1, height: 1 };
let region = vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0);
let print = vectorcraft_three_d::fold::raster::Print::new(region, 1, 1, vec![255; 4]).expect("a print");
let cache = Cache { print: Some((key, Arc::new(print))), ..Default::default() };
assert!(cache.print_for(&PrintKey { revision: 6, ..key }).is_some(), "a newer revision of the same blank keeps the last print");
for other in [PrintKey { uid: 2, ..key }, PrintKey { fold_lines: true, ..key }, PrintKey { region: [0, 0, 20, 10], ..key }] {
assert!(cache.print_for(&other).is_none(), "{other:?}");
}
}
#[test]
fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() {
use vectorcraft_three_d::fold::{Blank, Folded, FoldedHinge};
let hinge = |tree, closes, gap| FoldedHinge { a: 0, b: 1, angle: 90.0, tree, closes, gap };
let f = Folded {
base: 0,
panels: vec![],
order: vec![],
hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)],
collisions: vec![(0, 1)],
};
let lines = status(3, Some((&Blank::default(), &f)), true);
assert_eq!(
lines,
[
"Panels: 0, hinges: 0",
"Check the fold lines first.",
"Other blanks not shown: 2",
"A joint does not close by 12.3 pt.",
"Two panels pass through each other."
]
);
let f = Folded { hinges: vec![hinge(false, true, 0.05)], collisions: vec![], ..f };
assert_eq!(status(1, Some((&Blank::default(), &f)), false), ["Panels: 0, hinges: 0"]);
}
#[test]
fn the_window_says_when_folded_panels_pass_through_each_other() {
// A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. Folded
// about the base, the lid crosses the taller wall.
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap();
let outline = path(&mut app, "M0 0 L310 0 L310 50 L0 50 Z");
let creases = [path(&mut app, "M120 0 L120 50"), path(&mut app, "M150 0 L150 50"), path(&mut app, "M250 0 L250 50")];
app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap();
app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap();
app.run("select.none", json!({})).unwrap();
app.run("ui.foldPreview", json!({"base": [200, 25], "amount": 1})).unwrap();
let text = crate::tests_labels::painted_text(&mut app, show);
assert!(text.contains("Two panels pass through each other."), "{text}");
assert!(!text.contains("A joint does not close"), "{text}");
}
+8 -3
View File
@@ -1,11 +1,12 @@
//! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools),
//! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into
//! Dashes ([`dashes`]), Expand Dashes into Paths, Convert to Parametric Shape and Tangent Circle… ([`tangent_circle`]); the Anchor Inspector panel (the selected
//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape and Tangent Circle… ([`tangent_circle`]); the Anchor Inspector panel (the selected
//! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values,
//! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel
//! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and
//! `tool.setOption`.
pub mod bridge;
pub mod corner;
pub mod dashes;
pub mod set_corners;
@@ -74,6 +75,7 @@ pub fn menu() -> Vec<Item> {
Item::Cmd("Split at Crossings", "addon.pathtools.crossings", json!({ "cut": true })),
Item::Cmd("Divide into Dashes…", dashes::COMMAND, Value::Null),
Item::Cmd("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})),
Item::Cmd("Smooth Bridge…", bridge::COMMAND, Value::Null),
Item::Cmd("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})),
Item::Cmd("Tangent Circle…", tangent_circle::COMMAND, Value::Null),
Item::Cmd("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })),
@@ -246,12 +248,15 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
false
}
/// OK: set the tool's options.
/// OK: set the tool's options. When the tool refuses one of them, nothing is set and the dialog
/// stays open.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let tool = d.str("__tool");
let values: Map<String, Value> = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect();
let r = app.run("tool.setOption", json!({ "tool": tool, "values": values }));
app.ui.dialog = None;
if r.is_ok() {
app.ui.dialog = None;
}
r
}
@@ -0,0 +1,92 @@
//! Smooth Bridge in the interface: its dialog (the arcs' radius as a percentage of the smaller
//! circle's radius, Keep Originals), which previews on the canvas and runs `addon.pathtools.bridge`
//! on OK.
use egui::Ui;
use serde_json::{Value, json};
use crate::VectorcraftApp;
use crate::dialogs::{DialogSpec, form};
use crate::state::Dialog;
use crate::widgets;
/// The command, and its dialog's kind.
pub const COMMAND: &str = "addon.pathtools.bridge";
pub const KIND: &str = "smoothBridge";
/// The radius the command takes (%), and its default.
const RADII: std::ops::RangeInclusive<f64> = 1.0..=1000.0;
const RADIUS: f64 = 100.0;
const LABEL_W: f32 = 60.0;
const FIELD_W: f32 = 90.0;
/// The dialog's fields to start with: the command's defaults.
pub(crate) fn fields() -> Value {
json!({ "radius": RADIUS, "keepOriginals": false })
}
pub(crate) const SPEC: DialogSpec =
DialogSpec { heading: |_| tl!("Smooth Bridge").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM };
/// The command's parameters from the dialog's fields.
fn params(d: &Dialog) -> Value {
json!({ "radius": d.f64("radius", RADIUS), "keepOriginals": d.bool("keepOriginals") })
}
fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| {
if let Some(v) = widgets::range_field(ui, ("dlg-num", "radius"), d.f64("radius", RADIUS), RADII, "%", 0, FIELD_W) {
d.fields.insert("radius".into(), json!(v));
}
});
form::check(ui, d, "keepOriginals", tl!("Keep Originals"));
form::preview(app, ui, d, "Smooth Bridge", COMMAND, params(d));
false
}
/// OK: run the command (keep its preview) and close.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
form::commit_preview(app, COMMAND, params(d))
}
#[cfg(test)]
mod tests {
use serde_json::json;
use vectorcraft_engine::Session;
use crate::tests_labels::painted_text;
use crate::{VectorcraftApp, menus};
fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 {
app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap()
}
#[test]
fn smooth_bridge_opens_its_dialog_previews_and_runs_on_ok() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let (a, b) = (circle(&mut app, 100.0, 20.0), circle(&mut app, 160.0, 20.0));
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let entries = menus::menu_entries(&app);
let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Smooth Bridge…").unwrap();
let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
menus::invoke(&mut app, &cmd, p);
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND));
let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
for s in ["Smooth Bridge", "Radius:", "Keep Originals", "Preview"] {
assert!(shown.contains(s), "{s} in {shown}");
}
let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().unwrap().len();
app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true));
painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
assert_eq!(count(&app), 1, "previewed: one outline in place of the circles");
crate::dialogs::cancel(&mut app);
assert_eq!(count(&app), 2, "rolled back");
menus::invoke(&mut app, &cmd, serde_json::Value::Null);
let n = app.session.doc().unwrap().history.undo.len();
app.ui.dialog.as_mut().unwrap().fields.insert("keepOriginals".into(), json!(true));
crate::dialogs::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1);
assert_eq!(count(&app), 3, "the circles and the outline above them");
}
}
@@ -329,3 +329,45 @@ fn common_tangents_previews_cancels_and_runs_on_ok() {
assert_eq!((steps(&app), count(&app)), (n, nodes));
assert!(app.ui.status.contains("inside the other"), "{}", app.ui.status);
}
/// Common Tangents… on a point and an ellipse: every Tangents choice previews the same two lines
/// from the point, OK keeps them as one step, and a point inside the ellipse changes nothing and
/// says why.
#[test]
fn common_tangents_on_a_point_gives_the_same_lines_for_every_choice() {
let mut app = app();
let oval = app.run("shape.ellipse", json!({"x": 180.0, "y": 120.0, "width": 80.0, "height": 60.0})).unwrap()["id"].as_u64().unwrap();
let point =
|app: &mut VectorcraftApp, x: f64, y: f64| app.run("path.create", json!({"anchors": [{"x": x, "y": y}]})).unwrap()["id"].as_u64().unwrap();
let dot = point(&mut app, 40.0, 150.0);
app.run("select.set", json!({"ids": [oval, dot]})).unwrap();
let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node_count();
let (n, nodes) = (steps(&app), count(&app));
let open = |app: &mut VectorcraftApp| {
let entries = menus::menu_entries(app);
let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Common Tangents…").unwrap();
assert!(item.enabled);
let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
menus::invoke(app, &cmd, p);
};
open(&mut app);
crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true));
for (_, kind) in super::TANGENT_KINDS {
crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "tangents".into(), json!(kind));
painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
assert_eq!(count(&app), nodes + 2, "{kind}: the two lines from the point");
}
crate::dialogs::confirm(&mut app).unwrap();
assert_eq!((steps(&app), count(&app)), (n + 1, nodes + 2), "one undo step");
// A point inside the ellipse: nothing changes, and a message says why.
let inside = point(&mut app, 220.0, 150.0);
app.run("select.set", json!({"ids": [oval, inside]})).unwrap();
let (n, nodes) = (steps(&app), count(&app));
open(&mut app);
crate::dialogs::confirm(&mut app).unwrap();
assert_eq!((steps(&app), count(&app)), (n, nodes));
assert!(app.ui.status.contains("The point lies inside the path"), "{}", app.ui.status);
}
+199
View File
@@ -0,0 +1,199 @@
//! Unit Converter in the interface: its submenu (Object › Plug-ins › Unit Converter), which opens
//! the panel, and the panel. The panel shows one length in every unit of
//! [`Unit::EAST_ASIAN`], one number field each. A value typed in any field (units and arithmetic,
//! as every number field reads them) updates the others as it is typed; text that does not read
//! leaves them as they were. From Selection reads the selection's width and height
//! (`addon.units.selectionSize`), and Width or Height picks which of the two the fields show; the
//! size read is dropped when the document, its selection or the bounds measure changes. Apply gives the selection that
//! width or height through `object.setBounds` as the Transform panel's W or H field does (its
//! reference point, Constrain Width and Height Proportions and Transform Object Only, Pattern
//! Only or Both), as one undo step. Each field's copy button puts its value on the clipboard, with
//! its unit when Copy with Units is on.
use egui::Ui;
use serde_json::json;
use vectorcraft_doc::{Unit, finite_in_every_unit};
use crate::VectorcraftApp;
use crate::menus::Item;
use crate::panels::transform;
use crate::panels::{pstate, set_pstate};
use crate::widgets;
/// The panel's id (`window.panel {panel: "unitConverter"}`).
pub const ID: &str = "unitConverter";
/// The command that measures the selection.
pub const SELECTION_SIZE: &str = "addon.units.selectionSize";
/// Where the panel keeps its length and choices (panel state).
const STATE: &str = "unit-converter";
/// A row (label, field, copy button and two gaps) is 214 pt wide, inside the 240 pt body of the
/// default 260 pt floating panel with room for its scroll bar.
const LABEL_W: f32 = 90.0;
const FIELD_W: f32 = 90.0;
/// Object › Plug-ins › Unit Converter.
pub fn menu() -> Vec<Item> {
vec![Item::Cmd("Unit Converter Panel", "window.panel", json!({ "panel": ID }))]
}
/// The selection's side the fields show and Apply sets.
#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub(crate) enum Side {
#[default]
Width,
Height,
}
impl Side {
/// `object.setBounds`'s param for this side.
fn key(self) -> &'static str {
match self {
Side::Width => "width",
Side::Height => "height",
}
}
}
/// The panel's length and choices.
#[derive(Clone, Default, Debug, PartialEq)]
pub(crate) struct Converter {
/// The length (points), none until one is typed or read from the selection.
pub points: Option<f64>,
/// The selection's width and height (points) From Selection last read.
pub size: Option<(f64, f64)>,
/// The active document's uid and revision, and the bounds measure (Use Preview Bounds,
/// glyph bounds), when [`Converter::size`] was read.
pub read_at: Option<ReadAt>,
/// Which of them the fields show, and the side Apply sets.
pub side: Side,
/// Copy puts the unit after the number.
pub with_units: bool,
}
impl Converter {
/// Show `side`: the fields take that side of the size From Selection read, if any.
pub fn pick(&mut self, side: Side) {
self.side = side;
if let Some((w, h)) = self.size {
self.points = Some(if side == Side::Width { w } else { h });
}
}
/// A length typed in a field: after From Selection it replaces the side shown, so picking the
/// other side and back keeps it.
pub fn set(&mut self, pt: f64) {
self.points = Some(pt);
if let Some((w, h)) = &mut self.size {
*(if self.side == Side::Width { w } else { h }) = pt;
}
}
/// Drop the size From Selection read when the active document is no longer the one it was
/// read from or is measured another way (`now`: its uid and revision, which a change to the
/// selection also moves, and the bounds measure). The length the fields show stays.
pub fn follow(&mut self, now: Option<ReadAt>) {
if self.size.is_some() && self.read_at != now {
self.size = None;
self.read_at = None;
}
}
/// What the copy button of the field in `unit` puts on the clipboard.
pub fn copied(&self, unit: Unit) -> Option<String> {
self.points.map(|pt| if self.with_units { unit.format(pt) } else { unit.number(pt) })
}
}
/// A document's uid and revision, and the bounds measure.
pub(crate) type ReadAt = (u64, u64, vectorcraft_effects::preview::Measure);
/// The active document's uid and revision, and the bounds measure.
pub(crate) fn document_now(app: &VectorcraftApp) -> Option<ReadAt> {
app.session.active().map(|st| (st.uid, st.revision, app.session.bounds_measure()))
}
/// From Selection: read the selection's width and height into `st`, and show the side picked.
pub(crate) fn from_selection(app: &mut VectorcraftApp, st: &mut Converter) -> Result<(), String> {
let r = app.run(SELECTION_SIZE, json!({}))?;
if let (Some(w), Some(h)) = (r["width"]["points"].as_f64(), r["height"]["points"].as_f64()) {
st.size = Some((w, h));
st.read_at = document_now(app);
st.pick(st.side);
}
Ok(())
}
/// Apply: give the selection the length as its width or height, as the Transform panel's W or H
/// field does: from its reference point (a symbol instance's registration point with Use
/// Registration Point for Symbol on), with the other side following under Constrain Width and
/// Height Proportions, and with the panel menu's Transform Object Only, Pattern Only or Both.
/// Without a length it does nothing.
pub(crate) fn apply(app: &mut VectorcraftApp, ui: &Ui, st: &Converter) -> Result<(), String> {
let Some(pt) = st.points else { return Ok(()) };
let reference = app.selection_box().map_or_else(|| transform::reference_index(ui), |b| transform::panel_reference(app, ui, &b).index);
let params = json!({ st.side.key(): pt, "reference": reference, "proportional": transform::proportional(app, ui) });
let params = transform::with_pattern_switches(app, params);
app.run("object.setBounds", params)?;
Ok(())
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let mut st: Converter = pstate(ui.ctx(), STATE);
st.follow(document_now(app));
// A number typed without a unit is in its row's unit, so 2 in the Picas row is 2 picas, also
// with Preferences › Units › Numbers Without Units Are Points on; other panels' fields keep it.
let bare_points = widgets::typed_unit(ui.ctx(), Unit::Picas) == Unit::Points;
widgets::set_bare_numbers_are_points(ui.ctx(), false);
for unit in Unit::EAST_ASIAN {
widgets::label_row(ui, unit.label(), LABEL_W, |ui| {
// A length too large to show in one of the units (near the largest number, in Q and
// Ha) leaves the others as they were, as text that does not read does.
if let Some(pt) = widgets::num_field_live(ui, ("unit-converter", unit.key()), st.points, unit, FIELD_W)
&& finite_in_every_unit(pt)
{
st.set(pt);
}
// The button's name and tip carry the row's unit ("Copy Millimeters").
let tip = format!("{} {}", tl!("Copy"), tl!(unit.label()));
let copy = widgets::icon_button_enabled(ui, "copy", &tip, false, st.points.is_some(), 22.0);
if copy.clicked()
&& let Some(text) = st.copied(unit)
{
ui.ctx().copy_text(text);
}
});
}
widgets::set_bare_numbers_are_points(ui.ctx(), bare_points);
if widgets::check(ui, "Copy with Units", st.with_units, true) {
st.with_units = !st.with_units;
}
ui.add_space(6.0);
widgets::subheader(ui, tl!("Selection"));
let selected = app.session.active().is_some_and(|d| !d.selection.is_empty());
ui.horizontal(|ui| {
for (side, label) in [(Side::Width, "Width"), (Side::Height, "Height")] {
if widgets::radio(ui, label, st.side == side, true) {
st.pick(side);
}
}
});
ui.horizontal(|ui| {
let read = ui.add_enabled_ui(selected, |ui| widgets::flat_button(ui, tl!("From Selection"), 110.0)).inner;
if read.clicked()
&& let Err(e) = from_selection(app, &mut st)
{
app.status(e);
}
let set = ui.add_enabled_ui(selected && st.points.is_some(), |ui| widgets::flat_button(ui, tl!("Apply"), 70.0)).inner;
if set.clicked()
&& let Err(e) = apply(app, ui, &st)
{
app.status(e);
}
});
set_pstate(ui.ctx(), STATE, st);
}
#[cfg(test)]
mod tests;
+329
View File
@@ -0,0 +1,329 @@
//! Unit Converter's submenu and panel: one field per unit, typing in one updates the others and
//! text that does not read leaves them alone, From Selection reads the selection's size, Apply
//! sets the side picked as one undo step and adds none when nothing changes, and Copy writes the
//! value with or without its unit.
use egui::{Event, Key, Modifiers, Pos2, Rect, vec2};
use serde_json::json;
use vectorcraft_doc::Unit;
use vectorcraft_engine::Session;
use super::{Converter, ID, STATE, Side, apply, document_now, from_selection, show};
use crate::panels::{pstate, set_pstate};
use crate::tests_labels::{painted_text, shapes_text};
use crate::{VectorcraftApp, menus};
/// An app with a selected 72 × 36 pt rectangle.
fn app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap();
app
}
fn near(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-6
}
fn undo_steps(app: &VectorcraftApp) -> usize {
app.session.active().unwrap().history.undo.len()
}
/// The selection's width and height.
fn size(app: &mut VectorcraftApp) -> (f64, f64) {
let r = app.run("addon.units.selectionSize", json!({})).unwrap();
(r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap())
}
#[test]
fn the_submenu_opens_the_panel() {
let mut app = app();
let entries = menus::menu_entries(&app);
let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Unit Converter"] && e.label == "Unit Converter Panel").expect("listed");
menus::invoke(&mut app, "window.panel", item.params.clone());
assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens");
}
#[test]
fn the_panel_has_a_field_for_every_unit_and_its_buttons() {
let mut app = app();
let text = painted_text(&mut app, |app, ui| {
set_pstate(ui.ctx(), STATE, Converter { points: Some(720.0 / 25.4), ..Converter::default() });
show(app, ui);
});
for u in Unit::EAST_ASIAN {
assert!(text.lines().any(|l| l == u.label()), "{} in {text}", u.label());
}
for s in ["10 mm", "1 cm", "0.3937 in", "28.346 pt", "40 Q", "40 H"] {
assert!(text.lines().any(|l| l == s), "{s} in {text}");
}
for s in ["Copy with Units", "Selection", "Width", "Height", "From Selection", "Apply"] {
assert!(text.lines().any(|l| l == s), "{s} in {text}");
}
}
#[test]
fn typing_in_a_field_updates_the_others_and_text_that_does_not_read_leaves_them() {
let mut app = app();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events: Vec<Event>| {
time += 0.05;
let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 800.0)));
let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect, focused: true, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
(pstate::<Converter>(&ctx, STATE), shapes_text(&out))
};
let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE };
frame(&mut app, vec![]);
frame(&mut app, vec![]);
// Tab reaches the first field, Points, which selects its text so typing replaces it.
frame(&mut app, vec![tab]);
frame(&mut app, vec![]);
let (st, _) = frame(&mut app, vec![Event::Text("1in/2".into())]);
assert!(st.points.is_some_and(|pt| near(pt, 36.0)), "{st:?}");
let (st, text) = frame(&mut app, vec![]);
assert!(near(st.points.unwrap(), 36.0));
for s in ["0.5 in", "3 p", "12.7 mm", "1.27 cm"] {
assert!(text.lines().any(|l| l == s), "{s} in {text}");
}
// Text that does not read keeps the length the other fields show.
let (st, text) = frame(&mut app, vec![Event::Text("x".into())]);
assert!(near(st.points.unwrap(), 36.0), "{st:?}");
assert!(text.lines().any(|l| l == "12.7 mm"), "{text}");
// So does a length too large to show in Q and Ha.
let select_all = Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND };
frame(&mut app, vec![select_all]);
// 1.7e308 pt: finite in points.
let (st, _) = frame(&mut app, vec![Event::Text(format!("17{}", "0".repeat(307)))]);
assert!(near(st.points.unwrap(), 36.0), "{st:?}");
}
#[test]
fn a_number_typed_without_a_unit_in_the_picas_row_is_in_picas() {
let mut app = app();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
// Numbers Without Units Are Points is on (its default), and stays on for other fields.
crate::widgets::set_bare_numbers_are_points(&ctx, true);
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events: Vec<Event>| {
time += 0.05;
let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 800.0)));
let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect, focused: true, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
pstate::<Converter>(&ctx, STATE)
};
let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE };
frame(&mut app, vec![]);
frame(&mut app, vec![]);
// Tab reaches the Points field, then the Picas field (the copy buttons are off with no length).
for _ in 0..2 {
frame(&mut app, vec![tab.clone()]);
frame(&mut app, vec![]);
}
let st = frame(&mut app, vec![Event::Text("2".into())]);
assert!(st.points.is_some_and(|pt| near(pt, 24.0)), "{st:?}");
assert_eq!(crate::widgets::typed_unit(&ctx, Unit::Picas), Unit::Points, "other fields still read points");
}
#[test]
fn picking_a_side_shows_that_side_of_the_size_read() {
let mut st = Converter { size: Some((72.0, 36.0)), ..Converter::default() };
st.pick(Side::Height);
assert_eq!((st.side, st.points), (Side::Height, Some(36.0)));
st.pick(Side::Width);
assert_eq!(st.points, Some(72.0));
// A length typed after From Selection replaces the side shown, and picking the other side and
// back keeps it.
st.set(100.0);
st.pick(Side::Height);
assert_eq!(st.points, Some(36.0));
st.pick(Side::Width);
assert_eq!((st.points, st.size), (Some(100.0), Some((100.0, 36.0))));
// Before From Selection a side keeps the length typed.
let mut st = Converter::default();
st.set(5.0);
st.pick(Side::Height);
assert_eq!((st.points, st.size), (Some(5.0), None));
}
#[test]
fn copy_writes_the_value_with_or_without_its_unit() {
let mut st = Converter { points: Some(72.0), ..Converter::default() };
assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1"));
st.with_units = true;
assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1 in"));
assert_eq!(st.copied(Unit::Millimeters), Some(Unit::Millimeters.format(72.0)));
assert_eq!(Converter::default().copied(Unit::Points), None, "nothing to copy before a length");
}
/// Apply `st` in a frame whose shared reference point (the Transform panel's) is `reference`.
fn apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) {
try_apply_at(app, st, reference).unwrap();
}
/// [`apply_at`], with its result.
fn try_apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) -> Result<(), String> {
let ctx = egui::Context::default();
ctx.data_mut(|d| d.insert_temp(egui::Id::unique("refpt"), reference));
let mut result = Ok(());
ctx.run_ui(Default::default(), |ui| result = apply(app, ui, st)).textures_delta.clear();
result
}
/// The selection's bounding box.
fn bounds(app: &mut VectorcraftApp) -> vectorcraft_geom::Rect {
app.selection_box().unwrap().rect
}
#[test]
fn from_selection_reads_the_size_and_apply_sets_the_side_picked() {
let mut app = app();
let mut st = Converter::default();
from_selection(&mut app, &mut st).unwrap();
assert_eq!((st.size, st.points), (Some((72.0, 36.0)), Some(72.0)));
st.pick(Side::Height);
assert_eq!(st.points, Some(36.0));
// Apply: 1 in high, from the centre, as one undo step.
let steps = undo_steps(&app);
st.points = Some(72.0);
apply_at(&mut app, &st, 4);
let (w, h) = size(&mut app);
assert!(near(w, 72.0) && near(h, 72.0), "{w} × {h}");
assert_eq!(undo_steps(&app), steps + 1);
// The same length again changes nothing and adds no step.
apply_at(&mut app, &st, 4);
assert_eq!(undo_steps(&app), steps + 1);
// Without a length Apply does nothing.
apply_at(&mut app, &Converter::default(), 4);
assert_eq!(undo_steps(&app), steps + 1);
// Width, kept at the left edge (reference 3).
let x0 = bounds(&mut app).x0;
let st = Converter { points: Some(144.0), side: Side::Width, ..Converter::default() };
apply_at(&mut app, &st, 3);
let b = bounds(&mut app);
assert!(near(b.width(), 144.0) && near(b.x0, x0), "{b:?}");
assert_eq!(undo_steps(&app), steps + 2);
}
/// Apply follows the Transform panel's W and H fields: Constrain Width and Height Proportions
/// scales the other side too, and Transform Pattern Only leaves the object's size alone.
#[test]
fn apply_follows_the_transform_panels_proportions_and_pattern_choice() {
let mut app = app();
app.run("prefs.set", json!({"key": "constrainProportions", "value": true})).unwrap();
apply_at(&mut app, &Converter { points: Some(144.0), side: Side::Width, ..Converter::default() }, 4);
let (w, h) = size(&mut app);
assert!(near(w, 144.0) && near(h, 72.0), "{w} × {h}");
app.run("prefs.set", json!({"key": "constrainProportions", "value": false})).unwrap();
app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "pattern"})).unwrap();
// The object has no pattern to transform: whether the command reports that or not, the
// object keeps its size.
let _ = try_apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4);
let (w, h) = size(&mut app);
assert!(near(w, 144.0) && near(h, 72.0), "the object keeps its size: {w} × {h}");
app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "both"})).unwrap();
apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4);
assert!(near(size(&mut app).0, 10.0));
}
/// With Use Registration Point for Symbol on and one symbol instance selected, Apply keeps the
/// symbol's registration point (here its top-left corner) in place, as the Transform panel does,
/// instead of the shared reference point (the centre).
#[test]
fn apply_keeps_a_symbol_instances_registration_point() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 80, "height": 40})).unwrap();
let id = app.run("symbol.new", json!({"name": "Corner", "registration": 0})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
app.run("prefs.set", json!({"key": "useRegistrationPointForSymbol", "value": true})).unwrap();
apply_at(&mut app, &Converter { points: Some(160.0), side: Side::Width, ..Converter::default() }, 4);
assert_eq!(bounds(&mut app), vectorcraft_geom::Rect::new(100.0, 50.0, 260.0, 90.0));
}
/// The size From Selection read belongs to the selection it was read from: after the selection
/// changes, picking a side keeps the length shown instead of showing the old object's side, and
/// Apply sets that length.
#[test]
fn a_size_read_from_another_selection_is_dropped() {
let mut app = app();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let frame = |app: &mut VectorcraftApp| {
ctx.run_ui(Default::default(), |ui| show(app, ui)).textures_delta.clear();
pstate::<Converter>(&ctx, STATE)
};
let mut st = Converter::default();
from_selection(&mut app, &mut st).unwrap();
set_pstate(&ctx, STATE, st);
// Drawing the panel again with nothing changed keeps it.
assert_eq!(frame(&mut app).size, Some((72.0, 36.0)));
// Another object selected.
app.run("shape.rectangle", json!({"x": 200, "y": 100, "width": 20, "height": 50})).unwrap();
let mut st = frame(&mut app);
assert_eq!((st.size, st.points), (None, Some(72.0)), "{st:?}");
st.pick(Side::Height);
assert_eq!(st.points, Some(72.0), "not the first object's height");
apply_at(&mut app, &st, 4);
let (w, h) = size(&mut app);
assert!(near(w, 20.0) && near(h, 72.0), "{w} × {h}");
// So does a change to the document.
let mut st = Converter::default();
from_selection(&mut app, &mut st).unwrap();
app.run("object.rotate", json!({"angle": 30})).unwrap();
st.follow(document_now(&app));
assert_eq!(st.size, None);
// And a change to how the selection is measured (Use Preview Bounds), which leaves the
// document as it is.
let mut st = Converter::default();
from_selection(&mut app, &mut st).unwrap();
st.follow(document_now(&app));
assert!(st.size.is_some());
app.run("prefs.set", json!({"key": "usePreviewBounds", "value": true})).unwrap();
st.follow(document_now(&app));
assert_eq!(st.size, None);
}
/// Each row's copy button reads as copying that row's unit, so a screen reader tells the twelve
/// apart, and the fields are named by their rows.
#[test]
fn each_copy_button_and_field_is_named_with_its_unit() {
let mut app = app();
let ctx = egui::Context::default();
ctx.enable_accesskit();
crate::theme::install_fonts(&ctx);
set_pstate(&ctx, STATE, Converter { points: Some(72.0), ..Converter::default() });
ctx.run_ui(Default::default(), |ui| show(&mut app, ui)).textures_delta.clear();
let mut out = ctx.run_ui(Default::default(), |ui| show(&mut app, ui));
out.textures_delta.clear();
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
// A label node carries its text as its value.
let label_of = |id: egui::accesskit::NodeId| nodes.iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.label().or(n.value())).map(str::to_string);
let buttons: Vec<String> =
nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Button).filter_map(|(_, n)| n.label().map(str::to_string)).collect();
for u in Unit::EAST_ASIAN {
let name = format!("Copy {}", u.label());
assert_eq!(buttons.iter().filter(|b| **b == name).count(), 1, "{name} in {buttons:?}");
// The row fits the 240 pt body of the default 260 pt floating panel, with 10 pt left for
// its scroll bar.
let button = nodes.iter().find(|(_, n)| n.label() == Some(name.as_str())).and_then(|(_, n)| n.bounds()).unwrap();
assert!(button.x1 <= 230.0, "{name} ends at {}", button.x1);
// The field of the row is labeled by the row's label.
let field = nodes
.iter()
.find(|(_, n)| n.role() != egui::accesskit::Role::Button && n.labelled_by().iter().any(|l| label_of(*l).as_deref() == Some(u.label())));
assert!(field.is_some(), "a field labeled {}", u.label());
}
}
#[test]
fn from_selection_with_nothing_selected_reports_it_and_keeps_the_length() {
let mut app = app();
app.run("select.none", json!({})).unwrap();
let mut st = Converter { points: Some(10.0), ..Converter::default() };
assert!(from_selection(&mut app, &mut st).is_err());
assert_eq!((st.points, st.size), (Some(10.0), None));
}
+15 -6
View File
@@ -82,6 +82,7 @@ impl VectorcraftApp {
slices: None,
print_tiling: None,
live_paint_gaps: None,
find_font: None,
hidden_chars: Default::default(),
spelling: Default::default(),
selection_marks: Default::default(),
@@ -89,7 +90,9 @@ impl VectorcraftApp {
selection_box: None,
selection_bounds: None,
content_bounds: None,
three_d_exportable: None,
pixel_aligned: None,
symbol_instances: None,
plugin_keys: Default::default(),
placed_keys: Default::default(),
cursors: Default::default(),
@@ -182,6 +185,8 @@ impl VectorcraftApp {
automation_roots: None,
synthetic_frame: false,
pending_plugin_install: None,
script_picked: Vec::new(),
script_picked_left_out: false,
pen_end: Default::default(),
host_iteration: 0,
#[cfg(test)]
@@ -354,8 +359,13 @@ impl VectorcraftApp {
// A panel's, a dialog's or the text input's commit journaled in the frame before.
crate::panels::actions::after_journaled_edit(self);
crate::scripts_menu::poll(self, ctx);
if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() {
// A script in `$.sleep` goes on when its time is up; until then the app can idle.
if self.session.script_running()
&& !self.session.script_waiting()
&& self.session.script_dialog().is_none()
&& self.session.script_picker().is_none()
{
// A script in `$.sleep` goes on when its time is up; until then the app can idle. A
// script at a file dialog goes on when the dialog answers, and `picks::poll` looks for that.
match self.session.script_sleep_left() {
Some(left) => ctx.request_repaint_after(left),
None => ctx.request_repaint(),
@@ -576,6 +586,7 @@ impl VectorcraftApp {
self.ime_caret_rect = None;
scrub::begin_frame(self, &ctx);
font_menu::end_stale_preview(self, &ctx);
font_menu::apply_preview_size(self, &ctx);
tools_float::track(self, &ctx);
// A selection move released over a panel ends before any panel sees the release (#2826).
canvas::release_over_panel(self, &ctx);
@@ -602,10 +613,6 @@ impl VectorcraftApp {
if self.ui.toolbar && self.ui.screen_mode < 3 {
tools_float::set_window_dock_zone(&ctx, ui.available_rect_before_wrap());
}
if !self.ui.tools_beside_canvas {
// A canvas-edge target left from before the setting was turned off docks nothing.
tools_float::clear_canvas_dock_zone(&ctx);
}
// Beside the canvas, docked Tools draws inside the canvas panel (`toolbar::show_beside_canvas`).
// So does Tools docked on the right, left of the panels.
if self.ui.toolbar && self.ui.screen_mode < 3 && ((!self.ui.tools_beside_canvas && !self.ui.toolbar_right) || self.ui.toolbar_pos.is_some()) {
@@ -628,6 +635,8 @@ impl VectorcraftApp {
plugin_runs::show(self, &ctx);
trace_runs::show(self, &ctx);
opening::show(self, &ctx);
// After every window this pass may open, and before the palette's field takes the keyboard.
panel_docking::close_overlays_for_modal(self, &ctx);
palette::show(self, &ctx);
// After every panel had its chance to draw in this pass.
crate::panels::three_d::end_stale_drag(self, &ctx);
+64 -10
View File
@@ -252,9 +252,7 @@ impl VectorcraftApp {
{
self.last_pathfinder = Some(op.to_string());
}
if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut") {
self.publish_clipboard();
}
let copied = r.is_ok() && self.publish_copy(id);
self.sync_views();
self.refresh_replace_font_warning(false);
// File › Revert replaces the document in its tab, keeps the tab's view and starts the tool afresh.
@@ -262,16 +260,13 @@ impl VectorcraftApp {
match &r {
Err(e) => self.ui.status = e.clone(),
Ok(v) => {
// Image Trace's notes (a large image traces more slowly, or was scaled down).
if id.starts_with("imageTrace.make")
&& let Some(w) = v["warnings"].as_array().and_then(|w| w.first()).and_then(Value::as_str)
{
self.ui.status = w.to_string();
if matches!(id, "imageTrace.make" | "imageTrace.makeAndExpand") {
self.show_trace_notes(v);
}
// A renamed spot color swatch stays the Color Guide's base; a deleted one ends the link.
panels::color_guide::after_command(self, id, &params, v, spot_base);
if id == "file.new" {
self.ui.status.clear();
self.status("");
// New Document's Pixel preview mode (Overprint Preview is the engine's).
if v["previewMode"] == "pixel" {
self.ui.view.pixel_preview = true;
@@ -280,7 +275,7 @@ impl VectorcraftApp {
// Choosing a data set, or stepping to one, clears the status bar. The reply's `warning`
// below then shows when no object is bound to a variable the data set has a value for.
if matches!(id, "dataset.select" | "dataset.next" | "dataset.prev") {
self.ui.status.clear();
self.status("");
}
// A font applied with Character's font menu or Find Font's Change becomes the newest recent font.
// Find Font's Change records the family the text now carries (any name of it is stored as its
@@ -312,9 +307,42 @@ impl VectorcraftApp {
}
}
}
// The message the Copy or Cut leaves is the one its clipboard formats' notes may replace.
if copied {
self.clipboard_publishing.ran_with_status(&self.ui);
}
r
}
/// After a Copy or Cut `id` that ran: offer what it copied to other apps
/// ([`Self::publish_clipboard`]) → whether `id` is one.
fn publish_copy(&mut self, id: &str) -> bool {
let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut");
if copy {
self.publish_clipboard(matches!(id, "edit.cut" | "artboard.cut"));
}
copy
}
/// Image Trace's notes in `reply` (a large image traces more slowly, or was scaled down): the
/// first of them and how many there are, with the rest for the message's hover. A trace that
/// made no paths shows its first note as it is. Without notes, the message an earlier trace's
/// notes left is cleared while nothing has set the status since, and any other message stays.
fn show_trace_notes(&mut self, reply: &Value) {
let notes = io::notes_of(reply);
let left = self.trace_runs.notes_status.take();
let Some(first) = notes.first() else {
io::clear_notes_left(self, left);
return;
};
let status = match reply["paths"].as_u64() {
Some(0) => first.clone(),
_ => crate::trace_runs::traced_with_notes(notes.len(), first),
};
io::show_with_notes(self, status, notes);
self.trace_runs.notes_status = Some((self.ui.status.clone(), self.ui.status_sets));
}
fn set_command_warning(&mut self, id: &str, warning: &str) {
self.ui.status = warning.to_string();
if id != "text.replaceFont" {
@@ -484,4 +512,30 @@ impl VectorcraftApp {
self.ui.status = s.into();
self.ui.status_sets = self.ui.status_sets.wrapping_add(1);
}
/// Begin the interaction a dialog or a panel previews on. Typing in progress is kept as its own
/// undo step first, and the warning of the preview that keeping it applied shows in the status
/// bar, as it does when a tool's drag begins. On an error no interaction begins, so the caller
/// runs no preview.
pub(crate) fn begin_interaction(&mut self, label: &str) -> Result<(), String> {
let warnings = self.session.begin_interaction_warned(label).map_err(|e| e.to_string())?;
self.show_warnings(warnings);
Ok(())
}
/// Keep typing in progress as one undo step and end the Type tool's typing session, with the
/// typing that Real-time Drawing off left unapplied applied first; its warning shows in the
/// status bar.
pub(crate) fn keep_typing(&mut self) -> Result<(), String> {
let warnings = self.session.keep_typing().map_err(|e| e.to_string())?;
self.show_warnings(warnings);
Ok(())
}
/// Each warning in the status bar in turn, as the tool's status requests show; the last stays.
fn show_warnings(&mut self, warnings: Vec<String>) {
for w in warnings {
self.status(w);
}
}
}
+48
View File
@@ -42,6 +42,10 @@ pub struct CanvasCache {
pub print_tiling: Option<PrintTilingCache>,
/// The gap lines View → Show Live Paint Gaps draws for (document uid, revision).
pub live_paint_gaps: Option<LivePaintGapsCache>,
/// Type → Find Font's list of the document's fonts and whether the document misses one, for a
/// version of the document's content and of the available fonts: the dialog reads them every
/// frame.
pub find_font: Option<FindFontCache>,
/// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame
/// that does not draw them drops them ([`canvas::show`]).
pub hidden_chars: canvas::HiddenChars,
@@ -61,9 +65,15 @@ pub struct CanvasCache {
pub selection_bounds: Option<((u64, u64), Option<vectorcraft_geom::Rect>)>,
/// [`VectorcraftApp::content_bounds`] for (document uid, revision).
pub content_bounds: Option<((u64, u64), Option<vectorcraft_geom::Rect>)>,
/// Whether the 3D and Materials panel's Export 3D Object button is available (a selected
/// object has a 3D effect that `assets.add3D` exports) for (document uid, revision).
pub three_d_exportable: Option<((u64, u64), bool)>,
/// The Transform panel's Align to Pixel Grid state (on, off or mixed, and whether every
/// selected object can be aligned) for (document uid, revision).
pub pixel_aligned: Option<((u64, u64), Option<PixelAligned>)>,
/// The symbol instances in the selection and its groups, for (document uid, revision): the
/// Properties and Symbols panels read them every frame.
pub symbol_instances: Option<((u64, u64), SymbolInstances)>,
/// [`CacheKey::plugins`] by document uid, with the plug-in revision
/// ([`vectorcraft_render::effects::plugin_revision`]) it was last checked at.
pub plugin_keys: std::collections::HashMap<u64, (u64, u64)>,
@@ -111,10 +121,48 @@ pub type SliceCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_doc::SliceArea
/// uid, revision).
pub type LivePaintGapsCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_tools::Overlay>>);
/// [`CanvasCache::find_font`]: the document's fonts as `text.fonts` lists them, and whether
/// [`vectorcraft_engine::cmd::fontfiles::missing_fonts`] finds any (`None` until it is asked).
#[derive(Clone, Debug)]
pub struct FindFontCache {
/// The document and the content and fonts the answers were worked out from.
pub key: FontsKey,
pub fonts: std::sync::Arc<Vec<serde_json::Value>>,
pub missing: Option<bool>,
}
/// A document's uid, a version of its content (compared by identity) and the font database's
/// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's
/// allocation, so a later version is never placed at the same address while the key is kept.
#[derive(Clone, Debug)]
pub struct FontsKey {
pub uid: u64,
pub doc: std::sync::Weak<vectorcraft_doc::Document>,
pub generation: u64,
}
impl PartialEq for FontsKey {
fn eq(&self, other: &Self) -> bool {
self.uid == other.uid && self.generation == other.generation && std::sync::Weak::ptr_eq(&self.doc, &other.doc)
}
}
/// [`CanvasCache::pixel_aligned`]: the selected objects' Align to Pixel Grid, on or off when they
/// agree and `None` when they differ, with whether every one can be aligned.
pub type PixelAligned = (Option<bool>, bool);
/// [`CanvasCache::symbol_instances`]: the symbol instances in the selection and its groups.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SymbolInstances {
/// Each instance's id, in the order the selection's subtrees list them.
pub ids: Vec<vectorcraft_doc::NodeId>,
/// One of them has appearance changes of its own (`symbol_overrides`).
pub changed: bool,
/// One of them has a scale, rotation or shear that Reset Transformation would change; measured
/// on the first read.
pub transformed: Option<bool>,
}
/// [`CanvasCache::print_tiling`]: the print tiling of (document uid, revision).
pub type PrintTilingCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_pdf::TilingPage>>);
+5 -5
View File
@@ -64,14 +64,14 @@ pub use overlays::SharedPaths;
#[cfg(test)]
use overlays::selected_anchor;
use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay};
pub use panes::Panes;
pub use panes::{Layout as TileLayout, Panes};
pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area};
pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
use raster::{changed_pixels, frame_ppp, pixel_region, upload};
pub use selection_marks::SelectionMarks;
#[cfg(test)]
pub(crate) use task_bar::chip_paints;
use task_bar::task_bar;
#[cfg(test)]
pub(crate) use task_bar::{chip_paints, images_with_other_art};
pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type};
#[cfg(test)]
use tool_overlays::{DIAL_RADIUS, HiddenMarks};
@@ -175,7 +175,7 @@ enum Drag {
},
/// A Selection tool move over a panel or toolbar: the art waits where it last moved on the
/// canvas, and the panels get it ([`widgets::PanelDrag::Art`]) if it is released there. Back
/// on the canvas the move goes on, as in Illustrator (#2826).
/// on the canvas the move goes on (#2826).
Art,
/// Fingers making a touch gesture ([`crate::touch`]): the first one's press does nothing.
Gesture,
@@ -832,7 +832,7 @@ fn frame_options(
// Type › Highlight Substituted Fonts: pink behind text in a substitute font.
highlight_substituted_fonts: app.session.prefs.highlight_substituted_fonts,
// General › Anti-aliased Artwork: off, edges are hard on screen (raster effects and
// pattern tiles stay smooth), as in Illustrator.
// pattern tiles stay smooth).
anti_alias: if app.session.prefs.anti_aliased_artwork { vectorcraft_render::AntiAlias::Art } else { vectorcraft_render::AntiAlias::None },
progressive_placed: true,
trace_views: true,
+5 -4
View File
@@ -75,10 +75,11 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons
}
return;
}
// A symbol from the Symbols panel: an instance centred where it is dropped, on art or not.
if let widgets::PanelDrag::Symbol(name) = &*d {
// A symbol from the Symbols panel: an instance centred where it is dropped, on art or not. A
// symbol of another document is added to this one first.
if let widgets::PanelDrag::Symbol { document, name } = &*d {
let at = xf.to_doc(pos);
if let Err(e) = app.run("symbol.place", json!({"name": name, "x": at.x, "y": at.y})) {
if let Err(e) = app.run("symbol.placeFromDocument", json!({"sourceDocument": document, "name": name, "x": at.x, "y": at.y})) {
app.status(e);
}
return;
@@ -155,7 +156,7 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons
// Art dragged back onto the canvas: its move was already dropped. (A symbol was placed
// above.)
widgets::PanelDrag::Art(_)
| widgets::PanelDrag::Symbol(_)
| widgets::PanelDrag::Symbol { .. }
| widgets::PanelDrag::LibrarySymbol { .. }
| widgets::PanelDrag::LibraryGraphic { .. } => return,
// A Libraries panel style or group only moves within that panel.
+10 -1
View File
@@ -317,7 +317,7 @@ pub(super) fn drag_art_out(app: &VectorcraftApp, ui: &Ui, resp: &egui::Response,
// The art the drag started with: the release rolls the move back to it, and an Alt-copy's
// copies, selected while it previews, go with that.
let ids = it.selection.objects.clone();
egui::DragAndDrop::set_payload(ui.ctx(), widgets::PanelDrag::Art(ids));
widgets::drag_art(ui.ctx(), st.uid, ids);
true
}
@@ -423,6 +423,7 @@ pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result<Ve
for r in reqs {
match r {
vectorcraft_engine::UiRequest::Dialog(kind, p) => crate::dialogs::open_tool_dialog(app, &kind, p),
vectorcraft_engine::UiRequest::Panel(panel) => activate_panel(app, &panel),
vectorcraft_engine::UiRequest::SwitchTool(t) => app.select_tool(&t),
vectorcraft_engine::UiRequest::Status(msg) => app.status(msg),
vectorcraft_engine::UiRequest::Place(p) => crate::place::place_from_cursor(app, &p),
@@ -442,3 +443,11 @@ pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result<Ve
Err(e) => app.status(e.to_string()),
}
}
/// Show and select `panel` where it is (`window.panel.activate`): a panel already on show stays on
/// show, and a dock hidden by Tab shows again.
fn activate_panel(app: &mut VectorcraftApp, panel: &str) {
if let Err(e) = app.run("window.panel.activate", serde_json::json!({ "panel": panel })) {
app.status(e);
}
}
+1 -1
View File
@@ -432,7 +432,7 @@ pub(super) fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option<Point>, s
let sy = left.top() + d;
clip_left.line_segment([pos2(left.right() - len, sy), pos2(left.right(), sy)], Stroke::new(1.0, t.ruler_tick));
if let Some(text) = label {
// Vertical labels read top-to-bottom, one digit per line like Illustrator.
// Vertical labels read top-to-bottom, one digit per line.
let top = sy + 2.0;
if top < filled_to {
return;
+1 -1
View File
@@ -25,7 +25,7 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
/// The Home screen's column: welcome, New / Open, Recent Files, Learn, presets and community links.
fn home_content(app: &mut VectorcraftApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
// The welcome and the New / Open buttons sit centred, as PhotoCraft's Home screen does (#4684).
// The welcome and the New / Open buttons sit centred (#4684).
ui.vertical_centered(|ui| {
ui.label(egui::RichText::new(tl!("Welcome to VectorCraft")).font(theme::semibold(26.0)).color(t.text));
ui.add_space(4.0);
+129 -22
View File
@@ -1,5 +1,6 @@
//! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document
//! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its
//! area, in a grid, side by side or stacked; the 2-up to 6-up layouts show that many and leave the
//! rest under their tabs ([`Layout`]). The current document's pane is the canvas ([`super::show`]). Each other pane draws its
//! document from a render of its own, with its artboards, guides and selected objects, and a press
//! in it makes its document the current one. A Selection drag released in it drops the dragged
//! artwork into its document ([`crate::document_drag::drop_on_pane`]). Each view Window › New
@@ -39,6 +40,9 @@ pub struct Panes {
pending: HashMap<Slot, CacheKey>,
/// The panes the last frame drew, as (window, pane rect).
pub(crate) last: Vec<(Win, egui::Rect)>,
/// The slots of `last`'s windows, in the same order: which windows they were, as document
/// indices shift when a document closes.
last_slots: Vec<Option<Slot>>,
/// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and
/// center the fit gave.
fits: HashMap<Slot, (egui::Vec2, f64, Point)>,
@@ -50,6 +54,7 @@ impl Panes {
self.shown.clear();
self.pending.clear();
self.last.clear();
self.last_slots.clear();
self.fits.clear();
}
@@ -162,37 +167,123 @@ fn render_pane(
img
}
/// The grid of `n` panes in `area`, filled row by row: as many columns as the square root of `n`
/// rounded up, and as many rows as those columns need. The panes meet edge to edge and cover
/// `area`; the spare cells of the last row stay empty.
pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec<egui::Rect> {
if n == 0 {
return vec![];
/// How Tile lays out the panes (`window.arrange.tile`'s `layout`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Layout {
/// A grid: as many columns as the square root of the number of panes rounded up.
#[default]
Grid,
/// Side by side in one row, each pane as tall as the document area.
Vertical,
/// Stacked in one column, each pane as wide as the document area.
Horizontal,
/// At most this many panes (2, 3, 4 or 6); the other windows stay under their tabs.
Up(usize),
}
impl Layout {
/// Each layout with its name in `layout`, in the order the menus list them.
pub(crate) const ALL: [(&'static str, Layout); 7] = [
("grid", Layout::Grid),
("vertical", Layout::Vertical),
("horizontal", Layout::Horizontal),
("2up", Layout::Up(2)),
("3up", Layout::Up(3)),
("4up", Layout::Up(4)),
("6up", Layout::Up(6)),
];
/// The layout's name in `layout`.
pub(crate) fn name(self) -> &'static str {
Self::ALL.iter().find(|(_, l)| *l == self).map_or("grid", |(n, _)| n)
}
/// The layout `p`'s `layout` names, the grid without one. Any other value is an error.
pub(crate) fn from_params(p: &serde_json::Value) -> Result<Layout, String> {
let key = "layout";
match p.get(key) {
None => Ok(Layout::Grid),
Some(v) => v
.as_str()
.and_then(|s| Self::ALL.iter().find(|(n, _)| *n == s))
.map(|(_, l)| *l)
.ok_or_else(|| format!("`{key}` must be one of {}", Self::ALL.map(|(n, _)| n).join(", "))),
}
}
/// How many of `n` windows the layout gives a pane.
fn panes(self, n: usize) -> usize {
match self {
Layout::Up(k) => n.min(k),
_ => n,
}
}
/// How many columns the layout puts `n` panes in.
fn columns(self, n: usize) -> usize {
match self {
Layout::Grid => grid_columns(n),
Layout::Vertical => n,
Layout::Horizontal => 1,
Layout::Up(k) if k <= 3 => n,
Layout::Up(k) => grid_columns(k).min(n),
}
}
}
/// The square root of `n` rounded up.
fn grid_columns(n: usize) -> usize {
let mut cols = 1;
while cols * cols < n {
cols += 1;
}
cols
}
/// The `n` panes `layout` places in `area`, filled row by row, in as many rows as its columns
/// need (the grid: as many columns as the square root of `n` rounded up). The panes meet edge to
/// edge and cover `area`; the spare cells of the last row stay empty.
pub(crate) fn layout_cells(layout: Layout, n: usize, area: egui::Rect) -> Vec<egui::Rect> {
if n == 0 {
return vec![];
}
let cols = layout.columns(n).clamp(1, n);
let rows = n.div_ceil(cols);
let x = |c: usize| if c == cols { area.right() } else { area.left() + area.width() * c as f32 / cols as f32 };
let y = |r: usize| if r == rows { area.bottom() } else { area.top() + area.height() * r as f32 / rows as f32 };
(0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect()
}
/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own,
/// each fitted to its pane. With fewer than two windows open (when the menu item is grayed out) it
/// leaves the view and `tiled` as they are. The windows floating come back under the tabs for it.
pub(crate) fn tile(app: &mut VectorcraftApp) -> Result<serde_json::Value, String> {
/// The windows of `docked` (in tab order) that `layout` gives a pane: all of them, or as many of
/// the first ones as it shows, with the current window `active` in the last pane when it is not
/// among them.
pub(crate) fn shown_windows(layout: Layout, docked: &[Win], active: Option<Win>) -> Vec<Win> {
let k = layout.panes(docked.len());
let mut shown = docked[..k].to_vec();
if let (Some(a), Some(last)) = (active.filter(|a| !shown.contains(a) && docked.contains(a)), shown.last_mut()) {
*last = a;
}
shown
}
/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own
/// as `layout` places them (the grid without one), each fitted to its pane. With fewer than two
/// windows open (when the menu item is grayed out) it leaves the view, `tiled` and the layout as
/// they are. The windows floating come back under the tabs for it. A `layout` that is not one of
/// [`Layout::ALL`]'s names is an error.
pub(crate) fn tile(app: &mut VectorcraftApp, p: &serde_json::Value) -> Result<serde_json::Value, String> {
let layout = Layout::from_params(p)?;
app.sync_views();
let n = crate::doc_windows::windows(app).len();
if n < 2 {
return Ok(json!({"tiled": app.ui.tiled, "panes": n}));
return Ok(json!({"tiled": app.ui.tiled, "panes": n, "layout": app.ui.tile_layout.name()}));
}
crate::doc_windows::dock_all(app);
app.ui.tiled = true;
app.ui.tile_layout = layout;
app.ui.home = None;
crate::doc_windows::unfit_all(app);
Ok(json!({"tiled": app.ui.tiled, "panes": n}))
Ok(json!({"tiled": app.ui.tiled, "panes": layout.panes(n), "layout": layout.name()}))
}
/// `window.arrange.consolidateAllWindows`: one document at a time again, under its tab, the
@@ -220,27 +311,43 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
app.canvas.panes.clear();
}
app.canvas.panes.last.clear();
app.canvas.panes.last_slots.clear();
return false;
}
// The current window's pane is the canvas, unless it is a floating one.
let active = crate::doc_windows::current(app).filter(|a| docked.contains(a));
// The 2-up to 6-up layouts leave the windows past their panes under the tabs.
let layout = app.ui.tile_layout;
let shown = shown_windows(layout, &docked, active);
app.sync_views();
let live: Vec<Slot> = crate::doc_windows::windows(app).into_iter().filter_map(|w| slot(app, w)).collect();
// The renders of the panes and the floating windows stay; a window under its tab has none.
let live: Vec<Slot> =
crate::doc_windows::windows(app).into_iter().filter(|w| shown.contains(w) || !docked.contains(w)).filter_map(|w| slot(app, w)).collect();
app.canvas.panes.shown.retain(|s, _| live.contains(s));
app.canvas.panes.pending.retain(|s, _| live.contains(s));
app.canvas.panes.fits.retain(|s, _| live.contains(s));
// A window opened, closed, floated or docked changes the grid, and so does coming back to the
// panes from one window: each window fits its new pane.
if app.canvas.panes.last.iter().map(|(w, _)| *w).ne(docked.iter().copied()) {
for w in &docked {
if let Some(v) = crate::doc_windows::view_mut(app, *w) {
v.fitted = false;
}
// A window that moved to another pane fits it, and so does a window whose pane changed place or
// size because a window opened, closed, floated or docked, or because the panes came back from
// one window. A window that keeps its pane keeps its zoom and scroll, as when a tab brings its
// window into the last pane of a 2-up to 6-up layout, or when 6-Up loses its sixth document.
// Windows are compared by their slots, since a closed document shifts the indices of the
// documents after it, and panes by their place in the layout.
let before = std::mem::take(&mut app.canvas.panes.last_slots);
let now: Vec<Option<Slot>> = shown.iter().map(|w| slot(app, *w)).collect();
let unit = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(1.0, 1.0));
let (cells_before, cells_now) = (layout_cells(layout, before.len(), unit), layout_cells(layout, now.len(), unit));
for (i, (w, s)) in shown.iter().zip(&now).enumerate() {
if s.is_some() && before.get(i) == Some(s) && cells_before.get(i) == cells_now.get(i) {
continue;
}
if let Some(v) = crate::doc_windows::view_mut(app, *w) {
v.fitted = false;
}
}
app.canvas.panes.last_slots = now;
let t = Tokens::get(ui.ctx());
let ppp = ui.ctx().pixels_per_point();
let cells: Vec<(Win, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect();
let cells: Vec<(Win, egui::Rect)> = shown.iter().copied().zip(layout_cells(layout, shown.len(), ui.available_rect_before_wrap())).collect();
let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect();
let unfitted = refit_resized(app, &areas);
let mut activate = None;
+337 -2
View File
@@ -43,6 +43,11 @@ fn button(pos: Pos2, pressed: bool) -> egui::Event {
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }
}
/// Tile's grid of `n` panes in `area`.
fn cells(n: usize, area: egui::Rect) -> Vec<egui::Rect> {
layout_cells(Layout::Grid, n, area)
}
/// The documents' indices in the panes the last frame drew, and the panes.
fn panes(app: &VectorcraftApp) -> (Vec<usize>, Vec<egui::Rect>) {
app.canvas.panes.last.iter().map(|(w, r)| (w.0, *r)).unzip()
@@ -84,6 +89,336 @@ fn cells_tile_the_area_edge_to_edge() {
}
}
/// The distinct left and top edges of `c`: how many columns and rows its panes take.
fn columns_and_rows(c: &[egui::Rect]) -> (usize, usize) {
let lefts: BTreeSet<u32> = c.iter().map(|r| r.left().to_bits()).collect();
let tops: BTreeSet<u32> = c.iter().map(|r| r.top().to_bits()).collect();
(lefts.len(), tops.len())
}
#[test]
fn each_tile_layout_places_its_panes_edge_to_edge() {
let area = egui::Rect::from_min_size(pos2(10.0, 35.0), vec2(1001.0, 703.0));
let cases = [
(Layout::Vertical, 3, (3, 1)),
(Layout::Vertical, 7, (7, 1)),
(Layout::Horizontal, 3, (1, 3)),
(Layout::Up(2), 2, (2, 1)),
(Layout::Up(3), 3, (3, 1)),
(Layout::Up(3), 2, (2, 1)),
(Layout::Up(4), 4, (2, 2)),
(Layout::Up(4), 3, (2, 2)),
(Layout::Up(6), 6, (3, 2)),
(Layout::Up(6), 4, (3, 2)),
(Layout::Up(6), 2, (2, 1)),
];
for (layout, n, shape) in cases {
let c = layout_cells(layout, n, area);
assert_eq!(c.len(), n);
assert_eq!(columns_and_rows(&c), shape, "{layout:?} with {n} panes: columns and rows");
assert_eq!(c[0].min, area.min, "{layout:?}: the first pane starts at the corner");
let right = c.iter().map(|r| r.right()).fold(f32::MIN, f32::max);
let bottom = c.iter().map(|r| r.bottom()).fold(f32::MIN, f32::max);
assert_eq!((right, bottom), (area.right(), area.bottom()), "{layout:?} with {n} panes reaches the far edges");
for (i, r) in c.iter().enumerate() {
assert!(r.width() > 0.0 && r.height() > 0.0 && area.contains_rect(*r), "{layout:?}: {r:?}");
for o in &c[i + 1..] {
assert!(r.intersect(*o).area() <= 0.0, "{layout:?} panes overlap: {r:?} {o:?}");
}
}
}
assert!(layout_cells(Layout::Up(2), 0, area).is_empty());
}
#[test]
fn tile_layouts_line_the_documents_up_side_by_side_or_stacked() {
let mut app = app_with(3);
let ctx = egui::Context::default();
let reply = app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap();
assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "vertical"}));
frame(&mut app, &ctx, vec![]);
let (docs, rects) = panes(&app);
assert_eq!(docs, [0, 1, 2]);
assert!(rects.windows(2).all(|p| p[0].top() == p[1].top() && p[0].height() == p[1].height() && p[0].right() == p[1].left()), "{rects:?}");
let reply = app.run("window.arrange.tile", json!({"layout": "horizontal"})).unwrap();
assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "horizontal"}));
frame(&mut app, &ctx, vec![]);
let (docs, rects) = panes(&app);
assert_eq!(docs, [0, 1, 2]);
assert!(rects.windows(2).all(|p| p[0].left() == p[1].left() && p[0].width() == p[1].width() && p[0].bottom() == p[1].top()), "{rects:?}");
// Each document fits its new pane.
let artboard = Rect::new(0.0, 0.0, 400.0, 300.0);
let canvas = app.canvas_rect.unwrap();
for (i, r) in docs.iter().zip(&rects) {
let shown = if *i == 2 { canvas } else { view_rects(&app, *r, ctx.pixels_per_point()).1 };
let v = app.views[*i];
assert!(v.fitted && (v.zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9, "document {i} fits its pane: {v:?}");
}
assert_eq!(crate::control::inspect(&app, &ctx)["tileLayout"], json!("horizontal"));
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap()["layout"], json!("grid"), "Tile without a layout is the grid");
}
#[test]
fn n_up_shows_that_many_documents_and_keeps_the_rest_under_their_tabs() {
let mut app = app_with(5);
let ctx = egui::Context::default();
assert_eq!(app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "2up"}));
frame(&mut app, &ctx, vec![]);
assert_eq!(panes(&app).0, [0, 4], "the current document takes the last pane");
app.run("document.activate", json!({"index": 1})).unwrap();
frame(&mut app, &ctx, vec![]);
assert_eq!(panes(&app).0, [0, 1], "the first documents in tab order");
let second = (app.session.documents()[1].uid, 1);
app.run("document.activate", json!({"index": 0})).unwrap();
frame(&mut app, &ctx, vec![]);
assert!(app.canvas.panes.shown.contains_key(&second), "the second document is rendered for its pane");
app.run("document.activate", json!({"index": 3})).unwrap();
frame(&mut app, &ctx, vec![]);
let (docs, rects) = panes(&app);
assert_eq!(docs, [0, 3], "a document chosen under its tab comes into the last pane");
assert!(!app.canvas.panes.shown.contains_key(&second), "a document under its tab keeps no render");
let artboard = Rect::new(0.0, 0.0, 400.0, 300.0);
let shown = view_rects(&app, rects[0], ctx.pixels_per_point()).1;
assert!((app.views[0].zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9);
assert!(app.canvas_rect.is_some_and(|c| rects[1].contains_rect(c)), "the current document's pane is the canvas");
// A document brought into the last pane leaves the first pane's zoom as it is.
app.views[0].zoom *= 2.0;
let zoomed = app.views[0].zoom;
app.run("document.activate", json!({"index": 2})).unwrap();
frame(&mut app, &ctx, vec![]);
assert_eq!(panes(&app).0, [0, 2]);
assert_eq!(app.views[0].zoom, zoomed, "the document that stayed in its pane keeps its zoom");
let last = app.canvas_rect.unwrap();
assert!((app.views[2].zoom - fit_zoom(last, artboard, 0.0, 1.0)).abs() < 1e-9, "the document brought in fits its pane");
assert_eq!(app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap()["panes"], json!(4));
frame(&mut app, &ctx, vec![]);
let (docs, rects) = panes(&app);
assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3], (2, 2)));
assert_eq!(app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap()["panes"], json!(5), "6-Up with five documents shows them all");
frame(&mut app, &ctx, vec![]);
let (docs, rects) = panes(&app);
assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2)));
assert_eq!(app.run("window.arrange.tile", json!({"layout": "3up"})).unwrap()["panes"], json!(3));
frame(&mut app, &ctx, vec![]);
let (docs, rects) = panes(&app);
assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2], (3, 1)));
app.run("document.activate", json!({"index": 4})).unwrap();
frame(&mut app, &ctx, vec![]);
assert_eq!(panes(&app).0, [0, 1, 4]);
}
/// A document closed before the panes shifts the indices of the ones after it: the document that
/// moves into another pane fits it.
#[test]
fn closing_a_document_in_an_n_up_layout_fits_the_documents_that_change_panes() {
let mut app = app_with(4);
let ctx = egui::Context::default();
app.run("document.activate", json!({"index": 1})).unwrap();
app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap();
frame(&mut app, &ctx, vec![]);
app.run("document.activate", json!({"index": 3})).unwrap();
frame(&mut app, &ctx, vec![]);
assert_eq!(panes(&app).0, [0, 3]);
let moving = app.session.documents()[1].uid;
// The second document's view, under its tab, is zoomed away from its fit.
app.views[1].zoom *= 3.0;
app.run("file.close", json!({"index": 0})).unwrap();
frame(&mut app, &ctx, vec![]);
let (docs, rects) = panes(&app);
assert_eq!(docs, [0, 2], "the former second document is first now, the current one stays last");
assert_eq!(app.session.documents()[0].uid, moving);
let area = view_rects(&app, rects[0], ctx.pixels_per_point()).1;
let v = app.views[0];
assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its new pane: {v:?}");
}
/// 6-Up keeps its three columns and two rows with five documents: closing the sixth leaves the
/// others in their panes with the zoom they had. Side by side, closing one widens every pane, and
/// each document fits its new pane.
#[test]
fn closing_a_document_keeps_the_zoom_of_the_documents_whose_panes_stay() {
let mut app = app_with(6);
let ctx = egui::Context::default();
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap();
frame(&mut app, &ctx, vec![]);
assert_eq!(panes(&app).0, [0, 1, 2, 3, 4, 5]);
app.views[1].zoom *= 2.0;
let zoomed = app.views[1].zoom;
app.run("file.close", json!({"index": 5})).unwrap();
frame(&mut app, &ctx, vec![]);
let (docs, rects) = panes(&app);
assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2)));
assert_eq!(app.views[1].zoom, zoomed, "the document that kept its pane keeps its zoom");
let mut app = app_with(3);
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap();
frame(&mut app, &ctx, vec![]);
app.views[1].zoom *= 2.0;
app.run("file.close", json!({"index": 2})).unwrap();
frame(&mut app, &ctx, vec![]);
let (docs, rects) = panes(&app);
assert_eq!(docs, [0, 1]);
let area = view_rects(&app, rects[1], ctx.pixels_per_point()).1;
let v = app.views[1];
assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its wider pane: {v:?}");
}
#[test]
fn tile_refuses_a_layout_it_does_not_have() {
let mut app = app_with(3);
for bad in [json!("5up"), json!("Vertical"), json!(3), json!(null), json!({})] {
let err = app.run("window.arrange.tile", json!({"layout": bad})).unwrap_err();
assert_eq!(err, "`layout` must be one of grid, vertical, horizontal, 2up, 3up, 4up, 6up", "{bad}");
assert!(!app.ui.tiled && app.ui.tile_layout == Layout::Grid, "{bad}: the view stays as it is");
}
app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap();
assert!(app.run("window.arrange.tile", json!({"layout": "diagonal"})).is_err());
assert_eq!(app.ui.tile_layout, Layout::Vertical, "a refused layout leaves the tiled one");
// With one document the layout is still checked, and nothing changes.
let mut one = app_with(1);
assert!(one.run("window.arrange.tile", json!({"layout": "7up"})).is_err());
assert_eq!(one.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"}));
}
#[test]
fn the_tile_items_check_the_layout_the_panes_show() {
let mut app = app_with(3);
let checked = |app: &VectorcraftApp, layout: Option<&str>| {
let p = layout.map_or(serde_json::Value::Null, |l| json!({"layout": l}));
crate::menus::checked(app, "window.arrange.tile", &p)
};
assert_eq!(checked(&app, None), Some(false), "not tiled");
app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap();
assert_eq!(checked(&app, Some("4up")), Some(true));
assert_eq!(checked(&app, None), Some(false));
assert_eq!(checked(&app, Some("2up")), Some(false));
app.run("window.arrange.tile", json!({})).unwrap();
assert_eq!(checked(&app, None), Some(true), "Tile is the grid");
app.run("window.arrange.consolidateAllWindows", json!({})).unwrap();
assert_eq!(checked(&app, None), Some(false));
// Window › Arrange lists every layout, after Cascade and before Float in Window.
let window = crate::menus::menu_tree().into_iter().find(|(t, _)| *t == "Window").map(|(_, items)| items).unwrap();
let arrange = window
.into_iter()
.find_map(|i| match i {
crate::menus::Item::Sub("Arrange", items) => Some(items),
_ => None,
})
.unwrap();
let labels: Vec<&str> = arrange
.iter()
.filter_map(|i| match i {
crate::menus::Item::Cmd(l, ..) => Some(*l),
_ => None,
})
.collect();
assert_eq!(
labels,
[
"Cascade",
"Tile",
"Tile All Vertically",
"Tile All Horizontally",
"2-Up Layout",
"3-Up Layout",
"4-Up Layout",
"6-Up Layout",
"Float in Window",
"Float All in Windows",
"Consolidate All Windows"
]
);
// Each item's params run, as the menu sends them.
for item in &arrange {
if let crate::menus::Item::Cmd(_, "window.arrange.tile", p) = item {
let p = if p.is_null() { json!({}) } else { p.clone() };
assert!(app.run("window.arrange.tile", p.clone()).is_ok(), "{p}");
}
}
}
/// One frame of the application bar with screen-reader nodes on → the nodes.
fn app_bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<egui::accesskit::Node> {
app_bar_frame_in(app, ctx, events, 1400.0)
}
/// [`app_bar_frame`] on a window `width` points wide.
fn app_bar_frame_in(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>, width: f32) -> Vec<egui::accesskit::Node> {
let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(width, 800.0));
let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::app_bar(app, ui));
out.textures_delta.clear();
out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default()
}
/// The center of the application bar's node whose label, without its leading spaces, is `name`
/// (or starts with it and a shortcut in parentheses).
fn app_bar_node(nodes: &[egui::accesskit::Node], name: &str) -> Option<Pos2> {
let named = |l: &str| l.trim_start().strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.trim_start().starts_with('('));
let b = nodes.iter().find(|n| n.label().is_some_and(named))?.bounds()?;
Some(pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32))
}
/// Click the application bar's node labeled `name`.
fn click_app_bar(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) {
let at = app_bar_node(&app_bar_frame(app, ctx, vec![]), name).unwrap_or_else(|| panic!("{name} is drawn"));
app_bar_frame(app, ctx, vec![egui::Event::PointerMoved(at), button(at, true)]);
app_bar_frame(app, ctx, vec![button(at, false)]);
}
#[test]
fn the_arrange_documents_button_tiles_and_consolidates() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = app_with(3);
let ctx = egui::Context::default();
ctx.enable_accesskit();
crate::theme::install_fonts(&ctx);
app_bar_frame(&mut app, &ctx, vec![]);
let nodes = app_bar_frame(&mut app, &ctx, vec![]);
let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands"));
let (arrange, search) = (arrange.expect("the application bar has Arrange Documents"), search.expect("the search shows"));
assert!(arrange.x > search.x && (arrange.y - search.y).abs() < 1.0, "right of the search: {arrange:?}, {search:?}");
click_app_bar(&mut app, &ctx, "Arrange Documents");
let menu = app_bar_frame(&mut app, &ctx, vec![]);
for item in [
"Consolidate All Windows",
"Tile",
"Tile All Vertically",
"Tile All Horizontally",
"2-Up Layout",
"3-Up Layout",
"4-Up Layout",
"6-Up Layout",
] {
assert!(app_bar_node(&menu, item).is_some(), "the menu lists {item}");
}
click_app_bar(&mut app, &ctx, "Tile All Vertically");
assert!(app.ui.tiled && app.ui.tile_layout == Layout::Vertical, "{}", app.ui.status);
click_app_bar(&mut app, &ctx, "Arrange Documents");
click_app_bar(&mut app, &ctx, "Consolidate All Windows");
assert!(!app.ui.tiled);
}
/// As the application bar narrows, Arrange Documents goes before the search.
#[test]
fn a_narrow_application_bar_keeps_search_before_arrange_documents() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = app_with(3);
let ctx = egui::Context::default();
ctx.enable_accesskit();
crate::theme::install_fonts(&ctx);
let mut search_alone = false;
for width in (200..=1400).rev().step_by(4) {
app_bar_frame_in(&mut app, &ctx, vec![], width as f32);
let nodes = app_bar_frame_in(&mut app, &ctx, vec![], width as f32);
let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands").is_some());
assert!(search || !arrange, "{width} pt: Arrange Documents shows without the search");
search_alone |= search && !arrange;
}
assert!(search_alone, "some width shows the search without Arrange Documents");
}
#[test]
fn tile_shows_a_pane_for_each_document_fitted_to_it() {
let mut app = app_with(3);
@@ -91,7 +426,7 @@ fn tile_shows_a_pane_for_each_document_fitted_to_it() {
frame(&mut app, &ctx, vec![]);
assert!(panes(&app).0.is_empty(), "documents open under their tabs");
let tabbed = app.canvas_rect.unwrap();
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3}));
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"}));
frame(&mut app, &ctx, vec![]);
let (docs, rects) = panes(&app);
assert_eq!(docs, [0, 1, 2]);
@@ -454,7 +789,7 @@ fn arrange_items_follow_the_open_documents() {
fn tile_with_one_document_leaves_the_next_one_under_its_tab() {
let mut app = app_with(1);
let ctx = egui::Context::default();
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1}));
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"}));
assert!(!app.ui.tiled);
assert!(!enabled(&app, "window.arrange.consolidateAllWindows"));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
+26 -4
View File
@@ -92,6 +92,31 @@ fn smooth_tool_on_paths(app: &VectorcraftApp, ctx: &egui::Context) -> bool {
found
}
/// Whether the selection holds images together with other objects, for which the bar offers Make
/// Clipping Mask: at least one selected object is an image and at least one is not (a selected id
/// with no object counts as not an image). The walk stops once it has seen both. The answer is kept
/// in `ctx` for the document's revision, as [`smooth_tool_on_paths`] keeps its own.
pub(crate) fn images_with_other_art(st: &vectorcraft_engine::DocState, ctx: &egui::Context) -> bool {
let id = task_bar_id().with("mixed");
let key = (st.uid, st.revision);
if let Some((k, found)) = ctx.data(|d| d.get_temp::<((u64, u64), bool)>(id))
&& k == key
{
return found;
}
let (mut image, mut other) = (false, false);
let found = st.selection.objects.iter().any(|id| {
if st.doc.node(*id).is_some_and(|o| matches!(o.kind, NodeKind::Image(_))) {
image = true;
} else {
other = true;
}
image && other
});
ctx.data_mut(|d| d.insert_temp(id, (key, found)));
found
}
/// Whether the bar shows its blank canvas actions, Draw (Pencil) and Place Image: a selection tool is
/// in use and the active document has no artwork, only layers and guides.
fn blank_canvas(app: &VectorcraftApp) -> bool {
@@ -192,10 +217,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) {
_ => None,
});
// Images and vector art selected together: a clipping mask is the likely next step.
let mixed = n > 1 && {
let images = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).filter(|o| matches!(o.kind, NodeKind::Image(_))).count();
images > 0 && images < n
};
let mixed = n > 1 && images_with_other_art(st, ui.ctx());
// An Image Trace object: the group the engine names "Image Trace", its source image first.
let is_trace = is_group
&& first.as_ref().is_some_and(|f| {
+291 -3
View File
@@ -1647,6 +1647,37 @@ fn switch_selection_and_drawing_modes_command() {
}
}
/// Select Last Selection Tool: the Selection tool before any selection tool is chosen, then the
/// one of Selection, Direct Selection and Group Selection chosen last; Magic Wand and Lasso don't
/// count. Running it again keeps that tool, and it changes no art, selection or undo history.
#[test]
fn select_last_selection_tool_command() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone();
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
let last = |app: &mut VectorcraftApp| app.run("tool.selectLastSelection", json!({})).unwrap();
let state = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
(st.doc.clone(), st.selection.clone(), st.history.undo.len())
};
app.select_tool("pen");
let before = state(&app);
assert_eq!((last(&mut app), app.session.tool_id()), (json!({"tool": "selection"}), "selection"), "none chosen yet: Selection");
for id in ["directSelection", "groupSelection", "selection"] {
app.select_tool(id);
app.select_tool("pen");
assert_eq!(last(&mut app), json!({"tool": id}), "{id}");
}
app.select_tool("directSelection");
for other in ["magicWand", "lasso", "rectangle", "hand"] {
app.select_tool(other);
}
assert_eq!(last(&mut app), json!({"tool": "directSelection"}), "Magic Wand and Lasso are not remembered");
assert_eq!(last(&mut app), json!({"tool": "directSelection"}), "again: the same tool, no cycling");
assert!(state(&app) == before, "no art, selection or undo step changes");
}
/// A Switch Selection and Drawing Modes whose tool choice fails returns the error, in both
/// directions: the tool stays, the drawing tool to return to stays, and no undo step is added.
#[test]
@@ -6869,10 +6900,136 @@ fn hidden_char_marks(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<Shape
let blue = Color32::from_rgb(0x4f, 0x9d, 0xff);
shapes(app, ctx)
.into_iter()
.filter(|s| matches!(s, Shape::Circle(c) if c.fill == blue) || matches!(s, Shape::Text(t) if t.fallback_color == blue))
.filter(|s| match s {
Shape::Circle(c) => c.fill == blue || c.stroke.color == blue,
Shape::Text(t) => t.fallback_color == blue,
Shape::LineSegment { stroke, .. } => stroke.color == blue,
Shape::Path(p) => p.stroke.color == egui::epaint::ColorMode::Solid(blue),
_ => false,
})
.collect()
}
/// Show Hidden Characters marks each tab, nonbreaking space, narrow nonbreaking space, space of
/// a set width and discretionary hyphen with a mark of its kind, a plain space with a dot, and
/// a tab's arrow spans the tab's advance to its stop.
#[test]
fn hidden_characters_mark_tabs_nonbreaking_spaces_and_discretionary_hyphens() {
use super::tool_overlays::CharMark::*;
let text = "a b\tc\u{00A0}d\u{202F}e\u{2003}f\u{2009}g\u{200A}h\u{00AD}i";
let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 50.0), text, vectorcraft_doc::CharStyle::default());
let marks = HiddenMarks::of(&t);
let kinds: Vec<_> = marks.chars.iter().map(|c| c.0).collect();
assert_eq!(kinds, [Tab, NoBreakSpace, NarrowNoBreakSpace, FixedSpace, FixedSpace, FixedSpace, DiscretionaryHyphen]);
assert_eq!(marks.spaces.len(), 1, "only the plain space has a dot");
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
let tab = lay.glyphs.iter().find(|g| text[g.byte..].starts_with('\t')).unwrap();
assert!(tab.advance > 1.0, "{}", tab.advance);
let (_, a, b) = marks.chars[0];
let start = t.xf * vectorcraft_geom::Point::new(tab.origin.x, tab.origin.y - 3.0);
assert!((a - start).hypot() < 1e-9 && (b.x - a.x - tab.advance).abs() < 1e-9 && b.y == a.y, "{a:?} {b:?} {start:?}");
}
/// Show Hidden Characters marks a line that a forced line break (U+2028) ends with a bent arrow
/// and no ¶; the line a paragraph return ends gets ¶, and the story's end #.
#[test]
fn hidden_characters_mark_forced_line_breaks() {
let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "ab\u{2028}cd\nef", vectorcraft_doc::CharStyle::default());
let marks = HiddenMarks::of(&t);
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
assert_eq!(lay.lines.len(), 3);
assert_eq!(marks.breaks.len(), 1);
let (at, along, up) = marks.breaks[0];
let first = &lay.lines[0];
assert_eq!(at, vectorcraft_geom::Point::new(first.x1 + 1.0, first.baseline));
assert_eq!((along - at, up - at), (vectorcraft_geom::Vec2::new(1.0, 0.0), vectorcraft_geom::Vec2::new(0.0, -1.0)));
let ends: Vec<_> = marks.ends.iter().map(|e| (e.1, e.0.y)).collect();
assert_eq!(ends, [("", lay.lines[1].baseline), ("#", lay.lines[2].baseline)]);
// A story that ends with a forced line break: the arrow, and # on the empty line after it.
let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "ab\u{2028}", vectorcraft_doc::CharStyle::default());
let marks = HiddenMarks::of(&t);
assert_eq!((marks.breaks.len(), marks.ends.iter().map(|e| e.1).collect::<Vec<_>>()), (1, vec!["#"]));
}
/// A discretionary hyphen gets one ¬ also where the line breaks at it and the layout draws a
/// hyphen there, which stands for no character of the text.
#[test]
fn hidden_characters_mark_a_discretionary_hyphen_at_a_break_once() {
let style = vectorcraft_doc::CharStyle::default();
let db = vectorcraft_text::FontDb::global();
let word = vectorcraft_text::layout(db, &vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "coco-", style.clone()));
let width = word.lines[0].x1 - word.lines[0].x0 + 2.0;
let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "coco\u{00AD}co", style);
t.kind = vectorcraft_doc::text::TextKind::Area {
frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Rect::new(0.0, 0.0, width, 400.0).to_path(0.1)),
};
let lay = vectorcraft_text::layout(db, &t);
assert_eq!(lay.lines.len(), 2, "the line breaks at the discretionary hyphen");
assert!(lay.glyphs.iter().any(|g| g.len == 0), "the layout draws a hyphen at the break");
let marks = HiddenMarks::of(&t);
assert_eq!(marks.chars.iter().map(|c| c.0).collect::<Vec<_>>(), [super::tool_overlays::CharMark::DiscretionaryHyphen]);
}
/// In vertical type the marks follow the column: a space's dot sits beside the column, halfway
/// down the space, and ¶ goes below the column's last character.
#[test]
fn hidden_characters_follow_vertical_type() {
let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "a b\nc", vectorcraft_doc::CharStyle::default());
t.vertical = true;
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
let space = lay.glyphs.iter().find(|g| g.byte == 1).unwrap();
let marks = HiddenMarks::of(&t);
let dot = marks.spaces[0];
assert!((dot - vectorcraft_geom::Point::new(space.origin.x + 3.0, space.origin.y + space.advance / 2.0)).hypot() < 1e-9, "{dot:?} {space:?}");
let (at, glyph, align) = marks.ends[0];
assert_eq!((glyph, align), ("", egui::Align2::CENTER_TOP));
let b = lay.glyphs.iter().find(|g| g.byte == 2).unwrap();
assert!(at.y > b.origin.y, "{at:?} below {:?}", b.origin);
}
/// In a right-to-left paragraph ¶ goes at the line's left end, where the paragraph ends.
#[test]
fn hidden_characters_end_a_right_to_left_line_at_its_left() {
let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "אב גד\nהו", vectorcraft_doc::CharStyle::default());
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
assert!(lay.lines[0].rtl);
let marks = HiddenMarks::of(&t);
let (at, glyph, align) = marks.ends[0];
assert_eq!((glyph, align), ("", egui::Align2::RIGHT_BOTTOM));
assert_eq!(at.x, lay.lines[0].x0 - 1.0);
}
/// Type on a path has the marks over its characters and # after its last one.
#[test]
fn hidden_characters_mark_type_on_a_path() {
let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "a b\tc", vectorcraft_doc::CharStyle::default());
let path = vectorcraft_geom::Line::new((0.0, 100.0), (600.0, 100.0)).to_path(0.1);
t.kind = vectorcraft_doc::text::TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(&path), start: 0.0, end: None };
let marks = HiddenMarks::of(&t);
assert_eq!(marks.spaces.len(), 1);
assert_eq!(marks.chars.iter().map(|c| c.0).collect::<Vec<_>>(), [super::tool_overlays::CharMark::Tab]);
assert_eq!(marks.ends.iter().map(|e| e.1).collect::<Vec<_>>(), ["#"]);
}
/// The overlay draws each kind of mark: a dot, two rings, the tab's arrow, a tick, ¬, the forced
/// line break's bent arrow, ¶ and #.
#[test]
fn show_hidden_characters_draws_every_kind_of_mark() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let text = "a b\tc\u{00A0}d\u{202F}e\u{2003}f\u{00AD}g\u{2028}h\ni";
app.session.execute("text.create", &json!({"x": 20, "y": 60, "text": text})).unwrap();
let ctx = egui::Context::default();
let xf = Xf { rect: egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), zoom: 1.0, center: Point::new(200.0, 150.0), rot: 0.0 };
let shapes = hidden_chars(&mut app, &ctx, &xf);
let count = |f: &dyn Fn(&Shape) -> bool| shapes.iter().filter(|s| f(s)).count();
assert_eq!(count(&|s| matches!(s, Shape::Circle(c) if c.fill != Color32::TRANSPARENT)), 1, "{shapes:?}");
assert_eq!(count(&|s| matches!(s, Shape::Circle(c) if c.fill == Color32::TRANSPARENT)), 2, "{shapes:?}");
assert_eq!(count(&|s| matches!(s, Shape::LineSegment { .. })), 2, "the tab's shaft and the tick: {shapes:?}");
assert_eq!(count(&|s| matches!(s, Shape::Path(_))), 3, "the tab's head and the break's arrow: {shapes:?}");
assert_eq!(count(&|s| matches!(s, Shape::Text(_))), 3, "¬, ¶ and #: {shapes:?}");
}
/// Show Hidden Characters puts a dot over each space of a list paragraph and none over its
/// bullet, which stands for no character.
#[test]
@@ -6890,7 +7047,7 @@ fn hidden_characters_mark_no_space_at_a_bullet() {
fn show_hidden_characters_off_releases_the_text_nodes() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let text = json!({"x": 20, "y": 60, "text": "one two\nthree four"});
let text = json!({"x": 20, "y": 60, "text": "one\ttwo\u{00A0}x\nthree\u{2028}four"});
let id = vectorcraft_doc::NodeId(app.session.execute("text.create", &text).unwrap()["id"].as_u64().unwrap());
let ctx = egui::Context::default();
app.run("type.hiddenCharacters", json!({})).unwrap();
@@ -8871,6 +9028,36 @@ fn escape_while_editing_in_isolation_returns_to_selection_tool_and_keeps_isolati
assert!(app.session.active().unwrap().isolation.is_none(), "2nd Escape must exit isolation mode");
}
/// One Escape leaves isolation mode from a sublayer two levels down, where Exit Isolation Mode goes
/// up one layer at a time.
#[test]
fn escape_leaves_an_isolated_sublayer_in_one_step() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let top = app.session.active().unwrap().doc.layers[0].id;
let mid = app.session.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap();
let deep = app.session.execute("layer.newSublayer", &json!({"parent": mid})).unwrap()["id"].as_u64().unwrap();
app.session.execute("layer.setCurrent", &json!({"id": deep})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap();
app.session.execute("object.isolate", &json!({"id": deep})).unwrap();
app.select_tool("selection");
let ctx = egui::Context::default();
let timed = |app: &mut VectorcraftApp, time: f64, events: Vec<egui::Event>| {
let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }, |ui| {
crate::shortcuts::handle(app, ui.ctx());
show(app, ui)
});
out.textures_delta.clear();
};
let esc = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
timed(&mut app, 0.0, vec![]);
assert_eq!(app.session.active().unwrap().isolation, Some(vectorcraft_doc::NodeId(deep)));
timed(&mut app, 1.0, vec![esc(true), esc(false)]);
timed(&mut app, 1.1, vec![]);
assert_eq!(app.session.active().unwrap().isolation, None, "one Escape leaves every level");
}
#[test]
fn a_symbol_dropped_on_the_canvas_is_placed_there() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
@@ -8883,7 +9070,8 @@ fn a_symbol_dropped_on_the_canvas_is_placed_there() {
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
// Released over empty canvas: an instance centred there.
let at = xf.to_screen(Point::new(250.0, 180.0));
egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol(name.clone()));
let document = app.session.active().unwrap().uid;
egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document, name: name.clone() });
let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() };
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]);
let st = app.session.active().unwrap();
@@ -8894,6 +9082,106 @@ fn a_symbol_dropped_on_the_canvas_is_placed_there() {
assert!((c - xf.to_doc(at)).hypot() < 1e-6, "{c:?}");
}
/// A new active document with a symbol `name` made from a `w` by `h` rectangle and no art; → its
/// uid.
fn document_with_symbol(app: &mut VectorcraftApp, name: &str, w: f64, h: f64) -> u64 {
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": w, "height": h})).unwrap();
app.session.execute("symbol.new", &json!({"name": name})).unwrap();
app.session.execute("edit.clear", &json!({})).unwrap();
app.session.active().unwrap().uid
}
/// The natural size the active document records for symbol `name`.
fn symbol_size(app: &VectorcraftApp, name: &str) -> (f64, f64) {
let st = app.session.active().unwrap();
let size = st.doc.unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|m| m.get(name)).cloned().unwrap();
(size[0].as_f64().unwrap(), size[1].as_f64().unwrap())
}
/// A symbol dragged from one document's Symbols panel and released on the canvas after another
/// document with a different symbol of the same name became active places the dragged symbol: it
/// is added under a free name, the other document's symbol is left as it was, the source document
/// is not changed, and one Undo takes back both the symbol and the instance.
#[test]
fn a_symbol_dragged_from_another_document_places_that_documents_symbol() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0);
let ctx = egui::Context::default();
// While Leaf is held, a document with a Leaf of its own becomes active.
egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() });
document_with_symbol(&mut app, "Leaf", 10.0, 70.0);
frame(&mut app, &ctx, vec![]);
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
let undo = app.session.active().unwrap().history.undo.len();
let at = xf.to_screen(Point::new(250.0, 180.0));
let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() };
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]);
let st = app.session.active().unwrap();
assert_eq!(st.doc.symbols.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["Leaf", "Leaf 2"]);
assert_eq!(st.history.undo.len(), undo + 1, "added and placed as one undo step");
let placed = st.selection.objects.first().copied().expect("the placed instance is selected");
let n = st.doc.node(placed).unwrap();
assert!(matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Leaf 2"), "{:?}", n.kind);
let b = n.geometric_bounds().unwrap();
assert!((b.width() - 40.0).abs() < 1e-6 && (b.height() - 20.0).abs() < 1e-6, "the dragged symbol's size: {b:?}");
assert!((b.center() - xf.to_doc(at)).hypot() < 1e-6, "{b:?}");
assert_eq!(symbol_size(&app, "Leaf"), (10.0, 70.0), "this document's Leaf is unchanged");
app.run("edit.undo", json!({})).unwrap();
let st = app.session.active().unwrap();
assert_eq!(st.doc.symbols.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["Leaf"]);
assert!(st.doc.node(placed).is_none());
assert!(app.session.set_active(0));
assert_eq!(app.session.active().unwrap().uid, source);
assert_eq!(app.session.active().unwrap().doc.symbols.len(), 1, "the source document is unchanged");
assert_eq!(symbol_size(&app, "Leaf"), (40.0, 20.0));
}
/// A symbol dragged from a document that was closed before the release places nothing, even
/// where the active document has a symbol of the same name.
#[test]
fn a_symbol_whose_document_closed_places_nothing() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0);
document_with_symbol(&mut app, "Leaf", 10.0, 70.0);
app.session.execute("file.close", &json!({"index": 0})).unwrap();
assert!(app.session.documents().iter().all(|d| d.uid != source));
let ctx = egui::Context::default();
egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() });
frame(&mut app, &ctx, vec![]);
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
let undo = app.session.active().unwrap().history.undo.len();
let at = xf.to_screen(Point::new(250.0, 180.0));
let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() };
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]);
let st = app.session.active().unwrap();
assert_eq!(st.history.undo.len(), undo, "no edit");
assert!(st.selection.objects.is_empty(), "nothing placed");
}
/// The chip at the pointer shows the dragged symbol from the document it was dragged from after
/// another document, without a symbol of that name, became active.
#[test]
fn the_pointer_chip_of_a_dragged_symbol_shows_its_own_documents_symbol() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0);
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let ctx = egui::Context::default();
egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() });
let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)));
let run = |events| {
let mut out =
ctx.run_ui(egui::RawInput { screen_rect, events, ..Default::default() }, |ui| crate::panels::swatches::drag_preview(&app, ui.ctx()));
out.textures_delta.clear();
out
};
// The chip's area is drawn from its second frame.
run(vec![egui::Event::PointerMoved(pos2(200.0, 150.0))]);
let out = run(vec![]);
let thumbnail = out.shapes.iter().any(|c| matches!(&c.shape, Shape::Mesh(m) if m.texture_id != egui::TextureId::default()));
assert!(thumbnail, "the chip draws the source document's thumbnail of Leaf");
}
#[test]
fn a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+155 -23
View File
@@ -2,12 +2,14 @@ use super::grid::{clip_segment, pref_color};
use super::outline::{OVERLAY_MAX_ANCHORS, c32, stroke_path};
use super::{Color32, CornerRadius, Node, NodeKind, Overlay, Point, Pos2, Rect, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, pos2, vec2};
/// Type → Show Hidden Characters: spaces as dots, ¶ at paragraph ends, # at the end of a story.
/// The marks of each text object are kept from one frame to the next ([`HiddenChars`]).
/// Type → Show Hidden Characters: the characters that print no ink, and the ends of paragraphs,
/// lines and stories ([`HiddenMarks`]). The marks of each text object are kept from one frame to
/// the next ([`HiddenChars`]).
pub(super) fn hidden_chars_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) {
let Some(st) = app.session.active() else { return };
let clip = p.clip_rect();
let color = Color32::from_rgb(0x4f, 0x9d, 0xff);
let stroke = Stroke::new(1.0, color);
let font = egui::FontId::proportional(((10.0 * xf.zoom) as f32).clamp(7.0, 18.0));
let kept = &mut app.canvas.hidden_chars;
// `last` holds the marks of the last frame. The marks of the objects this frame doesn't draw
@@ -43,13 +45,62 @@ pub(super) fn hidden_chars_overlay(app: &mut VectorcraftApp, p: &egui::Painter,
for &at in &marks.spaces {
p.circle_filled(xf.to_screen(at), 1.2, color);
}
for &(at, glyph) in &marks.ends {
p.text(xf.to_screen(at), egui::Align2::LEFT_BOTTOM, glyph, font.clone(), color);
for &(mark, a, b) in &marks.chars {
draw_char_mark(p, mark, xf.to_screen(a), xf.to_screen(b), stroke, &font);
}
for &(at, along, up) in &marks.breaks {
let at = xf.to_screen(at);
let u = unit_or(xf.to_screen(along) - at, vec2(1.0, 0.0));
let n = unit_or(xf.to_screen(up) - at, vec2(0.0, -1.0));
// A bent arrow: down from above the line's end, then back along the line.
let corner = at + u * 7.0 + n * 2.0;
let tip = at + u + n * 2.0;
p.add(Shape::line(vec![at + u * 7.0 + n * 8.0, corner, tip], stroke));
p.add(Shape::line(vec![tip + u * 3.0 + n * 3.0, tip, tip + u * 3.0 - n * 3.0], stroke));
}
for &(at, glyph, align) in &marks.ends {
p.text(xf.to_screen(at), align, glyph, font.clone(), color);
}
kept.marks.insert(n.id, (n.clone(), marks));
});
}
/// `v` scaled to length 1, or `or` when `v` has no length.
fn unit_or(v: egui::Vec2, or: egui::Vec2) -> egui::Vec2 {
let len = v.length();
if len > 1e-3 { v / len } else { or }
}
/// Draws the mark of one character on screen. `a` and `b` are the start and end of the
/// character's advance, in the direction the text reads, above its baseline.
fn draw_char_mark(p: &egui::Painter, mark: CharMark, a: Pos2, b: Pos2, stroke: Stroke, font: &egui::FontId) {
let u = unit_or(b - a, vec2(1.0, 0.0));
let mid = a + (b - a) * 0.5;
match mark {
CharMark::Tab => {
// An arrow across the tab's advance, at least 6 px long.
let end = if (b - a).length() < 6.0 { a + u * 6.0 } else { b };
let n = vec2(u.y, -u.x);
p.line_segment([a, end], stroke);
p.add(Shape::line(vec![end - u * 3.0 + n * 2.5, end, end - u * 3.0 - n * 2.5], stroke));
}
CharMark::NoBreakSpace => {
p.circle_stroke(mid, 2.0, stroke);
}
CharMark::NarrowNoBreakSpace => {
p.circle_stroke(mid, 1.4, stroke);
}
CharMark::FixedSpace => {
// A short tick across the baseline's direction.
let n = vec2(u.y, -u.x) * 2.5;
p.line_segment([mid - n, mid + n], stroke);
}
CharMark::DiscretionaryHyphen => {
p.text(mid, egui::Align2::CENTER_BOTTOM, "¬", font.clone(), stroke.color);
}
}
}
/// The Show Hidden Characters marks of the text objects drawn in the last frame
/// ([`crate::CanvasCache::hidden_chars`]). Each is kept with the object it was laid out from: an
/// edited object is a new `Arc` and is laid out again, and all type is laid out again when the
@@ -63,12 +114,51 @@ pub struct HiddenChars {
pub(super) marks: std::collections::HashMap<vectorcraft_doc::NodeId, (std::sync::Arc<Node>, std::sync::Arc<HiddenMarks>)>,
}
/// One text object's marks in document space: a dot over each space, and ¶ or # after the lines
/// that end a paragraph or the story. Type on a path has none.
/// The mark Show Hidden Characters draws over a character other than a plain space.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum CharMark {
/// A tab (U+0009): an arrow across its advance, to the tab stop.
Tab,
/// A nonbreaking space (U+00A0): a ring.
NoBreakSpace,
/// A narrow nonbreaking space (U+202F): a smaller ring.
NarrowNoBreakSpace,
/// The spaces of a set width (U+2000 to U+200A, U+205F, U+3000): a short tick.
FixedSpace,
/// A discretionary hyphen (U+00AD): ¬, where the word can break.
DiscretionaryHyphen,
}
impl CharMark {
/// The mark of `c`, `None` for a character with no mark of its own.
pub(super) fn of(c: char) -> Option<Self> {
Some(match c {
'\t' => Self::Tab,
'\u{00A0}' => Self::NoBreakSpace,
'\u{202F}' => Self::NarrowNoBreakSpace,
'\u{2000}'..='\u{200A}' | '\u{205F}' | '\u{3000}' => Self::FixedSpace,
'\u{00AD}' => Self::DiscretionaryHyphen,
_ => return None,
})
}
}
/// One text object's marks in document space: a dot over each space, a [`CharMark`] over each
/// tab, nonbreaking space, space of a set width and discretionary hyphen, a bent arrow after
/// each line a forced line break (U+2028) ends, and ¶ or # after the lines that end a paragraph
/// or the story. Type on a path has the marks over characters, ¶ and the bent arrow at its
/// breaks, and # after its last character when all of its text is drawn.
#[derive(Default)]
pub(super) struct HiddenMarks {
pub(super) spaces: Vec<Point>,
ends: Vec<(Point, &'static str)>,
/// Each mark over a character, with the start and end of the character's advance 3 pt above
/// its baseline, in the direction the text reads.
pub(super) chars: Vec<(CharMark, Point, Point)>,
/// Each forced line break: where its arrow starts, a point 1 pt further along the line and a
/// point 1 pt above the baseline from there.
pub(super) breaks: Vec<(Point, Point, Point)>,
/// ¶ and #, where they are drawn and how the text is aligned to that point.
pub(super) ends: Vec<(Point, &'static str, egui::Align2)>,
}
impl HiddenMarks {
@@ -76,29 +166,71 @@ impl HiddenMarks {
pub(super) fn of(tx: &vectorcraft_doc::TextObject) -> Self {
let mut marks = Self::default();
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx);
if lay.on_path {
return marks;
}
let text = tx.plain_text();
let to = |q: Point| tx.xf * q;
// A list marker's glyphs (length 0) stand for no character.
for g in lay.glyphs.iter().filter(|g| g.len > 0) {
if text.get(g.byte..).is_some_and(|s| s.starts_with(' ')) {
marks.spaces.push(to(Point::new(g.origin.x + g.advance / 2.0, g.origin.y - 3.0)));
// The direction a glyph's baseline runs, and up from it (y points down).
let along = |angle: f64| vectorcraft_geom::Vec2::new(angle.cos(), angle.sin());
let up = |angle: f64| {
let d = along(angle);
vectorcraft_geom::Vec2::new(d.y, -d.x)
};
// A list marker's glyphs and a hyphen the layout adds at a break (length 0) stand for no
// character. Glyphs before the start of an open path draw nothing. A character drawn with
// several glyphs gets one mark.
let mut marked = None;
for g in lay.glyphs.iter().filter(|g| g.len > 0 && !g.off_path) {
let Some(c) = text.get(g.byte..).and_then(|s| s.chars().next()) else { continue };
if marked == Some(g.byte) {
continue;
}
let (d, n) = (along(g.angle), up(g.angle));
let start = g.origin + n * 3.0;
let end = start + d * g.advance;
if c == ' ' {
marks.spaces.push(to(start + d * (g.advance / 2.0)));
} else if let Some(mark) = CharMark::of(c) {
let (a, b) = if g.rtl { (end, start) } else { (start, end) };
marks.chars.push((mark, to(a), to(b)));
} else if lay.on_path && (c == '\n' || c == '\u{2028}') {
// Type on a path is one line: its breaks are marked where their glyphs are.
if c == '\n' {
marks.ends.push((to(g.origin), "", egui::Align2::LEFT_BOTTOM));
} else {
marks.breaks.push((to(g.origin), to(g.origin + d), to(g.origin + d + n)));
}
} else {
continue;
}
marked = Some(g.byte);
}
if lay.on_path {
// # after the last character, when the path holds all of the text.
let last = lay.glyphs.iter().filter(|g| g.len > 0 && !g.off_path).max_by_key(|g| g.byte + g.len);
if let Some(g) = last.filter(|g| g.byte + g.len >= text.len() && !lay.overflow) {
let d = along(g.angle);
let at = if g.rtl { g.origin - d } else { g.origin + d * (g.advance + 1.0) };
marks.ends.push((to(at), "#", egui::Align2::LEFT_BOTTOM));
}
return marks;
}
// Lines are in line space: `physical_point` turns them into columns in vertical type.
let at = |x: f64, y: f64| to(lay.physical_point(Point::new(x, y)));
for (i, line) in lay.lines.iter().enumerate() {
let last = i + 1 == lay.lines.len();
let breaks = text.get(line.end..).is_some_and(|s| s.starts_with('\n'));
let (glyph, at) = if last && line.end >= text.len() {
("#", true)
} else if breaks {
("", true)
} else {
("", false)
// A right-to-left line ends at its left edge.
let (x, dx) = if line.rtl { (line.x0 - 1.0, -1.0) } else { (line.x1 + 1.0, 1.0) };
let align = match (lay.vertical, line.rtl) {
(true, _) => egui::Align2::CENTER_TOP,
(false, true) => egui::Align2::RIGHT_BOTTOM,
(false, false) => egui::Align2::LEFT_BOTTOM,
};
if at {
marks.ends.push((to(Point::new(line.x1 + 1.0, line.baseline)), glyph));
let soft = text.get(line.start..line.end).is_some_and(|s| s.ends_with('\u{2028}'));
if last && line.end >= text.len() {
marks.ends.push((at(x, line.baseline), "#", align));
} else if soft {
marks.breaks.push((at(x, line.baseline), at(x + dx, line.baseline), at(x, line.baseline - 1.0)));
} else if text.get(line.end..).is_some_and(|s| s.starts_with('\n')) {
marks.ends.push((at(x, line.baseline), "", align));
}
}
marks
+1 -1
View File
@@ -94,7 +94,7 @@ pub(super) const HOLD_DELAY: f32 = 0.3;
/// …and how fast it zooms then (as `exp(seconds × HOLD_ZOOM)`: twice as close each second).
pub(super) const HOLD_ZOOM: f64 = std::f64::consts::LN_2;
/// Performance › Animated Zoom, which needs GPU Performance as in Illustrator: the Zoom tool zooms
/// Performance › Animated Zoom, which needs GPU Performance: the Zoom tool zooms
/// as it is dragged sideways or held, instead of zooming to the area dragged across, and a wheel
/// notch's zoom glides in ([`wheel`]).
pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool {
+44 -8
View File
@@ -36,7 +36,7 @@ use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_drop, tab_groups, tab_title}
pub use tabs::{doc_tabs, isolation_bar, step_document};
pub(crate) use tabs::{document_window_title, show_document, window_tab};
/// The application bar's height, in points (compact, as in PhotoCraft).
/// The application bar's height, in points (compact).
pub const APP_BAR_HEIGHT: f32 = 32.0;
/// The brand mark's side.
const MARK: f32 = 18.0;
@@ -110,7 +110,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
gap: ui.spacing().item_spacing.x,
community: crate::community::discord_width(ui, false),
});
let (switcher, ws_w, learn, discord) = (fit.switcher, fit.switcher_w, fit.learn, fit.community);
let (switcher, ws_w, arrange, learn, discord) = (fit.switcher, fit.switcher_w, fit.arrange, fit.learn, fit.community);
let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center)));
let ui = &mut rui;
// Workspace switcher: shows the current workspace, opens Window → Workspace.
@@ -129,6 +129,11 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
}
ui.add_space(8.0);
}
// Arrange Documents: Consolidate All Windows and the Tile layouts.
if arrange {
let resp = widgets::icon_button(ui, "layout-grid", tl!("Arrange Documents"), app.ui.tiled, BAR_ICON);
egui::Popup::menu(&resp).show(|ui| arrange_documents_popup(app, ui));
}
// Search → command palette (its shortcut opens it too).
let with_shortcut = |text: &str| match &field.shortcut {
Some(sc) => format!("{text} ({sc})"),
@@ -181,7 +186,34 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
/// The side of the app bar's square icon buttons (the search icon, Explore tutorials).
/// The Arrange Documents menu ([`menus::arrange_documents_items`]): each item as the Window menu
/// shows it, grayed out while its command can't run, the Tile layout the panes show checked.
fn arrange_documents_popup(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.set_min_width(200.0);
let mut clicked = None;
for it in menus::arrange_documents_items() {
match it {
menus::Item::Sep => {
ui.separator();
}
menus::Item::Cmd(label, id, p) => {
let Some((enabled, checked)) = menus::shown_state(app, id, &p) else { continue };
let label = crate::i18n::t_id(id, label);
let text = if checked == Some(true) { format!("✓ {label}") } else { format!(" {label}") };
if ui.add_enabled(enabled, egui::Button::new(text).min_size(vec2(200.0, 0.0))).clicked() {
clicked = Some((id, if p.is_null() { json!({}) } else { p }));
ui.close();
}
}
_ => {}
}
}
if let Some((id, p)) = clicked {
menus::invoke(app, id, p);
}
}
/// The side of the app bar's square icon buttons (the search icon, Arrange Documents, Explore tutorials).
const BAR_ICON: f32 = 28.0;
/// The narrowest the workspace switcher gets.
const MIN_SWITCHER: f32 = 64.0;
@@ -225,6 +257,8 @@ struct RightGroup {
switcher_w: f32,
/// How the search shows.
search: Search,
/// Whether Arrange Documents shows.
arrange: bool,
/// Whether Explore tutorials shows.
learn: bool,
/// Whether the community button shows.
@@ -232,8 +266,8 @@ struct RightGroup {
}
/// The right-hand group for the room it has. As the room runs short, the community button goes first
/// (it is also under Help), then Explore tutorials (also Window › Learn), then the search field becomes the
/// search icon, then the workspace switcher narrows to [`MIN_SWITCHER`], then the icon goes. In Safe
/// (it is also under Help), then Explore tutorials (also Window › Learn), then Arrange Documents (also Window ›
/// Arrange), then the search field becomes the search icon, then the workspace switcher narrows to [`MIN_SWITCHER`], then the icon goes. In Safe
/// Mode the label's width is taken first, and the switcher (also under Window › Workspace) goes when
/// a minimal one does not fit.
fn fit_right_group(w: &RightWidths) -> RightGroup {
@@ -254,10 +288,12 @@ fn fit_right_group(w: &RightWidths) -> RightGroup {
Search::Hidden => 0.0,
};
let switcher_w = w.switcher.min(room - 8.0 - search_w).max(MIN_SWITCHER);
let learn_end = switcher_w + 8.0 + search_w + w.gap + w.icon;
let learn = field && room >= learn_end;
let arrange_end = switcher_w + 8.0 + search_w + w.gap + w.icon;
let arrange = field && room >= arrange_end;
let learn_end = arrange_end + w.gap + w.icon;
let learn = arrange && room >= learn_end;
let community = learn && room >= learn_end + 10.0 + w.gap + w.community;
RightGroup { switcher, switcher_w, search, learn, community }
RightGroup { switcher, switcher_w, search, arrange, learn, community }
}
/// The app bar's search field: a button drawn as a field. The command palette's popup holds the
+52 -32
View File
@@ -188,9 +188,9 @@ const INLINE_FIELD_WIDTH: f32 = 80.0;
/// The keys and labels of the Control bar's inline X/Y/W/H fields, in their order.
const INLINE_FIELDS: [(&str, &str); 4] = [("x", "X:"), ("y", "Y:"), ("width", "W:"), ("height", "H:")];
/// The label of an inline X/Y/W/H field.
/// The label of an inline X/Y/W/H field, underlined: a click on it opens the Transform panel.
fn inline_label(t: &Tokens, lbl: &str) -> egui::RichText {
egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim)
egui::RichText::new(tl!(lbl)).size(12.0).color(t.text).underline()
}
/// The room the Control bar's inline X/Y/W/H fields take: their labels as drawn in the current
@@ -203,6 +203,53 @@ fn inline_transform_width(ui: &Ui, t: &Tokens) -> f32 {
labels + fields + crate::panels::transform::CONSTRAIN_LINK_SIZE + ui.spacing().item_spacing.x * items as f32
}
/// The Control bar's inline X/Y/W/H fields for the selection's box `b`, rotated with rotated
/// objects: X/Y are its reference point on the page (or a symbol instance's registration point),
/// shared with the Transform panel, and W/H its own sides. Edits keep or move that point, and the
/// Transform panel's menu choice of objects, patterns or both applies to them.
fn inline_transform_fields(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, units: vectorcraft_doc::Unit, b: &vectorcraft_doc::OrientedBox) {
let reference = crate::panels::transform::panel_reference(app, ui, b);
let (refi, rp) = (reference.index, reference.point);
let origin = app.ruler_origin();
let link = crate::panels::transform::proportional(app, ui);
let copy = crate::panels::transform::alt_enter_copies(app, ui);
let values = [(rp.x, origin.x), (rp.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)];
// The W/H link sits between W and H, but is made after H so Tab goes from W
// straight to H and finds the link after it.
let mut link_room = None;
let mut labels = Vec::with_capacity(INLINE_FIELDS.len());
for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) {
if k == "height" {
link_room = Some(crate::panels::transform::constrain_link_room(ui));
}
// A click on the label opens the Transform panel, as the Transform link does; a drag scrubs.
let label = widgets::field_panel_label(ui, inline_label(t, lbl)).on_hover_text(tl!("Transform options"));
let (id, shown) = (("cb", k), Some(v - offset));
let set = if matches!(k, "width" | "height") {
widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH)
} else {
widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH)
};
labels.push(label);
if let Some(nv) = set {
let params = match k {
"x" => json!({"x": reference.bounds_xy(nv + offset, 0.0).0, "reference": refi, "copy": copy}),
"y" => json!({"y": reference.bounds_xy(0.0, nv + offset).1, "reference": refi, "copy": copy}),
_ => json!({k: nv, "reference": refi, "proportional": link, "copy": copy}),
};
crate::panels::transform::run_transform(app, "object.setBounds", params);
}
}
if let Some(room) = link_room {
let id = ui.scope_id().with("cb-constrain-link");
crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click()));
}
// After the fields, which each take the label before them as their own.
for label in &labels {
crate::panels::transform::popover(app, label);
}
}
/// The size of the Control bar's Align, Distribute and area type vertical alignment buttons, and
/// the height of its Align To menu.
const BUTTON: f32 = 24.0;
@@ -710,7 +757,7 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) {
stroke_panel::weight_field(app, ui, "cb-stroke", weight, WEIGHT_FIELD_WIDTH);
if ui.available_width() < row_width(ui, &[stroke_panel::PROFILE_DROPDOWN_WIDTH]) + reserve {
left_out(ui);
} else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref().and_then(|s| s.profile.as_ref())) {
} else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref()) {
app.run("stroke.set", json!({"profile": id})).ok();
}
} else {
@@ -886,7 +933,7 @@ fn gripper(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, d
}
}
/// The Control bar (Window → Control), context-sensitive like Illustrator's, docked to the top or
/// The Control bar (Window → Control), context-sensitive, docked to the top or
/// the bottom of the window, or floating over the window below the menu bar, where it takes no room
/// from the canvas. A floating bar is [`FLOAT_WIDTH`] wide, or as wide as the window when that is
/// narrower, and is kept inside the window when the window shrinks.
@@ -1036,38 +1083,11 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect,
return;
}
crate::panels::transform::link(app, ui);
// The bounding box, rotated with rotated objects: its centre and its own sides.
let selection_box = app.selection_box();
if selection_box.is_some() && ui.available_width() < inline_transform_width(ui, t) {
left_out(ui);
} else if let Some(b) = selection_box {
let c = b.center();
let origin = app.ruler_origin();
let link = crate::panels::transform::proportional(app, ui);
let copy = crate::panels::transform::alt_enter_copies(app, ui);
let values = [(c.x, origin.x), (c.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)];
// The W/H link sits between W and H, but is made after H so Tab goes from W
// straight to H and finds the link after it.
let mut link_room = None;
for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) {
if k == "height" {
link_room = Some(crate::panels::transform::constrain_link_room(ui));
}
widgets::field_label(ui, inline_label(t, lbl));
let (id, shown) = (("cb", k), Some(v - offset));
let set = if matches!(k, "width" | "height") {
widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH)
} else {
widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH)
};
if let Some(nv) = set {
app.run("object.setBounds", json!({k: nv + offset, "reference": 4, "proportional": link, "copy": copy})).ok();
}
}
if let Some(room) = link_room {
let id = ui.scope_id().with("cb-constrain-link");
crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click()));
}
inline_transform_fields(app, ui, t, units, &b);
}
// Select Similar Objects comes last: it takes only the room every control ahead of it left.
trailing_select_similar(app, ui);
+6 -3
View File
@@ -364,8 +364,10 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) {
ui.painter().rect_filled(crumb_rect, 3.0, t.hover);
}
if resp.clicked() {
if crumb.is_layer {
nav_cmd = Some(("object.exitIsolation", json!({})));
// The top-level layer's crumb leaves isolation mode; a sublayer's or a group's
// crumb isolates that level.
if crumb.is_layer && i == 0 {
nav_cmd = Some(("object.exitIsolation", json!({ "all": true })));
} else if let Some(target) = crumb.id {
nav_cmd = Some(("object.isolate", json!({ "id": target.0 })));
}
@@ -401,7 +403,8 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) {
if bresp.clicked() {
pattern_cmd = pattern_cmd.or(pattern_edit.as_ref().map(|_| "object.pattern.done"));
if pattern_cmd.is_none() {
// Up one level: the isolated object's parent, or out of isolation mode from a layer.
// Up one level: the isolated object's parent group, or `object.exitIsolation`, which
// goes from an isolated sublayer to its parent layer and otherwise leaves isolation mode.
nav_cmd = Some(match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) {
Some(parent) => ("object.isolate", json!({ "id": parent.0 })),
None => ("object.exitIsolation", json!({})),
+112 -15
View File
@@ -172,11 +172,11 @@ fn right_stage(g: &super::RightGroup) -> String {
w if w > super::MIN_SWITCHER => "narrower switcher",
_ => "minimal switcher",
};
format!("community {}, learn {}, {:?}, {switcher}", g.community, g.learn, g.search)
format!("community {}, learn {}, arrange {}, {:?}, {switcher}", g.community, g.learn, g.arrange, g.search)
}
/// As the app bar's room runs short, the community button goes first, then Explore tutorials, then the search
/// field becomes the icon, then the workspace switcher narrows to its minimum, then the icon goes.
/// As the app bar's room runs short, the community button goes first, then Explore tutorials, then Arrange
/// Documents, then the search field becomes the icon, then the workspace switcher narrows to its minimum, then the icon goes.
/// Whatever shows fits in the room, down to the minimal switcher alone.
#[test]
fn the_app_bar_gives_up_its_right_hand_controls_in_order() {
@@ -193,31 +193,33 @@ fn the_app_bar_gives_up_its_right_hand_controls_in_order() {
super::Search::Icon => w.gap + w.icon,
super::Search::Hidden => 0.0,
};
let arrange = if g.arrange { w.gap + w.icon } else { 0.0 };
let learn = if g.learn { w.gap + w.icon } else { 0.0 };
let community = if g.community { 10.0 + w.gap + w.community } else { 0.0 };
let used = g.switcher_w + 8.0 + search + learn + community;
let used = g.switcher_w + 8.0 + search + arrange + learn + community;
assert!(used <= room || g.switcher_w == super::MIN_SWITCHER && g.search == super::Search::Hidden, "{room}: {g:?} needs {used}");
}
assert_eq!(
stages,
[
"community true, learn true, Field, full switcher",
"community false, learn true, Field, full switcher",
"community false, learn false, Field, full switcher",
"community false, learn false, Icon, full switcher",
"community false, learn false, Icon, narrower switcher",
"community false, learn false, Icon, minimal switcher",
"community true, learn true, arrange true, Field, full switcher",
"community false, learn true, arrange true, Field, full switcher",
"community false, learn false, arrange true, Field, full switcher",
"community false, learn false, arrange false, Field, full switcher",
"community false, learn false, arrange false, Icon, full switcher",
"community false, learn false, arrange false, Icon, narrower switcher",
"community false, learn false, arrange false, Icon, minimal switcher",
// Once the icon has gone, the switcher takes the room it leaves.
"community false, learn false, Hidden, narrower switcher",
"community false, learn false, Hidden, minimal switcher",
"community false, learn false, arrange false, Hidden, narrower switcher",
"community false, learn false, arrange false, Hidden, minimal switcher",
]
);
// In Safe Mode the label's width is taken first (not counted in `room`), and the switcher goes
// when a minimal one does not fit.
let safe = |room| right_stage(&super::fit_right_group(&right_widths(room, true)));
assert_eq!(safe(700.0), "community true, learn true, Field, full switcher");
assert_eq!(safe(72.0), "community false, learn false, Hidden, minimal switcher");
assert_eq!(safe(71.0), "community false, learn false, Hidden, no switcher");
assert_eq!(safe(700.0), "community true, learn true, arrange true, Field, full switcher");
assert_eq!(safe(72.0), "community false, learn false, arrange false, Hidden, minimal switcher");
assert_eq!(safe(71.0), "community false, learn false, arrange false, Hidden, no switcher");
}
/// What screen readers call the app bar's search field, and the icon it becomes, before the shortcut.
@@ -1914,6 +1916,45 @@ fn isolation_bar_navigation_and_back_button_steps_up() {
assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g2)));
}
/// With a sublayer isolated, the back arrow goes up one layer at a time and then leaves isolation
/// mode. The top-level layer's crumb leaves isolation mode from any depth, and a parent sublayer's
/// crumb isolates that sublayer.
#[test]
fn isolation_bar_back_button_steps_up_through_sublayers() {
use vectorcraft_doc::NodeId;
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
let top = app.session.active().unwrap().doc.layers[0].id;
let mid = NodeId(app.run("layer.newSublayer", json!({"parent": top.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap());
let deep = NodeId(app.run("layer.newSublayer", json!({"parent": mid.0, "name": "Sublayer C"})).unwrap()["id"].as_u64().unwrap());
app.run("layer.setCurrent", json!({"id": deep.0})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap();
let ctx = isolation_bar_context();
let click = |app: &mut crate::VectorcraftApp, pos: egui::Pos2| isolation_bar_gesture(app, &ctx, pos, pos);
let back = egui::pos2(15.0, 12.0);
let isolation = |app: &crate::VectorcraftApp| app.session.active().unwrap().isolation;
app.run("object.isolate", json!({"id": deep.0})).unwrap();
let steps = app.session.doc().unwrap().history.undo.len();
click(&mut app, back);
assert_eq!(isolation(&app), Some(mid), "back from the deepest sublayer");
click(&mut app, back);
assert_eq!(isolation(&app), Some(top), "back from the middle sublayer");
click(&mut app, back);
assert_eq!(isolation(&app), None, "back from the top-level layer");
assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "no undo step");
// "Layer 1" is the first crumb, at x 30 to about 75.
app.run("object.isolate", json!({"id": deep.0})).unwrap();
click(&mut app, egui::pos2(40.0, 12.0));
assert_eq!(isolation(&app), None, "the top-level layer's crumb");
// "Sublayer B" is the second crumb, from about x 95.
app.run("object.isolate", json!({"id": deep.0})).unwrap();
click(&mut app, egui::pos2(115.0, 12.0));
assert_eq!(isolation(&app), Some(mid), "the parent sublayer's crumb");
}
/// Headless frames of the isolation bar over a 1200 × 700 canvas for one pointer gesture: a press
/// at `from`, a move to `to` and a release there. `from == to` is a click.
fn isolation_bar_gesture(app: &mut crate::VectorcraftApp, ctx: &egui::Context, from: egui::Pos2, to: egui::Pos2) {
@@ -4651,3 +4692,59 @@ fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() {
assert!(groups_seen.iter().all(|s| *s), "{count} objects: a wide bar shows every group: {groups_seen:?}");
}
}
/// A click on the Control bar's X:, Y:, W: or H: label opens the Transform panel in a popover under
/// it, as the Transform link does, and a second click closes it. The click leaves the selection and
/// its bounds as they were, and no field takes the keyboard. A drag on W: still scrubs the width and
/// opens nothing.
#[test]
fn the_control_bars_x_y_w_and_h_labels_open_the_transform_panel() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 30})).unwrap()["id"].clone();
app.run("select.set", json!({ "ids": [id] })).unwrap();
let ctx = egui::Context::default();
ctx.enable_accesskit();
crate::theme::install_fonts(&ctx);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(2000.0, 600.0));
let frame = |app: &mut crate::VectorcraftApp, events| control_bar_frame_in(app, &ctx, screen, events);
let state = |app: &crate::VectorcraftApp| {
let st = app.session.active().unwrap();
let b = st.doc.bounds_of(&st.selection.objects, false).unwrap();
(st.selection.objects.len(), [b.x0, b.y0, b.x1, b.y1])
};
// The label's own node: a label whose text is `name` (the field it names is named the same).
let label = |nodes: &[egui::accesskit::Node], name: &str| {
let n = nodes.iter().find(|n| n.role() == egui::accesskit::Role::Label && n.value() == Some(name));
let b = n.and_then(|n| n.bounds()).unwrap_or_else(|| panic!("no {name} label"));
egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)
};
// The Transform panel's Rotate field is not on the bar itself.
let open = |nodes: &[egui::accesskit::Node]| nodes.iter().any(|n| n.label() == Some("Rotate"));
let before = state(&app);
frame(&mut app, vec![]);
for name in ["X:", "Y:", "W:", "H:"] {
let nodes = frame(&mut app, vec![]);
assert!(!open(&nodes), "{name}: the Transform panel is closed at first");
let at = label(&nodes, name);
frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]);
frame(&mut app, vec![press_at(at, false)]);
assert!(open(&frame(&mut app, vec![])), "{name}: a click on the label opens the Transform panel");
assert_eq!(ctx.memory(|m| m.focused()), None, "{name}: no field took the keyboard");
assert_eq!(state(&app), before, "{name}: the selection and its bounds stay");
frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]);
frame(&mut app, vec![press_at(at, false)]);
assert!(!open(&frame(&mut app, vec![])), "{name}: a second click closes it");
}
let at = label(&frame(&mut app, vec![]), "W:");
frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]);
for i in 1..=4 {
frame(&mut app, vec![egui::Event::PointerMoved(at + egui::vec2(5.0 * i as f32, 0.0))]);
}
frame(&mut app, vec![press_at(at + egui::vec2(20.0, 0.0), false)]);
let nodes = frame(&mut app, vec![]);
assert!(!open(&nodes), "a drag on W: opens nothing");
let (_, [x0, _, x1, _]) = state(&app);
assert!(x1 - x0 > before.1[2] - before.1[0], "a drag on W: scrubs the width: {:?} to {:?}", before.1, [x0, x1]);
}
+2 -2
View File
@@ -33,7 +33,7 @@ pub fn discord_button(app: &mut VectorcraftApp, ui: &mut Ui, large: bool) -> egu
let ir = egui::Rect::from_center_size(r.left_center() + vec2(h * 0.35 + icon / 2.0, 0.0), vec2(icon, icon));
if large {
// The theme's accent, as the primary buttons use it, so the call to action matches the
// rest of the window (and PhotoCraft's, #4684); Discord's colour stays on the app-bar icon.
// rest of the window (#4684); Discord's colour stays on the app-bar icon.
let t = Tokens::get(ui.ctx());
let fill = if resp.hovered() { t.accent } else { t.accent_strong };
ui.painter().rect_filled(r, CornerRadius::same((h / 2.0) as u8), fill);
@@ -77,7 +77,7 @@ pub fn links(app: &mut VectorcraftApp, ui: &mut Ui) {
links_in(app, ui, false);
}
/// [`links`] for a centred column (the Home screen's, as PhotoCraft's, #4684): the Discord button
/// [`links`] for a centred column (the Home screen's, #4684): the Discord button
/// and the links, each in the middle.
pub fn links_centered(app: &mut VectorcraftApp, ui: &mut Ui) {
links_in(app, ui, true);
+6 -4
View File
@@ -240,6 +240,7 @@ fn wrap(r: Result<Value, String>) -> Outcome {
pub fn all_commands(app: &VectorcraftApp) -> Value {
let mut v: Vec<Value> = app.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect();
for (id, label, sc, params) in crate::menus::UI_COMMANDS {
let sc = crate::shortcut_editor::ui_command_default(id, sc, crate::keymap::platform());
v.push(json!({"id": id, "label": label, "shortcut": sc, "params": params, "enabled": crate::menus::enabled(app, id), "ui": true}));
}
Value::Array(v)
@@ -274,11 +275,12 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
// The display profile the canvas is drawn through, or why none (Preferences ›
// Performance › Use Monitor Profile for Canvas).
"displayProfile": app.display_profile.status(app.session.prefs.monitor_profile_display),
// Window › Arrange › Tile (not saved, so not in `ui`) and the panes the last frame drew:
// each one's document index, view number (Window › New Window) and rect. Canvas
// coordinates map to the current window's pane, inside its rulers and scroll bars
// Window › Arrange › Tile and its layout (not saved, so not in `ui`) and the panes the
// last frame drew: each one's document index, view number (Window › New Window) and rect.
// Canvas coordinates map to the current window's pane, inside its rulers and scroll bars
// (`canvasRect`).
"tiled": app.ui.tiled,
"tileLayout": app.ui.tile_layout.name(),
"panes": app.canvas.panes.last.iter().map(|(w, c)| json!({
"document": w.0,
"view": w.1,
@@ -2105,7 +2107,7 @@ fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome {
r = app.run("window.panel", json!({"panel": pn}));
}
if let Some(st) = s("status") {
app.ui.status = st.to_string();
app.status(st);
}
for (k, flag) in [
("rulers", "view.rulers"),
+16
View File
@@ -1426,3 +1426,19 @@ fn dialog_set_refuses_a_field_the_dialog_does_not_have() {
app.ui.dialog = None;
assert_eq!(input_request(&mut app, "ui.dialog.set", json!({"field": "name", "value": "A"}))["error"], "no dialog open");
}
/// `engine.commands` lists each UI command's default shortcut on this platform: Select Last
/// Selection Tool shows Ctrl+` (`Cmd+~`) on Windows and Linux and none on macOS.
#[test]
fn the_command_list_shows_this_platforms_default_shortcut() {
let mut app = VectorcraftApp::new(Session::new(), Services::default());
let r = input_request(&mut app, "engine.commands", json!({}));
let row = r["result"].as_array().unwrap().iter().find(|c| c["id"] == "tool.selectLastSelection").cloned();
let row = row.unwrap_or_else(|| panic!("listed: {r}"));
assert_eq!(row["shortcut"], if crate::keymap::platform().is_mac() { "" } else { "Cmd+~" }, "{row}");
for p in [craft_keymap::Platform::Windows, craft_keymap::Platform::Linux] {
assert_eq!(crate::shortcut_editor::ui_command_default("tool.selectLastSelection", "Cmd+~", p), "Cmd+~", "{p:?}");
}
assert_eq!(crate::shortcut_editor::ui_command_default("tool.selectLastSelection", "Cmd+~", craft_keymap::Platform::Mac), "");
assert_eq!(crate::shortcut_editor::ui_command_default("view.zoomIn", "Cmd+=", craft_keymap::Platform::Mac), "Cmd+=");
}
+1 -1
View File
@@ -1,5 +1,5 @@
//! Tool cursors drawn as vector glyphs (egui only offers system cursors). Black shapes with a white
//! halo, hotspot at `p`, Illustrator's visual grammar: solid arrow (Selection), hollow arrow (Direct
//! halo, hotspot at `p`, one shape per tool: solid arrow (Selection), hollow arrow (Direct
//! Selection), pen nib with state badges, crosshair for drawing tools, curved arrows for rotate.
//!
//! The desktop app shows them as OS cursors ([`Images`]): the system moves those itself, at once,
+3 -2
View File
@@ -1121,6 +1121,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
ui.add_space((middle - BUTTON / 2.0 * row.len() as f32 - ui.cursor().min.x).max(0.0));
for &(s, slot) in row {
let Some((rect, shown)) = slot_button(ui, &t, &press, slot, &mut actions) else { continue };
crate::palette::note_spot(ui, rect, || crate::palette::SpotAt::Slot(Some(bar.name.clone()), slot.clone()));
if edit_this {
buttons.push((s, rect));
}
@@ -1382,7 +1383,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: &
let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect();
let heading = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(text).size(12.0).color(t.text_strong));
if !held.is_empty() {
heading(ui, &format!("{}:", tl!("Remove Tool")));
heading(ui, &crate::i18n::colon(tl!("Remove Tool")));
for tool in held.iter().filter_map(|id| tool_info(id)) {
if widgets::menu_item(ui, tool.label, true, false) {
actions.push(Action::RemoveTool(bar.name.clone(), tool.id));
@@ -1391,7 +1392,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: &
ui.separator();
}
for (cat, tools) in crate::edit_toolbar::sections() {
heading(ui, &format!("{}:", tl!(cat)));
heading(ui, &crate::i18n::colon(tl!(cat)));
for tool in tools {
if widgets::menu_item(ui, tool.label, !held.contains(&tool.id), false) {
actions.push(Action::AddTool(bar.name.clone(), tool.id));
+54 -10
View File
@@ -25,7 +25,7 @@ pub mod char_style_options;
pub mod check_spelling;
pub mod color_balance;
pub mod color_guide_options;
mod color_picker;
pub(crate) mod color_picker;
mod command;
pub mod composite_fonts;
pub mod confirm;
@@ -167,7 +167,7 @@ pub(crate) use export_for_screens::{
open_assets as open_export_for_screens_assets, preset_list as screen_preset_list, saved_options as screen_saved_options,
saved_rows as screen_saved_rows, settings_format as screen_settings_format,
};
pub(crate) use form::{humanize, number_list_text, plugin_color_button, read_number_list, unit_suffix};
pub(crate) use form::{humanize, number_list_text, plugin_color_button, ppi_suffix, read_number_list, unit_suffix};
pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card};
pub(crate) use new_document::{popup_open as new_document_popup_open, preset_name};
pub use png_options::open as open_raster_options;
@@ -419,6 +419,7 @@ registry! {
SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC,
DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC,
EpsOptions: [eps_options::KIND] => eps_options::SPEC,
EpsFlattenerOptions: [eps_options::CUSTOM_KIND] => eps_options::CUSTOM_SPEC,
Recovery: [crate::recovery::KIND] => recovery::SPEC,
PluginStopped: [safe_mode::STOPPED] => safe_mode::STOPPED_SPEC,
SafeMode: [safe_mode::KIND] => safe_mode::SPEC,
@@ -439,6 +440,7 @@ registry! {
ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC,
ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC,
ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC,
ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC,
VectorHalftone: [halftone::KIND] => halftone::SPEC,
SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC,
SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC,
@@ -476,6 +478,7 @@ registry! {
RenameArtboards: [rename_artboards::KIND] => rename_artboards::SPEC,
PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC,
DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC,
SmoothBridge: [crate::addons::pathtools::bridge::KIND] => crate::addons::pathtools::bridge::SPEC,
TangentCircle: [crate::addons::pathtools::tangent_circle::KIND] => crate::addons::pathtools::tangent_circle::SPEC,
SetCorners: [crate::addons::pathtools::set_corners::KIND] => crate::addons::pathtools::set_corners::SPEC,
NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC,
@@ -544,8 +547,9 @@ fn hidden_controls(d: &Dialog) -> &'static [&'static str] {
}
// The selected rows and Randomize's seed.
Some(DialogKind::Recolor) => &["__seed", "__sel"],
// The view, zoom, download speed, selected color table entry and the preset name being typed.
Some(DialogKind::SaveForWeb) => &["__color", "__kbps", "__presetName", "__view", "__zoom"],
// The view, zoom, download speed, selected color table entries, the color table entry whose
// Color Picker opens and the preset name being typed.
Some(DialogKind::SaveForWeb) => &["__color", "__colors", "__editColor", "__kbps", "__presetName", "__view", "__zoom"],
// The link that keeps width and height in proportion.
Some(DialogKind::Shape | DialogKind::TransformEach) => &["__constrain"],
// The attention filter, the Keys section, the search text and the key being recorded.
@@ -597,7 +601,8 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool {
/// Options setting set this way for several rows is sent to every row (Template also sets Lock
/// and Dim Images, as its checkbox does). A DXF Options preset set this way sets its fields, as
/// one picked from its menu does, and the preset it shows follows the DXF options set this way.
/// A Graph Data Column Width set this way sets every column, as Cell Style's does.
/// A Graph Data Column Width set this way sets every column, as Cell Style's does. An Import PDF
/// `allPages` set this way to the other pick sets Import PDF pages as links back to its default.
pub fn set_field(d: &mut Dialog, field: String, value: Value) {
if d.kind == brush_options::KIND {
brush_art_options::note_set(d, &field);
@@ -608,6 +613,9 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) {
if d.kind == layer_options::KIND {
layer_options::note_set(d, &field, &value);
}
if d.kind == import_pdf::KIND {
import_pdf::note_set(d, &field, &value);
}
if d.kind == "preferences" {
crate::prefs_dialog::note_set(d, &field, &value);
}
@@ -646,6 +654,16 @@ fn run_and_close(app: &mut VectorcraftApp, id: &str, params: Value) -> DialogRes
r
}
/// Set a tool's options with `tool.setOption` (`params`) and close the dialog; when the tool
/// refuses one of them, nothing is set and the dialog stays open.
fn set_tool_options_and_close(app: &mut VectorcraftApp, params: Value) -> DialogResult {
let r = app.run("tool.setOption", params);
if r.is_ok() {
app.ui.dialog = None;
}
r
}
/// The field of a dialog opened over another (Import Shortcut Set over Keyboard Shortcuts) that
/// holds the dialog under it, which Cancel and Escape show again.
pub(crate) const PARENT: &str = "__parent";
@@ -656,18 +674,27 @@ pub(crate) fn parent(d: &Dialog) -> Option<Dialog> {
}
/// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields
/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), a change
/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`, EPS Options'
/// `flattenerPreset`, which drops the Custom… options), a change
/// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in
/// the dialog, and Transform Each's Relative / Absolute keeps the Scale fields' size. A value
/// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor
/// Artwork's `group` selects that color group and its `groupAction` runs the button at once. A value
/// Composite Fonts' Show Sample can't take is refused.
pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> {
if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) {
transform_each::field_set(app, field, old);
return Ok(());
}
if app.ui.dialog.as_ref().is_some_and(|d| d.kind == recolor::KIND) {
return recolor::field_set(app, field);
}
if let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == composite_fonts::KIND) {
return composite_fonts::field_set(d, field);
}
if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == eps_options::KIND) {
eps_options::field_set(d, field);
return Ok(());
}
let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) };
match field {
"exportPreset" => export_for_screens::preset_set(app),
@@ -706,6 +733,9 @@ pub fn cancel(app: &mut VectorcraftApp) {
if d.kind == script_run::NOTICE_KIND {
script_run::notice_cancel(app, &d);
}
if d.kind == script_run::PICKER_KIND {
script_run::picker_cancel(app, &d);
}
missing_links::cancelled(app, &d);
// Find Font's next open starts with an empty replacement search.
if d.kind == "findFont"
@@ -817,6 +847,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
let focus_first = focus_first && !clicked;
let spec = spec(&d.kind);
// Opened over another dialog, which Cancel shows again: that one keeps where it was scrolled to.
if d.fields.get(PARENT).is_some_and(|p| !p.is_null()) {
modal::over_parent(ctx);
}
if let Some(window) = spec.window {
return window(app, ctx);
}
@@ -832,6 +866,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
if after_panel && !ctx.input(|i| i.key_down(egui::Key::Enter) || i.key_pressed(egui::Key::Enter)) {
d.fields.remove(AFTER_PANEL);
}
// A body can open another dialog in its place (EPS Options' Custom…): this frame's Enter
// doesn't confirm that one.
let opened = d.kind.clone();
let heading = (spec.heading)(&d);
let revolves = revolve_gizmo::active(&d);
if revolves {
@@ -856,14 +893,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
if focus_first {
ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true));
}
// When the dialog is taller than the window, its body scrolls, and the heading and the
// buttons stay in view.
if let Some(body) = spec.body_with_actions {
match body(app, ui, &mut d) {
match modal::body_rows(ui, |ui| body(app, ui, &mut d)) {
DialogAction::None => {}
DialogAction::Confirm => ok = true,
DialogAction::Cancel => cancel = true,
}
} else {
cancel = (spec.body)(app, ui, &mut d);
cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d));
}
// Taken (the flag is gone): done. Still there (the window's measuring frame): next frame.
if focus_first && ui.data_mut(|m| m.remove_temp::<bool>(widgets::dialog_focus_flag())).is_none() {
@@ -931,7 +970,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
if ok_clicked && !rejected && !refused_during_click {
ok = true;
}
if spec.ok.is_some() && ok_enabled && !after_panel && !rejected && crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) {
if spec.ok.is_some() && ok_enabled && !after_panel && !rejected && d.kind == opened && crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) {
ok = true;
}
if discard {
@@ -997,6 +1036,8 @@ mod tests_plugin_import;
#[cfg(test)]
mod tests_raster_formats;
#[cfg(test)]
mod tests_raster_supplied_options;
#[cfg(test)]
mod tests_svg_options_range;
#[cfg(test)]
@@ -1042,6 +1083,9 @@ mod tests_perspective;
#[cfg(test)]
mod tests_modal;
#[cfg(test)]
mod tests_scroll;
#[cfg(test)]
mod tests_rectangular_grid;
@@ -9,7 +9,7 @@
//! open).
//! Scatter: per value (`size`, `spacing`, `scatter` %, `rotation` °) `…Min`, `…Max` and `…Mode`
//! (`fixed` | `random` | `pressure` | `tilt` | `bearing` | `rotation`), `rotationRelativeTo` (`page` |
//! `path`).
//! `path`), `hueJitter` (°).
//! Art: `width` (%), `widthMode` (`fixed` | `pressure` | `tilt` | `bearing` | `rotation`),
//! `widthMax` (the width at the heaviest pen pressure, upright or at 180°, %), `scaleMode` (`proportional` | `stretch` | `betweenGuides`), `guideStart` and
//! `guideEnd` (% of the art's length), `direction` (`leftToRight` …), `flipAlong`, `flipAcross`,
@@ -187,6 +187,7 @@ pub(super) fn fields(b: &Brush, def: Value, f: &mut Map<String, Value>) {
f.insert(mode_key(key), json!(mode.id()));
}
f.insert("rotationRelativeTo".into(), json!(if s.rotation_relative_to_path { "path" } else { "page" }));
f.insert("hueJitter".into(), json!(s.hue_jitter));
}
BrushKind::Art(a) => {
let (mode, start, end) = match a.scale {
@@ -268,6 +269,7 @@ pub(super) fn params(d: &Dialog) -> Value {
p[*key] = json!([clamped(d, &min_key(key), range), clamped(d, &max_key(key), range)]);
}
p["modes"] = json!(SCATTER.map(|(key, _)| scatter_mode(d, key).id()));
p["hue_jitter"] = json!(clamped(d, "hueJitter", Scatter::HUE_JITTER_RANGE));
p
}
"art" => {
@@ -457,6 +459,9 @@ fn scatter_body(ui: &mut egui::Ui, d: &mut Dialog) {
ui.add_space(4.0);
let relative = [("page", tl!("Page")), ("path", tl!("Path"))];
super::form::choice(ui, d, "rotationRelativeTo", tl!("Rotation relative to:"), (LABEL_W, 104.0), &relative);
ui.add_space(4.0);
// Each copy turns its colors' hue by its own amount up to this many degrees either way.
widgets::label_row(ui, tl!("Hue Jitter:"), LABEL_W, |ui| number(ui, d, "hueJitter", Scatter::HUE_JITTER_RANGE, "°", true));
}
fn art_body(ui: &mut egui::Ui, d: &mut Dialog) {
@@ -472,6 +477,13 @@ fn art_body(ui: &mut egui::Ui, d: &mut Dialog) {
d.fields.insert("widthMode".into(), json!(m.id()));
}
});
// A path sets its own width, flips, overlap and colorization, not how the art scales or runs.
if d.bool(super::brush_options::OBJECT) {
flips(ui, d);
ui.add_space(4.0);
super::form::check(ui, d, "overlap", tl!("Overlap"));
return;
}
ui.add_space(4.0);
widgets::section_header(ui, tl!("Brush Scale Options"));
let scales = [
@@ -532,8 +544,11 @@ fn pattern_body(ui: &mut egui::Ui, d: &mut Dialog) {
slider_row(ui, d, "scale", tl!("Scale:"), PatternBrush::SCALE_RANGE);
widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| number(ui, d, "spacing", PatternBrush::SPACING_RANGE, "%", true));
ui.add_space(6.0);
tiles(ui, d);
ui.add_space(6.0);
// The tiles belong to the brush; a path sets its own scale, spacing, flips, fit and colorization.
if !d.bool(super::brush_options::OBJECT) {
tiles(ui, d);
ui.add_space(6.0);
}
flips(ui, d);
widgets::section_header(ui, tl!("Fit"));
let fits = [("stretch", tl!("Stretch to fit")), ("addSpace", tl!("Add space to fit")), ("approximate", tl!("Approximate path"))];
+152 -8
View File
@@ -17,10 +17,18 @@
//! New Brush opens the dialog for a brush that does not exist yet ([`open_new`]), with `__create`
//! and, for dropped art, `__ids`: OK runs `brush.new` instead, which gives a name another brush has
//! a number, and Cancel adds nothing.
//!
//! The panel menu's Options of Selected Object opens the dialog on the brush of the first selected
//! brushed path, with that path's own settings ([`open_object`]), with `__object`, `__targets` (the
//! brushed paths), `__opened` (the values it opened with) and `__doc` (the uid of the document). It
//! has no name, and of the Art and Pattern brush options only those a path can set for itself. OK
//! runs `brush.objectOptions` with the values changed since it opened: the paths change and the
//! brush stays as it is. OK after another document has become the active one changes nothing.
use egui::{Color32, Sense, Stroke, pos2, vec2};
use serde_json::{Map, Value, json};
use vectorcraft_brush::{Bristle, Brush, BrushKind, Calligraphic, Variation};
use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind};
use super::swatch_options::{grid, label};
use super::{DialogSpec, brush_art_options, form};
@@ -39,6 +47,18 @@ const CREATE: &str = "__create";
/// The field of such a dialog holding the ids of the art dropped on the Brushes panel.
const IDS: &str = "__ids";
/// The field of a Brush Options dialog that Options of Selected Object opened.
pub(super) const OBJECT: &str = "__object";
/// The field of such a dialog holding the brushed paths it sets.
const TARGETS: &str = "__targets";
/// The field of such a dialog holding the `brush.objectOptions` params it opened with.
const OPENED: &str = "__opened";
/// The field of such a dialog holding the uid of the document it opened in.
const DOC: &str = "__doc";
/// Calligraphic values: (field, label, suffix, decimals), in [`Calligraphic::RANGES`] order.
const CALLI: [(&str, &str, &str, usize); 3] = [("angle", "Angle:", "°", 0), ("roundness", "Roundness:", "%", 0), ("size", "Size:", " pt", 1)];
@@ -73,6 +93,9 @@ const NIB_W: f32 = 120.0;
const STROKE_W: f32 = 400.0;
fn heading(d: &Dialog) -> String {
if d.bool(OBJECT) {
return tl!("Options of Selected Object").into();
}
match d.str("__type").as_str() {
"bristle" => tl!("Bristle Brush Options").into(),
"calligraphic" => tl!("Calligraphic Brush Options").into(),
@@ -146,6 +169,118 @@ fn target(app: &VectorcraftApp) -> Option<String> {
selected.or_else(|| vectorcraft_brush::current(&st.doc))
}
/// The brush that the first brushed stroke of path `id` paints with, in library `lib`.
fn stroke_brush<'a>(app: &VectorcraftApp, lib: &'a [Brush], id: NodeId) -> Option<&'a Brush> {
let n = app.session.active()?.doc.node(id)?;
n.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Stroke(st) => st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)),
AppearanceItem::Fill(_) => None,
})
}
/// Can Options of Selected Object open: does a selected path or compound path (or one in a
/// selected group, but not a path inside a compound path, as `brush.objectOptions` takes them)
/// paint with a brush, are all their brushes of one type, and can a path set options of its own
/// for that type? These are the selections `brush.objectOptions` takes.
pub fn object_available(app: &VectorcraftApp) -> bool {
let Some(st) = app.session.active() else { return false };
let ids = st.selection.subjects();
if ids.is_empty() {
return false;
}
let lib = vectorcraft_brush::library(&st.doc);
let doc = &st.doc;
// The brush of every brushed stroke of the paths the command sets.
let mut brushes: Vec<&Brush> = vec![];
for id in ids {
let Some(n) = doc.node(*id) else { continue };
n.walk(&mut |c| {
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
let in_compound = doc.parent_of(c.id).and_then(|p| doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
if !own || in_compound {
return;
}
for i in &c.appearance.items {
if let AppearanceItem::Stroke(s) = i
&& let Some(b) = s.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name))
{
brushes.push(b);
}
}
});
}
let Some(first) = brushes.first() else { return false };
!first.kind.stroke_option_keys().is_empty() && brushes.iter().all(|b| b.kind.type_id() == first.kind.type_id())
}
/// Open Options of Selected Object: the Brush Options of the brush the first selected brushed path
/// paints with, at that path's own settings, without the name and with only the options a path can
/// set for itself.
pub fn open_object(app: &mut VectorcraftApp) -> Result<Value, String> {
let r = app.run("brush.objectOptions", json!({}))?;
let targets = r["ids"].clone();
let first = targets.get(0).and_then(Value::as_u64).map(NodeId).ok_or("no path painted with a brush is selected")?;
let st = app.session.active().ok_or("no document open")?;
let (lib, doc) = (vectorcraft_brush::library(&st.doc), st.uid);
let b = stroke_brush(app, &lib, first).ok_or("no path painted with a brush is selected")?;
let own: Map<String, Value> = serde_json::from_value(r["options"].clone()).unwrap_or_default();
let edited = b.with_stroke_options(&own)?;
let def = serde_json::to_value(&edited).map_err(|e| e.to_string())?;
let mut f = fields(&edited, def)?;
f.insert("__brush".into(), json!(b.name));
f.insert(OBJECT.into(), json!(true));
f.insert(TARGETS.into(), targets);
f.insert(DOC.into(), json!(doc));
let mut d = Dialog { kind: KIND.into(), fields: f };
let opened = object_params(&d, b.kind.stroke_option_keys());
d.fields.insert(OPENED.into(), Value::Object(opened));
d.fields.insert("__keys".into(), json!(b.kind.stroke_option_keys()));
app.ui.dialog = Some(d);
Ok(Value::Null)
}
/// The fields' `brush.options` params that a path can set for itself (`keys`).
fn object_params(d: &Dialog, keys: &[&str]) -> Map<String, Value> {
match params(d) {
Value::Object(p) => p.into_iter().filter(|(k, _)| keys.contains(&k.as_str())).collect(),
_ => Map::new(),
}
}
/// What of option value `now` changed from `was`, the value it opened with: `None` when nothing
/// did; of a range or a list of modes, the items that changed with `null` for the others, and of a
/// colorization, the fields that changed. The paths keep their own values for the rest.
fn changed_part(was: Option<&Value>, now: Value) -> Option<Value> {
match (was, now) {
(Some(w), n) if *w == n => None,
(Some(Value::Array(w)), Value::Array(n)) if w.len() == n.len() => {
Some(Value::Array(w.iter().zip(n).map(|(w, n)| if *w == n { Value::Null } else { n }).collect()))
}
(Some(Value::Object(w)), Value::Object(n)) => Some(Value::Object(n.into_iter().filter(|(f, v)| w.get(f) != Some(v)).collect())),
(_, n) => Some(n),
}
}
/// OK of Options of Selected Object: `brush.objectOptions` on the paths it opened for, with the
/// values changed since it opened ([`changed_part`]). The dialog closes when they are set. When
/// another document has become the active one, it closes as Cancel does and changes nothing.
fn confirm_object(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) {
app.ui.dialog = None;
return Ok(json!({}));
}
let keys: Vec<String> = d.fields.get("__keys").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();
let keys: Vec<&str> = keys.iter().map(String::as_str).collect();
let opened = d.fields.get(OPENED).and_then(Value::as_object).cloned().unwrap_or_default();
let changed: Map<String, Value> =
object_params(d, &keys).into_iter().filter_map(|(k, v)| changed_part(opened.get(&k), v).map(|v| (k, v))).collect();
let r = app.run("brush.objectOptions", json!({ "ids": d.fields.get(TARGETS).cloned().unwrap_or_default(), "params": changed }));
if r.is_ok() {
app.ui.dialog = None;
}
r
}
/// Open the Brush Options of a new brush of type `ty` (`calligraphic` | `scatter` | `art` |
/// `bristle` | `pattern`), the second step of New Brush. The fields start from the type's default
/// values and the name "New <Type> Brush", numbered when another brush has it. A scatter or art
@@ -240,7 +375,13 @@ fn create(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
/// OK: make the new brush when New Brush opened the dialog, else edit the brush.
fn ok(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
if d.bool(CREATE) { create(app, d) } else { confirm(app, d) }
if d.bool(CREATE) {
create(app, d)
} else if d.bool(OBJECT) {
confirm_object(app, d)
} else {
confirm(app, d)
}
}
/// The value of field `key` within `range`.
@@ -279,13 +420,16 @@ fn params(d: &Dialog) -> Value {
}
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
grid(ui, |ui| {
label(ui, tl!("Name:"));
let max = if d.str("__type") == "bristle" { Bristle::MAX_NAME_CHARS } else { usize::MAX };
form::text_edit_limited(ui, d, "name", 240.0, max);
ui.end_row();
});
ui.add_space(10.0);
// Options of Selected Object sets a path's settings, not the brush, so it has no name.
if !d.bool(OBJECT) {
grid(ui, |ui| {
label(ui, tl!("Name:"));
let max = if d.str("__type") == "bristle" { Bristle::MAX_NAME_CHARS } else { usize::MAX };
form::text_edit_limited(ui, d, "name", 240.0, max);
ui.end_row();
});
ui.add_space(10.0);
}
match d.str("__type").as_str() {
"bristle" => bristle_body(app, ui, d),
"calligraphic" => calligraphic_body(app, ui, d),
@@ -153,6 +153,7 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() {
"Random",
"Rotation relative to:",
"Page",
"Hue Jitter:",
"Colorization",
"Method:",
"Tints",
@@ -163,10 +164,11 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() {
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.f64("sizeMin", 0.0), d.f64("sizeMax", 0.0), d.str("sizeMode")), (60.0, 140.0, "random".into()));
assert_eq!((d.str("rotationRelativeTo"), d.str("colorization")), ("page".into(), "tints".into()));
// Values are kept within their ranges (rotation here); Fixed takes the first value.
assert_eq!(d.f64("hueJitter", -1.0), 0.0);
// Values are kept within their ranges (rotation and hue jitter here); Fixed takes the first value.
set(
&mut app,
json!({"sizeMode": "fixed", "sizeMin": 5000, "spacingMode": "pressure", "rotationMin": -400, "rotationRelativeTo": "path", "colorization": "hueShift"}),
json!({"sizeMode": "fixed", "sizeMin": 5000, "spacingMode": "pressure", "rotationMin": -400, "rotationRelativeTo": "path", "colorization": "hueShift", "hueJitter": 400}),
);
assert!(shown(&mut app).contains("Hue Shift"));
super::super::confirm(&mut app).unwrap();
@@ -177,12 +179,14 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() {
(&json!([5000.0, 140.0]), &json!(-180.0), &json!(["fixed", "pressure", "random", "random"]))
);
assert_eq!((&def["rotation_relative_to_path"], &def["colorization"]["method"]), (&json!(true), &json!("hueShift")));
assert_eq!(def["hue_jitter"], json!(180.0));
assert!(def["colorization"]["key"].is_object(), "the art's colour as the key: {def}");
assert!(drawn_height(&app, id) > before, "the stroke redraws with the bigger confetti");
// Opened again, it shows what was set.
app.run("ui.brushOptions", json!({"name": "Confetti"})).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.str("sizeMode"), d.str("spacingMode"), d.str("colorization")), ("fixed".into(), "pressure".into(), "hueShift".into()));
assert_eq!(d.f64("hueJitter", 0.0), 180.0);
}
#[test]
@@ -883,3 +887,160 @@ fn art_width_and_pattern_scale_have_sliders() {
let shown = tree(|ui| super::super::show(&mut app, ui.ctx()));
assert_eq!(slider_value(&shown, "Scale:"), (Some(100.0), Some(1.0), Some(10000.0), Some("100%".into())));
}
/// A level line, selected, painted with brush `brush`.
fn brushed_line(app: &mut VectorcraftApp, y: f64, brush: &str) -> u64 {
let id = app.run("shape.line", json!({"x1": 20, "y1": y, "x2": 220, "y2": y})).unwrap()["id"].as_u64().unwrap();
app.run("brush.apply", json!({"name": brush, "ids": [id]})).unwrap();
id
}
/// The own brush settings of the first stroke of path `id`.
fn own_options(app: &VectorcraftApp, id: u64) -> Value {
let st = app.session.active().unwrap().doc.node(NodeId(id)).and_then(|n| n.appearance.stroke().cloned()).unwrap();
Value::Object(st.brush_options)
}
fn select(app: &mut VectorcraftApp, ids: &[u64]) {
app.run("select.set", json!({ "ids": ids })).unwrap();
}
#[test]
fn options_of_selected_object_set_one_paths_art_brush_settings() {
let mut app = app();
let a = brushed_line(&mut app, 50.0, "Arrow");
let b = brushed_line(&mut app, 100.0, "Arrow");
select(&mut app, &[a]);
assert!(object_available(&app));
app.run("ui.brushObjectOptions", json!({})).unwrap();
let text = shown(&mut app);
for label in ["Options of Selected Object", "Width:", "Flip Along", "Flip Across", "Overlap", "Colorization", "OK"] {
assert!(text.contains(label), "{label} in {text}");
}
for label in ["Name:", "Brush Scale Options", "Direction:"] {
assert!(!text.contains(label), "{label} in {text}");
}
set(&mut app, json!({"width": 50}));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(own_options(&app, a), json!({"width": 50.0}));
assert_eq!(own_options(&app, b), json!({}));
assert_eq!(app.run("brush.get", json!({"name": "Arrow"})).unwrap()["width"], json!(100.0), "the brush keeps its width");
// Opened again, it shows the path's own width, and OK without a change changes nothing.
app.run("ui.brushObjectOptions", json!({})).unwrap();
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("width", 0.0), 50.0);
super::super::confirm(&mut app).unwrap();
assert_eq!(own_options(&app, a), json!({"width": 50.0}));
}
#[test]
fn options_of_selected_object_change_only_the_values_edited_on_each_path() {
let mut app = app();
let a = brushed_line(&mut app, 50.0, "Confetti");
let b = brushed_line(&mut app, 100.0, "Confetti");
app.run("brush.objectOptions", json!({"ids": [a], "params": {"size": [50, 80]}})).unwrap();
app.run("brush.objectOptions", json!({"ids": [b], "params": {"size": [60, 120]}})).unwrap();
select(&mut app, &[a, b]);
app.run("ui.brushObjectOptions", json!({})).unwrap();
// The dialog shows the first path's values; only the smallest size is edited.
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("sizeMax", 0.0), 80.0);
set(&mut app, json!({"sizeMin": 40}));
super::super::confirm(&mut app).unwrap();
assert_eq!(own_options(&app, a)["size"], json!([40.0, 80.0]));
assert_eq!(own_options(&app, b)["size"], json!([40.0, 120.0]), "the second path keeps its own largest size");
}
/// The modes the first stroke of path `id` draws its brush `brush` with.
fn drawn_modes(app: &VectorcraftApp, id: u64, brush: &str) -> Vec<Variation> {
let lib = vectorcraft_brush::library(&app.session.active().unwrap().doc);
let b = lib.iter().find(|b| b.name == brush).unwrap();
let own = own_options(app, id);
match b.with_stroke_options(own.as_object().unwrap()).unwrap().kind {
BrushKind::Calligraphic(c) => c.modes().to_vec(),
BrushKind::Scatter(s) => s.modes().to_vec(),
_ => vec![],
}
}
#[test]
fn options_of_selected_object_keep_the_modes_they_show_when_a_value_changes() {
let mut app = app();
// Confetti's size varies at random from 60% to 140%; a size of 60% to 60% leaves the mode the
// dialog shows.
let s = brushed_line(&mut app, 50.0, "Confetti");
select(&mut app, &[s]);
app.run("ui.brushObjectOptions", json!({})).unwrap();
assert_eq!(app.ui.dialog.as_ref().unwrap().str("sizeMode"), "random");
set(&mut app, json!({"sizeMax": 60}));
super::super::confirm(&mut app).unwrap();
assert_eq!(own_options(&app, s)["size"], json!([60.0, 60.0]));
assert_eq!(drawn_modes(&app, s, "Confetti")[0], Variation::Random);
// 6 pt. Flat's angle is Fixed; a variation set without a mode keeps it Fixed.
let c = brushed_line(&mut app, 100.0, "6 pt. Flat");
select(&mut app, &[c]);
app.run("ui.brushObjectOptions", json!({})).unwrap();
assert_eq!(app.ui.dialog.as_ref().unwrap().str("angleMode"), "fixed");
set(&mut app, json!({"angleVariation": 30}));
super::super::confirm(&mut app).unwrap();
assert_eq!(drawn_modes(&app, c, "6 pt. Flat")[0], Variation::Fixed);
}
#[test]
fn options_of_selected_object_show_what_a_path_can_set_for_each_type() {
let mut app = app();
// Calligraphic: OK without a change leaves the path on the brush's settings.
let c = brushed_line(&mut app, 40.0, "6 pt. Flat");
select(&mut app, &[c]);
app.run("ui.brushObjectOptions", json!({})).unwrap();
let text = shown(&mut app);
for label in ["Angle:", "Roundness:", "Size:"] {
assert!(text.contains(label), "{label} in {text}");
}
super::super::confirm(&mut app).unwrap();
assert_eq!(own_options(&app, c), json!({}));
// Pattern: scale, spacing, flips and fit, not the tiles.
let p = brushed_line(&mut app, 80.0, "Diamonds");
select(&mut app, &[p]);
app.run("ui.brushObjectOptions", json!({})).unwrap();
let text = shown(&mut app);
for label in ["Scale:", "Spacing:", "Fit", "Flip Along"] {
assert!(text.contains(label), "{label} in {text}");
}
assert!(!text.contains("Side Tile"), "{text}");
set(&mut app, json!({"scale": 200}));
super::super::confirm(&mut app).unwrap();
assert_eq!(own_options(&app, p), json!({"scale": 200.0}));
// Bristle brushes, nothing selected and two brush types are refused.
let r = brushed_line(&mut app, 120.0, "Bristle Round");
select(&mut app, &[r]);
assert!(!object_available(&app));
assert!(app.run("ui.brushObjectOptions", json!({})).is_err());
select(&mut app, &[c, p]);
assert!(!object_available(&app), "the menu item is off for two brush types");
assert!(app.run("ui.brushObjectOptions", json!({})).is_err());
assert!(app.ui.dialog.is_none());
select(&mut app, &[p, r]);
assert!(!object_available(&app), "the menu item is off for a pattern and a bristle brush");
app.run("select.none", json!({})).unwrap();
assert!(!object_available(&app));
}
#[test]
fn options_of_selected_object_change_nothing_after_another_document_became_active() {
let mut app = app();
let a = brushed_line(&mut app, 50.0, "Arrow");
select(&mut app, &[a]);
app.run("ui.brushObjectOptions", json!({})).unwrap();
set(&mut app, json!({"width": 50}));
// A second document with a brushed path of the same id becomes the active one.
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
app.run("document.activate", json!({"index": 1})).unwrap();
let other = brushed_line(&mut app, 50.0, "Arrow");
assert_eq!(other, a);
// OK closes the dialog as Cancel does.
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(own_options(&app, other), json!({}), "the second document's path keeps the brush's settings");
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(own_options(&app, a), json!({}), "the first document's path keeps the brush's settings");
}
@@ -44,7 +44,7 @@ pub fn replace(app: &mut VectorcraftApp, name: &str, ids: &[u64]) {
return;
}
// A preview on a copy of the document checks the art without changing anything.
if !app.session.in_interaction() && app.session.begin_interaction("Replace Brush Art").is_ok() {
if !app.session.in_interaction() && app.begin_interaction("Replace Brush Art").is_ok() {
let checked = app.session.preview("brush.replaceArt", &params);
// The interaction began above, on the active document: ending it puts that document back
// as it was, and can fail only when no document is open, when there is nothing to put back.
+118 -7
View File
@@ -12,14 +12,20 @@
//! preset picked), `bullet` (`dot`, `dash`, `circle` or `square`), `number` (`arabic`,
//! `upperLetters`, `lowerLetters`, `upperRoman`, `lowerRoman`, `twoDigits` or `threeDigits`),
//! `listAlign` (`left` or `right`), `listLevel` (1 to 9; 1 for paragraphs in no list),
//! `leftIndent` and `firstLineIndent` (pt), as `text.setFormat` takes them, with `__initial` (the
//! values it opened with) and `__targets` (the type and range it acts on).
//! `leftIndent` and `firstLineIndent` (pt), as `text.setFormat` takes them, `startAt` (the Numbers
//! tab's Start At box) and `startNumber` (its number, 1 to 999999999), with `__initial` (the values
//! it opened with) and `__targets` (the type and range it acts on).
//!
//! Start At is VectorCraft's own: on, OK gives the first numbered paragraph the number in the
//! field (`text.setFormat` `startNumber`), and the numbered paragraphs after it count on from it;
//! off, the paragraphs count on from the paragraph before (`restartNumbering` false). The box is on
//! when the paragraphs have a number of their own, off when none has, and blank when they differ.
//!
//! Behavior reference (public documentation):
//! <https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html>.
use serde_json::{Map, Value, json};
use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, NumberStyle, ParaList};
use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList};
use super::swatch_options::label;
use super::{DialogSpec, form};
@@ -52,7 +58,7 @@ const ARROWS: egui::EventFilter = egui::EventFilter { tab: false, horizontal_arr
/// The fields `ui.dialog.set` can set while the dialog does not hold them: the dialog leaves a
/// field out where the paragraphs differ, and holds no `bullet` or `number` for paragraphs in no
/// list or in another kind of list.
const INPUTS: [&str; 7] = ["list", "bullet", "number", "listAlign", "listLevel", "leftIndent", "firstLineIndent"];
const INPUTS: [&str; 9] = ["list", "bullet", "number", "listAlign", "listLevel", "leftIndent", "firstLineIndent", "startAt", "startNumber"];
pub(super) const SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Bullets and Numbering").into(),
@@ -85,8 +91,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
crate::panels::character::text_style(app).ok_or("select some type first")?;
// While typing, the dialog acts on the paragraphs of the text being edited.
let mut targets = json!({});
if let Some((id, a, b)) = crate::panels::character::text_editing(app) {
crate::panels::character::end_typing(app);
if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? {
targets = json!({"ids": [id.0], "start": a, "end": b});
}
let mut values = Map::new();
@@ -114,6 +119,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
if let Some(v) = shared_para_field(app, |p| p.first_line_indent) {
values.insert("firstLineIndent".into(), json!(v));
}
// …and Start At: on with the number when the paragraphs share one, off when none has one.
if let Some(start) = shared_para(app, |p| p.list.and_then(|l| l.start)) {
values.insert("startAt".into(), json!(start.is_some()));
if let Some(n) = start {
values.insert("startNumber".into(), json!(n));
}
}
let tab = tab.unwrap_or(if list == Some("number") { "numbers" } else { "bullets" });
let mut fields = Value::Object(values.clone());
fields[INITIAL] = Value::Object(values);
@@ -210,6 +222,29 @@ fn number_tab(ui: &mut egui::Ui, d: &mut Dialog) {
}
None => {}
}
ui.add_space(8.0);
start_at(ui, d);
}
/// The Start At box and its number, 1 to [`MAX_LIST_START`]: the box shows a dash while the
/// paragraphs' numbers differ, and a click then turns it on; the number field is dimmed unless the
/// box is on, and shows 1 until a number is typed.
fn start_at(ui: &mut egui::Ui, d: &mut Dialog) {
ui.horizontal(|ui| {
let on = d.fields.get("startAt").and_then(Value::as_bool);
if widgets::check3(ui, tl!("Start at:"), on, true) {
d.fields.insert("startAt".into(), json!(on != Some(true)));
}
let value = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0);
ui.add_enabled_ui(on == Some(true), |ui| {
let name = Some(tl!("Start at:"));
if let Some(v) =
widgets::range_field_named(ui, ("bullets-numbering", "startNumber"), name, value, 1.0..=f64::from(MAX_LIST_START), "", 0, 90.0)
{
d.fields.insert("startNumber".into(), json!(v));
}
});
});
}
/// A row of preset buttons named `names`, `current` selected, each drawn by `paint` (painter,
@@ -367,6 +402,20 @@ fn params(d: &Dialog) -> Map<String, Value> {
{
p.insert("listLevel".into(), json!(l));
}
// …and Start At, unless the paragraphs are made bulleted or taken out of their list: on, the
// number shown; off, the paragraphs count on from the one before.
if let Some(on) = d.fields.get("startAt").and_then(Value::as_bool)
&& !matches!(field("list"), Some("none" | "bullet"))
{
let n = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0);
let was_on = initial.and_then(|m| m.get("startAt")).and_then(Value::as_bool);
let was_n = initial.and_then(|m| m.get("startNumber")).and_then(Value::as_f64);
if on && (was_on != Some(true) || was_n != Some(n)) {
p.insert("startNumber".into(), json!(n));
} else if !on && was_on != Some(false) {
p.insert("restartNumbering".into(), json!(false));
}
}
// For paragraphs in a list and paragraphs in none, an indent left as it was is not sent:
// `text.setFormat` then gives each paragraph that joins the list its hanging indent.
let mixed = initial.is_some_and(|m| !m.contains_key("list"));
@@ -690,7 +739,8 @@ mod tests {
app.run("text.setFormat", json!({"ids": [id], "listAlign": "right", "listLevel": 2, "start": 0, "end": 0})).unwrap();
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
let held = app.ui.dialog.as_ref().unwrap().fields.clone();
for key in INPUTS {
// Neither paragraph has a number of its own, so Start at is off, not blank.
for key in INPUTS.into_iter().filter(|k| !["startAt", "startNumber"].contains(k)) {
assert!(!held.contains_key(key), "{key} is blank");
}
let fields = json!([
@@ -737,6 +787,67 @@ mod tests {
assert_eq!((first(&app, id).0.map(|l| l.level), paras(&app, id).1.list.map(|l| l.level)), (Some(2), Some(2)));
}
/// Start at: the box opens off for paragraphs without a number of their own and on with the
/// number for one that has it; a change shows on the type at once, OK keeps it as one undo
/// step, Cancel puts the type back, and turning the box off sends `restartNumbering` false.
#[test]
fn start_at_gives_the_first_numbered_paragraph_its_number() {
let (mut app, id) = app();
app.run("text.setFormat", json!({"number": "arabic"})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
let d = app.ui.dialog.clone().unwrap();
assert_eq!((d.fields.get("startAt"), d.fields.get("startNumber")), (Some(&json!(false)), None));
set(&mut app, "startAt", json!(true));
set(&mut app, "startNumber", json!(4));
frame(&mut app);
let starts = |app: &VectorcraftApp| {
let (one, two) = paras(app, id);
(one.list.and_then(|l| l.start), two.list.and_then(|l| l.start))
};
assert_eq!(starts(&app), (Some(4), None), "previewed on the type");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the preview adds no undo step");
super::super::cancel(&mut app);
assert_eq!(starts(&app), (None, None), "Cancel puts it back");
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
set(&mut app, "startAt", json!(true));
set(&mut app, "startNumber", json!(4));
super::super::confirm(&mut app).unwrap();
assert_eq!((starts(&app), app.session.active().unwrap().history.undo.len()), ((Some(4), None), undo + 1));
// One paragraph with a number and one without: the box is blank, and OK sends nothing for it.
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
let d = app.ui.dialog.clone().unwrap();
assert!(!d.fields.contains_key("startAt") && !changes(&params(&d)));
// The blank box shows a dash, not an empty box.
use egui::accesskit::{Role, Toggled};
let mut shown = d.clone();
let tree = crate::widgets::accessibility_tests::tree(|ui| start_at(ui, &mut shown));
let check = tree.iter().find(|n| n.label() == Some("Start at:") && n.role() == Role::CheckBox).map(|n| n.toggled());
assert_eq!(check, Some(Some(Toggled::Mixed)));
// A preset that makes the paragraphs bulleted sends no number.
set(&mut app, "startAt", json!(true));
pick_preset(&mut app, "bullet", Some("dot"));
let p = params(app.ui.dialog.as_ref().unwrap());
assert!(!p.contains_key("startNumber") && !p.contains_key("restartNumbering"));
super::super::cancel(&mut app);
// A paragraph with a number opens the box on with it, and off sends it back to counting on.
let solo = app.run("text.create", json!({"x": 10, "y": 200, "text": "Solo"})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [solo]})).unwrap();
app.run("text.setFormat", json!({"number": "arabic", "startNumber": 9})).unwrap();
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
let d = app.ui.dialog.clone().unwrap();
assert_eq!((d.fields.get("startAt"), d.f64("startNumber", 0.0)), (Some(&json!(true)), 9.0));
assert!(!changes(&params(&d)), "nothing changed yet");
set(&mut app, "startAt", json!(false));
assert_eq!(params(app.ui.dialog.as_ref().unwrap()).get("restartNumbering"), Some(&json!(false)));
super::super::confirm(&mut app).unwrap();
let start = match &app.session.active().unwrap().doc.node(NodeId(solo)).unwrap().kind {
NodeKind::Text(t) => t.para_at(0).list.map(|l| l.start),
_ => panic!("not text"),
};
assert_eq!(start, Some(None), "still numbered, with no number of its own");
}
/// `text.setFormat` sets `listLevel` only on paragraphs in a list, so a Level change alone on
/// paragraphs in no list sends nothing and adds no undo step; with a preset it applies.
#[test]
@@ -1036,6 +1036,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id {
/// (as drawn last frame). The section list stays put while the content scrolls. Returns whether
/// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`).
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
super::modal::fits_itself(ui);
let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height());
let content = ui.ctx().data(|m| m.get_temp::<f32>(content_id(ui))).unwrap_or(0.0);
let rest = (window - content).max(0.0);
@@ -1073,7 +1074,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
ui.separator();
if let Ok(attrs) = edited_attrs(d) {
for (key, value) in attrs {
ui.label(format!("{}: {}", super::humanize(&key), value));
ui.label(super::form::attribute_line(&key, &value));
}
}
}
+62 -10
View File
@@ -103,11 +103,22 @@ impl Channel {
Channel::Green => "G",
}
}
fn is_hsb(self) -> bool {
/// The channel's name, translated: Hue, Saturation, Brightness, Red, Green or Blue.
pub(crate) fn name(self) -> &'static str {
match self {
Channel::Hue => tl!("Hue"),
Channel::Saturation => tl!("Saturation"),
Channel::Brightness => tl!("Brightness"),
Channel::Red => tl!("Red"),
Channel::Green => tl!("Green"),
Channel::Blue => tl!("Blue"),
}
}
pub(crate) fn is_hsb(self) -> bool {
matches!(self, Channel::Hue | Channel::Saturation | Channel::Brightness)
}
/// Indices of (slider, field x, field y) into the channel's space: [h, s, b] or [r, g, b].
fn axes(self) -> (usize, usize, usize) {
pub(crate) fn axes(self) -> (usize, usize, usize) {
match self {
Channel::Hue => (0, 1, 2),
Channel::Saturation => (1, 0, 2),
@@ -119,7 +130,7 @@ impl Channel {
}
/// The color field's axes (across, up) as keys and screen readers see them: hue in degrees,
/// saturation and brightness in percent, red, green and blue from 0 to 255.
fn field_axes(self) -> [widgets::FieldAxis<'static>; 2] {
pub(crate) fn field_axes(self) -> [widgets::FieldAxis<'static>; 2] {
let axis = |i: usize| {
let (name, units, suffix) = match (self.is_hsb(), i) {
(true, 0) => (tl!("Hue"), 360.0, "°"),
@@ -282,6 +293,19 @@ pub(super) fn over_effect(parent: &Dialog, field: &str, colour: Color) -> Dialog
);
d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default());
store(&mut d, &Picked::of(colour));
d.fields.insert(crate::screen_color::PICKER_ID.into(), json!(crate::screen_color::picker_id()));
d
}
/// The entry of the dialog's color list that a Color Picker opened with [`over_list_entry`] sets.
const COLOUR_INDEX: &str = "__colourIndex";
/// The Color Picker over the dialog `parent`, on `colour`, that sets entry `index` of the dialog's
/// list of colors `field` (Document Setup's `gridColors`) with its OK and goes back to it, leaving
/// the other entries as they are. Cancel goes back to `parent` as it was. It previews nothing.
pub(super) fn over_list_entry(parent: &Dialog, field: &str, index: usize, colour: Color) -> Dialog {
let mut d = over_effect(parent, field, colour);
d.fields.insert(COLOUR_INDEX.into(), json!(index));
d
}
@@ -360,6 +384,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction {
let p = picked(d);
let original = d.fields.get("original").and_then(color_value).unwrap_or(p.color);
let gamut = gamut_fix(app, ui.ctx(), "picker-gamut", &p.color);
super::modal::fits_itself(ui);
let (side, values_w, button_w, stacked) = layout_size(ui);
let field_w = side + SLIDER_GAP + SLIDER_W;
let content_w = if stacked { field_w.max(values_w) } else { field_w + COLUMN_GAP + values_w };
@@ -406,10 +431,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction {
let track = |z: f32| c32(&Picked::of(slider_color(channel, z, x, y)).snapped(web).color);
let (v, suffix, max) = channel_value(channel, &p);
let shown = widgets::SliderValue::field(v as f64, 0.0..=max as f64, suffix, 0);
if let (Some(z), _) =
widgets::channel_slider_valued(ui, "cp-slider", tl!(channel.label()), Some(shown), z, vec2(SLIDER_W, side), &track)
{
pick = Some(field_pick(channel, z, x, y));
match widgets::channel_slider_stepped(
ui,
"cp-slider",
tl!(channel.label()),
Some(shown),
z,
true,
vec2(SLIDER_W, side),
&track,
) {
(Some(z), ..) => pick = Some(field_pick(channel, z, x, y)),
(None, _, Some(v)) => pick = Some(field_pick(channel, (v / max as f64) as f32, x, y)),
_ => {}
}
});
}
@@ -495,13 +529,18 @@ fn preview(app: &mut VectorcraftApp, d: &mut Dialog) {
if unchanged || !selected {
return;
}
let _ = app.session.begin_interaction(if artboard {
let label = if artboard {
"Artboard Options"
} else if d.bool("stroke") {
"Stroke Color"
} else {
"Fill Color"
});
};
// A failure to begin (typing that can't be kept) shows, and nothing previews.
if let Err(e) = app.begin_interaction(label) {
app.status(e);
return;
}
if let Err(e) = app.session.preview(cmd, &params) {
app.status(e.to_string());
}
@@ -724,7 +763,20 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
if let Some(field) = d.fields.get(COLOUR_FIELD).and_then(Value::as_str) {
let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?;
parent.fields.insert(field.to_string(), json!(picked(d).color.to_hex()));
let hex = json!(picked(d).color.to_hex());
match d.fields.get(COLOUR_INDEX) {
None => {
parent.fields.insert(field.to_string(), hex);
}
Some(index) => {
let entry = index
.as_u64()
.and_then(|i| usize::try_from(i).ok())
.and_then(|i| parent.fields.get_mut(field)?.as_array_mut()?.get_mut(i))
.ok_or("no such color")?;
*entry = hex;
}
}
// The dialog previews the new colour when it comes back: end this picker's interaction, as
// Cancel does, so the dialog starts its preview afresh.
let _ = app.session.cancel_interaction();
@@ -670,7 +670,8 @@ fn warnings_fit_below_the_preview_without_widening_the_dialog() {
}
let after = ctx.memory(|m| m.area_rect(id)).unwrap();
assert!((before.size() - after.size()).length() < 1.0, "{before:?} vs {after:?}");
click_at(&ctx, &mut app, warnings[1].center());
// The cube icon left of the web correction corrects the color too.
click_at(&ctx, &mut app, warnings[1].center() - vec2(19.0, 0.0));
assert!(is_web_safe(&picked(app.ui.dialog.as_ref().unwrap()).color), "web correction remains clickable");
}
+129 -3
View File
@@ -36,7 +36,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
let mut rows = v.as_str() == Some("rows");
ui.add_space(4.0);
egui::Grid::new("text-flow").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {
let row = ui.label(egui::RichText::new(format!("{}:", tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text));
let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text));
ui.label_inputs_by(row.id, |ui| {
ui.horizontal(|ui| {
if widgets::radio(ui, tl!("By Rows"), rows, true) {
@@ -250,8 +250,14 @@ const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "des
const AREA_FIT: form::Choices = &[("None", "none"), ("Auto Size", "autoHeight"), ("Shrink Text to Fit", "shrinkText"), ("Block", "block")];
/// Area Type Options › First Baseline.
const FIRST_BASELINE: form::Choices =
&[("Ascent", "ascent"), ("Cap Height", "capHeight"), ("x Height", "xHeight"), ("Leading", "leading"), ("Fixed", "fixed")];
const FIRST_BASELINE: form::Choices = &[
("Ascent", "ascent"),
("Cap Height", "capHeight"),
("x Height", "xHeight"),
("Leading", "leading"),
("Em Box Height", "emBoxHeight"),
("Fixed", "fixed"),
];
/// Area Type Options › Align (vertical alignment of the lines in each row/column).
const VERTICAL_ALIGN: form::Choices = &[("Top", "top"), ("Center", "center"), ("Bottom", "bottom"), ("Justify", "justify")];
@@ -313,6 +319,35 @@ mod tests {
assert_eq!(t.area.vertical_align, VerticalAlign::Center);
}
/// Area Type Options › First Baseline offers Em Box Height: OK sets it with its Min, and the
/// dialog opens again with it chosen.
#[test]
fn area_type_options_dialog_sets_the_em_box_height_first_baseline() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let id = app.run("text.create", json!({"x": 20, "y": 20, "text": "Hello", "area": {"width": 200, "height": 200}})).unwrap()["id"]
.as_u64()
.unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
// The labels `i18n::tests::first_baseline_choices_are_in_complete_catalogs` checks.
let labels: Vec<&str> = choices("text.areaOptions", "firstBaseline").unwrap().iter().map(|(l, _)| *l).collect();
assert_eq!(labels, ["Ascent", "Cap Height", "x Height", "Leading", "Em Box Height", "Fixed"]);
crate::menus::invoke(&mut app, "text.areaOptions", json!({}));
assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "ascent");
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx()));
out.textures_delta.clear();
let fields = &mut app.ui.dialog.as_mut().unwrap().fields;
fields.insert("firstBaseline".into(), json!("emBoxHeight"));
fields.insert("firstBaselineMin".into(), json!(4.0));
crate::dialogs::confirm(&mut app).unwrap();
let NodeKind::Text(t) = &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") };
assert_eq!((t.area.first_baseline, t.area.first_baseline_min), (vectorcraft_doc::FirstBaseline::EmBoxHeight, 4.0));
crate::menus::invoke(&mut app, "text.areaOptions", json!({}));
assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "emBoxHeight");
}
/// Area Type Options shows the gutter between rows beside the gutter, and OK sets a gutter
/// between rows of its own.
#[test]
@@ -433,6 +468,47 @@ mod tests {
assert!(p[0] == p[1] && p[1] == p[2] && p[0] < 128, "red in grayscale: {p:?}");
}
/// Object › Rasterize… opens this dialog with its options as parameter labels (#7991): in
/// French the heading, every field label and the resolution's unit ("ppp") are drawn in French.
#[test]
fn rasterize_dialog_is_drawn_in_the_ui_language() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let entries = crate::menus::menu_entries(&app);
let item = entries.iter().find(|e| e.path == ["Object"] && e.label == "Rasterize…").expect("listed");
let (cmd, p) = crate::menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
crate::menus::invoke(&mut app, &cmd, p);
assert_eq!(app.ui.dialog.as_ref().unwrap().str("__label"), "Rasterize");
let keys: Vec<String> = app.ui.dialog.as_ref().unwrap().fields.keys().filter(|k| !k.starts_with("__")).cloned().collect();
assert_eq!(keys.len(), 6, "{keys:?}");
assert_eq!(form::humanize("ppi"), "Resolution:");
crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap());
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
let heading = heading_label(app.ui.dialog.as_ref().unwrap());
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(heading, "Pixelliser");
let french = ["Ajouter autour de l’objet", "Lissage", "Arrière-plan", "Masque d’écrêtage", "Modèle colorimétrique", "Résolution", "ppp"];
for s in french {
assert!(shown.contains(s), "{s} in {shown}");
}
for s in ["Rasterize", "Add Around", "Anti Alias", "Background", "Clipping Mask", "Color Model", "Resolution", "Ppi", "ppi"] {
assert!(!shown.contains(s), "{s} left in English: {shown}");
}
// Every language with complete menus heads the dialog as the menu item that opened it
// reads, and has a row for each label, the unit and the Color Model choices.
for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) {
let menu = crate::i18n::tr(lang, &item.label);
assert_ne!(menu, item.label, "{}: menu item", lang.code());
assert_eq!(heading_in(lang, "Rasterize"), menu.trim_end_matches('…').trim_end(), "{}: heading", lang.code());
let labels = keys.iter().map(|k| form::humanize(k).trim_end_matches(':').to_string());
for label in labels.chain(["{n} ppi", "Grayscale", "Bitmap"].map(String::from)) {
assert!(crate::i18n::has(lang, &label), "{}: {label}", lang.code());
}
}
}
/// Object › Path › Clean Up… opens this dialog headed "Clean Up", which most catalogs hold only
/// as the menu label "Clean Up…" (#7991). In French the heading and every option are translated.
#[test]
@@ -530,6 +606,56 @@ mod tests {
assert_eq!(cols(&app), 2, "one Undo takes the whole change back");
}
/// Grid Repeat Options labels its column fields Columns and Flip Columns, as the Rows and Flip
/// Rows fields beside them are spelled out.
#[test]
fn grid_repeat_options_spell_out_columns() {
let mut app = grid_options_app();
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
for s in ["Rows:", "Columns:", "Flip Rows:", "Flip Columns:"] {
assert!(shown.contains(s), "{s} in {shown}");
}
assert!(!shown.contains("Cols"), "no Cols label: {shown}");
}
/// Object › Create Gradient Mesh… opens this dialog with the menu's rows, cols, appearance and
/// highlight. In French the heading and the four labels are translated, and "cols" is labeled
/// Columns (#7991).
#[test]
fn create_gradient_mesh_dialog_is_drawn_in_the_ui_language() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
let entries = crate::menus::menu_entries(&app);
let item = entries.iter().find(|e| e.path == ["Object"] && e.label == "Create Gradient Mesh…").expect("listed");
let (cmd, p) = crate::menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
crate::menus::invoke(&mut app, &cmd, p);
assert_eq!(app.ui.dialog.as_ref().unwrap().str("__label"), "Create Gradient Mesh");
assert_eq!(form::humanize("cols"), "Columns:");
crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap());
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
let heading = heading_label(app.ui.dialog.as_ref().unwrap());
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(heading, "Créer un filet de dégradé");
for s in ["Créer un filet de dégradé", "Lignes", "Colonnes", "Aspect"] {
assert!(shown.contains(s), "{s} in {shown}");
}
for s in ["Create Gradient Mesh", "Rows", "Cols", "Columns", "Appearance", "Highlight"] {
assert!(!shown.contains(s), "{s} left in English: {shown}");
}
// Every language with complete menus heads the dialog as the menu item reads and has the
// four labels.
for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) {
let menu = crate::i18n::tr(lang, &item.label);
assert_ne!(menu, item.label, "{}: menu item", lang.code());
assert_eq!(heading_in(lang, "Create Gradient Mesh"), menu.trim_end_matches('…').trim_end(), "{}: heading", lang.code());
for key in ["rows", "cols", "appearance", "highlight"] {
let label = form::humanize(key);
assert!(crate::i18n::has(lang, label.trim_end_matches(':')), "{}: {label}", lang.code());
}
}
}
/// Radial and Mirror Repeat Options have no Preview (their public pages list none): their
/// fields apply on OK only, and the dialog takes no `preview`.
#[test]
+83 -4
View File
@@ -4,7 +4,7 @@ use super::DialogSpec;
use crate::{VectorcraftApp, state::Dialog, theme::Tokens, widgets};
use egui::{RichText, Ui};
use serde_json::{Value, json};
use vectorcraft_doc::dimension::DimensionOptions;
use vectorcraft_doc::dimension::{ArrowStyle, DimensionOptions};
pub const KIND: &str = "dimensionOptions";
pub(super) const SPEC: DialogSpec = DialogSpec {
@@ -32,6 +32,10 @@ const UNITS: Choices = &[
];
const LINE_TYPES: Choices = &[("solid", "Solid"), ("dashed", "Dashed"), ("dotted", "Dotted")];
const ARROWS: Choices = &[("filled", "Filled"), ("open", "Open"), ("tick", "Tick"), ("none", "None")];
/// The style of each `ARROWS` entry, in the same order.
const ARROW_STYLES: [ArrowStyle; 4] = [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None];
/// The size of an Arrow Style preview: a line with the head at its right end.
const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 16.0);
const POSITIONS: Choices = &[("away", "Away from the Line"), ("between", "Between Line and Object")];
const ALIGNMENTS: Choices = &[("left", "Left"), ("center", "Center"), ("right", "Right")];
@@ -69,6 +73,29 @@ fn choose(ui: &mut Ui, fields: &mut serde_json::Map<String, Value>, key: &str, l
});
changed
}
/// The Arrow Style dropdown: each style shows a drawn preview of its arrowhead before its name, in
/// the open list and in the closed field.
fn arrow_style(ui: &mut Ui, fields: &mut serde_json::Map<String, Value>, id: &str) -> bool {
const KEY: &str = "arrowStyle";
let mut changed = false;
widgets::label_row(ui, tl!("Arrow Style:"), 96.0, |ui| {
let current = fields.get(KEY).and_then(Value::as_str).unwrap_or_default();
let shown = ARROWS.iter().position(|(v, _)| *v == current);
let names: Vec<&str> = ARROWS.iter().map(|(_, s)| tl!(*s)).collect();
let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, _: bool| {
if let Some(style) = ARROW_STYLES.get(i) {
crate::panels::stroke::paint_arrow(ui, rect, style.arrowhead().as_ref(), false, ink);
}
};
if let Some((value, _)) =
widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| ARROWS.get(i))
{
fields.insert(KEY.into(), json!(value));
changed = true;
}
});
changed
}
fn number(ui: &mut Ui, fields: &mut serde_json::Map<String, Value>, key: &str, label: &str, range: (f64, f64), suffix: &str) -> bool {
let mut changed = false;
widgets::label_row(ui, tl!(label), 96.0, |ui| {
@@ -160,7 +187,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
color(ui, f, "lineColor");
});
ui.horizontal(|ui| {
choose(ui, f, "arrowStyle", "Arrow Style:", ARROWS);
arrow_style(ui, f, "arrowStyle");
number(ui, f, "arrowScale", "Arrow Scale:", (1.0, 1000.0), "%");
});
});
@@ -211,7 +238,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
Ok(o) => {
let sample = o.label(72.0, false).unwrap_or_default();
let t = Tokens::get(ui.ctx());
ui.label(RichText::new(format!("{}: {sample}", tl!("Preview (1 inch on the page)"))).color(t.text));
ui.label(RichText::new(format!("{} {sample}", crate::i18n::colon(tl!("Preview (1 inch on the page)")))).color(t.text));
}
Err(e) => {
ui.colored_label(Tokens::get(ui.ctx()).text, e);
@@ -310,7 +337,7 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) {
changed |= number(ui, &mut f, "lineWeight", "Line Weight:", (0.1, 100.0), "pt");
changed |= color(ui, &mut f, "lineColor");
});
ui.horizontal(|ui| changed |= choose(ui, &mut f, "arrowStyle", "Arrow Style:", ARROWS));
ui.horizontal(|ui| changed |= arrow_style(ui, &mut f, "props-arrowStyle"));
ui.horizontal(|ui| {
changed |= number(ui, &mut f, "fontSize", "Font Size:", (1.0, 1000.0), "pt");
changed |= color(ui, &mut f, "textColor");
@@ -377,4 +404,56 @@ mod tests {
assert!(text.contains(label), "{label}: {text}");
}
}
/// Whether a frame drew a picture (a textured mesh) just before the text `name` on its line.
fn picture_before(out: &egui::FullOutput, name: &str) -> bool {
fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, pictures: &mut Vec<egui::Rect>) {
match s {
egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.visual_bounding_rect())),
egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => pictures.push(m.calc_bounds()),
egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, pictures)),
_ => {}
}
}
let (mut texts, mut pictures) = (vec![], vec![]);
for c in &out.shapes {
collect(&c.shape, &mut texts, &mut pictures);
}
texts
.iter()
.filter(|(t, _)| t == name)
.any(|(_, r)| pictures.iter().any(|p| p.max.x <= r.min.x + 1.0 && r.min.x - p.max.x < 16.0 && p.min.y < r.max.y && p.max.y > r.min.y))
}
/// The frame `f` draws, once its previews are loaded.
fn frame(app: &mut VectorcraftApp, mut f: impl FnMut(&mut VectorcraftApp, &mut Ui)) -> egui::FullOutput {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)).textures_delta.clear();
ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui))
}
/// The Arrow Style field of the Tool Options and of Properties shows the style's arrowhead,
/// drawn, before its name (#8049).
#[test]
fn arrow_style_shows_a_drawn_arrowhead() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("tool.options", json!({"tool":"dimension"})).unwrap();
let out = frame(&mut app, |app, ui| super::super::show(app, ui.ctx()));
assert!(picture_before(&out, "Filled"), "Tool Options");
app.ui.dialog = None;
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":{"arrowStyle":"tick"}})).unwrap();
let out = frame(&mut app, properties_section);
assert!(picture_before(&out, "Tick"), "Properties");
}
/// Each Arrow Style entry previews the style its value names.
#[test]
fn arrow_previews_follow_the_listed_styles() {
assert_eq!(ARROWS.len(), ARROW_STYLES.len());
for ((value, _), style) in ARROWS.iter().zip(ARROW_STYLES) {
assert_eq!(serde_json::to_value(style).unwrap(), json!(value));
}
}
}
+287 -10
View File
@@ -175,17 +175,30 @@ fn general(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool
close
}
/// The id of the Transparency tab's box that shows grid color `index` (0 or 1).
fn grid_color_box_id(index: usize) -> egui::Id {
egui::Id::unique(("grid-color-box", index))
}
/// The grid colors' hex codes that Document Setup `d` holds now (empty strings for entries that are
/// not strings).
fn grid_colors(d: &Dialog) -> Vec<String> {
d.fields.get("gridColors").and_then(Value::as_array).map(|a| a.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect()).unwrap_or_default()
}
fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
let t = Tokens::get(ui.ctx());
widgets::subheader(ui, tl!("Transparency Grid"));
let sizes: Vec<(&str, &str)> = GridSize::ALL.iter().map(|g| (g.id(), g.label())).collect();
choice(ui, d, "gridSize", tl!("Grid Size:"), &sizes);
let colors: Vec<String> = d
.fields
.get("gridColors")
.and_then(Value::as_array)
.map(|a| a.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect())
.unwrap_or_default();
// A preset name in the fields (any case, as `document.setup` takes it) becomes the preset's two
// colors, which the hex fields and the Color Picker edit one at a time.
if let Some((_, pair)) =
d.fields.get("gridColors").and_then(Value::as_str).and_then(|n| GRID_COLOR_PRESETS.iter().find(|(p, _)| p.eq_ignore_ascii_case(n)))
{
d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex())));
}
let colors = grid_colors(d);
let preset = GRID_COLOR_PRESETS
.iter()
.find(|(_, pair)| colors.len() == 2 && colors.iter().zip(pair).all(|(h, c)| h.eq_ignore_ascii_case(&c.to_hex())))
@@ -196,18 +209,40 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex())));
}
});
// The two colours (the first is also the paper colour): editing either makes them Custom.
// The two colours (the first is also the paper colour): editing either makes them Custom. A
// click on a color's box, or Space or Enter with the keyboard on it, opens the Color Picker on
// that color (white when its hex is not a color), and the picker's OK sets that color. The
// picker opens after the row, on the color Document Setup holds then: a press on a box ends a
// hex field's editing in the same frame, and that field's edit is the color the picker opens on.
// A hex field's edit replaces its own color in the pair Document Setup holds when it commits.
let mut pick = None;
widgets::label_row(ui, "", LABEL, |ui| {
for i in 0..2 {
let hex = colors.get(i).map_or("", |h| h.trim_start_matches('#'));
let colour = vectorcraft_color::Color::from_hex(hex);
let name = format!("{} {}", tl!("Grid Colors:"), i + 1);
let (chip, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover());
if let Some(c) = vectorcraft_color::Color::from_hex(hex) {
let resp = ui.interact(chip, grid_color_box_id(i), egui::Sense::click());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name));
let keyed = resp.has_focus()
&& ui.input_mut(|inp| {
inp.consume_key(egui::Modifiers::NONE, egui::Key::Space) | inp.consume_key(egui::Modifiers::NONE, egui::Key::Enter)
});
if resp.clicked() || keyed {
pick = Some(i);
}
if resp.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
if let Some(c) = colour {
ui.painter().rect_filled(chip, 2.0, crate::panels::c32(&c));
}
ui.painter().rect_stroke(chip, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside);
let name = format!("{} {}", tl!("Grid Colors:"), i + 1);
if resp.has_focus() {
ui.painter().rect_stroke(chip.expand(2.0), 3.0, ui.visuals().selection.stroke, egui::StrokeKind::Outside);
}
if let Some(c) = widgets::hex_field_named(ui, ("grid-color", i), Some(&name), hex).and_then(|h| vectorcraft_color::Color::from_hex(&h)) {
let mut v = colors.clone();
let mut v = grid_colors(d);
v.resize(2, "#ffffff".into());
v[i] = c.to_hex();
d.fields.insert("gridColors".into(), json!(v));
@@ -215,6 +250,10 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
ui.add_space(10.0);
}
});
if let Some(i) = pick {
let c = grid_colors(d).get(i).and_then(|h| vectorcraft_color::Color::from_hex(h.trim_start_matches('#')));
*d = super::color_picker::over_list_entry(d, "gridColors", i, c.unwrap_or(vectorcraft_color::Color::WHITE));
}
ui.add_space(4.0);
check(ui, d, "simulatePaper", tl!("Simulate Colored Paper"));
ui.add_space(14.0);
@@ -635,4 +674,242 @@ mod tests {
assert_eq!(fill(&app, id), before);
assert_eq!(undo_steps(&app), steps);
}
/// The Light pair a new document's transparency grid starts with.
const LIGHT: [&str; 2] = ["#ffffff", "#cccccc"];
fn hex(h: &str) -> Color {
Color::from_hex(h).unwrap_or_else(|| panic!("bad hex {h}"))
}
/// The grid colors Document Setup `d` holds.
fn dialog_grid(d: &crate::state::Dialog) -> Vec<Color> {
d.fields["gridColors"].as_array().unwrap().iter().map(|c| hex(c.as_str().unwrap())).collect()
}
/// A new document with Document Setup open on its Transparency tab, drawn in the context returned.
fn transparency_tab() -> (VectorcraftApp, egui::Context) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("file.documentSetup", json!({})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("tab".into(), json!("Transparency"));
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
crate::theme::apply(&ctx, Default::default());
for _ in 0..4 {
dialog_frame(&mut app, &ctx, vec![]);
}
(app, ctx)
}
/// Clicks the box of grid color `index`.
fn click_grid_box(app: &mut VectorcraftApp, ctx: &egui::Context, index: usize) {
let at = ctx.read_response(super::grid_color_box_id(index)).unwrap_or_else(|| panic!("no box {index}")).rect.center();
let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
dialog_frame(app, ctx, vec![Event::PointerMoved(at), button(true)]);
dialog_frame(app, ctx, vec![button(false)]);
}
/// The Color Picker is open over Document Setup, on `color`, and Document Setup's OK has not run.
fn assert_picker_over_setup(app: &VectorcraftApp, color: &str, case: &str) {
let d = app.ui.dialog.as_ref().unwrap_or_else(|| panic!("{case}: no dialog"));
assert_eq!(d.kind, "colorPicker", "{case}");
assert_eq!(d.fields.get("color").and_then(vectorcraft_engine::cmd::color_value), Some(hex(color)), "{case}");
assert_eq!(crate::dialogs::parent(d).map(|p| p.kind), Some(super::KIND.to_string()), "{case}");
assert_eq!(undo_steps(app), 0, "{case}: Document Setup's OK has not run");
}
/// A click on either grid color's box opens the Color Picker over Document Setup on that
/// color. Its OK sets only that color, the Grid Colors menu names the pair (Custom, or the
/// preset it matches), and Document Setup's OK applies the pair in one undo step.
#[test]
fn a_grid_color_box_opens_the_color_picker_and_its_ok_sets_that_color() {
for (index, picked, pair, name) in [(0, "#00ff00", ["#00ff00", "#cccccc"], "Custom"), (1, "#c4dcff", ["#ffffff", "#c4dcff"], "Blue")] {
let (mut app, ctx) = transparency_tab();
click_grid_box(&mut app, &ctx, index);
assert_picker_over_setup(&app, LIGHT[index], name);
app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!(picked));
crate::dialogs::confirm(&mut app).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.map(hex).to_vec()), "{name}");
assert_eq!(undo_steps(&app), 0, "{name}: the picker's OK leaves the document as it is");
dialog_frame(&mut app, &ctx, vec![]);
let texts: Vec<String> = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect();
assert!(texts.iter().any(|t| t == name), "{name}: {texts:?}");
crate::dialogs::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
let st = app.session.active().unwrap();
assert_eq!((st.doc.setup.grid_colors, st.doc.setup.grid_colors_name()), (pair.map(hex), name));
assert_eq!(undo_steps(&app), 1, "{name}");
app.run("edit.undo", json!({})).unwrap();
assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex), "{name}");
}
}
/// With the keyboard on a grid color's box, Enter or Space opens the Color Picker on that
/// color instead of pressing Document Setup's OK.
#[test]
fn enter_or_space_on_a_grid_color_box_opens_the_color_picker() {
for (index, key) in [(0, egui::Key::Enter), (1, egui::Key::Space)] {
let (mut app, ctx) = transparency_tab();
ctx.memory_mut(|m| m.request_focus(super::grid_color_box_id(index)));
dialog_frame(&mut app, &ctx, vec![]);
let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
dialog_frame(&mut app, &ctx, vec![press]);
assert_picker_over_setup(&app, LIGHT[index], &format!("{key:?}"));
}
}
/// Cancel in the Color Picker goes back to Document Setup with the grid colors as they were,
/// and so does its OK on the color it opened on; Document Setup's OK then records no undo step.
#[test]
fn grid_color_picker_cancel_or_an_unchanged_ok_changes_nothing() {
for cancel in [true, false] {
let (mut app, ctx) = transparency_tab();
click_grid_box(&mut app, &ctx, 1);
assert_picker_over_setup(&app, LIGHT[1], &format!("cancel {cancel}"));
if cancel {
app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000"));
crate::dialogs::cancel(&mut app);
} else {
crate::dialogs::confirm(&mut app).unwrap();
}
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, LIGHT.map(hex).to_vec()), "cancel {cancel}");
crate::dialogs::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(app.session.active().unwrap().doc.setup.grid_colors_name(), "Light");
assert_eq!(undo_steps(&app), 0, "cancel {cancel}");
}
}
/// With a preset name in Document Setup's `gridColors` field, the grid color boxes show the
/// preset's colors, and the Color Picker opens on the clicked one; its OK sets that color and
/// keeps the preset's other one.
#[test]
fn a_grid_color_box_opens_the_picker_when_the_field_names_a_preset() {
let (mut app, ctx) = transparency_tab();
app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!("blue"));
dialog_frame(&mut app, &ctx, vec![]);
click_grid_box(&mut app, &ctx, 1);
assert_picker_over_setup(&app, "#c4dcff", "blue");
app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#00ff00"));
crate::dialogs::confirm(&mut app).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, ["#ffffff", "#00ff00"].map(hex).to_vec()));
}
/// The screen color sampler works in the Color Picker of a grid color: the color sampled goes
/// to that picker, and its OK sets the grid color.
#[test]
fn the_grid_color_picker_takes_a_screen_sampled_color() {
let (mut app, ctx) = transparency_tab();
let (tx, rx) = std::sync::mpsc::channel::<crate::screen_color::Answer>();
let mut rx = Some(rx);
app.services.screen_color = Some(Box::new(move || rx.take().ok_or_else(|| "shown twice".to_string())));
click_grid_box(&mut app, &ctx, 0);
assert_picker_over_setup(&app, LIGHT[0], "before sampling");
app.run("ui.sampleScreenColor", json!({"picker": true})).unwrap();
tx.send(Ok(Some([0.0, 0.5, 1.0]))).unwrap();
crate::screen_color::poll(&mut app, &ctx);
let sampled = app.ui.dialog.as_ref().unwrap().fields.get("color").and_then(vectorcraft_engine::cmd::color_value).unwrap();
assert_ne!(sampled.to_hex(), LIGHT[0]);
crate::dialogs::confirm(&mut app).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
let grid: Vec<String> = dialog_grid(d).iter().map(Color::to_hex).collect();
assert_eq!((d.kind.as_str(), grid), (super::KIND, vec![sampled.to_hex(), LIGHT[1].to_string()]));
}
/// Clicks the hex field that shows `digits` and types `typed` over its text, leaving the edit
/// pending; returns the field's id.
fn type_into_hex_field(app: &mut VectorcraftApp, ctx: &egui::Context, digits: &str, typed: &str) -> egui::Id {
let texts = dialog_frame(app, ctx, vec![]);
let at = texts.iter().find(|(t, _)| t == digits).unwrap_or_else(|| panic!("no field {digits}: {texts:?}")).1.center();
let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
dialog_frame(app, ctx, vec![Event::PointerMoved(at), button(true)]);
dialog_frame(app, ctx, vec![button(false)]);
let field = ctx.memory(|m| m.focused()).unwrap_or_else(|| panic!("field {digits} has no focus"));
dialog_frame(app, ctx, vec![Event::Text(typed.into())]);
assert_eq!(ctx.memory(|m| m.focused()), Some(field), "the edit in {digits} is pending");
field
}
/// A click on a grid color's box whose press and release come in one frame, while that
/// color's hex field holds an edit, opens the Color Picker on the edited color: the press
/// commits the edit before the picker opens. The picker's unchanged OK keeps the edit, and the
/// other color stays as it was.
#[test]
fn a_grid_color_box_clicked_during_a_hex_edit_opens_the_picker_on_the_edit() {
for index in [0, 1] {
let (mut app, ctx) = transparency_tab();
type_into_hex_field(&mut app, &ctx, LIGHT[index].trim_start_matches('#'), "123456");
let at = ctx.read_response(super::grid_color_box_id(index)).unwrap_or_else(|| panic!("no box {index}")).rect.center();
let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
dialog_frame(&mut app, &ctx, vec![Event::PointerMoved(at), button(true), button(false)]);
let case = format!("box {index}");
assert_picker_over_setup(&app, "#123456", &case);
let mut pair = LIGHT;
pair[index] = "#123456";
assert_eq!(dialog_grid(&crate::dialogs::parent(app.ui.dialog.as_ref().unwrap()).unwrap()), pair.map(hex).to_vec(), "{case}");
crate::dialogs::confirm(&mut app).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.map(hex).to_vec()), "{case}");
}
}
/// A hex field's edit that commits in the frame a Grid Colors preset is chosen replaces only
/// its own color in the preset's pair: the other color is the preset's. The test gives the
/// field the focus while the Grid Colors menu is open, then chooses a preset with a click whose
/// press and release come in one frame.
#[test]
fn a_hex_edit_committed_with_a_preset_choice_keeps_the_presets_other_color() {
let field = {
let (mut app, ctx) = transparency_tab();
type_into_hex_field(&mut app, &ctx, "ffffff", "123456")
};
let (mut app, ctx) = transparency_tab();
let click = |app: &mut VectorcraftApp, label: &str, frames: usize| {
let texts = dialog_frame(app, &ctx, vec![]);
let at = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("no {label}: {texts:?}")).1.center();
let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
if frames == 1 {
dialog_frame(app, &ctx, vec![Event::PointerMoved(at), button(true), button(false)]);
} else {
dialog_frame(app, &ctx, vec![Event::PointerMoved(at), button(true)]);
dialog_frame(app, &ctx, vec![button(false)]);
}
};
click(&mut app, "Light", 2);
ctx.memory_mut(|m| m.request_focus(field));
dialog_frame(&mut app, &ctx, vec![]);
let select_all = Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND };
dialog_frame(&mut app, &ctx, vec![select_all, Event::Text("123456".into())]);
assert_eq!(ctx.memory(|m| m.focused()), Some(field), "the edit is pending");
let texts: Vec<String> = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect();
assert!(texts.iter().any(|t| t == "123456") && texts.iter().any(|t| t == "Blue"), "{texts:?}");
click(&mut app, "Blue", 1);
assert_eq!(dialog_grid(app.ui.dialog.as_ref().unwrap()), ["#123456", "#c4dcff"].map(hex).to_vec());
}
/// The picker's OK sets nothing when the dialog under it has no such color or is gone: it is
/// an error, and the picker stays open.
#[test]
fn grid_color_picker_without_its_color_or_its_dialog_is_an_error() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("file.documentSetup", json!({})).unwrap();
let setup = app.ui.dialog.clone().unwrap();
let mut short = setup.clone();
short.fields.insert("gridColors".into(), json!(["#ffffff"]));
let mut orphan = crate::dialogs::color_picker::over_list_entry(&setup, "gridColors", 0, Color::WHITE);
orphan.fields.remove(crate::dialogs::PARENT);
for picker in [crate::dialogs::color_picker::over_list_entry(&short, "gridColors", 1, Color::WHITE), orphan] {
app.ui.dialog = Some(picker);
app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000"));
assert!(crate::dialogs::confirm(&mut app).is_err());
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("colorPicker"));
}
assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex));
assert_eq!(undo_steps(&app), 0);
}
}
+18 -7
View File
@@ -41,7 +41,7 @@ fn three_d_refusal(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog,
} else if !app.session.in_interaction() && d.fields.get(TRIED) != Some(&params) {
// Waits for another interaction to end: trying inside it would replace its preview and
// cancel it. A failure to begin leaves no interaction: the preview below then reports it.
let _ = app.session.begin_interaction(&d.str("__label"));
let _ = app.begin_interaction(&d.str("__label"));
match app.session.preview(cmd, &params) {
Ok(_) => {
d.fields.remove(form::REFUSED);
@@ -255,9 +255,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
d.fields.insert("preview".into(), json!(pv));
if pv && (changed || pv_changed || !app.session.in_interaction()) {
let label = d.str("__label");
let _ = app.session.begin_interaction(&label);
let (cmd, p) = command(d);
let _ = app.session.preview(cmd, &p);
// A failure to begin (typing that can't be kept) shows, and nothing previews.
match app.begin_interaction(&label) {
Ok(()) => {
let (cmd, p) = command(d);
let _ = app.session.preview(cmd, &p);
}
Err(e) => app.status(e),
}
} else if !pv && pv_changed {
let _ = app.session.cancel_interaction();
}
@@ -317,6 +322,13 @@ fn center_round(x: f64) -> f64 {
(x * 1e4).round() / 1e4
}
/// The value screen readers give Blur Center at `c` (0 to 1 of the bounds): Horizontal and
/// Vertical in percent, each label followed by the UI language's colon.
pub(super) fn blur_center_value(c: [f64; 2]) -> String {
let percent = |v: f64| (v * 1000.0).round() / 10.0;
format!("{} {}%, {} {}%", crate::i18n::colon(tl!("Horizontal")), percent(c[0]), crate::i18n::colon(tl!("Vertical")), percent(c[1]))
}
/// Radial Blur's Blur Center: a box standing for the object's bounds, with the blur's pattern (rays
/// for Zoom, rings for Spin) drawn about the center. A press or a drag in the box puts the center
/// there; with the keyboard focus the arrow keys move it 1 % of the box (10 % with Shift). The
@@ -334,9 +346,8 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(CENTER_BOX, CENTER_BOX), Sense::hover());
let id = ui.scope_id().with("radial-blur-center");
let resp = ui.interact(rect, id, Sense::click_and_drag());
let percent = |v: f64| (v * 1000.0).round() / 10.0;
let name = tl!("Blur Center").to_string();
let value = format!("{}: {}%, {}: {}%", tl!("Horizontal"), percent(c[0]), tl!("Vertical"), percent(c[1]));
let value = blur_center_value(c);
let enabled = ui.is_enabled();
resp.widget_info(|| egui::WidgetInfo {
current_text_value: Some(value.clone()),
@@ -391,7 +402,7 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) {
ui.vertical(|ui| {
egui::Grid::new("blur-center-fields").num_columns(2).spacing([8.0, 8.0]).show(ui, |ui| {
for (i, label) in ["Horizontal", "Vertical"].into_iter().enumerate() {
let row = ui.label(egui::RichText::new(format!("{}:", tl!(label))).color(t.text));
let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!(label))).color(t.text));
ui.label_inputs_by(row.id, |ui| {
if let Some(x) =
widgets::range_field_named(ui, ("blur-center", i), None, c[i] * 100.0, 0.0..=100.0, &form::unit_suffix("%"), 1, 72.0)
+46 -4
View File
@@ -1,4 +1,4 @@
//! Effect → Effect Gallery: browse Photoshop-style raster filters by category, build a stack, and
//! Effect → Effect Gallery: browse raster filters by category, build a stack, and
//! apply it as separate appearance effects in one undo step.
//!
//! Each filter has a thumbnail, and the dialog has its own preview, as the
@@ -29,7 +29,7 @@ const PREVIEW_H: usize = 84;
/// Dialog kind for the Effect Gallery.
pub const KIND: &str = "effectGallery";
/// Raster effect submenus in the gallery (the six Photoshop-style folders it holds).
/// Raster effect submenus in the gallery (the six raster filter folders it holds).
const CATEGORIES: [(&str, &[&str]); 6] = [
("Artistic", &["Effect", "Artistic"]),
("Brush Strokes", &["Effect", "Brush Strokes"]),
@@ -313,11 +313,20 @@ fn stack_batch_params(stack: &[StackEntry]) -> Value {
}
/// Live canvas preview of the stack (`command.batch` would settle the dialog interaction each frame).
/// Typing in progress is kept as its own undo step first; only the gallery's own earlier preview is
/// canceled.
fn preview_stack_on_canvas(app: &mut VectorcraftApp, stack: &[StackEntry]) {
if let Err(e) = app.keep_typing() {
app.status(e);
return;
}
if app.session.in_interaction() {
let _ = app.session.cancel_interaction();
}
let _ = app.session.begin_interaction("Effect Gallery");
if let Err(e) = app.begin_interaction("Effect Gallery") {
app.status(e);
return;
}
for (i, entry) in stack.iter().enumerate() {
let params = Value::Object(entry.params.clone());
if app.run("effect.apply", json!({ "effect": entry.effect, "params": params })).is_err() {
@@ -425,7 +434,7 @@ fn sample_drawing(w: usize, h: usize) -> Vec<u8> {
out
}
/// Run one Photoshop-style filter on a premultiplied RGBA buffer. Leaves it unchanged when `id`
/// Run one raster filter on a premultiplied RGBA buffer. Leaves it unchanged when `id`
/// is not one of those filters or the buffer is the wrong size.
fn apply_pixel(id: &str, params: &Map<String, Value>, data: &mut [u8], w: usize, h: usize) {
let Some(n) = w.checked_mul(h).and_then(|n| n.checked_mul(4)) else { return };
@@ -766,6 +775,39 @@ mod tests {
assert!(app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects.is_empty());
}
/// With Real-time Drawing off, typing in progress when the stack previews is kept as a step of
/// its own, not canceled with the gallery's earlier preview.
#[test]
fn stack_preview_keeps_typing_in_progress() {
use vectorcraft_tools::{PointerEvent, PointerKind};
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap();
let id = app.run("text.create", json!({"x": 100, "y": 100, "text": "Hello", "size": 20})).unwrap()["id"].as_u64().unwrap();
let id = vectorcraft_doc::NodeId(id);
let v = vectorcraft_engine::ViewInfo::default();
app.session.select_tool("type", v).unwrap();
let b = app.session.active().unwrap().doc.bounds_of(&[id], false).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap();
}
app.session.tool_text(" world", v).unwrap();
let plain = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(id).unwrap().kind {
vectorcraft_doc::NodeKind::Text(t) => t.plain_text(),
_ => panic!("not text"),
};
assert_eq!(plain(&app), "Hello", "the typing waits");
let steps = app.session.active().unwrap().history.undo.len();
app.run("ui.effectGalleryDialog", json!({})).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("stack".into(), json!([{ "effect": "artistic.cutout", "visible": true, "params": { "levels": 3 } }]));
frame(&mut app);
let st = app.session.active().unwrap();
assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Effect Gallery"));
assert_eq!(st.history.undo.len(), steps + 1, "the typing is a step of its own");
assert_eq!(plain(&app), "Hello world");
}
#[test]
fn stack_ok_is_one_undo_step() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+112 -8
View File
@@ -6,14 +6,20 @@
//! Fields: `document.export` params (`format: eps`, `path?`, the artboard choice) and the EPS
//! options of `document.exportEps`. OK remembers the options for next time and writes the file
//! (asking where when there is no path); bad options keep the dialog open.
//!
//! Custom… beside the flattener preset opens Custom Transparency Flattener Options over the
//! dialog: its OK sets every flattener option as `flattener` (the preset then shows [Custom]) and
//! goes back to EPS Options; Cancel goes back with the options as they were. Choosing a preset
//! drops the custom options.
use serde_json::{Map, Value, json};
use vectorcraft_engine::cmd::{FlattenOptions, fileio};
use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio};
use vectorcraft_eps::{Level, Overprint, Preview};
use super::DialogSpec;
use super::document_setup::{LABEL, check, choice};
use crate::state::Dialog;
use crate::theme::Tokens;
use crate::{VectorcraftApp, io, widgets};
pub(super) const KIND: &str = "epsOptions";
@@ -25,7 +31,18 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
ok: Some("Export"),
min_width: 420.0,
max_width: Some(460.0),
inputs: |_| &["path"],
inputs: |_| &["path", "flattener"],
..DialogSpec::FORM
};
/// Custom Transparency Flattener Options, opened over EPS Options by Custom….
pub(super) const CUSTOM_KIND: &str = "epsFlattenerOptions";
pub(super) const CUSTOM_SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Custom Transparency Flattener Options").into(),
body: custom_body,
confirm: custom_confirm,
min_width: 420.0,
..DialogSpec::FORM
};
@@ -61,11 +78,12 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) {
fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone())));
}
}
fields.insert("format".into(), json!("eps"));
// A built-in preset named by id (`medium`) shows as its name.
if let Some(label) = fields.get("flattenerPreset").and_then(Value::as_str).and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase())) {
fields.insert("flattenerPreset".into(), json!(label));
// A preset asked for without options of its own replaces the custom options used last.
if params.get("flattenerPreset").is_some() && params.get("flattener").is_none() {
fields.remove("flattener");
}
fields.insert("format".into(), json!("eps"));
builtin_label(&mut fields);
app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields)));
}
@@ -90,8 +108,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let overprints: Vec<(&str, &str)> = Overprint::ALL.iter().map(|o| (o.id(), o.label())).collect();
choice(ui, d, "overprints", tl!("Overprints:"), &overprints);
let presets = app.session.flattener_presets();
let names: Vec<(&str, &str)> = presets.iter().map(|p| (p.name.as_str(), p.name.as_str())).collect();
choice(ui, d, "flattenerPreset", tl!("Preset:"), &names);
let current = flattener(d, &app.session.prefs.flattener_presets).ok();
let mut custom = false;
widgets::label_row(ui, tl!("Preset:"), LABEL, |ui| {
if let Some(p) = super::flatten::preset_dropdown(ui, "eps-flattener-preset", &presets, &d.str("flattenerPreset"), current.as_ref(), 180.0) {
d.fields.insert("flattenerPreset".into(), json!(p.name));
d.fields.remove("flattener");
}
custom = widgets::flat_button_fit(ui, tl!("Custom…"), 72.0).clicked();
});
if custom {
*d = over(d, &app.session.prefs.flattener_presets);
return false;
}
ui.add_space(8.0);
widgets::subheader(ui, tl!("Fonts"));
// Type is written as glyph outlines, which need no fonts.
@@ -122,6 +151,81 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
false
}
/// `ui.dialog.set` changed `field` of EPS Options `d`: a preset set there drops the Custom…
/// options, as choosing it in the dropdown does, and a built-in one named by id shows as its name.
pub(super) fn field_set(d: &mut Dialog, field: &str) {
if field == "flattenerPreset" {
d.fields.remove("flattener");
builtin_label(&mut d.fields);
}
}
/// A built-in preset named by id (`medium`) in `fields` shows as its name.
fn builtin_label(fields: &mut Map<String, Value>) {
if let Some(label) = fields.get("flattenerPreset").and_then(Value::as_str).and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase())) {
fields.insert("flattenerPreset".into(), json!(label));
}
}
/// The flattener options EPS Options `d` exports with: its preset, with the Custom… options over it.
fn flattener(d: &Dialog, saved: &[FlattenerPreset]) -> Result<FlattenOptions, String> {
FlattenOptions::for_export(d.fields.get("flattenerPreset").and_then(Value::as_str), d.fields.get("flattener"), saved)
}
/// Custom Transparency Flattener Options over EPS Options `parent`, on the options it exports with
/// (the default preset's while those are not valid), without alpha: EPS has none.
pub(super) fn over(parent: &Dialog, saved: &[FlattenerPreset]) -> Dialog {
let mut o = flattener(parent, saved).unwrap_or_default();
o.preserve_alpha = false;
let mut d = Dialog::new(CUSTOM_KIND, json!({}));
super::flatten::put_options(&mut d.fields, &o);
d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default());
d
}
/// The options Custom Transparency Flattener Options `d` holds.
fn custom_options(d: &Dialog) -> Result<FlattenOptions, String> {
FlattenOptions::from_params_with(&Value::Object(d.fields.clone()), &[])
}
/// Whether the EPS Options under `d` keep overprints (Overprints: Preserve).
fn overprints_kept(d: &Dialog) -> bool {
super::parent(d).is_none_or(|p| Overprint::from_id(&p.str("overprints")) != Some(Overprint::Discard))
}
/// The flattener options; the two Preserve switches show what the export does and are set by the
/// format (no alpha) and by EPS Options' Overprints.
fn custom_body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let current = custom_options(d);
// Values refused stay as entered, so that changing another option keeps them. The Preserve
// switches can't be set here, so the fields keep their own values of them.
let (mut o, unread) = super::flatten::shown_options(&d.fields, &current);
o.preserve_alpha = false;
o.preserve_overprints &= overprints_kept(d);
super::flatten::fields_editor(ui, "eps-flattener", &mut d.fields, &mut o, &unread, true);
if let Err(e) = &current {
ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5));
}
ui.add_space(8.0);
super::form::caption(ui, tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept."));
false
}
/// OK: EPS Options again, exporting with these options (a built-in preset under them, so that
/// deleting a saved preset leaves them whole); bad options keep the dialog open.
fn custom_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let mut o = custom_options(d)?;
o.preserve_alpha = false;
let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?;
if FlattenOptions::preset(&parent.str("flattenerPreset")).is_none() {
let medium = FlattenOptions::preset_label(FlattenOptions::PRESETS[1]).unwrap_or_default();
parent.fields.insert("flattenerPreset".into(), json!(medium));
}
parent.fields.insert("flattener".into(), serde_json::to_value(&o).map_err(|e| e.to_string())?);
app.ui.dialog = Some(parent);
Ok(Value::Null)
}
/// Check the options, remember them, and write the file(s).
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let params = fileio::eps::resolve(&super::form::params(d), &app.session.prefs.flattener_presets)?;
+185 -8
View File
@@ -1,7 +1,9 @@
//! Object → Expand: what to expand (Object: live shapes, type and effects; Fill: gradient and pattern fills;
//! Stroke: strokes into filled outlines) and what gradient fills become (a gradient mesh, or a
//! number of objects). Options the selection has nothing for are disabled. OK runs
//! `object.expand` as one undo step.
//! `object.expand` as one undo step and keeps its choices for the rest of the app's run: the dialog
//! opens on them, and Object › Expand… chosen with Alt (Option) expands with them at once
//! ([`expand_now`]).
//!
//! Fields: `object`, `fill`, `stroke`, `gradient` (`objects` | `mesh`), `steps` (1..1000), and
//! `__object`, `__fill`, `__stroke` (that option has something to expand: `object.expand.info`),
@@ -31,15 +33,51 @@ pub(crate) fn appearance_first() -> &'static str {
tl!("Expand Appearance first (Object › Expand Appearance)")
}
/// Open Expand for the selection, every option on (as `object.expand {}` does). A selection with
/// appearance attributes (effects, several fills or strokes…) refuses with [`appearance_first`]:
/// the menu item is dimmed for it.
/// Open Expand for the selection, on the choices OK last expanded with in this run of the app, or
/// every option on (as `object.expand {}` does) before that. A selection with appearance attributes
/// (effects, several fills or strokes…) refuses with [`appearance_first`]: the menu item is dimmed
/// for it.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fields = fields(app)?;
app.ui.dialog = Some(Dialog::new(KIND, fields));
Ok(Value::Null)
}
/// Object › Expand… chosen with Alt (Option): expand the selection at once, in one undo step, with
/// the choices OK last expanded with in this run of the app (the dialog's defaults before that), as
/// OK in the dialog opened on them would. When none of those choices has something to expand in the
/// selection, the dialog opens on them instead, and nothing changes. A selection with appearance
/// attributes refuses with [`appearance_first`], as [`open`] does.
pub fn expand_now(app: &mut VectorcraftApp) -> Result<Value, String> {
let d = Dialog::new(KIND, fields(app)?);
if !OPTIONS.iter().any(|(key, _)| d.bool(key) && option_enabled(&d, key)) {
app.ui.dialog = Some(d);
return Ok(Value::Null);
}
app.run(CMD, params(&d))
}
/// The choices OK last expanded with (`app.ui.expand_options`), when each one holds a value the
/// dialog shows: a switch for Object, Fill and Stroke, `objects` or `mesh`, and 1 to 1000 steps.
fn remembered(app: &VectorcraftApp) -> Option<&Value> {
let o = &app.ui.expand_options;
let switches = OPTIONS.iter().all(|(key, _)| o[key].is_boolean());
let gradient = matches!(o["gradient"].as_str(), Some("objects" | "mesh"));
let steps = o["steps"].as_f64().is_some_and(|n| (1.0..=MAX_STEPS as f64).contains(&n.round()));
(switches && gradient && steps).then_some(o)
}
/// The dialog's fields for the selection: the remembered choices (or the defaults) and what each
/// option has to expand.
fn fields(app: &mut VectorcraftApp) -> Result<Value, String> {
let info = app.session.execute("object.expand.info", &json!({})).map_err(|e| e.to_string())?;
if info["appearance"] == json!(true) {
return Err(appearance_first().into());
}
let mut fields = json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS});
let mut fields = match remembered(app) {
Some(o) => json!({"object": o["object"], "fill": o["fill"], "stroke": o["stroke"], "gradient": o["gradient"], "steps": o["steps"]}),
None => json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS}),
};
for (key, _) in OPTIONS {
fields[format!("__{key}")] = info[key].clone();
}
@@ -47,8 +85,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
for key in ["fill", "stroke", "gradient"] {
fields[format!("__{key}_symbol")] = json!(info["symbolArt"][key] == json!(true));
}
app.ui.dialog = Some(Dialog::new(KIND, fields));
Ok(Value::Null)
Ok(fields)
}
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
@@ -112,8 +149,12 @@ fn params(d: &Dialog) -> Value {
})
}
/// OK: expand, and keep the choices once the expansion succeeded.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
run_and_close(app, CMD, params(d))
let choices = params(d);
let r = run_and_close(app, CMD, choices.clone())?;
app.ui.expand_options = choices;
Ok(r)
}
#[cfg(test)]
@@ -253,4 +294,140 @@ mod tests {
app.run("select.none", json!({})).unwrap();
assert!(!crate::menus::enabled(&app, "ui.expandDialog"));
}
/// A rectangle with a linear gradient fill and no stroke is selected.
fn gradient_rectangle(app: &mut VectorcraftApp) {
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap();
app.run("paint.setFill", json!({"gradient": {"kind": "linear"}})).unwrap();
app.run("paint.setStroke", json!({"none": true})).unwrap();
}
/// Object › Expand… from the in-window menu, with Alt held or not.
fn choose_expand(app: &mut VectorcraftApp, alt: bool) {
let entries = crate::menus::menu_entries(app);
let e = entries.iter().find(|e| e.path == ["Object"] && e.label == "Expand…").expect("Object › Expand…");
assert!(e.enabled, "Expand… is available");
let target = crate::menus::click_target(&e.label, e.command.as_deref().unwrap(), &e.params);
let held = if alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE };
let (cmd, p) = crate::menus::with_held_keys(target, held);
crate::menus::invoke(app, &cmd, p);
}
/// Whether the selected object is a clip group holding a gradient mesh (Expand Gradient To ›
/// Gradient Mesh) rather than solid objects.
fn expanded_to_a_mesh(app: &VectorcraftApp) -> bool {
let st = app.session.doc().unwrap();
let g = st.doc.node(st.selection.objects[0]).unwrap();
let NodeKind::Group { children, clip: true } = &g.kind else { panic!("a clip group: {:?}", g.kind) };
children.iter().any(|c| matches!(c.kind, NodeKind::Mesh(_)))
}
#[test]
fn the_dialog_opens_on_the_choices_ok_last_expanded_with() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
gradient_rectangle(&mut app);
choose_expand(&mut app, false);
let d = app.ui.dialog.as_mut().expect("the Expand dialog");
d.fields.insert("gradient".into(), json!("mesh"));
d.fields.insert("steps".into(), json!(12));
d.fields.insert("stroke".into(), json!(false));
super::super::confirm(&mut app).unwrap();
assert!(expanded_to_a_mesh(&app));
app.run("edit.undo", json!({})).unwrap();
let kept = json!({"object": true, "fill": true, "stroke": false, "gradient": "mesh", "steps": 12.0});
choose_expand(&mut app, false);
assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept, "it opens on the choices OK expanded with");
// Cancel leaves them as they were.
app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("objects"));
super::super::cancel(&mut app);
assert_eq!(app.ui.expand_options, kept);
// So does an OK that fails, and nothing changes.
choose_expand(&mut app, false);
app.ui.dialog.as_mut().unwrap().fields.insert("steps".into(), json!(5000));
let before = app.session.doc().unwrap().doc.clone();
assert!(super::super::confirm(&mut app).is_err());
assert_eq!(app.session.doc().unwrap().doc, before);
assert_eq!(app.ui.expand_options, kept);
choose_expand(&mut app, false);
assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept);
}
#[test]
fn alt_expands_at_once_with_the_choices_ok_last_expanded_with() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
gradient_rectangle(&mut app);
choose_expand(&mut app, false);
app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("mesh"));
super::super::confirm(&mut app).unwrap();
app.run("edit.undo", json!({})).unwrap();
let undo = app.session.doc().unwrap().history.undo.len();
choose_expand(&mut app, true);
assert!(app.ui.dialog.is_none(), "no dialog");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
assert!(expanded_to_a_mesh(&app), "the kept Gradient Mesh choice");
}
#[test]
fn alt_before_any_ok_expands_with_the_defaults() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
gradient_rectangle(&mut app);
let undo = app.session.doc().unwrap().history.undo.len();
choose_expand(&mut app, true);
assert!(app.ui.dialog.is_none(), "no dialog");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
assert!(!expanded_to_a_mesh(&app), "the gradient becomes objects, the default");
assert!(app.ui.expand_options.is_null(), "Alt keeps no choices of its own");
}
#[test]
fn alt_opens_the_dialog_when_the_kept_choices_expand_nothing_in_the_selection() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap();
// Fill alone was kept, and a plain rectangle has no gradient or pattern fill.
app.ui.expand_options = json!({"object": false, "fill": true, "stroke": false, "gradient": "objects", "steps": 255.0});
let before = app.session.doc().unwrap().doc.clone();
let undo = app.session.doc().unwrap().history.undo.len();
choose_expand(&mut app, true);
let d = app.ui.dialog.as_ref().expect("the Expand dialog");
assert_eq!(params(d), app.ui.expand_options, "it opens on the kept choices");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "nothing recorded");
assert_eq!(app.session.doc().unwrap().doc, before);
}
#[test]
fn alt_refuses_a_selection_with_appearance_attributes_and_a_bad_immediate() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
zig_zag_line(&mut app);
let before = app.session.doc().unwrap().doc.clone();
assert_eq!(app.run("ui.expandDialog", json!({"immediate": true})).unwrap_err(), appearance_first());
assert!(app.ui.dialog.is_none());
assert_eq!(app.session.doc().unwrap().doc, before, "the line is left as it was");
app.run("effect.expandAppearance", json!({})).unwrap();
assert!(app.run("ui.expandDialog", json!({"immediate": "yes"})).is_err());
assert!(app.ui.dialog.is_none());
app.run("ui.expandDialog", json!({"immediate": false})).unwrap();
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND));
}
#[test]
fn kept_choices_with_a_value_the_dialog_does_not_show_are_left_out() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
gradient_rectangle(&mut app);
for bad in [
json!({"object": "yes", "fill": true, "stroke": true, "gradient": "mesh", "steps": 12}),
json!({"object": true, "fill": true, "stroke": true, "gradient": "strips", "steps": 12}),
json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh", "steps": 0}),
json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh"}),
] {
app.ui.expand_options = bad;
app.run("ui.expandDialog", json!({})).unwrap();
assert_eq!(
params(app.ui.dialog.as_ref().unwrap()),
json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": 255.0})
);
app.ui.dialog = None;
}
}
}
@@ -1,4 +1,4 @@
//! File → Export → Export for Screens, laid out as Illustrator's: on the left the Artboards and
//! File → Export → Export for Screens: on the left the Artboards and
//! Assets tabs (thumbnails with checkboxes, in a grid or a list), Clear Selection and the prefix;
//! on the right Select (All, a range or Full Document, Include Bleed, Include Artboard Fill), the destination (folder
//! picker, Open Location after Export, Create Sub-folders by scale or by format; the web downloads
@@ -721,7 +721,7 @@ fn tiles(
ui.painter().galley(label_pos, galley, t.text);
false
};
// The checkbox sits on the thumbnail's lower left corner, as Illustrator's.
// The checkbox sits on the thumbnail's lower left corner.
let bx = egui::Rect::from_min_size(egui::pos2(pic.left() + 4.0, pic.bottom() - 18.0), egui::vec2(14.0, 14.0));
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bx));
if widgets::check_box(&mut child, &name, checked, true) || resp.clicked() || caption_clicked {
+9 -6
View File
@@ -16,7 +16,7 @@ use vectorcraft_geom::Point;
use vectorcraft_tools::extra::{FLARE_OPTIONS, flare_params};
use super::document_setup::check;
use super::{DialogResult, DialogSpec, form, run_and_close};
use super::{DialogResult, DialogSpec, form, set_tool_options_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
@@ -155,12 +155,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult {
values.insert(key.into(), json!(d.bool(key)));
}
if let Some((cmd, params)) = command {
// Options the tool would refuse leave the dialog open, before the flare is accepted.
vectorcraft_tools::option_check::check_values(vectorcraft_tools::create("flare").as_ref(), &values)?;
// Accept the preview once; option persistence follows successful artwork creation.
let result = form::commit_preview(app, &cmd, params)?;
app.run("tool.setOption", json!({ "tool": "flare", "values": values }))?;
Ok(result)
} else {
run_and_close(app, "tool.setOption", json!({ "tool": "flare", "values": values }))
set_tool_options_and_close(app, json!({ "tool": "flare", "values": values }))
}
}
@@ -312,10 +314,11 @@ mod tests {
super::super::confirm(&mut app).unwrap();
let parts = flare_parts(&app);
assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}");
// Out-of-range values are kept within the option's range.
app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 900, "diameter": -4}})).unwrap();
let o = app.session.tool_options_of("flare");
assert_eq!((o["opacity"].as_f64(), o["diameter"].as_f64()), (Some(100.0), Some(0.0)));
// An out-of-range value is an error, and no option changes.
let before = app.session.tool_options_of("flare");
let e = app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 50, "diameter": -4}})).unwrap_err();
assert_eq!(e, "tool `flare`: `diameter` must be a number from 0 to 1000");
assert_eq!(app.session.tool_options_of("flare"), before);
}
#[test]
+121 -19
View File
@@ -48,6 +48,53 @@ pub(crate) fn put_options(fields: &mut Map<String, Value>, o: &FlattenOptions) {
}
}
/// The options `fields` hold over `base` as they were entered, values out of range included, for
/// the editor to show while [`FlattenOptions::from_params_with`] refuses them, and the keys of the
/// values of the wrong type, which take `base`'s value here and show blank in the editor.
pub(crate) fn entered_options(fields: &Map<String, Value>, base: &FlattenOptions) -> (FlattenOptions, Vec<String>) {
let Ok(Value::Object(mut v)) = serde_json::to_value(base) else { return (base.clone(), Vec::new()) };
let mut unread = Vec::new();
for (k, val) in fields {
let Some(slot) = v.get_mut(k) else { continue };
let old = std::mem::replace(slot, val.clone());
if serde_json::from_value::<FlattenOptions>(Value::Object(v.clone())).is_err() {
v.insert(k.clone(), old);
unread.push(k.clone());
}
}
(serde_json::from_value(Value::Object(v)).unwrap_or_else(|_| base.clone()), unread)
}
/// The options a dialog's `fields` hold, for [`fields_editor`]: `current` when they are valid, else
/// the values entered over the default preset's, with the keys of the values of the wrong type.
pub(crate) fn shown_options(fields: &Map<String, Value>, current: &Result<FlattenOptions, String>) -> (FlattenOptions, Vec<String>) {
match current {
Ok(o) => (o.clone(), Vec::new()),
Err(_) => entered_options(fields, &FlattenOptions::default()),
}
}
/// [`options_editor`] on the option fields of a dialog: `o` and `unread` from [`shown_options`].
/// Each option whose control was set is written into `fields`, also when it equals the value shown,
/// so that it replaces a value of the wrong type; the other fields stay as they were entered. With
/// `fixed_preserve`, the two Preserve switches show but can't be changed.
pub(crate) fn fields_editor(
ui: &mut egui::Ui,
id: &str,
fields: &mut Map<String, Value>,
o: &mut FlattenOptions,
unread: &[String],
fixed_preserve: bool,
) {
let set = editor(ui, id, o, true, fixed_preserve, unread);
let Ok(Value::Object(m)) = serde_json::to_value(&*o) else { return };
for k in set {
if let Some(v) = m.get(k) {
fields.insert(k.into(), v.clone());
}
}
}
/// The options the fields hold (a `preset` not loaded yet: its own).
fn options(d: &Dialog, saved: &[FlattenerPreset]) -> Result<FlattenOptions, String> {
if d.str("preset") != d.str(APPLIED) {
@@ -101,10 +148,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
save_row(app, ui, d);
}
ui.add_space(10.0);
let mut o = current.clone().unwrap_or_default();
if options_editor(ui, "flatten-dialog", &mut o, true) {
put_options(&mut d.fields, &o);
}
// Values refused stay as entered, so that changing another option keeps them.
let (mut o, unread) = shown_options(&d.fields, &current);
fields_editor(ui, "flatten-dialog", &mut d.fields, &mut o, &unread, false);
if let Err(e) = &current {
ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5));
}
@@ -180,8 +226,19 @@ const FIELD: f32 = 56.0;
/// panel edit them: the raster/vector balance, both resolutions and the six switches. Returns true
/// when one changed.
pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool) -> bool {
let t = Tokens::get(ui.ctx());
let before = o.clone();
editor(ui, id, o, enabled, false, &[]);
*o != before
}
/// The option controls, with the value fields of the options named in `unread` blank. With
/// `fixed_preserve`, Preserve Alpha Transparency and Preserve Overprints and Spot Colors show but
/// can't be changed (the file format or another control sets them). Returns the keys of the
/// options whose controls were set, also to the value they showed.
fn editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool, fixed_preserve: bool, unread: &[String]) -> Vec<&'static str> {
let t = Tokens::get(ui.ctx());
let mut set = Vec::new();
let field_value = |key: &str, v: f64| (!unread.iter().any(|k| k == key)).then_some(v);
let dim = |ui: &mut egui::Ui, s: &str| {
ui.label(egui::RichText::new(tl!(s)).color(t.text_dim).size(11.5));
};
@@ -203,44 +260,51 @@ pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions
);
if let Some(b) = x.map(|x| (x as f64 * 100.0).round()).or(keyed) {
o.balance = b;
set.push("balance");
}
dim(ui, tl!("Vectors"));
let value = field_value("balance", o.balance);
if let Some(v) =
widgets::range_field_named(ui, (id, "balance"), Some(tl!("Raster/Vector Balance:")), o.balance, 0.0..=100.0, "", 0, FIELD - 12.0)
widgets::range_field_named(ui, (id, "balance"), Some(tl!("Raster/Vector Balance:")), value, 0.0..=100.0, "", 0, FIELD - 12.0)
{
o.balance = v;
set.push("balance");
}
});
ui.add_space(4.0);
egui::Grid::new((id, "resolutions")).num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| {
for (label, key) in [(tl!("Line Art and Text Resolution:"), 0), (tl!("Gradient and Mesh Resolution:"), 1)] {
for (label, key, name) in
[(tl!("Line Art and Text Resolution:"), 0, "lineArtPpi"), (tl!("Gradient and Mesh Resolution:"), 1, "gradientPpi")]
{
widgets::dim_label(ui, label);
ui.horizontal(|ui| {
let v = if key == 0 { &mut o.line_art_ppi } else { &mut o.gradient_ppi };
if let Some(n) = widgets::range_field_named(ui, (id, key), Some(label), *v, 1.0..=2400.0, "", 0, FIELD) {
if let Some(n) = widgets::range_field_named(ui, (id, key), Some(label), field_value(name, *v), 1.0..=2400.0, "", 0, FIELD) {
*v = n;
set.push(name);
}
dim(ui, "ppi");
dim(ui, super::ppi_suffix().trim());
});
ui.end_row();
}
});
ui.add_space(4.0);
let switches: [(&str, &mut bool); 6] = [
(tl!("Convert All Text to Outlines"), &mut o.text_to_outlines),
(tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines),
(tl!("Clip Complex Regions"), &mut o.clip_complex_regions),
(tl!("Anti-alias Rasters"), &mut o.anti_alias),
(tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha),
(tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints),
let switches: [(&str, &mut bool, bool, &'static str); 6] = [
(tl!("Convert All Text to Outlines"), &mut o.text_to_outlines, false, "textToOutlines"),
(tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines, false, "strokesToOutlines"),
(tl!("Clip Complex Regions"), &mut o.clip_complex_regions, false, "clipComplexRegions"),
(tl!("Anti-alias Rasters"), &mut o.anti_alias, false, "antiAlias"),
(tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha, fixed_preserve, "preserveAlpha"),
(tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints, fixed_preserve, "preserveOverprints"),
];
for (label, v) in switches {
if widgets::check(ui, label, *v, enabled) {
for (label, v, fixed, key) in switches {
if widgets::check(ui, label, *v, enabled && !fixed) {
*v = !*v;
set.push(key);
}
}
});
*o != before
set
}
#[cfg(test)]
@@ -394,4 +458,42 @@ mod tests {
assert!(super::super::confirm(&mut app).unwrap_err().contains("resolutions"));
assert!(app.ui.dialog.is_some());
}
/// Changing a switch beside a value out of range keeps the values entered.
#[test]
fn a_switch_changed_beside_a_bad_value_keeps_the_values_entered() {
let mut app = scene();
app.run("ui.flattenTransparencyDialog", json!({})).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("balance".into(), json!(20));
d.fields.insert("gradientPpi".into(), json!(9000));
d.fields.insert("lineArtPpi".into(), json!("many"));
let mut f = super::super::tests_eps::Frames::new();
let (_, at) = f.control(&mut app, "Convert All Text to Outlines", egui::accesskit::Role::CheckBox);
let before = app.ui.dialog.as_ref().unwrap().bool("textToOutlines");
f.click(&mut app, at);
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!(d.bool("textToOutlines"), !before, "the switch changes");
assert_eq!((d.f64("balance", 0.0), d.f64("gradientPpi", 0.0)), (20.0, 9000.0), "the other values stay as entered");
assert_eq!(d.fields["lineArtPpi"], json!("many"), "a value of the wrong type stays to be refused");
assert!(super::super::confirm(&mut app).is_err());
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("lineArtPpi".into(), json!(300));
assert!(super::super::confirm(&mut app).unwrap_err().contains("resolutions"));
}
/// A value of the wrong type shows blank, and typing the default preset's value into its
/// field replaces it, so OK flattens.
#[test]
fn the_default_value_typed_over_a_value_of_the_wrong_type_replaces_it() {
let mut app = scene();
app.run("ui.flattenTransparencyDialog", json!({})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("lineArtPpi".into(), json!("many"));
let default = FlattenOptions::default().line_art_ppi;
let mut f = super::super::tests_eps::Frames::new();
f.type_into(&mut app, "Line Art and Text Resolution:", &default.to_string());
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["lineArtPpi"], json!(default));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none() && !transparent_left(&app));
}
}
+154 -11
View File
@@ -111,7 +111,7 @@ fn lengths(kind: &str) -> &'static [&'static str] {
/// number: fields that ↑/↓ step by one (Shift: ten) and that do math, as the distances do.
fn suffix(kind: &str, key: &str) -> Option<&'static str> {
match (kind, key) {
("rotate" | "shear" | "reflect" | "move" | "lineSegment", "angle") => Some("°"),
("rotate" | "shear" | "reflect" | "move" | "lineSegment", "angle") | ("shear", "axisAngle") => Some("°"),
("scale", "sx" | "sy") | ("spiral", "decay") => Some("%"),
_ => None,
}
@@ -138,6 +138,7 @@ fn order(kind: &str) -> &'static [&'static str] {
"spiral" => &["radius", "decay", "segments"],
"artboardOptions" => &["name", "width", "height"],
"lineSegment" => &["length", "angle"],
"shear" => &["angle", "axis", "axisAngle"],
_ => &[],
}
}
@@ -163,8 +164,7 @@ fn choices(kind: &str, key: &str) -> Vec<(&'static str, &'static str)> {
match (kind, key) {
("offsetPath", "joins") => vec![("miter", tl!("Miter")), ("round", tl!("Round")), ("bevel", tl!("Bevel"))],
("average", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("both", "Both")],
("reflect", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("angle", "Angle")],
("shear", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical")],
("reflect" | "shear", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("angle", "Angle")],
_ => vec![],
}
}
@@ -368,11 +368,19 @@ pub(super) fn grid_then(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit, more: imp
if lengths.contains(&k.as_str()) {
length_field(ui, d, &k, &humanized(&k), unit);
} else if let Some(suffix) = suffix(&d.kind, &k) {
let row = row_label(ui, &humanized(&k));
let label = match (d.kind.as_str(), k.as_str()) {
("shear", "axisAngle") => tl!("Axis Angle").into(),
_ => humanized(&k),
};
// Shear's Axis Angle is the axis while the Angle axis is chosen, and keeps its value otherwise.
let enabled = d.kind != "shear" || k != "axisAngle" || d.str("axis") == "angle";
let row = row_label(ui, &label);
ui.label_inputs_by(row.id, |ui| {
if let Some(v) = crate::widgets::plain_field(ui, ("dlg-num", &k), d.f64(&k, 0.0), suffix, 3, FIELD_W) {
d.fields.insert(k, json!(v));
}
ui.add_enabled_ui(enabled, |ui| {
if let Some(v) = crate::widgets::plain_field(ui, ("dlg-num", &k), d.f64(&k, 0.0), suffix, 3, FIELD_W) {
d.fields.insert(k, json!(v));
}
});
});
ui.end_row();
} else if let Some(ends) = skew_ends(&d.kind, &k) {
@@ -503,7 +511,9 @@ pub(super) fn param_fields(
}
}
Value::Number(n) => {
if let Some(x) = crate::widgets::plain_field(ui, ("fx-num", &k), n.as_f64().unwrap_or(0.0), "", 3, 140.0) {
// A resolution (Object › Rasterize's `ppi`) shows its unit in the UI language.
let suffix = if k == "ppi" { crate::i18n::fill_once(tl!("{n} ppi"), &[("n", "")]) } else { String::new() };
if let Some(x) = crate::widgets::plain_field(ui, ("fx-num", &k), n.as_f64().unwrap_or(0.0), &suffix, 3, 140.0) {
d.fields.insert(k.clone(), typed_number(x));
changed = true;
}
@@ -778,6 +788,12 @@ pub(crate) fn unit_suffix(unit: &str) -> String {
if unit.is_empty() || unit.starts_with(['°', '%', '′', '″']) { unit.to_string() } else { format!(" {unit}") }
}
/// What a resolution field shows after its value in the interface language: the `{n} ppi` row
/// without its number (" ppi", French " ppp").
pub(crate) fn ppi_suffix() -> String {
crate::i18n::fill_once(tl!("{n} ppi"), &[("n", "")])
}
/// A number of a list as [`value_field`] shows it: at most 4 decimals, without trailing zeros.
fn number_text(x: f64) -> String {
let s = format!("{x:.4}");
@@ -798,6 +814,7 @@ pub(crate) fn humanize(k: &str) -> String {
}
}
match s.as_str() {
"Ppi" => "Resolution:".into(),
"Dx" => "Horizontal".into(),
"Dy" => "Vertical".into(),
"Sx" => "Horizontal %".into(),
@@ -828,15 +845,23 @@ pub(crate) fn humanize(k: &str) -> String {
"Create" => "Create New Fields by:".into(),
"Height Width" => "Height/Width:".into(),
"Traps With Process Color" => "Traps with Process Color:".into(),
"Cols" => "Columns:".into(),
"Flip Cols" => "Flip Columns:".into(),
_ => format!("{s}:"),
}
}
/// [`humanize`] translated where it is painted: the ":" stays outside the translated text.
/// A style attribute as the style dialogs list it: the [`humanized`] key, then its value.
pub(super) fn attribute_line(key: &str, value: &Value) -> String {
format!("{} {value}", humanized(key))
}
/// [`humanize`] translated where it is painted: the ":" stays outside the translated text and is
/// written as the UI language writes a label's colon ([`crate::i18n::colon`]).
pub(super) fn humanized(k: &str) -> String {
let h = humanize(k);
match h.strip_suffix(':') {
Some(base) => format!("{}:", tl!(base)),
Some(base) => crate::i18n::colon(tl!(base)),
None => tl!(&h).to_string(),
}
}
@@ -1040,7 +1065,12 @@ fn preview_or_rollback(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: &
pub(super) fn preview_now(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: &str, cmd: &str, params: Value) -> Option<Value> {
let mut result = None;
if d.fields.get(PREVIEWED) != Some(&params) || !app.session.in_interaction() {
let _ = app.session.begin_interaction(label);
// A failure to begin (typing that can't be kept) shows, and nothing previews on the
// interaction still in progress.
if let Err(e) = app.begin_interaction(label) {
app.status(e);
return None;
}
match app.session.preview(cmd, &params) {
Ok(r) => {
d.fields.remove(REFUSED);
@@ -1154,6 +1184,27 @@ mod plugin_field_tests {
assert_eq!([shown("mm"), shown("°"), shown("%"), shown("1/min"), shown("µm")], ["5 mm", "5°", "5%", "5 1/min", "5 µm"]);
}
/// A resolution field's unit is the `{n} ppi` row without its number.
#[test]
fn the_ppi_unit_is_translated() {
assert_eq!(ppi_suffix(), " ppi");
crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap());
let fr = ppi_suffix();
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(fr, " ppp");
}
/// [`ppi_suffix`] drops the number from the `{n} ppi` row, so every catalog writes the number
/// first and then a space before the unit.
#[test]
fn every_catalog_writes_the_ppi_unit_after_the_number() {
for lang in crate::i18n::Lang::all() {
let row = crate::i18n::tr(lang, "{n} ppi");
let unit = row.strip_prefix("{n}").unwrap_or_default();
assert!(unit.starts_with(char::is_whitespace) && !unit.trim().is_empty(), "{}: {row:?}", lang.code());
}
}
#[test]
fn number_lists_read_as_typed_within_their_limits() {
let spec = ParamSpec::NumberList { min: 0.0, max: 360.0, default: vec![45.0], min_items: 1, max_items: 3 };
@@ -1167,6 +1218,98 @@ mod plugin_field_tests {
}
}
#[cfg(test)]
mod settled_typing_tests {
use super::*;
use vectorcraft_engine::{Session, ViewInfo};
use vectorcraft_tools::{PointerEvent, PointerKind};
/// An app with Real-time Drawing off and " world" typed after "Hello", not yet applied → the
/// type's id.
fn typing(app: &mut crate::VectorcraftApp) -> u64 {
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap();
let id = app.run("text.create", json!({"x": 100, "y": 100, "text": "Hello", "size": 20})).unwrap()["id"].as_u64().unwrap();
let v = ViewInfo::default();
app.session.select_tool("type", v).unwrap();
let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap();
}
app.session.tool_text(" world", v).unwrap();
id
}
fn plain(app: &crate::VectorcraftApp, id: u64) -> String {
match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind {
vectorcraft_doc::NodeKind::Text(t) => t.plain_text(),
_ => panic!("not text"),
}
}
/// A dialog's preview while typing is in progress keeps the typing as its own step and starts
/// from it; the status bar shows the warning of the typing's preview that keeping it applied.
#[test]
fn a_dialog_preview_keeps_the_typing_and_shows_its_warning() {
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
let id = typing(&mut app);
assert_eq!(plain(&app, id), "Hello", "the typing waits");
let steps = app.session.active().unwrap().history.undo.len();
let mut d = Dialog::new("test", json!({}));
assert!(preview_now(&mut app, &mut d, "Fill Color", "paint.setFill", json!({"color": "#00a000"})).is_some());
assert_eq!(plain(&app, id), "Hello world");
let st = app.session.active().unwrap();
assert_eq!(st.history.undo.len(), steps + 1, "the typing is a step of its own");
assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Fill Color"));
// The typing's deferred preview warns that type is skipped (as Bloat does with type selected).
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let rect = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap();
let text = app.run("text.create", json!({"x": 300, "y": 200, "text": "Hi"})).unwrap();
app.run("select.set", json!({"ids": [rect["id"], text["id"]]})).unwrap();
app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap();
app.session.begin_interaction("Typing").unwrap();
let p = json!({"tool": "bloat", "points": [[290.0, 200.0]], "width": 200.0, "height": 200.0});
app.session.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("object.liquify".into(), p));
app.ui.status.clear();
let mut d = Dialog::new("test", json!({}));
assert!(preview_now(&mut app, &mut d, "Fill Color", "paint.setFill", json!({"color": "#00a000"})).is_some());
assert!(app.ui.status.contains("type"), "{:?}", app.ui.status);
}
/// The font menus end the typing session before their preview: the typing Real-time Drawing
/// off left unapplied is kept as a step of its own.
#[test]
fn ending_typing_for_the_font_menus_keeps_the_typing() {
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
let id = typing(&mut app);
let steps = app.session.active().unwrap().history.undo.len();
crate::panels::character::end_typing(&mut app);
assert_eq!(plain(&app, id), "Hello world");
let st = app.session.active().unwrap();
assert_eq!(st.history.undo.len(), steps + 1);
assert!(st.interaction.is_none());
assert_ne!(app.session.tool_options().get("typing").and_then(Value::as_bool), Some(true), "the typing session is over");
}
/// A Character panel change keeps the typing first and acts on the characters the Type tool
/// selected in the typed text, not on a selection cut short to the text before the typing.
#[test]
fn a_character_change_acts_on_characters_selected_in_the_typing() {
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
let id = typing(&mut app);
app.session.set_tool_option("select", &json!({"start": 6, "end": 11}));
crate::panels::character::range_style(&mut app, json!({"underline": true}));
assert_eq!(plain(&app, id), "Hello world");
let vectorcraft_doc::NodeKind::Text(t) = &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else {
panic!("not text")
};
let underlined: String = t.runs.iter().filter(|r| r.style.underline).map(|r| r.text.as_str()).collect();
assert_eq!(underlined, "world");
}
}
#[cfg(test)]
mod typed_number_tests {
use super::*;
+94 -16
View File
@@ -21,7 +21,7 @@ use serde_json::{Map, Value, json};
use vectorcraft_brush::Variation;
use super::document_setup::check;
use super::{DialogSpec, form, run_and_close};
use super::{DialogSpec, form, set_tool_options_and_close};
use crate::state::Dialog;
use crate::theme::Tokens;
use crate::{VectorcraftApp, widgets};
@@ -334,22 +334,65 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
/// Side of the Blob Brush tip preview's square, in points.
const TIP_PREVIEW: f32 = 64.0;
/// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness and a line along
/// its long axis, and beside it three dabs of the tip, the middle one darker. A click or a drag in
/// the square points the Angle at the pointer and gives the square the keyboard focus; screen
/// readers get it as the Angle slider, and its keys step the Angle as a dialog slider's do
/// ([`widgets::stepped_area`]) within -180° to 180°.
/// Half the length of the Blob Brush tip in its preview, in points.
const TIP_LONG: f32 = 18.0;
/// How far from a Roundness dot of the tip preview a press still takes the dot, in points.
const TIP_DOT_REACH: f32 = 8.0;
/// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness, a line with an
/// arrowhead along its long axis and a black dot at each end of its short axis, and beside it three
/// dabs of the tip, the middle one darker. A click or a drag that starts on a dot sets the
/// Roundness from the pointer's distance from the center along the short axis
/// ([`blob_tip_roundness_at`]) until the release, inside the square or out of it, and gives the
/// Roundness slider the keyboard focus. A click or a drag that starts anywhere else in the square
/// points the Angle at the pointer and gives the Angle slider the focus. Screen readers get the
/// square as the Angle slider and then the Roundness slider, and their keys step the Angle within
/// -180° to 180° and the Roundness within 0% to 100% as a dialog slider's do
/// ([`widgets::stepped_area`]).
fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) {
let t = Tokens::get(ui.ctx());
let (rect, _) = ui.allocate_exact_size(egui::vec2(CONTENT_W, TIP_PREVIEW), egui::Sense::hover());
let square = egui::Rect::from_min_size(rect.min, egui::vec2(TIP_PREVIEW, TIP_PREVIEW));
let center = square.center();
let response = ui.interact(square, ui.scope_id().with("freehand-tip-angle"), egui::Sense::click_and_drag());
// Whether the press that started this click or drag was on a dot: it is kept until the release.
let on_dot = response.id.with("on-dot");
let near_dot = |p: egui::Pos2, d: &Dialog| {
blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)).iter().any(|dot| dot.distance(p) <= TIP_DOT_REACH)
};
let mut started = ui.data(|m| m.get_temp::<bool>(on_dot));
if started.is_none() && response.is_pointer_button_down_on() {
let pressed = ui.input(|i| i.pointer.press_origin()).is_some_and(|p| near_dot(p, d));
ui.data_mut(|m| m.insert_temp(on_dot, pressed));
started = Some(pressed);
}
// A click whose press and release came in the same frame: its press is among this frame's events.
let dot_drag = started.unwrap_or_else(|| {
let press = ui.input(|i| {
i.events.iter().rev().find_map(|e| match e {
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos),
_ => None,
})
});
response.clicked() && press.is_some_and(|p| near_dot(p, d))
});
if !response.is_pointer_button_down_on() {
ui.data_mut(|m| m.remove_temp::<bool>(on_dot));
}
if let Some((p, _)) = widgets::pointer_phase(&response) {
let delta = p - square.center();
if delta.length_sq() > 1.0 {
let delta = p - center;
if dot_drag {
d.fields.insert("roundness".into(), json!(blob_tip_roundness_at(delta, d.f64("angle", 0.0))));
} else if delta.length_sq() > 1.0 {
d.fields.insert("angle".into(), json!(f64::from((-delta.y).atan2(delta.x)).to_degrees().round()));
}
}
if dot_drag && response.is_pointer_button_down_on() {
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
} else if response.hover_pos().is_some_and(|p| near_dot(p, d)) && !response.is_pointer_button_down_on() {
ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
}
let painter = ui.painter_at(rect);
painter.rect_filled(square, 2.0, t.input);
painter.rect_stroke(square, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside);
@@ -358,11 +401,17 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) {
if let Some(a) = widgets::stepped_area(ui, &response, tl!("Angle"), Some(shown)) {
d.fields.insert("angle".into(), json!(a));
}
let a = d.f64("angle", 0.0).clamp(-180.0, 180.0).to_radians();
// The long axis on screen (y down: a positive angle tilts it up to the right) and the short one.
let u = egui::vec2(a.cos() as f32, -a.sin() as f32);
let v = egui::vec2(-u.y, u.x);
let long = 18.0;
// The Roundness slider takes the focus and the keys only: the square's response reads the pointer.
let roundness = ui.interact(square, ui.scope_id().with("freehand-tip-roundness"), egui::Sense::focusable_noninteractive());
if dot_drag && (response.drag_started() || response.clicked()) {
widgets::focus_by_pointer(ui, roundness.id);
}
let shown = widgets::SliderValue::field(d.f64("roundness", 100.0), 0.0..=100.0, "%", 0);
if let Some(r) = widgets::stepped_area(ui, &roundness, tl!("Roundness"), Some(shown)) {
d.fields.insert("roundness".into(), json!(r));
}
let (u, v) = blob_tip_axes(d.f64("angle", 0.0));
let long = TIP_LONG;
let short = long * blob_tip_short_ratio(d.f64("roundness", 100.0));
let dab = |center: egui::Pos2, color: egui::Color32| {
let points = (0..32)
@@ -373,15 +422,44 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) {
.collect();
painter.add(egui::Shape::convex_polygon(points, color, egui::Stroke::NONE));
};
let center = square.center();
dab(center, t.text);
painter.line_segment([center, center + u * 25.0], egui::Stroke::new(1.0, t.accent));
painter.line_segment([center, center + u * 22.0], egui::Stroke::new(1.0, t.accent));
let arrowhead = vec![center + u * 28.0, center + u * 22.0 + v * 3.0, center + u * 22.0 - v * 3.0];
painter.add(egui::Shape::convex_polygon(arrowhead, t.accent, egui::Stroke::NONE));
// Black with a white rim, so a dot shows on the tip and on the square in either theme.
for dot in blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)) {
painter.circle(dot, 3.0, egui::Color32::BLACK, egui::Stroke::new(1.0, egui::Color32::WHITE));
}
let strip = square.right() + 2.5 * long;
for (i, color) in [t.text_dim, t.text, t.text_dim].into_iter().enumerate() {
dab(egui::pos2(strip + i as f32 * 1.5 * long, center.y), color);
}
}
/// The tip preview's long axis on screen at Angle `angle` (degrees, y down: a positive angle tilts
/// it up to the right), and its short axis.
fn blob_tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) {
let a = angle.clamp(-180.0, 180.0).to_radians();
let u = egui::vec2(a.cos() as f32, -a.sin() as f32);
(u, egui::vec2(-u.y, u.x))
}
/// The two Roundness dots of the tip preview centered on `center`: the ends of the tip's short
/// axis at Angle `angle` and Roundness `roundness`.
fn blob_tip_dots(center: egui::Pos2, angle: f64, roundness: f64) -> [egui::Pos2; 2] {
let (_, v) = blob_tip_axes(angle);
let short = v * (TIP_LONG * blob_tip_short_ratio(roundness));
[center + short, center - short]
}
/// The Roundness, in whole percent from 0 to 100, that a dot of the tip preview dragged to `offset`
/// from the preview's center gives at Angle `angle`: the distance along the tip's short axis, on
/// either side of the center, as a percentage of half the tip's length.
fn blob_tip_roundness_at(offset: egui::Vec2, angle: f64) -> f64 {
let (_, v) = blob_tip_axes(angle);
(f64::from(offset.dot(v).abs() / TIP_LONG) * 100.0).round().clamp(0.0, 100.0)
}
/// The preview tip's short axis as a fraction of its long axis: Roundness in percent, with 0
/// percent drawn as 0.1 percent, the minimum the brush draws with.
fn blob_tip_short_ratio(roundness: f64) -> f32 {
@@ -391,7 +469,7 @@ fn blob_tip_short_ratio(roundness: f64) -> f32 {
/// OK: set the tool's options.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let values: Map<String, Value> = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect();
run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values }))
set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values }))
}
#[cfg(test)]
@@ -28,6 +28,24 @@ fn blob_tip_fields_confirm_and_cancel() {
assert_eq!(app.session.tool_options_of("blobBrush")["roundness"], json!(0.0));
}
/// OK with a Fidelity the Smooth tool refuses shows the error and keeps the dialog open, with
/// nothing set; a Fidelity it takes then closes it.
#[test]
fn a_refused_fidelity_keeps_the_dialog_open() {
let mut app = app();
app.run("tool.options", json!({"tool": "smooth"})).unwrap();
let before = app.session.tool_options_of("smooth");
app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(0.01));
let e = super::super::confirm(&mut app).unwrap_err();
assert_eq!(e, "tool `smooth`: `fidelity` must be a number from 0.05 to 100");
assert!(app.ui.dialog.is_some(), "the dialog stays open");
assert_eq!(app.session.tool_options_of("smooth"), before);
app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(5));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(app.session.tool_options_of("smooth")["fidelity"], json!(5.0));
}
#[test]
fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() {
for roundness in [-5.0, 0.0, 0.05, 0.1, 1.0, 50.0, 100.0, 120.0] {
@@ -36,6 +54,30 @@ fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() {
}
}
/// A Roundness dot of the tip preview gives its distance from the center along the tip's short
/// axis as a percentage of half the tip's length, on either side and at any Angle: 0% at the
/// center, 100% at half the length and past it. A move along the long axis leaves it as it is, and
/// the dots drawn for a Roundness give that Roundness back.
#[test]
fn a_roundness_dot_sets_its_distance_along_the_short_axis() {
for angle in [0.0, 30.0, 90.0, -135.0, 180.0] {
let (u, v) = blob_tip_axes(angle);
for (along, want) in [(0.0, 0.0), (4.5, 25.0), (-9.0, 50.0), (18.0, 100.0), (-18.0, 100.0), (40.0, 100.0), (-400.0, 100.0)] {
for sideways in [0.0, 7.0, -30.0] {
assert_eq!(blob_tip_roundness_at(v * along + u * sideways, angle), want, "angle {angle}, {along} along, {sideways} sideways");
}
}
let center = egui::pos2(32.0, 32.0);
for roundness in [0.0, 1.0, 37.0, 50.0, 99.0, 100.0] {
let [a, b] = blob_tip_dots(center, angle, roundness);
assert!(((a - center) + (b - center)).length() < 1e-4, "the dots face each other across the center");
for dot in [a, b] {
assert_eq!(blob_tip_roundness_at(dot - center, angle), roundness, "angle {angle}");
}
}
}
}
/// The labels the open dialog paints.
fn painted(app: &mut VectorcraftApp) -> String {
crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()))
+11 -62
View File
@@ -28,14 +28,13 @@ use crate::{VectorcraftApp, widgets};
pub const KIND: &str = "graphData";
/// The sheet's size: a row of labels over a graph's categories, a column of labels before its
/// series; the least it shows; a cell's longest text.
/// series; the least it shows.
const MAX_ROWS: usize = MAX_GRAPH_CATEGORIES + 1;
const MAX_COLS: usize = MAX_GRAPH_SERIES + 1;
const MIN_ROWS: usize = 8;
const MIN_COLS: usize = 6;
const MAX_CELL: usize = 256;
/// The largest file Import Data reads, 1 MB (1,048,576 bytes), the same as Import Data Sets'.
const MAX_IMPORT_BYTES: usize = 1 << 20;
const MAX_IMPORT_BYTES: usize = vectorcraft_engine::cmd::MAX_GRAPH_DATA_FILE;
/// The Cell Style limits (Adjust column width and decimal digits).
const MAX_DECIMALS: u64 = 10;
const MAX_WIDTH: u64 = 20;
@@ -105,75 +104,25 @@ pub(crate) fn grid_from_data(v: &Value) -> Grid {
grid
}
/// The sheet as `graph.setData` takes it: series labels, category labels (none when all are blank)
/// and the values (a blank cell, or text that isn't a number, has none), without the empty rows and
/// columns past the data.
/// The sheet as `graph.setData` takes it ([`vectorcraft_engine::cmd::graph_data_from_grid`]),
/// which Import Data Sets' `%` columns also use.
pub(crate) fn data_from_grid(grid: &Grid) -> Value {
let filled = |s: &String| !s.trim().is_empty();
// At most a graph's rows and columns, as a file gives (`grid_from_text`): a grid sent by
// automation is any size, and the values are their product.
let grid = &grid[..grid.len().min(MAX_ROWS)];
let rows = grid.iter().rposition(|r| r.iter().take(MAX_COLS).any(filled)).map_or(1, |i| i + 1).max(1);
let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(MAX_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1);
let label = |s: &str| {
let s = s.trim();
// A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside.
s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string()
};
// Series labels up to the last one given (none when all are blank).
let mut series: Vec<String> = (1..cols).map(|c| label(&cell(grid, 0, c))).collect();
while series.last().is_some_and(String::is_empty) {
series.pop();
}
let mut categories: Vec<String> = (1..rows).map(|r| label(&cell(grid, r, 0))).collect();
if categories.iter().all(String::is_empty) {
categories.clear();
}
let values: Vec<Vec<Value>> = (1..rows)
.map(|r| {
(1..cols)
.map(|c| {
let t = cell(grid, r, c);
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v))
})
.collect()
})
.collect();
json!({ "series": series, "categories": categories, "rows": values })
vectorcraft_engine::cmd::graph_data_from_grid(grid)
}
/// Text from a file or the clipboard as cells: tab-separated when any line holds a tab, else
/// comma-separated (decided once, so a label with a comma in a tab-separated file stays whole), at
/// most a graph's rows and columns.
/// Text from a file or the clipboard as cells ([`vectorcraft_engine::cmd::graph_grid_from_text`]).
pub(crate) fn grid_from_text(text: &str) -> Grid {
let sep = if text.contains('\t') { '\t' } else { ',' };
text.lines().take(MAX_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(MAX_COLS).map(|c| clean(c.trim())).collect()).collect()
vectorcraft_engine::cmd::graph_grid_from_text(text)
}
/// A text file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode Text"),
/// else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives them a
/// byte order ([`vectorcraft_engine::cmd::utf16_order_without_mark`]), else UTF-8 with or without
/// one. UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an
/// unpaired surrogate reads as U+FFFD.
/// A text file's bytes as text ([`vectorcraft_engine::cmd::graph_data_text`]).
pub(crate) fn decode(bytes: &[u8]) -> String {
let utf16 = |rest: &[u8], le: bool| {
let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect();
String::from_utf16_lossy(&units)
};
match bytes {
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
_ => match bytes.contains(&0).then(|| vectorcraft_engine::cmd::utf16_order_without_mark(bytes)).flatten() {
Some(le) => utf16(bytes, le),
None => String::from_utf8_lossy(bytes).into_owned(),
},
}
vectorcraft_engine::cmd::graph_data_text(bytes)
}
/// A cell's text: one line (tabs and line breaks become spaces), at most MAX_CELL characters.
/// A cell's text ([`vectorcraft_engine::cmd::graph_cell_text`]).
fn clean(s: &str) -> String {
s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(MAX_CELL).collect()
vectorcraft_engine::cmd::graph_cell_text(s)
}
fn cell(grid: &[Vec<String>], r: usize, c: usize) -> String {
+18 -2
View File
@@ -577,9 +577,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
false
}
/// `text` with the colon of a field label.
/// `text` with the colon of a field label, as the UI language writes it.
fn colon(text: &str) -> String {
format!("{text}:")
crate::i18n::colon(text)
}
/// A checkbox bound to `d.fields[key]`, dimmed while the type picked has no use for it.
@@ -977,6 +977,22 @@ mod tests {
assert!(app.ui.dialog.is_none());
}
/// Field labels end in the UI language's colon: in French a no-break space and a colon (#7991).
#[test]
fn field_labels_use_the_language_colon() {
let mut app = app_with_graph("column");
crate::menus::invoke(&mut app, COMMAND, json!({}));
set(&mut app, PAGE, json!("valueAxis"));
let fr = crate::i18n::Lang::from_code("fr").unwrap();
crate::i18n::set_current(fr);
let mut h = harness(app);
h.run_steps(3);
let want = format!("{}\u{a0}:", crate::i18n::tr(fr, "Suffix"));
let found = h.query_by_role_and_label(Role::TextInput, &want).is_some();
crate::i18n::set_current(crate::i18n::Lang::EN);
assert!(found, "a text field named {want:?}");
}
/// A Type button changes the graph's type and keeps its data.
#[test]
fn a_type_button_changes_the_graph_type_and_keeps_its_data() {
+40 -10
View File
@@ -3,7 +3,10 @@
//!
//! Fields: `mode` (`open` | `place`), `name`, `path?`, `pageCount`, `page` (the page shown, and the
//! one placed; 1-based), `allPages`, `range` and `linkPages` (open: Import PDF Pages as Links, for
//! a file read from a path and opened without a password), `cropTo` and `password`. `__locked` is set
//! a file read from a path and opened without a password; `null` until it is checked or cleared,
//! when it follows the pages picked: on for All, off for a range; picking the other of All and
//! Range sets it back to `null`; `__linkable` is false for a file `linkPages` does not take, such as
//! one over its size limit), `cropTo` and `password`. `__locked` is set
//! until the password is accepted: OK then unlocks the file, and with `__passwordOnly` (Place with
//! Show Import Options off) places its first page at once. `__place` keeps the other `file.place`
//! params (Link, Template, `at`…). The file's bytes stay out of the fields, in
@@ -144,10 +147,11 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St
"page": 1,
"allPages": true,
"range": "",
"linkPages": false,
"linkPages": null,
"cropTo": CropTo::default().id(),
"password": "",
"__locked": locked,
"__linkable": fileio::pages_can_link(name, bytes),
});
if let Some(p) = path {
fields["path"] = json!(p);
@@ -214,14 +218,40 @@ fn password(d: &Dialog) -> Option<String> {
}
/// Can the pages open linked: the file was read from a path (a linked page is read from its
/// file again) and opens without a password (`document.open`'s `linkPages` refuses one).
/// file again), `document.open`'s `linkPages` takes its size, and it opens without a password
/// (`linkPages` refuses one).
fn can_link(d: &Dialog) -> bool {
d.fields.get("path").and_then(Value::as_str).is_some() && password(d).is_none()
d.fields.get("path").and_then(Value::as_str).is_some() && d.bool("__linkable") && password(d).is_none()
}
/// Import PDF Pages as Links as checked or cleared, or, when it is `null`, as the pages picked
/// default it: on for All, off for a range.
fn link_pages(d: &Dialog) -> bool {
d.fields.get("linkPages").and_then(Value::as_bool).unwrap_or_else(|| d.bool("allPages"))
}
/// Import PDF Pages as Links is checked, and can be.
fn links_on(d: &Dialog) -> bool {
d.bool("linkPages") && can_link(d)
pub(super) fn links_on(d: &Dialog) -> bool {
link_pages(d) && can_link(d)
}
/// Picks All (true) or Range. A change of pick sets Import PDF Pages as Links back to that pick's
/// default; picking the one already picked keeps the box as it is.
fn pick_all_pages(d: &mut Dialog, all: bool) {
if d.bool("allPages") != all {
d.fields.insert("allPages".into(), json!(all));
d.fields.insert("linkPages".into(), Value::Null);
}
}
/// Records that `ui.dialog.set` sets `field` to `value`: a change of `allPages` sets Import PDF
/// Pages as Links back to its default, as a click on All or Range does.
pub(super) fn note_set(d: &mut Dialog, field: &str, value: &Value) {
if field == "allPages"
&& let Some(all) = value.as_bool()
{
pick_all_pages(d, all);
}
}
/// OK: unlock the file with the password, else open the pages or place the page.
@@ -330,20 +360,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
ui.label(egui::RichText::new(tl!("Pages")).color(t.text));
let all = d.bool("allPages");
if widgets::radio(ui, tl!("All"), all, true) {
d.fields.insert("allPages".into(), json!(true));
pick_all_pages(d, true);
}
ui.horizontal(|ui| {
if widgets::radio(ui, tl!("Range:"), !all, true) {
d.fields.insert("allPages".into(), json!(false));
pick_all_pages(d, false);
}
if super::form::text_edit_named(ui, d, "range", tl!("Range:"), 90.0).gained_focus() {
d.fields.insert("allPages".into(), json!(false));
pick_all_pages(d, false);
}
});
widgets::dim_label(ui, tl!("e.g. 1-3, 5"));
ui.add_space(10.0);
if widgets::check(ui, tl!("Import PDF pages as links"), links_on(d), can_link(d)) {
d.fields.insert("linkPages".into(), json!(!d.bool("linkPages")));
d.fields.insert("linkPages".into(), json!(!link_pages(d)));
}
}
});
+1 -2
View File
@@ -92,8 +92,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
// While typing, the dialog acts on the paragraphs of the text being edited.
let mut targets = json!({});
let mut story = None;
if let Some((id, a, b)) = crate::panels::character::text_editing(app) {
crate::panels::character::end_typing(app);
if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? {
targets = json!({"ids": [id.0], "start": a, "end": b});
// After Select All in threaded text: every paragraph of every frame ([`params`]).
story = crate::panels::character::text_story(app).map(|_| id.0);
+2 -2
View File
@@ -12,7 +12,7 @@ use serde_json::{Map, Value, json};
use vectorcraft_tools::distort::liquify::LiquifyKind;
use super::document_setup::check;
use super::{DialogSpec, form, run_and_close};
use super::{DialogSpec, form, set_tool_options_and_close};
use crate::state::Dialog;
use crate::theme::Tokens;
use crate::{VectorcraftApp, widgets};
@@ -145,7 +145,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
values.insert(key.into(), json!(d.f64(key, 0.0) / 100.0));
}
}
run_and_close(app, "tool.setOption", json!({ "tool": kind(d).id(), "values": values }))
set_tool_options_and_close(app, json!({ "tool": kind(d).id(), "values": values }))
}
#[cfg(test)]
@@ -15,7 +15,7 @@ use vectorcraft_doc::LAYER_COLORS;
use vectorcraft_tools::builder::LP_BUCKET_WIDTH_RANGE;
use super::tile_edge_color::{checked, resolve};
use super::{DialogSpec, form, run_and_close};
use super::{DialogSpec, form, set_tool_options_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
@@ -86,7 +86,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
checked(&d.str("color"))?;
}
let values: Map<String, Value> = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect();
run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values }))
set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values }))
}
#[cfg(test)]
@@ -13,7 +13,7 @@ use vectorcraft_doc::LAYER_COLORS;
use vectorcraft_tools::builder::LP_SELECT_WIDTH_RANGE;
use super::tile_edge_color::{checked, resolve};
use super::{DialogSpec, form, run_and_close};
use super::{DialogSpec, form, set_tool_options_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
@@ -80,7 +80,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
checked(&d.str("color"))?;
}
let values: Map<String, Value> = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect();
run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values }))
set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values }))
}
#[cfg(test)]
+401 -22
View File
@@ -2,8 +2,9 @@
//! window with no title bar that opens centred and moves by dragging its heading (the band from its
//! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where
//! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows
//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons
//! stay in view.
//! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its
//! heading and buttons stay in view. A window without such rows that is still too tall or too wide
//! for the screen scrolls as a whole on that axis.
use egui::{Id, Rect, Vec2};
@@ -25,6 +26,8 @@ pub(crate) fn show_at<R>(ctx: &egui::Context, title: &str, id: Id, initial: Vec2
// Not focusable (`Sense::click()` is): Tab goes through the dialog's controls, not the backdrop.
ui.allocate_rect(ctx.content_rect(), egui::Sense::CLICK);
});
let pass = ctx.cumulative_pass_nr();
ctx.data_mut(|d| d.insert_temp(drawn_pass_id(), pass));
let shown = egui::Window::new(title)
.id(id)
.order(egui::Order::Foreground)
@@ -33,17 +36,114 @@ pub(crate) fn show_at<R>(ctx: &egui::Context, title: &str, id: Id, initial: Vec2
.title_bar(false)
.anchor(egui::Align2::CENTER_CENTER, offset(ctx, id, initial))
.frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(margin)))
.show(ctx, add)?;
keep_rest(ctx, id, shown.response.rect.height());
.show(ctx, |ui| {
// Just opened: what scrolls in the window starts at its top, wherever it was left when
// the window last closed.
if opened(ctx, id) {
ctx.data_mut(|m| {
m.insert_temp(id.with(TOP_ROWS_KEY), true);
m.insert_temp(id.with(TOP_WHOLE_KEY), true);
});
}
// A window whose contents are wider than the screen has room for, or taller without
// rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis,
// so none of it is out of reach. The contents keep their ids whether the window scrolls
// or not, so a field being edited keeps its text when that changes.
let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default();
let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents"));
let (r, contents) = if wide || tall {
let room = whole_room(ctx, margin);
let mut area = egui::ScrollArea::new([wide, tall]);
if ctx.data_mut(|m| m.remove_temp::<bool>(id.with(TOP_WHOLE_KEY))).is_some() {
area = area.scroll_offset(Vec2::ZERO);
}
let out = area
.id_salt("modal-whole")
.max_width(room.x)
.max_height(room.y)
.min_scrolled_width(room.x)
.min_scrolled_height(room.y)
.show(ui, |ui| ui.scope_builder(scope, add).inner);
(out.inner, out.content_size)
} else {
let r = ui.scope_builder(scope, add).inner;
(r, ui.min_rect().size())
};
ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents));
r
})?;
keep_rest(ctx, id, shown.response.rect.height(), margin);
shown.inner
}
/// Mark the modal window drawn next in this pass as opened over the one drawn in the pass before,
/// which it hides until it closes and shows that one again (Import Shortcut Set over Keyboard
/// Shortcuts). The window under it keeps where it was scrolled to.
pub(crate) fn over_parent(ctx: &egui::Context) {
let pass = ctx.cumulative_pass_nr();
ctx.data_mut(|m| m.insert_temp(Id::unique(OVER_KEY), pass));
}
/// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before,
/// and none of the windows drawn in the pass before was one opened over it ([`over_parent`]).
fn opened(ctx: &egui::Context, id: Id) -> bool {
let pass = ctx.cumulative_pass_nr();
ctx.data_mut(|m| {
// The windows drawn in this pass so far and in the pass before.
let (at, now, prev) = m.get_temp::<(u64, Vec<Id>, Vec<Id>)>(Id::unique(LAST_KEY)).unwrap_or_default();
let (mut now, prev) = if at == pass {
(now, prev)
} else if at.saturating_add(1) == pass {
(vec![], now)
} else {
(vec![], vec![])
};
let before: Vec<Id> = prev.iter().copied().filter(|&other| other != id).collect();
now.push(id);
m.insert_temp(Id::unique(LAST_KEY), (pass, now, prev));
let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass);
if last != u64::MAX && last.saturating_add(1) >= pass {
return false;
}
// Shown again as the window opened over it closed.
if before.iter().any(|over| m.get_temp::<Id>(over.with(HOLDS_KEY)) == Some(id)) {
return false;
}
// Opened over the window drawn last in the pass before, it holds that one; otherwise none.
match before.last().copied().filter(|_| m.get_temp::<u64>(Id::unique(OVER_KEY)) == Some(pass)) {
Some(under) => {
m.insert_temp(id.with(HOLDS_KEY), under);
}
None => {
m.remove::<Id>(id.with(HOLDS_KEY));
}
}
true
})
}
/// The room for the contents of a modal window with `margin` inside its frame.
fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 {
(ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO)
}
/// The layer of the backdrop behind a modal dialog window, which takes the clicks the rest of
/// the app would get.
pub(crate) fn backdrop() -> egui::LayerId {
egui::LayerId::new(egui::Order::Middle, Id::unique("modal-dim"))
}
/// The key of the pass in which [`show_at`] last drew a modal window.
fn drawn_pass_id() -> Id {
Id::unique("modal-drawn-pass")
}
/// Whether [`show_at`] drew a modal window in this pass. Unlike the backdrop's visibility, which
/// also counts the last pass, it is false in the pass after the window closes.
pub(crate) fn drawn_this_pass(ctx: &egui::Context) -> bool {
ctx.data(|d| d.get_temp::<u64>(drawn_pass_id())) == Some(ctx.cumulative_pass_nr())
}
/// The dialog's heading, which also moves the window ([`drag_band`]).
pub(crate) fn heading(ui: &mut egui::Ui, text: &str) {
let t = Tokens::get(ui.ctx());
@@ -73,34 +173,158 @@ pub(super) fn handle(id: Id) -> Id {
id.with("modal-drag")
}
/// Under a modal window's id: how tall its [`scrolled_rows`] were drawn this frame, and how tall
/// the rest of it was when last drawn.
/// Under a modal window's id: how tall its [`scrolled_rows`] (or [`body_rows`]) were drawn this
/// frame, and how tall the rest of it was when last drawn.
const ROWS_KEY: &str = "modal-rows";
const REST_KEY: &str = "modal-rest";
/// Under a modal window's id: its contents drew [`scrolled_rows`] of their own or fit themselves to
/// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`).
const OWN_ROWS_KEY: &str = "modal-own-rows";
const OWN_BEFORE_KEY: &str = "modal-own-before";
/// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame.
const BODY_KEY: &str = "modal-body";
/// Under a modal window's id: how large its contents would be without scrolling as a whole, this
/// frame.
const CONTENTS_KEY: &str = "modal-contents";
/// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on
/// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`).
const TALL_KEY: &str = "modal-tall";
const WHOLE_KEY: &str = "modal-whole";
/// Under a modal window's id: the pass it was last drawn in (`SHOWN_KEY`), and, since it opened,
/// its rows (`TOP_ROWS_KEY`) or the window as a whole (`TOP_WHOLE_KEY`) have not scrolled yet, so
/// they start at the top when they first do.
const SHOWN_KEY: &str = "modal-shown";
const TOP_ROWS_KEY: &str = "modal-top-rows";
const TOP_WHOLE_KEY: &str = "modal-top-whole";
/// For all modal windows: the pass the last one was drawn in, the ids of those drawn in that pass
/// and of those drawn in the pass before it (`LAST_KEY`), and the pass
/// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`).
/// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`).
const LAST_KEY: &str = "modal-last";
const OVER_KEY: &str = "modal-over";
const HOLDS_KEY: &str = "modal-holds";
/// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window
/// would be taller than the screen. Their height is the screen's less the rest of the window as
/// last drawn (a frame late, as only the drawn window knows its height).
/// Rows that fit are as tall as they are.
pub(crate) fn scrolled_rows<R>(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
let id = ui.layer_id().id;
let rest = ui.ctx().data(|m| m.get_temp::<f32>(id.with(REST_KEY))).unwrap_or(0.0);
let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0);
// As tall as the room at once: by itself a scroll area grows a frame at a time with the window.
let rows = ui.scope(|ui| egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room).show(ui, add).inner);
ui.ctx().data_mut(|m| m.insert_temp(id.with(ROWS_KEY), rows.response.rect.height()));
rows.inner
fits_itself(ui);
let (r, drawn, _) = rows(ui, salt, true, add);
ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn));
r
}
/// After modal window `id` is drawn `height` tall: keep the height of all of it but its
/// [`scrolled_rows`] for the next frame. If the rows were sized by a different one (the window just
/// opened, or what is around them changed), the next frame is drawn at once, for the rows to fit
/// without waiting for input.
fn keep_rest(ctx: &egui::Context, id: Id, height: f32) {
let Some(rows) = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(ROWS_KEY))) else { return };
let rest = (height - rows).max(0.0);
let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest));
if (used - rest).abs() > 0.5 {
/// Mark the contents of the modal window `ui` is in as fitting themselves to the screen (sizing
/// what scrolls in them from the screen's height), so neither [`body_rows`] nor the window
/// scroll them again.
pub(crate) fn fits_itself(ui: &egui::Ui) {
ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true));
}
/// The body of a shared dialog window. While the window would be taller than the screen has room
/// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view;
/// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is.
pub(crate) fn body_rows<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
let id = ui.layer_id().id;
let (r, drawn, body) = rows(ui, "dialog-body", body_scrolls(ui.ctx(), id), add);
if !ui.ctx().data(|m| m.get_temp::<bool>(id.with(OWN_ROWS_KEY))).unwrap_or(false) {
ui.ctx().data_mut(|m| {
m.insert_temp(id.with(ROWS_KEY), drawn);
m.insert_temp(id.with(BODY_KEY), body);
});
}
r
}
/// Whether the [`body_rows`] of modal window `id` scroll in this frame.
fn body_scrolls(ctx: &egui::Context, id: Id) -> bool {
let own = ctx.data(|m| m.get_temp::<bool>(id.with(OWN_BEFORE_KEY))).unwrap_or(false);
!own && ctx.data(|m| m.get_temp::<bool>(id.with(TALL_KEY))).unwrap_or(false)
}
/// While the [`body_rows`] of the modal window `ui` is in scroll: how tall they are drawn.
pub(crate) fn body_view(ui: &egui::Ui) -> Option<f32> {
let id = ui.layer_id().id;
body_scrolls(ui.ctx(), id).then(|| rows_room(ui.ctx(), id))
}
/// How modal window `id` scrolls: while its [`body_rows`] scroll, how tall they are drawn; and on
/// which axes ([wide, tall]) the window scrolls as a whole.
#[cfg(test)]
pub(crate) fn scrolling(ctx: &egui::Context, id: Id) -> (Option<f32>, [bool; 2]) {
let body = body_scrolls(ctx, id).then(|| rows_room(ctx, id));
(body, ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default())
}
/// The height of a list `height` tall at most, with a scroll bar of its own, in the [`body_rows`]
/// of the modal window `ui` is in: while the body scrolls, no taller than the body is drawn, so
/// the list and its bar can be scrolled into view whole.
pub(crate) fn list_height(ui: &egui::Ui, height: f32) -> f32 {
body_view(ui).map_or(height, |view| view.min(height))
}
/// The height rows that scroll in modal window `id` are drawn: the screen's less the rest of the
/// window as last drawn.
fn rows_room(ctx: &egui::Context, id: Id) -> f32 {
let rest = ctx.data(|m| m.get_temp::<f32>(id.with(REST_KEY))).unwrap_or(0.0);
(ctx.content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0)
}
/// [`scrolled_rows`] without marking the window's body as having rows of its own or keeping their
/// height. Also returns how tall the rows were drawn and how tall they would be without scrolling.
/// Rows that do not `scroll` are as tall as they are, with no
/// scroll area (which would take the scroll requests of their fields from the window's). The rows
/// keep their ids either way, so a field being edited keeps its text when they start or stop
/// scrolling.
fn rows<R>(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) {
let id = ui.layer_id().id;
let room = rows_room(ui.ctx(), id);
let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows"));
if !scroll {
let rows = ui.scope_builder(scope, add);
let height = rows.response.rect.height();
return (rows.inner, height, height);
}
// As tall as the room at once: by itself a scroll area grows a frame at a time with the window.
let mut area = egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room);
if ui.ctx().data_mut(|m| m.remove_temp::<bool>(id.with(TOP_ROWS_KEY))).is_some() {
area = area.scroll_offset(Vec2::ZERO);
}
let rows = ui.scope(|ui| area.show(ui, |ui| ui.scope_builder(scope, add).inner));
(rows.inner.inner, rows.response.rect.height(), rows.inner.content_size.y)
}
/// After modal window `id` (with `margin` inside its frame) is drawn `height` tall: keep the height
/// of all of it but its [`scrolled_rows`] for the next frame. If the rows were sized by a different
/// one (the window just opened, or what is around them changed), the next frame is drawn at once,
/// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll
/// while the window would be taller than the screen has room for without them scrolling; a window
/// without rows that scroll scrolls as a whole while its contents would be taller than the room,
/// and any window scrolls sideways while its contents would be wider.
fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) {
let rows = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(ROWS_KEY)));
let body = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(BODY_KEY)));
let contents = ctx.data_mut(|m| m.remove_temp::<Vec2>(id.with(CONTENTS_KEY))).unwrap_or_default();
let own = ctx.data_mut(|m| m.remove_temp::<bool>(id.with(OWN_ROWS_KEY))).unwrap_or(false);
ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own));
let room = whole_room(ctx, margin);
let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP;
let tall = match (rows, body) {
(Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5,
_ => false,
};
// A window that fits itself to the screen's height can still be too wide for it.
let whole = [contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5];
let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall));
let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole));
let mut repaint = tall != was_tall || whole != was_whole;
if let Some(rows) = rows {
let rest = (height - rows).max(0.0);
let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest));
repaint |= (used - rest).abs() > 0.5;
}
if repaint {
ctx.request_repaint();
}
}
@@ -146,4 +370,159 @@ mod tests {
// Larger than the screen: its top left stays in view.
assert_eq!(on_screen(r(-10.0, -10.0, 900.0, 700.0), screen), r(0.0, 0.0, 900.0, 700.0));
}
/// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with the modal
/// windows named in `open` open, in that order: the first a heading and 60 rows, in
/// [`scrolled_rows`] when `in_rows`, and any other a short alert. A window named "over …" is
/// opened over the one before it ([`over_parent`]). Returns whether a first row could be seen in
/// the last frame (inside the screen and its clip).
fn first_row_seen(ctx: &egui::Context, open: &[&str], in_rows: bool, events: Vec<egui::Event>, time: &mut f64, frames: usize) -> bool {
let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0));
let add = |ui: &mut egui::Ui| {
for i in 0..60 {
ui.label(format!("Row {i}"));
}
};
let mut events = Some(events);
let mut seen = false;
for _ in 0..frames {
*time += 1.0 / 60.0;
let input =
egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(*time), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| {
for (i, &name) in open.iter().enumerate() {
if name.starts_with("over ") {
over_parent(ui.ctx());
}
show(ui.ctx(), name, Id::unique(("modal-reopen-test", name)), 0.0, 8, |ui| {
heading(ui, "Top");
if i > 0 {
ui.label("Alert");
} else if in_rows {
scrolled_rows(ui, "rows", add);
} else {
add(ui);
}
});
}
});
out.textures_delta.clear();
seen = out.shapes.iter().any(|c| match &c.shape {
egui::Shape::Text(t) => {
let r = t.visual_bounding_rect();
t.galley.text() == "Row 0" && screen.contains_rect(r) && c.clip_rect.contains_rect(r)
}
_ => false,
});
}
seen
}
/// A wheel turn far down, at the middle of the 400×300 screen.
fn wheel_down() -> Vec<egui::Event> {
let wheel = egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -3000.0),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Unknown,
modifiers: egui::Modifiers::NONE,
};
vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0)), wheel]
}
#[test]
fn a_window_that_scrolled_opens_again_at_its_top() {
for in_rows in [false, true] {
let ctx = egui::Context::default();
crate::theme::apply(&ctx, Default::default());
let mut time = 0.0;
assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top");
assert!(!first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away");
first_row_seen(&ctx, &[], in_rows, vec![], &mut time, 2);
assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top");
}
}
#[test]
fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() {
// As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it
// did not close. A window that another replaced did close. Either may have shown an alert
// of its own, drawn after it in the same passes.
let others: [(&[&str], bool); 4] = [(&["over B"], true), (&["over B", "Alert"], true), (&["C"], false), (&["C", "Alert"], false)];
let mut wrong = vec![];
for in_rows in [false, true] {
for (other, kept) in others {
let ctx = egui::Context::default();
crate::theme::apply(&ctx, Default::default());
let mut time = 0.0;
first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4);
if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) {
wrong.push(format!("rows {in_rows}: the wheel does not scroll A"));
}
if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) {
wrong.push(format!("rows {in_rows}: {other:?} does not open at its top"));
}
if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept {
wrong.push(format!("rows {in_rows}: after {other:?}, A {} where it was scrolled to", if kept { "is not" } else { "is still" }));
}
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
#[test]
fn a_field_keeps_its_text_and_focus_when_the_window_starts_or_stops_scrolling() {
// A field's edit state and the keyboard focus are kept under its id, so typing goes on into
// the same field when the screen's height changes whether the body or the window scrolls.
let mut wrong = vec![];
for in_body in [false, true] {
let ctx = egui::Context::default();
crate::theme::apply(&ctx, Default::default());
let window = Id::unique("modal-field-id-test");
let mut text = String::from("12");
let mut time = 0.0;
let mut field = None;
let mut focus_given = false;
let mut seen = vec![];
for (height, typed) in [(900.0, "3"), (300.0, "4"), (900.0, "5")] {
let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height));
for i in 0..4 {
time += 1.0 / 60.0;
// Typed once the window has settled at this height.
let events = if i == 3 { vec![egui::Event::Text(typed.into())] } else { vec![] };
let input = egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| {
show(ui.ctx(), "Test", window, 0.0, 8, |ui| {
heading(ui, "Top");
let mut add = |ui: &mut egui::Ui| {
let r = ui.text_edit_singleline(&mut text);
for i in 0..30 {
ui.label(format!("Row {i}"));
}
r.id
};
field = Some(if in_body { body_rows(ui, add) } else { add(ui) });
});
});
out.textures_delta.clear();
// The field is given the focus once, after the first frame; a resize that took it
// away would leave the keys typed after it untaken.
if let Some(id) = field.filter(|_| !focus_given) {
ctx.memory_mut(|m| m.request_focus(id));
focus_given = true;
}
}
let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) };
let scrolls = ctx.data(|m| m.get_temp::<bool>(key).unwrap_or(false) || m.get_temp::<[bool; 2]>(key).is_some_and(|a| a[1]));
seen.push((scrolls, text.clone(), ctx.memory(|m| m.focused()) == field && field.is_some()));
}
let want = [(false, "123", true), (true, "1234", true), (false, "12345", true)];
let want: Vec<_> = want.iter().map(|&(s, t, f)| (s, t.to_string(), f)).collect();
if seen != want {
wrong.push((in_body, seen));
}
}
// Only the short screen scrolls, and the field keeps its focus and takes each key.
assert_eq!(wrong, vec![], "(body, [(scrolls, text, focused)]) that went wrong");
}
}
@@ -85,7 +85,7 @@ mod tests {
d.fields.insert("solidDashes".into(), json!(solid));
super::super::confirm(app)
};
assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true}));
assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true, "viewArtboardContentsOnly": true}));
assert!(app.ui.dialog.is_none());
app.run("ui.navigatorPanelOptions", json!({})).unwrap();
set(&mut app, "#0000FF", true).unwrap();
+27 -3
View File
@@ -1,5 +1,5 @@
//! New Swatch: the Swatch Options fields (name, colour type, Global, mode, sliders and hex)
//! prefilled from the active fill or stroke; a gradient, a pattern or a tint of a global colour
//! New Swatch: the Swatch Options fields (name, colour type, Global, mode, sliders, hex and the
//! colour warnings) prefilled from the active fill or stroke; a gradient, a pattern or a tint of a global colour
//! (saved as a tint swatch, "Name 40%") only takes a name. OK runs `swatch.new`.
//!
//! Fields: `name`, `spot`, `global`, `mode` and `color` as in Swatch Options, `group` (the colour
@@ -45,7 +45,7 @@ pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&s
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
if d.fields.contains_key("__paint") {
grid(ui, |ui| name_row(ui, d));
} else if editor(ui, d)
} else if editor(app, ui, d)
&& d.str("name") == d.str("__auto")
&& let Some(st) = app.session.active()
{
@@ -87,6 +87,30 @@ mod tests {
assert_eq!(params(&d), json!({"name": "Dots", "pattern": "Dots"}));
}
#[test]
fn a_warning_corrects_the_new_colour_only_until_ok() {
use super::super::swatch_options::tests::{click_at, context, settled, warning_rows};
let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
app.run("paint.setFill", json!({"color": "#0000fe"})).unwrap();
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.swatches_iter().count();
let before = count(&app);
open(&mut app, false, false, None).unwrap();
let rows = warning_rows(&settled(&ctx, &mut app));
assert_eq!(rows.len(), 2, "out of gamut and out of web colors");
click_at(&ctx, &mut app, rows[1].1.center());
let d = app.ui.dialog.clone().unwrap();
assert_eq!((color_of(&d).to_hex(), d.str("mode")), ("#0000ff".to_string(), "rgb".to_string()));
assert_eq!(count(&app), before, "no swatch before OK");
assert_eq!(warning_rows(&settled(&ctx, &mut app)).len(), 1, "the web warning is gone");
let name = app.ui.dialog.as_ref().unwrap().str("name");
super::super::confirm(&mut app).unwrap();
assert_eq!(app.session.active().unwrap().doc.swatch(&name).and_then(|s| s.paint.color()).map(|c| c.to_hex()), Some("#0000ff".into()));
app.run("edit.undo", json!({})).unwrap();
assert_eq!(count(&app), before, "one undo step");
}
#[test]
fn a_tint_opens_as_a_named_tint_swatch() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
+1 -1
View File
@@ -77,7 +77,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
});
if let Ok(attrs) = super::char_style_options::edited_attrs(d) {
for (key, value) in attrs {
ui.label(format!("{}: {}", super::humanize(&key), value));
ui.label(super::form::attribute_line(&key, &value));
}
}
});
@@ -11,7 +11,7 @@
use serde_json::{Map, Value, json};
use vectorcraft_doc::objects_on_path::CENTER;
use super::{DialogSpec, run_and_close};
use super::{DialogSpec, set_tool_options_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
@@ -73,7 +73,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
/// Save: set the tool's Pivot and Rotate.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let values: Map<String, Value> = ["pivot", "rotate"].iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect();
run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values }))
set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values }))
}
#[cfg(test)]
@@ -952,7 +952,7 @@ pub(crate) fn general_body(ui: &mut egui::Ui, d: &mut Dialog) {
ui.separator();
if let Ok(attrs) = edited_attrs(d) {
for (key, value) in attrs {
ui.label(format!("{}: {}", super::humanize(&key), value));
ui.label(super::form::attribute_line(&key, &value));
}
}
}
@@ -982,6 +982,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id {
/// (as drawn last frame). The section list stays put while the content scrolls. Returns whether
/// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`).
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
super::modal::fits_itself(ui);
let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height());
let content = ui.ctx().data(|m| m.get_temp::<f32>(content_id(ui))).unwrap_or(0.0);
let rest = (window - content).max(0.0);
+1 -1
View File
@@ -198,7 +198,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
&& let Some(counts) = d.fields.get("__counts")
&& let (Some(before), Some(after)) = (counts["before"].as_u64(), counts["after"].as_u64())
{
ui.label(format!("{}: {before} → {after}", tl!("Anchor Points")));
ui.label(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points"))));
}
}
false
+8 -3
View File
@@ -63,8 +63,13 @@ pub fn open(app: &mut VectorcraftApp, f: &Format, mut params: Value) {
false => export_size(&st.doc, &params),
});
if let Some(o) = params.as_object_mut() {
o.insert("ppi".into(), json!(72));
o.extend(defaults(app, f));
let mut initial = defaults(app, f);
initial.insert("ppi".into(), json!(72));
for (key, value) in initial {
if o.get(&key).is_none_or(Value::is_null) {
o.insert(key, value);
}
}
if let Some((w, h)) = size {
o.insert("__size".into(), json!([w, h]));
}
@@ -155,7 +160,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
d.fields.insert("__otherPpi".into(), json!(i == 3));
}
if preset.is_none()
&& let Some(v) = widgets::range_field(ui, "ro-ppi-other", ppi, 1.0..=4608.0, " ppi", 0, 80.0)
&& let Some(v) = widgets::range_field(ui, "ro-ppi-other", ppi, 1.0..=4608.0, &super::ppi_suffix(), 0, 80.0)
{
d.fields.insert("ppi".into(), json!(v));
}
+2 -1
View File
@@ -251,7 +251,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
ui.vertical(|ui| {
ui.set_width(500.0);
ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong));
egui::ScrollArea::vertical().id_salt(("print", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section {
let list_h = super::modal::list_height(ui, 360.0);
egui::ScrollArea::vertical().id_salt(("print", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section {
"Marks and Bleed" => super::save_pdf::marks_and_bleeds(app, ui, d),
"Output" => output(ui, d, &preview),
"Graphics" => graphics(ui, d),
+1 -1
View File
@@ -167,7 +167,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0);
widgets::dim_label(ui, &format!("{} × {} px · {}: {}", count("width"), count("height"), tl!("Layers"), count("layers")));
widgets::dim_label(ui, &format!("{} × {} px · {} {}", count("width"), count("height"), crate::i18n::colon(tl!("Layers")), count("layers")));
// Offered only for a file with slices, with either conversion.
let sliced = count("slices") > 0;
ui.add_space(8.0);
+2 -2
View File
@@ -59,7 +59,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
}
}
if preset.is_none()
&& let Some(v) = widgets::plain_field(ui, "raster-ppi", ppi, " ppi", 0, 80.0)
&& let Some(v) = widgets::plain_field(ui, "raster-ppi", ppi, &super::ppi_suffix(), 0, 80.0)
{
d.fields.insert("resolution".into(), json!(v));
}
@@ -124,7 +124,7 @@ pub(super) fn effect_fields(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dia
}
if !document
&& preset.is_none()
&& let Some(v) = widgets::plain_field(ui, "rasterize-ppi", ppi, " ppi", 0, 80.0)
&& let Some(v) = widgets::plain_field(ui, "rasterize-ppi", ppi, &super::ppi_suffix(), 0, 80.0)
{
d.fields.insert("resolution".into(), json!(v));
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -733,7 +733,7 @@ pub(super) fn reset_dot(ui: &mut egui::Ui, key: &str, changed: bool, default: &s
ui.painter().rect_filled(r, 3.0, Tokens::get(ui.ctx()).hover);
}
dot(ui, r.center(), changed);
response.on_hover_text(format!("{}: {default}", tl!("Reset to default"))).clicked()
response.on_hover_text(format!("{} {default}", crate::i18n::colon(tl!("Reset to default")))).clicked()
}
#[cfg(test)]
+2 -1
View File
@@ -75,7 +75,8 @@ impl Light {
/// The name screen readers give the light at `index`: its number, Rotation, Height and side.
fn name(self, index: usize) -> String {
let side = if self.behind { format!(", {}", tl!("Light behind the object")) } else { String::new() };
format!("{} {}: {} {:.1}°, {} {:.1}°{side}", c3("Light"), index + 1, tl!("Rotation"), self.rotation, tl!("Height"), self.height)
let light = crate::i18n::colon(&format!("{} {}", c3("Light"), index + 1));
format!("{light} {} {:.1}°, {} {:.1}°{side}", tl!("Rotation"), self.rotation, tl!("Height"), self.height)
}
}
+356 -33
View File
@@ -2,13 +2,18 @@
//! as the web image Save writes, beside the original (Original, Optimized, 2-Up and 4-Up views,
//! each with its file size and download time), and the settings: format (GIF, JPEG, PNG-8,
//! PNG-24), colour reduction, colours, dither, transparency and matte, interlacing, web snap,
//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort), image size
//! and anti-aliasing, Clip to Artboard, sRGB, metadata, slices and HTML output, and presets.
//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color,
//! Restore Generated Table, a double-click that shifts a color to one picked in the Color Picker,
//! and Unshift All Colors), image size and anti-aliasing, Clip to Artboard, sRGB, metadata,
//! slices and HTML output, and presets.
//!
//! Fields are the `document.exportForWeb` settings (`webExport.settings` gives them; set one with
//! `ui.dialog.set`, or `preset` to load a preset), plus the dialog's own: `__view` (`original`,
//! `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` (connection speed),
//! `__color` (the colour table's selected colour, by source), `__presetName` (shown while saving a
//! `__color` (the colour table's selected colour, by source: the one Lock, Transparent and Web
//! Shift edit, and where a Shift-click range starts), `__colors` (every selected color, by source,
//! which Delete Color deletes; when it is empty, `__color` alone), `__editColor` (a source color:
//! the Color Picker opens on it, as a double-click on its swatch opens it), `__presetName` (shown while saving a
//! preset) and `__hasSlices`. Optimize to File Size… (`__optimizeOpen: true`) shows `__optimizeK` (the desired size in K),
//! `__optimizeStart` (`current`, `auto`) and with slices `__optimizeUse` (`allSlices`,
//! `eachSlice`, `currentSlice`); `__optimizeGo: true` runs `webExport.optimizeToFileSize` and
@@ -52,6 +57,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
/// The preview area (panes and their captions) and the settings column.
const PREVIEW_W: f32 = 620.0;
/// The narrowest the panes get in a narrow window.
const MIN_PREVIEW_W: f32 = 240.0;
const PREVIEW_H: f32 = 470.0;
const SIDE_W: f32 = 296.0;
const GAP: f32 = 16.0;
@@ -107,10 +114,10 @@ fn remembered(app: &VectorcraftApp) -> WebSettings {
/// Reset (Cancel with Alt or Option held, or `ui.dialogReset`): the settings go back to the
/// remembered ones on the document's active artboard ([`remembered`]), and a pending `preset`, a
/// pending Done (`discard`, which a failed Done leaves), the preset name being typed and the
/// selected color table entry are dropped. The view, zoom, connection speed and `path` stay,
/// selected color table entries are dropped. The view, zoom, connection speed and `path` stay,
/// nothing is remembered or written, and the dialog stays open.
fn reset(app: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
for key in ["preset", "discard", "__presetName", "__color"] {
for key in ["preset", "discard", "__presetName", "__color", "__colors"] {
d.fields.remove(key);
}
d.fields.extend(settings_fields(&remembered(app)));
@@ -530,12 +537,22 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
{
app.status(e);
}
take_shift(d);
let settings = settings_of(app, d);
let mut browser = false;
ui.horizontal_top(|ui| {
// In a window too narrow for both, the panes are narrower, so the settings beside them and the
// buttons below stay in view. The room is the screen's (the window's own width follows what it
// drew last), less a column for the bar of the body while it scrolls; the settings column is as
// wide as it was drawn last.
let bar = if super::modal::body_view(ui).is_some() { ui.spacing().scroll.allocated_width() } else { 0.0 };
let room = ui.ctx().content_rect().width() - 2.0 * (f32::from(super::MARGIN) + super::EDGE_GAP) - bar;
let rest_id = egui::Id::unique("save-for-web-beside-panes");
let rest = ui.ctx().data(|m| m.get_temp::<f32>(rest_id)).unwrap_or(ui.spacing().item_spacing.x + GAP + SIDE_W);
let preview_w = (room.min(ui.available_width()) - rest).clamp(MIN_PREVIEW_W, PREVIEW_W);
let row = ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(PREVIEW_W);
browser = preview_area(app, ui, d, &settings);
ui.set_width(preview_w);
browser = preview_area(app, ui, d, &settings, preview_w);
});
ui.add_space(GAP);
ui.vertical(|ui| {
@@ -543,23 +560,33 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
side(app, ui, d, settings.as_ref().ok());
});
});
let drawn = row.response.rect.width() - preview_w;
if (ui.ctx().data_mut(|m| std::mem::replace(m.get_temp_mut_or(rest_id, rest), drawn)) - drawn).abs() > 0.5 {
ui.ctx().request_repaint();
}
optimize_on_enter(ui.ctx(), d);
if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) {
app.status(e);
}
// A double-clicked swatch (or an agent's `__editColor`) opens the Color Picker last, over the
// dialog as it now is.
if let Some(source) = d.fields.remove("__editColor").and_then(|v| v.as_str().map(String::from)) {
let start = d.fields.remove("__editStart").and_then(|v| v.as_str().map(String::from)).unwrap_or_else(|| source.clone());
edit_color(d, &source, &start);
}
false
}
/// The view tabs, the panes and the zoom and speed row. Returns whether Preview in Browser was
/// clicked.
fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result<WebSettings, String>) -> bool {
/// The view tabs, the panes (`width` wide) and the zoom and speed row. Returns whether Preview in
/// Browser was clicked.
fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result<WebSettings, String>, width: f32) -> bool {
let t = Tokens::get(ui.ctx());
let view = VIEWS.iter().position(|v| *v == d.str("__view")).unwrap_or(2);
if let Some(i) = widgets::tab_bar(ui, &VIEW_LABELS, view) {
d.fields.insert("__view".into(), json!(VIEWS[i]));
}
ui.add_space(4.0);
let (area, resp) = ui.allocate_exact_size(egui::vec2(PREVIEW_W, PREVIEW_H), egui::Sense::click_and_drag());
let (area, resp) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_H), egui::Sense::click_and_drag());
let pan_id = egui::Id::unique("save-for-web-pan");
let mut pan: egui::Vec2 = ui.ctx().data(|m| m.get_temp(pan_id)).unwrap_or_default();
if resp.dragged() {
@@ -604,6 +631,17 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set
}
ui.add_space(6.0);
let mut browser = false;
// Preview in Browser goes on a row of its own when the panes are too narrow for it beside the
// two lists (its width as `widgets::secondary_button` draws it).
let label = tl!("Preview in Browser");
let button_w = (ui.painter().layout_no_wrap(label.to_string(), crate::theme::semibold(12.5), t.text).size().x + 32.0).max(72.0);
let mut beside = false;
let mut button = |ui: &mut egui::Ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, label));
browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked();
});
};
ui.horizontal(|ui| {
let z = ZOOMS.iter().position(|z| *z == d.str("__zoom")).unwrap_or(2);
let zoom = ui.name_inputs(tl!("Zoom"), |ui| widgets::dropdown(ui, "sfw-zoom", ZOOM_LABELS[z], &ZOOM_LABELS, 110.0));
@@ -620,11 +658,15 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set
{
d.fields.insert("__kbps".into(), json!(s));
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Preview in Browser")));
browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked();
});
beside = ui.available_width() >= button_w;
if beside {
button(ui);
}
});
if !beside {
ui.add_space(4.0);
ui.horizontal(button);
}
browser
}
@@ -729,7 +771,8 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<&
presets_row(app, ui, d, s);
optimize_rows(ui, d, s, &art_key(app));
widgets::divider(ui);
egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(PREVIEW_H - 40.0).auto_shrink([false, true]).show(ui, |ui| {
let list_h = super::modal::list_height(ui, PREVIEW_H - 40.0);
egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| {
let choice = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, options: &[(&str, &str)]| {
form::choice(ui, d, key, label, (LABEL_W, FIELD_W), options);
};
@@ -737,7 +780,12 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<&
let format = s.map_or(WebFormat::Gif, |s| s.format);
match format {
WebFormat::Gif | WebFormat::Png8 => {
let reduction = d.str("reduction");
choice(ui, d, "reduction", tl!("Reduction:"), &pairs(&Reduction::ALL, Reduction::id, Reduction::label));
// Another reduction makes a new palette.
if d.str("reduction") != reduction {
restore_table(d);
}
colors_row(ui, d);
choice(ui, d, "dither", tl!("Dither:"), &pairs(&Dither::ALL, Dither::id, Dither::label));
if Dither::from_id(&d.str("dither")).is_some_and(|x| x != Dither::None) {
@@ -765,7 +813,9 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<&
choice(ui, d, "metadata", tl!("Metadata:"), &pairs(&WebMetadata::ALL, WebMetadata::key, WebMetadata::label));
if format.palette() {
widgets::divider(ui);
color_table(ui, d, s);
if let Err(e) = color_table(ui, d, s) {
app.status(e);
}
}
widgets::divider(ui);
image_size(app, ui, d, s);
@@ -1043,10 +1093,15 @@ fn matte_row(ui: &mut egui::Ui, d: &mut Dialog) {
});
}
/// The colour table of the current settings' preview: swatches (the selected one ringed; locked
/// ones with a square, web-safe ones with a diamond, transparent ones over the grid) and the
/// buttons that edit the selected colour, plus the sort order.
fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) {
/// The colour table of the current settings' preview: swatches (the selected ones ringed; locked
/// ones with a square, web-safe ones with a diamond, transparent ones over the grid), the buttons
/// that edit the selected colour, Delete Color and the table's menu, plus the sort order. A click
/// selects one color, a Shift-click the colors from the anchor, and a Ctrl-click
/// (Command-click on macOS) adds or removes one; a double-click on an opaque color asks for the
/// Color Picker (`__editColor`), and a color shifted by hand shows its source color at the upper
/// left and its new color at the lower right. Returns an error for a deletion that would leave
/// no color.
fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Result<(), String> {
let t = Tokens::get(ui.ctx());
let cache: Option<Cache> = ui.ctx().data(|m| m.get_temp(cache_id()));
let key = s.map(|s| s.to_json().to_string());
@@ -1054,21 +1109,39 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) {
let Some(shot) = shot else {
widgets::subheader(ui, tl!("Color Table"));
widgets::dim_label(ui, tl!("Shown with the optimised preview."));
return;
// A Custom table the preview can't use (a deletion that left only colors mapped to
// transparent) can still go back to the generated palette.
if s.is_some_and(|s| s.color_table.is_custom()) && widgets::flat_button_fit(ui, tl!("Restore Generated Table"), 88.0).clicked() {
restore_table(d);
}
return Ok(());
};
let table = s.map(|s| s.color_table.clone()).unwrap_or_default();
widgets::subheader(ui, &crate::i18n::tn(shot.colors.len() as u64, "Color Table ({n} color)", "Color Table ({n} colors)"));
if table.is_custom() {
widgets::dim_label(ui, tl!("Custom"));
}
let selected = d.str("__color");
let picked = selection(d);
// (colour shown, source, transparent, locked, web-safe, mapped by hand)
let rows: Vec<(TableColor, bool)> = shot
.colors
.iter()
.map(|c| (*c, false))
.chain(shot.mapped.iter().map(|c| (TableColor { color: *c, source: *c, transparent: true, locked: false, web_shifted: false }, true)))
.chain(
shot.mapped
.iter()
.map(|c| (TableColor { color: *c, source: *c, transparent: true, locked: false, web_shifted: false, shifted: false }, true)),
)
.collect();
const CELL: f32 = 15.0;
let per_row = ((SIDE_W - 8.0) / (CELL + 2.0)).floor().max(1.0) as usize;
let lines = rows.len().div_ceil(per_row).max(1);
let (area, resp) = ui.allocate_exact_size(egui::vec2(SIDE_W - 8.0, lines as f32 * (CELL + 2.0)), egui::Sense::click());
let (area, _) = ui.allocate_exact_size(egui::vec2(SIDE_W - 8.0, lines as f32 * (CELL + 2.0)), egui::Sense::hover());
// The colors that can be selected, in table order (for Shift-click ranges).
let order: Vec<String> = rows.iter().filter(|(c, mapped)| !c.transparent || *mapped).map(|(c, _)| hex(c.source)).collect();
let mut clicked = None;
let mut edit = None;
let p = ui.painter();
for (i, (c, mapped)) in rows.iter().enumerate() {
let r = egui::Rect::from_min_size(
@@ -1087,6 +1160,15 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) {
}
} else {
p.rect_filled(r, 0.0, fill);
if c.shifted {
// Shifted by hand: the source color at the upper left, the new one at the lower right.
let [red, g, b] = c.source;
p.add(egui::Shape::convex_polygon(
vec![r.left_top(), r.right_top(), r.left_bottom()],
egui::Color32::from_rgb(red, g, b),
egui::Stroke::NONE,
));
}
}
let mark = if c.color.iter().map(|v| u32::from(*v)).sum::<u32>() > 380 { egui::Color32::BLACK } else { egui::Color32::WHITE };
if c.locked {
@@ -1102,17 +1184,39 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) {
}
// The transparent entry itself isn't a colour to edit.
let pickable = !c.transparent || *mapped;
let picked = pickable && hex(c.source) == selected;
p.rect_stroke(r, 0.0, egui::Stroke::new(if picked { 2.0 } else { 1.0 }, if picked { t.accent } else { t.border }), egui::StrokeKind::Outside);
if pickable && resp.clicked() && resp.interact_pointer_pos().is_some_and(|pos| r.contains(pos)) {
d.fields.insert("__color".into(), json!(hex(c.source)));
let ringed = pickable && picked.iter().any(|h| h.eq_ignore_ascii_case(&hex(c.source)));
p.rect_stroke(r, 0.0, egui::Stroke::new(if ringed { 2.0 } else { 1.0 }, if ringed { t.accent } else { t.border }), egui::StrokeKind::Outside);
if !pickable {
continue;
}
let resp = ui.interact(r, swatch_id(&hex(c.source)), egui::Sense::click());
if resp.clicked() {
clicked = Some(hex(c.source));
}
// A double-click edits an opaque color: the picker opens on the color as shown, or on the
// source color for a color already shifted by hand.
if resp.double_clicked() && !c.transparent {
edit = Some((hex(c.source), hex(if c.shifted { c.source } else { c.color })));
}
}
if let Some(c) = clicked {
let m = ui.input(|i| i.modifiers);
pick(d, &order, &c, m.shift, m.command);
}
if let Some((source, start)) = edit {
d.fields.insert("__editColor".into(), json!(source));
d.fields.insert("__editStart".into(), json!(start));
}
let shifted = |c: &str| table.shifted.keys().any(|k| k.eq_ignore_ascii_case(c));
// The colors the table shows, by source: Lock, Transparent, Web Shift and Delete Color act only
// on these.
let palette: Vec<String> =
shot.colors.iter().filter(|c| !c.transparent).map(|c| hex(c.source)).chain(shot.mapped.iter().map(|c| hex(*c))).collect();
let shown = palette.iter().any(|p| p.eq_ignore_ascii_case(&selected));
ui.add_space(4.0);
let table = s.map(|s| s.color_table.clone()).unwrap_or_default();
let on = |list: &[String]| list.iter().any(|h| h.eq_ignore_ascii_case(&selected));
ui.horizontal(|ui| {
ui.add_enabled_ui(!selected.is_empty(), |ui| {
ui.add_enabled_ui(shown, |ui| {
for (list, on_label, off_label) in [
("transparent", tl!("Restore"), tl!("Transparent")),
("webShift", tl!("Unshift"), tl!("Web Shift")),
@@ -1123,13 +1227,43 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) {
"webShift" => &table.web_shift,
_ => &table.locked,
};
let is_on = on(current);
if widgets::flat_button(ui, if is_on { on_label } else { off_label }, 88.0).clicked() {
// A color shifted by hand stays locked until it is unshifted.
let fixed = list == "locked" && shifted(&selected);
let is_on = on(current) || fixed;
let label = if is_on { on_label } else { off_label };
if ui.add_enabled(!fixed, |ui: &mut egui::Ui| widgets::flat_button(ui, label, 88.0)).clicked() {
toggle(d, list, &selected, !is_on);
// Web Shift replaces a shift by hand.
if list == "webShift" && !is_on {
unshift(d, &selected);
}
}
}
});
});
// Delete Color (the button and the table's menu) and Restore Generated Table. Delete Color
// takes only selected colors the table shows (`palette`, by source).
let deletable = !selected_in(d, &palette).is_empty();
let (mut delete, mut restore, mut unshift_all) = (false, false, false);
ui.horizontal(|ui| {
delete |= widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Color"), false, deletable, 24.0).clicked();
let menu = widgets::icon_button(ui, "menu", tl!("Color Table"), false, 24.0);
let open = menu.clicked();
let _ = widgets::popover(&menu, open, |ui| {
if widgets::menu_item(ui, tl!("Delete Color"), deletable, false) {
delete = true;
ui.close();
}
if widgets::menu_item(ui, tl!("Restore Generated Table"), table.is_custom(), false) {
restore = true;
ui.close();
}
if widgets::menu_item(ui, tl!("Unshift All Colors"), !table.shifted.is_empty() || !table.web_shift.is_empty(), false) {
unshift_all = true;
ui.close();
}
});
});
let sort = table.sort;
widgets::label_row(ui, tl!("Order:"), LABEL_W, |ui| {
let labels = ColorSort::ALL.map(ColorSort::label);
@@ -1139,6 +1273,195 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) {
set_table(d, "sort", json!(o.id()));
}
});
if restore {
restore_table(d);
}
if unshift_all {
unshift_all_colors(d);
}
if delete {
delete_colors(d, &palette)?;
}
Ok(())
}
/// The selected colors (by source) that `palette`, the colors the table shows, holds.
pub(super) fn selected_in(d: &Dialog, palette: &[String]) -> Vec<String> {
selection(d).into_iter().filter(|c| palette.iter().any(|p| p.eq_ignore_ascii_case(c))).collect()
}
/// The colour table's selected colors, by source: `__colors`, else `__color`.
pub(super) fn selection(d: &Dialog) -> Vec<String> {
let many: Vec<String> =
d.fields.get("__colors").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_ascii_lowercase).collect();
if !many.is_empty() {
return many;
}
let one = d.str("__color");
if one.is_empty() { vec![] } else { vec![one.to_ascii_lowercase()] }
}
/// A click on the table's color `color`: it alone is selected and becomes the anchor (`__color`);
/// with `shift`, the colors from the anchor to it in table order (`order`), the anchor unchanged;
/// with `command` (Ctrl, or Command on macOS), it is added to the selection and becomes the anchor,
/// or taken out, and the anchor moves to the last color left in the selection.
pub(super) fn pick(d: &mut Dialog, order: &[String], color: &str, shift: bool, command: bool) {
let color = color.to_ascii_lowercase();
let at = |c: &str| order.iter().position(|o| o.eq_ignore_ascii_case(c));
if shift && let (Some(a), Some(b)) = (at(&d.str("__color")), at(&color)) {
let range: Vec<String> = order[a.min(b)..=a.max(b)].iter().map(|c| c.to_ascii_lowercase()).collect();
d.fields.insert("__colors".into(), json!(range));
return;
}
let mut set = selection(d);
let anchor = if command {
match set.iter().position(|c| *c == color) {
Some(i) => {
set.remove(i);
set.last().cloned()
}
None => {
set.push(color.clone());
Some(color)
}
}
} else {
set = vec![color.clone()];
Some(color)
};
d.fields.insert("__colors".into(), json!(set));
match anchor {
Some(c) => d.fields.insert("__color".into(), json!(c)),
None => d.fields.remove("__color"),
};
}
/// Delete Color: the selected colors join the color table's `deleted` list and leave its other
/// lists. The first deletion fixes the palette (`customPalette`) to `palette`, the table's colors
/// (by source) with the deleted ones, so the colors left do not change. A deletion that leaves no
/// color, or only colors mapped to transparent, is refused with nothing changed. Only selected
/// colors that `palette` holds are deleted; when it holds none of them, the table is left as it is
/// and the selection is cleared. The selection is cleared after a deletion too.
pub(super) fn delete_colors(d: &mut Dialog, palette: &[String]) -> Result<(), String> {
let picked = selected_in(d, palette);
if picked.is_empty() {
d.fields.remove("__colors");
d.fields.remove("__color");
return Ok(());
}
let list = |d: &Dialog, key: &str| -> Vec<String> {
d.fields
.get("colorTable")
.and_then(|t| t.get(key))
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_ascii_lowercase)
.collect()
};
let mut custom = list(d, "customPalette");
if custom.is_empty() {
custom = palette.iter().map(|c| c.to_ascii_lowercase()).collect();
}
let mut deleted = list(d, "deleted");
for c in &picked {
if !deleted.contains(c) {
deleted.push(c.clone());
}
}
// A color has to stay that is neither deleted nor mapped to transparent.
let clear: Vec<String> = list(d, "transparent").into_iter().filter(|c| !picked.contains(c)).collect();
if custom.iter().all(|c| deleted.contains(c) || clear.contains(c)) {
return Err(webexport::KEEP_ONE.into());
}
for key in ["locked", "transparent", "webShift"] {
if list(d, key).iter().any(|c| picked.contains(c)) {
for c in &picked {
toggle(d, key, c, false);
}
}
}
for c in &picked {
unshift(d, c);
}
set_table(d, "customPalette", json!(custom));
set_table(d, "deleted", json!(deleted));
d.fields.remove("__colors");
d.fields.remove("__color");
Ok(())
}
/// Restore Generated Table: no deleted colors and no fixed palette; the reduction makes the
/// palette again.
pub(super) fn restore_table(d: &mut Dialog) {
set_table(d, "deleted", json!([]));
set_table(d, "customPalette", json!([]));
}
/// The id of the color table's swatch for the source color `source` (`#rrggbb`).
pub(super) fn swatch_id(source: &str) -> egui::Id {
egui::Id::unique(("sfw-swatch", source.to_ascii_lowercase()))
}
/// The field of the Color Picker's OK over Save for Web: the color the edited swatch shifts to.
const SHIFT_TO: &str = "__shiftTo";
/// The Color Picker over the dialog for the color table's source color `source`, on `start`; its
/// OK shifts the color ([`shift_color`]) and its Cancel leaves the table as it was. Nothing opens
/// when either is not a color.
pub(super) fn edit_color(d: &mut Dialog, source: &str, start: &str) {
let (Some(_), Some(c)) = (vectorcraft_color::Color::from_hex(source), vectorcraft_color::Color::from_hex(start)) else { return };
d.fields.insert("__shiftSource".into(), json!(source));
*d = super::color_picker::over_effect(d, SHIFT_TO, c);
}
/// Back from the Color Picker: its OK's color shifts the color it was opened for.
fn take_shift(d: &mut Dialog) {
let source = d.fields.remove("__shiftSource");
if let (Some(to), Some(source)) = (d.fields.remove(SHIFT_TO), source)
&& let (Some(to), Some(source)) = (to.as_str(), source.as_str())
{
shift_color(d, source, to);
}
}
/// Shift the source color `source` to `to` (`colorTable.shifted`), wherever it is in the image; it
/// is no longer web-shifted. Picking the source color itself takes the shift away. The color
/// becomes the selection. Nothing changes when either is not a color.
pub(super) fn shift_color(d: &mut Dialog, source: &str, to: &str) {
let hex = |h: &str| vectorcraft_color::Color::from_hex(h).map(|c| c.to_hex());
let (Some(source), Some(to)) = (hex(source), hex(to)) else { return };
unshift(d, &source);
if to != source {
let mut map = shifts(d);
map.insert(source.clone(), json!(to));
set_table(d, "shifted", Value::Object(map));
}
toggle(d, "webShift", &source, false);
d.fields.insert("__colors".into(), json!([source]));
d.fields.insert("__color".into(), json!(source));
}
/// The `colorTable.shifted` field.
fn shifts(d: &Dialog) -> Map<String, Value> {
d.fields.get("colorTable").and_then(|t| t.get("shifted")).and_then(Value::as_object).cloned().unwrap_or_default()
}
/// Take the shift by hand of the source color `source` away.
pub(super) fn unshift(d: &mut Dialog, source: &str) {
let mut map = shifts(d);
let before = map.len();
map.retain(|k, _| !k.eq_ignore_ascii_case(source));
if map.len() != before {
set_table(d, "shifted", Value::Object(map));
}
}
/// Unshift All Colors: no color is shifted by hand or web-shifted.
pub(super) fn unshift_all_colors(d: &mut Dialog) {
set_table(d, "shifted", json!({}));
set_table(d, "webShift", json!([]));
}
/// Add `color` to the colour table's `list`, or take it out.
+55 -8
View File
@@ -152,10 +152,31 @@ fn params(d: &Dialog) -> Value {
p
}
/// Save PDF: write the file (a PDF copy, or the PDF a Save As / Save a Copy asked for, `__save`);
/// the dialog stays open when that fails (bad range, cancelled save…). While Save Preset… asks for
/// a name, OK (and Enter) saves the preset instead.
/// The field that holds why the last Save PDF failed, shown in the dialog (the status bar sits
/// behind it, #6861).
const ERROR: &str = "__error";
/// Save PDF: write the file (see [`write`]). When that fails the dialog stays open and says why,
/// under its sections, as well as in the status bar the dialog covers.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let r = write(app, d);
if let Some(open) = app.ui.dialog.as_mut().filter(|o| o.kind == d.kind) {
match &r {
Err(e) => {
open.fields.insert(ERROR.into(), json!(e));
}
Ok(_) => {
open.fields.remove(ERROR);
}
}
}
r
}
/// Write the file (a PDF copy, or the PDF a Save As / Save a Copy asked for, `__save`); the
/// dialog stays open when that fails (bad range, cancelled save…). While Save Preset… asks for a
/// name, OK (and Enter) saves the preset instead.
fn write(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
if d.fields.contains_key(SAVE_AS) {
let mut d = d.clone();
let r = save_preset(app, &mut d);
@@ -408,7 +429,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
ui.vertical(|ui| {
ui.set_width(500.0);
ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong));
egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section {
let list_h = super::modal::list_height(ui, 360.0);
egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section {
"Compression" => compression(ui, d),
"Marks and Bleeds" => marks_and_bleeds(app, ui, d),
"Output" => output(ui, d),
@@ -417,6 +439,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
"Summary" => summary(app, ui, d),
_ => general(ui, d, editor),
});
if let Some(e) = d.fields.get(ERROR).and_then(Value::as_str) {
ui.add_space(6.0);
ui.label(egui::RichText::new(crate::i18n::message(crate::i18n::current(), e)).color(t.error));
}
});
});
false
@@ -452,7 +478,8 @@ pub(super) fn section_list(ui: &mut egui::Ui, d: &mut Dialog, sections: &[&str],
/// What choosing `standard` changes: the compatibility, to its version unless it allows the one
/// chosen, and off what files of a standard can't have (editing data, passwords; layers in PDF/X-1a
/// and PDF/X-3).
/// and PDF/X-3). In PDF/X-3 and PDF/X-4, Profile inclusion goes back to unset: the picker is
/// disabled there, and `none` would write every CMYK color as DeviceCMYK.
fn standard_chosen(d: &mut Dialog, standard: Standard) {
if choice::<Compatibility>(d, "compatibility").is_some_and(|c| !standard.allows(c)) {
set(d, "compatibility", json!(standard.version().id()));
@@ -466,6 +493,9 @@ fn standard_chosen(d: &mut Dialog, standard: Standard) {
if !standard.allows_layers() {
set(d, "createLayers", json!(false));
}
if standard.is_pdfx() && !standard.cmyk_only() {
set(d, "output.profiles", json!(vectorcraft_pdf::UNSET_CHOICE));
}
}
/// The Preset row (the presets, built-in and saved, and Save Preset…) and, while Save Preset…
@@ -590,9 +620,10 @@ fn image_rows(ui: &mut egui::Ui, d: &mut Dialog, key: &str, title: &str) {
ui.horizontal(|ui| {
pick::<Downsample>(ui, d, &format!("{base}.downsample"), 150.0, |_| true);
ui.label(tl!("to"));
number(ui, d, &format!("{base}.ppi"), " ppi", on);
let ppi = super::ppi_suffix();
number(ui, d, &format!("{base}.ppi"), &ppi, on);
ui.label(tl!("above"));
number(ui, d, &format!("{base}.abovePpi"), " ppi", on);
number(ui, d, &format!("{base}.abovePpi"), &ppi, on);
});
ui.horizontal(|ui| {
ui.label(tl!("Compression:"));
@@ -711,6 +742,22 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog) {
});
if standard.cmyk_only() {
note(ui, tl!("PDF/X-1a files are CMYK: every colour is converted to the destination (blank: the output intent's CMYK profile), untagged."));
} else if standard.is_pdfx() {
note(
ui,
tl!(
"Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK."
),
);
// A preset or the dialog's params can bring `none` with the standard; the picker can't change it.
if choice::<ProfileInclusion>(d, "output.profiles") == Some(ProfileInclusion::None) {
note(
ui,
tl!(
"With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile."
),
);
}
} else if standard != Standard::None {
note(ui, tl!("Files of this standard tag their colours with ICC profiles."));
}
@@ -911,7 +958,7 @@ pub(super) fn option_rows<'a>(ui: &mut egui::Ui, changed: impl IntoIterator<Item
Value::String(s) => s.clone(),
other => other.to_string(),
};
ui.label(egui::RichText::new(format!("{}: {value}", label(c["option"].as_str().unwrap_or_default()))).color(t.text));
ui.label(egui::RichText::new(format!("{} {value}", crate::i18n::colon(&label(c["option"].as_str().unwrap_or_default())))).color(t.text));
}
}
@@ -92,6 +92,27 @@ fn confirm_runs_export_pdf_with_the_dialog_options() {
assert!(app.ui.status.starts_with("Saved /tmp/out.pdf"), "{}", app.ui.status);
}
/// A Save PDF that fails keeps the dialog open and says why inside it (#6861): the status bar is
/// behind the dialog. Saving again, once it works, clears the message.
#[test]
fn a_failed_save_says_why_in_the_dialog() {
let (mut app, written, _) = app();
app.run("ui.savePdfDialog", json!({"path": "/tmp/out.pdf"})).unwrap();
set_field(&mut app, "__allArtboards", json!(false));
set_field(&mut app, "range", json!("9"));
let e = super::super::confirm(&mut app).unwrap_err();
assert!(written.borrow().is_empty(), "nothing was written");
let d = app.ui.dialog.as_ref().expect("the dialog stays open");
assert_eq!(d.str(ERROR), e, "the dialog holds the reason");
assert!(!e.is_empty());
assert!(params(d).get(ERROR).is_none(), "the message is not an option of the export");
frame(&mut app);
set_field(&mut app, "range", json!("1"));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(written.borrow().len(), 1);
}
/// Opened for a page of the art's bounds (Export As with Use Artboards off), the dialog has no
/// Artboards section, and OK writes one page of the art's bounds with its options, a saved preset
/// and View PDF after Saving included.
@@ -537,6 +558,39 @@ fn choosing_a_pdfx_standard_sets_its_version_and_writes_the_standard() {
assert_eq!((get(d, "compatibility"), get(d, "createLayers")), (&json!("1.6"), &json!(true)));
}
/// Profile inclusion is disabled with a standard, so choosing PDF/X-3 or PDF/X-4 sets it back to
/// unset: a `none` chosen before would write every CMYK color as DeviceCMYK.
#[test]
fn choosing_pdfx3_or_pdfx4_unsets_profile_inclusion() {
let (mut app, _, _) = app();
for standard in [Standard::PdfX3, Standard::PdfX4] {
app.run("ui.savePdfDialog", json!({"path": "/tmp/x.pdf", "output": {"profiles": "none"}})).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
assert_eq!(get(d, "output.profiles"), &json!("none"));
set(d, "standard", json!(standard.id()));
standard_chosen(d, standard);
assert_eq!(get(d, "output.profiles"), &json!(vectorcraft_pdf::UNSET_CHOICE), "{}", standard.id());
}
}
/// Opened with PDF/X-3 or PDF/X-4 and `none` (params or a preset, without choosing the standard),
/// the dialog keeps `none` and its Output note says every CMYK color is written as DeviceCMYK.
#[test]
fn a_loaded_pdfx_standard_with_no_profiles_says_cmyk_is_device_cmyk() {
const NOTE: &str = "every CMYK color is written as DeviceCMYK";
let (mut app, _, _) = app();
for (standard, profiles, shown) in
[(Standard::PdfX4, "none", true), (Standard::PdfX3, "none", true), (Standard::PdfX4, "all", false), (Standard::PdfX1a, "none", false)]
{
let params = json!({"path": "/tmp/x.pdf", "standard": standard.id(), "output": {"profiles": profiles}});
app.run("ui.savePdfDialog", params).unwrap();
set_field(&mut app, "__section", json!("Output"));
assert_eq!(get(app.ui.dialog.as_ref().unwrap(), "output.profiles"), &json!(profiles));
let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx()));
assert_eq!(text.contains(NOTE), shown, "{} {profiles}: {text}", standard.id());
}
}
/// "Write pages longer than 200 in at full size in points" is enabled only without a standard, at
/// PDF 1.5 and later: PDF/X files and PDF 1.3 and 1.4 files write long pages in points anyway, and
/// PDF/A files keep the `UserUnit`.
+1 -1
View File
@@ -271,7 +271,7 @@ fn report(ui: &mut egui::Ui, r: &Value, t: &Tokens) {
for p in problems {
let Some(label) = p["code"].as_str().and_then(problem_label) else { continue };
let label = match p["detail"].as_str() {
Some(detail) => format!("{label}: {detail}"),
Some(detail) => format!("{} {detail}", crate::i18n::colon(label)),
None => label.to_string(),
};
row(ui, t, &label, false, &place(p));
+213 -1
View File
@@ -13,10 +13,22 @@
//! `stop`. OK, Enter or `ui.dialog.confirm` without an `answer` gives the default button's answer.
//! Escape or `ui.dialog.cancel` gives Cancel for a prompt, No for a confirm and Stop for an alert.
//! Stop ends the run and puts back everything it did.
//!
//! A script's file dialog (kind `scriptFiles`: `File.openDialog`, `File.saveDialog`,
//! `Folder.selectDialog` and the objects' `openDlg`, `saveDlg` and `selectDlg`) has the fields
//! `kind` (open, save or folder), `prompt` and `canAlways`, and takes `answer`: `once`, `always`
//! (only with `canAlways`), `deny` or `stop`. Only the person at the keyboard answers `once` or
//! `always`: from `ui.dialog.set`, `ui.dialog.confirm` or synthetic input they are refused, and the
//! dialog stays open; `deny` and `stop` are taken from automation too. The paths it allows are the
//! ones Choose… picked in the host's file dialog, at most 2,048; `ui.dialog.set` cannot set them,
//! and the dialog's own fields change neither what it allows nor what it says it allows. Escape,
//! `ui.dialog.cancel`, Enter, and OK or `ui.dialog.confirm` without an `answer` give Deny.
//! `selectDlg` opens the host's folder picker in its own folder.
use serde_json::{Value, json};
use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs};
use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text};
use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker};
use vectorcraft_engine::script::{DialogAnswer, ScriptDialog};
use super::{DialogAction, DialogSpec};
@@ -32,6 +44,19 @@ pub const GROWTH_KIND: &str = "scriptGrowth";
pub const CLOSE_KIND: &str = "scriptClose";
/// The dialog kind of a script's `alert`, `confirm` and `prompt`.
pub const NOTICE_KIND: &str = "scriptDialog";
/// The dialog kind of a script's file dialogs.
pub const PICKER_KIND: &str = "scriptFiles";
pub(super) const PICKER_SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Script File Access").into(),
body_with_actions: Some(picker_body),
confirm: picker_confirm,
ok: None,
inputs: |_| &["answer"],
min_width: 420.0,
max_width: Some(560.0),
..DialogSpec::FORM
};
pub(super) const NOTICE_SPEC: DialogSpec = DialogSpec {
heading: notice_heading,
@@ -171,7 +196,7 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result<Value, String>
/// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which
/// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet.
pub(crate) fn ask_to_close(app: &mut VectorcraftApp) {
let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND);
let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND);
if app.ui.dialog.is_some() {
return;
}
@@ -192,6 +217,7 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) {
if !app.session.script_running() {
app.ui.dialog = None;
} else if app.session.script_dialog().is_none()
&& app.session.script_picker().is_none()
&& let Some(d) = app.ui.dialog.as_mut()
{
d.fields.remove(super::PARENT);
@@ -327,6 +353,192 @@ fn give(app: &mut VectorcraftApp, d: &Dialog, answer: &str) -> Result<Value, Str
Ok(Value::Null)
}
/// Shows the file dialog the running script waits at.
pub(crate) fn open_picker(app: &mut VectorcraftApp, p: &ScriptPicker) {
let fields = json!({
"kind": p.kind.id(),
"prompt": p.prompt,
"multiple": p.multiple,
"start": p.start,
"filters": p.filters,
"canAlways": p.can_always,
});
app.script_picked.clear();
app.script_picked_left_out = false;
app.ui.dialog = Some(Dialog::new(PICKER_KIND, fields));
}
/// Shows the host's file dialog of the kind the running script asked for, starting at the script's
/// file or folder, with the script's file types, and keeps what it picked in
/// [`VectorcraftApp::script_picked`]: in place of the paths before, or after them when the script
/// asked for several files. At most [`MAX_ENTRIES`] paths are kept, the number of files the script
/// is given; the dialog tells the person when it left out more.
pub(crate) fn choose(app: &mut VectorcraftApp, d: &mut Dialog) {
let r = crate::picks::in_app_dialog(app, d, |app, _| {
let Some(p) = app.session.script_picker() else { return Ok(()) };
let start = p.start.as_deref().map(std::path::Path::new);
let name = start.and_then(|s| s.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let folder = start.and_then(|s| s.parent()).map(|s| s.to_string_lossy().into_owned());
let pick = FilePick { name, folder, filters: p.filters.clone() };
let several = p.multiple && p.kind == PickerKind::Open;
let chosen: Vec<String> = match p.kind {
PickerKind::Open if several => crate::picks::open_files(app, &pick),
PickerKind::Open => crate::picks::open(app, &pick).into_iter().collect(),
PickerKind::Save => crate::picks::save(app, &pick).into_iter().collect(),
// `selectDlg` starts in its folder; `Folder.selectDialog` gives none.
PickerKind::Folder => match p.start.clone() {
Some(start) => crate::picks::folder_at(app, &start).into_iter().collect(),
None => crate::picks::folder(app).into_iter().collect(),
},
};
if !chosen.is_empty() {
let mut paths = if several { std::mem::take(&mut app.script_picked) } else { Vec::new() };
let mut seen: std::collections::HashSet<String> = paths.iter().cloned().collect();
for path in chosen {
if seen.contains(&path) {
continue;
}
if paths.len() >= MAX_ENTRIES {
app.script_picked_left_out = true;
break;
}
seen.insert(path.clone());
paths.push(path);
}
app.script_picked = paths;
}
Ok(())
});
// Picking a path doesn't fail.
let _ = r;
}
/// The dialog's prompt and the access it describes come from the request the run waits at, not
/// from the dialog's fields, so `ui.dialog.set` cannot change what the person reads.
fn picker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction {
let t = Tokens::get(ui.ctx());
let Some((kind, prompt)) = app.session.script_picker().map(|p| (p.kind, shown_text(&p.prompt, true))) else { return DialogAction::None };
if !prompt.is_empty() {
egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| ui.label(&prompt));
ui.add_space(8.0);
}
ui.label(picker_request(kind));
ui.add_space(8.0);
let paths = app.script_picked.clone();
ui.horizontal(|ui| {
if widgets::secondary_button(ui, tl!("Choose…")).clicked() {
choose(app, d);
}
ui.add_space(8.0);
if let [path] = paths.as_slice() {
ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong));
}
});
if paths.len() > 1 {
ui.add_space(4.0);
egui::ScrollArea::vertical().id_salt("script-picked").max_height(120.0).show(ui, |ui| {
for path in &paths {
ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong));
}
});
}
if app.script_picked_left_out {
ui.add_space(4.0);
ui.colored_label(t.error, crate::i18n::msg(PICKED_LEFT_OUT));
}
ui.add_space(16.0);
let chosen = !app.script_picked.is_empty();
let can_always = app.session.script_picker().is_some_and(|p| p.can_always);
let mut answer = None;
let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y);
ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| {
if widgets::primary_button_enabled(ui, tl!("Allow Once"), chosen).clicked() {
answer = Some("once");
}
ui.add_space(8.0);
if can_always {
if ui.add_enabled_ui(chosen, |ui| widgets::secondary_button(ui, tl!("Always Allow This Script"))).inner.clicked() {
answer = Some("always");
}
ui.add_space(8.0);
}
if widgets::secondary_button(ui, tl!("Deny")).clicked() {
answer = Some("deny");
}
// The row runs right to left: Stop goes at its left end.
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
if widgets::secondary_button(ui, tl!("Stop")).clicked() {
answer = Some("stop");
}
});
});
// Enter gives the dialog's default answer, Deny, as `ui.dialog.confirm` without an answer does,
// unless it goes to the button that has the keyboard focus (Choose…).
let unfocused = ui.ctx().memory(|m| m.focused().is_none());
if answer.is_none() && unfocused && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) {
answer = Some("deny");
}
let Some(answer) = answer else { return DialogAction::None };
d.fields.insert("answer".into(), json!(answer));
DialogAction::Confirm
}
/// What the file dialog of `kind` asks the person to allow.
fn picker_request(kind: PickerKind) -> &'static str {
match kind {
PickerKind::Open => tl!("The script asks to read a file you choose."),
PickerKind::Save => tl!("The script asks to read and write a file you choose."),
PickerKind::Folder => tl!("The script asks to read and write a folder you choose, with everything in it."),
}
}
/// The note the file dialog shows when the person picked more files than a script is given.
const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out";
/// Gives the running script the file dialog's `answer`, or Deny.
fn picker_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let answer = d.fields.get("answer").and_then(Value::as_str).unwrap_or("deny");
give_pick(app, answer)
}
/// Escape or Cancel: Deny.
pub(super) fn picker_cancel(app: &mut VectorcraftApp, _: &Dialog) {
let _ = give_pick(app, "deny");
}
/// Gives the running script `answer` with the paths Choose… picked. Only the person at the keyboard
/// allows access: Allow Once and Always Allow are refused, and the dialog stays open, while
/// automation sends the answer (a control or MCP request, or synthetic input) or opened the host's
/// file dialog; Deny and Stop are taken from anyone.
fn give_pick(app: &mut VectorcraftApp, answer: &str) -> Result<Value, String> {
let paths = app.script_picked.clone();
let can_always = app.session.script_picker().is_some_and(|p| p.can_always);
let given = match answer {
"stop" => None,
"deny" => Some(PickAnswer::Deny),
"once" | "always" if app.automation_asked() => return Err("Only the person at the keyboard can allow a script's file access".into()),
"once" | "always" if paths.is_empty() => return Err("choose a file or folder first, or deny".into()),
"always" if !can_always => return Err("this script's file access can be allowed only once".into()),
"once" => Some(PickAnswer::Allow { paths, always: false }),
"always" => Some(PickAnswer::Allow { paths, always: true }),
_ => return Err("`answer` for a script's file dialog must be one of: once, always, deny, stop".into()),
};
app.script_picked.clear();
app.script_picked_left_out = false;
match given {
None => {
app.session.script_request_stop();
}
Some(a) => {
app.session.script_pick(a);
}
}
if app.ui.dialog.as_ref().is_some_and(|open| open.kind == PICKER_KIND) {
app.ui.dialog = None;
}
Ok(Value::Null)
}
fn answers_for(kind: &str) -> &'static str {
match kind {
"confirm" => "yes, no, stop",
@@ -14,7 +14,7 @@ use vectorcraft_color::Color;
use vectorcraft_doc::LAYER_COLORS;
use super::tile_edge_color::{checked, resolve};
use super::{DialogSpec, form, run_and_close};
use super::{DialogSpec, form, set_tool_options_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
@@ -124,7 +124,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
checked(&d.str("highlightColor"))?;
}
let values: Map<String, Value> = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect();
run_and_close(app, "tool.setOption", json!({ "tool": "shapeBuilder", "values": values }))
set_tool_options_and_close(app, json!({ "tool": "shapeBuilder", "values": values }))
}
#[cfg(test)]
+44 -23
View File
@@ -102,8 +102,8 @@ fn line_length_angle(d: &Dialog) -> (f64, f64) {
fn arc_options(d: &Dialog) -> Value {
json!({
"closed": d.str("arcType").eq_ignore_ascii_case("closed"),
"lengthX": d.f64("lengthX", 100.0),
"lengthY": d.f64("lengthY", 100.0),
"lengthX": d.f64("lengthX", 100.0).abs(),
"lengthY": d.f64("lengthY", 100.0).abs(),
"reference": arc_reference(d),
"baseAlong": d.str("baseAlong"),
"slope": d.f64("slope", 50.0),
@@ -270,8 +270,8 @@ fn arc_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
const ARC_PREVIEW: egui::Vec2 = egui::vec2(160.0, 120.0);
const ARC_PREVIEW_MARGIN: f32 = 12.0;
/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`], kept as the tool
/// keeps them: a slope from -100 to 100, a Base Along of Y or else X), as `shape.arc` draws it
/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`]; a slope past -100
/// or 100, which OK refuses, is drawn at that end, and a Base Along other than Y along X), as `shape.arc` draws it
/// with its reference point at the origin and General › Constrain Angle `constrain` (degrees)
/// turning it about that point. `None` when a length or the slope is not finite.
fn arc_preview_path(d: &Dialog, constrain: f64) -> Option<vectorcraft_geom::path::PathData> {
@@ -554,13 +554,11 @@ fn box_origin(d: &Dialog) -> (f64, f64) {
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
// Tool Options: the options the tool's next drag and click use; nothing is drawn.
if d.bool(TOOL_OPTIONS) {
let r = app.run("tool.setOption", json!({"tool": d.kind, "values": tool_options(d)}));
app.ui.dialog = None;
return r;
return super::set_tool_options_and_close(app, json!({"tool": d.kind, "values": tool_options(d)}));
}
let count = match d.kind.as_str() {
"polygon" => Some(("sides", 6.0, 3.0)),
"star" => Some(("points", 5.0, 2.0)),
"star" => Some(("points", 5.0, 3.0)),
_ => None,
};
let options = count
@@ -590,7 +588,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
"cx": x,
"cy": y,
"radius": d.f64("radius", 50.0).max(0.01),
"decay": d.f64("decay", 80.0).clamp(5.0, 150.0),
"decay": d.f64("decay", 80.0).clamp(5.0, 99.99),
"segments": (d.f64("segments", 10.0) as u64).clamp(2, 1000),
"clockwise": d.bool("clockwise"),
}),
@@ -648,7 +646,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
// On the active plane while the perspective grid shows, sized in plane units from the click;
// else along General › Constrain Angle, turned about the point the dialog places at the click
// (a grid's reference point, the other shapes' top-left corner or centre).
let options = options.or_else(|| (d.kind == "spiral").then(|| params.clone()));
let options = options.or_else(|| {
(d.kind == "spiral").then(|| json!({"decay": params["decay"], "segments": params["segments"], "clockwise": params["clockwise"]}))
});
// Options the tool would refuse leave the dialog open, before anything is drawn.
if let Some(Value::Object(o)) = &options {
vectorcraft_tools::option_check::check_values(vectorcraft_tools::create(&d.kind).as_ref(), o)?;
}
let result = match vectorcraft_engine::perspective_click(&app.session, id, &params, vectorcraft_geom::Point::new(x, y)) {
Some((id, params)) => run_and_close(app, &id, params),
None => {
@@ -707,6 +711,15 @@ mod tests {
assert!(app.ui.dialog.is_none());
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 1);
assert_eq!(app.session.tool_options_of("spiral"), json!({"decay": 65.0, "segments": 12, "clockwise": true}));
// A decay typed past 99.99 % draws the spiral at 99.99 %, the most a spiral draws, and
// keeps that decay.
super::super::open_tool_dialog(&mut app, "spiral", json!({"x": 40.0, "y": 60.0}));
app.ui.dialog.as_mut().unwrap().fields.insert("decay".into(), json!(120.0));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
assert_eq!(app.session.tool_options_of("spiral")["decay"], json!(99.99));
}
/// With General › Constrain Angle at 90°, the Spiral dialog's spiral starts straight up from the
@@ -812,21 +825,27 @@ mod tests {
}
}
/// For values the Arc tool does not keep as typed, the picture shows the arc of the options OK
/// sets: the same picture as a dialog holding those options.
/// For values the dialog reads as other values, the picture shows the arc of the options OK
/// sets: the same picture as a dialog holding those options. A slope outside -100 to 100 or a
/// Base Along other than X or Y is refused: OK leaves the dialog open and keeps the options.
#[test]
fn the_arc_preview_shows_the_options_ok_sets() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
for typed in [
json!({"slope": 140.0}),
json!({"slope": -250.0}),
json!({"slope": "steep"}),
json!({"lengthX": "wide"}),
json!({"lengthY": null}),
json!({"baseAlong": "z"}),
json!({"reference": 12}),
for (typed, error) in [
(json!({"slope": 140.0}), "`slope` must be a number from -100 to 100"),
(json!({"slope": -250.0}), "`slope` must be a number from -100 to 100"),
(json!({"baseAlong": "z"}), "`baseAlong` must be one of"),
] {
let before = app.session.tool_options_of("arc");
app.ui.dialog = Some(arc_dialog(typed.clone()));
let r = super::super::confirm(&mut app);
assert!(r.as_ref().is_err_and(|e| e.contains(error)), "{typed}: {r:?}");
assert!(app.ui.dialog.is_some(), "{typed}");
assert_eq!(app.session.tool_options_of("arc"), before, "{typed}");
app.ui.dialog = None;
}
for typed in [json!({"slope": "steep"}), json!({"lengthX": "wide"}), json!({"lengthY": null}), json!({"reference": 12})] {
let d = arc_dialog(typed.clone());
let shown = arc_preview_path(&d, 0.0).expect("an arc");
app.ui.dialog = Some(d);
@@ -1112,9 +1131,11 @@ mod tests {
super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0}));
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 6.0);
app.ui.dialog = None;
// `tool.setOption` keeps it from 2 to 1000, and the dialog opens on what it keeps.
for (set, want) in [(json!(1), 2.0), (json!(2000), 1000.0), (json!(7), 7.0)] {
app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})).unwrap();
// `tool.setOption` takes it from 2 to 1000 and refuses other counts, and the dialog opens on
// what it keeps.
for (set, want) in [(json!(1), 6.0), (json!(2000), 6.0), (json!(2), 2.0), (json!(1000), 1000.0), (json!(7), 7.0)] {
let r = app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}}));
assert_eq!(r.is_ok(), set.as_u64().is_some_and(|n| (2..=1000).contains(&n)), "{set}: {r:?}");
super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0}));
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), want, "{set}");
app.ui.dialog = None;
@@ -670,6 +670,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open);
let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0);
crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| {
crate::dialogs::modal::fits_itself(ui);
ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0);
crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set"));
ui.add_space(10.0);
@@ -87,7 +87,7 @@ impl Strip {
/// The open strip `d` moves to the level `cmd {auto: true}` picks for the selection, and the
/// canvas previews it → {level}.
pub fn auto(&self, app: &mut VectorcraftApp, mut d: Dialog) -> Result<Value, String> {
let _ = app.session.begin_interaction(self.label);
app.begin_interaction(self.label)?;
let r = app.session.preview(self.cmd, &json!({ "auto": true })).map_err(|e| e.to_string())?;
let level = r["level"].as_f64().unwrap_or(self.default_level);
d.fields.insert("level".into(), json!(level));
@@ -98,7 +98,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult {
let lines: Vec<String> = options()
.into_iter()
.filter(|(key, ..)| d.bool(key))
.map(|(_, count, label)| format!("{label}: {}", r["replaced"][count].as_u64().unwrap_or(0)))
.map(|(_, count, label)| format!("{} {}", crate::i18n::colon(label), r["replaced"][count].as_u64().unwrap_or(0)))
.collect();
super::confirm::tell(app, tl!("Smart Punctuation"), &lines.join("\n"));
}
+202 -17
View File
@@ -1,7 +1,10 @@
//! Swatch Options: name, colour type (process or spot), Global, colour mode with sliders and hex,
//! previewed live on the canvas (Cancel rolls the preview back). Double-clicking a swatch opens it
//! for a solid colour; for a gradient it shows the name and the gradient; patterns open pattern
//! editing ([`open`]).
//! and the out-of-gamut and out-of-web-color warnings under the colour, previewed live on the canvas
//! (Cancel rolls the preview back). A click on a warning's icon or colour corrects the colour
//! (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf,
//! Swatch options; https://helpx.adobe.com/illustrator/using/adjusting-colors.html).
//! Double-clicking a swatch opens it for a solid colour; for a gradient it shows the name and the
//! gradient; patterns open pattern editing ([`open`]).
//!
//! Fields: `__swatch` (the swatch being edited), `name`, `spot`, `global`, `mode` (`gray`, `rgb`,
//! `hsb`, `lab`, `cmyk` or `web`), `color` (`"#rrggbb"` or a colour object such as
@@ -14,7 +17,9 @@ use vectorcraft_color::{Color, Paint};
use super::{DialogSpec, form, run_and_close};
use crate::VectorcraftApp;
use crate::panels::color::{Mode, components, from_components, parse_hex, track_color, web_safe};
use crate::panels::color::{
GAMUT_WARNING, Mode, WEB_WARNING, components, from_components, gamut_fix, is_web_safe, parse_hex, track_color, warning_chip, web_safe,
};
use crate::state::Dialog;
use crate::theme::Tokens;
use crate::widgets;
@@ -113,7 +118,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
widgets::gradient_chip(ui, r, &g);
changed
}
None => editor(ui, d),
None => editor(app, ui, d),
};
ui.add_space(8.0);
let mut pv = d.bool("preview");
@@ -123,8 +128,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
d.fields.insert("preview".into(), json!(pv));
}
if pv && (changed || pv_changed || !app.session.in_interaction()) {
let _ = app.session.begin_interaction("Swatch Options");
if let Err(e) = app.session.preview("swatch.edit", &edit_params(d)) {
// A failure to begin (typing that can't be kept) shows, and nothing previews.
if let Err(e) = app.begin_interaction("Swatch Options") {
app.status(e);
} else if let Err(e) = app.session.preview("swatch.edit", &edit_params(d)) {
app.status(e.to_string());
}
} else if !pv && pv_changed {
@@ -157,9 +164,9 @@ pub(super) fn name_row(ui: &mut egui::Ui, d: &mut Dialog) -> bool {
changed
}
/// The shared fields of Swatch Options and New Swatch: name, colour type, Global, mode, sliders and
/// hex. Returns true when anything changed.
pub(super) fn editor(ui: &mut egui::Ui, d: &mut Dialog) -> bool {
/// The shared fields of Swatch Options and New Swatch: name, colour type, Global, mode, sliders,
/// hex and the colour warnings. Returns true when anything changed.
pub(super) fn editor(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let mut changed = false;
grid(ui, |ui| {
changed |= name_row(ui, d);
@@ -191,15 +198,46 @@ pub(super) fn editor(ui: &mut egui::Ui, d: &mut Dialog) -> bool {
ui.end_row();
});
ui.add_space(6.0);
changed | sliders(ui, d)
changed | sliders(app, ui, d)
}
/// One slider and value field per component of the dialog's mode, the hex field (RGB, HSB and Web)
/// and a chip of the colour. Returns true when the colour changed.
fn sliders(ui: &mut egui::Ui, d: &mut Dialog) -> bool {
/// A warning under the colour of the swatch dialogs.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Warning {
Gamut,
Web,
}
/// The warnings the swatch dialogs show in `mode`: out of gamut in RGB, HSB and Lab, and out of web
/// colors in every mode but Web Safe RGB.
fn shown_warnings(mode: Mode) -> (bool, bool) {
(matches!(mode, Mode::Rgb | Mode::Hsb | Mode::Lab), mode != Mode::WebSafe)
}
/// The colour and mode a click on `warning` gives `c`, edited in `mode`: the nearest web-safe colour
/// (in RGB unless the mode is RGB or HSB), or the colour's CMYK equivalent in the active CMYK space
/// (in CMYK). `None` when the conversion returns no CMYK values.
fn corrected(app: &mut VectorcraftApp, warning: Warning, mode: Mode, c: &Color) -> Result<Option<(Color, Mode)>, String> {
match warning {
Warning::Web => Ok(Some((web_safe(c), if matches!(mode, Mode::Rgb | Mode::Hsb) { mode } else { Mode::Rgb }))),
Warning::Gamut => {
let r = app.run("color.convert", json!({"color": crate::panels::color_json(c), "to": "cmyk"}))?;
let v = |i: usize| r["values"][i].as_f64().map(|v| v as f32);
Ok(v(0).zip(v(1)).zip(v(2)).zip(v(3)).map(|(((c, m), y), k)| (Color::cmyk(c, m, y, k), Mode::Cmyk)))
}
}
}
/// One slider and value field per component of the dialog's mode, the hex field (RGB, HSB and Web),
/// a chip of the colour and under it the mode's warnings. Returns true when the colour changed.
fn sliders(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let t = Tokens::get(ui.ctx());
let mode = mode_of(d);
let color = color_of(d);
let (shows_gamut, shows_web) = shown_warnings(mode);
let gamut = if shows_gamut { gamut_fix(app, ui.ctx(), "swatch-gamut", &color) } else { None };
let web = (shows_web && !is_web_safe(&color)).then(|| web_safe(&color));
let mut clicked: Option<Warning> = None;
// Keep the displayed components while the colour is unchanged (hue survives S = 0 etc.).
let key = format!("{}|{}", mode_id(mode), serde_json::to_string(&color).unwrap_or_default());
let comps: Vec<f32> = match d.fields.get("__comps") {
@@ -239,13 +277,47 @@ fn sliders(ui: &mut egui::Ui, d: &mut Dialog) -> bool {
});
}
});
let (r, _) = ui.allocate_exact_size(vec2(44.0, 44.0), egui::Sense::hover());
widgets::swatch_tile(ui, r, &Paint::solid(color), false, false);
ui.vertical(|ui| {
let (r, _) = ui.allocate_exact_size(vec2(44.0, 44.0), egui::Sense::hover());
widgets::swatch_tile(ui, r, &Paint::solid(color), false, false);
let warnings: Vec<_> = [(Warning::Gamut, GAMUT_WARNING, gamut), (Warning::Web, WEB_WARNING, web)]
.into_iter()
.filter_map(|(w, chip, fix)| Some((w, chip, fix?)))
.collect();
for (w, chip, fix) in &warnings {
ui.add_space(4.0);
if warning_chip(ui, *chip, fix) {
clicked = Some(*w);
}
}
// Room for the mode's other warnings, so the dialog keeps its height as the colour changes.
for _ in warnings.len()..usize::from(shows_gamut) + usize::from(shows_web) {
ui.add_space(4.0);
ui.scope(|ui| {
ui.set_invisible();
warning_chip(ui, WEB_WARNING, &Color::WHITE)
});
}
});
});
let mut mode = mode;
if let Some(w) = clicked {
match corrected(app, w, mode, &color) {
Ok(Some((c, m))) => {
mode = m;
d.fields.insert("mode".into(), json!(mode_id(m)));
new = Some((c, components(m, &c)));
}
Ok(None) => {}
Err(e) => app.status(e),
}
}
let Some((c, comps)) = new else { return false };
set_color(d, c);
d.fields.insert("__compsKey".into(), json!(format!("{}|{}", mode_id(mode), serde_json::to_string(&c).unwrap_or_default())));
d.fields.insert("__comps".into(), json!(comps));
// The warnings above were drawn for the colour before the change.
ui.ctx().request_repaint();
true
}
@@ -277,9 +349,122 @@ fn hex_field(ui: &mut egui::Ui, hex: &str) -> Option<Color> {
}
#[cfg(test)]
mod tests {
pub(super) mod tests {
use super::*;
/// A test context with the application's fonts and default theme.
pub(crate) fn context() -> egui::Context {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
crate::theme::apply(&ctx, Default::default());
ctx
}
/// Runs one frame of the open dialog with `events` and returns the rectangles it paints.
pub(crate) fn draw(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<egui::Rect> {
fn collect(s: &egui::Shape, out: &mut Vec<egui::Rect>) {
match s {
egui::Shape::Rect(r) => out.push(r.rect),
egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)),
_ => {}
}
}
let input =
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 900.0))), events, ..Default::default() };
let mut out = ctx.run_ui(input, |ui| super::super::show(app, ui.ctx()));
out.textures_delta.clear();
let mut boxes = vec![];
out.shapes.iter().for_each(|c| collect(&c.shape, &mut boxes));
boxes
}
/// Lets the auto-sized dialog settle and returns the rectangles of the next frame.
pub(crate) fn settled(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec<egui::Rect> {
for _ in 0..6 {
draw(ctx, app, vec![]);
}
draw(ctx, app, vec![])
}
/// A primary-button press and release at `at`, in two frames.
pub(crate) fn click_at(ctx: &egui::Context, app: &mut VectorcraftApp, at: egui::Pos2) {
for pressed in [true, false] {
let button = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
draw(ctx, app, vec![egui::Event::PointerMoved(at), button]);
}
}
/// The warning rows under the dialog's 44-point colour chip, top first: the centre of each
/// row's icon and the rectangle of its corrected colour.
pub(crate) fn warning_rows(boxes: &[egui::Rect]) -> Vec<(egui::Pos2, egui::Rect)> {
let near = |a: f32, b: f32| (a - b).abs() < 0.5;
let chip = boxes.iter().find(|r| near(r.width(), 44.0) && near(r.height(), 44.0)).copied().unwrap();
let mut rows: Vec<egui::Rect> = boxes
.iter()
.filter(|r| near(r.width(), 16.0) && near(r.height(), 16.0))
.filter(|r| r.top() >= chip.bottom() && r.left() >= chip.left() - 1.0 && r.right() <= chip.right() + 1.0)
.copied()
.collect();
rows.sort_by(|a, b| a.top().total_cmp(&b.top()));
rows.dedup_by(|a, b| near(a.top(), b.top())); // The tile's fill and border share one rectangle.
rows.into_iter().map(|r| (r.center() - vec2(19.0, 0.0), r)).collect()
}
fn dialog(app: &VectorcraftApp) -> &Dialog {
app.ui.dialog.as_ref().unwrap()
}
#[test]
fn swatch_options_shows_and_corrects_both_warnings() {
let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("swatch.new", json!({"name": "Sky", "color": "#0000fe", "spot": true})).unwrap();
app.run("ui.swatchOptions", json!({"name": "Sky"})).unwrap();
let rows = warning_rows(&settled(&ctx, &mut app));
assert_eq!(rows.len(), 2, "out of gamut and out of web colors");
// The cube's icon shifts to the nearest web-safe colour, in the same mode.
click_at(&ctx, &mut app, rows[1].0);
assert_eq!((color_of(dialog(&app)).to_hex(), dialog(&app).str("mode")), ("#0000ff".to_string(), "rgb".to_string()));
let rows = warning_rows(&settled(&ctx, &mut app));
assert_eq!(rows.len(), 1, "web-safe blue is still out of gamut");
// The triangle's colour shifts to the CMYK equivalent, edited in CMYK.
let ink = corrected(&mut app, Warning::Gamut, Mode::Rgb, &Color::rgb8(0, 0, 255)).unwrap().unwrap().0;
click_at(&ctx, &mut app, rows[0].1.center());
assert_eq!((color_of(dialog(&app)), dialog(&app).str("mode")), (ink, "cmyk".to_string()));
assert!(app.ui.dialog.is_some(), "a correction only edits the fields");
super::super::confirm(&mut app).unwrap();
let sw = app.session.active().unwrap().doc.swatch("Sky").cloned().unwrap();
assert_eq!((sw.paint.color(), sw.spot, sw.global), (Some(ink), true, true), "still a spot colour");
app.run("edit.undo", json!({})).unwrap();
let sw = app.session.active().unwrap().doc.swatch("Sky").cloned().unwrap();
assert_eq!(sw.paint.color().map(|c| c.to_hex()), Some("#0000fe".into()), "one undo step");
}
#[test]
fn swatch_warnings_follow_the_mode() {
let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("swatch.new", json!({"name": "Mid", "color": "#808080"})).unwrap();
app.run("ui.swatchOptions", json!({"name": "Mid"})).unwrap();
let mut rows_in = |mode: &str, c: Color| {
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("mode".into(), json!(mode));
set_color(d, c);
warning_rows(&settled(&ctx, &mut app)).len()
};
assert_eq!(rows_in("gray", Color::gray(0.5)), 1, "a gray off the web palette, never out of gamut");
let cyan = Color::cmyk(1.0, 0.0, 0.0, 0.0);
assert_eq!(rows_in("cmyk", cyan), usize::from(!is_web_safe(&cyan)), "CMYK is never out of gamut");
assert_eq!(rows_in("web", Color::rgb8(0, 0, 255)), 0, "Web Safe RGB shows no warning");
assert_eq!(rows_in("rgb", Color::rgb8(0, 0, 255)), 1, "RGB blue is out of gamut");
assert_eq!(rows_in("lab", Color::lab(30.0, 60.0, -100.0)), 2, "Lab shows both");
// A web correction of a Lab colour is edited in RGB.
let rows = warning_rows(&settled(&ctx, &mut app));
click_at(&ctx, &mut app, rows[1].0);
assert_eq!(dialog(&app).str("mode"), "rgb");
assert!(is_web_safe(&color_of(dialog(&app))));
}
#[test]
fn fields_round_trip_modes_and_colours() {
for (m, id) in MODES {
+17 -5
View File
@@ -8,7 +8,8 @@
//! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` |
//! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid;
//! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol), `__edit` (true when editing an
//! existing symbol). Help:
//! existing symbol), `__keepArt` (true when a new symbol leaves the selection as ordinary art).
//! Help:
//! <https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html>.
use serde_json::{Map, Value, json};
@@ -69,15 +70,23 @@ const EXPORT_TYPES: [(&str, &str); 2] = [("movieClip", "Movie Clip"), ("graphic"
pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Symbol Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM };
/// Open Symbol Options to name a new symbol made from the selection.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
/// Open Symbol Options to name a new symbol made from the selection. With `keep_art`, OK leaves
/// the selection as ordinary art instead of replacing it with an instance.
pub fn open(app: &mut VectorcraftApp, keep_art: bool) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
if st.selection.is_empty() {
return Err("nothing selected".into());
}
let name = st.doc.unique_symbol_name("New Symbol");
let mut fields =
json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "alignToPixelGrid": false, "__edit": false });
let mut fields = json!({
"name": name,
"exportType": "movieClip",
"type": "dynamic",
"registration": 4,
"alignToPixelGrid": false,
"__edit": false,
"__keepArt": keep_art,
});
if let Some(o) = fields.as_object_mut() {
o.extend(slice_fields(None));
}
@@ -193,6 +202,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
} else {
let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel });
merge(&mut params, slice_params(d));
if d.bool("__keepArt") {
params["keepArt"] = json!(true);
}
app.run("symbol.new", params)
};
if r.is_ok() {
@@ -6,7 +6,7 @@
use serde_json::{Map, Value, json};
use super::{DialogResult, DialogSpec, form, run_and_close};
use super::{DialogResult, DialogSpec, form, set_tool_options_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
@@ -50,7 +50,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
/// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges).
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult {
let values: Map<String, Value> = KEYS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect();
run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values }))
set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values }))
}
#[cfg(test)]
+204
View File
@@ -178,6 +178,64 @@ fn effect_preview_is_kept_as_one_undo_step() {
assert_eq!(app.session.doc().unwrap().doc, before);
}
/// A field label's colon is written as the UI language writes it, in the generic parameter
/// dialogs and the effect dialogs alike (#7991): French puts a no-break space before it, Chinese
/// writes a full-width colon, and English is unchanged.
#[test]
fn field_label_colons_follow_the_ui_language() {
let mut app = app();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
let text =
app.run("text.create", json!({"x": 20, "y": 80, "text": "Hello", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap();
// Each dialog, opened the way its menu item opens it, and the label it shows.
let entries = crate::menus::menu_entries(&app);
let clean_up = entries.iter().find(|e| e.path == ["Object", "Path"] && e.label == "Clean Up…").expect("listed");
let clean_up = crate::menus::click_target(&clean_up.label, clean_up.command.as_deref().unwrap(), &clean_up.params);
let dialogs = [
(clean_up.0, clean_up.1, "Stray Points"),
("effect.dialog".to_string(), json!({"effect": "blur.radial"}), "Horizontal"),
("text.areaOptions".to_string(), json!({}), "Text Flow"),
];
for (command, params, label) in dialogs {
app.run("select.set", json!({"ids": [text]})).unwrap();
if command != "text.areaOptions" {
app.run("select.all", json!({})).unwrap();
}
crate::menus::invoke(&mut app, &command, params);
assert!(app.ui.dialog.is_some(), "{command} opened no dialog");
for (code, colon) in [("fr", "\u{a0}:"), ("zh-hans", ":"), ("en", ":")] {
let lang = crate::i18n::Lang::from_code(code).unwrap();
crate::i18n::set_current(lang);
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
crate::i18n::set_current(crate::i18n::Lang::EN);
let want = format!("{}{colon}", crate::i18n::tr(lang, label));
assert!(shown.lines().any(|l| l.trim() == want), "{command}, {code}: {want:?} in {shown}");
if code == "fr" {
let bare: Vec<_> = shown.lines().map(str::trim).filter(|l| l.ends_with(':') && !l.ends_with("\u{a0}:")).collect();
assert!(bare.is_empty(), "{command}: French labels with a bare colon: {bare:?}");
}
}
app.ui.dialog = None;
}
assert_eq!(super::form::humanized("strayPoints"), "Stray Points:", "English is unchanged");
}
/// A label followed by its value takes the UI language's colon too (#7991): Blur Center's value for
/// screen readers, and a style's attribute list, which no longer shows a second colon.
#[test]
fn label_and_value_colons_follow_the_ui_language() {
let fr = crate::i18n::Lang::from_code("fr").unwrap();
crate::i18n::set_current(fr);
let center = super::effect::blur_center_value([0.5, 0.25]);
let attribute = super::form::attribute_line("fontSize", &json!(12));
crate::i18n::set_current(crate::i18n::Lang::EN);
let (h, v) = (crate::i18n::tr(fr, "Horizontal"), crate::i18n::tr(fr, "Vertical"));
assert_eq!(center, format!("{h}\u{a0}: 50%, {v}\u{a0}: 25%"));
assert_eq!(attribute, format!("{}\u{a0}: 12", crate::i18n::tr(fr, "Font Size")));
assert_eq!(super::effect::blur_center_value([0.5, 0.25]), "Horizontal: 50%, Vertical: 25%");
assert_eq!(super::form::attribute_line("fontSize", &json!(12)), "Font Size: 12");
}
/// Drop Shadow's Color typed as text the effect can't draw: OK returns the error and keeps the
/// dialog open, with Preview on or off, and the document stays as it was.
#[test]
@@ -2832,6 +2890,61 @@ fn the_blob_brush_tip_preview_is_a_named_slider_with_arrow_keys() {
assert_eq!(angle(&app), -44.0, "the drag gives the preview the focus");
}
/// A drag that starts on a black dot of the Blob Brush tip preview sets the Roundness from the
/// pointer's distance from the center along the tip's short axis, leaves the Angle as it is, goes
/// on past the square's edge (stopping at 100%), and gives the Roundness slider the focus, whose
/// keys step the Roundness by 1% (10% with Shift) within 0% to 100%. A drag that starts anywhere
/// else sets only the Angle, and Tab goes from the Angle slider to the Roundness slider.
#[test]
fn a_drag_on_a_blob_brush_tip_dot_sets_the_roundness() {
use egui::Key::{ArrowDown, ArrowRight, ArrowUp, End, Home, Tab};
use egui::Modifiers as M;
let mut app = app();
app.run("tool.options", json!({"tool": "blobBrush"})).unwrap();
let values = |app: &VectorcraftApp| {
let d = app.ui.dialog.as_ref().expect("Blob Brush Tool Options is open");
(d.f64("angle", f64::NAN), d.f64("roundness", f64::NAN))
};
let mut f = Frames::new();
f.run(&mut app, vec![]);
let out = f.run(&mut app, vec![]);
let (_, value, text) = slider_node(&out, "Roundness");
assert_eq!((value, text.as_deref()), (Some(100.0), Some("100%")));
let center = f.control(&mut app, "Roundness", egui::accesskit::Role::Slider);
// At 0° the dots are straight above and below the center, 18 pt from it at 100%. A click
// pressed 6 pt from the upper dot and released 11 pt from it in the same frame takes the dot.
let (down, up) = (center + egui::vec2(0.0, -12.0), center + egui::vec2(0.0, -7.0));
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: M::NONE };
f.run(&mut app, vec![egui::Event::PointerMoved(down), button(down, true), egui::Event::PointerMoved(up), button(up, false)]);
assert_eq!(values(&app), (0.0, 39.0), "a click that starts on the upper dot");
f.drag(&mut app, center + egui::vec2(0.0, -7.0), egui::vec2(1.0, -11.0));
assert_eq!(values(&app), (0.0, 100.0), "the upper dot dragged out to the tip's length");
f.drag(&mut app, center + egui::vec2(0.0, -18.0), egui::vec2(1.0, 9.0));
assert_eq!(values(&app), (0.0, 50.0), "the upper dot dragged half way to the center");
f.drag(&mut app, center + egui::vec2(0.0, 9.0), egui::vec2(3.0, 60.0));
assert_eq!(values(&app), (0.0, 100.0), "the lower dot dragged out of the square");
f.drag(&mut app, center + egui::vec2(0.0, 18.0), egui::vec2(0.0, -18.0));
assert_eq!(values(&app), (0.0, 0.0), "the lower dot dragged to the center");
let mut seen = vec![];
for (key, mods, want) in
[(ArrowUp, M::NONE, 1.0), (ArrowRight, M::SHIFT, 11.0), (ArrowDown, M::NONE, 10.0), (End, M::NONE, 100.0), (Home, M::NONE, 0.0)]
{
f.key(&mut app, key, mods);
seen.push((key, mods.shift, values(&app)));
assert_eq!(values(&app), (0.0, want), "{seen:?}");
}
let out = f.run(&mut app, vec![]);
assert_eq!(slider_node(&out, "Roundness").2.as_deref(), Some("0%"));
// With a 0% tip the dots are at the center; a drag that starts away from them sets the Angle.
f.drag(&mut app, center + egui::vec2(20.0, 0.0), egui::vec2(0.0, -20.0));
assert_eq!(values(&app), (45.0, 0.0), "the drag ends up to the right");
f.key(&mut app, ArrowRight, M::NONE);
assert_eq!(values(&app), (46.0, 0.0), "the drag gives the Angle slider the focus");
f.key(&mut app, Tab, M::NONE);
f.key(&mut app, ArrowUp, M::NONE);
assert_eq!(values(&app), (46.0, 1.0), "Tab goes on to the Roundness slider");
}
/// Screen readers can set the Blob Brush tip preview's Angle to a number: the slider offers the
/// set-value action, a fraction rounds to the whole degrees the field shows, a number past -180° to
/// 180° sets the nearer end, the last request in a frame wins, and a value that is not a finite
@@ -3654,3 +3767,94 @@ fn color_halftones_max_radius_stays_in_pixels_whatever_the_units() {
assert!(shows, "{typed} shows as {shown}, not in centimetres");
}
}
/// The resolution fields of Flatten Transparency, Document Raster Effects Settings, Effect ›
/// Rasterize, the PNG options and the PDF save dialog's Compression section show their unit in the interface
/// language (French "ppp"), as the `{n} ppi` row writes it.
#[test]
fn resolution_fields_show_the_ppi_unit_in_the_interface_language() {
fn texts(s: &egui::Shape, out: &mut Vec<String>) {
match s {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
fn shown(app: &mut VectorcraftApp) -> Vec<String> {
let ctx = egui::Context::default();
theme::install_fonts(&ctx);
theme::apply(&ctx, Default::default());
let raw =
|| egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0))), ..Default::default() };
// A window is measured in its first frame and drawn from the second.
ctx.run_ui(raw(), |ui| show(app, ui.ctx())).textures_delta.clear();
let mut out = ctx.run_ui(raw(), |ui| show(app, ui.ctx()));
out.textures_delta.clear();
let mut all = vec![];
out.shapes.iter().for_each(|s| texts(&s.shape, &mut all));
all
}
type Open = fn(&mut VectorcraftApp);
let dialogs: [(&str, Open, &str); 5] = [
(
"Flatten Transparency",
|app| {
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
app.run("transparency.set", json!({"opacity": 50})).unwrap();
app.run("ui.flattenTransparencyDialog", json!({})).unwrap();
},
"ppp",
),
(
"Document Raster Effects Settings",
|app| {
crate::menus::invoke(app, "document.rasterEffectsSettings", json!({}));
app.ui.dialog.as_mut().unwrap().fields.insert("resolution".into(), json!(200));
},
"200 ppp",
),
(
"Rasterize",
|app| {
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
crate::menus::invoke(app, "effect.dialog", json!({"effect": "rasterize"}));
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("useDocumentResolution".into(), json!(false));
d.fields.insert("resolution".into(), json!(200));
},
"200 ppp",
),
(
"PNG Options",
|app| {
png_options::open(app, vectorcraft_engine::cmd::fileio::format("png").unwrap(), json!({"format": "png", "path": "/out/a.png"}));
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("ppi".into(), json!(200));
d.fields.insert("__otherPpi".into(), json!(true));
},
"200 ppp",
),
(
"Save PDF",
|app| {
app.run("ui.savePdfDialog", json!({"path": "/tmp/ppi.pdf"})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("__section".into(), json!("Compression"));
},
" ppp",
),
];
let mut bad = vec![];
for (name, open, want) in dialogs {
let mut app = app();
open(&mut app);
crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap());
let texts = shown(&mut app);
crate::i18n::set_current(crate::i18n::Lang::EN);
let translated = texts.iter().any(|t| t.trim() == want.trim() || (want.starts_with(' ') && t.ends_with(want)));
let english = texts.iter().any(|t| t.trim() == "ppi" || t.ends_with(" ppi"));
if !translated || english {
bad.push(format!("{name}: {texts:?}"));
}
}
assert!(bad.is_empty(), "{}", bad.join("\n"));
}
+218
View File
@@ -67,6 +67,224 @@ fn eps_options_take_saved_flattener_presets_and_refuse_bad_ones() {
assert!(written.borrow()[0].1.starts_with(b"%!PS-Adobe-3.0 EPSF-3.0"), "{:?}", &written.borrow()[0].1[..8]);
}
/// Two overlapping squares, the second half transparent, so that an EPS export flattens them.
fn transparent_art(app: &mut VectorcraftApp) {
for (x, color) in [(5, "#ff0000"), (20, "#0000ff")] {
app.run("select.none", json!({})).unwrap();
app.run("paint.setFill", json!({"color": color})).unwrap();
app.run("shape.rectangle", json!({"x": x, "y": 5, "width": 30, "height": 30})).unwrap();
}
app.run("transparency.set", json!({"opacity": 50})).unwrap();
}
/// Custom… over EPS Options, as its button opens it.
fn open_custom(app: &mut VectorcraftApp) {
let parent = app.ui.dialog.clone().expect("EPS Options are open");
app.ui.dialog = Some(eps_options::over(&parent, &app.session.prefs.flattener_presets));
frame(app);
}
#[test]
fn custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged() {
let (mut app, _) = app(1);
app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "flattenerPreset": "high"})).unwrap();
frame(&mut app);
let before = app.ui.dialog.as_ref().unwrap().fields.clone();
open_custom(&mut app);
assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND));
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.f64("balance", 0.0), d.f64("lineArtPpi", 0.0), d.bool("clipComplexRegions")), (100.0, 1200.0, true), "High Resolution's");
assert!(!d.bool("preserveAlpha"), "EPS has no alpha");
set(&mut app, "balance", json!(10));
cancel(&mut app);
assert_eq!(kind(&app), Some("epsOptions"));
assert_eq!(app.ui.dialog.as_ref().unwrap().fields, before, "Cancel leaves EPS Options as they were");
}
#[test]
fn custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen() {
let (mut app, written) = app(1);
transparent_art(&mut app);
app.run("flattener.presets.save", json!({"name": "Mine", "balance": 100})).unwrap();
let opts = json!({"path": "/out/a.eps", "flattenerPreset": "Mine", "previewFormat": "none", "thumbnails": false});
app.run("ui.epsOptionsDialog", opts).unwrap();
frame(&mut app);
open_custom(&mut app);
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("balance", 0.0), 100.0, "the saved preset's");
set(&mut app, "balance", json!(0));
confirm(&mut app).unwrap();
assert_eq!(kind(&app), Some("epsOptions"), "OK goes back to EPS Options");
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.fields["flattener"]["balance"].as_f64(), d.fields["flattener"]["preserveAlpha"].as_bool()), (Some(0.0), Some(false)));
assert_eq!(d.str("flattenerPreset"), "Medium Resolution", "a built-in preset under options that set everything");
frame(&mut app);
// The custom options don't need the saved preset they started from.
app.run("flattener.presets.delete", json!({"name": "Mine"})).unwrap();
confirm(&mut app).unwrap();
assert!(ps(&written.borrow()[0].1).contains("image"), "balance 0 rasterizes the flattened art");
// The next EPS Options start from them; a preset asked for without options drops them.
crate::menus::invoke(&mut app, "ui.epsOptionsDialog", json!({}));
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"]["balance"].as_f64(), Some(0.0));
cancel(&mut app);
app.run("ui.epsOptionsDialog", json!({"path": "/out/b.eps", "flattenerPreset": "medium"})).unwrap();
assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener"));
confirm(&mut app).unwrap();
assert!(!ps(&written.borrow()[1].1).contains("image"), "Medium Resolution keeps the squares vector");
}
#[test]
fn a_flattener_preset_set_from_outside_drops_the_custom_options() {
let (mut app, _) = app(1);
app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap();
frame(&mut app);
open_custom(&mut app);
set(&mut app, "balance", json!(20));
confirm(&mut app).unwrap();
assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener"));
// `ui.dialog.set {flattenerPreset: "low"}`, as the control channel sets it.
let old = app.ui.dialog.as_ref().unwrap().fields.get("flattenerPreset").cloned();
set(&mut app, "flattenerPreset", json!("low"));
field_set(&mut app, "flattenerPreset", old.as_ref()).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert!(!d.fields.contains_key("flattener"), "the preset replaces the custom options");
assert_eq!(d.str("flattenerPreset"), "Low Resolution");
}
#[test]
fn bad_custom_flattener_options_keep_the_dialog_open() {
let (mut app, _) = app(1);
app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "overprints": "discard"})).unwrap();
frame(&mut app);
open_custom(&mut app);
set(&mut app, "gradientPpi", json!(9000));
frame(&mut app);
let e = confirm(&mut app).unwrap_err();
assert!(e.contains("resolutions"), "{e}");
assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND));
// Overprints decides whether overprints are kept, so OK keeps the option as it was.
set(&mut app, "gradientPpi", json!(150));
set(&mut app, "preserveAlpha", json!(true));
confirm(&mut app).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.fields["flattener"]["preserveOverprints"].as_bool(), d.fields["flattener"]["preserveAlpha"].as_bool()), (Some(true), Some(false)));
}
/// Headless frames of the dialog layer with screen-reader output, input events and a clock.
pub(super) struct Frames {
ctx: egui::Context,
time: f64,
}
impl Frames {
pub(super) fn new() -> Self {
let ctx = egui::Context::default();
ctx.enable_accesskit();
crate::theme::install_fonts(&ctx);
Self { ctx, time: 0.0 }
}
fn run(&mut self, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> egui::FullOutput {
self.time += 0.1;
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0));
let input = egui::RawInput { events, time: Some(self.time), screen_rect: Some(screen), ..Default::default() };
let mut out = self.ctx.run_ui(input, |ui| show(app, ui.ctx()));
out.textures_delta.clear();
out
}
/// The screen-reader node of the control of `role` named `label`, with its center.
pub(super) fn control(&mut self, app: &mut VectorcraftApp, label: &str, role: egui::accesskit::Role) -> (egui::accesskit::NodeId, egui::Pos2) {
self.run(app, vec![]);
let out = self.run(app, vec![]);
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
let (id, n) =
nodes.iter().find(|(_, n)| n.label() == Some(label) && n.role() == role).unwrap_or_else(|| panic!("no {role:?} named {label:?}"));
let b = n.bounds().expect("bounds");
(*id, egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5))
}
pub(super) fn click(&mut self, app: &mut VectorcraftApp, at: egui::Pos2) {
for pressed in [true, false] {
let button = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
self.run(app, vec![egui::Event::PointerMoved(at), button]);
}
}
/// Click the text field named `label`, type `text` over its text and press Tab.
pub(super) fn type_into(&mut self, app: &mut VectorcraftApp, label: &str, text: &str) {
let (_, at) = self.control(app, label, egui::accesskit::Role::TextInput);
self.click(app, at);
self.run(app, vec![egui::Event::Text(text.into())]);
let tab = |pressed| egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
self.run(app, vec![tab(true)]);
self.run(app, vec![tab(false)]);
self.run(app, vec![]);
}
}
/// Enter on the focused Custom… button opens the custom options and does not also confirm them.
#[test]
fn enter_on_the_custom_button_opens_the_custom_options() {
use egui::accesskit::{Action, ActionRequest, Role, TreeId};
let (mut app, _) = app(1);
app.run("flattener.presets.save", json!({"name": "Mine", "balance": 0})).unwrap();
app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "flattenerPreset": "Mine"})).unwrap();
let mut f = Frames::new();
let (node, _) = f.control(&mut app, "Custom…", Role::Button);
f.run(
&mut app,
vec![egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Focus, target_node: node, target_tree: TreeId::ROOT, data: None })],
);
let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
f.run(&mut app, vec![enter(true)]);
f.run(&mut app, vec![enter(false)]);
assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND), "the custom options stay open");
let parent = super::parent(app.ui.dialog.as_ref().unwrap()).unwrap();
assert_eq!(parent.str("flattenerPreset"), "Mine", "EPS Options keep their preset");
}
/// With a value out of range, the editor shows the values entered, and changing a switch keeps
/// them, so OK still refuses the bad value.
#[test]
fn a_switch_changed_beside_a_bad_value_keeps_the_values_entered() {
let (mut app, _) = app(1);
app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap();
frame(&mut app);
open_custom(&mut app);
set(&mut app, "balance", json!(20));
set(&mut app, "gradientPpi", json!(9000));
set(&mut app, "lineArtPpi", json!("many"));
let mut f = Frames::new();
let (_, at) = f.control(&mut app, "Convert All Text to Outlines", egui::accesskit::Role::CheckBox);
let before = app.ui.dialog.as_ref().unwrap().bool("textToOutlines");
f.click(&mut app, at);
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!(d.bool("textToOutlines"), !before, "the switch changes");
assert_eq!((d.f64("balance", 0.0), d.f64("gradientPpi", 0.0)), (20.0, 9000.0), "the other values stay as entered");
assert_eq!(d.fields["lineArtPpi"], json!("many"), "a value of the wrong type stays to be refused");
assert!(confirm(&mut app).is_err());
set(&mut app, "lineArtPpi", json!(300));
assert!(confirm(&mut app).unwrap_err().contains("resolutions"));
}
/// A value of the wrong type shows blank, and typing the default preset's value into its field
/// replaces it, so OK takes the options.
#[test]
fn the_default_value_typed_over_a_value_of_the_wrong_type_replaces_it() {
let (mut app, _) = app(1);
app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap();
frame(&mut app);
open_custom(&mut app);
set(&mut app, "lineArtPpi", json!("many"));
let default = vectorcraft_engine::cmd::FlattenOptions::default().line_art_ppi;
let mut f = Frames::new();
f.type_into(&mut app, "Line Art and Text Resolution:", &default.to_string());
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["lineArtPpi"], json!(default));
confirm(&mut app).unwrap();
assert_eq!(kind(&app), Some("epsOptions"));
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"]["lineArtPpi"].as_f64(), Some(default));
}
#[test]
fn the_eps_options_dialog_needs_a_document() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
+44 -2
View File
@@ -95,12 +95,19 @@ fn import_pdf_pages_as_links_opens_each_page_linked() {
let path = dir.join("three.pdf").to_string_lossy().into_owned();
std::fs::write(&path, three_pages()).unwrap();
let mut app = app();
// All pages: checked without a click.
io::open_bytes(&mut app, &path, &three_pages(), Some(path.clone())).unwrap();
assert_eq!(field(&app, "linkPages"), false, "off by default");
frame(&mut app);
set(&mut app, "linkPages", json!(true));
confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(artboard_widths(&app), [100.0, 200.0, 300.0]);
assert_eq!(placed_pages(&app), [true, true, true], "All opens the pages linked");
// A range: cleared, and checked by hand it opens the range linked.
io::open_bytes(&mut app, &path, &three_pages(), Some(path.clone())).unwrap();
set(&mut app, "allPages", json!(false));
set(&mut app, "range", json!("1, 3"));
assert!(!import_pdf::links_on(app.ui.dialog.as_ref().unwrap()), "Range: cleared");
set(&mut app, "linkPages", json!(true));
frame(&mut app);
confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
@@ -124,6 +131,41 @@ fn import_pdf_pages_as_links_opens_each_page_linked() {
assert_eq!(placed_pages(&app), [false, false]);
}
/// Picking All checks Import PDF pages as links and picking Range clears it. A click on the box
/// stands until the other one is picked; picking the one already picked or editing the range keeps
/// it. `ui.dialog.set` picks the way the buttons do.
#[test]
fn picking_all_or_a_range_sets_the_links_default() {
let mut app = app();
io::open_bytes(&mut app, "three.pdf", &three_pages(), Some("/tmp/three.pdf".into())).unwrap();
let pick = |app: &mut VectorcraftApp, k: &str, v: serde_json::Value| set_field(app.ui.dialog.as_mut().unwrap(), k.into(), v);
let on = |app: &VectorcraftApp| import_pdf::links_on(app.ui.dialog.as_ref().unwrap());
assert!(on(&app), "All: checked");
pick(&mut app, "allPages", json!(false));
assert!(!on(&app), "Range: cleared");
pick(&mut app, "linkPages", json!(true));
pick(&mut app, "allPages", json!(false));
pick(&mut app, "range", json!("1-2"));
frame(&mut app);
assert!(on(&app), "checked by hand, picking Range again and editing the range keep it");
pick(&mut app, "allPages", json!(true));
assert!(on(&app), "All: checked");
pick(&mut app, "linkPages", json!(false));
pick(&mut app, "allPages", json!(true));
frame(&mut app);
assert!(!on(&app), "cleared by hand, picking All again keeps it");
pick(&mut app, "allPages", json!(false));
pick(&mut app, "allPages", json!(true));
assert!(on(&app), "All picked after Range: checked again");
// A file `linkPages` does not take (one over its size limit) leaves the box clear.
assert_eq!(field(&app, "__linkable"), true);
set(&mut app, "__linkable", json!(false));
assert!(!on(&app), "a file linkPages does not take");
// A file given without its path can't link its pages: the box stays clear.
io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap();
assert!(!on(&app));
}
#[test]
fn single_page_pdfs_open_directly() {
let mut app = app();
@@ -678,6 +678,14 @@ fn simplify_dialog_preview_counts_and_cancel_restore_the_original() {
let texts = frame(&ctx, &mut app, vec![]);
let preview = texts.iter().find(|(t, _)| t == "Preview").map(|(_, r)| *r).expect("a Preview checkbox");
assert!(texts.iter().any(|(t, _)| t == "Anchor Points: 20 → 2"), "the reduction is visible: {texts:?}");
// In French the label ends in a no-break space and a colon (#7991).
let fr = crate::i18n::Lang::from_code("fr").unwrap();
crate::i18n::set_current(fr);
let french = frame(&ctx, &mut app, vec![]);
crate::i18n::set_current(crate::i18n::Lang::EN);
let want = format!("{}\u{a0}: 20 → 2", crate::i18n::tr(fr, "Anchor Points"));
assert!(french.iter().any(|(t, _)| *t == want), "{want:?} in {french:?}");
frame(&ctx, &mut app, vec![]);
assert!(app.session.in_interaction());
assert!(app.session.doc().unwrap().selection.anchors.is_empty());
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len);
+6 -2
View File
@@ -428,13 +428,17 @@ fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId
egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None })
}
/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out.
/// Type `typed` into Scale W, which shows `shown` (the leftmost field that does, before H), and Tab out.
fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) {
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
screen.run(app, vec![]);
let out = screen.run(app, vec![]);
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown)));
// W is left of H on their row (the tree lists its nodes in no particular order).
let w = nodes
.iter()
.filter(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown)))
.min_by(|(_, a), (_, b)| a.bounds().map_or(f64::MAX, |r| r.x0).total_cmp(&b.bounds().map_or(f64::MAX, |r| r.x0)));
screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]);
screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]);
screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]);
@@ -0,0 +1,54 @@
use serde_json::json;
use vectorcraft_engine::cmd::fileio;
use super::tests_export::{app, frame, kind};
use super::{confirm, png_options};
#[test]
fn raster_options_preserve_supplied_values_through_the_png_command() {
let (mut app, written) = app(1);
app.run("file.export.png", json!({"ppi": 300, "background": "#204080", "antiAlias": "type", "interlaced": true})).unwrap();
assert_eq!(kind(&app), Some("pngOptions"));
let fields = &app.ui.dialog.as_ref().unwrap().fields;
assert_eq!(fields["ppi"], 300);
assert_eq!(fields["background"], "#204080");
assert_eq!(fields["antiAlias"], "type");
assert_eq!(fields["interlaced"], true);
frame(&mut app);
confirm(&mut app).unwrap();
{
let output = written.borrow();
assert_eq!(output.len(), 1);
let png = &output[0].1;
assert_eq!(png[28], 1);
let physical = png.windows(4).position(|w| w == b"pHYs").unwrap();
assert_eq!(&png[physical + 4..physical + 8], ((300.0f64 / 0.0254).round() as u32).to_be_bytes());
let decoded = craft_image_codecs::decode(png).unwrap();
assert_eq!(decoded.dimensions(), (250, 167));
assert_eq!(&decoded.to_rgba8()[..4], &[0x20, 0x40, 0x80, 255]);
}
png_options::open(&mut app, fileio::format("jpg").unwrap(), json!({"format": "jpg", "path": "/out/supplied.jpg", "ppi": 144, "quality": 40}));
let fields = &app.ui.dialog.as_ref().unwrap().fields;
assert_eq!(fields["quality"], 40);
assert_eq!(fields["ppi"], 144);
assert_eq!(fields["background"], "white");
frame(&mut app);
confirm(&mut app).unwrap();
assert_eq!(written.borrow().len(), 2);
for omitted in [json!({}), json!({"ppi": null, "background": null, "antiAlias": null, "interlaced": null})] {
app.run("file.export.png", omitted).unwrap();
let fields = &app.ui.dialog.as_ref().unwrap().fields;
assert_eq!(fields["ppi"], 72);
assert_eq!(fields["background"], "transparent");
assert_eq!(fields["antiAlias"], "art");
assert_eq!(fields["interlaced"], false);
app.ui.dialog = None;
}
app.run("file.export.png", json!({"ppi": 0})).unwrap();
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["ppi"], 0);
assert!(confirm(&mut app).unwrap_err().contains("ppi must be a positive number"));
assert_eq!(written.borrow().len(), 2);
}
@@ -339,6 +339,20 @@ fn rectangular_grid_failed_creation_does_not_save_counts() {
assert_eq!(app.session.doc().unwrap().history.undo.len(), before.undo);
}
/// Tool Options with a width the tool refuses is an error that keeps the dialog open and sets
/// nothing.
#[test]
fn rectangular_grid_tool_options_with_a_refused_width_stay_open() {
let mut app = app();
let before = app.session.tool_options_of(KIND);
super::shapes::open_options(&mut app, KIND).unwrap();
set(&mut app, "width", json!(0));
let e = super::confirm(&mut app).unwrap_err();
assert!(e.contains("`width`"), "{e}");
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND));
assert_eq!(app.session.tool_options_of(KIND), before);
}
/// #1377: the dialog shows the tool's stored skews (sliders under their divider counts) and
/// switches; OK draws with them and stores them, and the next drag uses them too.
#[test]
@@ -727,6 +727,312 @@ fn colour_table_buttons_edit_the_lists() {
assert_eq!(d.fields["colorTable"], json!({"locked": [], "webShift": ["#123456"], "sort": "hue"}));
}
/// A click selects one color, a Shift-click the range from the last one clicked, a Ctrl-click
/// (Command-click) adds or removes one; Delete Color deletes the whole selection in one edit,
/// takes it out of the other lists, fixes the palette and refuses to delete every color.
#[test]
fn colour_table_selection_and_delete_color() {
let mut d = Dialog::new(save_for_web::KIND, json!({}));
let order: Vec<String> = ["#000000", "#111111", "#222222", "#333333"].map(String::from).to_vec();
let sel = |d: &Dialog| save_for_web::selection(d);
assert!(sel(&d).is_empty());
save_for_web::pick(&mut d, &order, "#111111", false, false);
assert_eq!(sel(&d), ["#111111"]);
save_for_web::pick(&mut d, &order, "#333333", true, false);
assert_eq!((sel(&d), d.str("__color")), (vec!["#111111".to_string(), "#222222".into(), "#333333".into()], "#111111".into()));
save_for_web::pick(&mut d, &order, "#222222", false, true);
assert_eq!(sel(&d), ["#111111", "#333333"]);
save_for_web::pick(&mut d, &order, "#000000", false, true);
assert_eq!((sel(&d), d.str("__color")), (vec!["#111111".to_string(), "#333333".into(), "#000000".into()], "#000000".into()));
save_for_web::pick(&mut d, &order, "#000000", false, true);
assert_eq!((sel(&d), d.str("__color")), (vec!["#111111".to_string(), "#333333".into()], "#333333".into()));
// A Shift-click back from the anchor.
save_for_web::pick(&mut d, &order, "#222222", false, false);
save_for_web::pick(&mut d, &order, "#000000", true, false);
assert_eq!(sel(&d), ["#000000", "#111111", "#222222"]);
// `__color` alone (an agent's selection) is the selection too.
d.fields.remove("__colors");
d.fields.insert("__color".into(), json!("#222222"));
assert_eq!(sel(&d), ["#222222"]);
save_for_web::toggle(&mut d, "locked", "#222222", true);
save_for_web::toggle(&mut d, "locked", "#000000", true);
save_for_web::toggle(&mut d, "webShift", "#333333", true);
save_for_web::pick(&mut d, &order, "#333333", false, true);
save_for_web::delete_colors(&mut d, &order).unwrap();
assert_eq!(d.fields["colorTable"], json!({"locked": ["#000000"], "webShift": [], "customPalette": order, "deleted": ["#222222", "#333333"]}));
assert!(!d.fields.contains_key("__colors") && !d.fields.contains_key("__color") && sel(&d).is_empty());
// Nothing selected: nothing deleted.
let before = d.fields.clone();
save_for_web::delete_colors(&mut d, &order).unwrap();
assert_eq!(d.fields, before);
// The colors left can't all go: refused, nothing changed.
save_for_web::pick(&mut d, &order, "#000000", false, false);
save_for_web::pick(&mut d, &order, "#111111", false, true);
let before = d.fields.clone();
assert_eq!(save_for_web::delete_colors(&mut d, &order), Err(vectorcraft_engine::cmd::webexport::KEEP_ONE.to_string()));
assert_eq!(d.fields, before);
// Nor can the last color that is not mapped to transparent.
save_for_web::toggle(&mut d, "transparent", "#111111", true);
save_for_web::pick(&mut d, &order, "#000000", false, false);
let before = d.fields.clone();
assert_eq!(save_for_web::delete_colors(&mut d, &order), Err(vectorcraft_engine::cmd::webexport::KEEP_ONE.to_string()));
assert_eq!(d.fields, before);
// Restore Generated Table.
save_for_web::restore_table(&mut d);
assert_eq!((&d.fields["colorTable"]["deleted"], &d.fields["colorTable"]["customPalette"]), (&json!([]), &json!([])));
}
/// Delete Color takes only selected colors the table shows: a selection the table no longer holds
/// (after a change of reduction or color count, or set through `ui.dialog.set`) deletes nothing,
/// fixes no palette and is cleared, and a selection partly in the table deletes only what it shows.
#[test]
fn delete_color_skips_selected_colors_the_table_does_not_show() {
let mut d = Dialog::new(save_for_web::KIND, json!({}));
let shown: Vec<String> = ["#000000", "#111111"].map(String::from).to_vec();
let table = |d: &Dialog, key: &str| d.fields.get("colorTable").and_then(|t| t.get(key)).cloned();
d.fields.insert("__colors".into(), json!(["#ABCDEF"]));
d.fields.insert("__color".into(), json!("#abcdef"));
assert!(save_for_web::selected_in(&d, &shown).is_empty());
save_for_web::delete_colors(&mut d, &shown).unwrap();
assert_eq!((table(&d, "customPalette"), table(&d, "deleted")), (None, None));
assert!(!d.fields.contains_key("__colors") && !d.fields.contains_key("__color"));
d.fields.insert("__colors".into(), json!(["#abcdef", "#111111"]));
assert_eq!(save_for_web::selected_in(&d, &shown), ["#111111"]);
save_for_web::delete_colors(&mut d, &shown).unwrap();
assert_eq!((table(&d, "customPalette"), table(&d, "deleted")), (Some(json!(shown)), Some(json!(["#111111"]))));
}
/// A shift by hand replaces a web shift and selects the color; a shift to the color itself takes it
/// away; Unshift All Colors clears both kinds; Delete Color takes a deleted color's shift away.
#[test]
fn colour_table_shift_unshift_and_unshift_all() {
let mut d = Dialog::new(save_for_web::KIND, json!({}));
save_for_web::toggle(&mut d, "webShift", "#123456", true);
save_for_web::shift_color(&mut d, "#123456", "#FF8800");
assert_eq!(d.fields["colorTable"], json!({"webShift": [], "shifted": {"#123456": "#ff8800"}}));
assert_eq!(save_for_web::selection(&d), ["#123456"]);
// Not a color: nothing changes.
let before = d.fields.clone();
save_for_web::shift_color(&mut d, "nope", "#000000");
save_for_web::shift_color(&mut d, "#123456", "nope");
assert_eq!(d.fields, before);
save_for_web::shift_color(&mut d, "#ABCDEF", "#00ff00");
save_for_web::shift_color(&mut d, "#123456", "#123456");
assert_eq!(d.fields["colorTable"]["shifted"], json!({"#abcdef": "#00ff00"}));
save_for_web::toggle(&mut d, "webShift", "#222222", true);
save_for_web::unshift_all_colors(&mut d);
assert_eq!((&d.fields["colorTable"]["shifted"], &d.fields["colorTable"]["webShift"]), (&json!({}), &json!([])));
let order: Vec<String> = ["#000000", "#222222"].map(String::from).to_vec();
save_for_web::shift_color(&mut d, "#222222", "#ffffff");
save_for_web::delete_colors(&mut d, &order).unwrap();
assert_eq!((&d.fields["colorTable"]["shifted"], &d.fields["colorTable"]["deleted"]), (&json!({}), &json!(["#222222"])));
}
/// One frame of `app` in `ctx`, 50 ms after the last.
fn tick(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) {
let time = ctx.input(|i| i.time) + 0.05;
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)));
let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| show(app, ui.ctx()));
out.textures_delta.clear();
}
/// Double-click the color table's swatch of the source color `source`.
fn double_click_swatch(app: &mut VectorcraftApp, ctx: &egui::Context, source: &str) {
for _ in 0..3 {
tick(app, ctx, vec![]);
}
let pos = ctx.read_response(save_for_web::swatch_id(source)).unwrap_or_else(|| panic!("no swatch for {source}")).rect.center();
let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
tick(app, ctx, vec![egui::Event::PointerMoved(pos), button(true)]);
tick(app, ctx, vec![button(false)]);
tick(app, ctx, vec![button(true)]);
tick(app, ctx, vec![button(false)]);
tick(app, ctx, vec![]);
}
/// The color the open Color Picker shows.
fn picker_color(app: &VectorcraftApp) -> Option<String> {
let d = app.ui.dialog.as_ref()?;
assert_eq!(d.kind, "colorPicker", "the Color Picker is open");
d.fields.get("color").and_then(vectorcraft_engine::cmd::color_value).map(|c| c.to_hex())
}
/// A double-click on a swatch opens the Color Picker on its color. Cancel changes nothing; OK
/// shifts the color in the table and the saved file. A double-click on a shifted swatch opens the
/// picker on the source color, and Web Shift replaces the shift by hand.
#[test]
fn double_clicking_a_swatch_shifts_its_color() {
let dir = vectorcraft_testkit::temp_dir("sfw-shift-color");
let (mut app, _) = app(&dir, false);
app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap();
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
app.run("file.saveForWeb", json!({})).unwrap();
for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] {
set(&mut app, k, v);
}
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let shifted = |app: &VectorcraftApp| app.ui.dialog.as_ref().map(|d| d.fields["colorTable"]["shifted"].clone());
double_click_swatch(&mut app, &ctx, "#0000ff");
assert_eq!(picker_color(&app).as_deref(), Some("#0000ff"));
crate::dialogs::cancel(&mut app);
tick(&mut app, &ctx, vec![]);
assert_eq!((kind(&app), shifted(&app)), (Some(save_for_web::KIND), Some(json!({}))), "Cancel shifts nothing");
double_click_swatch(&mut app, &ctx, "#0000ff");
set(&mut app, "color", json!("#00ff00"));
confirm(&mut app).unwrap();
tick(&mut app, &ctx, vec![]);
assert_eq!((kind(&app), shifted(&app)), (Some(save_for_web::KIND), Some(json!({"#0000ff": "#00ff00"}))), "OK shifts the color");
// The shifted swatch opens on its source color.
double_click_swatch(&mut app, &ctx, "#0000ff");
assert_eq!(picker_color(&app).as_deref(), Some("#0000ff"));
crate::dialogs::cancel(&mut app);
// Web Shift replaces the shift by hand.
click_text(&mut app, "Web Shift");
let t = app.ui.dialog.as_ref().unwrap().fields["colorTable"].clone();
assert_eq!((&t["shifted"], &t["webShift"]), (&json!({}), &json!(["#0000ff"])));
// Shifted again, the color reaches the saved file and is remembered.
double_click_swatch(&mut app, &ctx, "#0000ff");
set(&mut app, "color", json!("#00ff00"));
confirm(&mut app).unwrap();
tick(&mut app, &ctx, vec![]);
let r = confirm(&mut app).unwrap();
let image = image::open(r["path"].as_str().unwrap()).unwrap().to_rgba8();
assert_eq!((image.get_pixel(50, 20).0, image.get_pixel(20, 14).0), ([0, 255, 0, 255], [204, 51, 0, 255]));
let remembered = app.session.last_web_settings().color_table;
assert_eq!((remembered.shifted.get("#0000ff").map(String::as_str), remembered.web_shift.len()), (Some("#00ff00"), 0));
}
/// `ui.dialog.set` accepts `__editColor`, and the next frame opens the Color Picker on that color,
/// whose OK shifts it.
#[test]
fn dialog_set_edit_color_opens_the_color_picker() {
let dir = vectorcraft_testkit::temp_dir("sfw-edit-color-set");
let (mut app, _) = app(&dir, false);
app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap();
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
app.run("file.saveForWeb", json!({})).unwrap();
set(&mut app, "format", json!("gif"));
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": "__editColor", "value": "#0000ff"}));
let crate::control::Outcome::Done(r) = crate::control::handle(&mut app, &ctx, &req) else { panic!("not done") };
assert_eq!(r["ok"], true, "{r}");
tick(&mut app, &ctx, vec![]);
assert_eq!(picker_color(&app).as_deref(), Some("#0000ff"));
set(&mut app, "color", json!("#00ff00"));
confirm(&mut app).unwrap();
tick(&mut app, &ctx, vec![]);
let shifted = app.ui.dialog.as_ref().map(|d| d.fields["colorTable"]["shifted"].clone());
assert_eq!((kind(&app), shifted), (Some(save_for_web::KIND), Some(json!({"#0000ff": "#00ff00"}))));
}
/// Lock, Transparent and Web Shift are off while the selected color (`__color`) is one the table
/// no longer shows, so a click adds it to no list; with a color the table shows, Lock locks it.
#[test]
fn table_buttons_skip_a_selected_color_the_table_does_not_show() {
let dir = vectorcraft_testkit::temp_dir("sfw-stale-anchor");
let (mut app, _) = app(&dir, false);
app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap();
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
app.run("file.saveForWeb", json!({})).unwrap();
for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] {
set(&mut app, k, v);
}
let table = |app: &VectorcraftApp| app.ui.dialog.as_ref().and_then(|d| d.fields.get("colorTable").cloned()).unwrap_or_default();
let has = |app: &VectorcraftApp, list: &str, c: &str| table(app)[list].as_array().is_some_and(|l| l.iter().any(|v| v == c));
set(&mut app, "__color", json!("#abcdef"));
for label in ["Lock", "Transparent", "Web Shift"] {
click_text(&mut app, label);
}
for list in ["locked", "transparent", "webShift"] {
assert!(!has(&app, list, "#abcdef"), "{list}: {}", table(&app));
}
set(&mut app, "__color", json!("#0000ff"));
click_text(&mut app, "Lock");
assert!(has(&app, "locked", "#0000ff"), "{}", table(&app));
}
/// Click the dialog's text `label` with the pointer (frames a quarter second apart).
fn click_text(app: &mut VectorcraftApp, label: &str) {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
let time = ctx.input(|i| i.time) + 0.25;
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)));
let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| show(app, ui.ctx()));
out.textures_delta.clear();
fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::Rect)>) {
match s {
egui::Shape::Text(t) => v.push((t.galley.text().to_string(), egui::Rect::from_min_size(t.pos, t.galley.size()))),
egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)),
_ => {}
}
}
let mut v = vec![];
out.shapes.iter().for_each(|c| walk(&c.shape, &mut v));
v
};
frame(app, vec![]);
let texts = frame(app, vec![]);
let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}"));
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(app, vec![egui::Event::PointerMoved(at)]);
frame(app, vec![press(true)]);
frame(app, vec![press(false)]);
}
/// A Custom table whose preview fails (only a color mapped to transparent left) still offers
/// Restore Generated Table, which brings the preview back.
#[test]
fn restore_generated_table_shows_when_the_preview_fails() {
let dir = vectorcraft_testkit::temp_dir("sfw-restore-table");
let (mut app, _) = app(&dir, false);
app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap();
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
app.run("file.saveForWeb", json!({})).unwrap();
let table = json!({"deleted": ["#cc3300"], "customPalette": ["#cc3300", "#0000ff"], "transparent": ["#0000ff"]});
for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none")), ("colorTable", table)] {
set(&mut app, k, v);
}
let p = json!({"format": "gif", "antiAlias": "none", "colorTable": app.ui.dialog.as_ref().unwrap().fields["colorTable"].clone()});
assert!(app.session.execute("document.exportForWeb.preview", &p).is_err(), "the preview fails");
click_text(&mut app, "Restore Generated Table");
let t = &app.ui.dialog.as_ref().unwrap().fields["colorTable"];
assert_eq!((&t["deleted"], &t["customPalette"]), (&json!([]), &json!([])));
}
/// The saved file lacks the deleted color, whose pixels take the color left; the edit is
/// remembered, reopens with the dialog and stays through a format change.
#[test]
fn delete_color_reaches_the_saved_file_and_is_remembered() {
let dir = vectorcraft_testkit::temp_dir("sfw-delete-color");
let (mut app, _) = app(&dir, false);
app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap();
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
app.run("file.saveForWeb", json!({})).unwrap();
for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] {
set(&mut app, k, v);
}
frame(&mut app);
set(&mut app, "__colors", json!(["#cc3300"]));
save_for_web::delete_colors(app.ui.dialog.as_mut().unwrap(), &["#cc3300".into(), "#0000ff".into()]).unwrap();
frame(&mut app);
for format in ["jpg", "gif"] {
set(&mut app, "format", json!(format));
frame(&mut app);
}
let r = confirm(&mut app).unwrap();
let image = image::open(r["path"].as_str().unwrap()).unwrap().to_rgba8();
assert_eq!((image.get_pixel(20, 14).0, image.get_pixel(50, 20).0), ([0, 0, 255, 255], [0, 0, 255, 255]));
assert_eq!(app.session.last_web_settings().color_table.deleted, ["#cc3300"]);
app.run("file.saveForWeb", json!({})).unwrap();
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["colorTable"]["deleted"], json!(["#cc3300"]));
frame(&mut app);
}
#[test]
fn optimize_to_file_size_takes_the_settings_that_fit() {
let dir = vectorcraft_testkit::temp_dir("sfw-optimize");
+449
View File
@@ -0,0 +1,449 @@
//! Dialogs in a short or narrow window: a dialog too large for the window scrolls instead of
//! running off the screen. Every scroll bar here is drawn at rest (a solid bar style), so the tests
//! can find it.
use egui::{Pos2, Rect, Shape, vec2};
use serde_json::json;
use vectorcraft_engine::Session;
use super::*;
type Open = fn(&mut VectorcraftApp);
/// What a dialog drew: the shapes, the dialog window's rectangle, and how it scrolls
/// ([`modal::scrolling`]).
struct Shown {
shapes: Vec<egui::epaint::ClippedShape>,
window: Rect,
body: Option<f32>,
whole: [bool; 2],
}
/// Open a dialog with `open` in a `size` window, with the pointer in the window's corner (away
/// from the dialog), and draw it until it settles. With `scroll`, then scroll far down and right
/// near the dialog's right edge (on the bar of a window that scrolls as a whole, beside the lists
/// inside it) and draw it until it settles again.
fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
crate::theme::apply(&ctx, Default::default());
ctx.global_style_mut(|s| s.spacing.scroll = egui::style::ScrollStyle::solid());
open(&mut app);
let screen = Rect::from_min_size(Pos2::ZERO, size);
let window = |ctx: &egui::Context| {
ctx.memory(|m| {
m.areas()
.visible_layer_ids()
.into_iter()
.filter(|l| l.order == egui::Order::Foreground)
.filter_map(|l| Some((l.id, m.area_rect(l.id)?)))
.max_by(|a, b| a.1.area().total_cmp(&b.1.area()))
})
.unwrap_or((egui::Id::NULL, Rect::NOTHING))
};
let mut time = 0.0;
let mut frames = |app: &mut VectorcraftApp, first: Vec<egui::Event>| {
let mut first = Some(first);
let mut shapes = vec![];
for _ in 0..12 {
time += 1.0;
let input =
egui::RawInput { screen_rect: Some(screen), events: first.take().unwrap_or_default(), time: Some(time), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx()));
out.textures_delta.clear();
shapes = std::mem::take(&mut out.shapes);
}
shapes
};
let mut shapes = frames(&mut app, vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))]);
if scroll {
let wheel = egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: vec2(-5000.0, -5000.0),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Unknown,
modifiers: egui::Modifiers::NONE,
};
let (id, w) = window(&ctx);
let (body, whole) = modal::scrolling(&ctx, id);
let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body, whole };
// On the window's upright bar, else on its body's bar, else on its sideways bar, else at
// its right edge.
let sideways = bars(&before, true, true).into_iter().find(|r| r.width() >= 0.5 * w.width());
let at = whole_bar(&before).or(body_bar(&before)).or(sideways).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center());
shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel]);
}
let (id, window) = window(&ctx);
let (body, whole) = modal::scrolling(&ctx, id);
Shown { shapes, window, body, whole }
}
/// Filled bars 4 to 10 pt across and longer than 12 pt (scroll bars and their handles), upright or
/// (`sideways`) flat, inside the dialog window; with `seen`, only those inside their clip.
fn bars(shown: &Shown, sideways: bool, seen: bool) -> Vec<Rect> {
fn walk(s: &Shape, clip: Rect, sideways: bool, seen: bool, out: &mut Vec<Rect>) {
match s {
Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT => {
let (across, along) = if sideways { (r.rect.height(), r.rect.width()) } else { (r.rect.width(), r.rect.height()) };
if (4.0..=10.0).contains(&across) && along > 12.0 && (!seen || clip.contains_rect(r.rect)) {
out.push(r.rect);
}
}
Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, sideways, seen, out)),
_ => {}
}
}
let mut out = vec![];
shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, sideways, seen, &mut out));
out.retain(|r| shown.window.expand(0.5).contains_rect(*r));
out
}
/// The bar of a shared dialog's scrolling body: the rightmost upright bar as tall as the body is
/// drawn (a list inside the body draws its bar further left).
fn body_bar(shown: &Shown) -> Option<Rect> {
let view = shown.body?;
bars(shown, false, true).into_iter().filter(|r| (r.height() - view).abs() <= 1.0).max_by(|a, b| a.right().total_cmp(&b.right()))
}
/// The bar of a window that scrolls as a whole: an upright bar at the window's right edge that
/// runs most of the window's height (lists inside it are shorter).
fn whole_bar(shown: &Shown) -> Option<Rect> {
let w = shown.window;
bars(shown, false, true)
.into_iter()
.filter(|r| r.right() >= w.right() - 24.0 && r.height() >= 0.8 * w.height())
.max_by(|a, b| a.height().total_cmp(&b.height()))
}
/// The texts `labels` the dialog drew, each with whether it can be seen (inside the screen and
/// its clip).
fn buttons(shown: &Shown, screen: Rect, labels: &[&str]) -> Vec<(String, bool)> {
texts(shown)
.into_iter()
.filter(|(s, ..)| labels.contains(&s.as_str()))
.map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r)))
.collect()
}
#[test]
fn a_dialog_taller_than_the_window_scrolls_its_body_and_keeps_its_buttons_in_view() {
let opens: [(&str, Open, &[&str]); 7] = [
("SVG Options", |app| svg_options::open(app, svg_options::Mode::Export, Some("/tmp/x.svg")), &["OK", "Cancel"]),
("EPS Options", |app| eps_options::open(app, &json!({"format": "eps", "path": "/tmp/x.eps"})), &["Export", "Cancel"]),
("DXF Options", |app| dxf_options::open(app, &json!({"format": "dxf", "path": "/tmp/x.dxf"})), &["Export", "Cancel"]),
(
"Save PDF",
|app| {
save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap();
},
&["Cancel"],
),
(
"Save for Web",
|app| {
save_for_web::open(app).unwrap();
},
&["Cancel", "Done"],
),
("Export for Screens", export_for_screens::open, &["Cancel"]),
(
"Print",
|app| {
print::open(app).unwrap();
},
&["Cancel", "Done"],
),
];
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 480.0));
for (name, open, labels) in opens {
let tall = show_in(open, vec2(1280.0, 900.0), false);
assert!(tall.window.height() > screen.height(), "{name}: the dialog is taller than the short window ({:?})", tall.window);
assert_eq!((tall.body, tall.whole), (None, [false; 2]), "{name}: in a tall window nothing scrolls");
let shown = show_in(open, screen.size(), false);
assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window);
let found = buttons(&shown, screen, labels);
assert_eq!(found.len(), labels.len(), "{name}: {found:?}");
assert!(found.iter().all(|(_, seen)| *seen), "{name}: the buttons stay in view: {found:?}");
assert_eq!(shown.whole, [false; 2], "{name}: the window does not scroll as a whole");
let bar = body_bar(&shown);
assert!(bar.is_some(), "{name}: the body scrolls ({:?}) and its bar is drawn: {:?}", shown.body, bars(&shown, false, true));
}
}
#[test]
fn a_list_in_a_scrolling_body_is_no_taller_than_the_body() {
// The settings of Save for Web and the sections of Print and Save PDF scroll in lists of their
// own; in a short window those lists are no taller than the body shows, so each list and its
// bar can be scrolled into view whole.
let opens: [(&str, Open); 3] = [
("Save for Web", |app| {
save_for_web::open(app).unwrap();
}),
("Print", |app| {
print::open(app).unwrap();
if let Some(d) = app.ui.dialog.as_mut() {
d.fields.insert("__section".into(), json!("Marks and Bleed"));
}
}),
("Save PDF", |app| {
save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap();
if let Some(d) = app.ui.dialog.as_mut() {
d.fields.insert("__section".into(), json!("Marks and Bleeds"));
}
}),
];
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 400.0));
let mut wrong = vec![];
for (name, open) in opens {
let shown = show_in(open, screen.size(), false);
let Some(body) = body_bar(&shown) else {
wrong.push(format!("{name}: the body does not scroll ({:?}): {:?}", shown.body, bars(&shown, false, false)));
continue;
};
// The tracks of the lists' bars, seen or not: left of the body's bar and inside the window
// (a list taller than the body runs past the window's bottom).
let lists: Vec<Rect> = bars(&shown, false, false).into_iter().filter(|r| r.right() < body.left()).collect();
let tallest = lists.iter().map(|r| r.height()).fold(0.0, f32::max);
if tallest == 0.0 || tallest > body.height() + 0.5 {
wrong.push(format!("{name}: no list bar no taller than the body ({}): {:?}", body.height(), bars(&shown, false, false)));
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
#[test]
fn save_for_web_in_the_smallest_window_keeps_its_settings_and_buttons_in_view() {
let open: Open = |app| {
save_for_web::open(app).unwrap();
};
// The app window's smallest size, 800 by 500 pixels, at a UI scale of 100%, 110% and 125%.
let mut wrong = vec![];
for size in [vec2(800.0, 500.0), vec2(727.0, 454.0), vec2(640.0, 400.0)] {
let screen = Rect::from_min_size(Pos2::ZERO, size);
let shown = show_in(open, size, false);
let labels = ["Format:", "Optimize to File Size…", "Cancel", "Done"];
let found = buttons(&shown, screen, &labels);
if !screen.contains_rect(shown.window) || found.len() != labels.len() || !found.iter().all(|(_, seen)| *seen) {
wrong.push(format!("{size:?}: the dialog ({:?}) leaves its settings and buttons in view: {found:?}", shown.window));
}
if body_bar(&shown).is_none() || shown.whole != [false; 2] {
wrong.push(format!("{size:?}: only the body scrolls ({:?}, {:?})", shown.body, shown.whole));
}
// The controls under the narrower panes stay in their column, left of the settings.
let controls = text_rects(&shown, "Preview in Browser").first().map(|r| r.right());
let settings = text_rects(&shown, "Format:").first().map(|r| r.left());
if !matches!((controls, settings), (Some(c), Some(s)) if c < s) {
wrong.push(format!("{size:?}: Preview in Browser ({controls:?}) is left of the settings ({settings:?})"));
}
// Preview in Browser is right of the download speed list or on a row below it, not over it.
let button = text_rects(&shown, "Preview in Browser").first().copied();
let speed = text_rects(&shown, "56.6 Kbps").first().copied();
if !matches!((button, speed), (Some(b), Some(s)) if b.left() > s.right() + 16.0 || b.top() > s.bottom() + 8.0) {
wrong.push(format!("{size:?}: Preview in Browser ({button:?}) clears the download speed list ({speed:?})"));
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// The rectangles of the texts `label` the dialog drew.
fn text_rects(shown: &Shown, label: &str) -> Vec<Rect> {
fn walk(s: &Shape, label: &str, out: &mut Vec<Rect>) {
match s {
Shape::Text(t) if t.galley.text() == label => out.push(t.visual_bounding_rect()),
Shape::Vec(v) => v.iter().for_each(|s| walk(s, label, out)),
_ => {}
}
}
let mut out = vec![];
shown.shapes.iter().for_each(|c| walk(&c.shape, label, &mut out));
out
}
#[test]
fn a_window_too_large_for_the_screen_scrolls_as_a_whole() {
let opens: [(&str, Open, &[&str]); 4] = [
("Preferences", |app| crate::prefs_dialog::open(app, None), &["OK", "Cancel"]),
("Keyboard Shortcuts", crate::shortcut_editor::open, &["OK", "Cancel"]),
("New Document", new_document::open, &["Create", "Close"]),
("Find Font", crate::find_font::open, &["Done"]),
];
// The app window's smallest size.
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
for (name, open, labels) in opens {
let tall = show_in(open, vec2(1280.0, 900.0), false);
assert!(
tall.window.height() > screen.height() || tall.window.width() > screen.width(),
"{name}: the dialog is larger than the small window ({:?})",
tall.window
);
assert_eq!(tall.whole, [false; 2], "{name}: in a large window the dialog does not scroll as a whole");
let shown = show_in(open, screen.size(), false);
assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window);
assert!(shown.whole[1], "{name}: the dialog scrolls as a whole");
assert!(whole_bar(&shown).is_some(), "{name}: the window's bar is drawn: {:?}", bars(&shown, false, true));
// The buttons can sit outside the part in view; each is in view at the top or scrolled to
// the end.
let scrolled = show_in(open, screen.size(), true);
let (top, end) = (buttons(&shown, screen, labels), buttons(&scrolled, screen, labels));
for label in labels {
let seen = |found: &[(String, bool)]| found.iter().any(|(s, seen)| s == label && *seen);
assert!(seen(&top) || seen(&end), "{name}: {label} can be scrolled into view: {top:?} {end:?}");
}
}
}
#[test]
fn keyboard_shortcuts_keeps_its_scroll_under_import_shortcut_set() {
// Scrolled down in the smallest window, Keyboard Shortcuts is where it was left when Import
// Shortcut Set, opened over it, is canceled; closed and opened again, it starts at its top.
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
crate::theme::apply(&ctx, Default::default());
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut time = 0.0;
// Draws 12 frames, the first with `events`; returns whether the heading can be seen.
let mut heading_seen = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
let mut events = Some(events);
let mut seen = false;
for _ in 0..12 {
time += 1.0;
let input =
egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(time), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx()));
out.textures_delta.clear();
let shown = Shown { shapes: out.shapes, window: screen, body: None, whole: [false; 2] };
seen = buttons(&shown, screen, &["Keyboard Shortcuts"]).iter().any(|(_, seen)| *seen);
}
seen
};
let wheel = |at: Pos2| {
let wheel = egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: vec2(0.0, -5000.0),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Unknown,
modifiers: egui::Modifiers::NONE,
};
vec![egui::Event::PointerMoved(at), wheel]
};
crate::shortcut_editor::open(&mut app);
assert!(heading_seen(&mut app, vec![]), "Keyboard Shortcuts opens at its top");
// On the window's bar, inside its 20 pt margin.
let window = ctx.memory(|m| m.area_rect(egui::Id::unique("dialog-shortcuts"))).unwrap_or(screen);
assert!(!heading_seen(&mut app, wheel(egui::pos2(window.right() - 23.0, window.center().y))), "the wheel scrolls the heading away");
let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n}\n";
crate::io::open_bytes(&mut app, "Keys.kys", kys.as_bytes(), None).unwrap();
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(shortcut_import::KIND));
heading_seen(&mut app, vec![]);
cancel(&mut app);
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "Cancel shows Keyboard Shortcuts again");
assert!(!heading_seen(&mut app, vec![]), "shown again, Keyboard Shortcuts is where it was scrolled to");
cancel(&mut app);
heading_seen(&mut app, vec![]);
crate::shortcut_editor::open(&mut app);
assert!(heading_seen(&mut app, vec![]), "opened again, Keyboard Shortcuts starts at its top");
}
/// Open Import Shortcut Set on a set of two shortcuts.
fn open_shortcut_import(app: &mut VectorcraftApp) {
let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n";
crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap();
}
#[test]
fn a_window_that_fits_itself_but_is_too_wide_scrolls_sideways() {
// Import Shortcut Set sizes its lists from the window's height and is about 780 pt wide. An
// 800 by 600 pixel window at a UI scale of 125% is 640 by 480 pt.
let wide = show_in(open_shortcut_import, vec2(1280.0, 900.0), false);
let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 480.0));
assert!(wide.window.width() > screen.width(), "Import Shortcut Set is wider than the window: {:?}", wide.window);
assert_eq!(wide.whole, [false; 2], "in a large window it does not scroll");
let shown = show_in(open_shortcut_import, screen.size(), false);
assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window);
assert_eq!(shown.whole, [true, false], "it scrolls sideways only");
let sideways: Vec<Rect> = bars(&shown, true, true).into_iter().filter(|r| r.width() >= 0.5 * shown.window.width()).collect();
assert!(!sideways.is_empty(), "its sideways bar is drawn: {:?}", bars(&shown, true, false));
}
#[test]
fn a_window_wider_than_the_screen_scrolls_sideways_to_its_right_edge() {
// In a window 70% as wide as the dialog, the dialog scrolls sideways, and scrolled to its right
// edge, the text drawn furthest right in a large window can be seen.
let opens: [(&str, Open); 3] = [
("Import Shortcut Set", open_shortcut_import),
("Keyboard Shortcuts", crate::shortcut_editor::open),
("Preferences", |app| crate::prefs_dialog::open(app, None)),
];
let mut wrong = vec![];
for (name, open) in opens {
let wide = show_in(open, vec2(1600.0, 1000.0), false);
let Some((right, _)) = texts(&wide)
.into_iter()
.filter(|(_, r, _)| wide.window.contains_rect(*r))
.map(|(s, r, _)| (s, r.right()))
.max_by(|a, b| a.1.total_cmp(&b.1))
else {
wrong.push(format!("{name}: no text in the large window"));
continue;
};
let screen = Rect::from_min_size(Pos2::ZERO, vec2((0.7 * wide.window.width()).round(), 1000.0));
let shown = show_in(open, screen.size(), false);
let scrolled = show_in(open, screen.size(), true);
// Within 1 pt: a text's drawn box can reach a fraction of a point past the content's edge.
let seen =
|shown: &Shown| texts(shown).iter().any(|(s, r, clip)| *s == right && screen.contains_rect(*r) && clip.expand(1.0).contains_rect(*r));
let sideways = bars(&shown, true, true).into_iter().any(|r| r.width() >= 0.5 * shown.window.width());
if !screen.contains_rect(shown.window) || !shown.whole[0] || !sideways || seen(&shown) || !seen(&scrolled) {
let at = |shown: &Shown| texts(shown).into_iter().filter(|(s, ..)| *s == right).collect::<Vec<_>>();
wrong.push(format!(
"{name} in {:?}: window {:?}, scrolls {:?}, sideways bar {sideways}, {right:?} seen at first {} {:?}, scrolled {} {:?}, bars {:?}",
screen.size(),
shown.window,
shown.whole,
seen(&shown),
at(&shown),
seen(&scrolled),
at(&scrolled),
bars(&shown, true, true)
));
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// Every text the dialog drew, with its rectangle and its clip.
fn texts(shown: &Shown) -> Vec<(String, Rect, Rect)> {
fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) {
match s {
Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)),
Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)),
_ => {}
}
}
let mut out = vec![];
shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut out));
out
}
#[test]
fn a_dialog_with_buttons_in_its_body_scrolls_them_with_the_body() {
// Check Spelling draws its buttons inside its body: in a window too short for it, the heading
// stays in view and the buttons scroll with the body.
let open: Open = |app| {
check_spelling::open(app).unwrap();
};
let tall = show_in(open, vec2(1280.0, 900.0), false);
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, (0.6 * tall.window.height()).round()));
let shown = show_in(open, screen.size(), false);
let scrolled = show_in(open, screen.size(), true);
let seen = |shown: &Shown, label: &str| buttons(shown, screen, &[label]).iter().any(|(_, seen)| *seen);
assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window);
assert!(body_bar(&shown).is_some() && shown.whole == [false; 2], "only the body scrolls ({:?}, {:?})", shown.body, shown.whole);
assert!(seen(&shown, "Check Spelling") && seen(&scrolled, "Check Spelling"), "the heading stays in view");
assert!(!seen(&shown, "Cancel") && seen(&scrolled, "Cancel"), "Cancel is out of view until the body is scrolled down");
}
+52 -3
View File
@@ -3,7 +3,7 @@
//! places it as area type (`file.place` with `text`) and remembers the options: the next text file
//! starts from them, and is placed with them when Show Import Options is off.
//!
//! Fields: `platform` (`windows` | `mac`), `characterSet` (`unicode` | `ansi`),
//! Fields: `platform` (`windows` | `mac`), `characterSet` (one of [`CHARACTER_SETS`]),
//! `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces` (on or off), `spaces` (how many
//! spaces make a tab, 2–100), and `__params` (the `file.place` params naming the file).
@@ -22,6 +22,21 @@ pub(super) const SPEC: DialogSpec =
/// The label column of the Encoding rows.
const LABEL: f32 = 104.0;
/// The Character Set choices: `file.place`'s `text.characterSet` value and the menu label.
const CHARACTER_SETS: [(&str, &str); 11] = [
("unicode", "Unicode"),
("ansi", "ANSI"),
("shiftJis", "Shift JIS"),
("gb2312", "GB2312"),
("chineseBig5", "Chinese Big 5"),
("cyrillic", "Cyrillic"),
("gb18030", "GB18030"),
("greek", "Greek"),
("turkish", "Turkish"),
("baltic", "Baltic"),
("centralEuropean", "Central European"),
];
/// Is the file `p` names (`path` or `name`) a text file?
pub fn is_text(p: &Value) -> bool {
let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default();
@@ -41,7 +56,8 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value {
"__params": params,
});
let last = &app.ui.text_import;
for (k, wanted) in [("platform", ["windows", "mac"]), ("characterSet", ["unicode", "ansi"])] {
let sets = CHARACTER_SETS.map(|(value, _)| value);
for (k, wanted) in [("platform", &["windows", "mac"][..]), ("characterSet", &sets[..])] {
if let Some(v) = last.get(k).and_then(Value::as_str).filter(|v| wanted.contains(v)) {
fields[k] = json!(v);
}
@@ -68,7 +84,7 @@ pub fn last_options(app: &VectorcraftApp) -> Value {
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
widgets::subheader(ui, tl!("Encoding"));
form::choice(ui, d, "platform", tl!("Platform:"), (LABEL, 180.0), &[("windows", "Windows"), ("mac", "Mac")]);
form::choice(ui, d, "characterSet", tl!("Character Set:"), (LABEL, 180.0), &[("unicode", "Unicode"), ("ansi", "ANSI")]);
form::choice(ui, d, "characterSet", tl!("Character Set:"), (LABEL, 180.0), &CHARACTER_SETS);
ui.add_space(10.0);
widgets::subheader(ui, tl!("Line Breaks"));
for (key, label) in
@@ -166,6 +182,39 @@ mod tests {
assert_eq!(st.history.undo.len(), 1);
}
/// Every character set is a choice: one confirmed last comes back on the next text file and
/// decodes it, an unknown remembered value falls back to Unicode, and with Show Import Options
/// off the remembered set is the one the file is placed with.
#[test]
fn a_remembered_character_set_comes_back_and_places_the_file() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let file = json!({"name": "notes.txt", "dataBase64": vectorcraft_format::base64_encode(&[0x93, 0xFA, 0x96, 0x7B])});
app.ui.text_import = json!({"characterSet": "shiftJis", "platform": "windows"});
app.run("file.place", file.clone()).unwrap();
assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("shiftJis"));
assert!(frame(&mut app).contains("Shift JIS"), "the remembered set is shown");
let r = super::super::confirm(&mut app).unwrap();
let st = app.session.doc().unwrap();
let n = st.doc.node(vectorcraft_engine::doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
let NodeKind::Text(t) = &n.kind else { panic!("type") };
assert_eq!(t.plain_text(), "日本");
assert_eq!(last_options(&app)["characterSet"], "shiftJis", "remembered for Show Import Options off");
app.ui.text_import = json!({"characterSet": "latin9"});
app.run("file.place", file).unwrap();
assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("unicode"));
let values: Vec<&str> = CHARACTER_SETS.iter().map(|(v, _)| *v).collect();
let labels: Vec<&str> = CHARACTER_SETS.iter().map(|(_, l)| *l).collect();
assert_eq!(
values,
["unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic", "centralEuropean"]
);
assert_eq!(
labels,
["Unicode", "ANSI", "Shift JIS", "GB2312", "Chinese Big 5", "Cyrillic", "GB18030", "Greek", "Turkish", "Baltic", "Central European"]
);
}
/// A text file dropped on a canvas is placed by the dialog's OK in the document it was dropped
/// on, even when another document became active meanwhile.
#[test]
@@ -1,6 +1,6 @@
//! The 3D and Materials panel's Materials tab: the document's Graphics (its symbols) as thumbnails,
//! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces, or
//! Revolve's side) with their face, position, size and turn. Picking a thumbnail maps that graphic
//! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces,
//! Extrude & Bevel's side, or Revolve's side) with their face, position, size and turn. Picking a thumbnail maps that graphic
//! onto the selected objects (`threeD.mapGraphic`); art dropped on the thumbnails becomes a graphic
//! (`threeD.addGraphic`). Editing a mapped graphic changes the effect's `graphics` parameter, which
//! the panel sends as it sends every other setting.
@@ -85,6 +85,15 @@ pub(crate) fn library(app: &VectorcraftApp, ui: &mut egui::Ui, apply: bool) -> O
action
}
/// The name of `face` in the interface.
fn face_label(face: PlanarFace) -> &'static str {
match face {
PlanarFace::Front => tl!("Front"),
PlanarFace::Back => tl!("Back"),
PlanarFace::Side => tl!("Side"),
}
}
/// The Materials tab of the 3D effect in `d.fields["__effect"]`: the Graphics list, then the
/// graphics mapped onto the object, the selected one with its settings. Edits `d.fields`; a click
/// in the list is left in [`ACTION`].
@@ -112,7 +121,7 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog)
}
let mut index = d.fields.get(SELECTED).and_then(Value::as_u64).map_or(0, |i| i as usize).min(list.len() - 1);
for (i, g) in list.iter().enumerate() {
let face = if g.face == PlanarFace::Back { tl!("Back") } else { tl!("Front") };
let face = face_label(g.face);
if ui.selectable_label(i == index, format!("{} · {face}", g.symbol)).clicked() {
index = i;
}
@@ -121,15 +130,18 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog)
ui.add_space(6.0);
let Some(g) = list.get(index).cloned() else { return };
let mut edited = g.clone();
// A plane has one face, and Revolve's graphics go on its side.
// A plane has one face, and Revolve's graphics go on its side. Extrude & Bevel's graphics go on
// its front or back cap, or on its side (its walls and bevels).
if effect != ROTATE && effect != REVOLVE {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
label(ui, tl!("Face"));
let labels = [tl!("Front"), tl!("Back")];
let at = usize::from(g.face == PlanarFace::Back);
if let Some(k) = widgets::dropdown(ui, "three-d-graphic-face", labels[at], &labels, 120.0) {
edited.face = PlanarFace::ALL[k.min(1)];
let labels = PlanarFace::ALL.map(face_label);
let at = PlanarFace::ALL.iter().position(|f| *f == g.face).unwrap_or(0);
if let Some(k) = widgets::dropdown(ui, "three-d-graphic-face", labels[at], &labels, 120.0)
&& let Some(face) = PlanarFace::ALL.get(k)
{
edited.face = *face;
}
});
}
+1 -1
View File
@@ -112,7 +112,7 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) {
"rotate" => json!({"angle": 0}),
"reflect" => json!({"axis": "vertical", "angle": 90}),
"scale" => json!({"sx": 100, "sy": 100, "uniform": true}),
"shear" => json!({"angle": 0, "axis": "horizontal"}),
"shear" => json!({"angle": 0, "axis": "horizontal", "axisAngle": 0}),
_ => json!({}),
};
if let (Some(b), Some(o)) = (base.as_object_mut(), p.as_object()) {
Loaded 100 of 680 files, more files were not shown because too many files have changed in this diff. Show more