mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 23:24:24 +00:00
Merge branch 'fw/merge-d' into area/fwb2
This commit is contained in:
@@ -615,7 +615,9 @@ stencilcraft-format = ["dep:craft-stencilcraft-format"]
|
||||
stream-codecs = ["dep:craft-stream-codecs"]
|
||||
|
||||
svg = ["dep:craft-svg"]
|
||||
svg-draw = ["svg", "craft-svg/draw"]
|
||||
svg-tree = ["svg", "craft-svg/tree"]
|
||||
svg-tree-core = ["svg", "craft-svg/tree-core"]
|
||||
svg-tree-render = ["svg", "craft-svg/tree-render"]
|
||||
svg-tree-render-system-fonts = ["svg", "craft-svg/tree-render-system-fonts"]
|
||||
svg-tree-system-fonts = ["svg", "craft-svg/tree-system-fonts"]
|
||||
|
||||
@@ -53,6 +53,7 @@ pub struct FakeLayers {
|
||||
/// filter's Missing.
|
||||
pub missing: Vec<u32>,
|
||||
info_calls: Cell<usize>,
|
||||
sub_rows_calls: Cell<usize>,
|
||||
}
|
||||
|
||||
impl FakeLayers {
|
||||
@@ -254,7 +255,7 @@ impl FakeLayers {
|
||||
tree
|
||||
}
|
||||
|
||||
/// `count` pixel layers at the top level, for the 10,000-row test; counts the `info` calls.
|
||||
/// `count` pixel layers at the top level, for the long-list trials; counts the `info` and `sub_rows` calls.
|
||||
pub fn flat(count: usize) -> Self {
|
||||
let mut tree = Self::default();
|
||||
for n in 0..count {
|
||||
@@ -305,6 +306,11 @@ impl FakeLayers {
|
||||
pub fn take_info_calls(&self) -> usize {
|
||||
self.info_calls.replace(0)
|
||||
}
|
||||
|
||||
/// How many times `sub_rows` was called since the last [`take_sub_rows_calls`](Self::take_sub_rows_calls).
|
||||
pub fn take_sub_rows_calls(&self) -> usize {
|
||||
self.sub_rows_calls.replace(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl FakeLayers {
|
||||
@@ -394,6 +400,7 @@ impl LayerTree for FakeLayers {
|
||||
}
|
||||
|
||||
fn sub_rows(&self, id: &u32, group: SubRowGroup) -> Option<SubRows> {
|
||||
self.sub_rows_calls.set(self.sub_rows_calls.get() + 1);
|
||||
let layer = self.layer(id)?;
|
||||
match group {
|
||||
SubRowGroup::Effects => layer.effects.clone(),
|
||||
|
||||
@@ -386,3 +386,63 @@ fn a_stacking_key_on_a_selected_smart_filter_row_moves_the_filter() {
|
||||
.collect();
|
||||
assert_eq!(moves, [(SMART, SubRowGroup::SmartFilters, 0, 1)], "{events:?}");
|
||||
}
|
||||
|
||||
/// `count` pixel layers above a closed group and a smart object with two Smart Filters shown, at a fixed revision;
|
||||
/// returns the tree and the smart object.
|
||||
fn long(count: usize) -> (FakeLayers, u32) {
|
||||
let mut tree = FakeLayers::flat(count);
|
||||
let group = tree.add(None, LayerInfo::new("Closed Group", LayerKind::Group), false);
|
||||
tree.add(Some(group), LayerInfo::new("Inside", LayerKind::Pixel), false);
|
||||
let mut smart = LayerInfo::new("Smart Object", LayerKind::SmartObject);
|
||||
smart.has_smart_filters = true;
|
||||
let id = tree.add(None, smart, false);
|
||||
let layer = tree.layer_mut(id);
|
||||
layer.effects_open = true;
|
||||
layer.smart_filters = Some(SubRows::new(SubRow::new("Smart Filters"), vec![sub_row("Gaussian Blur"), sub_row("Sharpen")]));
|
||||
tree.selection = LayerSelection::new(vec![1], Some(1), LayerPart::Pixels);
|
||||
tree.revision = Some(1);
|
||||
(tree, id)
|
||||
}
|
||||
|
||||
/// FW15: a long layer list asks the app only for the rows in view: a settled frame makes as many `info` and
|
||||
/// `sub_rows` calls for 2,000 layers as for 200, and an off-screen group or Smart Filter row lays out nothing.
|
||||
/// Scrolled into view they show; a filter selected there stays selected after it scrolls away again.
|
||||
#[trial]
|
||||
fn a_long_layer_list_asks_only_for_the_rows_in_view() {
|
||||
let mut calls = Vec::new();
|
||||
for count in [200, 2_000] {
|
||||
let (tree, smart) = long(count);
|
||||
let (mut fixture, app) = rig(tree);
|
||||
let _ = (app.borrow().tree.take_info_calls(), app.borrow().tree.take_sub_rows_calls());
|
||||
fixture.frame(vec![]);
|
||||
calls.push((app.borrow().tree.take_info_calls(), app.borrow().tree.take_sub_rows_calls()));
|
||||
for name in ["Closed Group", "Smart Object", "Gaussian Blur", "Sharpen"] {
|
||||
assert!(fixture.by_label(name).is_none(), "{count} layers: the off-screen row {name:?} lays out nothing");
|
||||
}
|
||||
|
||||
let list = node(&fixture, "Layers").center();
|
||||
fixture.frame(vec![pointer::moved(list)]);
|
||||
// The list's extent grows as it measures the rows a wheel brings in, so the end takes a few wheels.
|
||||
for _ in 0..3 {
|
||||
fixture.frame(vec![pointer::wheel(-1.0e7)]).settle();
|
||||
}
|
||||
for name in ["Closed Group", "Smart Object", "Gaussian Blur", "Sharpen"] {
|
||||
assert!(fixture.by_label(name).is_some(), "{count} layers: scrolled to the bottom, {name:?} shows");
|
||||
}
|
||||
let blur = node(&fixture, "Gaussian Blur");
|
||||
fixture.click(&blur).settle();
|
||||
let selected = Some(LayerRowKey::Filters(smart, Some(0)));
|
||||
assert_eq!(app.borrow().tree.selection.sub_row, selected, "{count} layers: the filter is selected");
|
||||
take(&app);
|
||||
for _ in 0..3 {
|
||||
fixture.frame(vec![pointer::wheel(1.0e7)]).settle();
|
||||
}
|
||||
// The selected filter is the list's lead, which stays built out of view.
|
||||
let view = node(&fixture, "Layers").rect;
|
||||
let left = fixture.by_label("Gaussian Blur");
|
||||
assert!(left.is_none_or(|row| !row.rect.intersects(view)), "{count} layers: scrolled back to the top, the filter is out of view");
|
||||
assert!(take(&app).iter().all(|event| !matches!(event, LayersEvent::Select(_))), "{count} layers: scrolling selects nothing");
|
||||
assert_eq!(app.borrow().tree.selection.sub_row, selected, "{count} layers: the filter stays selected");
|
||||
}
|
||||
assert_eq!(calls[0], calls[1], "a settled frame asks for as many rows for 2,000 layers as for 200 (info, sub_rows)");
|
||||
}
|
||||
|
||||
+11
-5
@@ -26,17 +26,23 @@ vectorcraft-pathops = { workspace = true }
|
||||
usvg = { version = "=0.48.1", default-features = false, optional = true }
|
||||
# Rendering the parsed tree uses the matching renderer version. Keep it behind an opt-in feature
|
||||
# so callers that only need bounded SVG text/tree parsing do not pull in raster backends.
|
||||
resvg = { version = "=0.48.1", default-features = false, features = ["text", "raster-images"], optional = true }
|
||||
resvg = { version = "=0.48.1", default-features = false, optional = true }
|
||||
|
||||
data-url = { version = "0.3.2", optional = true }
|
||||
|
||||
[features]
|
||||
# `craft_svg::tree`: usvg behind the bounded entry point.
|
||||
tree = ["dep:usvg", "dep:data-url", "dep:craft-image-codecs"]
|
||||
# `craft_svg::tree` without images: usvg behind the bounded entry point, the preflight, the
|
||||
# limits and the draw check. For a caller that parses SVG it trusts no `<image>` in (UI icons).
|
||||
tree-core = ["dep:usvg"]
|
||||
# `craft_svg::tree`: usvg behind the bounded entry point, with the data-URL image resolver.
|
||||
tree = ["tree-core", "dep:data-url", "dep:craft-image-codecs"]
|
||||
# Text converted to paths (needs a font database in the options).
|
||||
tree-text = ["tree", "usvg/text"]
|
||||
# The system's fonts in `usvg::fontdb`.
|
||||
tree-system-fonts = ["tree-text", "usvg/system-fonts"]
|
||||
# Bounded rendering of a parsed tree through the matching resvg/tiny-skia versions.
|
||||
tree-render = ["tree", "dep:resvg"]
|
||||
# Bounded drawing of a parsed tree through the matching resvg/tiny-skia versions, without text or
|
||||
# raster images (`tree::draw::render`, `render_node`, the `resvg` and `tiny_skia` re-exports).
|
||||
draw = ["tree-core", "dep:resvg"]
|
||||
# Bounded rendering of a parsed tree with its text and raster images.
|
||||
tree-render = ["tree", "draw", "resvg/text", "resvg/raster-images"]
|
||||
tree-render-system-fonts = ["tree-render", "resvg/system-fonts"]
|
||||
|
||||
@@ -26,6 +26,6 @@ pub mod paths;
|
||||
pub mod preflight;
|
||||
pub mod sniff;
|
||||
pub mod svgz;
|
||||
#[cfg(feature = "tree")]
|
||||
#[cfg(feature = "tree-core")]
|
||||
pub mod tree;
|
||||
pub mod write;
|
||||
|
||||
@@ -23,6 +23,8 @@ pub struct Limits {
|
||||
pub attribute_work: usize,
|
||||
/// Maximum XML nodes after entity expansion.
|
||||
pub xml_nodes: u32,
|
||||
/// Accept a document type declaration; `false` refuses any `<!DOCTYPE`.
|
||||
pub allow_dtd: bool,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
@@ -35,6 +37,7 @@ impl Default for Limits {
|
||||
attributes: crate::guard::MAX_ATTRIBUTES,
|
||||
attribute_work: crate::guard::MAX_ATTRIBUTE_WORK,
|
||||
xml_nodes: 4_000_000,
|
||||
allow_dtd: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,7 +96,7 @@ pub fn parse_text_with_depth<'a>(svg: &'a str, limits: &Limits) -> Result<(roxml
|
||||
if prescan.too_deep {
|
||||
return Err(Error::TooDeep(limits.depth));
|
||||
}
|
||||
let options = roxmltree::ParsingOptions { allow_dtd: true, nodes_limit: limits.xml_nodes, ..Default::default() };
|
||||
let options = roxmltree::ParsingOptions { allow_dtd: limits.allow_dtd, nodes_limit: limits.xml_nodes, ..Default::default() };
|
||||
let xml = roxmltree::Document::parse_with_options(svg, options).map_err(|e| Error::Xml(e.to_string()))?;
|
||||
Ok((xml, prescan.depth, prescan.open_depth))
|
||||
}
|
||||
@@ -123,4 +126,11 @@ mod tests {
|
||||
let normal = Limits::default();
|
||||
assert!(matches!(parse_text_with_depth("<svg><g></svg>", &normal), Err(Error::Xml(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_type_is_refused_only_when_the_limits_say_so() {
|
||||
let svg = r#"<!DOCTYPE svg [<!ENTITY a "x">]><svg>&a;</svg>"#;
|
||||
assert!(parse_text(svg, &Limits::default()).is_ok());
|
||||
assert!(matches!(parse_text(svg, &Limits { allow_dtd: false, ..Default::default() }), Err(Error::Xml(_))));
|
||||
}
|
||||
}
|
||||
|
||||
+21
-2
@@ -22,9 +22,13 @@
|
||||
//! 16 MB or so, and a 1 MB stack takes a depth of about 34.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "tree")]
|
||||
use std::collections::HashSet;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
#[cfg(feature = "tree")]
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
#[cfg(feature = "tree")]
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
pub use usvg;
|
||||
@@ -58,6 +62,8 @@ pub struct Limits {
|
||||
pub attribute_work: usize,
|
||||
/// Nodes the XML may hold once entities are expanded.
|
||||
pub xml_nodes: u32,
|
||||
/// Accept a document type declaration; `false` refuses any `<!DOCTYPE`.
|
||||
pub allow_dtd: bool,
|
||||
/// Bytes of all SVG documents embedded in `<image>` data URLs, unpacked, for
|
||||
/// [`image_resolver`].
|
||||
pub embedded_bytes: usize,
|
||||
@@ -80,6 +86,7 @@ impl Default for Limits {
|
||||
attributes: guard::MAX_ATTRIBUTES,
|
||||
attribute_work: guard::MAX_ATTRIBUTE_WORK,
|
||||
xml_nodes: 4_000_000,
|
||||
allow_dtd: true,
|
||||
embedded_bytes: 32 << 20,
|
||||
embedded_depth: 4,
|
||||
embedded_raster_pixels: 24_000_000,
|
||||
@@ -163,6 +170,7 @@ pub struct Preflight<'s> {
|
||||
xml: roxmltree::Document<'s>,
|
||||
depth: usize,
|
||||
/// [`height`]: the nesting usvg converts, references followed.
|
||||
#[cfg_attr(not(feature = "tree"), expect(dead_code, reason = "only the embedded-image resolver reads it"))]
|
||||
height: usize,
|
||||
}
|
||||
|
||||
@@ -189,6 +197,7 @@ pub fn preflight<'s>(svg: &'s str, limits: &Limits) -> Result<Preflight<'s>, Err
|
||||
attributes: limits.attributes,
|
||||
attribute_work: limits.attribute_work,
|
||||
xml_nodes: limits.xml_nodes,
|
||||
allow_dtd: limits.allow_dtd,
|
||||
};
|
||||
let (xml, _, depth) = crate::preflight::parse_text_with_depth(svg, &preflight_limits).map_err(|e| match e {
|
||||
crate::preflight::Error::Text(e) => Error::Text(e),
|
||||
@@ -375,6 +384,7 @@ pub fn height(xml: &roxmltree::Document<'_>, most: usize) -> Result<Option<usize
|
||||
Ok(Some(heights.get(&xml.root_element().id()).copied().unwrap_or(0)))
|
||||
}
|
||||
|
||||
#[cfg(feature = "tree")]
|
||||
/// What the embedded SVGs of one import have used so far.
|
||||
struct Used {
|
||||
bytes: AtomicUsize,
|
||||
@@ -391,6 +401,7 @@ struct Used {
|
||||
svg_resource_limit: AtomicUsize,
|
||||
}
|
||||
|
||||
#[cfg(feature = "tree")]
|
||||
/// What resolving one drawing's embedded images used or refused.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ImageUsage {
|
||||
@@ -416,6 +427,7 @@ pub struct ImageUsage {
|
||||
pub svg_resource_limit_images: usize,
|
||||
}
|
||||
|
||||
#[cfg(feature = "tree")]
|
||||
/// A data-URL resolver and the accounting for the one drawing it serves.
|
||||
///
|
||||
/// Keep this value while parsing, then read [`usage`](Self::usage). Linked files are never read.
|
||||
@@ -424,6 +436,7 @@ pub struct ImageResolver {
|
||||
used: Arc<Used>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "tree")]
|
||||
impl ImageResolver {
|
||||
/// Create one resolver budget for one drawing import.
|
||||
pub fn new(limits: Limits) -> Self {
|
||||
@@ -483,6 +496,7 @@ impl ImageResolver {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "tree")]
|
||||
// usvg's data-URL decoder returns before resolve_data for invalid base64. Count
|
||||
// these omissions separately, including feImage, without reading linked resources.
|
||||
fn account_invalid_data_urls(xml: &roxmltree::Document<'_>, used: &Used) {
|
||||
@@ -504,6 +518,7 @@ fn account_invalid_data_urls(xml: &roxmltree::Document<'_>, used: &Used) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "tree")]
|
||||
fn raster_format(data: &[u8]) -> Option<craft_image_codecs::Format> {
|
||||
match craft_image_codecs::detect(data)? {
|
||||
format @ (craft_image_codecs::Format::Png
|
||||
@@ -514,6 +529,7 @@ fn raster_format(data: &[u8]) -> Option<craft_image_codecs::Format> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "tree")]
|
||||
fn raster_image(used: &Used, limits: &Limits, data: Arc<Vec<u8>>, format: craft_image_codecs::Format) -> Option<usvg::ImageKind> {
|
||||
let Ok((width, height)) = craft_image_codecs::probe_allocation_size(&data) else {
|
||||
used.invalid_raster.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -576,6 +592,7 @@ fn raster_image(used: &Used, limits: &Limits, data: Arc<Vec<u8>>, format: craft_
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(feature = "tree")]
|
||||
/// An embedded SVG document, if the budgets allow it.
|
||||
fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<'_>) -> Option<usvg::ImageKind> {
|
||||
if used.depth.load(Ordering::Relaxed) >= limits.embedded_depth {
|
||||
@@ -650,6 +667,7 @@ fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<'
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "tree")]
|
||||
/// An image resolver for `usvg::Options::image_href_resolver` that reads `<image>` data URLs
|
||||
/// only: raster images as they are (PNG, JPEG, GIF, WebP), SVG documents (SVGZ too) through the
|
||||
/// same checks as [`parse`] and within [`Limits::embedded_bytes`] in all and
|
||||
@@ -659,6 +677,7 @@ pub fn image_resolver(limits: Limits) -> usvg::ImageHrefResolver<'static> {
|
||||
ImageResolver::new(limits).resolver()
|
||||
}
|
||||
|
||||
#[cfg(feature = "tree")]
|
||||
fn image_resolver_for(limits: Limits, used: Arc<Used>) -> usvg::ImageHrefResolver<'static> {
|
||||
usvg::ImageHrefResolver {
|
||||
resolve_data: Box::new(move |mime, data, options| {
|
||||
@@ -690,5 +709,5 @@ fn image_resolver_for(limits: Limits, used: Arc<Used>) -> usvg::ImageHrefResolve
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, feature = "tree"))]
|
||||
mod tests;
|
||||
|
||||
@@ -24,9 +24,9 @@ use std::collections::HashMap;
|
||||
|
||||
use usvg::Transform;
|
||||
|
||||
#[cfg(feature = "tree-render")]
|
||||
#[cfg(feature = "draw")]
|
||||
pub use resvg;
|
||||
#[cfg(feature = "tree-render")]
|
||||
#[cfg(feature = "draw")]
|
||||
pub use resvg::tiny_skia;
|
||||
|
||||
/// Filter primitives per filter. A result of every primitive is kept; real filters have 1 to 12
|
||||
@@ -165,7 +165,7 @@ pub fn check(nodes: &[usvg::Node], ts: Transform, width: u32, height: u32, held:
|
||||
/// Draws a complete tree onto a transparent pixmap after checking the peak RGBA allocation.
|
||||
/// `held` is caller-owned RGBA storage that remains live during the draw; the target itself is
|
||||
/// charged by this function.
|
||||
#[cfg(feature = "tree-render")]
|
||||
#[cfg(feature = "draw")]
|
||||
pub fn render(tree: &usvg::Tree, ts: Transform, width: u32, height: u32, held: u64, budget: u64) -> Result<tiny_skia::Pixmap, Refusal> {
|
||||
check_filter_cost(tree, ts, 2_000_000_000, 10_000_000, 200)?;
|
||||
// Even an empty tree allocates the target. `check` only walks buffers added by nodes, so
|
||||
@@ -186,7 +186,7 @@ pub fn render(tree: &usvg::Tree, ts: Transform, width: u32, height: u32, held: u
|
||||
|
||||
/// Draws one node onto `target` after checking the peak RGBA allocation. The node remains in its
|
||||
/// parent's coordinate space, matching `resvg::render_node`.
|
||||
#[cfg(feature = "tree-render")]
|
||||
#[cfg(feature = "draw")]
|
||||
pub fn render_node(node: &usvg::Node, ts: Transform, target: &mut tiny_skia::Pixmap, held: u64, budget: u64) -> Result<bool, Refusal> {
|
||||
check(std::slice::from_ref(node), ts, target.width(), target.height(), held, budget)?;
|
||||
Ok(resvg::render_node(node, ts, &mut target.as_mut()).is_some())
|
||||
|
||||
@@ -1259,7 +1259,9 @@ impl<'a, 't: 'a> Run<'a, 't> {
|
||||
|
||||
/// The keys the canvas holds: intents routed to it while it has focus, the arrows, Enter and Escape while nothing
|
||||
/// in the window has focus, and the chords the tool claimed at the end of the last pass. A session control in the
|
||||
/// canvas body (`KeyUse::session`) has taken the arrows, Enter and Escape it acts on before this runs.
|
||||
/// canvas body (`KeyUse::session`) has taken the arrows, Enter and Escape it acts on before this runs. The Escape
|
||||
/// of the focused canvas reaches the tool once, through the window's intents (`with_window_intents` offers the
|
||||
/// focused document canvas's Escape); one the tool leaves stays the canvas's, for the scopes around it.
|
||||
fn keys(&mut self, ctx: &Context, canvas: Id, rtl: bool) {
|
||||
keys::with_window_intents(ctx, rtl, |window| {
|
||||
let mut taken = self.offer(window, |intents| intents.take_nudge().map(|(direction, mods)| ToolKey::Nudge { direction, mods }));
|
||||
@@ -1282,9 +1284,6 @@ impl<'a, 't: 'a> Run<'a, 't> {
|
||||
});
|
||||
}
|
||||
taken |= self.offer(&mut intents, |intents| intents.take(Intent::Submit).then_some(ToolKey::Submit));
|
||||
if !self.cancelled {
|
||||
taken |= self.offer(&mut intents, |intents| intents.take(Intent::Cancel).then_some(ToolKey::Cancel));
|
||||
}
|
||||
if taken {
|
||||
keys::settle(ctx, Some(canvas), &intents);
|
||||
}
|
||||
@@ -1309,10 +1308,5 @@ impl<'a, 't: 'a> Run<'a, 't> {
|
||||
self.response.took_key = Some(kept);
|
||||
}
|
||||
}
|
||||
// An Escape the focused canvas's sessions and tool were offered and left is the window's, as it is with
|
||||
// nothing focused.
|
||||
if !self.cancelled {
|
||||
keys::leave_to_window(ctx, canvas, |intent| *intent == Intent::Cancel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! The full-window parts' own logic: the view's fit and zoom rules, the wheel zoom and the mapped overlay.
|
||||
//! The full-window parts' own logic: the view's fit and zoom rules, the wheel zoom, Escape on a focused canvas, the
|
||||
//! close of the dialog's own window and the mapped overlay.
|
||||
|
||||
use craft_behavior::PixelSize;
|
||||
use craft_ui::canvas::ViewCommands;
|
||||
@@ -216,6 +217,150 @@ mod momentary {
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape on a focused canvas inside a full-window dialog.
|
||||
mod escape {
|
||||
use craft_behavior::{CancelReason, Intent, PixelSize};
|
||||
use craft_ui::canvas::{CanvasTool, PixelRect, RasterSource, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer};
|
||||
use craft_ui::contract::{Bind, ShowContainer as _};
|
||||
use craft_ui::dialog::{FullWindowCanvas, FullWindowDialog, FullWindowView};
|
||||
use craft_ui::primitives::{Draw, Revision};
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::runtime::focus::Initial;
|
||||
use craft_ui::runtime::keys;
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Color32, ColorImage, Key, Modifiers};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
struct Grey;
|
||||
|
||||
impl RasterSource for Grey {
|
||||
fn size(&self) -> PixelSize {
|
||||
PixelSize::new(800, 600)
|
||||
}
|
||||
|
||||
fn revision(&self) -> Revision {
|
||||
Revision::new(1)
|
||||
}
|
||||
|
||||
fn damage(&self, _: Revision) -> Option<PixelRect> {
|
||||
Some(PixelRect::default())
|
||||
}
|
||||
|
||||
fn read(&self, _: PixelRect, _: u32, out: &mut ColorImage) {
|
||||
out.pixels.fill(Color32::from_rgb(0x80, 0x80, 0x80));
|
||||
}
|
||||
}
|
||||
|
||||
/// A tool that takes its clicks and, when `takes_escape`, the Escape.
|
||||
struct Picker {
|
||||
takes_escape: bool,
|
||||
}
|
||||
|
||||
impl CanvasTool for Picker {
|
||||
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
|
||||
ToolAction::Claimed
|
||||
}
|
||||
|
||||
fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn key(&mut self, key: &ToolKey, _: &mut ToolContext<'_>) -> bool {
|
||||
self.takes_escape && *key == ToolKey::Cancel
|
||||
}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the Edit command")
|
||||
}
|
||||
}
|
||||
|
||||
// The RAW Develop form: the canvas a click focused leaves the Escape its tool refuses to the dialog, which closes;
|
||||
// the window, reading its intents last, sees none. An Escape the tool takes closes nothing.
|
||||
#[trial]
|
||||
fn escape_on_a_focused_canvas_in_a_full_window_dialog_closes_the_dialog_and_not_the_window() {
|
||||
for takes_escape in [false, true] {
|
||||
let open = Rc::new(Cell::new(true));
|
||||
let window_cancels = Rc::new(Cell::new(0));
|
||||
let view = Rc::new(RefCell::new(FullWindowView::new()));
|
||||
let (shown, seen, viewed) = (open.clone(), window_cancels.clone(), view.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut is_open = shown.get();
|
||||
let mut tool = Picker { takes_escape };
|
||||
let mut view = viewed.borrow_mut();
|
||||
FullWindowDialog::new("Workspace").opened(Bind::bound(&mut is_open)).initial_focus(Initial::Keep).show(ui, |ui, _| {
|
||||
FullWindowCanvas::new(Bind::bound(&mut *view), &Grey).tool(&mut tool).show(ui);
|
||||
});
|
||||
shown.set(is_open);
|
||||
keys::with_window_intents(ui.ctx(), false, |window| {
|
||||
let took = window.take(Intent::Cancel);
|
||||
seen.set(seen.get() + u32::from(took));
|
||||
took
|
||||
});
|
||||
});
|
||||
fixture.settle();
|
||||
let canvas = fixture.by_role(Role::CANVAS).remove(0);
|
||||
fixture.click(&canvas).settle();
|
||||
assert!(open.get(), "a click on the canvas leaves the dialog open");
|
||||
window_cancels.set(0);
|
||||
fixture.frame(vec![key_press(Key::Escape, Modifiers::NONE)]).settle();
|
||||
assert_eq!(open.get(), takes_escape, "Escape closes the dialog only when the tool leaves it (tool takes it: {takes_escape})");
|
||||
assert_eq!(window_cancels.get(), 0, "the window sees no Escape (tool takes it: {takes_escape})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A full-window dialog in a window of its own.
|
||||
mod own_window {
|
||||
use craft_ui::contract::{Bind, ShowContainer as _};
|
||||
use craft_ui::dialog::{DialogResult, FullWindowDialog};
|
||||
use craft_ui::runtime::overlay::CloseReason;
|
||||
use craft_ui::runtime::windows::WindowSpec;
|
||||
use craft_ui::testing::trial;
|
||||
use craft_ui_test_kit::windows::Windows;
|
||||
use egui::{ViewportEvent, ViewportInfo};
|
||||
use std::cell::Cell;
|
||||
|
||||
// The OS closing the dialog's window (its close button, a window manager's close) is a cancel: the dialog reports
|
||||
// `Requested`, which every host but OK reads as Cancel, so an outer gesture over its edits is taken back.
|
||||
#[trial]
|
||||
fn closing_a_full_window_dialogs_own_window_cancels_it() {
|
||||
let windows = Windows::new();
|
||||
let open = Cell::new(true);
|
||||
let closed = Cell::new(None);
|
||||
let frame = || {
|
||||
windows.frame(vec![], vec![], |ui| {
|
||||
let mut is_open = open.get();
|
||||
let output = FullWindowDialog::new("Workspace")
|
||||
.own_window(WindowSpec::dialog())
|
||||
.outer_gesture(true)
|
||||
.opened(Bind::bound(&mut is_open))
|
||||
.show(ui, |_, _| {})
|
||||
.output;
|
||||
open.set(is_open);
|
||||
if let Some(reason) = output.closed {
|
||||
closed.set(Some((reason, matches!(output.result(|| ()), Some(DialogResult::Cancel)))));
|
||||
}
|
||||
})
|
||||
};
|
||||
for _ in 0..4 {
|
||||
frame();
|
||||
}
|
||||
assert!(open.get(), "the dialog opened in its own window");
|
||||
windows.child_info(ViewportInfo { events: vec![ViewportEvent::Close], ..ViewportInfo::default() });
|
||||
for _ in 0..2 {
|
||||
frame();
|
||||
}
|
||||
assert!(!open.get(), "closing the dialog's window closes the dialog");
|
||||
assert_eq!(closed.get(), Some((CloseReason::Requested, true)), "the close is a cancel");
|
||||
}
|
||||
}
|
||||
|
||||
/// An overlay drawn through a frame.
|
||||
mod mapped_overlay {
|
||||
use craft_behavior::PixelSize;
|
||||
|
||||
@@ -62,8 +62,8 @@ craft-fonts-build = { workspace = true }
|
||||
# Only `color_fonts` reads it: the feature turns on epaint's colour glyphs.
|
||||
epaint = { version = "0.37", default-features = false, optional = true }
|
||||
|
||||
# Icon rasterising; the version egui_extras's `svg` feature uses, so apps build one copy.
|
||||
resvg = { version = "0.45.1", default-features = false }
|
||||
# Icon parsing and rasterising: the bounded usvg/resvg stack every Craft app shares, without text or raster images.
|
||||
craft-svg = { workspace = true, features = ["draw"] }
|
||||
# `std::time::Instant` on native; the browser clock on wasm, where `Instant::now` panics.
|
||||
web-time = "1.1"
|
||||
|
||||
|
||||
@@ -24,14 +24,14 @@ use crate::primitives::SurfaceSlot;
|
||||
use crate::runtime::access::scope;
|
||||
use crate::runtime::access::{self, Politeness, Role};
|
||||
use crate::runtime::commands;
|
||||
use crate::runtime::egui::{alloc, areas, child, repaint, response, style, viewports};
|
||||
use crate::runtime::egui::{alloc, areas, child, repaint, response, style};
|
||||
use crate::runtime::env::{AppValues, ArenaId, ColumnSweep, Env, RowLine};
|
||||
use crate::runtime::focus::FocusPolicy;
|
||||
use crate::runtime::memory::{MemoryStage, sub};
|
||||
use crate::runtime::motion::{Driver, Presence, spec};
|
||||
use crate::runtime::overlay::CloseReason;
|
||||
use crate::runtime::pass_state;
|
||||
use crate::runtime::{keys, layout_memory, pointer, wheel};
|
||||
use crate::runtime::{keys, layout_memory, pointer, wheel, windows};
|
||||
use crate::style::ComponentStyle as _;
|
||||
use crate::style::{ScrollBarKind, StyleCx, SurfaceKind, band_color, scroll_bar_look, surface_style};
|
||||
use craft_behavior::layout_memory::measure_tolerance;
|
||||
@@ -169,7 +169,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
// A viewport whose fallback covers the window is fixed in both modes, as a full-window mount is: its body
|
||||
// never sizes as a layer's content.
|
||||
Mount::Viewport { fallback, .. } if fallback.is_full_window() => true,
|
||||
Mount::Viewport { .. } if viewports::available(&ctx) => true,
|
||||
Mount::Viewport { .. } if windows::mount_window(&ctx, id) => true,
|
||||
Mount::Layer(_) | Mount::Viewport { .. } => {
|
||||
let placement = overlay_of(props).map_or_else(Placement::default, |overlay| {
|
||||
let screen = crate::contract::overlay::screen_for(&ctx, env, overlay);
|
||||
@@ -617,7 +617,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
let props = comp.props(Internal::new());
|
||||
let (scroll, layer) = (scroll_of(props), matches!(props.mount, Mount::Layer(_) | Mount::Viewport { .. }));
|
||||
// The OS asked a viewport mount's window to close: the container closes at step 15.
|
||||
if matches!(props.mount, Mount::Viewport { .. }) && crate::runtime::windows::take_close_request(cx.core.memory.ctx(), cx.core.id) {
|
||||
if matches!(props.mount, Mount::Viewport { .. }) && windows::take_close_request(cx.core.memory.ctx(), cx.core.id) {
|
||||
self.close = true;
|
||||
self.reason = self.reason.or(Some(CloseReason::Requested));
|
||||
}
|
||||
@@ -654,7 +654,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
self.window_movable(viewport, cx);
|
||||
}
|
||||
self.pane_drag(props, cx);
|
||||
if layer && !(matches!(props.mount, Mount::Viewport { .. }) && viewports::available(cx.core.memory.ctx())) {
|
||||
if layer && !(matches!(props.mount, Mount::Viewport { .. }) && windows::mount_window(cx.core.memory.ctx(), cx.core.id)) {
|
||||
self.window_keys(props, cx);
|
||||
self.window_drag(props, cx);
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ pub(super) fn overlay_of(props: &ContainerProps) -> Option<&crate::contract::Ove
|
||||
pub(super) fn measure_layer(props: &ContainerProps, id: Id, ui: &Ui) -> areas::Layer {
|
||||
let area = sub(id, "area");
|
||||
match &props.mount {
|
||||
Mount::Viewport { .. } if windows::WindowHost::of(ui.ctx()).viewports_available() => ui.layer_id(),
|
||||
Mount::Viewport { .. } if windows::mount_window(ui.ctx(), id) => ui.layer_id(),
|
||||
Mount::Layer(overlay) | Mount::Viewport { fallback: overlay, .. } => {
|
||||
areas::layer_of(crate::runtime::overlay::layer_tier(ui.ctx(), overlay.rank), area)
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ fn answered_by_platform(ctx: &Context, viewport: ViewportId) -> bool {
|
||||
pub(super) fn os_window(props: &ContainerProps, ctx: &Context, id: Id, env: &EnvView<'_>) -> Option<ViewportId> {
|
||||
let embedded = env.get::<ShellEntry>().0.is_some_and(|shell| shell.region().is_some());
|
||||
match &props.mount {
|
||||
Mount::Viewport { .. } if viewports::available(ctx) => Some(viewports::viewport_id(id)),
|
||||
Mount::Viewport { .. } if windows::mount_window(ctx, id) => Some(viewports::viewport_id(id)),
|
||||
Mount::Window { .. } | Mount::Pane(_) | Mount::Inline if !embedded => Some(pass::current_viewport(ctx)),
|
||||
Mount::Window { .. } | Mount::Pane(_) | Mount::Inline | Mount::Viewport { .. } | Mount::Layer(_) | Mount::FullWindow => None,
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::runtime::layout_memory;
|
||||
use crate::runtime::memory::{MemoryStage, SaveKey, sub};
|
||||
use crate::runtime::motion::{self, Presence};
|
||||
use crate::runtime::overlay::CloseReason;
|
||||
use crate::runtime::windows::{self, ViewportOpen, WindowHost, WindowSpec};
|
||||
use crate::runtime::windows::{self, ViewportOpen, WindowSpec};
|
||||
use craft_behavior::ScopeKind;
|
||||
use egui::{Id, Pos2, Rect, Ui, Vec2};
|
||||
|
||||
@@ -51,7 +51,7 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &
|
||||
},
|
||||
Mount::FullWindow => full_window(props.focus),
|
||||
Mount::Viewport { fallback, spec } => {
|
||||
let viewports = WindowHost::of(ctx).viewports_available();
|
||||
let viewports = windows::mount_window(ctx, at.id);
|
||||
// A full-window container without OS windows covers the main window, as `Mount::FullWindow` does.
|
||||
if !viewports && fallback.is_full_window() {
|
||||
full_window(fallback.focus)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use crate::primitives::SvgIcon;
|
||||
use crate::runtime::cursor::{CursorArt, CursorBitmap};
|
||||
use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, Vec2};
|
||||
use resvg::tiny_skia;
|
||||
use craft_svg::tree::draw::tiny_skia;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// How far past a mark's geometry its antialiasing reaches, in device pixels.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The SVG icon catalog the build embeds, the app icon sets registered beside it, and their rasteriser.
|
||||
|
||||
use egui::{Color32, ColorImage};
|
||||
use resvg::tiny_skia;
|
||||
use craft_svg::tree::draw::{self as svg_draw, tiny_skia};
|
||||
use std::sync::{PoisonError, RwLock};
|
||||
|
||||
use super::svg_tree;
|
||||
@@ -151,14 +151,15 @@ fn draw(svg: &[u8], own: Option<f32>, px: u32, stroke_px: f32, mirrored: bool) -
|
||||
let text = std::str::from_utf8(svg).map_err(|e| e.to_string())?;
|
||||
tree = svg_tree::parse(scale_stroke_widths(text, units / own).as_bytes())?;
|
||||
}
|
||||
let mut pixmap = tiny_skia::Pixmap::new(px, px).ok_or("zero size")?;
|
||||
let (sx, sy) = (px as f32 / view.width(), px as f32 / view.height());
|
||||
let transform =
|
||||
if mirrored { tiny_skia::Transform::from_row(-sx, 0.0, 0.0, sy, px as f32, 0.0) } else { tiny_skia::Transform::from_scale(sx, sy) };
|
||||
resvg::render(&tree, transform, &mut pixmap.as_mut());
|
||||
Ok(pixmap)
|
||||
svg_draw::render(&tree, transform, px, px, 0, ICON_DRAW_BUDGET).map_err(|refusal| refusal.message)
|
||||
}
|
||||
|
||||
/// Bytes drawing one icon may allocate, its target included.
|
||||
const ICON_DRAW_BUDGET: u64 = 64 << 20;
|
||||
|
||||
/// `svg` with each `stroke-width="..."` attribute multiplied by `factor`.
|
||||
fn scale_stroke_widths(svg: &str, factor: f32) -> String {
|
||||
const ATTR: &str = "stroke-width=\"";
|
||||
|
||||
@@ -1,14 +1,31 @@
|
||||
//! The one SVG parser. Icon files come from the build and from icon themes on the user's disk, so parsing is bounded:
|
||||
//! no gzip (its size is unlimited), no DTD (entity expansion), a node limit, and no `<image>` loaded, which keeps a
|
||||
//! document from making the renderer read another file or nest an SVG.
|
||||
//! The one SVG parser, craft-svg's bounded entry point. Icon files come from the build and from icon themes on the
|
||||
//! user's disk, so parsing is bounded: no gzip, no DTD (entity expansion), a node limit, a nesting limit, and no
|
||||
//! `<image>` loaded, which keeps a document from making the renderer read another file or nest an SVG.
|
||||
|
||||
use resvg::usvg;
|
||||
use craft_svg::tree::{self, Limits, usvg};
|
||||
|
||||
/// Elements and text nodes an icon SVG may have; a glyph has a handful.
|
||||
const MAX_NODES: u32 = 10_000;
|
||||
/// The first bytes of a gzip stream.
|
||||
const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b];
|
||||
|
||||
/// What an icon may use. Icons parse on the UI thread, whose stack may be 1 MB (Windows' main thread): craft-svg
|
||||
/// gives about 34 levels for that, so nesting stops at 32.
|
||||
fn icon_limits() -> Limits {
|
||||
Limits {
|
||||
bytes: 1 << 20,
|
||||
depth: 32,
|
||||
tree_depth: 32,
|
||||
xml_nodes: MAX_NODES,
|
||||
allow_dtd: false,
|
||||
refuse_entity_markup: true,
|
||||
embedded_bytes: 0,
|
||||
embedded_depth: 0,
|
||||
embedded_raster_pixels: 0,
|
||||
..Limits::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The render tree of `svg`, or why it was refused.
|
||||
#[doc(hidden)]
|
||||
pub fn parse(svg: &[u8]) -> Result<usvg::Tree, String> {
|
||||
@@ -19,8 +36,5 @@ pub fn parse(svg: &[u8]) -> Result<usvg::Tree, String> {
|
||||
image_href_resolver: usvg::ImageHrefResolver { resolve_data: Box::new(|_, _, _| None), resolve_string: Box::new(|_, _| None) },
|
||||
..usvg::Options::default()
|
||||
};
|
||||
let text = std::str::from_utf8(svg).map_err(|e| e.to_string())?;
|
||||
let xml = usvg::roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES };
|
||||
let doc = usvg::roxmltree::Document::parse_with_options(text, xml).map_err(|e| e.to_string())?;
|
||||
usvg::Tree::from_xmltree(&doc, &options).map_err(|e| e.to_string())
|
||||
tree::parse(svg, &icon_limits(), &options).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
@@ -8,6 +8,11 @@ pub(crate) fn available(ctx: &Context) -> bool {
|
||||
!ctx.embed_viewports()
|
||||
}
|
||||
|
||||
/// The viewport the running viewport was opened from; the root for the root.
|
||||
pub(crate) fn parent(ctx: &Context) -> ViewportId {
|
||||
ctx.parent_viewport_id()
|
||||
}
|
||||
|
||||
/// How a viewport opens.
|
||||
pub(crate) struct Spec<'a> {
|
||||
/// The window title.
|
||||
|
||||
@@ -32,8 +32,6 @@ pub(crate) use input::{input_hook, queue_nav, take_menu_keys, take_nav};
|
||||
pub use intents::Intents;
|
||||
#[doc(hidden)]
|
||||
pub use intents::intents_of;
|
||||
#[doc(hidden)]
|
||||
pub use intents::leave_to_window;
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) use intents::lent_taken;
|
||||
#[doc(hidden)]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The intents routed to a component and what it leaves untaken: Submit, Cancel, Escape and context requests.
|
||||
|
||||
use super::current;
|
||||
use super::{Stage, current};
|
||||
use super::route::push;
|
||||
use crate::runtime::focus::{self};
|
||||
use craft_behavior::focus::{EscapeFacts, EscapeStep, escape_step};
|
||||
@@ -269,44 +269,52 @@ pub fn intents_of(ctx: &Context, id: Option<Id>, rtl: bool) -> Intents {
|
||||
///
|
||||
/// The window's intents are the keys the runtime routes to no component this pass: an Escape (`Intent::Cancel`)
|
||||
/// or a plain Enter (`Intent::Submit`) while no framework stop is focused, and the arrows' nudge; with the document
|
||||
/// canvas focused, the Escape its sessions and its tool left (`leave_to_window`). A component or a scope that runs
|
||||
/// earlier in the pass takes them first (an open dialog takes the Escape that closes it, a canvas session the one
|
||||
/// that ends it), so an app that hosts the runtime reads them last in its UI to see what no component took. `rtl`
|
||||
/// reads horizontal moves in the window's direction.
|
||||
/// canvas focused, the Escape the canvas, its sessions, its tool and every scope around it left. A component or a
|
||||
/// scope that runs earlier in the pass takes them first (an open dialog takes the Escape that closes it, a canvas
|
||||
/// session the one that ends it), so an app that hosts the runtime reads them last in its UI to see what no
|
||||
/// component took. `rtl` reads horizontal moves in the window's direction.
|
||||
pub fn with_window_intents(ctx: &Context, rtl: bool, take: impl FnOnce(&mut Intents) -> bool) -> bool {
|
||||
if focus::focused_rec(ctx).is_some_and(|rec| !rec.stop.keys.chrome_key) {
|
||||
return false;
|
||||
}
|
||||
let canvas = match focus::focused_rec(ctx) {
|
||||
Some(rec) if !rec.stop.keys.chrome_key => return false,
|
||||
Some(rec) => Some(rec.stop.id),
|
||||
None => None,
|
||||
};
|
||||
let mut window = intents_of(ctx, None, rtl);
|
||||
// The focused canvas's leftover Escape is offered as the window's; it stays in the canvas's slot until taken.
|
||||
let lent_cancel = canvas
|
||||
.filter(|canvas| !window.items.iter().any(|(item, _)| *item == Intent::Cancel) && holds(ctx, Some(*canvas), &Intent::Cancel))
|
||||
.map(|canvas| {
|
||||
window.items.push((Intent::Cancel, false));
|
||||
(canvas, window.items.len() - 1)
|
||||
});
|
||||
let taken = take(&mut window);
|
||||
if let Some((canvas, at)) = lent_cancel {
|
||||
let (_, cancel_taken) = window.items.remove(at);
|
||||
if cancel_taken && !crate::runtime::measure::active(ctx) {
|
||||
current(ctx, |stage| take_from(stage, Some(canvas), &Intent::Cancel));
|
||||
}
|
||||
}
|
||||
if taken {
|
||||
settle(ctx, None, &window);
|
||||
}
|
||||
taken
|
||||
}
|
||||
|
||||
/// Moves the intents `which` picks that the focused document canvas `from` left untaken this pass to the window's,
|
||||
/// where `with_window_intents` reads them. The canvas's tool host calls it once the canvas's session members and its
|
||||
/// tool had their chance. Nothing moves while `from` is not the focused stop.
|
||||
#[doc(hidden)]
|
||||
pub fn leave_to_window(ctx: &Context, from: Id, which: impl Fn(&Intent) -> bool) {
|
||||
if crate::runtime::measure::active(ctx) || !focus::focused_rec(ctx).is_some_and(|rec| rec.stop.id == from && rec.stop.keys.chrome_key) {
|
||||
return;
|
||||
}
|
||||
current(ctx, |stage| {
|
||||
let Some(routed) = stage.routed.get_mut(&Some(from)) else { return };
|
||||
let mut left = Vec::new();
|
||||
routed.items.retain(|item| {
|
||||
let moves = which(&item.intent);
|
||||
if moves {
|
||||
left.push(item.clone());
|
||||
}
|
||||
!moves
|
||||
});
|
||||
if !left.is_empty() {
|
||||
stage.routed.entry(None).or_default().items.extend(left);
|
||||
/// Whether an intent of the kind of `intent` is routed to `id` and not taken this pass.
|
||||
fn holds(ctx: &Context, id: Option<Id>, intent: &Intent) -> bool {
|
||||
current(ctx, |stage| stage.routed.get(&id).is_some_and(|routed| routed.items.iter().any(|item| item.intent.same_kind(intent))))
|
||||
}
|
||||
|
||||
/// Removes one intent of the kind of `intent` routed to `id`; whether there was one.
|
||||
fn take_from(stage: &mut Stage, id: Option<Id>, intent: &Intent) -> bool {
|
||||
let Some(routed) = stage.routed.get_mut(&id) else { return false };
|
||||
match routed.items.iter().position(|item| item.intent.same_kind(intent)) {
|
||||
Some(at) => {
|
||||
routed.items.remove(at);
|
||||
true
|
||||
}
|
||||
});
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys an arena's session control borrowed this pass (`KeyUse::session`), with the ids they were routed to.
|
||||
@@ -440,16 +448,7 @@ fn take_untaken(ctx: &Context, intent: &Intent) -> bool {
|
||||
if crate::runtime::measure::active(ctx) {
|
||||
return false;
|
||||
}
|
||||
current(ctx, |stage| {
|
||||
let Some(routed) = stage.routed.get_mut(&focused) else { return false };
|
||||
match routed.items.iter().position(|item| item.intent.same_kind(intent)) {
|
||||
Some(at) => {
|
||||
routed.items.remove(at);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
})
|
||||
current(ctx, |stage| take_from(stage, focused, intent))
|
||||
}
|
||||
|
||||
/// What an untaken Escape does in a scope: `None` when no Escape arrived or a component took it. One scope
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::runtime::frame::PerViewport;
|
||||
use crate::runtime::overlay;
|
||||
use crate::runtime::pass_state;
|
||||
use craft_behavior::{Cursor, CursorIcon, CursorPriority};
|
||||
use craft_host::target::{Caps, EdgeInsets, Os, ShellInfo, WindowChrome, WindowKind};
|
||||
use craft_host::target::{Backend, Caps, EdgeInsets, Os, ShellInfo, WindowChrome, WindowKind, WindowState};
|
||||
use craft_window::desktop::Desktop;
|
||||
use craft_window::native::NativeWindow;
|
||||
use craft_window::policy::{Captions, Decision, Frame, LayoutWatch};
|
||||
@@ -301,6 +301,28 @@ pub(crate) fn blocking_modal(ctx: &Context) -> Option<ViewportId> {
|
||||
overlay::modal_viewport(ctx, pass::current_viewport(ctx))
|
||||
}
|
||||
|
||||
/// Whether container `id`'s viewport mount shows in an OS window of its own this pass: OS viewports are available,
|
||||
/// and the window it opens from is neither full screen nor, on Wayland, maximized. A window opened over such a
|
||||
/// window covers it; the compositor then sends the covered window no frames, and the immediate viewport, drawn inside
|
||||
/// them, freezes. Otherwise the mount shows its fallback layer in the opener.
|
||||
///
|
||||
/// It reads only this pass's facts, so the mount, the body (which runs inside the child's pass) and the window steps
|
||||
/// agree within a pass.
|
||||
pub(crate) fn mount_window(ctx: &Context, id: Id) -> bool {
|
||||
if !WindowHost::of(ctx).viewports_available() {
|
||||
return false;
|
||||
}
|
||||
let current = pass::current_viewport(ctx);
|
||||
let opener = if current == viewports::viewport_id(id) { viewports::parent(ctx) } else { current };
|
||||
let shell = shell_of(ctx, opener);
|
||||
let covers = match shell.window.state {
|
||||
WindowState::Fullscreen => true,
|
||||
WindowState::Maximized => shell.backend == Backend::Wayland,
|
||||
_ => false,
|
||||
};
|
||||
!covers
|
||||
}
|
||||
|
||||
/// Refuses the close request of the running viewport while an app-modal layer blocks it, and raises the modal's
|
||||
/// window. True when it refused.
|
||||
fn refuse_close_under_modal(ctx: &Context) -> bool {
|
||||
|
||||
@@ -128,7 +128,7 @@ pub(crate) fn take_close_request(ctx: &Context, id: Id) -> bool {
|
||||
/// Whether container `id` shows in an OS window that has not reported its place yet: its body lays out in room the OS
|
||||
/// has not given, so what it takes there is no size of its content.
|
||||
pub(crate) fn unplaced(ctx: &Context, id: Id) -> bool {
|
||||
super::WindowHost::of(ctx).viewports_available()
|
||||
super::mount_window(ctx, id)
|
||||
&& PerViewport::<Record>::with(ctx, viewports::viewport_id(id), |record| record.kind.is_some() && record.seen.is_none())
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex};
|
||||
use craft_fonts_build::ServedFace;
|
||||
use craft_ui::fonts::{Family, FetchDone, FetchWake, FontFetcher, FontRef, I18nScripts, SystemFonts, UiFonts};
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
use egui::FontId;
|
||||
use egui::{FontFamily, FontId};
|
||||
|
||||
const ARABIC: &[u8] = include_bytes!("../../fonts/NotoSansArabic-test.ttf");
|
||||
/// Noto Sans with Vietnamese ổ but not ẫ.
|
||||
@@ -244,3 +244,54 @@ fn a_failed_download_moves_on_and_is_retried_later() {
|
||||
assert!(!draws('⇥'));
|
||||
assert_eq!(fetch.requested(), [MATH_URL]);
|
||||
}
|
||||
|
||||
const ARABIC_URL: &str = "fonts/noto-sans-arabic/NotoSansArabic.ttf";
|
||||
|
||||
/// A language change installs the fonts anew in the same context: a face fetched before it stays, and is not fetched
|
||||
/// again.
|
||||
#[trial]
|
||||
fn a_fetched_face_survives_a_reinstall() {
|
||||
let faces = [ServedFace { coverage: coverage_of(ARABIC), ..served("Noto Sans Arabic", "Regular", &["Arab"], ARABIC_URL, 0) }];
|
||||
let fetch = Arc::new(FakeFetch::default());
|
||||
let (ctx, mut draws) = web_context_with("en", &faces, &fetch);
|
||||
assert!(!draws('ع'));
|
||||
assert_eq!(fetch.requested(), [ARABIC_URL]);
|
||||
fetch.answer(ARABIC_URL, Ok(ARABIC));
|
||||
assert!(draws('ع'));
|
||||
|
||||
web_fonts("ru", &faces).fetcher(Arc::clone(&fetch) as Arc<dyn FontFetcher>).install(&ctx);
|
||||
assert!(draws('ع'), "the fetched face is installed again");
|
||||
assert!(fetch.requested().is_empty(), "nothing is fetched again");
|
||||
}
|
||||
|
||||
/// Of two served faces that draw Han, the interface language's comes first in the proportional chain, whichever was
|
||||
/// fetched first.
|
||||
#[trial]
|
||||
fn the_interface_languages_served_face_leads() {
|
||||
const JP_URL: &str = "fonts/noto-sans-cjk-jp/NotoSansCJKjp.otf";
|
||||
const SC_URL: &str = "fonts/noto-sans-cjk-sc/NotoSansCJKsc.otf";
|
||||
let han = (0x4E00, 0x9FFF);
|
||||
let faces = [
|
||||
ServedFace {
|
||||
coverage: craft_fonts_build::coverage::encode(&[(0x3040, 0x30FF), han]).leak(),
|
||||
..served("Noto Sans CJK JP", "Regular", &["Jpan"], JP_URL, 0)
|
||||
},
|
||||
ServedFace { coverage: craft_fonts_build::coverage::encode(&[han]).leak(), ..served("Noto Sans CJK SC", "Regular", &["Hans"], SC_URL, 0) },
|
||||
];
|
||||
let fetch = Arc::new(FakeFetch::default());
|
||||
let (ctx, mut draws) = web_context_with("zh-CN", &faces, &fetch);
|
||||
// Kana only the Japanese face covers, and Han, which the Simplified Chinese face draws first in this UI.
|
||||
draws('あ');
|
||||
draws('中');
|
||||
let mut asked = fetch.requested();
|
||||
asked.sort_unstable();
|
||||
assert_eq!(asked, [JP_URL, SC_URL], "kana asks for the Japanese face, Han for the Simplified Chinese one");
|
||||
// The Japanese face arrives first.
|
||||
fetch.answer(JP_URL, Ok(NOTO_SANS_LATIN));
|
||||
draws('あ');
|
||||
fetch.answer(SC_URL, Ok(include_bytes!("../../fonts/NotoSansCJKsc-test.otf")));
|
||||
draws('中');
|
||||
let chain = ctx.fonts(|f| f.definitions().families[&FontFamily::Proportional].clone());
|
||||
let at = |name: &str| chain.iter().position(|face| face == name).unwrap_or_else(|| panic!("{name} is in the chain: {chain:?}"));
|
||||
assert!(at("Noto Sans CJK SC Regular") < at("Noto Sans CJK JP Regular"), "the interface language's face leads: {chain:?}");
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! `runtime::windows`: the input hook per viewport, window info per viewport, the press release after an OS
|
||||
//! resize (H4), the raise of a modal's window, the mount of a full-window container, the size of a content-sized
|
||||
//! window, the app id of child windows, injected keys across a focus loss, non-finite injected points, the window
|
||||
//! that has the keys, and `act`.
|
||||
//! resize (H4), the raise of a modal's window, the mount of a full-window container (in a window of its own, or in a
|
||||
//! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows,
|
||||
//! injected keys across a focus loss, non-finite injected points, the window that has the keys, and `act`.
|
||||
|
||||
use craft_behavior::{Cursor, CursorIcon, PointerButton};
|
||||
use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind};
|
||||
@@ -141,6 +141,24 @@ fn a_blocking_modal_is_raised_when_the_main_window_gains_focus() {
|
||||
windows.root_info(focus(true));
|
||||
assert!(raised_child(&modal_frame(&windows)), "the main window gained focus: the modal's window is raised");
|
||||
assert!(!raised_child(&modal_frame(&windows)), "the main window keeps focus: nothing more is raised");
|
||||
|
||||
// A full-window dialog in a window of its own (the Camera Raw form) is raised the same way.
|
||||
let windows = Windows::new();
|
||||
let frame = || {
|
||||
windows.frame(vec![], vec![], |ui| {
|
||||
Palette::full_window("Workspace").show(ui, |_, _| {});
|
||||
})
|
||||
};
|
||||
windows.root_info(focus(false));
|
||||
let mut out = None;
|
||||
for _ in 0..4 {
|
||||
out = Some(frame());
|
||||
}
|
||||
let (dialog, _) = builder_titled(&out.expect("the frames ran"), "Workspace");
|
||||
let raised = |out: &Out| out.commands.iter().any(|(id, command)| *id == dialog && *command == ViewportCommand::Minimized(false));
|
||||
assert!(!raised(&frame()), "the main window stays unfocused: the dialog's window is not raised");
|
||||
windows.root_info(focus(true));
|
||||
assert!(raised(&frame()), "the main window gained focus: the dialog's window is raised");
|
||||
}
|
||||
|
||||
/// A container mounted in an OS viewport that opens as `spec`, with a body the trial gives it.
|
||||
@@ -264,6 +282,59 @@ fn a_full_window_viewport_fills_the_main_window_without_viewports_and_opens_its_
|
||||
assert_eq!(shown.and_then(|key| tree.bounds_of(key)), Some(content.get()), "the workspace covers the main window");
|
||||
}
|
||||
|
||||
/// FW3: a viewport mount opened from a full-screen window, or from a maximized one on Wayland, shows in that window
|
||||
/// instead of a window of its own: a window opened over it would cover it, the compositor would send it no frames, and
|
||||
/// the dialog drawn inside them would freeze. A main window that goes full screen under an open dialog takes the dialog
|
||||
/// in, and the dialog stays open.
|
||||
#[trial]
|
||||
fn a_viewport_mount_stays_in_a_full_screen_or_wayland_maximized_window() {
|
||||
let state = |fullscreen: bool, maximized: bool| ViewportInfo { fullscreen: Some(fullscreen), maximized: Some(maximized), ..ViewportInfo::default() };
|
||||
let frame = |windows: &Windows| {
|
||||
windows.frame(vec![], vec![], |ui| {
|
||||
Palette::full_window("Workspace").show(ui, |_, _| {});
|
||||
})
|
||||
};
|
||||
let own_window = |out: &Out| out.builders.iter().any(|(_, builder)| builder.title.as_deref() == Some("Workspace"));
|
||||
let in_root = |out: &Out| {
|
||||
out.trees.iter().rfind(|(id, _)| *id == ViewportId::ROOT).is_some_and(|(_, tree)| {
|
||||
tree.keys().into_iter().any(|key| tree.role_of(key) == Some(Role::GROUP) && tree.name_of(key) == Some("Workspace"))
|
||||
})
|
||||
};
|
||||
let cases = [
|
||||
(Backend::X11, false, false, true),
|
||||
(Backend::X11, true, false, false),
|
||||
(Backend::X11, false, true, true),
|
||||
(Backend::Wayland, false, false, true),
|
||||
(Backend::Wayland, true, false, false),
|
||||
(Backend::Wayland, false, true, false),
|
||||
];
|
||||
for (backend, fullscreen, maximized, own) in cases {
|
||||
let windows = Windows::with(InstallSpec::new(ShellInfo::default().backend(backend), Arc::new(FakeSystem::new())));
|
||||
windows.root_info(state(fullscreen, maximized));
|
||||
let mut out = None;
|
||||
for _ in 0..4 {
|
||||
out = Some(frame(&windows));
|
||||
}
|
||||
let out = out.expect("the frames ran");
|
||||
let case = format!("{backend:?}, full screen {fullscreen}, maximized {maximized}");
|
||||
assert_eq!(own_window(&out), own, "{case}: a window of its own");
|
||||
assert_eq!(in_root(&out), !own, "{case}: shown in the main window");
|
||||
}
|
||||
|
||||
let windows = Windows::with(InstallSpec::new(ShellInfo::default().backend(Backend::X11), Arc::new(FakeSystem::new())));
|
||||
for _ in 0..4 {
|
||||
frame(&windows);
|
||||
}
|
||||
assert!(own_window(&frame(&windows)), "a normal main window: the dialog opens its own window");
|
||||
windows.root_info(state(true, false));
|
||||
let mut out = None;
|
||||
for _ in 0..4 {
|
||||
out = Some(frame(&windows));
|
||||
}
|
||||
let out = out.expect("the frames ran");
|
||||
assert!(!own_window(&out) && in_root(&out), "the main window went full screen: the dialog shows in it and is still open");
|
||||
}
|
||||
|
||||
/// A window sized by its content sends no size before it has reported its place, so it never opens at what its body
|
||||
/// took in room the OS has not given; once it has reported, it takes its content's size.
|
||||
#[trial]
|
||||
|
||||
@@ -512,7 +512,7 @@ impl ExportPreview {
|
||||
pub struct ExportAsResult {
|
||||
/// The settings the user confirmed.
|
||||
pub options: ExportOptions,
|
||||
/// The file the user chose to write.
|
||||
/// The file the user chose to write; the folder when the export writes more than one file.
|
||||
pub path: PathBuf,
|
||||
/// The output size in pixels.
|
||||
pub size: PixelSize,
|
||||
@@ -570,13 +570,12 @@ impl<T: Clone + PartialEq> Revisions<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A file name safe on every platform: at most 80 characters, control characters and `< > : " / \ | ? *` replaced by
|
||||
/// `_`, leading and trailing dots and spaces trimmed; empty becomes `fallback` ("layer" for per-layer exports, the
|
||||
/// document name otherwise).
|
||||
/// The file name a save dialog suggests for `name`: each control character and each character a file name can't hold
|
||||
/// (`< > : " / \ | ? *`) turned into `_`, at most 80 characters; spaces and dots at the ends stay as the name holds
|
||||
/// them. `fallback` for a name of nothing but whitespace and dots.
|
||||
pub(crate) fn export_file_name(name: &str, fallback: &str) -> String {
|
||||
let name: String = name.chars().take(MAX_NAME_CHARS).map(|c| if c.is_control() || RESERVED.contains(c) { '_' } else { c }).collect();
|
||||
let name = name.trim().trim_matches('.');
|
||||
if name.is_empty() { fallback.to_owned() } else { name.to_owned() }
|
||||
if name.chars().all(|c| c.is_whitespace() || c == '.') { fallback.to_owned() } else { name }
|
||||
}
|
||||
|
||||
const MAX_NAME_CHARS: usize = 80;
|
||||
|
||||
@@ -123,7 +123,8 @@ impl Outcome for ExportAsOutput {
|
||||
/// turns Cancel into Reset, which restores the settings the dialog opened with. Export asks the app for a file
|
||||
/// to write (`ExportAsOutput::requests`), or a folder with more than one Scale All row, and the dialog stays open
|
||||
/// until the app answers with the path. Without [`folder_export`](ExportAsDialog::folder_export), more than one row
|
||||
/// refuses Export with a note.
|
||||
/// refuses Export with a note. An export of several files ([`files`](ExportAsDialog::files)) asks for a folder
|
||||
/// too where the app can write one.
|
||||
/// - Settings: the dialog opens on the value in the bind, fitted to the document, and writes its edits back.
|
||||
/// - Previews: whenever the settings change, `wanted_preview` carries a new revision. The app encodes a proxy and
|
||||
/// gives it back with `preview`; a size estimate shows at once ("≈ 1.2 MB"), and the app may follow with an exact
|
||||
@@ -173,6 +174,10 @@ pub struct ExportAsDialog<'a> {
|
||||
/// whose file dialog answers no folder (the browser) sets it off.
|
||||
#[prop]
|
||||
folder_export: bool,
|
||||
/// How many files the export writes before Scale All, one per exportable layer of a layer export; the default is
|
||||
/// 1. With more than one and [`folder_export`](ExportAsDialog::folder_export), Export asks for a folder.
|
||||
#[prop]
|
||||
files: usize,
|
||||
}
|
||||
|
||||
impl<'a> ExportAsDialog<'a> {
|
||||
@@ -194,6 +199,7 @@ impl<'a> ExportAsDialog<'a> {
|
||||
remember: None,
|
||||
opening: None,
|
||||
folder_export: true,
|
||||
files: 1,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,6 +221,7 @@ impl<'a> ExportAsDialog<'a> {
|
||||
remember,
|
||||
opening,
|
||||
folder_export,
|
||||
files,
|
||||
} = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<ExportWords>();
|
||||
@@ -287,7 +294,7 @@ impl<'a> ExportAsDialog<'a> {
|
||||
if reset.pick(picked) == Some(ResetPick::Accept)
|
||||
&& let Some(options) = &latest
|
||||
{
|
||||
requests.request_path(save_request(&formats, options, &file_name, &words));
|
||||
requests.request_path(save_request(&formats, options, &file_name, folder_export && files > 1, &words));
|
||||
}
|
||||
let result = accepted.zip(answered.into_inner()).map(|(options, path)| answer_of(options, source, path, remember));
|
||||
let events = events.into_inner();
|
||||
@@ -301,9 +308,9 @@ impl<'a> ExportAsDialog<'a> {
|
||||
}
|
||||
|
||||
/// The save dialog Export asks for: the document's name with the format's extension and filter; a folder for more than
|
||||
/// one Scale All row.
|
||||
fn save_request(formats: &[ExportFormat], options: &ExportOptions, file_name: &str, words: &ExportWords) -> PathRequest {
|
||||
if options.scale_all.len() > 1 {
|
||||
/// one Scale All row, or when `several_files` (a layer export of more than one layer, where the app writes a folder).
|
||||
fn save_request(formats: &[ExportFormat], options: &ExportOptions, file_name: &str, several_files: bool, words: &ExportWords) -> PathRequest {
|
||||
if options.scale_all.len() > 1 || several_files {
|
||||
return PathRequest::new(SAVE_KEY, PathKind::Folder);
|
||||
}
|
||||
let format = formats.iter().find(|format| format.id == options.format);
|
||||
@@ -360,6 +367,7 @@ pub struct HostedExportAs {
|
||||
/// The path the host's save dialog answered, or automation set; Export finishes with it.
|
||||
path: Option<PathBuf>,
|
||||
folder_export: bool,
|
||||
files: usize,
|
||||
#[cfg(feature = "testing")]
|
||||
facts: crate::testing::StoryOutput,
|
||||
}
|
||||
@@ -414,6 +422,7 @@ impl HostedExportAs {
|
||||
remember: None,
|
||||
path: None,
|
||||
folder_export: true,
|
||||
files: 1,
|
||||
#[cfg(feature = "testing")]
|
||||
facts: crate::testing::StoryOutput::default(),
|
||||
}
|
||||
@@ -426,6 +435,13 @@ impl HostedExportAs {
|
||||
self
|
||||
}
|
||||
|
||||
/// How many files the export writes before Scale All ([`ExportAsDialog::files`]).
|
||||
#[must_use]
|
||||
pub fn files(mut self, count: usize) -> Self {
|
||||
self.files = count;
|
||||
self
|
||||
}
|
||||
|
||||
/// The formats the list offers.
|
||||
#[must_use]
|
||||
pub fn formats(mut self, formats: Vec<ExportFormat>) -> Self {
|
||||
@@ -505,7 +521,8 @@ impl StackDialog for HostedExportAs {
|
||||
let Some(path) = self.path.clone() else {
|
||||
if !self.saving {
|
||||
let words = Env::of_root(ctx).words::<ExportWords>();
|
||||
self.requests.request_path(save_request(&self.formats, &self.options, &self.file_name, &words));
|
||||
let several_files = self.folder_export && self.files > 1;
|
||||
self.requests.request_path(save_request(&self.formats, &self.options, &self.file_name, several_files, &words));
|
||||
self.saving = true;
|
||||
}
|
||||
return None;
|
||||
@@ -563,6 +580,7 @@ impl StackDialog for HostedExportAs {
|
||||
remember: self.remember.clone(),
|
||||
opening: Some(self.opening.clone()),
|
||||
folder_export: self.folder_export,
|
||||
files: self.files,
|
||||
..ExportAsDialog::new(self.file_name.clone(), self.source, Bind::bound(&mut self.options))
|
||||
};
|
||||
let mut shown = dialog.show(ui);
|
||||
|
||||
@@ -5,7 +5,7 @@ use craft_ui::contract::{Bind, Role, SaveKey};
|
||||
use craft_ui::dialog::{DialogHost, DialogResult, StackDialog};
|
||||
use craft_ui::patterns::form_dialogs::{
|
||||
ExportAsDialog, ExportAsResult, ExportOptions, ExportOptionsKind, ExportSize, FormatOptions, FormatOptionsDialog, HostedExportAs,
|
||||
HostedFormatOptions, JpegOptions, OutputPathRow, Resample, SizeEstimate,
|
||||
HostedFormatOptions, JpegOptions, OutputPathRow, Resample, ScaleRow, ScaleSize, SizeEstimate,
|
||||
};
|
||||
use craft_ui::runtime::requests::PathRequest;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
@@ -38,13 +38,16 @@ fn requested_file(name: &str) -> String {
|
||||
filed.file_name.expect("the request names a file")
|
||||
}
|
||||
|
||||
/// The default file name is the document's, made safe on every platform: reserved characters become underscores, dots and
|
||||
/// spaces at the ends go, and a name with nothing left is Untitled.
|
||||
/// The suggested file name is the document's with what no file name holds turned into underscores; spaces and dots
|
||||
/// at its ends stay, as production PhotoCraft keeps them, and a name of nothing but spaces and dots is Untitled.
|
||||
#[trial]
|
||||
fn the_default_file_name_is_made_safe() {
|
||||
fn the_suggested_file_name_keeps_its_ends_and_drops_what_no_file_name_holds() {
|
||||
assert_eq!(requested_file("Poster"), "Poster.png");
|
||||
assert_eq!(requested_file(" ..My: poster/v2?.. "), "My_ poster_v2_.png");
|
||||
assert_eq!(requested_file(" Artboard 1 "), " Artboard 1 .png");
|
||||
assert_eq!(requested_file(" a/b "), " a_b .png");
|
||||
assert_eq!(requested_file("a/b:c*?"), "a_b_c__.png");
|
||||
assert_eq!(requested_file(" . "), "Untitled.png");
|
||||
assert_eq!(requested_file("..."), "Untitled.png");
|
||||
let long = "x".repeat(100);
|
||||
assert_eq!(requested_file(&long).len(), 80 + ".png".len(), "at most 80 characters");
|
||||
}
|
||||
@@ -259,7 +262,8 @@ fn export_as_starts_from_its_remembered_options_and_stores_the_confirmed_ones()
|
||||
let shown = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
|
||||
fixture.room(Vec2::new(1400.0, 1000.0));
|
||||
let jpeg = options("jpg", 40);
|
||||
let mut jpeg = options("jpg", 40);
|
||||
jpeg.scale_all = vec![ScaleRow::default(), ScaleRow::new(ScaleSize::X2, "@2x")];
|
||||
|
||||
let first = export_from(&host, &mut fixture, jpeg.clone());
|
||||
assert_eq!(first.options.format, "jpg", "nothing stored: the dialog exports what it was given");
|
||||
@@ -268,11 +272,13 @@ fn export_as_starts_from_its_remembered_options_and_stores_the_confirmed_ones()
|
||||
first.remember(fixture.ctx());
|
||||
let reopened = opened_with(&host, &mut fixture, ExportOptions::default());
|
||||
assert_eq!((reopened.format.as_str(), reopened.quality), ("jpg", 40), "the stored options replace the given ones at open");
|
||||
assert_eq!(reopened.scale_all, jpeg.scale_all, "the stored Scale All rows come back with them");
|
||||
|
||||
let webp = options("webp", 55);
|
||||
let _unstored = export_from(&host, &mut fixture, webp);
|
||||
let again = opened_with(&host, &mut fixture, ExportOptions::default());
|
||||
assert_eq!((again.format.as_str(), again.quality), ("jpg", 40), "a result not stored leaves the stored options as they were");
|
||||
assert_eq!(again.scale_all, jpeg.scale_all, "and their Scale All rows");
|
||||
}
|
||||
|
||||
/// Export As with the app's resample methods offers no other: an unlisted opening method opens as the first listed
|
||||
|
||||
@@ -314,6 +314,67 @@ fn export_as_writes_one_file_per_scale_all_row_and_only_from_its_button() {
|
||||
assert!(pick(&host).is_none() && !host.borrow_mut().confirm::<HostedExportAs>(&ctx), "without a folder two rows refuse Export");
|
||||
}
|
||||
|
||||
/// A layer export of several files asks for a folder where the app can write one, the browser's build keeps the save
|
||||
/// request, and an export of one file asks for that file by name.
|
||||
#[trial]
|
||||
fn an_export_of_several_files_asks_for_a_folder() {
|
||||
use craft_ui::runtime::requests::PathKind;
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let mut fixture = fixture(&host);
|
||||
let pick = |host: &Rc<RefCell<DialogHost>>| host.borrow_mut().get_mut::<HostedExportAs>().and_then(HostedExportAs::pick_path);
|
||||
for (files, folder_export, folder) in [(2, true, true), (2, false, false), (1, true, false)] {
|
||||
host.borrow_mut().open(HostedExportAs::new("Poster", PICTURE, ExportOptions::default()).files(files).folder_export(folder_export));
|
||||
fixture.idle(10);
|
||||
let export = fixture.by_label("Export…").expect("the Export button");
|
||||
fixture.click(&export).idle(4);
|
||||
let request = pick(&host).expect("Export asks where to write");
|
||||
let case = format!("{files} files, folder export {folder_export}");
|
||||
assert_eq!(matches!(request.kind, PathKind::Folder), folder, "{case}: a folder");
|
||||
if !folder {
|
||||
assert_eq!(request.file_name.as_deref(), Some("Poster.png"), "{case}: the file is named");
|
||||
}
|
||||
fixture.key(Key::Escape, Modifiers::NONE).idle(4);
|
||||
assert!(host.borrow().is_empty(), "{case}: Escape cancels");
|
||||
}
|
||||
}
|
||||
|
||||
/// Enter in a field of Export As commits that field and leaves the dialog open. + adds sizes in their order up to the
|
||||
/// row limit, then is disabled, and a suffix is cut at its limit.
|
||||
#[trial]
|
||||
fn export_as_keeps_scale_all_within_its_limits_and_enter_in_a_field_only_commits_it() {
|
||||
use craft_ui::patterns::form_dialogs::{ScaleRow, ScaleSize};
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let mut fixture = fixture(&host);
|
||||
host.borrow_mut().open(HostedExportAs::new("Poster", PICTURE, ExportOptions::default()));
|
||||
fixture.idle(10);
|
||||
let options = |host: &Rc<RefCell<DialogHost>>| host.borrow().get::<HostedExportAs>().map(|dialog| dialog.options().clone()).expect("open");
|
||||
|
||||
let scale = fixture.by_label("Scale").expect("the Scale field");
|
||||
fixture.click(&scale).idle(2);
|
||||
fixture.key(Key::A, Modifiers::COMMAND).type_text("50");
|
||||
fixture.key(Key::Enter, Modifiers::NONE).idle(4);
|
||||
assert!(host.borrow().is_open::<HostedExportAs>(), "Enter in the Scale field leaves the dialog open");
|
||||
assert_eq!(options(&host).output_size(PICTURE), PixelSize::new(800, 450), "Enter commits the field");
|
||||
|
||||
for _ in 1..ScaleRow::MAX_ROWS {
|
||||
let add = fixture.by_label("Add a size").expect("the + button");
|
||||
fixture.click(&add).idle(4);
|
||||
}
|
||||
let rows = options(&host).scale_rows();
|
||||
assert_eq!(rows.len(), ScaleRow::MAX_ROWS, "+ adds rows up to the limit");
|
||||
let added: Vec<ScaleSize> = rows.iter().skip(1).map(|row| row.size).collect();
|
||||
let order: Vec<ScaleSize> = ScaleSize::ADD_ORDER.iter().copied().filter(|size| *size != rows[0].size).take(added.len()).collect();
|
||||
assert_eq!(added, order, "+ adds the sizes in their order");
|
||||
let add = fixture.by_label("Add a size").expect("the + button");
|
||||
assert!(fixture.tree().is_disabled_key(add.node), "+ is disabled at the limit");
|
||||
|
||||
let suffix = fixture.by_label("Suffix 2").expect("the second row's suffix");
|
||||
fixture.click(&suffix).idle(2);
|
||||
fixture.key(Key::A, Modifiers::COMMAND).type_text(&"s".repeat(ScaleRow::MAX_SUFFIX + 10));
|
||||
fixture.key(Key::Tab, Modifiers::NONE).idle(4);
|
||||
assert_eq!(options(&host).scale_rows()[1].suffix.chars().count(), ScaleRow::MAX_SUFFIX, "a suffix is cut at its limit");
|
||||
}
|
||||
|
||||
/// Image Size's readout counts the flat image in whole-byte rows (a Bitmap row of 9 pixels takes 2 bytes) and says
|
||||
/// "(was …)" only once the pixel size differs from the document's.
|
||||
#[trial]
|
||||
|
||||
@@ -36,7 +36,7 @@ craft-i18n = { workspace = true, features = ["collate"] }
|
||||
# The saved forms of `ScreenMode`, `RecentView` and `RecentSort`.
|
||||
serde = { workspace = true }
|
||||
# The caption button icons.
|
||||
resvg = { version = "0.45.1", default-features = false }
|
||||
craft-svg = { workspace = true, features = ["draw"] }
|
||||
# `std::time::Instant` on native; the browser clock on wasm, where `Instant::now` panics.
|
||||
web-time = "1.1"
|
||||
|
||||
|
||||
@@ -137,10 +137,13 @@ fn theme_files(_theme: &str) -> [Option<Arc<[u8]>>; 4] {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Bytes drawing one caption icon may allocate, its target included.
|
||||
const MASK_DRAW_BUDGET: u64 = 64 << 20;
|
||||
|
||||
/// An SVG's coverage (alpha) as a `px` x `px` mask, the drawing fitted and centred. `None` for an unreadable SVG or
|
||||
/// an absurd size.
|
||||
fn rasterize_mask(svg: &[u8], px: u32) -> Option<CaptionMask> {
|
||||
use resvg::tiny_skia;
|
||||
use craft_svg::tree::draw::{self, tiny_skia};
|
||||
if !(1..=MAX_MASK_SIDE).contains(&px) {
|
||||
return None;
|
||||
}
|
||||
@@ -155,8 +158,8 @@ fn rasterize_mask(svg: &[u8], px: u32) -> Option<CaptionMask> {
|
||||
}
|
||||
let scale = px as f32 / side;
|
||||
let (dx, dy) = ((px as f32 - size.width() * scale) / 2.0, (px as f32 - size.height() * scale) / 2.0);
|
||||
let mut pixmap = tiny_skia::Pixmap::new(px, px)?;
|
||||
resvg::render(&tree, tiny_skia::Transform::from_scale(scale, scale).post_translate(dx, dy), &mut pixmap.as_mut());
|
||||
let transform = tiny_skia::Transform::from_scale(scale, scale).post_translate(dx, dy);
|
||||
let pixmap = draw::render(&tree, transform, px, px, 0, MASK_DRAW_BUDGET).ok()?;
|
||||
Some(pixmap.data().as_chunks::<4>().0.iter().map(|[_, _, _, a]| *a).collect())
|
||||
}))
|
||||
.ok()
|
||||
|
||||
@@ -29,6 +29,15 @@ fn hostile_svgs_render_nothing() {
|
||||
assert!(mask_of(image.as_bytes(), GLYPH_PX).is_some_and(|mask| mask.iter().all(|coverage| *coverage == 0)), "nothing drawn");
|
||||
}
|
||||
|
||||
/// Icons parse on the UI thread: a document nested deeper than its stack takes is refused, not a stack overflow.
|
||||
#[trial]
|
||||
fn an_icon_nested_past_its_depth_is_refused_not_a_crash() {
|
||||
let deep = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">{}<path d="M4 4h8v8H4z"/>{}</svg>"#, "<g>".repeat(200), "</g>".repeat(200));
|
||||
assert!(mask_of(deep.as_bytes(), GLYPH_PX).is_none());
|
||||
let shallow = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">{}<path d="M4 4h8v8H4z"/>{}</svg>"#, "<g>".repeat(8), "</g>".repeat(8));
|
||||
assert!(mask_of(shallow.as_bytes(), GLYPH_PX).is_some_and(|mask| mask.iter().any(|coverage| *coverage > 0)), "a shallow icon draws");
|
||||
}
|
||||
|
||||
/// A glyph is a square coverage mask of the drawing, fitted to the asked side; the glyphs a theme lacks have none.
|
||||
#[trial]
|
||||
fn masks_are_square_coverage() {
|
||||
|
||||
Reference in New Issue
Block a user