dialogs-w9: net change of 5 commits

- dialogs-w9: written from its sheet
- dialogs-w9: repair 1
- Integration: imaging's trial list keeps dialogs-w17's raw_develop beside color_range
- dialogs-w9: review fixes (review-1)
- dialogs-w9: the color range trial's proxy is large enough that the preview fits it to the well inside the zoom range (top run round)
This commit is contained in:
aiongg
2026-11-15 04:46:08 +00:00
parent f87418d391
commit 4ff83a83e2
10 changed files with 856 additions and 100 deletions
+311 -10
View File
@@ -1,11 +1,30 @@
//! The Color Range dialog's body.
use craft_ui::canvas::RasterSource;
use craft_ui::contract::{Bind, EditResponse, NoValue, Outcome, Pattern, Props};
use craft_ui::runtime::env::Label;
use egui::{Response, Ui};
use std::ops::RangeInclusive;
use std::sync::Arc;
use super::ColorRangeValue;
use craft_behavior::{CursorBadge, EditEvent, EditEvents, IconId, Mixed};
use craft_ui::buttons::Button;
use craft_ui::canvas::{PixelRect, RasterSource};
use craft_ui::choice::{Checkbox, Radio, RadioGroup, Segmented};
use craft_ui::contract::{
Bind, CanvasGesture, EditResponse, Entry, NoValue, Outcome, Pattern, Props, Sampler as _, Show as _, ShowContainer as _, clicked,
};
use craft_ui::display::{Shade, Text};
use craft_ui::form::{Field, FieldGroup, SliderField};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::patterns::form_dialogs::{PreviewPane, PreviewState, PreviewView};
use craft_ui::pickers::Select;
use craft_ui::primitives::{IconSpec, TextureCache};
use craft_ui::runtime::env::{Env, Label, UnitKind};
use craft_ui::runtime::pointer;
use craft_ui::style::TypeRole;
use egui::load::SizedTexture;
use egui::{Color32, ColorImage, Response, Ui, Vec2};
use super::{ColorRangeSelect, ColorRangeValue, ColorRangeWords, SampleTool};
use crate::selection::PreviewMode;
use crate::ui::selection::SelectionWords;
/// What the Color Range body reports.
#[derive(Debug)]
@@ -15,6 +34,12 @@ pub struct ColorRangeOutput {
pub edit: EditResponse<ColorRangeValue>,
/// The body's response.
pub response: Response,
/// The sample tool picked this pass.
pub tool: Option<SampleTool>,
/// The view picked this pass: `true` for Image, `false` for Selection.
pub show_image: Option<bool>,
/// The Selection Preview mode picked this pass.
pub preview: Option<PreviewMode>,
}
impl Outcome for ColorRangeOutput {
@@ -26,9 +51,14 @@ impl Outcome for ColorRangeOutput {
}
/// The Color Range body: the select, the sliders, the selection preview and the sampling tools.
///
/// The sample tool, the Selection / Image view and the Selection Preview mode are dialog state beside the value: the
/// caller passes them in and takes the changes from the output.
///
/// A press (and each pass the held pointer moves) in the preview samples a colour while Sampled Colors is selected.
/// Each pass applies only the press phase of its own input, so a second pass in the same frame samples nothing.
#[must_use = "show the dialog body with `show`"]
#[derive(Pattern, Props)]
#[allow(dead_code)] // P3(dialogs-w9): dl.K54
pub struct ColorRangeDialog<'a> {
label: Label,
value: Bind<'a, ColorRangeValue>,
@@ -41,24 +71,295 @@ pub struct ColorRangeDialog<'a> {
/// The integer proxy factor `k`, halved by integer division.
#[prop]
picture_scale: u32,
/// The document's size in pixels, which a sample is clamped to.
#[prop]
document: [u32; 2],
/// An error to show under the preview.
#[prop]
error: Option<Label>,
/// The canvas the sampling presses reach.
#[prop]
canvas: Option<egui::Id>,
/// The sample tool.
#[prop]
tool: SampleTool,
/// Whether the Image view is chosen rather than the Selection view.
#[prop]
show_image: bool,
/// The Selection Preview mode.
#[prop]
preview_mode: PreviewMode,
}
/// The edits one pass collects: each is lifted onto the whole value, the later ones from what the earlier made.
struct Pass {
current: ColorRangeValue,
events: EditEvents<ColorRangeValue>,
}
impl Pass {
fn new(now: ColorRangeValue) -> Self {
Pass { current: now, events: EditEvents::new() }
}
/// A control's `events` of one field as events of the value, `set` writing the field into the value.
fn lift<T: Clone + 'static>(&mut self, events: EditEvents<T>, set: impl Fn(&mut ColorRangeValue, T)) {
let base = self.current.clone();
let lifted = events.map(move |x| {
let mut next = base.clone();
set(&mut next, x);
next
});
if let Some(value) = lifted.value() {
self.current = value.clone();
}
for event in lifted {
self.events.push(event);
}
}
/// A one-step change the body makes itself (a sample, Clear Samples): `after` as one `Set` named `label`.
fn set(&mut self, label: &Label, after: ColorRangeValue) {
if after == self.current {
return;
}
let event = EditEvent::set(Mixed::Same(self.current.clone()), after.clone(), Arc::from(label.as_str()), None);
self.current = after;
self.events.push(event);
}
/// A whole-number slider row over `range`, enabled or not.
fn slider(
&mut self,
ui: &mut Ui,
label: &Label,
value: f64,
range: RangeInclusive<f64>,
percent: bool,
enabled: bool,
set: fn(&mut ColorRangeValue, f64),
) {
let mut field = SliderField::new(label.clone(), Bind::given(value), range).step(1.0).enabled(enabled);
if percent {
field = field.unit_kind(UnitKind::Percent);
}
let events = field.show(ui).events;
self.lift(events, move |value, x| set(value, x.round()));
}
}
/// What a pass of the body gathered for the output.
struct Collected {
events: EditEvents<ColorRangeValue>,
tool: Option<SampleTool>,
show_image: Option<bool>,
preview: Option<PreviewMode>,
}
/// The texture of `source` at its own size, kept by the texture cache under the source's revision. `kind` keeps the
/// mask and the image apart.
fn texture(ctx: &egui::Context, source: &dyn RasterSource, kind: &'static str) -> SizedTexture {
let size = source.size();
let (width, height) = (size.width as usize, size.height as usize);
let id = TextureCache::texture(ctx, (kind, source.revision(), size.width, size.height), || {
let mut image = ColorImage::filled([width, height], Color32::TRANSPARENT);
source.read(PixelRect::of_size(size), 1, &mut image);
image
});
SizedTexture::new(id, Vec2::new(width as f32, height as f32))
}
/// The Select's entries, in Photoshop's order.
fn select_entries(words: &ColorRangeWords) -> Vec<Entry<ColorRangeSelect>> {
[
(ColorRangeSelect::Sampled, &words.sampled),
(ColorRangeSelect::Reds, &words.reds),
(ColorRangeSelect::Yellows, &words.yellows),
(ColorRangeSelect::Greens, &words.greens),
(ColorRangeSelect::Cyans, &words.cyans),
(ColorRangeSelect::Blues, &words.blues),
(ColorRangeSelect::Magentas, &words.magentas),
(ColorRangeSelect::Highlights, &words.highlights),
(ColorRangeSelect::Midtones, &words.midtones),
(ColorRangeSelect::Shadows, &words.shadows),
(ColorRangeSelect::SkinTones, &words.skin_tones),
(ColorRangeSelect::OutOfGamut, &words.out_of_gamut),
]
.into_iter()
.map(|(select, name)| Entry::new(select, name.clone()))
.collect()
}
impl<'a> ColorRangeDialog<'a> {
/// The body named `label` over `value`.
pub fn new(label: impl Into<Label>, value: Bind<'a, ColorRangeValue>) -> Self {
let _ = (label.into(), value);
todo!("dl.K54")
ColorRangeDialog {
label: label.into(),
value,
mask: None,
image: None,
picture_scale: 1,
document: [0, 0],
error: None,
canvas: None,
tool: SampleTool::default(),
show_image: false,
preview_mode: PreviewMode::default(),
}
}
/// Draws the body.
pub fn show(self, ui: &mut Ui) -> ColorRangeOutput {
let _ = (self, ui);
todo!("dl.K54")
let ColorRangeDialog { label, mut value, mask, image, picture_scale, document, error, canvas, tool, show_image, preview_mode } = self;
let env = Env::of(ui);
let words = env.words::<ColorRangeWords>();
let preview_words = env.words::<SelectionWords>();
// Holding ⌘ (Ctrl off macOS; `Mods` folds Ctrl into `cmd` there) shows the other view while held: view only,
// `show_image` does not change.
let swapped = pointer::frame(ui.ctx()).mods.cmd;
let image_shown = show_image != swapped;
let source = if image_shown { image } else { mask };
let state = match (&error, source) {
(Some(error), _) => PreviewState::Failed(error.clone()),
(None, Some(source)) => PreviewState::Ready(texture(ui.ctx(), source, if image_shown { "image" } else { "mask" })),
(None, None) => PreviewState::Pending(None),
};
let k = picture_scale.max(1);
let mut collected = None;
let shown = FieldGroup::new(label).show(ui, |ui, cx| {
let now = match value.reborrow().read(cx) {
Some(Mixed::Same(now)) => now,
_ => ColorRangeValue::default(),
};
let c = now.controls();
if let Some(canvas) = canvas {
cx.keep_view_open(canvas);
if c.sampling {
cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY);
}
}
let mut pass = Pass::new(now.clone());
let (mut picked_tool, mut picked_view, mut picked_preview) = (None, None, None);
Field::new(words.select.clone()).show(ui, |ui, _| {
let entries = select_entries(&words);
let events = Select::new(words.select.clone(), Bind::given(now.select), &entries).show(ui).events;
pass.lift(events, |value, select| value.select = select);
});
let events = Checkbox::new(Bind::given(now.localized)).label(words.localized.clone()).enabled(c.sampling).show(ui).events;
pass.lift(events, |value, on| value.localized = on);
if c.tonal {
pass.slider(ui, &words.fuzziness, now.tone_fuzziness, 0.0..=100.0, true, c.fuzziness, |v, x| v.tone_fuzziness = x);
} else {
pass.slider(ui, &words.fuzziness, now.fuzziness, 0.0..=200.0, false, c.fuzziness, |v, x| v.fuzziness = x);
}
if c.range {
pass.slider(ui, &words.range, now.range, 0.0..=100.0, true, true, |v, x| v.range = x);
}
if c.tonal {
match now.select {
ColorRangeSelect::Shadows => {
pass.slider(ui, &words.shadows_up_to, now.shadows_level, 0.0..=255.0, false, true, |v, x| v.shadows_level = x);
}
ColorRangeSelect::Highlights => {
pass.slider(ui, &words.highlights_from, now.highlights_level, 0.0..=255.0, false, true, |v, x| v.highlights_level = x);
}
_ => {
pass.slider(ui, &words.midtones_from, now.midtones_low, 0.0..=255.0, false, true, |v, x| v.midtones_low = x);
pass.slider(ui, &words.midtones_to, now.midtones_high, 0.0..=255.0, false, true, |v, x| v.midtones_high = x);
}
}
}
Row::new().show(ui, |ui, _| {
let pane = PreviewPane::state(words.preview.clone(), state.clone(), &PreviewView::fixed()).aspect(1.0).click_centres(false).show(ui);
if c.sampling
&& let Some(p) = pane.pressed
{
// The picture is a proxy reduced `k` times: the sample is the centre of the proxy pixel in document pixels.
let at = [
f64::from(p.x.floor().max(0.0)) * f64::from(k) + f64::from(k / 2),
f64::from(p.y.floor().max(0.0)) * f64::from(k) + f64::from(k / 2),
];
let mods = pointer::frame(ui.ctx()).mods;
let mut next = pass.current.clone();
next.samples.pick(at, document, tool, mods);
pass.set(&words.eyedropper, next);
}
Stack::new().show(ui, |ui, _| {
Stack::new().enabled(c.sampling).show(ui, |ui, _| {
let tools = [
Entry::new(SampleTool::Sample, words.eyedropper.clone()).icon(IconSpec::svg(IconId::new("eyedropper"))),
Entry::new(SampleTool::Add, words.add_to_sample.clone()).icon(IconSpec::mark(CursorBadge::Add)),
Entry::new(SampleTool::Subtract, words.subtract_from_sample.clone()).icon(IconSpec::mark(CursorBadge::Subtract)),
];
picked_tool = Segmented::new(words.sample_tools.clone(), Bind::given(tool), &tools).show(ui).value().copied();
let (added, removed) = (now.samples.add.len(), now.samples.subtract.len());
let count = |n: usize| {
let n_text = n.to_string();
if n == 1 { words.one_sample.fill(&[("n", n_text.as_str())]) } else { words.many_samples.fill(&[("n", n_text.as_str())]) }
};
let text = match (added, removed) {
(0, 0) => words.sample_foreground.as_str().to_owned(),
(added, 0) => count(added),
(added, removed) => {
let (added_text, removed_text) = (count(added), removed.to_string());
words.with_subtracted.fill(&[("added", added_text.as_str()), ("removed", removed_text.as_str())])
}
};
Text::new(text).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
if added + removed > 0 && clicked(&Button::new(words.clear_samples.clone()).show(ui)) {
let mut next = pass.current.clone();
next.samples.clear();
pass.set(&words.clear_samples, next);
}
});
let events = Checkbox::new(Bind::given(now.invert)).label(words.invert.clone()).show(ui).events;
pass.lift(events, |value, on| value.invert = on);
Field::new(words.selection.clone()).id_salt("view").show(ui, |ui, _| {
let group = RadioGroup::new(words.selection.clone(), Bind::given(show_image)).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
Radio::new(false).label(words.selection.clone()).show(ui);
Radio::new(true).label(words.image.clone()).show(ui);
});
});
picked_view = group.output.value().copied();
});
Field::new(words.selection_preview.clone()).show(ui, |ui, _| {
let modes = [
Entry::new(PreviewMode::None, words.none.clone()),
Entry::new(PreviewMode::Grayscale, preview_words.grayscale.clone()),
Entry::new(PreviewMode::BlackMatte, preview_words.black_matte.clone()),
Entry::new(PreviewMode::WhiteMatte, preview_words.white_matte.clone()),
Entry::new(PreviewMode::QuickMask, preview_words.quick_mask.clone()),
];
picked_preview = Select::new(words.selection_preview.clone(), Bind::given(preview_mode), &modes).show(ui).value().copied();
});
});
});
for event in &pass.events {
let _ = value.reborrow().write(cx, event);
}
collected = Some(Collected {
events: pass.events,
tool: picked_tool.filter(|t| *t != tool),
show_image: picked_view.filter(|v| *v != show_image),
preview: picked_preview.filter(|m| *m != preview_mode),
});
});
let response = shown.output;
match collected {
Some(Collected { events, tool, show_image, preview }) => {
ColorRangeOutput { edit: EditResponse::lifted(response.clone(), events, None), response, tool, show_image, preview }
}
// The body did not run (a parent's measuring pass reuses what it measured): nothing was edited.
None => ColorRangeOutput {
edit: EditResponse::lifted(response.clone(), EditEvents::new(), None),
response,
tool: None,
show_image: None,
preview: None,
},
}
}
}
+143 -34
View File
@@ -1,32 +1,70 @@
//! [`HostedColorRange`]: Color Range on the dialog host.
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use std::sync::Arc;
use craft_ui::canvas::RasterSource;
use craft_ui::contract::Bind;
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field};
use craft_ui::patterns::form_dialogs::FormDialog;
use craft_ui::runtime::env::Label;
use egui::{Context, Ui};
use serde_json::{Value, json};
use super::ColorRangeValue;
use super::{ColorRangeDialog, ColorRangeSelect, ColorRangeValue, SampleTool};
use crate::selection::PreviewMode;
/// The key of the hosted Color Range dialog.
const KEY: &str = "select.colorRange";
/// The preview the app rendered, as the dialog host keeps it.
type Preview = Arc<dyn RasterSource + Send + Sync>;
/// Color Range as a dialog the dialog host owns. It is not registered: the app opens it. It answers with the value at OK.
///
/// The sample tool, the Selection / Image view and the Selection Preview mode are dialog state, not part of the
/// value: they start at the eyedropper, Selection and None at each open, and automation reaches them as the `tool`,
/// `view` and `selectionPreview` fields beside the value's own.
pub struct HostedColorRange {
id: DialogId,
title: Label,
open: bool,
value: ColorRangeValue,
size: [u32; 2],
tool: SampleTool,
show_image: bool,
preview: PreviewMode,
canvas: Option<egui::Id>,
mask: Option<Preview>,
image: Option<Preview>,
picture_scale: u32,
error: Option<Label>,
}
impl HostedColorRange {
/// The dialog titled `title` over `value`, for a document of `size` pixels.
pub fn new(title: impl Into<Label>, value: ColorRangeValue, size: [u32; 2]) -> Self {
let _ = (title.into(), size);
HostedColorRange { id: dialog_id(KEY), value }
HostedColorRange {
id: dialog_id(KEY),
title: title.into(),
open: true,
value,
size,
tool: SampleTool::default(),
show_image: false,
preview: PreviewMode::default(),
canvas: None,
mask: None,
image: None,
picture_scale: 1,
error: None,
}
}
/// The canvas the sampling presses reach.
#[must_use]
pub fn canvas(self, canvas: egui::Id) -> Self {
let _ = canvas;
todo!("dl.K54")
pub fn canvas(mut self, canvas: egui::Id) -> Self {
self.canvas = Some(canvas);
self
}
/// The value the dialog shows.
@@ -34,36 +72,54 @@ impl HostedColorRange {
&self.value
}
/// The sample tool chosen in the dialog, before Shift or Alt change it.
pub fn tool(&self) -> SampleTool {
self.tool
}
/// Sets the previews the app rendered: the selection `mask` and the `image`, shown at `picture_scale`, or the
/// `error` that kept them from rendering.
// P3(dialogs-w9): dl.K54 `set_preview` takes the four arguments
pub fn set_preview(
&mut self,
mask: Option<std::sync::Arc<dyn craft_ui::canvas::RasterSource + Send + Sync>>,
image: Option<std::sync::Arc<dyn craft_ui::canvas::RasterSource + Send + Sync>>,
picture_scale: u32,
error: Option<Label>,
) {
let _ = (mask, image, picture_scale, error);
todo!("dl.K54")
pub fn set_preview(&mut self, mask: Option<Preview>, image: Option<Preview>, picture_scale: u32, error: Option<Label>) {
self.mask = mask;
self.image = image;
self.picture_scale = picture_scale;
self.error = error;
}
/// The Selection Preview mode the dialog shows on the canvas.
// P3(dialogs-w9): dl.K54 `preview_mode`
pub fn preview_mode(&self) -> crate::selection::PreviewMode {
todo!("dl.K54")
pub fn preview_mode(&self) -> PreviewMode {
self.preview
}
/// Whether the dialog's view shows the image rather than the selection.
// P3(dialogs-w9): dl.K54 `shows_image`
pub fn shows_image(&self) -> bool {
todo!("dl.K54")
self.show_image
}
/// A press on the canvas at `at` with `mods` held samples a colour. `false` for a press outside the document.
/// A press on the canvas at `at` with `mods` held samples a colour. `false` for a press outside the document or
/// while the select takes no samples.
pub fn sample_canvas(&mut self, at: [f64; 2], mods: craft_keymap::Mods) -> bool {
let _ = (at, mods);
todo!("dl.K54")
let inside = |v: f64, extent: u32| v.is_finite() && v >= 0.0 && v < f64::from(extent);
if !self.value.controls().sampling || !inside(at[0], self.size[0]) || !inside(at[1], self.size[1]) {
return false;
}
self.value.samples.pick(at, self.size, self.tool, mods);
true
}
/// Whether the row of `field` is shown and enabled for the select.
fn takes(&self, field: &str) -> bool {
let c = self.value.controls();
match field {
"localized" | "samples" | "tool" => c.sampling,
"fuzziness" => c.fuzziness && !c.tonal,
"toneFuzziness" => c.tonal,
"range" => c.range,
"shadowsLevel" => self.value.select == ColorRangeSelect::Shadows,
"highlightsLevel" => self.value.select == ColorRangeSelect::Highlights,
"midtonesLow" | "midtonesHigh" => self.value.select == ColorRangeSelect::Midtones,
_ => true,
}
}
}
@@ -74,9 +130,41 @@ impl StackDialog for HostedColorRange {
self.id
}
fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<DialogResult<ColorRangeValue>> {
let _ = (ui, stack);
todo!("dl.K54")
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<ColorRangeValue>> {
let HostedColorRange { title, open, value, size, tool, show_image, preview, canvas, mask, image, picture_scale, error, .. } = self;
let shown = FormDialog::new(title.clone(), Bind::bound(value)).opened(Bind::bound(open)).show(ui, |ui, _, value| {
let mut body = ColorRangeDialog::new(title.clone(), Bind::bound(value))
.picture_scale(*picture_scale)
.document(*size)
.tool(*tool)
.show_image(*show_image)
.preview_mode(*preview);
if let Some(mask) = mask.as_deref() {
body = body.mask(mask);
}
if let Some(image) = image.as_deref() {
body = body.image(image);
}
if let Some(error) = error {
body = body.error(error.clone());
}
if let Some(canvas) = *canvas {
body = body.canvas(canvas);
}
let out = body.show(ui);
if let Some(next) = out.tool {
*tool = next;
}
if let Some(next) = out.show_image {
*show_image = next;
}
if let Some(next) = out.preview {
*preview = next;
}
true
});
let accepted = shown.accepted.map(DialogResult::Ok);
accepted.or(shown.closed.map(|_| DialogResult::Cancel))
}
fn key(&self) -> Option<&str> {
@@ -85,15 +173,36 @@ impl StackDialog for HostedColorRange {
fn confirm(&mut self, ctx: &Context) -> Option<ColorRangeValue> {
let _ = ctx;
todo!("dl.K54")
Some(self.value.clone())
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K54")
fn json_fields(&self) -> Option<Value> {
let mut fields = serde_fields(&self.value)?;
let map = fields.as_object_mut()?;
map.insert("tool".into(), serde_json::to_value(self.tool).ok()?);
map.insert("view".into(), json!(if self.show_image { "image" } else { "selection" }));
map.insert("selectionPreview".into(), serde_json::to_value(self.preview).ok()?);
Some(fields)
}
fn set_json_field(&mut self, ctx: &Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K54")
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
let _ = ctx;
if !self.takes(field) {
return Err(FieldRefusal::Inactive.message(field));
}
let rejected = |value: &Value| FieldRefusal::Rejects(value).message(field);
match field {
"tool" => self.tool = serde_json::from_value(value.clone()).map_err(|_| rejected(&value))?,
"view" => {
self.show_image = match value.as_str() {
Some("image") => true,
Some("selection") => false,
_ => return Err(rejected(&value)),
}
}
"selectionPreview" => self.preview = serde_json::from_value(value.clone()).map_err(|_| rejected(&value))?,
_ => return set_serde_field(&mut self.value, field, value),
}
Ok(())
}
}
@@ -6,9 +6,39 @@ craft_ui::words! {
/// The dialog's title.
name: "colorRange.name" = "Color Range";
select: "colorRange.select" = "Select";
localized: "colorRange.localized" = "Localized Color Clusters";
fuzziness: "colorRange.fuzziness" = "Fuzziness";
range: "colorRange.range" = "Range";
shadows_up_to: "colorRange.shadowsUpTo" = "Shadows up to";
highlights_from: "colorRange.highlightsFrom" = "Highlights from";
midtones_from: "colorRange.midtonesFrom" = "Midtones from";
midtones_to: "colorRange.midtonesTo" = "Midtones to";
preview: "colorRange.preview" = "Color Range preview";
sample_tools: "colorRange.sampleTools" = "Sample tools";
eyedropper: "colorRange.eyedropper" = "Eyedropper";
add_to_sample: "colorRange.addToSample" = "Add to Sample";
subtract_from_sample: "colorRange.subtractFromSample" = "Subtract from Sample";
sample_foreground: "colorRange.sampleForeground" = "Sample: foreground color";
one_sample: template "colorRange.oneSample" = "{n} sample";
many_samples: template "colorRange.manySamples" = "{n} samples";
with_subtracted: template "colorRange.withSubtracted" = "{added}, {removed} subtracted";
clear_samples: "colorRange.clearSamples" = "Clear Samples";
invert: "colorRange.invert" = "Invert";
selection: "colorRange.selection" = "Selection";
image: "colorRange.image" = "Image";
selection_preview: "colorRange.selectionPreview" = "Selection Preview";
none: "colorRange.none" = "None";
sampled: "colorRange.sampled" = "Sampled Colors";
reds: "colorRange.reds" = "Reds";
yellows: "colorRange.yellows" = "Yellows";
greens: "colorRange.greens" = "Greens";
cyans: "colorRange.cyans" = "Cyans";
blues: "colorRange.blues" = "Blues";
magentas: "colorRange.magentas" = "Magentas";
highlights: "colorRange.highlights" = "Highlights";
midtones: "colorRange.midtones" = "Midtones";
shadows: "colorRange.shadows" = "Shadows";
skin_tones: "colorRange.skinTones" = "Skin Tones";
out_of_gamut: "colorRange.outOfGamut" = "Out Of Gamut";
}
}
+13 -1
View File
@@ -1,8 +1,20 @@
//! Color Range: the Select menu's dialog that selects by sampled colours, colour families or tonal ranges.
//! Color Range: Photoshop's Select › Color Range, the dialog that selects by sampled colours, colour families or
//! tonal ranges.
//!
//! - [`ColorRangeDialog`]: the body. The select, the sliders that apply to it, the preview of the selection (or of the
//! image) that the sample tools click and drag in, the sample count, Invert, and the Selection / Image and Selection
//! Preview choices. It edits a [`ColorRangeValue`] and reports the dialog state it keeps beside it (the sample tool,
//! the view, the Selection Preview).
//! - [`HostedColorRange`]: the body in a form dialog the dialog host owns. The app renders the previews and feeds them
//! with `set_preview`; the canvas samples through `sample_canvas`.
//! - [`ColorRangeValue`]: the command's parameters. [`ColorSamples`] holds the sampled points and the order they were
//! made in; its `pick` is also Replace Color's sampling rule.
mod dialog;
mod hosted;
mod labels;
#[cfg(feature = "screen-testing")]
mod stories;
mod value;
pub use dialog::{ColorRangeDialog, ColorRangeOutput};
@@ -0,0 +1,63 @@
//! Stories of the Color Range dialog: the body at Sampled Colors with two samples, at Midtones, with a failed
//! preview, and the hosted dialog opened from a button.
use std::sync::Arc;
use craft_ui::contract::Bind;
use craft_ui::dialog::stories::hosted;
use craft_ui::runtime::env::Label;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use super::{ColorRangeDialog, ColorRangeSelect, ColorRangeValue, HostedColorRange, SampleSign};
use crate::ui::mock_image::MockImage;
/// The proxy's size and the factor it is reduced by.
const PROXY: [u32; 2] = [120, 80];
const SCALE: u32 = 4;
fn sampled() -> ColorRangeValue {
let mut value = ColorRangeValue::default();
value.samples.add = vec![[62.0, 42.0], [200.0, 150.0]];
value.samples.order = vec![SampleSign::Add, SampleSign::Add];
value
}
fn document() -> [u32; 2] {
[PROXY[0] * SCALE, PROXY[1] * SCALE]
}
#[story(ColorRangeDialog<'static>, covers = [Default], drive = Drive::Never)]
fn color_range_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let value = data.value("value", sampled());
let picture = MockImage::new(PROXY);
ColorRangeDialog::new("Color Range", Bind::bound(value)).mask(&picture).image(&picture).picture_scale(SCALE).document(document()).show(ui).into()
}
#[story(ColorRangeDialog<'static>, covers = [], drive = Drive::Never)]
fn color_range_dialog_midtones(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let value = data.value("value", ColorRangeValue { select: ColorRangeSelect::Midtones, ..ColorRangeValue::default() });
let picture = MockImage::new(PROXY);
ColorRangeDialog::new("Color Range", Bind::bound(value)).mask(&picture).image(&picture).picture_scale(SCALE).document(document()).show(ui).into()
}
#[story(ColorRangeDialog<'static>, covers = [], drive = Drive::Never)]
fn color_range_dialog_failed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let value = data.value("value", ColorRangeValue::default());
ColorRangeDialog::new("Color Range", Bind::bound(value))
.picture_scale(SCALE)
.document(document())
.error(Label::from("The preview could not be rendered."))
.show(ui)
.into()
}
#[story(ColorRangeDialog<'static>, covers = [], drive = Drive::Never, title = "In its dialog")]
fn hosted_color_range(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
hosted(ui, data, (), || {
let mut dialog = HostedColorRange::new("Color Range", sampled(), document());
let picture = Arc::new(MockImage::new(PROXY));
dialog.set_preview(Some(picture.clone()), Some(picture), SCALE, None);
dialog
})
}
+81 -35
View File
@@ -9,9 +9,8 @@ use serde::{Deserialize, Serialize};
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum ColorRangeSelect {
/// Sampled colours.
/// Sampled colours. Serialises as the engine's `sampledColors`.
#[default]
// P3(dialogs-w9): dl.K54 the engine's name
#[serde(rename = "sampledColors")]
Sampled,
/// Reds.
@@ -33,15 +32,12 @@ pub enum ColorRangeSelect {
/// Shadows.
Shadows,
/// Skin tones.
// P3(dialogs-w9): dl.K54 `SkinTones`
SkinTones,
/// Out-of-gamut colours.
// P3(dialogs-w9): dl.K54 `OutOfGamut`
OutOfGamut,
}
/// The sampling tool: the plain eyedropper, Add to Sample or Subtract from Sample.
// P3(dialogs-w9): dl.K54 serde for the `tool` json key
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
@@ -56,28 +52,38 @@ pub enum SampleTool {
}
impl SampleTool {
/// The tool as `mods` change it: Shift adds, else Alt subtracts.
/// The tool as `mods` change it: Shift adds, else Alt subtracts. The one place this rule lives, for a pick and
/// for the canvas cursor's mark.
#[must_use]
pub fn with_mods(self, mods: Mods) -> SampleTool {
let _ = (self, mods);
todo!("dl.K54")
if mods.shift {
SampleTool::Add
} else if mods.alt {
SampleTool::Subtract
} else {
self
}
}
/// The mark the canvas cursor shows for the tool.
pub fn badge(self) -> Option<CursorBadge> {
let _ = self;
todo!("dl.K54")
match self {
SampleTool::Sample => None,
SampleTool::Add => Some(CursorBadge::Add),
SampleTool::Subtract => Some(CursorBadge::Subtract),
}
}
}
/// Whether a sample adds to the range or subtracts from it.
/// Whether a sample adds to the range or subtracts from it. Serialises as the engine's `"+"` and `"-"`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum SampleSign {
/// An added sample.
#[serde(rename = "+")]
Add,
/// A subtracted sample.
#[serde(rename = "-")]
Subtract,
}
@@ -95,30 +101,56 @@ pub struct ColorSamples {
impl ColorSamples {
/// Takes a sample at `at` in a document of `size`: floored and clamped to the document, by `tool` as `mods` change
/// it. Also Replace Color's sampling rule.
///
/// The eyedropper replaces every sample with this one; Add and Subtract append, so the order of the clicks is kept
/// (the engine applies additions and subtractions one after another).
pub fn pick(&mut self, at: [f64; 2], size: [u32; 2], tool: SampleTool, mods: Mods) {
let _ = (at, size, tool, mods);
todo!("dl.K54")
let cell = |v: f64, extent: u32| {
let v = if v.is_finite() { v } else { 0.0 };
v.floor().clamp(0.0, f64::from(extent.max(1)) - 1.0)
};
let at = [cell(at[0], size[0]), cell(at[1], size[1])];
match tool.with_mods(mods) {
SampleTool::Add => {
self.add.push(at);
self.order.push(SampleSign::Add);
}
SampleTool::Subtract => {
self.subtract.push(at);
self.order.push(SampleSign::Subtract);
}
SampleTool::Sample => {
self.add = vec![at];
self.subtract.clear();
self.order = vec![SampleSign::Add];
}
}
}
/// The order of the samples, `None` while they are all of one sign.
/// The order of the samples, `None` while it does not match the two lists (then the engine takes the lists in
/// their own order).
pub fn order(&self) -> Option<&[SampleSign]> {
todo!("dl.K54")
let added = self.order.iter().filter(|sign| **sign == SampleSign::Add).count();
let subtracted = self.order.len() - added;
(added == self.add.len() && subtracted == self.subtract.len()).then_some(self.order.as_slice())
}
/// Drops every sample.
pub fn clear(&mut self) {
todo!("dl.K54")
self.add.clear();
self.subtract.clear();
self.order.clear();
}
}
/// The Color Range dialog's value.
/// The Color Range dialog's value: the command's parameters.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ColorRangeValue {
/// What the range picks by.
pub select: ColorRangeSelect,
/// Fuzziness, 0..=200.
/// Fuzziness of Sampled Colors and Skin Tones, 0..=200.
pub fuzziness: f64,
/// Range, 0..=100 percent.
pub range: f64,
@@ -131,31 +163,45 @@ pub struct ColorRangeValue {
/// Whether the selection is inverted.
pub invert: bool,
/// Localized Color Clusters.
// P3(dialogs-w9): dl.K54 `localized`
pub localized: bool,
/// The fuzziness of the tonal ranges (Highlights, Midtones, Shadows, Skin Tones).
// P3(dialogs-w9): dl.K54 `tone_fuzziness`
/// The fuzziness of the tonal ranges (Highlights, Midtones, Shadows), 0..=100 percent.
pub tone_fuzziness: f64,
/// The Shadows level.
// P3(dialogs-w9): dl.K54 `shadows_level`
/// The Shadows level, 0..=255.
pub shadows_level: f64,
/// The Highlights level.
// P3(dialogs-w9): dl.K54 `highlights_level`
/// The Highlights level, 0..=255.
pub highlights_level: f64,
}
impl Default for ColorRangeValue {
/// Production's opening values (pc color_range_ui.rs:94-110).
// P3(dialogs-w9): dl.K54 `impl Default`
/// Photoshop's opening values: Sampled Colors, Fuzziness 40, Range 100, no samples.
fn default() -> Self {
todo!("dl.K54")
ColorRangeValue {
select: ColorRangeSelect::Sampled,
fuzziness: 40.0,
range: 100.0,
midtones_low: 105.0,
midtones_high: 150.0,
samples: ColorSamples::default(),
invert: false,
localized: false,
tone_fuzziness: 20.0,
shadows_level: 65.0,
highlights_level: 190.0,
}
}
}
impl ColorRangeValue {
/// Which controls the value's `select` shows.
/// Which controls the value's `select` shows or enables.
pub fn controls(&self) -> RangeControls {
todo!("dl.K54")
let sampled = self.select == ColorRangeSelect::Sampled;
let tonal = matches!(self.select, ColorRangeSelect::Highlights | ColorRangeSelect::Midtones | ColorRangeSelect::Shadows);
RangeControls {
fuzziness: sampled || tonal || self.select == ColorRangeSelect::SkinTones,
sampling: sampled,
range: sampled && self.localized,
tonal,
}
}
}
@@ -163,12 +209,12 @@ impl ColorRangeValue {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RangeControls {
/// The Fuzziness slider.
/// The Fuzziness slider is enabled.
pub fuzziness: bool,
/// The sampling tools.
/// The sampling tools are enabled.
pub sampling: bool,
/// The Range slider.
/// The Range slider is shown.
pub range: bool,
/// The Midtones bounds.
/// The tonal sliders (Shadows, Highlights, Midtones bounds) are shown.
pub tonal: bool,
}
+24 -12
View File
@@ -9,13 +9,16 @@
//! hue and saturation, color balance, channel mixer, selective color and more).
//! - [`live_preview`]: the [`LivePreview`] of an adjustment on a proxy of the image.
//! - [`layer_style`]: the [`LayerStyleDialog`], the [`BlendIfBar`] and the [`ContourField`].
//! - [`blend_keys`]: the [`BlendKeys`] that pick a blend mode from the keyboard.
//! - [`color_range`]: the [`ColorRangeDialog`] of Select › Color Range, its [`ColorRangeValue`] and the
//! [`HostedColorRange`] on the dialog host.
//! - [`select`]: the [`MarqueeTool`] and the lasso tools; [`selection`]: the [`SelectionOverlay`];
//! [`mask_view`]: the [`MaskViewControls`] for a mask's views.
//! - [`select_mask`], [`fill`], [`filter_gallery`], [`liquify`], [`wide_angle`] and
//! [`vanishing_point`]: the full-window editors ([`SelectMaskWorkspace`],
//! [`ContentAwareFillWorkspace`], [`FilterGalleryWorkspace`], [`LiquifyWorkspace`],
//! [`WideAngleWorkspace`], [`VanishingPointWorkspace`]), each with its session, panel and options bar.
//! - [`raw_develop`]: the [`RawDevelopWorkspace`], the full-window editor of a raw file; its settings are
//! [`crate::raw::RawDevelopSettings`].
//! - [`blur_pins`]: the [`BlurPinsOverlay`] and [`BlurPinsPanel`] of the blur effects.
//! - [`channels`]: the Channels panel.
//! - [`scopes`]: the scope panel (histogram, statistics, tone zones, vectorscope) and the
@@ -24,7 +27,7 @@
//! The main types of each module are also re-exported here.
pub mod adjust;
pub mod blend_keys;
pub mod blur_pins;
pub mod channels;
pub mod color_range;
@@ -49,13 +52,13 @@ pub mod warp;
pub mod wide_angle;
pub use adjust::{
AdjustContext, AdjustField, AdjustSession, AdjustSliders, AdjustTrack, AdjustWords, BlackWhite, BlackWhiteEditor, BrightnessContrast,
AdjustDialogCx, AdjustmentKind, AdjustmentsPanel, AdjustmentsPanelOutput, ToneChannelCommands, AdjustContext, AdjustField, AdjustSession, AdjustSliders, AdjustTrack, AdjustWords, BlackWhite, BlackWhiteEditor, BrightnessContrast,
BrightnessContrastEditor, ChannelMixer, ChannelMixerEditor, ColorBalance, ColorBalanceEditor, CurvesMode, CurvesPanel, CurvesPanelOutput,
HostedAdjustDialog, HueSaturation, HueSaturationEditor, Levels, LevelsClip, LevelsEditor, LevelsEditorOutput, LevelsPanel, LevelsPanelOutput,
LevelsWords, PhotoFilter, PhotoFilterEditor, SelectiveColor, SelectiveColorEditor, ThresholdEditor, ToneCurves, TonePick, TonePickTool,
TonePicker, TonePickerRow, TonePickerRowOutput,
};
pub use blend_keys::{BlendKeyEntry, BlendKeyPick, BlendKeys, BlendShortcut, BlendStep};
pub use blur_pins::{
BlurKind, BlurPin, BlurPins, BlurPinsCommand, BlurPinsOutput, BlurPinsOverlay, BlurPinsPanel, BlurPinsPanelOutput, BlurPinsWords, IrisShape,
TiltBand,
@@ -64,13 +67,17 @@ pub use channels::{
ChannelKind, ChannelRow, ChannelsCommands, ChannelsEvent, ChannelsFooterButton, ChannelsOutput, ChannelsPanel, ChannelsWords, ColorIndicates,
OVERLAY_OPACITIES, OverlayPreset, targeted_row,
};
pub use color_range::{
ColorRangeDialog, ColorRangeOutput, ColorRangeSelect, ColorRangeValue, ColorRangeWords, ColorSamples, HostedColorRange, RangeControls, SampleSign,
SampleTool,
};
pub use curve::{Curve, CurveChannel, CurveEditor, CurveEditorOutput, CurvePreview, CurveRows, CurveRules, CurveSampler, CurveWords, ToneRamp};
pub use fill::{
ContentAwareFillWorkspace, FillBar, FillBarOutput, FillEvent, FillLimit, FillLimits, FillOpen, FillOutput, FillOverlay, FillPanel,
ContentAwareFillWorkspace, FillBar, FillBarOutput, FillEvent, FillLimit, FillLimits, FillOp, FillOpen, FillOverlay, FillPanel,
FillPanelOutput, FillSession, FillSettings, FillSource, FillTool, FillWords,
};
pub use filter_gallery::{
EffectParameters, EffectStack, FilterCatalog, FilterGalleryEvent, FilterGalleryOpen, FilterGalleryOutput, FilterGallerySession,
EffectParameters, EffectStack, FilterCatalog, FilterGalleryEvent, FilterGalleryOpen, FilterGallerySession,
FilterGalleryWords, FilterGalleryWorkspace, FilterTree, GalleryFilter,
};
pub use histogram::{
@@ -82,11 +89,15 @@ pub use layer_style::{
LayerStyleWords, StylePresets,
};
pub use liquify::{
LiquifyCommands, LiquifyEvent, LiquifyOpen, LiquifyOutput, LiquifyPanel, LiquifyPanelOutput, LiquifySession, LiquifySettings, LiquifySource,
LiquifyCommands, LiquifyDone, LiquifyEvent, LiquifyOpen, LiquifyPanel, LiquifyPanelOutput, LiquifySession, LiquifySettings, LiquifySource,
LiquifyTiming, LiquifyTool, LiquifyWords, LiquifyWorkspace,
};
pub use live_preview::{DraftScale, LivePreview, PreviewKey, PreviewLane, PreviewSession, ProxyPlan};
pub use mask_view::{MaskViewControls, MaskViewControlsOutput, MaskViewKeys, MaskViewMode, MaskViewRecipe, MaskViewState, MaskViewWords};
pub use raw_develop::{
Demosaic, RawDevelopEvent, RawDevelopOpen, RawDevelopPanel, RawDevelopResult, RawDevelopSource, RawDevelopWorkspace, RawFilmItem, RawFinish,
RawFloatingScope, RawPreviewRequest, RawScopeStrip, RawTarget,
};
pub use scopes::{
COLORS_CHANNEL, ChannelOverlay, ClipWarning, ClippingDiagnostic, ClippingFrame, ClippingMode, ClippingOverlay, ClippingWarnings, HistogramSet,
ScopeChannel, ScopeCommand, ScopeFrame, ScopeMenuAction, ScopePanel, ScopePanelOutput, ScopePanelState, ScopeReadout, ScopeSettings, ScopeSource,
@@ -94,16 +105,17 @@ pub use scopes::{
};
pub use select::{
LassoTool, MagneticLassoTool, MagneticSettings, MarqueeKind, MarqueeTool, PolygonLassoTool, SelectEvent, SelectWords, SelectionShape,
operations::{SelectionOpWords, selection_operations},
};
pub use select_mask::{
LimitRefused, SelectMaskBar, SelectMaskBarOutput, SelectMaskEdit, SelectMaskEvent, SelectMaskLimits, SelectMaskOpen, SelectMaskOutput,
LimitRefused, SelectMaskBar, SelectMaskBarOutput, SelectMaskEdit, SelectMaskEvent, SelectMaskLimits, SelectMaskDone, SelectMaskOp, SelectMaskOpen,
SelectMaskPanel, SelectMaskPanelOutput, SelectMaskSession, SelectMaskSettings, SelectMaskSource, SelectMaskWords, SelectMaskWorkspace,
};
pub use selection::{OutlineSource, SelectionOverlay, SelectionOverlayOutput, SelectionWords};
pub use transform_preview::{PreviewMap, PreviewQuality, StyledPreview, TransformPreview};
pub use vanishing_point::{
StampLimits, StampSettings, VanishingPlane, VanishingPointBar, VanishingPointBarOutput, VanishingPointEditor, VanishingPointEvent,
VanishingPointOpen, VanishingPointOutput, VanishingPointSession, VanishingPointSettings, VanishingPointSource, VanishingPointWords,
StampLimits, StampSettings, VanishingPlane, VanishingPointBar, VanishingPointBarOutput, VanishingPointCommand, VanishingPointEditor,
VanishingPointEvent, VanishingPointOpen, VanishingPointSession, VanishingPointSettings, VanishingPointSource, VanishingPointWords,
VanishingPointWorkspace, VanishingScene,
};
pub use warp::perspective::{
@@ -114,10 +126,10 @@ pub use warp::pin::{
Pin, PinWarp, PinWarpBar, PinWarpBarOutput, PinWarpBarWords, PinWarpCommands, PinWarpOutput, PinWarpSession, PinWarpSettings, PinWarpWords,
};
pub use warp::{
WarpEdit, WarpFieldValues, WarpFields, WarpFieldsEdit, WarpFieldsOutput, WarpFieldsWords, WarpGrid, WarpGridChoice, WarpGridOutput,
CylinderHandle, CylinderValues, CylinderWarp, CylinderWarpOutput, WarpEdit, WarpFieldValues, WarpFields, WarpFieldsEdit, WarpFieldsOutput, WarpFieldsWords, WarpGrid, WarpGridChoice, WarpGridOutput,
WarpGridStyle, WarpMesh, WarpSide, WarpSplit, WarpStyleEntry, WarpWords,
};
pub use wide_angle::{
PreviewDone, WideAngleConstraint, WideAngleEvent, WideAngleModel, WideAngleOpen, WideAngleOutput, WideAnglePanel, WideAnglePanelOutput,
PreviewDone, WideAngleConstraint, WideAngleEvent, WideAngleModel, WideAngleOpen, WideAnglePanel, WideAnglePanelOutput,
WideAngleSession, WideAngleSource, WideAngleTool, WideAngleWords, WideAngleWorkspace,
};
+161
View File
@@ -0,0 +1,161 @@
//! The Color Range body: its preview samples with the tool, Shift and Alt, through the real pointer path.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use craft_behavior::PixelSize;
use craft_imaging::ui::color_range::{ColorRangeDialog, ColorRangeSelect, ColorRangeValue, SampleSign, SampleTool};
use craft_ui::canvas::{PixelRect, RasterSource};
use craft_ui::contract::Bind;
use craft_ui::primitives::Revision;
use craft_ui::testing::{Fixture, trial};
use egui::{Color32, ColorImage, Modifiers, Pos2, Rect, vec2};
/// The proxy: 40 × 20 pixels shown in a square well, so the picture is letterboxed and the well has room off it. It is
/// large enough that the fitted zoom stays inside the pane's zoom range, so the picture spans the well's width.
const PROXY: [u32; 2] = [40, 20];
const SCALE: u32 = 5;
const DOCUMENT: [u32; 2] = [200, 100];
struct Flat;
impl RasterSource for Flat {
fn size(&self) -> PixelSize {
PixelSize::new(PROXY[0], PROXY[1])
}
fn revision(&self) -> Revision {
Revision::of(&PROXY)
}
fn damage(&self, _: Revision) -> Option<PixelRect> {
None
}
fn read(&self, _: PixelRect, _: u32, out: &mut ColorImage) {
out.pixels.fill(Color32::WHITE);
}
}
struct State {
value: ColorRangeValue,
tool: SampleTool,
}
/// The dialog body in a fixture over a shared state; the tool the body reports is adopted as the host does. While
/// `twice` is on, egui runs each frame twice and gives the frame's input to its first pass only.
fn fixture(state: &Rc<RefCell<State>>, twice: &Rc<Cell<bool>>) -> Fixture {
let (shown, twice) = (state.clone(), Rc::clone(twice));
let mut fixture = Fixture::new(move |ui| {
let mut st = shown.borrow_mut();
let tool = st.tool;
let out = ColorRangeDialog::new("Color Range", Bind::bound(&mut st.value))
.mask(&Flat)
.image(&Flat)
.picture_scale(SCALE)
.document(DOCUMENT)
.tool(tool)
.show(ui);
if let Some(next) = out.tool {
st.tool = next;
}
if twice.get() && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the frame runs twice");
}
});
fixture.settle();
fixture
}
/// The screen point at the centre of proxy cell (`x`, `y`) of the letterboxed picture in `well`.
fn cell(well: Rect, x: f32, y: f32) -> Pos2 {
let fx = (x + 0.5) / PROXY[0] as f32;
let fy = 0.25 + 0.5 * (y + 0.5) / PROXY[1] as f32;
well.min + vec2(well.width() * fx, well.height() * fy)
}
#[trial]
fn preview_presses_and_drags_sample_add_and_subtract_in_order() {
let state = Rc::new(RefCell::new(State { value: ColorRangeValue::default(), tool: SampleTool::Sample }));
let twice = Rc::new(Cell::new(false));
let mut fixture = fixture(&state, &twice);
let well = fixture.by_label("Color Range preview").expect("the preview pane").rect;
let samples = || state.borrow().value.samples.clone();
let cell_at = |x: f64, y: f64| [x * f64::from(SCALE) + f64::from(SCALE / 2), y * f64::from(SCALE) + f64::from(SCALE / 2)];
// A plain press replaces the samples with the cell's centre in document pixels.
fixture.click_at(cell(well, 2.0, 3.0));
fixture.settle();
assert_eq!(samples().add, vec![cell_at(2.0, 3.0)]);
assert_eq!(samples().order(), Some(&[SampleSign::Add][..]));
fixture.click_at(cell(well, 4.0, 4.0));
fixture.settle();
assert_eq!(samples().add, vec![cell_at(4.0, 4.0)], "the eyedropper replaces the samples");
// Add to Sample appends, and a drag adds one sample for the press and one per frame the pointer moves; a held
// frame and a rerun pass of the same frame add none.
state.borrow_mut().tool = SampleTool::Add;
fixture.click_at(cell(well, 1.0, 1.0));
fixture.settle();
assert_eq!(samples().add.len(), 2);
let before = samples().add.len();
let from = cell(well, 6.0, 2.0);
let by = cell(well, 14.0, 2.0) - from;
fixture.drag_hold_at(from, by);
assert_eq!(samples().add.len(), before + 1 + 4, "the press and each of the four moving frames add one");
assert_eq!(samples().add.last(), Some(&cell_at(14.0, 2.0)));
fixture.frame(Vec::new());
assert_eq!(samples().add.len(), before + 1 + 4, "a held frame with no move adds none");
twice.set(true);
fixture.frame(Vec::new());
twice.set(false);
assert_eq!(samples().add.len(), before + 1 + 4, "a rerun pass adds none");
fixture.release_at(from + by);
fixture.settle();
assert_eq!(samples().add.len(), before + 1 + 4, "the release adds none");
// Shift adds and Alt subtracts whatever the tool; repeated Alt presses each append.
state.borrow_mut().tool = SampleTool::Sample;
let added = samples().add.len();
fixture.hold(Modifiers { shift: true, ..Modifiers::NONE });
fixture.click_at(cell(well, 0.0, 0.0));
fixture.settle();
assert_eq!(samples().add.len(), added + 1);
fixture.hold(Modifiers { alt: true, ..Modifiers::NONE });
fixture.click_at(cell(well, 9.0, 0.0));
fixture.settle();
fixture.click_at(cell(well, 9.0, 4.0));
fixture.settle();
fixture.hold(Modifiers::NONE);
assert_eq!(samples().subtract, vec![cell_at(9.0, 0.0), cell_at(9.0, 4.0)]);
assert_eq!(samples().order.last(), Some(&SampleSign::Subtract));
assert!(samples().order().is_some());
// The order answers only while it matches the lists.
state.borrow_mut().value.samples.add.pop();
assert_eq!(samples().order(), None);
// A press off the picture samples nothing.
let count = samples().order.len();
fixture.click_at(well.min + vec2(well.width() * 0.5, well.height() * 0.05));
fixture.settle();
assert_eq!(samples().order.len(), count);
// A first Add with no samples gives one added sample.
{
let mut st = state.borrow_mut();
st.value.samples.clear();
st.tool = SampleTool::Add;
}
fixture.click_at(cell(well, 3.0, 2.0));
fixture.settle();
assert_eq!(samples().add, vec![cell_at(3.0, 2.0)]);
assert_eq!(samples().order(), Some(&[SampleSign::Add][..]));
// With Sampled Colors off the preview takes no sample.
state.borrow_mut().value.select = ColorRangeSelect::Reds;
let count = samples().order.len();
fixture.click_at(cell(well, 5.0, 2.0));
fixture.settle();
assert_eq!(samples().order.len(), count);
}
+1
View File
@@ -3,6 +3,7 @@
mod adjust_editors;
mod adjust_tone;
mod blur_pins;
mod color_range;
mod contour_field;
mod curve;
mod fill;
@@ -14,7 +14,9 @@ use crate::runtime::env::{Env, Label, UnitKind};
use crate::runtime::focus::{ActivateKeys, KeepKeys, KeyUse};
use crate::style::{ComponentStyle, FocusLook, StyleCx};
use crate::text::NumberField;
use craft_behavior::{AccessAction, AccessData, CanvasTransform, CursorIcon, CursorPriority, IconId, Metrics, NavMove, PartKey, PressPhase, Sense};
use craft_behavior::{
AccessAction, AccessData, CanvasTransform, CursorIcon, CursorPriority, IconId, Metrics, NavMove, PartKey, PointerButton, PressPhase, Sense,
};
use egui::load::SizedTexture;
use egui::{Pos2, Rect, Response, Ui, Vec2, pos2};
use std::ops::RangeInclusive;
@@ -224,8 +226,9 @@ pub struct PreviewOutput {
/// texture's size is its pixel size) from its top-left corner; `None` when there was no click or it missed the
/// picture. It is reported whether or not the click centres the view: an eyedropper or a locator reads it.
pub clicked: Option<Pos2>,
/// The point of the picture a press landed on this pass, in the same units as `clicked`; unlike `clicked` it is
/// reported when the press begins, not when it ends as a click.
/// The point of the picture a primary press of a `fixed` view landed on this pass, in the same units as `clicked`:
/// on the press and on each pass the held pointer moves, not when it ends as a click. `None` for a view that is not
/// `fixed` (a drag pans there), off the picture, or in a pass that carries no press or move.
pub pressed: Option<Pos2>,
}
@@ -271,6 +274,8 @@ pub struct PreviewPane<'a> {
double_clicked: bool,
/// The picture point a single click landed on this pass.
clicked: Option<Pos2>,
/// The picture point a primary press of a fixed view landed on or moved over this pass.
pressed: Option<Pos2>,
/// The host's drawing over the picture of a `Ready` pane.
#[prop(func = "FnOnce(&ContentPainterCx, CanvasTransform, Rect)")]
overlay: Option<PaneOverlay<'a>>,
@@ -300,6 +305,7 @@ impl PreviewPane<'_> {
moved: None,
double_clicked: false,
clicked: None,
pressed: None,
overlay: None,
overflow: (false, false),
fixed: view.fixed,
@@ -376,6 +382,14 @@ impl PreviewPane<'_> {
CanvasTransform::new(view.scale, view.offset.clamp(-slack, slack))
}
/// The point of a picture of `picture` points shown through `shown` in `well` that the pointer at `pos` is over, from
/// the picture's top-left corner; `None` off the picture.
fn picture_point(pos: Pos2, well: Rect, shown: CanvasTransform, picture: Vec2) -> Option<Pos2> {
let point = (pos - well.center() - shown.offset) / shown.scale + picture / 2.0;
let on_picture = (0.0..=picture.x).contains(&point.x) && (0.0..=picture.y).contains(&point.y);
on_picture.then(|| point.to_pos2())
}
/// The picture of a `Ready` pane.
fn picture(&self) -> Option<SizedTexture> {
match &self.state {
@@ -468,18 +482,25 @@ impl Component for PreviewPane<'_> {
// reports a view only when the result differs from what it shows, so the press staying down changes nothing.
let mut refit = false;
match cx.part(WELL).press.phase {
PressPhase::Drag { delta, .. } => {
PressPhase::Drag { start, pos, delta, .. } => {
next.offset += delta;
cx.cursor(CursorIcon::Grabbing, CursorPriority::Drag);
if self.fixed && start.button == PointerButton::Primary && delta != Vec2::ZERO {
self.pressed = Self::picture_point(pos, well, shown, texture.size);
}
}
PressPhase::DragStart { start, pos, .. } if self.fixed && start.button == PointerButton::Primary => {
self.pressed = Self::picture_point(pos, well, shown, texture.size);
}
PressPhase::Down { start, .. } if self.fixed && start.button == PointerButton::Primary => {
self.pressed = Self::picture_point(start.origin, well, shown, texture.size);
}
PressPhase::Down { start, .. } if start.clicks >= 2 && !self.fixed => {
refit = true;
self.double_clicked = true;
}
PressPhase::Release { start, pos, click: true, .. } if start.clicks < 2 => {
let point = (pos - well.center() - shown.offset) / shown.scale + texture.size / 2.0;
let on_picture = (0.0..=texture.size.x).contains(&point.x) && (0.0..=texture.size.y).contains(&point.y);
self.clicked = on_picture.then(|| point.to_pos2());
self.clicked = Self::picture_point(pos, well, shown, texture.size);
if self.click_centres {
next.offset += well.center() - pos;
}
@@ -588,7 +609,7 @@ impl Component for PreviewPane<'_> {
shown,
double_clicked: self.double_clicked,
clicked: self.clicked,
pressed: None, // P3(dialogs-w9): dl.K75
pressed: self.pressed,
}
}
}