Merge branch 'main' into fix/ui-perf-1-floating-windows

This commit is contained in:
FredApps authored and GitHub committed 2026-11-28 22:02:54 +01:00
commit e058e4d58e
57 files changed
+1620 -244

No files matched your search

+8
View File
@@ -257,3 +257,11 @@ pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]>
}
out
}
/// What `f` gives, and how many paragraph ends the reader looked up on this thread while it ran
/// to give each character run its paragraph's format.
pub fn count_paragraph_lookups<T>(f: impl FnOnce() -> T) -> (T, usize) {
crate::text::MATCH_READS.with(|reads| reads.set(0));
let value = f();
(value, crate::text::MATCH_READS.with(std::cell::Cell::get))
}
+28 -2
View File
@@ -240,12 +240,26 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
// Sorted by end (they are in order in every file), so both lookups below are binary
// searches: a block can have as many paragraphs and runs as characters.
paragraphs.sort_by_key(|(end, _)| *end);
let align_at = |i: usize| paragraphs.get(paragraphs.partition_point(|(end, _)| *end <= i)).map(|(_, a)| *a).or(open).unwrap_or_default();
let align_at = |i: usize| {
let at = paragraphs.partition_point(|(end, _)| {
count_match_read();
*end <= i
});
paragraphs.get(at).map(|(_, a)| *a).or(open).unwrap_or_default()
};
let mut cuts: Vec<usize> = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect();
cuts.dedup();
let push = |r: &mut Reader, runs: &mut Vec<TextRun>, attrs: Option<ObjId>, from: usize, to: usize, budget: &mut Option<usize>| {
// Split at paragraph ends so every run has one paragraph format.
let inside = cuts.get(cuts.partition_point(|c| *c <= from)..cuts.partition_point(|c| *c < to)).unwrap_or_default();
let first = cuts.partition_point(|c| {
count_match_read();
*c <= from
});
let past = cuts.partition_point(|c| {
count_match_read();
*c < to
});
let inside = cuts.get(first..past).unwrap_or_default();
let mut a = from;
for &c in inside.iter().chain(std::iter::once(&to)) {
push_run(r, runs, attrs, characters(&chars, a, c), world, budget, align_at(a));
@@ -282,6 +296,18 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
(runs, first_align.unwrap_or(Align::Left))
}
// Each paragraph end `story_runs` reads to match character runs to paragraphs, on this thread.
#[cfg(any(test, feature = "synth"))]
std::thread_local! {
pub(crate) static MATCH_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[inline]
fn count_match_read() {
#[cfg(any(test, feature = "synth"))]
MATCH_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
}
fn characters(chars: &[char], start: usize, end: usize) -> String {
chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect()
}
+26 -19
View File
@@ -111,25 +111,32 @@ fn a_shared_story_is_read_within_the_characters_of_one_document() {
#[test]
fn many_paragraphs_and_runs_are_matched_in_about_linear_time() {
// 200 000 paragraphs, each with its own run and format.
let n = 200_000;
let text = "a\u{2029}".repeat(n);
let fmt =
|end: usize| vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))];
let blk = F::Obj(
tag(b"StBl"),
vec![
(tag(b"Glyp"), utf8(&text)),
(tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])),
(tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])),
],
);
let started = std::time::Instant::now();
let d = open(vec![artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]))]);
let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") };
assert_eq!(t.runs.len(), n);
// (About half a second; quadratic matching took over half a minute on the same machine.)
assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
// `n` paragraphs, each with its own run and format, and how many paragraph ends matching
// them looks up.
let lookups = |n: usize| {
let text = "a\u{2029}".repeat(n);
let fmt = |end: usize| {
vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))]
};
let blk = F::Obj(
tag(b"StBl"),
vec![
(tag(b"Glyp"), utf8(&text)),
(tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])),
(tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])),
],
);
let story = artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]));
let (d, lookups) = synth::count_paragraph_lookups(|| open(vec![story]));
let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") };
assert_eq!(t.runs.len(), n);
lookups
};
// Four times the paragraphs and runs: a few binary searches each, so about four times the
// lookups (a little more for the longer searches), where matching each run against every
// paragraph is sixteen times.
let (quarter, full) = (lookups(50_000), lookups(200_000));
assert!(full <= 5 * quarter, "{quarter} lookups for 50,000 paragraphs, {full} for 200,000");
}
/// A shape node of `size` px.
+29 -6
View File
@@ -361,17 +361,35 @@ fn edge_index(t: &[f32], start: bool) -> f32 {
if start {
let v = t[0];
// The first value that differs, given they do so from there on.
let first_other = t.partition_point(|x| (*x - v).abs() <= 1e-7);
let first_other = t.partition_point(|x| {
count_edge_read();
(*x - v).abs() <= 1e-7
});
let i = if first_other >= n { n - 1 } else { first_other.saturating_sub(1) };
i as f32 / (n - 1) as f32
} else {
let v = t[n - 1];
// The start of the trailing run equal to the last value.
let i = t.partition_point(|x| (*x - v).abs() > 1e-7);
let i = t.partition_point(|x| {
count_edge_read();
(*x - v).abs() > 1e-7
});
i as f32 / (n - 1) as f32
}
}
// Each table entry `edge_index` reads on this thread.
#[cfg(test)]
std::thread_local! {
static EDGE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[inline]
fn count_edge_read() {
#[cfg(test)]
EDGE_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
}
#[cfg(test)]
mod tests {
use super::*;
@@ -381,13 +399,18 @@ mod tests {
// Four million zeros and a one: a scan per call would be 8·10¹¹ steps for these calls.
let mut t = vec![0.0f32; 4_000_000];
t.push(1.0);
// Bisection reads one entry per halving of the table, and a scan reads the whole run.
let per_call = t.len().ilog2() as usize + 2;
let c = Curve::Table(t);
let started = std::time::Instant::now();
let mut last = 0.0;
for _ in 0..200_000 {
EDGE_READS.with(|reads| reads.set(0));
let mut last = c.eval_inverse(0.0);
let one_call = EDGE_READS.with(std::cell::Cell::get);
assert!(one_call <= per_call, "one inversion read {one_call} entries");
for _ in 1..200_000 {
last = c.eval_inverse(0.0);
}
assert!(last > 0.99, "the flat start ends at the last zero: {last}");
assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
let total = EDGE_READS.with(std::cell::Cell::get);
assert!(total <= 200_000 * per_call, "200,000 inversions read {total} entries");
}
}
+2 -2
View File
@@ -74,8 +74,8 @@ pub use panel::{
ColorPanelShown, ColorPanelState, ColorPanelWords, PanelTarget, TintRow,
};
pub use picker::{
ChannelRow, ChannelRule, ChannelUnit, ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, PickedColor,
ScreenPickGesture, TrackRamp,
ChannelRow, ChannelRowOutput, ChannelRule, ChannelUnit, ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords,
PickedColor, ScreenPickGesture, TrackRamp,
};
pub use picker_dialog::{
ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickerLibrary,
+50 -9
View File
@@ -245,7 +245,8 @@ pub struct ColorPanelState {
pub hide_options: bool,
/// The FillStroke layout shows the Recent Colors slot.
pub recent_colors: bool,
/// The R, G and B rows count percents, 0 to 100, in place of 0 to 255.
/// The R, G and B rows count percents, 0 to 100, in place of 0 to 255; Web Color's rows keep 0 to 255. A double
/// click on a units cell ([`ColorPanel::rgb_units_cell`]) switches it.
pub rgb_percent: bool,
}
@@ -446,6 +447,7 @@ pub struct ColorPanel<'a> {
cmyk: Option<&'a CmykConverter>,
rgb: Option<&'a dyn ColorModel>,
dynamic: bool,
rgb_units: bool,
layout: ColorPanelLayout,
wells: Option<([PairWell; 2], Bind<'a, Well>)>,
buttons: Option<[Label; 2]>,
@@ -490,6 +492,7 @@ impl<'a> ColorPanel<'a> {
cmyk: None,
rgb: None,
dynamic: true,
rgb_units: false,
layout: ColorPanelLayout::default(),
wells: None,
buttons: None,
@@ -523,6 +526,14 @@ impl<'a> ColorPanel<'a> {
self
}
/// A units cell right of each R, G and B field (not Web Color's): a double click on it switches
/// [`ColorPanelState::rgb_percent`]. The cell has no keyboard stop, so a host that turns it on offers the same
/// switch as a command that writes `rgb_percent`. Off by default.
pub fn rgb_units_cell(mut self, on: bool) -> Self {
self.rgb_units = on;
self
}
/// How the panel arranges its body; the Photoshop foreground and background arrangement by default.
pub fn layout(mut self, layout: ColorPanelLayout) -> Self {
self.layout = layout;
@@ -589,8 +600,23 @@ impl<'a> ColorPanel<'a> {
/// Shows the panel and returns this pass's edits and requests.
pub fn show(self, ui: &mut Ui) -> ColorPanelOutput {
let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_models, recent_setup, gamut } =
self;
let ColorPanel {
state,
colors,
cmyk,
rgb,
dynamic,
rgb_units,
layout,
wells,
buttons,
edited,
shown: rows,
recent,
recent_models,
recent_setup,
gamut,
} = self;
let env = Env::of(ui);
let (words, dialog) = (env.words::<ColorPanelWords>(), env.words::<ColorPickerDialogWords>());
let mut held = Held::new(state);
@@ -622,6 +648,7 @@ impl<'a> ColorPanel<'a> {
rgb,
gamut: &gamut,
dynamic,
rgb_units,
words: &words,
dialog: &dialog,
inputs: Inputs {
@@ -922,6 +949,8 @@ struct Body<'a> {
rgb: &'a dyn ColorModel,
gamut: &'a Gamut<'a>,
dynamic: bool,
/// The R, G and B rows have units cells ([`ColorPanel::rgb_units_cell`]).
rgb_units: bool,
words: &'a ColorPanelWords,
dialog: &'a ColorPickerDialogWords,
/// The state as this pass leaves it.
@@ -1173,15 +1202,18 @@ impl Body<'_> {
self.kept.tracks.retain(|(id, target, _)| (*id, *target) != slot);
self.kept.tracks.push((slot.0, slot.1, current));
}
// The R, G and B rows are not Web Color's. The units are read once, so a double click on one units cell
// switches all three rows together, from the next pass.
let rgb = !web && model.id() == self.rgb.id();
let rgb_percent = self.now.rgb_percent;
for (i, ch) in model.channels().iter().enumerate() {
let mut rule = ChannelRule::of(ch);
if web {
rule.step = WEB_STEP;
}
// The R, G and B rows count percents of the channel's range; an edit goes back through `scale`.
// PLAN: a double click on the units cell flips `rgb_percent` while the rows are enabled; `ChannelRow`
// (color-w2) reports no signal for its units cell, so the panel cannot read it.
let percent = self.now.rgb_percent && model.id() == self.rgb.id();
// With `rgb_percent` the R, G and B rows count percents of the channel's range; an edit goes back through
// `scale`.
let percent = rgb && rgb_percent;
let scale = if percent { 100.0 / *rule.range.end() } else { 1.0 };
let unit = if percent { ChannelUnit::Percent } else { ChannelUnit::of(ch.unit) };
if percent {
@@ -1197,8 +1229,17 @@ impl Body<'_> {
// The field shows the channel's places, as Photoshop's; the edits start from the unrounded values.
let places = 10f64.powi(i32::from(rule.decimals));
let shown = (f64::from(current.values[i]) * scale * places).round() / places;
let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(shown), rule).short(ch.label).unit(unit).track(track).show(ui);
for event in row.into_iter().flat_map(|row| row.events) {
let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(shown), rule).short(ch.label).unit(unit).track(track);
let edit = if rgb && self.rgb_units {
let row = row.show_with_units(ui);
if row.units_double_clicked {
self.now.rgb_percent = !rgb_percent;
}
row.edit
} else {
row.show(ui)
};
for event in edit.into_iter().flat_map(|row| row.events) {
self.channel_event(model, current, i, event.map(|x| x / scale));
}
}
+145 -14
View File
@@ -3,14 +3,18 @@
use std::ops::RangeInclusive;
use craft_behavior::{Axis, Sense};
use craft_behavior::press::MULTI_CLICK_TIME;
use craft_behavior::{Axis, Metrics, PartKey, PressPhase, Sense};
use craft_theme::{Channel, ColorModel, Srgba};
use craft_ui::contract::{
Bind, Common, Component, Cx, DisabledLook, EditResponse, GlyphLabel, LabelKind, MeasureCx, Role, Show as _, ShowContainer as _, SideLabel, Sizing,
Bind, Common, Component, Cx, DisabledLook, EditResponse, Gap, GlyphLabel, LabelKind, MeasureCx, NoValue, Outcome, PartsCx, Pointer as _, Role,
Show as _, ShowContainer as _, SideLabel, Sizing,
};
use craft_ui::form::{Field, SliderField, SliderFieldLayout};
use craft_ui::layout_components::Row;
use craft_ui::primitives::{PaintShape, StrokeWidth};
use craft_ui::runtime::env::{Label, UnitKind};
use craft_ui::runtime::pointer;
use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx};
use craft_ui::value_drag::{SliderThumb, TrackFace};
use egui::{Color32, CornerRadius, Ui, Vec2};
@@ -183,6 +187,15 @@ pub struct ChannelRow<'a> {
marks: &'a [f64],
}
/// What [`ChannelRow::show_with_units`] reports.
#[non_exhaustive]
pub struct ChannelRowOutput {
/// The edit of the slider or the field, `None` when the row did not run.
pub edit: Option<EditResponse<f64>>,
/// The units cell was double-clicked in this pass: the host switches the units the row counts in.
pub units_double_clicked: bool,
}
impl<'a> ChannelRow<'a> {
/// A row named `label` over `value`, ruled by `rule`.
pub fn new(label: impl Into<Label>, value: Bind<'a, f64>, rule: ChannelRule) -> Self {
@@ -223,22 +236,140 @@ impl<'a> ChannelRow<'a> {
/// Shows the row; the edit of the slider or the field, `None` when the row did not run.
pub fn show(self, ui: &mut Ui) -> Option<EditResponse<f64>> {
self.show_row(ui, false).edit
}
/// Shows the row with a blank units cell after the number field, for a row whose host can switch the units the
/// value counts in: the edit of the slider or the field, and whether the cell was double-clicked. The cell is
/// highlighted under the pointer and takes no keyboard focus, so the host offers the same switch as a command; in
/// a disabled container it does not report a double click. The slider gives up the cell's width, so the row keeps
/// its width.
pub fn show_with_units(self, ui: &mut Ui) -> ChannelRowOutput {
self.show_row(ui, true)
}
fn show_row(self, ui: &mut Ui, units_cell: bool) -> ChannelRowOutput {
let ChannelRow { label, short, mut value, rule, track, checker, unit, marks } = self;
let side = match short {
Some(short) => SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text(Label::from(short)))),
None => SideLabel::new(),
};
Field::new(label.clone())
.side(side.scrub(true))
.show(ui, |ui, _| {
channel_slider(label.clone(), value.reborrowed(), &rule, unit, track.clone().map(|stops| (stops, checker)))
.marks(marks)
.layout(SliderFieldLayout::Inline)
.field_sizing(Sizing::Content)
.thumb(SliderThumb::Triangle)
.show(ui)
.edit
})
.inner
let mut field = |ui: &mut Ui| {
Field::new(label.clone())
.side(side.clone().scrub(true))
.show(ui, |ui, _| {
channel_slider(label.clone(), value.reborrowed(), &rule, unit, track.clone().map(|stops| (stops, checker)))
.marks(marks)
.layout(SliderFieldLayout::Inline)
.field_sizing(Sizing::Content)
.thumb(SliderThumb::Triangle)
.show(ui)
.edit
})
.inner
};
if !units_cell {
return ChannelRowOutput { edit: field(ui), units_double_clicked: false };
}
let shown = Row::new().fill_width().gap(Gap::Tight).show(ui, |ui, _| {
let edit = field(ui);
let cell = UnitsCell::new().show(ui);
(edit, cell.double_clicked)
});
let (edit, units_double_clicked) = shown.inner.unwrap_or((None, false));
ChannelRowOutput { edit, units_double_clicked }
}
}
/// The units cell's one part, which takes the pointer.
const UNITS: PartKey = PartKey::new("units");
/// The style of a units cell: its size.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct UnitsCellStyle {
#[style(metrics)]
metrics: Metrics,
/// The cell's size: `size.icon.glyph_sm` wide, a control high, so it fills the row's line.
size: Vec2,
}
/// The blank cell after a channel row's number field ([`ChannelRow::show_with_units`]): highlighted under the pointer, it
/// reports a double click. It has no keyboard stop and no node: the host's command that switches the units is its
/// keyboard path.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(sample = UnitsCell::new)]
struct UnitsCell {
#[common]
common: Common,
double_clicked: bool,
}
impl UnitsCell {
fn new() -> Self {
UnitsCell { common: Common::new(), double_clicked: false }
}
}
/// What a units cell reports: its response and whether it was double-clicked in this pass.
struct UnitsCellOutput {
response: egui::Response,
double_clicked: bool,
}
impl Outcome for UnitsCellOutput {
type Value = NoValue;
fn response(&self) -> &egui::Response {
&self.response
}
}
impl Component for UnitsCell {
const ROLE: Role = Role::None;
const OVERLAYS: bool = false;
const STOPS: bool = false;
type Style = UnitsCellStyle;
type Output = UnitsCellOutput;
fn style(cx: &StyleCx<'_>, _: UnitsCellStyleKey) -> UnitsCellStyle {
UnitsCellStyle { metrics: Metrics::new(), size: Vec2::new(cx.tokens.size.icon.glyph_sm, cx.control().height) }
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
cx.style.size
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) {
cx.part(UNITS, rect).sense(Sense::CLICK).state_layer().pointer_only("the host's command switches the units");
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let first = cx.id.with("units-first-click");
let ctx = &cx.response.ctx;
// A press off the cell ends the cell's click run, even when it starts a new count that the next click on the
// cell continues.
if pointer::frame(ctx).press.is_some_and(|press| !cx.response.rect.contains(press.origin)) {
ctx.data_mut(|data| data.remove::<(f64, u32)>(first));
}
let PressPhase::Release { start, click: true, .. } = cx.part(UNITS).press.phase else { return };
// The click count also counts a press just beside the cell, on the number field, so a click is the second of a
// double click only when the click just before it, by the count, was a click on this cell.
let earlier = ctx.data(|data| data.get_temp::<(f64, u32)>(first));
let follows = earlier.is_some_and(|(time, clicks)| start.clicks == clicks + 1 && start.time - time <= MULTI_CLICK_TIME);
if start.clicks >= 2 && follows {
self.double_clicked = true;
ctx.data_mut(|data| data.remove::<(f64, u32)>(first));
} else {
ctx.data_mut(|data| data.insert_temp(first, (start.time, start.clicks)));
}
}
fn finish(self, cx: Cx<'_, Self>) -> UnitsCellOutput {
UnitsCellOutput { response: cx.response.clone(), double_clicked: self.double_clicked }
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ use egui::{Pos2, Response, Ui};
use super::{AreaMode, ColorWarning};
pub(crate) use channel::channel_name;
pub use channel::{ChannelRow, ChannelRule, ChannelUnit, TrackRamp};
pub use channel::{ChannelRow, ChannelRowOutput, ChannelRule, ChannelUnit, TrackRamp};
pub(crate) use full::TWO_COLUMNS;
pub use value::ColorConstraint;
use value::Rules;
+38 -18
View File
@@ -24,7 +24,7 @@ use craft_ui::dialog::{
ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field,
};
use craft_ui::layout::{CellAlign, GridFit};
use craft_ui::layout_components::{Grid, Stack};
use craft_ui::layout_components::{Grid, Row, Stack};
use craft_ui::notices::{Notice, NoticeLayout};
use craft_ui::patterns::form_dialogs::{HostRequests, ResetFooter};
use craft_ui::pickers::Select;
@@ -41,7 +41,7 @@ use std::borrow::Cow;
use std::sync::Arc;
use super::picker::TWO_COLUMNS;
use super::{ColorPicker, ColorPickerLayout, ColorWarning, Gamut, PickedColor, ScreenPickGesture, SwatchPalette};
use super::{ColorPicker, ColorPickerLayout, ColorPickerWords, ColorWarning, CompareSwatch, Gamut, PickedColor, ScreenPickGesture, SwatchPalette};
use crate::{AreaMode, CmykModel, not_web_safe, web_safe};
type StandardColors = (Vec<(Label, Srgba)>, Vec<(Label, Srgba)>);
@@ -318,27 +318,47 @@ impl TabbedBody<'_> {
let (cells, greys) = self.standard.map_or((&[][..], &[][..]), |(cells, greys)| (cells.as_slice(), greys.as_slice()));
let current = held.same().map(|picked| picked.color);
let mut pick = None;
Stack::new().show(ui, |ui, _| {
let honeycomb = SwatchTable::new(self.words.standard_colors.clone(), cells)
.arrangement(SwatchArrangement::Honeycomb)
.tips(true)
.selection(Bind::given(chosen(cells, current)))
.show_all(ui);
if let Some(at) = honeycomb.selected {
pick = cells.get(at).map(|(_, color)| *color);
}
let row = SwatchTable::new(self.words.greys.clone(), greys)
.per_row(greys.len().max(1))
.tips(true)
.selection(Bind::given(chosen(greys, current)))
.show_all(ui);
if let Some(at) = row.selected {
pick = greys.get(at).map(|(_, color)| *color);
let mut restore = None;
// The compare block stands beside the honeycomb, as it does beside the Custom page's area.
Row::new().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
let honeycomb = SwatchTable::new(self.words.standard_colors.clone(), cells)
.arrangement(SwatchArrangement::Honeycomb)
.tips(true)
.selection(Bind::given(chosen(cells, current)))
.show_all(ui);
if let Some(at) = honeycomb.selected {
pick = cells.get(at).map(|(_, color)| *color);
}
let row = SwatchTable::new(self.words.greys.clone(), greys)
.per_row(greys.len().max(1))
.tips(true)
.selection(Bind::given(chosen(greys, current)))
.show_all(ui);
if let Some(at) = row.selected {
pick = greys.get(at).map(|(_, color)| *color);
}
});
if let Some(compare) = self.compare {
let new = held.same().map_or(Mixed::Mixed, |picked| Mixed::Same(picked.color));
let current = match compare {
Mixed::Same(current) => Mixed::Same(current.color),
Mixed::Mixed => Mixed::Mixed,
};
let label = Env::of(ui).words::<ColorPickerWords>().new_color.clone();
if CompareSwatch::new(label, new, current).show(ui).restore
&& let Mixed::Same(current) = compare
{
restore = Some(current);
}
}
});
if let Some(color) = pick {
*held = Mixed::Same(PickedColor::rgb(color));
}
if let Some(current) = restore {
*held = Mixed::Same(current);
}
}
/// The compact picker over the colour, the compare swatch beside its area; the model switch is the memory's.
+7 -7
View File
@@ -97,8 +97,8 @@ pub struct SwatchesPanel<'a> {
search: bool,
row_icons: Option<RowIconsFn<'a>>,
select: SelectMode,
drops: Vec<DropMaker<'a>>,
report_invalid_renames: bool,
takes_drop: Option<DropMaker<'a>>,
payloads: Vec<PayloadAdder<'a>>,
row_items: Option<RowItemsFn<'a>>,
document: Option<IdSalt>,
@@ -131,8 +131,8 @@ impl<'a> SwatchesPanel<'a> {
search: true,
row_icons: None,
select: SelectMode::Single,
drops: Vec::new(),
report_invalid_renames: false,
takes_drop: None,
payloads: Vec::new(),
row_items: None,
document: None,
@@ -211,12 +211,12 @@ impl<'a> SwatchesPanel<'a> {
self
}
/// A host payload of type `P` can be dropped onto a swatch or between swatches at `place` where `accepts` agrees;
/// the drop comes back as `PresetEvent::Dropped`.
/// Adds a target for host payloads of type `P` at `place` where `accepts` agrees.
/// Each drop comes back as `PresetEvent::Dropped`.
pub fn takes_drop<P: Send + Sync + 'static>(mut self, place: DropPlace, accepts: impl Fn(&P, &DropAt<SwatchKey>) -> bool + 'a) -> Self {
// The body can run more than once a pass, and a `PresetDrop` is used up by the browser: it is built per run.
let accepts = Rc::new(accepts);
self.takes_drop = Some(Box::new(move || {
self.drops.push(Box::new(move || {
let accepts = Rc::clone(&accepts);
PresetDrop::new::<P>(place, move |payload: &P, at: &DropAt<SwatchKey>| accepts(payload, at))
}));
@@ -270,8 +270,8 @@ impl<'a> SwatchesPanel<'a> {
search,
row_icons,
select,
drops,
report_invalid_renames,
takes_drop,
payloads,
row_items,
document,
@@ -331,7 +331,7 @@ impl<'a> SwatchesPanel<'a> {
if let Some(items) = &row_items {
browser = browser.row_menu(PresetRowMenu::Host).row_items(|key: &SwatchKey| items(key));
}
if let Some(make) = &takes_drop {
for make in &drops {
browser = browser.takes_drop(make());
}
for add in &payloads {
+198 -4
View File
@@ -38,6 +38,7 @@ type Edits = Rc<RefCell<Vec<(PanelTarget, EditEvent<PickedColor>)>>>;
/// The Color panel on a state and two colours the test can change, collecting what it reports.
struct PanelRig {
fixture: Fixture,
state: Rc<RefCell<ColorPanelState>>,
colors: Rc<Cell<[Srgba; 2]>>,
edits: Edits,
}
@@ -48,15 +49,19 @@ impl PanelRig {
}
fn in_room(mode: ColorPanelMode, room: Vec2) -> Self {
let start = ColorPanelState { mode, ..Default::default() };
Self::with_state(ColorPanelState { mode, ..Default::default() }, room, true)
}
/// The panel from `start`, with the RGB units cells where `units` is set.
fn with_state(start: ColorPanelState, room: Vec2, units: bool) -> Self {
let state = Rc::new(RefCell::new(start));
let colors = Rc::new(Cell::new([RED, BLUE]));
type Shared = (Edits, Rc<RefCell<Vec<ColorRequest>>>, Rc<RefCell<Vec<PanelTarget>>>);
let (edits, opened, added): Shared = Default::default();
let (s, c, e, o, a) = (state, colors.clone(), edits.clone(), opened, added);
let (s, c, e, o, a) = (state.clone(), colors.clone(), edits.clone(), opened, added);
let mut fixture = Fixture::new(move |ui| {
let mut current = *s.borrow();
let shown = ColorPanel::new(Bind::bound(&mut current), c.get()).show(ui);
let shown = ColorPanel::new(Bind::bound(&mut current), c.get()).rgb_units_cell(units).show(ui);
*s.borrow_mut() = current;
e.borrow_mut().extend(shown.edits);
o.borrow_mut().extend(shown.pick_color);
@@ -64,7 +69,7 @@ impl PanelRig {
});
fixture.room(room);
fixture.settle();
PanelRig { fixture, colors, edits }
PanelRig { fixture, state, colors, edits }
}
fn set_colors(&mut self, colors: [Srgba; 2]) {
@@ -197,6 +202,145 @@ fn a_channel_step_keeps_the_other_channels_unrounded() {
}
}
/// A point in the units cell right of `field`, on its line.
fn right_of(field: &craft_ui::testing::Target) -> egui::Pos2 {
egui::pos2(field.rect.right() + 6.0, field.rect.center().y)
}
/// The number fields' values, top to bottom, and the end of the first one's range.
fn field_values(fixture: &Fixture) -> (Vec<f64>, f64) {
let tree = fixture.tree();
let fields = fixture.by_role(Role::SPIN_BUTTON);
let numbers: Vec<_> = fields.iter().map(|field| tree.numeric_of(field.node).expect("a field's value and range")).collect();
let values = numbers.iter().map(|number| number.value.expect("a field's value")).collect();
(values, *numbers[0].range.end())
}
/// A double click right of the R, G or B field switches all three rows between 0 to 255 and percent, and the next one
/// switches them back. The colour does not change.
#[trial]
fn a_double_click_right_of_an_rgb_field_switches_the_rgb_units() {
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
rig.set_colors([Srgba::rgb(1.0, 0.5, 0.0), BLUE]);
let (bytes, end) = field_values(&rig.fixture);
assert!(!rig.state.borrow().rgb_percent && end > 100.0, "the rows start at 0 to 255 ({bytes:?}, to {end})");
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
let at = right_of(&fields[0]);
rig.fixture.click_at(at).click_at(at).settle();
assert!(rig.state.borrow().rgb_percent, "a double click right of R switches to percent");
let (percents, end) = field_values(&rig.fixture);
assert_eq!(end, 100.0, "the fields count to 100 %");
for (percent, byte) in percents.iter().zip(&bytes) {
assert!((percent - byte / 2.55).abs() < 0.51, "every row shows its percent ({percents:?}, {bytes:?})");
}
rig.fixture.advance(1.0);
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
let at = right_of(&fields[2]);
rig.fixture.click_at(at).click_at(at).settle();
assert!(!rig.state.borrow().rgb_percent, "a double click right of B switches back");
assert_eq!(field_values(&rig.fixture).0, bytes, "the rows count 0 to 255 again");
assert!(rig.edits.borrow().is_empty(), "switching the units changes no colour: {:?}", rig.edits.borrow());
}
/// A single click right of an RGB field, and a double click on the field itself, leave the units as they are.
#[trial]
fn only_a_double_click_on_the_units_cell_switches_the_rgb_units() {
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
rig.fixture.click_at(right_of(&fields[1])).settle();
assert!(!rig.state.borrow().rgb_percent, "a single click right of G switches nothing");
rig.fixture.advance(1.0);
let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(1);
rig.fixture.click(&field).click(&field).settle();
assert!(!rig.state.borrow().rgb_percent, "a double click on the G field switches nothing");
}
/// A click at the right edge of an RGB field followed at once by a click on the units cell beside it is not a double
/// click on the cell, though the two presses are close enough to count as one, nor are two clicks on the cell with a
/// click on the field between them.
#[trial]
fn a_click_on_the_field_then_one_on_the_units_cell_switches_nothing() {
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(0);
let (edge, cell) = (egui::pos2(field.rect.right() - 0.4, field.rect.center().y), egui::pos2(field.rect.right() + 2.4, field.rect.center().y));
rig.fixture.click_at(cell).click_at(cell).settle();
assert!(rig.state.borrow().rgb_percent, "a double click at {cell:?} is on the units cell");
rig.fixture.advance(1.0);
rig.fixture.click_at(edge).click_at(cell).settle();
assert!(rig.state.borrow().rgb_percent, "a click on the field's edge and one on the cell switch nothing");
rig.fixture.advance(1.0);
rig.fixture.click_at(cell).click_at(edge).click_at(cell).settle();
assert!(rig.state.borrow().rgb_percent, "two clicks on the cell with one on the field between them switch nothing");
}
/// Two clicks on the units cell with a click on the field between them switch nothing when the field click is too far
/// from the first to continue its click run, and the second cell click is close enough to the field click to count as
/// its second click.
#[trial]
fn a_field_click_that_starts_a_new_run_between_two_units_cell_clicks_switches_nothing() {
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(0);
let (top, bottom) = (field.rect.top() + 1.0, field.rect.bottom() - 1.0);
let (first, edge, second) =
(egui::pos2(field.rect.right() + 2.4, top), egui::pos2(field.rect.right() - 0.4, bottom), egui::pos2(field.rect.right() + 2.4, bottom));
rig.fixture.click_at(second).click_at(second).settle();
assert!(rig.state.borrow().rgb_percent, "a double click at {second:?} is on the units cell");
rig.fixture.advance(1.0);
rig.fixture.click_at(first).click_at(edge).click_at(second).settle();
assert!(rig.state.borrow().rgb_percent, "a field click that starts a new run between two cell clicks switches nothing");
}
/// Rows of other modes have no units cell, nor do the RGB rows of a panel whose host did not ask for them, and Web
/// Color keeps 0 to 255 while the RGB rows show percent.
#[trial]
fn rows_other_than_rgb_keep_their_units() {
let rgb = ColorPanelState { mode: ColorPanelMode::RgbSliders, ..Default::default() };
let mut rigs = vec![("RGB without units cells".to_owned(), PanelRig::with_state(rgb, COLOR_ROOM, false))];
for mode in [ColorPanelMode::CmykSliders, ColorPanelMode::HsbSliders, ColorPanelMode::WebColorSliders] {
rigs.push((format!("{mode:?}"), PanelRig::new(mode)));
}
for (case, mut rig) in rigs {
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
let at = right_of(&fields[0]);
rig.fixture.click_at(at).click_at(at).settle();
assert!(!rig.state.borrow().rgb_percent, "{case}: a double click right of a field switches nothing");
}
let start = ColorPanelState { mode: ColorPanelMode::WebColorSliders, rgb_percent: true, ..Default::default() };
let rig = PanelRig::with_state(start, COLOR_ROOM, true);
let (_, end) = field_values(&rig.fixture);
assert!(end > 100.0, "Web Color counts 0 to 255 while the RGB rows show percent (to {end})");
}
/// The FillStroke layout's RGB rows switch their units the same way, and not while a mixed selection disables them.
#[trial]
fn a_disabled_fill_stroke_rgb_row_does_not_switch_its_units() {
let state = Rc::new(RefCell::new(ColorPanelState::default()));
let edited = Rc::new(Cell::new(Some(PickedColor::rgb(RED))));
let (s, e) = (state.clone(), edited.clone());
let mut fixture = Fixture::new(move |ui| {
let mut current = *s.borrow();
let _ = ColorPanel::new(Bind::bound(&mut current), [RED, BLUE])
.layout(ColorPanelLayout::FillStroke)
.shown(ColorPanelShown::Mode(ColorPanelMode::RgbSliders))
.rgb_units_cell(true)
.edited(e.get())
.show(ui);
*s.borrow_mut() = current;
});
fixture.room(COLOR_ROOM).settle();
let fields = fixture.by_role(Role::SPIN_BUTTON);
let at = right_of(&fields[0]);
fixture.click_at(at).click_at(at).settle();
assert!(state.borrow().rgb_percent, "a double click right of R switches the FillStroke rows to percent");
edited.set(None);
fixture.settle().advance(1.0);
fixture.click_at(at).click_at(at).settle();
assert!(state.borrow().rgb_percent, "with the rows disabled a double click switches nothing");
}
/// A Color panel whose host supplies authoritative native CMYK components.
fn native_cmyk_panel(picked: PickedColor) -> (Fixture, Rc<RefCell<PickedColor>>, Edits) {
let host = Rc::new(RefCell::new(picked));
@@ -994,6 +1138,56 @@ fn a_dragged_swatch_carries_the_hosts_payload_beside_the_panels_own_move() {
assert_eq!(edits.borrow().len(), 1, "a drop outside the panel edits nothing: {:?}", edits.borrow());
}
#[trial]
fn swatches_keep_both_host_drop_places() {
use craft_color_ui::palette::SwatchEntry;
use craft_ui::contract::{DropAt, DropPlace, ListDrag, ShowCollection as _};
use craft_ui::list::{List, ListRow};
use craft_ui::patterns::presets::{PresetEvent, PresetView};
use egui::{Pos2, Rect, UiBuilder};
#[derive(Clone)]
struct Art;
const SWATCHES: Rect = Rect { min: Pos2::ZERO, max: Pos2::new(300.0, 300.0) };
const LAYERS: Rect = Rect { min: Pos2::new(320.0, 0.0), max: Pos2::new(460.0, 120.0) };
let groups = vec![SwatchGroup {
name: String::new(),
entries: vec![SwatchEntry::new("Red", SwatchColor::Rgb([1.0, 0.0, 0.0])), SwatchEntry::new("Blue", SwatchColor::Rgb([0.0, 0.0, 1.0]))],
}];
let received = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&received);
let mut state = SwatchesState::default();
state.browser.view = PresetView::List;
let mut fixture = Fixture::new(move |ui| {
ui.scope_builder(UiBuilder::new().max_rect(LAYERS), |ui| {
let ids = [7_u32];
let source = craft_behavior::keyed(&ids, |id: &u32| *id);
List::<u32>::new("Layers").drag_payload(|_: &ListDrag<u32>| Some(Art)).show_items(ui, &source, &mut |_, _| ListRow::new("Art"));
});
ui.scope_builder(UiBuilder::new().max_rect(SWATCHES), |ui| {
let out = SwatchesPanel::new(&groups, Bind::bound(&mut state), RED)
.takes_drop::<Art>(DropPlace::Between, |_, _| true)
.takes_drop::<Art>(DropPlace::Onto, |_, _| true)
.show(ui);
seen.borrow_mut().extend(
out.events
.into_iter()
.filter_map(|event| if let PresetEvent::Dropped { at, payload, .. } = event { payload.get::<Art>().map(|_| at) } else { None }),
);
});
});
fixture.room(Vec2::new(480.0, 320.0)).settle();
let blue = fixture.by_label("Blue, #0000ff").expect("the Blue swatch").rect;
let gap = Pos2::new(blue.center().x, blue.min.y + 2.0);
for to in [gap, blue.center()] {
let from = fixture.by_label("Art").expect("the layer row").center();
fixture.drag_at(from, to - from).settle();
}
let blue = SwatchKey::Swatch("Blue".into());
assert_eq!(*received.borrow(), [DropAt::gap(Some(blue.clone()), 1), DropAt::Onto(blue)]);
}
/// A panel shown for one document after another keeps a rename left open with its document: the other document's
/// swatch of the same name opens no field, and Enter there renames nothing.
#[trial]
+51 -3
View File
@@ -5,12 +5,12 @@ use std::rc::Rc;
use craft_behavior::Mixed;
use craft_color_ui::ui::{
ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab, ColorPopover, ColorReadout, ColorWarning,
PickedColor, PickerLibrary, PickerSwatches,
ChannelRow, ChannelRowOutput, ChannelRule, ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab,
ColorPopover, ColorReadout, ColorWarning, PickedColor, PickerLibrary, PickerSwatches,
};
use craft_host::{AppInfo, Host};
use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, OklchModel, RgbModel, Rgba, Size, Srgba, ThemeId};
use craft_ui::contract::{Bind, Role, ShowContainer as _};
use craft_ui::contract::{Bind, EditResponse, Role, ShowContainer as _};
use craft_ui::dialog::{DialogHost, DialogResult, StackDialog, dialog_id};
use craft_ui::layout::RowAlign;
use craft_ui::layout_components::Row;
@@ -177,6 +177,45 @@ fn the_dialogs_rgb_fields_show_the_hosts_working_values() {
}
}
/// `ChannelRow::show` returns the row's edit, and `show_with_units` returns the same edit with the units cell's
/// double click, which typing into the field does not report.
#[trial]
fn a_channel_rows_show_returns_its_edit_and_show_with_units_adds_the_units_cell() {
let rule = ChannelRule { range: 0.0..=100.0, step: 1.0, decimals: 0 };
/// Each edit: the row, the value and whether the units cell was double-clicked.
type Seen = Rc<RefCell<Vec<(&'static str, f64, bool)>>>;
let got: Seen = Rc::default();
let seen = Rc::clone(&got);
let mut fixture = Fixture::new(move |ui| {
let edit: Option<EditResponse<f64>> = ChannelRow::new("Plain", Bind::given(40.0), rule.clone()).show(ui);
for event in edit.into_iter().flat_map(|edit| edit.events) {
if let Some(v) = event.value() {
seen.borrow_mut().push(("Plain", *v, false));
}
}
let row: ChannelRowOutput = ChannelRow::new("Units", Bind::given(40.0), rule.clone()).show_with_units(ui);
for event in row.edit.into_iter().flat_map(|edit| edit.events) {
if let Some(v) = event.value() {
seen.borrow_mut().push(("Units", *v, row.units_double_clicked));
}
}
});
fixture.room(vec2(320.0, 200.0));
fixture.idle(2);
for (i, text) in [(0, "70"), (1, "20")] {
let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().nth(i).unwrap_or_else(|| panic!("number field {i}"));
fixture.click(&field);
fixture.key(Key::A, Modifiers::COMMAND);
fixture.type_text(text);
fixture.key(Key::Enter, Modifiers::NONE);
fixture.settle();
}
let got = got.borrow();
assert!(got.iter().any(|&(row, v, _)| row == "Plain" && v == 70.0), "show reports the typed value: {got:?}");
assert!(got.iter().any(|&(row, v, _)| row == "Units" && v == 20.0), "show_with_units reports the typed value: {got:?}");
assert!(got.iter().all(|&(_, _, clicked)| !clicked), "typing is not a double click on the units cell: {got:?}");
}
/// The densities and themes every layout trial runs in: compact and comfortable, a Pro and a Studio theme.
const LOOKS: [(Size, &str); 4] =
[(Size::Compact, "craft.pro"), (Size::Comfortable, "craft.pro"), (Size::Compact, "craft.studio"), (Size::Comfortable, "craft.studio")];
@@ -558,6 +597,15 @@ fn the_tabbed_colors_dialog_opens_on_its_tab_and_answers_from_either_page() {
fixture.click(&cell);
fixture.idle(4);
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#0000ff"), "a honeycomb pick is the colour");
// #7984: the Standard page shows the compare block too, and its current half restores the opening colour.
assert!(fixture.by_label("New color").is_some(), "the Standard page shows the compare block");
let restore = fixture.by_label("Restore current color").expect("the compare block's current half");
fixture.click(&restore);
fixture.idle(4);
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#123456"), "the current half restores the opening colour");
let cell = fixture.by_label("Standard 2").expect("the honeycomb shows its cells");
fixture.click(&cell);
fixture.idle(4);
assert!(dialogs.borrow_mut().confirm::<ColorPickerDialog>(&ctx), "OK answers");
let answered = dialogs.borrow_mut().take::<ColorPickerDialog>().and_then(DialogResult::ok).map(|result| result.picked.color.to_hex());
+2 -2
View File
@@ -19,7 +19,7 @@ pub struct CornerStyle {
pub(super) dot: f32,
/// The pointer's reach.
pub(super) reach: f32,
/// The least distance inside a corner.
/// The least distance inside a corner: [`CornerWidgets::INSET`](super::CornerWidgets::INSET).
pub(super) inset: f32,
/// The shortest side, on the screen, whose corners show widgets.
pub(super) min_side: f32,
@@ -38,7 +38,7 @@ impl CornerStyle {
widget: tokens.size.handle.md,
dot: tokens.size.handle.sm,
reach: tokens.size.hit.target,
inset: tokens.space.gap.stack,
inset: super::CornerWidgets::INSET,
min_side: MIN_SIDE,
fill: cx.color(tokens.color.overlay.handle_fill),
color: cx.color(tokens.color.overlay.line),
+4
View File
@@ -101,6 +101,10 @@ impl<'a> CornerWidgets<'a> {
/// The widest inner angle, in degrees, a widget shows at unless [`hide_above`](Self::hide_above) says otherwise.
pub const HIDE_ABOVE: f64 = 180.0;
/// The least distance, in screen points along each side of a right angle, a widget sits inside its corner, at every
/// density. A host that hit-tests the widgets itself reads it from here.
pub const INSET: f32 = 10.0;
}
/// What the widgets report: the edit of the targets and what the widgets ask the host to do.
+27
View File
@@ -118,3 +118,30 @@ fn a_triangle_apex_rounds_with_the_pointer_travel() {
assert!(small > START_RADIUS, "a short pull rounds the apex: {small}");
assert!(large > small, "a longer pull rounds it more: {small} then {large}");
}
/// A slightly rounded right-angle corner's widget sits `CornerWidgets::INSET` points inside the corner along each side,
/// at every density, so a host that hit-tests the widgets with that constant presses where the widget is drawn.
#[trial]
fn a_widget_sits_the_published_inset_inside_its_corner_at_every_density() {
for density in [craft_theme::Size::Compact, craft_theme::Size::Comfortable] {
let vertex = Rc::new(Cell::new(egui::Pos2::ZERO));
let seen = Rc::clone(&vertex);
let mut targets = vec![square()];
let mut fixture = Fixture::new(move |ui| {
let room = ui.available_rect_before_wrap();
let view = CanvasView::new(room, Point::new(210.0, 200.0), 1.0);
seen.set(view.to_screen(targets[0].corners[0].vertex));
Canvas::new("Document")
.view(view)
.show(ui, |ui, body| CornerWidgets::new("Corner radius", Bind::bound(&mut targets)).show_at(ui, body.rect));
});
fixture.density(density).settle();
let widget = fixture.by_label("Corner 1 of 4").expect("the first corner has a widget");
let offset = widget.center() - vertex.get();
let inset = CornerWidgets::INSET;
assert!(
(offset.x - inset).abs() < 0.5 && (offset.y - inset).abs() < 0.5,
"{density:?}: the widget sits {offset:?} from its corner, not {inset} along each side"
);
}
}
+19 -2
View File
@@ -1757,7 +1757,8 @@ fn deflate_rows(
/// and completes the flush: when a sync flush fills the buffer, miniz_oxide (flate2's former Rust
/// backend) can return before compressing the last lookahead bytes, and the next call only
/// drains the pending output, so a resumed flush silently drops data. `None` (the caller then
/// uses the serial encoder) if the single call did not finish.
/// uses the serial encoder) if the single call did not finish. The returned bytes keep no
/// spare capacity, because the caller holds every band until it joins them into one stream.
fn deflate_band(filtered: &[u8], lvl: flate2::Compression, last: bool) -> Option<Vec<u8>> {
let mut c = flate2::Compress::new(lvl, false);
// Stored blocks cost 5 bytes per 64 KiB, the flush an empty stored block: 1/8 is ample.
@@ -1766,7 +1767,10 @@ fn deflate_band(filtered: &[u8], lvl: flate2::Compression, last: bool) -> Option
let flush = if last { flate2::FlushCompress::Finish } else { flate2::FlushCompress::Sync };
let status = c.compress_vec(filtered, &mut z, flush).ok()?;
let done = if last { status == flate2::Status::StreamEnd } else { c.total_in() as usize == filtered.len() && z.len() < z.capacity() };
done.then_some(z)
done.then(|| {
z.shrink_to_fit();
z
})
}
/// One scanline with the adaptive filter choice, appended to `out` (type byte + data).
@@ -2256,6 +2260,19 @@ mod parallel_tests {
}
}
/// Every band is held until the stream is joined, so a band keeps only the bytes it holds,
/// not the worst-case buffer it was deflated into (about 1.125 times the image in all).
#[test]
fn deflated_bands_keep_no_spare_capacity() {
let (w, h, bpp) = (1024usize, 600usize, 3usize);
let px: Vec<u8> = (0..w * h * bpp).map(|i| (i % 7) as u8).collect();
let parts = deflate_rows(&px, None, w * bpp, bpp, band_rows(w * bpp), flate2::Compression::default(), true, 2).unwrap();
assert!(parts.len() > 2);
for (i, p) in parts.iter().enumerate() {
assert!(p.z.capacity() <= p.z.len() + 64, "band {i}: capacity {} for {} bytes of {}", p.z.capacity(), p.z.len(), p.len);
}
}
/// The bytes depend on the image, not on the machine: one, two and 32 worker threads
/// (and the machine's own count, through `encode`) give the same stream.
#[test]
+16 -2
View File
@@ -226,6 +226,8 @@ pub enum GalleryFace<'a> {
thumbnails: &'a Thumbnails<u64>,
/// What renders the thumbnail.
source: &'a dyn ThumbSource<u64>,
/// Whether the transparency grid shows behind transparent pixels.
checker: bool,
},
/// A tile painted directly.
Paint(&'a dyn Fn(&ContentPainterCx, Rect)),
@@ -250,7 +252,17 @@ impl<'a> GalleryFace<'a> {
/// A thumbnail under `key`, rendered by `source` into `thumbnails`.
pub fn rendered(key: u64, thumbnails: &'a Thumbnails<u64>, source: &'a dyn ThumbSource<u64>) -> Self {
GalleryFace::Rendered { key, thumbnails, source }
GalleryFace::Rendered { key, thumbnails, source, checker: true }
}
/// Whether a rendered thumbnail shows the transparency grid behind its transparent pixels (default on). Off for a
/// thumbnail that is a mask on the surface it sits on, such as an equation symbol. Other faces ignore it.
#[must_use]
pub fn checker(mut self, on: bool) -> Self {
if let GalleryFace::Rendered { checker, .. } = &mut self {
*checker = on;
}
self
}
/// The picture this face shows, `size` high and `aspect` times as wide. It is decoration: the tile that holds it
@@ -258,7 +270,9 @@ impl<'a> GalleryFace<'a> {
fn picture(&self, aspect: ThumbAspect, size: ThumbSize) -> Picture<'a> {
let picture = match self {
GalleryFace::Image { key, revision, image } => Picture::new(Label::default(), *key, *image).revision(*revision),
GalleryFace::Rendered { key, thumbnails, source } => Picture::rendered(Label::default(), *key, thumbnails, *source),
GalleryFace::Rendered { key, thumbnails, source, checker } => {
Picture::rendered(Label::default(), *key, thumbnails, *source).checker(*checker)
}
GalleryFace::Paint(paint) => {
let paint = *paint;
Picture::painter(Label::default(), aspect, move |cx: &ContentPainterCx<'_>, rect: Rect| paint(cx, rect))
+2 -3
View File
@@ -172,8 +172,7 @@ fn gallery_rendered(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let options = ThumbnailOptions::new();
let thumbnails = Thumbnails::<u64>::in_context(ui.ctx(), "craft_menu.gallery.story", options);
let source = FakeThumbSource::<u64>::new().later(true);
let items: Vec<GalleryItem<'_, usize>> = (0..COUNT)
.map(|at| GalleryItem { key: at, label: name(at), face: GalleryFace::Rendered { key: at as u64, thumbnails: &thumbnails, source: &source } })
.collect();
let items: Vec<GalleryItem<'_, usize>> =
(0..COUNT).map(|at| GalleryItem { key: at, label: name(at), face: GalleryFace::rendered(at as u64, &thumbnails, &source) }).collect();
show(ui, &items)
}
+4
View File
@@ -24,6 +24,8 @@ use crate::shortcuts::state::{DialogState, Env};
const LISTS_SHARE: f32 = 0.5;
/// The detail column's share of the width beside the lists.
const DETAIL_SHARE: f32 = 0.5;
/// The most Categories rows shown before the list scrolls.
const CATEGORY_ROWS: u16 = 6;
const PANES: [ColumnWidth; 2] = [ColumnWidth::fill(LISTS_SHARE), ColumnWidth::fill(DETAIL_SHARE)];
/// One frame of the command-lists body: a search field, the Categories list beside the Commands
@@ -62,6 +64,8 @@ fn categories(ui: &mut Ui, env: &Env<'_>, state: &mut DialogState) {
let mut selection = Selection::new(at.into_iter().collect(), at, at);
let out = List::<usize>::new(words.categories.clone())
.id_salt("categories")
// A short list, so the Commands list under it keeps room in a dialog of ordinary height.
.max_rows(CATEGORY_ROWS)
.select(SelectMode::Single)
.selection(Bind::bound(&mut selection))
.show_items(ui, &Titles(&labels), &mut |key, _| ListRow::new(labels[*key].clone()));
+23
View File
@@ -263,3 +263,26 @@ fn the_current_tile_paints_an_accent_fill_and_edge_even_when_focused() {
assert!(shapes.iter().any(|p| p.fill == fill && near(p, current)), "{who}: the focused current tile keeps its fill");
}
}
/// How many shapes a gallery of one rendered tile of a transparent image paints, as built or with `checker(false)`.
fn shapes_of_rendered(opt_out: bool) -> usize {
use craft_ui::primitives::textures::{FakeThumbSource, ThumbnailOptions, Thumbnails};
let mut fixture = Fixture::new(move |ui| {
let options = ThumbnailOptions::new().jobs(std::sync::Arc::new(craft_host::InlineJobs));
let thumbnails = Thumbnails::<u64>::in_context(ui.ctx(), "gallery_checker_test", options);
let source = FakeThumbSource::<u64>::new();
// The default case sets nothing, so a default that turned the grid off fails here.
let face = GalleryFace::rendered(1, &thumbnails, &source);
let face = if opt_out { face.checker(false) } else { face };
let items = [GalleryItem { key: 0_usize, label: Label::from("Mask"), face }];
Gallery::new("Symbols", &items, None).tiles(1, 1).show(ui);
});
fixture.settle();
fixture.frame_shapes().len()
}
#[trial]
fn a_rendered_gallery_tile_paints_a_checker_unless_it_opts_out() {
let (with, without) = (shapes_of_rendered(false), shapes_of_rendered(true));
assert!(with > without, "the default paints {with} shapes, the opt-out {without}: the grid is the difference");
}
+27 -1
View File
@@ -1,7 +1,7 @@
//! The Customize Keyboard layout: each change is applied at once and Escape closes without rolling back.
use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Scope, Scopes, Trigger};
use craft_menu::shortcuts::{Layout, Outcome};
use craft_menu::shortcuts::{Area, Layout, Outcome};
use craft_ui::contract::Role;
use craft_ui::testing::trial;
use egui::{Key, Modifiers};
@@ -79,3 +79,29 @@ fn command_lists_assign_remove_and_close_apply_each_change_at_once() {
assert_eq!(keys(&rig), left, "the keymap keeps the edits");
assert!(rig.bindings("file.export").is_empty(), "the taken chord is not given back");
}
/// A long Categories list must not take the room the Commands list needs: in a dialog of ordinary height a command row
/// still shows above the footer.
#[trial]
fn commands_keep_room_beside_a_long_categories_list() {
let rig = Rig::tuned(Platform::Mac, |options| {
options.layout = Layout::CommandLists;
options.own_areas = true;
options.size = Some(egui::vec2(640.0, 460.0));
options.areas = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"].map(|name| Area::new(name, name, |_| true)).to_vec();
});
let row = rig.find("Bring to Front").center();
let footer = rig.find("Reset All…").center();
assert!(row.y < footer.y, "the command row ({row:?}) sits above the footer ({footer:?})");
// The capped list scrolls: the arrow keys still reach its last entry.
let mut rig = rig;
rig.click("A");
for _ in 0..11 {
rig.press(Modifiers::NONE, Key::ArrowDown);
}
let area = {
let shared = rig.shared.borrow();
shared.state.snapshot(&shared.km).expect("the dialog has shown").area
};
assert_eq!(area, "L", "the last Categories entry is reachable");
}
+2 -2
View File
@@ -52,8 +52,8 @@ pub use reading::{ReadingNav, ReadingNavOutput, ReadingState, ReadingView, Readi
pub use setup::{PageLayoutChoice, PageLayoutMenus, PageSetupDialog};
pub use sync_views::{Lead, SyncedViews, SyncedViewsOutput, SyncedViewsState};
pub use table::{
BorderEdges, BorderPreset, CellAlign, CellSelectionOverlay, EdgeKey, EdgeLook, EdgePicker, RowHeight, SampleArea, TableChange, TableGeometry,
TableProperties, TablePropertiesOutput, TableSizePicker, TableSizePickerOutput, TableValues, TextDirection,
BorderEdges, BorderPreset, CellAlign, CellSelectionOverlay, EdgeKey, EdgeLook, EdgePicker, EdgeSize, RowHeight, SampleArea, TableChange,
TableGeometry, TableProperties, TablePropertiesOutput, TableSizePicker, TableSizePickerOutput, TableValues, TextDirection,
};
pub use text_selection::{
MarkArea, MarkKind, PageTextSource, PageTexts, TextMark, TextMarks, TextSelectState, TextSelectTool, TextSelection, TextSpan,
+22 -2
View File
@@ -163,6 +163,8 @@ pub struct EdgePickerStyle {
focus: FocusLook,
/// The side of the square.
side: f32,
/// The side of the square at [`EdgeSize::Sample`].
sample_side: f32,
/// How far the outer lines sit inside the square, and how near a line the pointer picks it.
inset: f32,
/// The area inside the lines.
@@ -198,6 +200,20 @@ pub struct EdgePicker<'a> {
/// How the picture is drawn: the proxy diagram, or a sample of the borders on text, a paragraph or a page.
#[prop]
look: EdgeLook,
/// The extent of the square: a thumbnail, or a sample-sized preview.
#[prop]
preview: EdgeSize,
}
/// How large the picker's square is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum EdgeSize {
/// A thumbnail (`size.thumb.lg`).
#[default]
Thumb,
/// A preview at sample size (`size.thumb.sample.lg`), for a Borders or Shading dialog's page-like preview.
Sample,
}
/// How the borders preview is drawn.
@@ -246,7 +262,7 @@ struct ClickRun {
impl<'a> EdgePicker<'a> {
/// A picker named `label` editing `edges`.
pub fn new(label: impl Into<Label>, edges: Bind<'a, BorderEdges>) -> Self {
EdgePicker { common: Common::new(), edges, paragraph: false, look: EdgeLook::default() }.label(label).ltr_axis()
EdgePicker { common: Common::new(), edges, paragraph: false, look: EdgeLook::default(), preview: EdgeSize::default() }.label(label).ltr_axis()
}
/// The name of `edge`.
@@ -353,6 +369,7 @@ impl Component for EdgePicker<'_> {
.border(edge, cx.tokens.stroke.thin),
focus: cx.focus_look(),
side: cx.tokens.size.thumb.lg,
sample_side: cx.tokens.size.thumb.sample.lg,
inset: cx.tokens.space.pad.regular,
fill: cx.color(colors.surface.sunken),
on: Stateful::new(cx.color(colors.accent.solid)),
@@ -361,7 +378,10 @@ impl Component for EdgePicker<'_> {
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::splat(cx.style.side)
Vec2::splat(match self.preview {
EdgeSize::Thumb => cx.style.side,
EdgeSize::Sample => cx.style.sample_side,
})
}
fn sense(&self) -> Sense {
+1 -1
View File
@@ -9,7 +9,7 @@ pub mod size_picker;
#[cfg(feature = "suite")]
pub(crate) mod stories;
pub use edges::{BorderEdges, BorderPreset, EdgeKey, EdgeLook, EdgePicker, EdgePickerStyle, EdgePickerWords, SampleArea};
pub use edges::{BorderEdges, BorderPreset, EdgeKey, EdgeLook, EdgePicker, EdgePickerStyle, EdgePickerWords, EdgeSize, SampleArea};
pub use properties::{CellAlign, RowHeight, TableChange, TableProperties, TablePropertiesOutput, TablePropertiesWords, TableValues, TextDirection};
pub use selection::{CellSelectionOverlay, CellSelectionStyle, TableGeometry};
pub use size_picker::{TableSizePicker, TableSizePickerOutput, TableSizePickerStyle, TableSizePickerWords};
+19
View File
@@ -25,3 +25,22 @@ fn right_at_a_row_end_goes_on_to_the_next_row() {
fixture.key(Key::ArrowRight, Modifiers::NONE).idle(2);
assert_eq!(hovered.get(), Some((2, 1)), "Right wraps to the next row");
}
/// A picker asked for sample size draws a larger square than the default thumbnail.
#[trial]
fn edge_picker_sample_size_is_larger_than_the_thumbnail() {
use craft_pages::ui::table::{BorderEdges, EdgePicker, EdgeSize};
use craft_ui::contract::Bind;
let sides = Rc::new(Cell::new((0.0, 0.0)));
let seen = sides.clone();
let mut edges = BorderEdges::default();
let mut fixture = Fixture::new(move |ui| {
let thumb = EdgePicker::new("Thumb", Bind::bound(&mut edges)).show(ui).response.rect.width();
let mut other = BorderEdges::default();
let sample = EdgePicker::new("Sample", Bind::bound(&mut other)).preview(EdgeSize::Sample).show(ui).response.rect.width();
seen.set((thumb, sample));
});
fixture.settle();
let (thumb, sample) = sides.get();
assert!(thumb > 0.0 && sample > thumb, "thumb {thumb}, sample {sample}");
}
+2
View File
@@ -24,6 +24,8 @@ mod writer;
#[cfg(any(test, feature = "test-support"))]
pub(crate) mod testkit;
#[cfg(test)]
pub(crate) use security::{ALL_FOLLOWED, ALL_FOLLOWED_LIMIT, MAX_FOLLOWED};
pub use crate::crypt::{
Algorithm, Auth, Method as CryptMethod, NewEncryption, Permissions, SecurityHandler, effective_password, pdfdoc_byte, pdfdoc_char,
+16 -3
View File
@@ -767,9 +767,22 @@ impl Document {
Some(XrefEntry::InFile { offset, .. }) => {
let resolve = |r: ObjRef| self.stream_length(r);
let off = offset as usize;
let at = |off: usize| match parse_indirect_shared(&self.data, off, &resolve, &self.endstreams) {
Ok((id, o)) if id.num == num => Some(self.decrypted(id, o)),
_ => None,
let at = |off: usize| {
#[cfg(test)]
{
let parses = super::tests::OFFSET_PARSES.with(|parses| {
let mut parses = parses.borrow_mut();
let count = parses.entry(num).or_default();
*count += 1;
*count
});
let limit = super::tests::OFFSET_PARSE_LIMIT.with(std::cell::Cell::get);
assert!(parses <= limit, "object {num} parsed {parses} times at an offset, more than the {limit} allowed");
}
match parse_indirect_shared(&self.data, off, &resolve, &self.endstreams) {
Ok((id, o)) if id.num == num => Some(self.decrypted(id, o)),
_ => None,
}
};
// Offsets relative to a shifted header, or simply wrong: try both fixes.
at(off)
+15 -10
View File
@@ -26,6 +26,11 @@ std::thread_local! {
pub(super) static FILE_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// How many times `Document::objstm` decoded an object stream on this thread.
pub(super) static OBJSTM_DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// How many times `Document::load` parsed each file object at an offset on this thread, by
/// object number.
pub(super) static OFFSET_PARSES: std::cell::RefCell<HashMap<u32, usize>> = std::cell::RefCell::new(HashMap::new());
/// The most offset parses of one object a test allows: one more fails the test at once.
pub(super) static OFFSET_PARSE_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
}
/// A scan that doesn't find an object isn't made again: each reads the whole file, and a file can
@@ -2465,8 +2470,6 @@ fn the_chain_row_limit_counts_rows_an_xref_stream_index_repeats() {
assert!(detail.contains("more than 7 entries"), "{detail}");
}
// Not on the web: it times the load on a thread, and wasm32-unknown-unknown has none.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_stream_whose_length_is_itself_and_never_ends_loads_quickly() {
// From the nightly fuzz job: `6 0 obj << /Length 6 0 R >> stream` with no `endstream`
@@ -2476,14 +2479,16 @@ fn a_stream_whose_length_is_itself_and_never_ends_loads_quickly() {
// only runs when the header is shifted.
let mut bytes = b"%PDF-1.7\n1 0 obj\n<< /Type /Catalog >>\nendobj\n".to_vec();
bytes.extend_from_slice(b"6 0 obj\n<< /Length 6 0 R >>\nstream\nno end marker follows\n");
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
if let Ok(doc) = Document::open(Arc::new(bytes)) {
let _ = doc.try_get(6);
}
let _ = tx.send(());
});
rx.recv_timeout(std::time::Duration::from_secs(20)).expect("loading must not retry exponentially");
// Each object is parsed at its offset at most twice; a retry of each attempt is past this
// limit long before its end.
OFFSET_PARSES.with(|parses| parses.borrow_mut().clear());
OFFSET_PARSE_LIMIT.with(|limit| limit.set(2));
if let Ok(doc) = Document::open(Arc::new(bytes)) {
let _ = doc.try_get(6);
}
OFFSET_PARSE_LIMIT.with(|limit| limit.set(usize::MAX));
let parses = OFFSET_PARSES.with(|parses| parses.borrow().clone());
assert!(parses.get(&6).is_some_and(|&n| n <= 2) && parses.values().all(|&n| n <= 2), "{parses:?}");
}
/// A file whose object 3 (its `/Info`) can't be parsed: the rest reads.
+15 -1
View File
@@ -20,7 +20,7 @@ use crate::cos::{Dict, Document, Object, PdfString, Stream};
/// file could make one read a tree of them, each object read again once the cache has let it go.
/// An object takes a few of these, and two dozen if every part of it is given by reference; past
/// this they read as absent. The parameters of an object stream, read together, count as one.
const MAX_FOLLOWED: u32 = 32;
pub(crate) const MAX_FOLLOWED: u32 = 32;
std::thread_local! {
/// How many [`FollowScope`]s this thread is inside.
@@ -58,9 +58,23 @@ pub(crate) fn following<T>(spent: T, f: impl FnOnce() -> T) -> T {
return spent;
}
FOLLOWED.set(FOLLOWED.get() + 1);
#[cfg(test)]
{
let all = ALL_FOLLOWED.replace(ALL_FOLLOWED.get().saturating_add(1)).saturating_add(1);
let limit = ALL_FOLLOWED_LIMIT.get();
assert!(all <= limit, "{all} references followed, more than the {limit} allowed");
}
f()
}
#[cfg(test)]
std::thread_local! {
/// The references followed on this thread, in every [`FollowScope`].
pub(crate) static ALL_FOLLOWED: Cell<usize> = const { Cell::new(0) };
/// The most references a test lets this thread follow: one more fails the test at once.
pub(crate) static ALL_FOLLOWED_LIMIT: Cell<usize> = const { Cell::new(usize::MAX) };
}
/// `o`, or the object it refers to, for what decides how a stream or dictionary is treated. Past
/// [`MAX_FOLLOWED`] a reference reads as absent.
fn followed<'o>(doc: &Document, o: &'o Object) -> Held<'o> {
+9 -8
View File
@@ -1310,14 +1310,15 @@ fn selectors_that_lead_to_selectors_load_at_once() {
top = stream_of(&mut doc, vec![Object::Ref(a), first.clone(), second.clone(), Object::Ref(b)]);
}
let saved = write_incremental(&doc, &SaveOptions::default()).unwrap();
let (done, finished) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let doc = Document::open(Arc::new(saved)).unwrap();
let _ = done.send(doc.get(top).as_dict().is_some());
});
// With the budget it takes milliseconds, and without it longer than anyone would wait, so a
// margin this wide can't fail on a busy machine.
assert_eq!(finished.recv_timeout(std::time::Duration::from_secs(120)), Ok(true), "loading must not fan out");
let doc = Document::open(Arc::new(saved)).unwrap();
// The one read follows no more references than its budget allows; one that fans out is past
// this limit long before its end.
let budget = crate::cos::MAX_FOLLOWED as usize;
crate::cos::ALL_FOLLOWED.set(0);
crate::cos::ALL_FOLLOWED_LIMIT.set(budget);
assert!(doc.get(top).as_dict().is_some(), "loading must not fan out");
crate::cos::ALL_FOLLOWED_LIMIT.set(usize::MAX);
assert!(crate::cos::ALL_FOLLOWED.get() <= budget);
}
/// An R6 file of the fixture's page, its `/Encrypt` given `cf` as `/CF` and `selectors` (`/StmF`,
+39 -23
View File
@@ -300,6 +300,7 @@ impl<'a> MapLookup<'a> {
/// Lowercase the query only; the first group's representative keeps its authored case.
pub(crate) fn fold(&self, c: char) -> char {
count_map_steps(1);
let l = c.to_lowercase().next().unwrap_or(c);
self.first.get(&l).copied().unwrap_or(l)
}
@@ -308,10 +309,34 @@ impl<'a> MapLookup<'a> {
fn alternatives(&self, c: char) -> Vec<char> {
let mut seen = HashSet::new();
seen.insert(c);
self.groups_of.get(&c).into_iter().flatten().filter_map(|&i| self.groups.get(i)).flatten().copied().filter(|&x| seen.insert(x)).collect()
self.groups_of
.get(&c)
.into_iter()
.flatten()
.filter_map(|&i| self.groups.get(i))
.inspect(|group| count_map_steps(1 + group.len()))
.flatten()
.copied()
.filter(|&x| seen.insert(x))
.collect()
}
}
// The MAP lookups on this thread: one per letter folded, and one per group a letter's
// alternatives come from and per member read from it.
#[cfg(test)]
std::thread_local! {
static MAP_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[inline]
fn count_map_steps(count: usize) {
#[cfg(test)]
MAP_STEPS.with(|steps| steps.set(steps.get().saturating_add(count)));
#[cfg(not(test))]
let _ = count;
}
/// Every way of changing up to `t.max_map_changes` letters of `chars` to a MAP relative (`alts`,
/// letter by letter), with its cost: all one-change variants first, then two, and so on, so the
/// [`MAX_MAP_VARIANTS`] cap drops the variants with the most changes.
@@ -738,36 +763,27 @@ mod tests {
let dic = format!("{}\n{}\n", words.len(), words.join("\n"));
AffixDict::from_hunspell(&aff, &dic, &[]).unwrap()
}
fn cpu_cost(f: &mut impl FnMut()) -> f64 {
let ran = || {
let s = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
s.split_whitespace().next()?.parse::<u64>().ok()
};
let (start, before) = (std::time::Instant::now(), ran());
f();
match (before, ran()) {
(Some(a), Some(b)) if b > a => (b - a) as f64 * 1e-9,
_ => start.elapsed().as_secs_f64(),
}
}
let small = dictionary(1);
let big = dictionary(8);
let run = |d: &AffixDict| {
MAP_STEPS.with(|steps| steps.set(0));
let out = suggest_in(d, "abcdef", 8, &Tuning::DEFAULT);
let expected: Vec<String> = (0..8).map(|i| format!("abcde{}", char::from_u32(0xe000 + i).unwrap())).collect();
assert_eq!(out, expected);
std::hint::black_box(out);
MAP_STEPS.with(std::cell::Cell::get)
};
run(&small);
run(&big);
let (mut t1, mut t8) = (f64::INFINITY, f64::INFINITY);
for _ in 0..5 {
t1 = t1.min(cpu_cost(&mut || (0..8).for_each(|_| run(&small))) / 8.0);
t8 = t8.min(cpu_cost(&mut || run(&big)));
let (s1, s8) = (run(&small), run(&big));
// 8x the groups and the stems: about 8x the lookups, where a scan of the groups for each
// letter of each stem is 64x.
assert!(s8 <= 10 * s1, "8x MAP and stems cost {s8} MAP lookups against {s1}");
// A letter folds through the index alone, one lookup: with the groups taken away, each
// letter still folds the same.
let groups: Vec<Vec<char>> = vec!["aąá".chars().collect(), "óu".chars().collect()];
let lookup = MapLookup::new(&groups);
let index_only = MapLookup { groups: &[], first: lookup.first.clone(), groups_of: lookup.groups_of.clone() };
for &c in groups.iter().flatten() {
assert_eq!(index_only.fold(c), lookup.fold(c), "{c}");
}
let ratio = t8 / t1.max(1e-9);
eprintln!("MAP/stem scan: small={t1:.6}s big={t8:.6}s ratio={ratio:.2}");
assert!(ratio < 24.0, "8x MAP and stems cost {ratio:.2}x: {t1:.6}s / {t8:.6}s");
}
/// craft-libs#487 review: MAP variants are made by number of changes, so when a long word has
+31 -5
View File
@@ -317,19 +317,25 @@ impl Name {
let mut letters_from = vec![0usize; n + 1];
let mut run = 0usize;
for (slot, c) in letters_from.iter_mut().zip(&chars).rev() {
count_name_read();
run = if c.is_alphabetic() { run.saturating_add(1) } else { 0 };
*slot = run;
}
let last_bang = chars.iter().rposition(|c| *c == '!');
let last_bang = chars.iter().rposition(|c| {
count_name_read();
*c == '!'
});
let mut cyrillic_runs: Vec<(usize, usize)> = (0..n).map(|i| (i, i + 1)).collect();
let mut start = 0;
while start < n {
count_name_read();
if !chars.get(start).is_some_and(|c| is_cyrillic(*c)) {
start += 1;
continue;
}
let mut end = start + 1;
while chars.get(end).is_some_and(|c| is_cyrillic(*c)) {
count_name_read();
end += 1;
}
for slot in cyrillic_runs.get_mut(start..end).into_iter().flatten() {
@@ -341,6 +347,19 @@ impl Name {
}
}
// Each character of a decoded name that `Name::new` and the position checks of `score` read on
// this thread.
#[cfg(test)]
std::thread_local! {
static NAME_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[inline]
fn count_name_read() {
#[cfg(test)]
NAME_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
}
/// Whether the character at `i` of `chars` is common in Western names, for weighing windows-1252
/// against Mac Roman: letters (but not those windows-1252 has only at 0x80–0x9F, where Mac Roman
/// keeps its accented lowercase: Mac "Größe" is 1252 "Grš§e"), typographic punctuation,
@@ -356,6 +375,7 @@ fn is_latin_common(name: &Name, i: usize) -> bool {
/// Where the character at `i` of `name` sits: right after an ASCII letter or digit (inside a word
/// or a number), and how many letters (accented ones too: "¡Ánimo!") follow it directly.
fn position(name: &Name, i: usize) -> (bool, usize) {
count_name_read();
let after_ascii = i.checked_sub(1).and_then(|k| name.chars.get(k)).is_some_and(|c| c.is_ascii_alphanumeric());
let letters_after = name.letters_from.get(i.saturating_add(1)).copied().unwrap_or(0);
(after_ascii, letters_after)
@@ -394,6 +414,7 @@ fn cyrillic_word(name: &Name, i: usize) -> bool {
/// The run of Cyrillic letters around the Cyrillic letter at `i` (`start..end`).
fn cyrillic_run(name: &Name, i: usize) -> (usize, usize) {
count_name_read();
name.cyrillic_runs.get(i).copied().unwrap_or((i, i.saturating_add(1)))
}
@@ -870,11 +891,16 @@ mod tests {
// 64 KiB of one letter (é in windows-1252, й in windows-1251, Mac Roman's È), of
// alternating Cyrillic letters, and of "¡ab" with no "!": every character used to rescan
// the rest of the name, which took minutes.
for unit in [&[0xe9u8][..], &[0xe9, 0xea][..], &[0xa1, b'a', b'b'][..]] {
let name = unit.repeat(GUESS_SAMPLE / unit.len());
let started = std::time::Instant::now();
// A name four times as long must take about four times the reads, not sixteen.
let reads = |unit: &[u8], len: usize| {
let name = unit.repeat(len / unit.len());
NAME_READS.with(|reads| reads.set(0));
let _ = guess(&[&name], "");
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?} took {:?}", unit, started.elapsed());
NAME_READS.with(std::cell::Cell::get)
};
for unit in [&[0xe9u8][..], &[0xe9, 0xea][..], &[0xa1, b'a', b'b'][..]] {
let (quarter, full) = (reads(unit, GUESS_SAMPLE / 4), reads(unit, GUESS_SAMPLE));
assert!(full <= 5 * quarter, "{unit:?}: {quarter} reads for a quarter of the name, {full} for all of it");
}
}
}
+36 -6
View File
@@ -185,12 +185,41 @@ fn references(text: &str) -> impl Iterator<Item = &str> {
text.match_indices('&').filter_map(|(at, _)| {
let rest = text.get(at + 1..)?;
// Look no further than the longest name: a file of `&`s without `;` would be read quadratically.
let end = rest.bytes().take(MAX_NAME + 1).position(|b| b == b';')?;
let name = rest.get(..end)?;
let mut read = 0usize;
let end = rest.bytes().take(MAX_NAME + 1).position(|b| {
read += 1;
b == b';'
});
count_name_bytes(read);
let name = rest.get(..end?)?;
(!name.is_empty() && name.len() <= MAX_NAME && !name.starts_with('#') && !name.contains(char::is_whitespace)).then_some(name)
})
}
// The bytes `references` reads after each `&` while looking for the `;`, on this thread, and the
// most a test lets it read: past that the count fails the test at once rather than after the rest
// of the work.
#[cfg(test)]
std::thread_local! {
static NAME_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static NAME_BYTE_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
}
#[inline]
fn count_name_bytes(count: usize) {
#[cfg(test)]
{
let read = NAME_BYTES.with(|read| {
read.set(read.get().saturating_add(count));
read.get()
});
let limit = NAME_BYTE_LIMIT.with(std::cell::Cell::get);
assert!(read <= limit, "{read} bytes read for reference names, more than the {limit} allowed");
}
#[cfg(not(test))]
let _ = count;
}
/// What entity `name` expands to (bytes), references in its value followed.
fn expanded<'a>(name: &'a str, entities: &HashMap<&'a str, Vec<&'a str>>, memo: &mut HashMap<&'a str, usize>, depth: u32) -> usize {
if let Some(n) = memo.get(name) {
@@ -501,11 +530,12 @@ mod tests {
assert!(!expansion_too_large("<svg a=\"&amp;&#10;\"/>"));
// Many `&`s with no `;` after them are read in linear time.
let ampersands = format!("<!DOCTYPE svg [<!ENTITY a \"x\">]><svg id=\"{}\"/>", "&".repeat(1 << 20));
let start = std::time::Instant::now();
// At most the longest name and its `;` after each `&`; a quadratic read is past this limit
// long before its end.
NAME_BYTES.with(|read| read.set(0));
NAME_BYTE_LIMIT.with(|limit| limit.set(ampersands.matches('&').count() * (MAX_NAME + 1)));
assert!(!expansion_too_large(&ampersands));
eprintln!("DIAG svg ampersand run read in {:?}", start.elapsed());
// A quadratic read would take hours; the bound is loose for a loaded machine.
assert!(start.elapsed() < std::time::Duration::from_secs(120), "{:?}", start.elapsed());
NAME_BYTE_LIMIT.with(|limit| limit.set(usize::MAX));
}
#[test]
+162 -42
View File
@@ -4,11 +4,10 @@
use super::length::{DocUnit, length_field, shown};
use craft_behavior::{EditEvent, EditEvents, Metrics, Mixed, NumberCodec};
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{
Bind, Common, Component, Cx, Entry, FieldLayout, MeasureCx, PaintUi, Props as _, Role, Show as _, ShowContainer as _, SideLabel, Sizing,
Validity, clicked,
Bind, Common, Component, Cx, Entry, FieldLayout, MeasureCx, PaintUi, Pointer as _, Props as _, Role, Show as _, ShowContainer as _, SideLabel,
Sizing, Validity,
};
use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft_ui::form::{Field, FieldGroup};
@@ -18,7 +17,7 @@ use craft_ui::primitives::{PaintShape, StrokeWidth};
use craft_ui::runtime::env::{Env, Label, Message, Units};
use craft_ui::runtime::words::CommonWords;
use craft_ui::sections::{DialogRole, FooterButton, GroupBox};
use craft_ui::style::{ComponentStyle, StyleColor, StyleCx, SurfaceKind, TypeRole};
use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, SurfaceKind, TypeRole};
use craft_ui::text::{NumberField, NumberOutput};
use egui::{Pos2, Rect, Ui, Vec2, pos2, vec2};
use std::cell::Cell;
@@ -129,6 +128,19 @@ pub enum ColumnsPreset {
Right,
}
impl ColumnsPreset {
/// The number of columns, and for Left and Right whether the narrow one is first.
fn shape(self) -> (u32, Option<bool>) {
match self {
ColumnsPreset::One => (1, None),
ColumnsPreset::Two => (2, None),
ColumnsPreset::Three => (3, None),
ColumnsPreset::Left => (2, Some(true)),
ColumnsPreset::Right => (2, Some(false)),
}
}
}
/// The Columns dialog: only what changed comes back.
///
/// - [`word`](Self::word) off (PowerPoint): Number (1 to [`MAX_COLUMNS`]) and Spacing (0 to [`MAX_SPACING`] points);
@@ -287,13 +299,7 @@ impl TextColumnsDialog {
let Some(width) = self.word else { return };
let spacing = DEFAULT_SPACING;
self.edited.spacing = Some(spacing);
let (count, narrow_first) = match preset {
ColumnsPreset::One => (1, None),
ColumnsPreset::Two => (2, None),
ColumnsPreset::Three => (3, None),
ColumnsPreset::Left => (2, Some(true)),
ColumnsPreset::Right => (2, Some(false)),
};
let (count, narrow_first) = preset.shape();
self.edited.count = Some(count);
match narrow_first {
None => {
@@ -533,7 +539,11 @@ impl TextColumnsDialog {
let mut chosen = None;
Row::new().show(ui, |ui, _| {
for (preset, label) in every {
if clicked(&Button::new(label.clone()).show(ui)) {
let tile = Field::new(label.clone())
.layout(FieldLayout::Above)
.sizing(Sizing::Content)
.show(ui, |ui, _| ColumnsPresetTile::new(label.clone(), Self::preset_rows(preset)).show(ui).clicked);
if tile.inner == Some(true) {
chosen = Some(preset);
}
}
@@ -543,6 +553,25 @@ impl TextColumnsDialog {
}
}
/// The columns a preset draws as, over a text width of 1 and a spacing of a twelfth.
pub(crate) fn preset_rows(preset: ColumnsPreset) -> Vec<(f32, f32)> {
let (count, narrow_first) = preset.shape();
let spacing = 1.0 / 12.0;
match narrow_first {
// Not `even_rows`: its minimum column width is in points and would close the gaps over a width of 1.
None => {
let each = (1.0 - spacing * (count - 1) as f32) / count as f32;
(0..count).map(|i| (each, if i + 1 < count { spacing } else { 0.0 })).collect()
}
Some(left) => {
let narrow = (1.0 - spacing) * NARROW_SHARE;
let wide = 1.0 - spacing - narrow;
let (first, second) = if left { (narrow, wide) } else { (wide, narrow) };
vec![(first, spacing), (second, 0.0)]
}
}
}
/// One row per column: its number, then its width and the spacing after it, each behind its caption.
fn grid(&mut self, ui: &mut Ui, words: &TextColumnsWords, units: &Units) {
let rows = self.rows();
@@ -723,6 +752,25 @@ pub struct ColumnsPreviewStyle {
pane: f32,
/// The distance between text lines.
pitch: f32,
#[style(focus)]
focus: FocusLook,
}
impl ColumnsPreviewStyle {
/// The preview's look; a preset thumbnail takes the same with a smaller pane.
fn at(cx: &StyleCx<'_>) -> Self {
let colors = &cx.tokens.color;
ColumnsPreviewStyle {
metrics: Metrics::new(),
page: cx.color(colors.surface.raised),
edge: cx.color(colors.line.border),
line: cx.color(colors.text.faint),
separator: cx.color(colors.text.normal),
pane: cx.tokens.size.thumb.sample.lg,
pitch: cx.tokens.typography.get(TypeRole::Body).line_height * LINE_PITCH,
focus: cx.focus_look(),
}
}
}
/// The page preview: the columns and the line between them on a page, as Word's dialog draws it.
@@ -750,16 +798,7 @@ impl Component for ColumnsPreview {
type Output = egui::Response;
fn style(cx: &StyleCx<'_>, _: ColumnsPreviewStyleKey) -> ColumnsPreviewStyle {
let colors = &cx.tokens.color;
ColumnsPreviewStyle {
metrics: Metrics::new(),
page: cx.color(colors.surface.raised),
edge: cx.color(colors.line.border),
line: cx.color(colors.text.faint),
separator: cx.color(colors.text.normal),
pane: cx.tokens.size.thumb.md,
pitch: cx.tokens.typography.get(TypeRole::Body).line_height * LINE_PITCH,
}
ColumnsPreviewStyle::at(cx)
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
@@ -767,26 +806,15 @@ impl Component for ColumnsPreview {
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let style = cx.style;
let pane = cx.rect;
let height = pane.height().min(pane.width() / PAGE_ASPECT);
let page = Rect::from_center_size(pane.center(), vec2(height * PAGE_ASPECT, height));
let draw = ui.draw();
draw.surface(pane, SurfaceKind::Sunken, craft_ui::style::Corners::None);
draw.fill(&PaintShape::Rect(page, egui::CornerRadius::ZERO), style.page);
draw.stroke(&PaintShape::Rect(page, egui::CornerRadius::ZERO), StrokeWidth::Thin, style.edge);
let plan = preview_plan(&self.rows, self.text_width, self.line_between, page);
let line = |a: Pos2, b: Pos2, color: StyleColor| draw.stroke(&PaintShape::Path(vec![a, b]), StrokeWidth::Thin, color);
for &(left, right) in &plan.columns {
let mut y = plan.text.top();
while y + style.pitch / 2.0 <= plan.text.bottom() {
line(pos2(left, y), pos2(right, y), style.line);
y += style.pitch;
}
}
for &x in &plan.separators {
line(pos2(x, plan.text.top()), pos2(x, plan.text.bottom()), style.separator);
}
paint_columns(
ui,
[cx.style.page, cx.style.edge, cx.style.line, cx.style.separator],
cx.style.pitch,
cx.rect,
&self.rows,
self.text_width,
self.line_between,
);
}
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
@@ -794,6 +822,98 @@ impl Component for ColumnsPreview {
}
}
/// Draws the page of `rows` over `text_width` in `pane`.
fn paint_columns(ui: &mut PaintUi<'_>, inks: [StyleColor; 4], pitch: f32, pane: Rect, rows: &[(f32, f32)], text_width: f32, line_between: bool) {
let height = pane.height().min(pane.width() / PAGE_ASPECT);
let page = Rect::from_center_size(pane.center(), vec2(height * PAGE_ASPECT, height));
let draw = ui.draw();
draw.surface(pane, SurfaceKind::Sunken, craft_ui::style::Corners::None);
let [page_ink, edge, text, separator] = inks;
draw.fill(&PaintShape::Rect(page, egui::CornerRadius::ZERO), page_ink);
draw.stroke(&PaintShape::Rect(page, egui::CornerRadius::ZERO), StrokeWidth::Thin, edge);
let plan = preview_plan(rows, text_width, line_between, page);
let line = |a: Pos2, b: Pos2, color: StyleColor| draw.stroke(&PaintShape::Path(vec![a, b]), StrokeWidth::Thin, color);
for &(left, right) in &plan.columns {
let mut y = plan.text.top();
while y + pitch / 2.0 <= plan.text.bottom() {
line(pos2(left, y), pos2(right, y), text);
y += pitch;
}
}
for &x in &plan.separators {
line(pos2(x, plan.text.top()), pos2(x, plan.text.bottom()), separator);
}
}
/// A preset's thumbnail: a small page with the preset's columns, a button named by the label.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
pub struct ColumnsPresetTile {
#[common]
common: Common,
rows: Vec<(f32, f32)>,
clicked: bool,
}
/// What a preset tile reports.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ColumnsPresetTileOutput {
/// The tile's response.
pub response: egui::Response,
/// A click, Space or Enter reached the enabled tile.
pub clicked: bool,
}
impl craft_ui::contract::Outcome for ColumnsPresetTileOutput {
type Value = craft_ui::contract::NoValue;
fn response(&self) -> &egui::Response {
&self.response
}
}
impl ColumnsPresetTile {
/// A tile named `label` drawing `rows` (each column's width and the spacing after it).
pub fn new(label: impl Into<Label>, rows: Vec<(f32, f32)>) -> Self {
ColumnsPresetTile { common: Common::new(), rows, clicked: false }.label(label)
}
}
impl Component for ColumnsPresetTile {
const ROLE: Role = Role::BUTTON;
const PARTS: bool = false;
const OVERLAYS: bool = false;
type Style = ColumnsPreviewStyle;
type Output = ColumnsPresetTileOutput;
fn style(cx: &StyleCx<'_>, _: ColumnsPresetTileStyleKey) -> ColumnsPreviewStyle {
let mut style = ColumnsPreviewStyle::at(cx);
style.pane = cx.tokens.size.thumb.lg;
style.pitch /= 2.0;
style
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::splat(cx.style.pane)
}
fn sense(&self) -> craft_behavior::Sense {
craft_behavior::Sense::CLICK | craft_behavior::Sense::FOCUS
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
self.clicked = cx.activation().is_some() && cx.resolved.enabled;
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
paint_columns(ui, [cx.style.page, cx.style.edge, cx.style.line, cx.style.separator], cx.style.pitch, cx.rect, &self.rows, 1.0, false);
}
fn finish(self, cx: Cx<'_, Self>) -> ColumnsPresetTileOutput {
ColumnsPresetTileOutput { response: cx.response.clone(), clicked: self.clicked }
}
}
/// A choice from the Columns menu.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
+6 -1
View File
@@ -1,6 +1,6 @@
//! Stories of the Columns dialog and the page preview.
use super::{ColumnsApply, ColumnsPreview, TextColumns, TextColumnsDialog};
use super::{ColumnsApply, ColumnsPresetTile, ColumnsPreview, TextColumns, TextColumnsDialog};
use craft_ui::contract::Show as _;
use craft_ui::dialog::{DialogStack, StackDialog as _};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
@@ -24,3 +24,8 @@ fn preview(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let rows = vec![(140.0, 24.0), (140.0, 24.0), (140.0, 0.0)];
ColumnsPreview::new("Preview", rows, TEXT_WIDTH, true).show(ui).into()
}
#[story(ColumnsPresetTile, covers = [Default], drive = Drive::Activate)]
fn preset_tile(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
ColumnsPresetTile::new("Left", vec![(0.3, 1.0 / 12.0), (0.62, 0.0)]).show(ui).into()
}
+60
View File
@@ -0,0 +1,60 @@
//! The Columns dialog's preset thumbnails and page preview.
use craft_text::ui::columns::{ColumnsApply, TextColumns, TextColumnsDialog};
use craft_ui::dialog::{DialogStack, StackDialog as _};
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers};
use std::cell::RefCell;
use std::rc::Rc;
fn opened() -> (Fixture, Rc<RefCell<TextColumnsDialog>>) {
let columns = TextColumns { count: Some(1), spacing: Some(36.0), equal_width: Some(true), line_between: Some(false), ..TextColumns::default() };
let dialog = Rc::new(RefCell::new(TextColumnsDialog::new(columns).word(468.0).apply_to(&[ColumnsApply::Document], ColumnsApply::Document)));
let shown = dialog.clone();
let mut fixture = Fixture::new(move |ui| {
let _ = shown.borrow_mut().show(ui, &DialogStack::default());
});
fixture.idle(2);
(fixture, dialog)
}
/// A preset is a drawn thumbnail that a click applies, and the preview is larger than the thumbnail.
#[trial]
fn a_preset_thumbnail_applies_its_preset_and_the_preview_is_larger() {
let (mut fixture, dialog) = opened();
let tile = fixture.by_label("Two").expect("the Two preset");
let preview = fixture.by_label("Preview").expect("the preview");
let field = fixture.by_label("Line between").expect("a text control");
assert!(tile.rect.height() > field.rect.height() * 1.5, "a drawn thumbnail, not a text button: {:?} against {:?}", tile.rect, field.rect);
assert!(preview.rect.width() > tile.rect.width(), "preview {:?} over tile {:?}", preview.rect, tile.rect);
fixture.click(&tile).idle(4);
assert_eq!(dialog.borrow().edited().count, Some(2));
}
/// Tab reaches a preset thumbnail and draws a focus ring on it.
#[trial]
fn a_focused_preset_thumbnail_draws_a_focus_ring() {
use craft_text::ui::columns::ColumnsPresetTile;
use craft_ui::contract::Show as _;
let mut fixture = Fixture::new(|ui| {
let _ = ColumnsPresetTile::new("Left", vec![(1.0, 0.0)]).show(ui);
});
fixture.idle(2);
let before = fixture.frame_shapes().len();
fixture.key(Key::Tab, Modifiers::NONE).idle(2);
assert!(fixture.focused().is_some(), "Tab reaches the thumbnail");
let after = fixture.frame_shapes().len();
assert!(after > before, "focus adds a ring: {before} shapes before, {after} after");
}
/// Every preset thumbnail draws its columns apart, over a text width of 1: gaps between them, nothing past the page.
#[trial]
fn preset_thumbnails_draw_their_columns_apart() {
use craft_text::ui::columns::ColumnsPreset::{Left, One, Right, Three, Two};
for preset in [One, Two, Three, Left, Right] {
let rows = TextColumnsDialog::preset_rows(preset);
let total: f32 = rows.iter().map(|(width, gap)| width + gap).sum();
assert!((total - 1.0).abs() < 1e-4, "{preset:?} fills the text width: {rows:?}");
assert!(rows[..rows.len() - 1].iter().all(|(_, gap)| *gap > 0.0), "{preset:?} has a gap between columns: {rows:?}");
}
}
+1
View File
@@ -2,6 +2,7 @@
// Unwrapping, expecting and panicking on failure is fine in tests, unlike in shipped code.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
pub(crate) mod columns;
pub(crate) mod editor;
#[cfg(feature = "find")]
pub(crate) mod find;
+29 -2
View File
@@ -227,8 +227,30 @@ impl VariantLook {
// A disabled solid button keeps its shape: its solid colour dimmed towards the disabled fill, which alone
// would match the panel and leave only the label.
Emphasis::Solid => {
let dimmed = crate::derive::mix(solid, c.state.disabled_fill, DISABLED_SOLID_DIM);
VariantLook::new(States::new(solid, solid_hover, solid_pressed, dimmed), text(on_solid)).radius(button)
// Dimmed towards the disabled fill until it differs from the enabled fill by
// `DISABLED_SOLID_SEPARATION`, so a dark theme's disabled button is not taken for an enabled one. A theme
// whose disabled fill is itself close to the solid colour dims towards black, then white, instead.
let dim = |to: Rgba| {
let mut at = DISABLED_SOLID_DIM;
let mut fill = crate::derive::mix(solid, to, at);
while at < DISABLED_SOLID_DIM_MAX && crate::contrast::contrast_ratio(fill, solid) < DISABLED_SOLID_SEPARATION {
at += 0.05;
fill = crate::derive::mix(solid, to, at);
}
fill
};
let apart = |fill: Rgba| crate::contrast::contrast_ratio(fill, solid) >= DISABLED_SOLID_SEPARATION;
let dimmed = [c.state.disabled_fill, Rgba::BLACK, Rgba::WHITE]
.into_iter()
.map(dim)
.find(|fill| apart(*fill))
.unwrap_or_else(|| dim(c.state.disabled_fill));
// Its label is the disabled ink moved off the dimmed fill until it reads (4.5:1): the disabled grey alone
// is pale on a pale blue block and says nothing.
let label =
crate::contrast::ensure_contrast(c.text.disabled, dimmed, crate::contrast::text_contrast_min(crate::theme::Contrast::Standard));
let text = States::new(on_solid, on_solid, on_solid, label);
VariantLook::new(States::new(solid, solid_hover, solid_pressed, dimmed), text).radius(button)
}
Emphasis::Soft => VariantLook::new(States::new(soft_fill, soft_fill, soft_fill, c.state.disabled_fill), text(fg))
.edge(States::new(edge, edge, edge, c.line.divider))
@@ -256,6 +278,11 @@ impl VariantLook {
/// How far a disabled solid fill moves from its solid colour to the disabled fill.
const DISABLED_SOLID_DIM: f64 = 0.5;
/// The least contrast ratio between a disabled solid fill and the enabled one, and how far the fill may be dimmed to
/// get it.
const DISABLED_SOLID_SEPARATION: f64 = 1.5;
const DISABLED_SOLID_DIM_MAX: f64 = 0.95;
/// A look for one component's style key, built in a `const`. It describes itself; nothing registers it.
#[derive(Clone, Copy)]
pub struct CustomVariant {
+37
View File
@@ -0,0 +1,37 @@
//! A disabled solid button (primary, danger) keeps a readable label and stays clearly unlike the enabled one in every
//! built-in theme and contrast setting (wordcraft#7978).
use craft_theme::contrast::contrast_ratio;
use craft_theme::{Appearance, Contrast, Mode, Size, TextSize, Variant, Variants, builtins, resolve};
/// Least contrast ratio between the disabled fill and the enabled one.
const FILL_SEPARATION: f64 = 1.5;
#[test]
fn disabled_solid_label_reads_and_the_button_is_not_the_enabled_one() {
for theme in builtins() {
// Classic draws a disabled button with its bevel; its pinned greys are not this look.
if theme.name == "Classic" {
continue;
}
let modes = match theme.variants {
Variants::Both => vec![Mode::Light, Mode::Dark],
Variants::LightOnly => vec![Mode::Light],
Variants::DarkOnly => vec![Mode::Dark],
};
for mode in modes {
for contrast in [Contrast::Standard, Contrast::High] {
let appearance = Appearance { mode, contrast, size: Size::Comfortable, text_size: TextSize::Small, reduced_motion: false };
let tokens = resolve(theme, appearance, None).tokens;
for variant in [Variant::PRIMARY, Variant::DANGER] {
let look = variant.resolve(&tokens);
let who = format!("{} {mode:?} {contrast:?} {variant:?}", theme.name);
let label = contrast_ratio(look.text.disabled, look.fill.disabled);
assert!(label >= 4.5, "{who}: disabled label is {label:.2}:1");
let apart = contrast_ratio(look.fill.disabled, look.fill.rest);
assert!(apart >= FILL_SEPARATION, "{who}: disabled fill is {apart:.2}:1 from the enabled one");
}
}
}
}
}
+1
View File
@@ -1,5 +1,6 @@
//! Integration tests, built into the library's own test executable.
mod disabled_solid;
mod dumps;
mod selection;
mod strong_hover;
+38 -7
View File
@@ -155,6 +155,7 @@ impl ImageInfo {
let mut sorted: Vec<u64> = Vec::new();
if (0..n).any(|i| self.byte_counts.get(i).is_none_or(|&l| l == 0)) {
sorted = self.offsets.clone();
count_offset_reads(sorted.len());
sorted.sort_unstable();
sorted.dedup();
}
@@ -173,7 +174,13 @@ impl ImageInfo {
Some(&l) if l > 0 => l,
_ => {
// infer: up to the next larger offset, else end of data
let next = sorted.get(sorted.partition_point(|&o| o <= offset)).copied().unwrap_or(data_len);
let next = sorted
.get(sorted.partition_point(|&o| {
count_offset_reads(1);
o <= offset
}))
.copied()
.unwrap_or(data_len);
next.saturating_sub(offset)
}
};
@@ -183,6 +190,30 @@ impl ImageInfo {
}
}
// The offsets `ImageInfo::chunks` sorts and then reads to infer missing byte counts, on this
// thread, and the most a test lets it read: past that the count fails the test at once rather
// than after the rest of the work.
#[cfg(test)]
std::thread_local! {
static OFFSET_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static OFFSET_READ_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
}
#[inline]
fn count_offset_reads(count: usize) {
#[cfg(test)]
{
let reads = OFFSET_READS.with(|reads| {
reads.set(reads.get().saturating_add(count));
reads.get()
});
let limit = OFFSET_READ_LIMIT.with(std::cell::Cell::get);
assert!(reads <= limit, "{reads} offsets read, more than the {limit} allowed");
}
#[cfg(not(test))]
let _ = count;
}
/// The bytes of a chunk, clipped to the available data (truncated files yield a shorter slice).
/// Returns `None` only when the chunk starts past the end of `data`.
pub fn chunk_bytes<'a>(data: &'a [u8], c: &Chunk) -> Option<&'a [u8]> {
@@ -229,12 +260,12 @@ mod tests {
fn many_strips_without_byte_counts_are_fast() {
let n = 1_000_000u64;
let info = strips((0..n).rev().map(|i| 1000 + i * 2).collect(), Vec::new());
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let chunks = info.chunks(1000 + n * 2);
let _ = tx.send(chunks.iter().map(|c| c.len).collect::<Vec<u64>>());
});
let lens = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("chunks() took longer than 20 s");
// One sort of the offsets, then a bisection of them per strip, not a scan or a sort per strip.
let per_strip = n.ilog2() as usize + 2;
OFFSET_READS.with(|reads| reads.set(0));
OFFSET_READ_LIMIT.with(|limit| limit.set(n as usize * (per_strip + 1)));
let lens: Vec<u64> = info.chunks(1000 + n * 2).iter().map(|c| c.len).collect();
OFFSET_READ_LIMIT.with(|limit| limit.set(usize::MAX));
assert!(lens.iter().all(|&l| l == 2));
}
}
+3 -1
View File
@@ -89,7 +89,9 @@ impl<'a> RotateView<'a> {
}
/// The compass' rect in the top corner of `canvas` where the reading direction ends, a medium thumbnail side
/// across (`size.thumb.md`, as the old `compass_rect`), inset from the canvas edges by the stack gap.
/// across (`size.thumb.md`, as the old `compass_rect`), inset from the canvas edges by the stack gap. A canvas that
/// shows scroll bars passes [`CanvasScrollbars::clear_of`](super::CanvasScrollbars::clear_of) its rect, so the
/// vertical bar does not cover the compass.
pub fn compass_rect(ui: &Ui, canvas: Rect) -> Rect {
let env = Env::of(ui);
let corner = if env.direction.is_rtl() { Align2::LEFT_TOP } else { Align2::RIGHT_TOP };
+19 -5
View File
@@ -151,6 +151,8 @@ pub struct RulersStyle {
cross: StyleColor,
/// The halo under the cross hairs, so they read on the paper, the pasteboard and any art.
halo: StyleColor,
/// The side of the "+" the corner shows to mark the draggable zero point.
origin_mark: f32,
}
/// The type role of the tick labels.
@@ -197,8 +199,9 @@ enum MenuRow {
/// - A drag on the top ruler reports a horizontal guide in [`RulersOutput::guide`] and to the canvas's body
/// ([`ruler_guide`](super::ruler_guide)), one on the left ruler a vertical guide; Alt turns it, Shift snaps it to the ticks, and a release over a ruler or off the document reports no
/// position, which removes the guide.
/// - A drag out of the corner moves the zero point: cross hairs show where it lands, Shift snaps to the ticks
/// (otherwise the canvas's [`Snap`]), dropped back on the corner it stays, Esc cancels. A double click
/// - The corner shows a "+" that marks the zero point. A drag out of the corner moves the zero point: cross hairs show
/// where it lands, Shift snaps to the ticks (otherwise the canvas's [`Snap`]), dropped back on the corner it stays,
/// Esc cancels. A double click
/// on the corner and the menu's Reset Zero Point put the zero point back at the document's origin, one edit through the zero bind. The arrow keys move the focused corner. [`origin_locked`](Rulers::origin_locked)
/// turns the drag and the reset off.
/// - A secondary click on a strip or the corner, or the Menu key or Shift+F10 on the focused corner, opens the units
@@ -388,6 +391,7 @@ impl Component for Rulers<'_> {
marker: cx.color(c.text.normal),
cross: cx.color(c.overlay.stroke),
halo: cx.color(c.overlay.halo),
origin_mark: cx.tokens.size.handle.md,
}
}
@@ -502,8 +506,10 @@ impl Component for Rulers<'_> {
let numbers = cx.env.units();
let words = cx.words::<CanvasWords>();
let shown = self.published().x.kind;
// A menu row's `&` marks its mnemonic, so the `&` of a unit's name ("Feet & Inches") is doubled to show as written.
let row_name = |kind: UnitKind| Label::from(numbers.name(kind).as_str().replace('&', "&&"));
let mut entries: Vec<Entry<MenuRow>> =
units.iter().map(|&kind| Entry::new(MenuRow::Unit(kind), numbers.name(kind)).checked(kind == shown)).collect();
units.iter().map(|&kind| Entry::new(MenuRow::Unit(kind), row_name(kind)).checked(kind == shown)).collect();
entries.push(Entry::separator());
entries.push(Entry::new(MenuRow::ResetZero, Label::from(words.ruler_reset_zero.as_str().to_owned())).enabled(!self.origin_locked));
let name = Label::from(words.ruler_menu.as_str().to_owned());
@@ -550,8 +556,16 @@ impl Component for Rulers<'_> {
draw.fill(&rect(top), style.fill);
draw.fill(&rect(left), style.fill);
let Some(space) = space else {
// The corner: its fill and the "+" that marks the zero point a drag from it moves.
let paint_corner = || {
draw.fill(&rect(corner), style.fill);
let (c, arm) = (corner.center(), style.origin_mark / 2.0);
for (from, to) in [(c - Vec2::new(arm, 0.0), c + Vec2::new(arm, 0.0)), (c - Vec2::new(0.0, arm), c + Vec2::new(0.0, arm))] {
draw.stroke(&PaintShape::Path(vec![from, to]), StrokeWidth::Thin, style.marker);
}
};
let Some(space) = space else {
paint_corner();
return;
};
let face = style.face;
@@ -678,7 +692,7 @@ impl Component for Rulers<'_> {
}
}
draw.fill(&rect(corner), style.fill);
paint_corner();
draw.edge_rule(RuleKind::Divider, top, RectSide::Bottom);
draw.edge_rule(RuleKind::Divider, left, RectSide::Right);
}
+25 -5
View File
@@ -27,15 +27,15 @@ use crate::display::Text;
use crate::primitives::{Draw, PaintShape, ScrollBar, StrokeWidth};
use crate::runtime::access::Numeric;
use crate::runtime::commands::FireSource;
use crate::runtime::env::Label;
use crate::runtime::env::{Env, Label};
use crate::runtime::focus::KeyUse;
use crate::runtime::frame;
use crate::style::{ComponentStyle, ScrollBarKind, ScrollBarLook, Stateful, StyleColor, StyleCx};
use crate::style::{ComponentStyle, ScrollBarKind, ScrollBarLook, Stateful, StyleColor, StyleCx, UiTokens};
use craft_behavior::kurbo::{Point, Rect as DocRect};
use craft_behavior::overlay::{Align, Side};
use craft_behavior::scroll::ScrollSpan;
use craft_behavior::{Axis, CanvasView, Metrics, PartKey, PartRef, PressPhase, PressStart, Sense};
use egui::{CornerRadius, Pos2, Rect, Response, Vec2, pos2, vec2};
use egui::{CornerRadius, Pos2, Rect, Response, Ui, Vec2, pos2, vec2};
use std::ops::{Deref, Range};
const HORIZONTAL: PartKey = PartKey::new("horizontal");
@@ -55,6 +55,13 @@ const KEPT_IN_VIEW: f64 = 100.0;
/// The popup of the tip beside a dragged vertical thumb.
const TIP: &str = "tip";
/// A bar's thickness and the margin it keeps from the canvas's edges, from `tokens`: the docked bars keep a tight gap,
/// the document window's bars none.
fn bar_size(tokens: &UiTokens, document_chrome: bool) -> (f32, f32) {
let margin = if document_chrome { 0.0 } else { tokens.space.gap.tight };
(tokens.size.icon.md, margin)
}
/// The thumb part that `PartsCx::scroll` declares for the bar `bar`.
fn thumb_of(bar: PartKey) -> PartRef {
bar.at(THUMB)
@@ -476,6 +483,19 @@ impl<'a> CanvasScrollbars<'a> {
changed
}
/// `rect`, a canvas's rect the bars are shown in, without the strips they take: the vertical bar's along the right
/// edge and, unless `vertical_only`, the horizontal bar's along the bottom. `document_chrome` is the bars' own flag.
/// A canvas control placed in a corner of the view (the Rotate View compass) is placed inside this rect so the bars
/// do not cover it.
pub fn clear_of(ui: &Ui, rect: Rect, document_chrome: bool, vertical_only: bool) -> Rect {
let env = Env::of(ui);
let (thickness, margin) = bar_size(&env.tokens, document_chrome);
let strip = thickness + margin;
let right = (rect.right() - strip).max(rect.left());
let bottom = if vertical_only { rect.bottom() } else { (rect.bottom() - strip).max(rect.top()) };
Rect::from_min_max(rect.min, pos2(right, bottom))
}
fn bars(&self, view: &CanvasView, rect: Rect, style: &ScrollbarsStyle, held: Option<&HeldThumb>) -> Bars {
// A horizontal thumb held keeps its bar until the press ends, so its release closes the drag.
let horizontal = !self.vertical_only || held.is_some_and(|held| held.on(Axis::X));
@@ -491,8 +511,8 @@ impl Component for CanvasScrollbars<'_> {
fn style(cx: &StyleCx<'_>, key: CanvasScrollbarsStyleKey) -> ScrollbarsStyle {
let mut look = cx.scroll_bar_of(ScrollBarKind::Docked);
look.thickness = cx.tokens.size.icon.md;
let margin = if key.document_chrome { 0.0 } else { cx.tokens.space.gap.tight };
let (thickness, margin) = bar_size(cx.tokens, key.document_chrome);
look.thickness = thickness;
let document = key.document_chrome.then(|| {
let color = &cx.tokens.color;
look.track = Stateful::new(cx.color(color.surface.sunken));
+71 -1
View File
@@ -2,7 +2,7 @@
use craft_behavior::geometry::{SnapOptions, SnapTargets};
use craft_behavior::kurbo::{Point, Rect as DocRect};
use craft_behavior::{CancelReason, CanvasView, RulerUnits, TickLabels, Ticks};
use craft_behavior::{CancelReason, CanvasView, Mixed, RulerUnits, TickLabels, Ticks};
use craft_ui::canvas::{
CENTIMETRE_LABEL_STEP_MIN, Canvas, CanvasTool, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, PageFrame, Pasteboard, RulerText, Rulers, Snap,
StepLadder, TickRule, ToolAction, ToolContext, ToolPath, ToolPointer,
@@ -268,6 +268,43 @@ fn the_units_menu_names_each_unit() {
}
}
/// A ruler counting Feet & Inches checks the Feet & Inches row of the units menu, not the Feet row beside it, and
/// picking Feet & Inches reports that unit rather than Feet.
#[trial]
fn the_units_menu_tells_feet_and_inches_from_feet() {
const UNITS: [UnitKind; 3] = [UnitKind::Inches, UnitKind::Feet, UnitKind::FeetInches];
let text = RulerText::new(RulerUnits::new(1.0 / 864.0, Ticks::decimal(false)), UnitKind::FeetInches);
let zero = Rc::new(RefCell::new(Point::ZERO));
let shown_zero = Rc::clone(&zero);
let room = Rc::new(Cell::new(Rect::NOTHING));
let shown_room = Rc::clone(&room);
let picked = Rc::new(Cell::new(None));
let seen = Rc::clone(&picked);
let mut fixture = Fixture::new(move |ui| {
let at = ui.available_rect_before_wrap();
shown_room.set(at);
let view = CanvasView::new(at, Point::new(f64::from(at.center().x), f64::from(at.center().y)), 1.0);
let mut zero = shown_zero.borrow_mut();
let rulers = Rulers::new("Rulers", Bind::bound(&mut *zero)).units(&UNITS);
let shown = Canvas::new("Document").view(view).with_rulers(Some(rulers)).rulers(text, text).show(ui, |_, _| {});
if let Some(kind) = shown.output.rulers.and_then(|rulers| rulers.unit_picked) {
seen.set(Some(kind));
}
});
fixture.room(Vec2::new(500.0, 400.0)).settle();
let at = egui::pos2(room.get().center().x, room.get().min.y + 4.0);
fixture.frame(vec![craft_ui::testing::pointer::moved(at)]);
fixture.frame(vec![craft_ui::testing::pointer::secondary(at, true)]);
fixture.frame(vec![craft_ui::testing::pointer::secondary(at, false)]);
fixture.settle();
let feet_inches = fixture.by_label("Feet & Inches").expect("the menu lists Feet & Inches");
let feet = fixture.by_label("Feet").expect("the menu lists Feet");
assert_eq!(fixture.tree().toggled_of(feet_inches.node), Some(Mixed::Same(true)), "the ruler's unit is checked");
assert_ne!(fixture.tree().toggled_of(feet.node), Some(Mixed::Same(true)), "Feet is not checked for a Feet & Inches ruler");
fixture.click(&feet_inches).settle();
assert_eq!(picked.get(), Some(UnitKind::FeetInches), "the pick names Feet & Inches");
}
/// A drag of the rulers' corner with one move past the drag threshold, released there, moves the zero point to where it
/// was released: the drag proposes its landing at its start and at its release, not only on the moves between.
#[trial]
@@ -350,6 +387,39 @@ fn cross_hair_strokes(mode: craft_theme::Mode, contrast: craft_theme::Contrast)
(strokes, pasteboard)
}
/// The rulers' corner marks the draggable zero point with a "+": a level and an upright line, each centred in the
/// corner and inside it.
#[trial]
fn the_ruler_corner_marks_the_zero_point_with_a_plus() {
let room = Vec2::new(800.0, 600.0);
let view = CanvasView::new(Rect::from_min_size(Pos2::ZERO, room), Point::new(400.0, 300.0), 1.0);
let text = RulerText::new(RulerUnits::pixels(), UnitKind::Pixels);
let mut zero = Point::ZERO;
let mut fixture = Fixture::new(move |ui| {
let strips = Rulers::new("Rulers", Bind::bound(&mut zero));
let _ = Canvas::new("Document").view(view).with_rulers(Some(strips)).rulers(text, text).show(ui, |_, _| {});
});
fixture.room(room);
fixture.settle();
let corner = fixture.by_label("Ruler origin").expect("the rulers' corner").rect;
let lines: Vec<[Pos2; 2]> = fixture
.frame_shapes()
.iter()
.filter_map(|shape| match shape {
Shape::LineSegment { points, .. } => Some(*points),
Shape::Path(path) if path.points.len() == 2 => Some([path.points[0], path.points[1]]),
_ => None,
})
.filter(|[a, b]| corner.contains(*a) && corner.contains(*b))
.collect();
// The pointer marker crosses the whole corner under its fill; the plus is shorter than the corner's side.
let mark = |length: f32| length > 1.0 && length < corner.width() * 0.75;
let centred = |a: Pos2, b: Pos2| ((a + b.to_vec2()) / 2.0 - corner.center()).length() < 1.0;
let level = lines.iter().any(|[a, b]| (a.y - b.y).abs() < 0.01 && mark((a.x - b.x).abs()) && centred(*a, *b));
let upright = lines.iter().any(|[a, b]| (a.x - b.x).abs() < 0.01 && mark((a.y - b.y).abs()) && centred(*a, *b));
assert!(level && upright, "the corner {corner:?} shows a centred plus: lines {lines:?}");
}
/// With artboards hidden the paper fills the canvas, so the zero point's cross hairs cross the paper as well as the
/// pasteboard and dark art. Over each, the top line contrasts with what lies under it (the strokes below it over the
/// backdrop) by the minimum the theme sets for overlay strokes on their halo: 3 to 1, and 4.5 to 1 in high contrast.
+33 -1
View File
@@ -5,7 +5,7 @@ use std::rc::Rc;
use craft_behavior::kurbo::{Point, Rect as DocRect, Size};
use craft_behavior::{Axis, CanvasView};
use craft_ui::canvas::{Canvas, CanvasScrollbars, NavigationOptions, Rulers, canvas_space};
use craft_ui::canvas::{Canvas, CanvasScrollbars, NavigationOptions, RotateView, Rulers, canvas_space};
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::runtime::access::Role;
use craft_ui::runtime::env::Label;
@@ -504,3 +504,35 @@ fn after_a_thumb_drag_the_bars_follow_a_new_zoom() {
let first = shown_range(&view.get(), Axis::X).0;
assert!((first - fresh).abs() < 1.0, "after a thumb drag paging reaches the same end: shows from {first}, without the drag {fresh}");
}
/// The Rotate View compass of a turned view, placed in `CanvasScrollbars::clear_of` the window, sits clear of the
/// vertical bar, and that rect stops above the horizontal bar, with or without the document chrome.
#[trial]
fn the_rotate_view_compass_placed_clear_of_the_bars_is_not_covered_by_them() {
for chrome in [false, true] {
let large = Size::new(4000.0, 3000.0);
let clear = Rc::new(Cell::new(Rect::NOTHING));
let seen = Rc::clone(&clear);
let mut view = CanvasView::new(DOCUMENT_WINDOW, Point::new(2000.0, 1500.0), 1.0).rotation(30.0);
let mut fixture = Fixture::new(move |ui| {
let mut turn = view.rotation;
Canvas::new("Document").document(large).view(view).show_at(ui, DOCUMENT_WINDOW, |ui, _| {
let room = CanvasScrollbars::clear_of(ui, DOCUMENT_WINDOW, chrome, false);
seen.set(room);
let _ = RotateView::new("Rotation", Bind::bound(&mut turn), false).show_at(ui, RotateView::compass_rect(ui, room));
});
let doc = DocRect::from_origin_size(Point::ZERO, large);
let bars = CanvasScrollbars::new("Scroll bars", Bind::bound(&mut view), doc);
let bars = if chrome { bars.document_chrome() } else { bars };
let _ = bars.show_at(ui, DOCUMENT_WINDOW);
});
fixture.room(vec2(760.0, 560.0)).settle();
let compass = fixture.by_label("Rotation compass").expect("the compass").rect;
let vertical = fixture.by_label("Vertical scroll bar").expect("the vertical bar").rect;
let horizontal = fixture.by_label("Horizontal scroll bar").expect("the horizontal bar").rect;
assert!(compass.right() <= vertical.left() + TOLERANCE, "chrome {chrome}: the compass {compass:?} reaches under the bar {vertical:?}");
let room = clear.get();
assert!(room.right() <= vertical.left() + TOLERANCE, "chrome {chrome}: {room:?} reaches the vertical bar {vertical:?}");
assert!(room.bottom() <= horizontal.top() + TOLERANCE, "chrome {chrome}: {room:?} reaches the horizontal bar {horizontal:?}");
}
}
+28 -12
View File
@@ -54,6 +54,7 @@ craft_ui::words! {
lines_per_inch_name: "units.linesPerInchName" = "Lines/Inch";
lines_per_centimetre_name: "units.linesPerCentimetreName" = "Lines/Centimetre";
feet_name: "units.feetName" = "Feet";
feet_inches_name: "units.feetInchesName" = "Feet & Inches";
yards_name: "units.yardsName" = "Yards";
metres_name: "units.metresName" = "Metres";
q_name: "units.qName" = "Q";
@@ -160,6 +161,10 @@ pub enum UnitKind {
LinesPerCentimetre,
/// `{n} ft`.
Feet,
/// `{n} ft`: the Feet & Inches unit of a document. Its numbers are feet, written and read as [`Feet`](Self::Feet)
/// writes and reads them; only its name differs, so a list of units can offer both and check the one a document
/// uses.
FeetInches,
/// `{n} yd`.
Yards,
/// `{n} m`.
@@ -190,7 +195,7 @@ impl UnitKind {
Self::ALL.get(tag as usize).copied()
}
const ALL: [UnitKind; 24] = [
const ALL: [UnitKind; 25] = [
UnitKind::Pixels,
UnitKind::Percent,
UnitKind::Degrees,
@@ -207,6 +212,7 @@ impl UnitKind {
UnitKind::LinesPerInch,
UnitKind::LinesPerCentimetre,
UnitKind::Feet,
UnitKind::FeetInches,
UnitKind::Yards,
UnitKind::Metres,
UnitKind::Q,
@@ -223,7 +229,7 @@ impl UnitKind {
UnitKind::Pixels | UnitKind::Minutes | UnitKind::Letters | UnitKind::Hyphens | UnitKind::Milliseconds => 0..=0,
UnitKind::Percent | UnitKind::Degrees | UnitKind::Points => 0..=1,
UnitKind::Q | UnitKind::Ha => 0..=2,
UnitKind::Feet | UnitKind::Yards | UnitKind::Metres => 0..=4,
UnitKind::Feet | UnitKind::FeetInches | UnitKind::Yards | UnitKind::Metres => 0..=4,
UnitKind::Times
| UnitKind::Centimetres
| UnitKind::Millimetres
@@ -241,7 +247,13 @@ impl UnitKind {
/// the kind steps by the kind's rule.
pub const fn step(self) -> f64 {
match self {
UnitKind::Times | UnitKind::Inches | UnitKind::Centimetres | UnitKind::Feet | UnitKind::Yards | UnitKind::Metres => 0.1,
UnitKind::Times
| UnitKind::Inches
| UnitKind::Centimetres
| UnitKind::Feet
| UnitKind::FeetInches
| UnitKind::Yards
| UnitKind::Metres => 0.1,
_ => 1.0,
}
}
@@ -258,7 +270,7 @@ impl UnitKind {
UnitKind::Millimetres => Some(25.4),
UnitKind::Points => Some(points_per_inch),
UnitKind::Picas => Some(points_per_inch / 12.0),
UnitKind::Feet => Some(1.0 / 12.0),
UnitKind::Feet | UnitKind::FeetInches => Some(1.0 / 12.0),
UnitKind::Yards => Some(1.0 / 36.0),
UnitKind::Metres => Some(0.0254),
UnitKind::Q | UnitKind::Ha => Some(101.6),
@@ -473,7 +485,7 @@ impl Units {
UnitKind::Columns => words.columns.as_str(),
UnitKind::LinesPerInch => words.lines_per_inch.as_str(),
UnitKind::LinesPerCentimetre => words.lines_per_centimetre.as_str(),
UnitKind::Feet => words.feet.as_str(),
UnitKind::Feet | UnitKind::FeetInches => words.feet.as_str(),
UnitKind::Yards => words.yards.as_str(),
UnitKind::Metres => words.metres.as_str(),
UnitKind::Q => words.q.as_str(),
@@ -505,6 +517,7 @@ impl Units {
UnitKind::LinesPerInch => &words.lines_per_inch_name,
UnitKind::LinesPerCentimetre => &words.lines_per_centimetre_name,
UnitKind::Feet => &words.feet_name,
UnitKind::FeetInches => &words.feet_inches_name,
UnitKind::Yards => &words.yards_name,
UnitKind::Metres => &words.metres_name,
UnitKind::Q => &words.q_name,
@@ -641,7 +654,7 @@ impl Units {
pub fn length_reader(&self, lengths: LengthUnits) -> Reader {
let Some(shown) = self.length_per_inch(lengths.shown, lengths.pixels_per_inch) else { return self.reader(None) };
let factor = |other: UnitKind| Some(shown / self.length_per_inch(other, lengths.pixels_per_inch)?);
let reader = self.reader_over(factor);
let reader = self.reader_over(Some(lengths.shown), factor);
match lengths.bare.and_then(factor) {
Some(bare) => reader.bare(bare),
None => reader,
@@ -654,8 +667,8 @@ impl Units {
}
fn build_reader(&self, kind: Option<UnitKind>, points_per_inch: f64) -> Reader {
let Some(kind) = kind else { return self.reader_over(|_| None) };
self.reader_over(|other| match (kind.per_inch(points_per_inch), other.per_inch(points_per_inch)) {
let Some(kind) = kind else { return self.reader_over(None, |_| None) };
self.reader_over(Some(kind), |other| match (kind.per_inch(points_per_inch), other.per_inch(points_per_inch)) {
(Some(of), Some(per)) => Some(of / per),
_ if other == kind => Some(1.0),
_ => None,
@@ -669,12 +682,13 @@ impl Units {
pub fn document_reader(&self, ruler: UnitKind, extent: f64, pixels_per_inch: f64, points_per_inch: f64) -> Reader {
let pixels = |kind: UnitKind| kind.to_pixels(1.0, extent, pixels_per_inch, points_per_inch);
let one_ruler = pixels(ruler).filter(|one| *one != 0.0);
self.reader_over(|other| Some(pixels(other)? / one_ruler?))
self.reader_over(Some(ruler), |other| Some(pixels(other)? / one_ruler?))
}
/// The locale's separators and, for every unit kind `factor` gives a factor to, its spellings (in the user's
/// language and in English) reading as that many of the reader's own unit.
fn reader_over(&self, factor: impl Fn(UnitKind) -> Option<f64>) -> Reader {
/// language and in English) reading as that many of the reader's own unit. `own`'s spellings come first, so a
/// spelling two kinds share (`ft` for Feet and Feet & Inches) names `own` when it is one of them.
fn reader_over(&self, own: Option<UnitKind>, factor: impl Fn(UnitKind) -> Option<f64>) -> Reader {
let (decimal, group) = self.format.separators();
let mut reader = Reader::new().decimal(decimal);
if let Some(group) = group {
@@ -682,7 +696,9 @@ impl Units {
}
let english = Units::new(self.format.clone(), english_words(), Arc::new(Words::english()), self.point_size);
let points = factor(UnitKind::Points);
for (tag, other) in UnitKind::ALL.into_iter().enumerate() {
let order = own.into_iter().chain(UnitKind::ALL.into_iter().filter(|other| Some(*other) != own));
for other in order {
let Some(tag) = UnitKind::ALL.iter().position(|kind| *kind == other) else { continue };
let Some(factor) = factor(other) else { continue };
for spelling in [self.symbol(other), english.symbol(other)] {
if is_unit_spelling(&spelling) {
@@ -2,6 +2,7 @@
use crate::contract::{
Bind, BodyCx, CollectionEvent, NoValue, Outcome, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _,
Sizing,
};
use crate::dialog::{ButtonPlace, Dialog, DialogId, DialogOutput, DialogResult, DialogStack, StackDialog};
use crate::display::{Shade, Text};
@@ -321,6 +322,10 @@ impl StackDialog for HostedListManager {
}
}
/// The fewest rows the list is tall, and the most it shows before it scrolls.
const MIN_ROWS: u16 = 8;
const MAX_ROWS: u16 = 12;
/// The name box's text in `bind`: empty while a kept binding holds none.
fn text_of(bind: &mut Bind<'_, String>, cx: &mut BodyCx<'_>) -> String {
match bind.reborrow().read(cx) {
@@ -556,6 +561,11 @@ impl<'a> ListManager<'a> {
.id(list_id)
.select(SelectMode::Single)
.allow_empty(true)
// A capped list is sized from its rows: without a cap it takes no height in a dialog that sizes to its
// content, and the empty message or the first rows are drawn over the section under it.
.sizing(Sizing::Content)
.min_rows(MIN_ROWS)
.max_rows(MAX_ROWS)
.deletable(true)
.selection(Bind::bound(&mut selection));
if let Some(empty) = &empty {
@@ -126,6 +126,8 @@ pub struct RowSpec<'a> {
/// default a drop-down, and on a card ([`PreferencesLayout::Cards`](super::PreferencesLayout::Cards)) a short
/// choice of up to five options is segmented. Ignored by other kinds.
pub pills: Option<bool>,
/// A [`RowKind::Text`] row: the translated text shown while the field is empty. Ignored by other kinds.
pub placeholder: Option<&'a str>,
/// The control and the value it shows.
pub kind: RowKind<'a>,
}
@@ -133,7 +135,7 @@ pub struct RowSpec<'a> {
impl<'a> RowSpec<'a> {
/// A visible, enabled row with no keywords or help.
pub fn new(key: &'a str, label: &'a str, kind: RowKind<'a>) -> Self {
Self { key, label, keywords: "", help: None, visible: true, enabled: true, step: None, pills: None, kind }
Self { key, label, keywords: "", help: None, visible: true, enabled: true, step: None, pills: None, placeholder: None, kind }
}
/// Sets extra search text for the row.
@@ -171,6 +173,13 @@ impl<'a> RowSpec<'a> {
self
}
/// Sets the text a [`RowKind::Text`] row shows while empty.
#[must_use]
pub fn placeholder(mut self, placeholder: &'a str) -> Self {
self.placeholder = Some(placeholder);
self
}
/// Sets the step of a [`RowKind::Float`] row.
#[must_use]
pub fn step(mut self, step: f64) -> Self {
@@ -39,7 +39,7 @@ pub(super) enum Kind {
Int { value: i64, range: RangeInclusive<i64>, unit: Option<UnitKind>, unit_text: Option<Label> },
Float { value: f64, range: RangeInclusive<f64>, decimals: u8, step: Option<f64>, unit: Option<UnitKind>, unit_text: Option<Label> },
Length { value: f64, range: RangeInclusive<f64>, lengths: LengthUnits },
Text(String),
Text { value: String, placeholder: Option<Label> },
Custom,
CustomRows,
}
@@ -72,7 +72,7 @@ impl ShownRow {
unit_text: unit_text.map(|text| Label::from(text.to_owned())),
},
RowKind::Length { value, range, lengths } => Kind::Length { value: *value, range: range.clone(), lengths: *lengths },
RowKind::Text(text) => Kind::Text((*text).to_owned()),
RowKind::Text(text) => Kind::Text { value: (*text).to_owned(), placeholder: row.placeholder.map(|text| Label::from(text.to_owned())) },
RowKind::Custom => Kind::Custom,
RowKind::CustomRows => Kind::CustomRows,
};
@@ -229,10 +229,14 @@ pub(super) fn show_row<H: PreferencesModel + ?Sized>(
});
record(next.map(PrefValue::Float));
}
Kind::Text(value) => {
Kind::Text { value, placeholder } => {
let mut next = None;
control(ui, row, cards, |ui| {
next = TextField::new(label.clone(), Bind::given(value.clone())).show(ui).events.landed().cloned();
let mut field = TextField::new(label.clone(), Bind::given(value.clone()));
if let Some(placeholder) = placeholder {
field = field.placeholder(placeholder.clone());
}
next = field.show(ui).events.landed().cloned();
});
record(next.map(PrefValue::Text));
}
@@ -267,3 +267,21 @@ fn a_hosted_list_manager_hands_over_kept_open_choices_and_answers_with_the_closi
let answered = host.borrow_mut().take::<HostedListManager>();
assert!(matches!(&answered, Some(DialogResult::Ok(run)) if run.action == "run" && run.entry.as_deref() == Some("a")), "{answered:?}");
}
// #7979: with no entries the empty message stands in the list's own box, above the section under it, not over it.
#[trial]
fn an_empty_list_keeps_its_box_above_the_section_under_it() {
let mut fixture = Fixture::new(|ui| {
let actions = vec![ListManagerAction::new("add", "Add", ActionEnabled::OnNewName).keeps_open()];
let _ = ListManager::new("Marks", "Name:", Vec::new(), actions)
.empty(craft_ui::runtime::env::Label::Static("No marks yet."))
.under_list(|ui| {
Text::new("Under the list").show(ui);
})
.show(ui);
});
fixture.idle(10);
let empty = fixture.by_label("No marks yet.").expect("the empty message");
let under = fixture.by_label("Under the list").expect("the section under the list");
assert!(empty.rect.max.y <= under.rect.min.y, "the message {:?} clears the section {:?}", empty.rect, under.rect);
}
@@ -320,3 +320,33 @@ fn the_search_shows_how_many_settings_match() {
fixture.click(&search).type_text("snap").settle();
assert!(fixture.texts().iter().any(|t| t.text == "1 match"), "{:?}", fixture.texts().iter().map(|t| &t.text).collect::<Vec<_>>());
}
/// A text row with a placeholder shows it while the field is empty; one without shows none.
#[trial]
fn a_text_rows_placeholder_shows_while_empty() {
struct Initials(bool);
impl PreferencesModel for Initials {
fn pages(&self) -> Vec<PageSpec<'_>> {
let row = RowSpec::new("general.initials", "Initials", RowKind::Text(""));
vec![PageSpec::new("general", "General", vec![if self.0 { row.placeholder("AB") } else { row }])]
}
fn set(&mut self, _: &str, _: PrefValue) {}
fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool {
false
}
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
false
}
fn reset_page(&mut self, _: &str) {}
}
let shown = |placeholder| {
let mut state = PreferencesState::default();
let mut fixture = Fixture::new(move |ui| {
PreferencesPage::new(Bind::bound(&mut state)).show(ui, &mut Initials(placeholder));
});
fixture.settle();
craft_ui::testing::text::painted(&fixture.frame_shapes()).iter().any(|text| text == "AB")
};
assert!(shown(true), "the placeholder is painted");
assert!(!shown(false), "no placeholder, none painted");
}
+3 -2
View File
@@ -120,9 +120,10 @@ impl ZoomField {
self
}
/// Uses the status bar's space and field appearance.
/// Uses the status bar's space and field appearance: the whole percentage in an unframed recessed well. An app that
/// shows its own zoom field in a status bar sets it.
#[must_use]
pub(crate) fn status_bar(mut self) -> Self {
pub fn status_bar(mut self) -> Self {
self.status_bar = true;
self
}
@@ -64,6 +64,37 @@ fn a_length_field_types_and_steps_in_the_shown_unit() {
assert!((stepped - tenth_up).abs() < SAME, "an arrow moves a tenth of an inch: {stepped} against {tenth_up}");
}
/// A Feet & Inches length is written, typed and stepped as feet, as a Feet length is, and only its name tells the two
/// apart.
#[trial]
fn a_feet_and_inches_length_counts_feet() {
let feet = LengthUnits::new(UnitKind::Points, UnitKind::Feet, START);
let feet_inches = LengthUnits::new(UnitKind::Points, UnitKind::FeetInches, START);
for text in ["1.5", "18 in", "1.5 ft"] {
let plain = in_lengths(feet, START, type_and_commit(text));
let both = in_lengths(feet_inches, START, type_and_commit(text));
assert!((both - plain).abs() < SAME && both != START, "{text} reads as feet: {both} against {plain}");
}
let stepped = |lengths: LengthUnits| {
in_lengths(lengths, START, |frames, show| {
frames.frame(vec![key_press(Key::ArrowUp, Modifiers::NONE)], show);
})
};
assert!((stepped(feet_inches) - stepped(feet)).abs() < SAME, "an arrow steps both by the same tenth of a foot");
let mut frames = Frames::new();
frames.frame(vec![], |ui| {
let units = Env::of(ui).units();
assert_eq!(units.show(UnitKind::FeetInches, 1.5), units.show(UnitKind::Feet, 1.5), "both write feet");
assert_ne!(units.name(UnitKind::FeetInches), units.name(UnitKind::Feet), "a list of units tells them apart");
for kind in [UnitKind::Feet, UnitKind::FeetInches] {
let reader = units.length_reader(LengthUnits::new(UnitKind::Points, kind, START));
let named = reader.read_tagged("1.5 ft", None).ok().and_then(|(_, tag)| tag).and_then(UnitKind::from_tag);
assert_eq!(named, Some(kind), "a typed ft names the field's own unit");
}
});
}
/// With bare numbers in points, a bare number in a picas field reads as points; a spelled unit still reads as written.
#[trial]
fn a_bare_number_reads_in_the_lengths_bare_unit() {
@@ -398,6 +398,32 @@ fn zoom_field_fits_a_narrow_host_slot() {
assert!((kept.zoom() - 200.0).abs() < 0.01, "the field remains editable");
}
/// An app's own status-bar zoom field draws in the status bar's look: unlike a plain zoom field, it shows no outline
/// while it does not have the focus.
#[trial]
fn an_apps_status_bar_zoom_field_draws_without_an_outline() {
let outlines = |status_bar: bool| {
let mut fixture = Fixture::new(move |ui| {
let canvas = Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0));
let field = ZoomField::new(ZOOM, Some(CanvasView::new(canvas, Point::new(1000.0, 750.0), 1.0)), DOCUMENT);
let field = if status_bar { field.status_bar() } else { field };
field.show(ui);
});
fixture.settle();
let field = fixture.by_label(ZOOM).expect("the zoom field").rect;
fixture
.frame_shapes()
.iter()
.filter(|shape| match shape {
egui::Shape::Rect(rect) => rect.stroke.width > 0.0 && rect.stroke.color.a() > 0 && rect.rect.intersects(field),
_ => false,
})
.count()
};
assert!(outlines(false) > 0, "a plain zoom field draws its outline");
assert_eq!(outlines(true), 0, "the status-bar zoom field draws none");
}
/// A rail-width field shows all of a three-digit zoom and its percent sign.
#[trial]
fn rail_width_zoom_shows_its_whole_value() {
+55 -1
View File
@@ -348,8 +348,10 @@ fn doctype_refused(input: &[u8], policy: Doctype) -> bool {
let mut at = 0;
while at < input.len() {
let Some(rel) = input.get(at..).and_then(|bytes| bytes.iter().position(|b| *b == b'<')) else {
scanned(input.len() - at);
break;
};
scanned(rel + 1);
at += rel;
let Some(rest) = input.get(at..) else { break };
if rest.starts_with(b"<!--") {
@@ -377,13 +379,43 @@ fn doctype_refused(input: &[u8], policy: Doctype) -> bool {
fn after(input: &[u8], start: usize, terminator: &[u8]) -> usize {
input
.get(start..)
.and_then(|rest| rest.windows(terminator.len()).position(|w| w == terminator))
.and_then(|rest| {
rest.windows(terminator.len()).position(|w| {
scanned(1);
w == terminator
})
})
.map_or(input.len(), |i| start + i + terminator.len())
}
// The places of the input `doctype_refused` and its helpers look at on this thread: each byte one
// of them reads, or each window `after` compares. Past the limit a test sets, the count fails the
// test at once rather than after the rest of the work.
#[cfg(test)]
std::thread_local! {
static SCANNED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static SCAN_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
}
#[inline]
fn scanned(count: usize) {
#[cfg(test)]
{
let read = SCANNED.with(|scanned| {
scanned.set(scanned.get().saturating_add(count));
scanned.get()
});
let limit = SCAN_LIMIT.with(std::cell::Cell::get);
assert!(read <= limit, "{read} places read, more than the {limit} allowed");
}
#[cfg(not(test))]
let _ = count;
}
fn after_instruction(input: &[u8], mut at: usize) -> usize {
let mut quote = None;
while let Some(&byte) = input.get(at) {
scanned(1);
if let Some(q) = quote {
if byte == q {
quote = None;
@@ -402,6 +434,7 @@ fn doctype_end(input: &[u8], mut at: usize) -> (usize, bool) {
let mut quote = None;
let mut subset = false;
while let Some(&byte) = input.get(at) {
scanned(1);
if let Some(q) = quote {
if byte == q {
quote = None;
@@ -421,6 +454,7 @@ fn doctype_end(input: &[u8], mut at: usize) -> (usize, bool) {
fn after_markup(input: &[u8], mut at: usize) -> usize {
let mut quote = None;
while let Some(&byte) = input.get(at) {
scanned(1);
if let Some(q) = quote {
if byte == q {
quote = None;
@@ -1003,3 +1037,23 @@ fn decode_refs(s: &str, attr: bool, unknown: UnknownEntity) -> Result<String, St
pub fn unescape(s: &str) -> String {
decode_refs(s, false, UnknownEntity::Literal).unwrap_or_else(|_| s.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
/// Looking for an internal subset reads each place of the input once, however many markers a
/// comment holds or how many never close.
#[test]
fn looking_for_an_internal_subset_is_linear_in_the_input() {
let marker = "<!DOCTYPE ";
let in_comment = format!("<!--{}--><x/>", marker.repeat(100_000));
let unclosed = format!("<x>{}", marker.repeat(100_000));
for input in [in_comment, unclosed] {
SCANNED.with(|scanned| scanned.set(0));
SCAN_LIMIT.with(|limit| limit.set(input.len()));
assert!(!doctype_refused(input.as_bytes(), Doctype::RejectInternalSubset));
SCAN_LIMIT.with(|limit| limit.set(usize::MAX));
}
}
}
+2 -3
View File
@@ -362,7 +362,8 @@ fn attributes_are_bounded_over_the_whole_tree() {
assert_eq!(tight.parse_streaming(doc.as_bytes(), &["c"], |_| Ok::<(), Error>(())), Err(Error::TooManyAttrsTotal(ATTRS - 1)));
}
/// An internal subset is found wherever it hides, and looking for it is linear in the input.
/// An internal subset is found wherever it hides. The unit test
/// `looking_for_an_internal_subset_is_linear_in_the_input` counts what the search reads.
#[test]
fn an_internal_subset_is_refused_wherever_it_hides() {
let opts = Options { doctype: Doctype::RejectInternalSubset, ..Options::default() };
@@ -379,10 +380,8 @@ fn an_internal_subset_is_refused_wherever_it_hides() {
let marker = "<!DOCTYPE ";
let in_comment = format!("<!--{}--><x/>", marker.repeat(100_000));
let unclosed = format!("<x>{}", marker.repeat(100_000));
let start = std::time::Instant::now();
assert!(opts.parse(in_comment.as_bytes()).is_ok());
let _ = opts.parse(unclosed.as_bytes());
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
}
/// A reader of many parts keeps one budget: each tree is charged at its node count and the next