diff --git a/crates/affinity/src/synth.rs b/crates/affinity/src/synth.rs index 5b75ca0bff..a25cba792b 100644 --- a/crates/affinity/src/synth.rs +++ b/crates/affinity/src/synth.rs @@ -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(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)) +} diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs index c74dc287f6..f645d66857 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -240,12 +240,26 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect(); cuts.dedup(); let push = |r: &mut Reader, runs: &mut Vec, attrs: Option, from: usize, to: usize, budget: &mut Option| { // 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 = 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() } diff --git a/crates/affinity/tests/it/import_limits.rs b/crates/affinity/tests/it/import_limits.rs index f08c044298..9924125d9d 100644 --- a/crates/affinity/tests/it/import_limits.rs +++ b/crates/affinity/tests/it/import_limits.rs @@ -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. diff --git a/crates/cms/src/curve.rs b/crates/cms/src/curve.rs index 8494bd029a..f1df948d43 100644 --- a/crates/cms/src/curve.rs +++ b/crates/cms/src/curve.rs @@ -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 = 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"); } } diff --git a/crates/color-ui/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index a13003b5c9..c075c29095 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -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, diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index dc32f707b1..d2548b1045 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -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::(), env.words::()); 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)); } } diff --git a/crates/color-ui/src/ui/picker/channel.rs b/crates/color-ui/src/ui/picker/channel.rs index 6e4356f33b..8cb04ab0a5 100644 --- a/crates/color-ui/src/ui/picker/channel.rs +++ b/crates/color-ui/src/ui/picker/channel.rs @@ -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, FieldDecimals, 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}; @@ -185,6 +189,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>, + /// 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