mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 10:48:15 +01:00
Merge pull request #4451 from davidmann4/batch/davidmann4-2026-11-30
Batch: six of my open craft-libs PRs (#4383, #4348, #4340, #4338, #4337, #4323)
This commit is contained in:
28 files changed
+1008
-132
No files matched your search
@@ -4,7 +4,7 @@
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::hash::Hash;
|
||||
|
||||
use craft_behavior::{Codec as _, EditEvent, EditEvents, IconId, Mixed, NumberCodec, Value};
|
||||
use craft_behavior::{Codec as _, EditEvent, EditEvents, IconId, Mixed, NumberCodec, Selection, Value};
|
||||
use craft_ui::buttons::IconButton;
|
||||
use craft_ui::contract::{
|
||||
Bind, BodyCx, EditResponse, MemoProps, MemoView, Outbox, Outcome, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _, TooltipSpec,
|
||||
@@ -15,7 +15,8 @@ use craft_ui::form::SliderField;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::menu::{Menu, MenuItem};
|
||||
use craft_ui::patterns::presets::{
|
||||
CellShape, PickerField, PresetBrowser, PresetEvent, PresetFooterOptions, PresetPicker, PresetSource, PresetState, PresetView,
|
||||
CellShape, PickerField, PresetBrowser, PresetEvent, PresetFooterOptions, PresetPicker, PresetRow, PresetRowMenu, PresetSource, PresetState,
|
||||
PresetView,
|
||||
};
|
||||
use craft_ui::primitives::{FacePaint, IconSpec};
|
||||
use craft_ui::runtime::env::{Env, Label, UnitKind};
|
||||
@@ -31,6 +32,9 @@ use crate::ui::brush_settings::{BrushSizeField, TipAngle, TipEllipse};
|
||||
/// The largest diameter the picker's Size row allows until the app sets its engine's limit.
|
||||
const DEFAULT_MAX_DIAMETER: f64 = 5000.0;
|
||||
|
||||
/// The most height the recent row takes: one row of tiles, which scrolls past that.
|
||||
const RECENT_ROOM: f32 = 96.0;
|
||||
|
||||
/// The brush values the picker's head edits, given by the app each pass.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
@@ -97,7 +101,7 @@ pub enum GearSection {
|
||||
Preset,
|
||||
/// The Brush Name, Brush Stroke and Brush Tip boxes.
|
||||
Parts,
|
||||
/// Show Search Bar.
|
||||
/// Show Search Bar and Show Recent Brushes.
|
||||
View,
|
||||
/// Import Brushes… (with [`BrushPresetPicker::import`]).
|
||||
Library,
|
||||
@@ -110,7 +114,8 @@ pub enum GearSection {
|
||||
pub type GearRows = fn(&mut Ui, GearSection);
|
||||
|
||||
/// The picker's state, kept by the host while the app runs: the browser's view (search, open groups, scale), the
|
||||
/// parts the presets show and whether the search field shows. [`settings`](Self::settings) is what persists.
|
||||
/// parts the presets show, whether the search field and the recent row show, and the recently used presets.
|
||||
/// [`settings`](Self::settings) is what persists; the recent presets are for the running session only.
|
||||
#[derive(Clone, Debug, craft_ui::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct BrushPickerState<K> {
|
||||
@@ -120,6 +125,17 @@ pub struct BrushPickerState<K> {
|
||||
pub parts: BrushCardParts,
|
||||
/// The gear's Show Search Bar.
|
||||
pub search: bool,
|
||||
/// The gear's Show Recent Brushes: the row of recently used presets under the search field.
|
||||
pub recent_row: bool,
|
||||
/// The recently used presets, newest first, at most [`RECENT_MAX`](Self::RECENT_MAX); kept by
|
||||
/// [`note_recent`](Self::note_recent).
|
||||
pub recent: Vec<K>,
|
||||
/// While the pointer is on the open picker's recent row: the row keeps its order, so its tiles do not move under
|
||||
/// the pointer.
|
||||
holding: bool,
|
||||
/// The presets picked while `holding`, oldest first: they go to the front of `recent` in that order once the hold
|
||||
/// ends.
|
||||
held: Vec<K>,
|
||||
}
|
||||
|
||||
impl<K> Default for BrushPickerState<K> {
|
||||
@@ -129,15 +145,92 @@ impl<K> Default for BrushPickerState<K> {
|
||||
}
|
||||
|
||||
impl<K> BrushPickerState<K> {
|
||||
/// Every part on, the search field shown, scale 1, an empty search.
|
||||
/// Every part on, the search field and the recent row shown, scale 1, an empty search, no recent preset.
|
||||
pub fn new() -> Self {
|
||||
Self { browser: PresetState::new(), parts: BrushCardParts::ALL, search: true }
|
||||
Self {
|
||||
browser: PresetState::new(),
|
||||
parts: BrushCardParts::ALL,
|
||||
search: true,
|
||||
recent_row: true,
|
||||
recent: Vec::new(),
|
||||
holding: false,
|
||||
held: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: Clone + PartialEq> BrushPickerState<K> {
|
||||
/// How many presets the recent row keeps.
|
||||
pub const RECENT_MAX: usize = 8;
|
||||
|
||||
/// Notes the preset the brush now comes from, `current`: it goes to the front of [`recent`](Self::recent),
|
||||
/// moving there when it was in the row already, and the row keeps at most [`RECENT_MAX`](Self::RECENT_MAX). A
|
||||
/// preset `exists` no longer holds leaves the row. While the pointer is on the open picker's recent row the row
|
||||
/// keeps its order and `current` waits until the pointer leaves it. Returns whether the state changed. The picker
|
||||
/// notes its own picks; the host calls this once per frame too, so a preset chosen elsewhere (a panel, a key)
|
||||
/// joins the row.
|
||||
pub fn note_recent(&mut self, current: Option<&K>, exists: impl Fn(&K) -> bool) -> bool {
|
||||
let (recent, held) = (self.recent.clone(), self.held.clone());
|
||||
self.recent.retain(|key| exists(key));
|
||||
self.held.retain(|key| exists(key));
|
||||
if let Some(key) = current.filter(|key| exists(key)) {
|
||||
if self.holding {
|
||||
if self.held.last() != Some(key) {
|
||||
self.held.retain(|k| k != key);
|
||||
self.held.push(key.clone());
|
||||
let over = self.held.len().saturating_sub(Self::RECENT_MAX);
|
||||
self.held.drain(..over);
|
||||
}
|
||||
} else {
|
||||
to_front(&mut self.recent, key);
|
||||
}
|
||||
}
|
||||
self.recent.truncate(Self::RECENT_MAX);
|
||||
self.recent != recent || self.held != held
|
||||
}
|
||||
|
||||
/// Ends a hold of the recent row (the pointer left it, or the picker closed): every preset picked during it goes
|
||||
/// to the front in the order it was picked. Returns whether the state changed. The picker ends its holds itself;
|
||||
/// a host that closes the picker without showing it again calls this.
|
||||
pub fn release_recent(&mut self) -> bool {
|
||||
if !self.holding {
|
||||
return false;
|
||||
}
|
||||
self.holding = false;
|
||||
for key in std::mem::take(&mut self.held) {
|
||||
to_front(&mut self.recent, &key);
|
||||
}
|
||||
self.recent.truncate(Self::RECENT_MAX);
|
||||
true
|
||||
}
|
||||
|
||||
/// Starts a hold while `on` (the pointer is on the open picker's recent row), else ends one.
|
||||
fn hold_recent(&mut self, on: bool) {
|
||||
if on {
|
||||
self.holding = true;
|
||||
} else {
|
||||
let _ = self.release_recent();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts `key` first in `list`, dropping an equal entry.
|
||||
fn to_front<K: Clone + PartialEq>(list: &mut Vec<K>, key: &K) {
|
||||
if list.first() != Some(key) {
|
||||
list.retain(|k| k != key);
|
||||
list.insert(0, key.clone());
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: Eq + Hash> PartialEq for BrushPickerState<K> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.browser == other.browser && self.parts == other.parts && self.search == other.search
|
||||
self.browser == other.browser
|
||||
&& self.parts == other.parts
|
||||
&& self.search == other.search
|
||||
&& self.recent_row == other.recent_row
|
||||
&& self.recent == other.recent
|
||||
&& self.holding == other.holding
|
||||
&& self.held == other.held
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,8 +261,8 @@ pub struct BrushPresetPickerOutput<K> {
|
||||
pub open: bool,
|
||||
/// The picks, in the order they happened.
|
||||
pub picks: Vec<BrushPick<K>>,
|
||||
/// The persisted view when the user changed it this pass (a part box, Show Search Bar, the scale): the app saves
|
||||
/// it.
|
||||
/// The persisted view when the user changed it this pass (a part box, Show Search Bar, Show Recent Brushes, the
|
||||
/// scale): the app saves it.
|
||||
pub settings: Option<BrushPickerSettings>,
|
||||
}
|
||||
|
||||
@@ -232,9 +325,14 @@ impl Opened {
|
||||
/// - **Search row.** The browser's search field (any letter case, groups open while filtering) unless Show Search
|
||||
/// Bar is off, then at its reading end the Brush Settings and New Brush Preset buttons and the gear. The popover
|
||||
/// opens with the focus in the search field, so typing filters the presets.
|
||||
/// - **Recent row.** Under the search row while Show Recent Brushes is on, one row of the recently used presets'
|
||||
/// tips, newest first ([`BrushPickerState::recent`]), drawn from [`recent_source`](Self::recent_source) (else the
|
||||
/// picker's source). A click picks and keeps the picker open, a double click or Enter picks and closes it, as in the
|
||||
/// presets below. While the pointer is on the row its tiles keep their places; a preset picked there moves to the
|
||||
/// front once the pointer leaves the row or the picker closes.
|
||||
/// - **Gear menu.** New Brush Preset…; Rename Brush… (opens the name field on the current preset) and Delete Brush…
|
||||
/// (enabled with a current preset); the Brush Name, Brush Stroke and Brush Tip boxes (at least one stays on); Show
|
||||
/// Search Bar; Import Brushes… with [`import`](Self::import). The app adds its own rows to each section with
|
||||
/// Search Bar and Show Recent Brushes; Import Brushes… with [`import`](Self::import). The app adds its own rows to each section with
|
||||
/// [`gear_rows`](Self::gear_rows).
|
||||
/// - **Presets.** The browser, with the scale slider (0.15 to 2.0) in its footer. The tip alone is a grid with the
|
||||
/// size as each caption; the name or the stroke is a list, with the stroke band while the stroke shows. A click
|
||||
@@ -282,6 +380,10 @@ pub struct BrushPresetPicker<'a, K: Value + Eq + Hash + MemoProps> {
|
||||
/// sampled tip's shape); without it the chip shows the picked preset's tip.
|
||||
#[prop]
|
||||
tip: Option<FacePaint>,
|
||||
/// The presets the recent row takes its tiles from: the picker's presets built to show the tip alone, so the row
|
||||
/// shows tips whatever parts the presets below show. Without it the row takes the picker's source.
|
||||
#[prop]
|
||||
recent_source: Option<&'a PresetSource<'a, K>>,
|
||||
}
|
||||
|
||||
/// The app's own rows of the picker's gear menu.
|
||||
@@ -312,6 +414,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
|
||||
enabled: true,
|
||||
app_rows: None,
|
||||
tip: None,
|
||||
recent_source: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -339,6 +442,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
|
||||
enabled,
|
||||
mut app_rows,
|
||||
tip: tip_paint,
|
||||
recent_source,
|
||||
} = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<BrushPresetWords>();
|
||||
@@ -357,6 +461,8 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
|
||||
let mut browser = before.browser.clone();
|
||||
let next_parts = Cell::new(parts);
|
||||
let next_search = Cell::new(before.search);
|
||||
let next_recent_row = Cell::new(before.recent_row);
|
||||
let on_recent = Cell::new(false);
|
||||
let tool_picks: RefCell<Vec<BrushPick<K>>> = RefCell::new(Vec::new());
|
||||
let (mut diameter, mut hardness, mut tip) = (EditEvents::new(), EditEvents::new(), EditEvents::new());
|
||||
let mut out_of_range = None;
|
||||
@@ -380,6 +486,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
|
||||
held: held.clone(),
|
||||
parts,
|
||||
search: before.search,
|
||||
recent_row: before.recent_row,
|
||||
import,
|
||||
browser_id,
|
||||
gear_rows,
|
||||
@@ -390,8 +497,43 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
|
||||
*tool_picks.borrow_mut() = run.picks;
|
||||
next_parts.set(run.parts);
|
||||
next_search.set(run.search);
|
||||
next_recent_row.set(run.recent_row);
|
||||
}
|
||||
};
|
||||
// The recent row under the search row: its picks join the browser's, so the picker picks and closes as
|
||||
// for a preset below.
|
||||
let recent_keys = if compact || !before.recent_row { Vec::new() } else { before.recent.clone() };
|
||||
let recent_id = browser_id.with("recent");
|
||||
let band = |ui: &mut Ui| {
|
||||
let all = recent_source.unwrap_or(source).rows(ui.ctx(), &env);
|
||||
let rows: Vec<PresetRow<K>> = recent_keys
|
||||
.iter()
|
||||
.filter_map(|key| all.iter().find(|row| !row.is_group() && row.key == *key))
|
||||
.map(|row| {
|
||||
let mut row = row.clone();
|
||||
row.depth = 0;
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
if rows.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let listed = PresetSource::listed(&rows);
|
||||
let mut view = PresetState::new();
|
||||
let mut row = PresetBrowser::new(words.recent.clone(), Bind::bound(&mut view), &listed)
|
||||
.browser_id(recent_id)
|
||||
.view_lock(PresetView::Grid)
|
||||
.cell_shape(CellShape::Square)
|
||||
.row_menu(PresetRowMenu::Off)
|
||||
.max_rows(1)
|
||||
.room_height(RECENT_ROOM);
|
||||
if let Some(key) = held.clone() {
|
||||
row = row.selection(Bind::given(Selection::single(key)));
|
||||
}
|
||||
let out = row.show(ui);
|
||||
on_recent.set(out.response.contains_pointer());
|
||||
out.events.into_iter().filter(|event| matches!(event, PresetEvent::Select { .. } | PresetEvent::Activate { .. })).collect()
|
||||
};
|
||||
let mut picker = PresetPicker::new(words.picker.clone(), current.reborrowed(), source, Bind::bound(&mut browser))
|
||||
.field(PickerField::Chip)
|
||||
.caption(NumberCodec::new(env.units().reader(None), 0).format(&Some(values.diameter.round())))
|
||||
@@ -402,11 +544,13 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
|
||||
.toolbar(true)
|
||||
.search(before.search)
|
||||
.keep_open()
|
||||
.stays_under_modal()
|
||||
.thumb_range(BRUSH_THUMBS)
|
||||
.footer(PresetFooterOptions::new().new_group(false))
|
||||
.browser_id(browser_id)
|
||||
.head(head)
|
||||
.tools(tools);
|
||||
.tools(tools)
|
||||
.band(band);
|
||||
if let Some(key) = resizable.clone() {
|
||||
picker = picker.resizable(key);
|
||||
}
|
||||
@@ -422,7 +566,20 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
|
||||
picks.insert(0, if out.closed { BrushPick::Activate(key) } else { BrushPick::Select(key) });
|
||||
}
|
||||
picks.extend(picks_of(std::mem::take(&mut out.events)));
|
||||
let after = BrushPickerState { browser, parts: next_parts.get(), search: next_search.get() };
|
||||
let mut after = BrushPickerState {
|
||||
browser,
|
||||
parts: next_parts.get(),
|
||||
search: next_search.get(),
|
||||
recent_row: next_recent_row.get(),
|
||||
recent: before.recent.clone(),
|
||||
holding: before.holding,
|
||||
held: before.held.clone(),
|
||||
};
|
||||
// The row holds its order while the pointer is on it in the open picker, then notes the preset picked.
|
||||
after.hold_recent(out.open && on_recent.get());
|
||||
let rows = source.rows(ui.ctx(), &env);
|
||||
let now = out.picked.clone().or_else(|| held.clone());
|
||||
let _ = after.note_recent(now.as_ref(), |key| rows.iter().any(|row| !row.is_group() && row.key == *key));
|
||||
let mut settings = None;
|
||||
if after != before {
|
||||
let event = EditEvent::set(Mixed::Same(before.clone()), after.clone(), name.clone(), None);
|
||||
@@ -510,6 +667,7 @@ struct ToolsProps<'a, K: 'static> {
|
||||
held: Option<K>,
|
||||
parts: BrushCardParts,
|
||||
search: bool,
|
||||
recent_row: bool,
|
||||
import: bool,
|
||||
browser_id: egui::Id,
|
||||
#[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")]
|
||||
@@ -517,22 +675,25 @@ struct ToolsProps<'a, K: 'static> {
|
||||
sent: Outbox<'a, ToolsRun<K>>,
|
||||
}
|
||||
|
||||
/// What a run of the search row's tools reports: the picks, and the parts and Show Search Bar as the gear left them.
|
||||
/// What a run of the search row's tools reports: the picks, and the parts, Show Search Bar and Show Recent Brushes as
|
||||
/// the gear left them.
|
||||
struct ToolsRun<K> {
|
||||
picks: Vec<BrushPick<K>>,
|
||||
parts: BrushCardParts,
|
||||
search: bool,
|
||||
recent_row: bool,
|
||||
}
|
||||
|
||||
/// The Brush Settings and New Brush Preset buttons and the gear menu. A memoized view: it runs while its menu is
|
||||
/// open, and replays while nothing it shows changes.
|
||||
fn tools_view<K: Value + Eq + Hash + MemoProps>(props: &mut ToolsProps<'_, K>, ui: &mut Ui) {
|
||||
let words = Env::of(ui).words::<BrushPresetWords>();
|
||||
let ToolsProps { has_current, ref held, parts, search, import, browser_id, gear_rows, .. } = *props;
|
||||
let ToolsProps { has_current, ref held, parts, search, recent_row, import, browser_id, gear_rows, .. } = *props;
|
||||
let held = held.clone();
|
||||
let mut picks = Vec::new();
|
||||
let next_parts = Cell::new(parts);
|
||||
let next_search = Cell::new(search);
|
||||
let next_recent_row = Cell::new(recent_row);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let icon = |name: &'static str| IconSpec::svg(IconId::new(name));
|
||||
let settings = IconButton::new(icon("adjustments")).label(words.settings.clone()).tooltip(words.settings.clone()).show(ui);
|
||||
@@ -585,6 +746,10 @@ fn tools_view<K: Value + Eq + Hash + MemoProps>(props: &mut ToolsProps<'_, K>, u
|
||||
if MenuItem::new(words.search_bar.clone()).check(shown).keep_open(true).show(ui).ran {
|
||||
next_search.set(!shown);
|
||||
}
|
||||
let recent_shown = next_recent_row.get();
|
||||
if MenuItem::new(words.recent_row.clone()).check(recent_shown).keep_open(true).show(ui).ran {
|
||||
next_recent_row.set(!recent_shown);
|
||||
}
|
||||
app_rows(ui, GearSection::View);
|
||||
Divider::horizontal().show(ui);
|
||||
if import && MenuItem::new(words.menu_import.clone()).show(ui).ran {
|
||||
@@ -597,7 +762,7 @@ fn tools_view<K: Value + Eq + Hash + MemoProps>(props: &mut ToolsProps<'_, K>, u
|
||||
}
|
||||
});
|
||||
});
|
||||
props.sent.send(ToolsRun { picks, parts: next_parts.get(), search: next_search.get() });
|
||||
props.sent.send(ToolsRun { picks, parts: next_parts.get(), search: next_search.get(), recent_row: next_recent_row.get() });
|
||||
}
|
||||
|
||||
/// Keeps what Escape goes back to while the popover is open and returns the values Escape sets back, if any.
|
||||
@@ -632,3 +797,24 @@ fn escape_revert<K>(
|
||||
}
|
||||
reverted
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::BrushPickerState;
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
/// While the pointer is on the recent row the row keeps its order; once the hold ends, every preset picked
|
||||
/// during it goes to the front in the order it was picked.
|
||||
#[trial]
|
||||
fn a_hold_keeps_the_order_until_it_ends() {
|
||||
let mut state = BrushPickerState::<u32>::new();
|
||||
state.recent = vec![1, 2, 3];
|
||||
state.hold_recent(true);
|
||||
assert!(state.note_recent(Some(&3), |_| true));
|
||||
assert!(state.note_recent(Some(&2), |_| true));
|
||||
assert_eq!(state.recent, vec![1, 2, 3], "the row keeps its order during the hold");
|
||||
state.hold_recent(false);
|
||||
assert_eq!(state.recent, vec![2, 3, 1], "both picks count, the last one first");
|
||||
assert!(!state.release_recent(), "the hold has ended");
|
||||
}
|
||||
}
|
||||
@@ -76,10 +76,11 @@ impl BrushCardParts {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the picker remembers across restarts: which parts show, whether the search field shows and the thumbnail
|
||||
/// scale. The app saves it in its settings (serde) when
|
||||
/// What the picker remembers across restarts: which parts show, whether the search field and the recent row show
|
||||
/// and the thumbnail scale. The app saves it in its settings (serde) when
|
||||
/// [`BrushPresetPickerOutput::settings`](super::BrushPresetPickerOutput::settings) is set and restores it with
|
||||
/// [`BrushPickerState::restore`]; the search text, open groups and an open rename are not saved.
|
||||
/// [`BrushPickerState::restore`]; the search text, open groups, an open rename and the recent presets themselves are
|
||||
/// not saved.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui::contract::MemoProps)]
|
||||
#[serde(default)]
|
||||
#[non_exhaustive]
|
||||
@@ -90,11 +91,13 @@ pub struct BrushPickerSettings {
|
||||
pub scale: f32,
|
||||
/// The gear's Show Search Bar: the search field in the row above the presets.
|
||||
pub search: bool,
|
||||
/// The gear's Show Recent Brushes: the row of recently used presets under the search field.
|
||||
pub recent_row: bool,
|
||||
}
|
||||
|
||||
impl Default for BrushPickerSettings {
|
||||
fn default() -> Self {
|
||||
Self { parts: BrushCardParts::ALL, scale: 1.0, search: true }
|
||||
Self { parts: BrushCardParts::ALL, scale: 1.0, search: true, recent_row: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,30 +105,31 @@ impl BrushPickerSettings {
|
||||
/// The footer slider's range: under 0.15 the thumbnails and rows stop making sense.
|
||||
pub const SCALE_RANGE: RangeInclusive<f32> = 0.15..=2.0;
|
||||
|
||||
/// The settings with the given parts and scale, and the search field shown.
|
||||
/// The settings with the given parts and scale, and the search field and the recent row shown.
|
||||
pub const fn new(parts: BrushCardParts, scale: f32) -> Self {
|
||||
Self { parts, scale, search: true }
|
||||
Self { parts, scale, search: true, recent_row: true }
|
||||
}
|
||||
|
||||
/// The settings made safe to show: the scale clamped to [`SCALE_RANGE`](Self::SCALE_RANGE) (one that isn't a
|
||||
/// finite number gives 1), and every part on when none is.
|
||||
pub fn restored(self) -> Self {
|
||||
let scale = if self.scale.is_finite() { self.scale.clamp(*Self::SCALE_RANGE.start(), *Self::SCALE_RANGE.end()) } else { 1.0 };
|
||||
Self { parts: self.parts.normalised(), scale, search: self.search }
|
||||
Self { parts: self.parts.normalised(), scale, search: self.search, recent_row: self.recent_row }
|
||||
}
|
||||
}
|
||||
|
||||
impl<K> BrushPickerState<K> {
|
||||
/// The part of this state that persists.
|
||||
pub fn settings(&self) -> BrushPickerSettings {
|
||||
BrushPickerSettings { parts: self.parts, scale: self.browser.zoom as f32, search: self.search }
|
||||
BrushPickerSettings { parts: self.parts, scale: self.browser.zoom as f32, search: self.search, recent_row: self.recent_row }
|
||||
}
|
||||
|
||||
/// Sets the parts and scale from `settings`, [`restored`](BrushPickerSettings::restored) first.
|
||||
pub fn restore(&mut self, settings: &BrushPickerSettings) {
|
||||
let BrushPickerSettings { parts, scale, search } = settings.restored();
|
||||
let BrushPickerSettings { parts, scale, search, recent_row } = settings.restored();
|
||||
self.parts = parts;
|
||||
self.search = search;
|
||||
self.recent_row = recent_row;
|
||||
self.browser.zoom = f64::from(scale);
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,10 @@ craft_ui::words! {
|
||||
part_tip: "brushPresets.partTip" = "Brush Tip";
|
||||
/// Gear menu: the search field box.
|
||||
search_bar: "brushPresets.searchBar" = "Show Search Bar";
|
||||
/// Gear menu: the recent row box.
|
||||
recent_row: "brushPresets.recentRow" = "Show Recent Brushes";
|
||||
/// The row of recently used presets under the search field, for AccessKit.
|
||||
recent: "brushPresets.recent" = "Recent brushes";
|
||||
/// Gear menu: Import Brushes….
|
||||
menu_import: "brushPresets.menuImport" = "Import Brushes…";
|
||||
/// A preset's accessible name: "{name}, {size}".
|
||||
|
||||
@@ -35,7 +35,7 @@ impl Outcome for BrushSizeOutput {
|
||||
}
|
||||
|
||||
/// The brush Size row of Brush Tip Shape and of the Brush Preset picker's head: the label and a number field (px,
|
||||
/// whole pixels, 1 to the maximum) on one line, a log slider below.
|
||||
/// whole pixels, 1 to the maximum; a typed fraction is cut off, 2.5 is 2) on one line, a log slider below.
|
||||
///
|
||||
/// The field and the slider show one value: a slider drag rounds to whole pixels and stays one gesture while the
|
||||
/// binding takes the rounded value; a typed value is a `Set`. Escape during a drag cancels. With
|
||||
@@ -66,8 +66,13 @@ impl<'a> BrushSizeField<'a> {
|
||||
Some(original) => diameter.reset(original.clamp(1.0, max)),
|
||||
None => diameter,
|
||||
};
|
||||
let shown =
|
||||
SliderField::new(label, diameter, 1.0..=max).scale(SliderScale::Log).step(1.0).unit_kind(UnitKind::Pixels).enabled(max > 1.0).show(ui);
|
||||
let shown = SliderField::new(label, diameter, 1.0..=max)
|
||||
.scale(SliderScale::Log)
|
||||
.step(1.0)
|
||||
.truncate_typed()
|
||||
.unit_kind(UnitKind::Pixels)
|
||||
.enabled(max > 1.0)
|
||||
.show(ui);
|
||||
BrushSizeOutput { response: shown.edit.response.clone(), edit: shown.edit, out_of_range: shown.out_of_range }
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@ use craft_theme::Srgba;
|
||||
use craft_ui::buttons::{IconButton, ToggleButton};
|
||||
use craft_ui::choice::{Checkbox, Swatch, SwatchFill, SwatchImage};
|
||||
use craft_ui::contract::{
|
||||
Bind, BodyCx, Entry, Gap, LabelKind, PopupKind, Props as _, Remember as _, Show as _, ShowContainer as _, SideLabel, Trigger, clicked,
|
||||
Bind, BodyCx, Entry, FieldLayout, Gap, LabelKind, PopupKind, Props as _, Remember as _, Show as _, ShowContainer as _, SideLabel, Trigger,
|
||||
clicked,
|
||||
};
|
||||
use craft_ui::display::Divider;
|
||||
use craft_ui::form::Field;
|
||||
@@ -17,6 +18,7 @@ use craft_ui::layout_components::Row;
|
||||
use craft_ui::menu::{Menu, MenuItem};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::popover::Popover;
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::{Env, Label, UnitKind};
|
||||
use craft_ui::text::{NumberField, RangeAlert};
|
||||
use egui::{Response, Ui};
|
||||
@@ -30,6 +32,9 @@ pub use words::PaintBarWords;
|
||||
/// The icon of the toggles that let pen pressure control the opacity or the size.
|
||||
const PRESSURE: &str = "target";
|
||||
|
||||
/// The degrees the Pencil's Angle field holds.
|
||||
const ANGLE_RANGE: RangeInclusive<f64> = -180.0..=180.0;
|
||||
|
||||
/// The painting tools the bar serves.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
|
||||
#[non_exhaustive]
|
||||
@@ -66,6 +71,8 @@ pub struct PaintValues<M> {
|
||||
pub erase_to_history: bool,
|
||||
/// The pencil erases where it starts on the foreground colour.
|
||||
pub auto_erase: bool,
|
||||
/// The brush tip's angle in degrees, -180 to 180; the Pencil's bar shows it.
|
||||
pub angle: f64,
|
||||
/// The Mixer Brush's values.
|
||||
pub mixer: MixerValues,
|
||||
}
|
||||
@@ -84,6 +91,7 @@ impl<M> PaintValues<M> {
|
||||
mode,
|
||||
erase_to_history: false,
|
||||
auto_erase: false,
|
||||
angle: 0.0,
|
||||
mixer: MixerValues::default(),
|
||||
}
|
||||
}
|
||||
@@ -227,9 +235,9 @@ struct SmoothingOpen(bool);
|
||||
|
||||
/// The bar's members for one painting tool, after the preset picker that carries the size and the hardness: a rule,
|
||||
/// Mode, Opacity and the pressure-for-opacity toggle, Flow and the build-up toggle (not the Pencil), Smoothing and its
|
||||
/// options (the Pencil's Auto Erase in their place), Erase to History for the Eraser, a rule and the
|
||||
/// pressure-for-size toggle. Opacity and Flow hold 1 to 100 %, Smoothing 0 to 100 %. The Mixer Brush shows its load,
|
||||
/// combinations and mix values instead.
|
||||
/// options, the Pencil's Angle, a rule and Auto Erase, Erase to History for the Eraser, a rule and the
|
||||
/// pressure-for-size toggle. Opacity and Flow hold 1 to 100 %, Smoothing 0 to 100 %, Angle whole degrees from
|
||||
/// -180 to 180. The Mixer Brush shows its load, combinations and mix values instead.
|
||||
#[must_use = "show the bar with `show`"]
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
#[pattern(probe(PaintBar<'static, u32>))]
|
||||
@@ -311,11 +319,11 @@ impl<'a, M: Value> PaintBar<'a, M> {
|
||||
pass.toggle(ui, "sparkles", &words.build_up, sized && soft, pass.values.build_up, |v, x| v.build_up = x);
|
||||
}
|
||||
pass.percent(ui, "smoothing", &words.smoothing, Percents::any(true), pass.values.smoothing.amount, |v, x| v.smoothing.amount = x);
|
||||
pass.smoothing_options(ui, cx, &words);
|
||||
if tool == PaintTool::Pencil {
|
||||
pass.angle(ui, &words);
|
||||
Divider::vertical().show(ui);
|
||||
pass.check(ui, &words.auto_erase, true, Some(&words.auto_erase_tip), pass.values.auto_erase, |v, x| v.auto_erase = x);
|
||||
} else {
|
||||
pass.smoothing_options(ui, cx, &words);
|
||||
}
|
||||
if tool == PaintTool::Eraser {
|
||||
pass.check(ui, &words.erase_to_history, true, None, pass.values.erase_to_history, |v, x| v.erase_to_history = x);
|
||||
@@ -414,6 +422,49 @@ impl<M: Value> Pass<'_, M> {
|
||||
});
|
||||
}
|
||||
|
||||
/// The brush tip's Angle: whole degrees in [`ANGLE_RANGE`] behind an angle icon, the caption its accessible name.
|
||||
fn angle(&mut self, ui: &mut Ui, words: &PaintBarWords) {
|
||||
let current = self.values.angle;
|
||||
let collected: RefCell<(EditEvents<Option<f64>>, Option<RangeAlert>)> = RefCell::new((EditEvents::new(), None));
|
||||
let side = SideLabel::new().scrub(true).icon(IconSpec::svg(IconId::new("rotate_cw"))).layout(FieldLayout::Inside);
|
||||
let _ = Field::new(words.angle.clone()).side(side).id_salt("angle").show(ui, |ui, _| {
|
||||
let field = NumberField::new(words.angle.clone(), Bind::given(Some(current)))
|
||||
.unit_kind(UnitKind::Degrees)
|
||||
.range(ANGLE_RANGE)
|
||||
.commit_decimals(0)
|
||||
.tooltip(words.angle_tip.clone())
|
||||
.scrub_by_label()
|
||||
.show(ui);
|
||||
let mut sink = collected.borrow_mut();
|
||||
for event in field.edit.events.clone() {
|
||||
sink.0.push(event);
|
||||
}
|
||||
if field.out_of_range.is_some() {
|
||||
sink.1 = field.out_of_range;
|
||||
}
|
||||
});
|
||||
let (events, alert) = collected.into_inner();
|
||||
if alert.is_some() {
|
||||
self.out_of_range = alert;
|
||||
}
|
||||
// Only a proposed angle is made whole: a `before` keeps the host's angle, so a cancel or an undo restores it.
|
||||
let whole = |shown: Option<f64>| shown.map(|degrees| degrees.round().clamp(*ANGLE_RANGE.start(), *ANGLE_RANGE.end()));
|
||||
let events: EditEvents<Option<f64>> = events
|
||||
.into_iter()
|
||||
.map(|event| match event {
|
||||
EditEvent::Update { id, value, .. } => EditEvent::update(id, whole(value)),
|
||||
EditEvent::Commit { id, before, after, .. } => EditEvent::commit(id, before, whole(after)),
|
||||
EditEvent::Set { before, after, label, doc_key, .. } => EditEvent::set(before, whole(after), label, doc_key),
|
||||
other => other,
|
||||
})
|
||||
.collect();
|
||||
self.emit(events, |v, shown: Option<f64>| {
|
||||
if let Some(degrees) = shown {
|
||||
v.angle = degrees;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A checkbox over a flag; a pick is one `Set`.
|
||||
fn check(&mut self, ui: &mut Ui, caption: &Label, enabled: bool, tip: Option<&Label>, current: bool, set: fn(&mut PaintValues<M>, bool)) {
|
||||
let mut checkbox = Checkbox::new(Bind::given(current)).label(caption.clone()).enabled(enabled);
|
||||
|
||||
@@ -33,6 +33,10 @@ craft_ui::words! {
|
||||
auto_erase: "paintBar.autoErase" = "Auto Erase";
|
||||
/// The tooltip of Auto Erase.
|
||||
auto_erase_tip: "paintBar.autoEraseTip" = "Draws background color over foreground colors";
|
||||
/// The Pencil's Angle field's caption.
|
||||
angle: "paintBar.angle" = "Angle";
|
||||
/// The tooltip of the Angle field.
|
||||
angle_tip: "paintBar.angleTip" = "Set the brush angle";
|
||||
/// The Eraser's Brush mode.
|
||||
eraser_brush: "paintBar.eraserBrush" = "Brush";
|
||||
/// The Eraser's Pencil mode.
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
//! The Brush Preset picker: Rename Brush… in the gear opens the browser's name field on the current preset; the app
|
||||
//! opens the picker at a point without its field; a resized picker keeps its size; the head edits angle and
|
||||
//! roundness; Escape reverts the head's edits; a Size or Hardness typed out of range reports the range alert.
|
||||
//! roundness; Escape reverts the head's edits; a Size or Hardness typed out of range reports the range alert, and the
|
||||
//! picker stays open under the alert; a typed Size fraction is cut off; the recent row under the search row picks its
|
||||
//! presets and Show Recent Brushes hides it.
|
||||
|
||||
use craft_draw::ui::brush_presets::{BrushCardParts, BrushPick, BrushPickerState, BrushPickerValues, BrushPresetPicker, BrushRowPaint, brush_row};
|
||||
use craft_draw::ui::brush_presets::{
|
||||
BrushCardParts, BrushPick, BrushPickerSettings, BrushPickerState, BrushPickerValues, BrushPresetPicker, BrushRowPaint, brush_row,
|
||||
};
|
||||
use craft_draw::ui::brush_settings::TipAngle;
|
||||
use craft_ui::contract::{Bind, Role, SaveKey};
|
||||
use craft_ui::dialog::{Alert, DialogHost, HostedAlert};
|
||||
use craft_ui::patterns::presets::{PresetEvent, PresetFns, PresetRow, PresetSource};
|
||||
use craft_ui::primitives::FacePaint;
|
||||
use craft_ui::runtime::env::Env;
|
||||
@@ -275,6 +280,66 @@ fn size_and_hardness_typed_out_of_range_report_the_range_alert() {
|
||||
assert_eq!(host.alerts.len(), 3, "a value in range and a slider press alert nothing: {:?}", host.alerts);
|
||||
}
|
||||
|
||||
/// The app's side of a picker that shows the range alert it reports on a dialog host, as an app does.
|
||||
struct Alerting {
|
||||
current: Option<u32>,
|
||||
state: BrushPickerState<u32>,
|
||||
values: BrushPickerValues,
|
||||
open: bool,
|
||||
dialogs: DialogHost,
|
||||
}
|
||||
|
||||
/// A picker opened at [`POINT`] whose range alerts open on `dialogs`, drawn after the picker.
|
||||
fn alerting_rig() -> (Fixture, Rc<RefCell<Alerting>>) {
|
||||
let host = Rc::new(RefCell::new(Alerting {
|
||||
current: Some(HARD),
|
||||
state: BrushPickerState::new(),
|
||||
values: OPENED,
|
||||
open: true,
|
||||
dialogs: DialogHost::new(),
|
||||
}));
|
||||
let shown = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut host = shown.borrow_mut();
|
||||
let Alerting { current, state, values, open, dialogs } = &mut *host;
|
||||
let rows = PresetSource::new(state.parts, PresetFns::new(two_rows));
|
||||
let out = BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &rows, Bind::bound(state), *values)
|
||||
.open_at(POINT, Bind::bound(open))
|
||||
.show(ui);
|
||||
if let Some(diameter) = out.diameter.landed() {
|
||||
values.diameter = *diameter;
|
||||
}
|
||||
if let Some(alert) = &out.out_of_range {
|
||||
let _ = dialogs.open(HostedAlert::new(Alert::range("Alert", alert, &Env::of(ui))));
|
||||
}
|
||||
dialogs.run(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(640.0, 760.0));
|
||||
fixture.settle();
|
||||
(fixture, host)
|
||||
}
|
||||
|
||||
/// The range alert the picker raises opens over it, and the picker stays open under the alert and after its OK, so
|
||||
/// the next value can be typed; a typed Size fraction is cut off without an alert.
|
||||
#[trial]
|
||||
fn the_picker_stays_open_under_its_range_alert_and_after_ok() {
|
||||
let (mut fixture, host) = alerting_rig();
|
||||
type_into(&mut fixture, "Size", "2.5");
|
||||
assert_eq!(host.borrow().values.diameter, 2.0, "a typed fraction is cut off, not rounded");
|
||||
assert!(host.borrow().dialogs.is_empty(), "a value in range opens no alert");
|
||||
type_into(&mut fixture, "Size", "9999");
|
||||
fixture.idle(4);
|
||||
assert_eq!(host.borrow().values.diameter, 5000.0);
|
||||
assert!(!host.borrow().dialogs.is_empty(), "the alert is open");
|
||||
assert!(host.borrow().open, "the picker stays open under the alert");
|
||||
let ok = fixture.by_label("OK").expect("the alert's OK shows");
|
||||
fixture.click(&ok);
|
||||
fixture.idle(4);
|
||||
assert!(host.borrow().dialogs.is_empty(), "OK closes the alert");
|
||||
assert!(host.borrow().open, "the picker stays open after OK");
|
||||
assert_eq!(host.borrow().values.diameter, 5000.0, "OK keeps the closest value");
|
||||
}
|
||||
|
||||
/// The memoized views of `props` that ran in the last frame.
|
||||
fn views_ran(fixture: &Fixture, props: &str) -> usize {
|
||||
last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Ran).count()
|
||||
@@ -306,3 +371,93 @@ fn a_size_drag_runs_the_head_and_replays_the_preset_list() {
|
||||
fixture.frame(vec![release(from + Vec2::new(32.0, 0.0))]);
|
||||
assert_ne!(host.borrow().values.diameter, OPENED.diameter, "the drag edited the size");
|
||||
}
|
||||
|
||||
/// The current preset goes to the front of the recent row once, a preset picked again moves there, the row keeps at
|
||||
/// most eight, and a preset that no longer exists leaves it.
|
||||
#[trial]
|
||||
fn note_recent_keeps_the_newest_eight_that_still_exist() {
|
||||
let mut state = BrushPickerState::<u32>::new();
|
||||
let all = |_: &u32| true;
|
||||
assert!(state.note_recent(Some(&1), all));
|
||||
assert!(!state.note_recent(Some(&1), all), "the same preset again changes nothing");
|
||||
assert!(state.note_recent(Some(&2), all));
|
||||
assert!(state.note_recent(Some(&1), all));
|
||||
assert_eq!(state.recent, vec![1, 2], "a preset picked again moves to the front");
|
||||
for key in 3..=12 {
|
||||
let _ = state.note_recent(Some(&key), all);
|
||||
}
|
||||
assert_eq!(state.recent, (5..=12).rev().collect::<Vec<_>>(), "the row keeps the newest eight");
|
||||
assert!(state.note_recent(None, |key| *key != 12));
|
||||
assert_eq!(state.recent.first(), Some(&11), "a deleted preset leaves the row");
|
||||
assert!(!state.note_recent(Some(&40), |key| *key != 40), "a preset that does not exist is not noted");
|
||||
assert!(!state.release_recent(), "no hold to end");
|
||||
}
|
||||
|
||||
/// Show Recent Brushes is part of the remembered view: it comes back through `restore`, and settings saved before it
|
||||
/// existed keep the row shown.
|
||||
#[trial]
|
||||
fn show_recent_brushes_round_trips_through_the_settings() {
|
||||
let mut state = BrushPickerState::<u32>::new();
|
||||
assert!(state.recent_row && state.settings().recent_row, "the row shows by default");
|
||||
state.recent_row = false;
|
||||
let saved = serde_json::to_value(state.settings()).expect("the settings serialise");
|
||||
let mut fresh = BrushPickerState::<u32>::new();
|
||||
fresh.restore(&serde_json::from_value::<BrushPickerSettings>(saved).expect("the settings read back"));
|
||||
assert!(!fresh.recent_row, "the hidden row stays hidden");
|
||||
let old: BrushPickerSettings = serde_json::from_value(serde_json::json!({"search": false})).expect("old settings read");
|
||||
assert!(old.recent_row, "settings without the key show the row");
|
||||
}
|
||||
|
||||
/// A picker over two presets with no current preset and the recent row holding Soft Round then Hard Round, opened
|
||||
/// from its field.
|
||||
fn recent_rig() -> (Fixture, Rc<RefCell<Host>>) {
|
||||
let mut state = BrushPickerState::new();
|
||||
state.recent = vec![1, HARD];
|
||||
let host = Rc::new(RefCell::new(Host { current: None, state, picks: Vec::new() }));
|
||||
let shown = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut host = shown.borrow_mut();
|
||||
let Host { current, state, picks } = &mut *host;
|
||||
let rows = PresetSource::new(state.parts, PresetFns::new(two_rows));
|
||||
let values = BrushPickerValues::new(12.0, Some(1.0));
|
||||
let out = BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &rows, Bind::bound(state), values).show(ui);
|
||||
picks.extend(out.picks);
|
||||
});
|
||||
fixture.room(Vec2::new(480.0, 720.0));
|
||||
fixture.settle();
|
||||
let field = fixture.by_role(Role::COMBO_BOX).first().copied().expect("the closed field shows");
|
||||
fixture.click(&field);
|
||||
fixture.idle(3);
|
||||
(fixture, host)
|
||||
}
|
||||
|
||||
/// The recent row sits under the search row; a click on its first tile picks Soft Round and keeps the picker open.
|
||||
#[trial]
|
||||
fn a_click_on_a_recent_tile_picks_that_preset() {
|
||||
let (mut fixture, host) = recent_rig();
|
||||
let gear = fixture.by_label("Brush Preset Options").expect("the gear sits in the search row");
|
||||
let row = fixture.by_label("Recent brushes").expect("the recent row shows");
|
||||
assert!(row.rect.min.y >= gear.rect.max.y - 1.0, "the row is under the search row: {:?} / {:?}", gear.rect, row.rect);
|
||||
fixture.click_at(row.rect.left_top() + Vec2::splat(12.0));
|
||||
fixture.idle(3);
|
||||
let host = host.borrow();
|
||||
assert!(host.picks.contains(&BrushPick::Select(1)), "the tile's preset is picked: {:?}", host.picks);
|
||||
assert_eq!(host.current, Some(1), "the binding holds it");
|
||||
assert!(!fixture.by_role(Role::DIALOG).is_empty(), "a click keeps the picker open");
|
||||
assert_eq!(host.state.recent, vec![1, HARD], "the row keeps its order");
|
||||
}
|
||||
|
||||
/// The gear's Show Recent Brushes hides the row and reports the changed view for the app to save.
|
||||
#[trial]
|
||||
fn show_recent_brushes_hides_the_row() {
|
||||
let (mut fixture, host) = recent_rig();
|
||||
assert!(fixture.by_label("Recent brushes").is_some(), "the row shows");
|
||||
let gear = fixture.by_label("Brush Preset Options").expect("the gear shows");
|
||||
fixture.click(&gear);
|
||||
fixture.idle(3);
|
||||
let toggle = fixture.by_label("Show Recent Brushes").expect("the gear lists Show Recent Brushes");
|
||||
fixture.click(&toggle);
|
||||
fixture.idle(3);
|
||||
assert!(!host.borrow().state.recent_row, "the box turned the row off");
|
||||
assert!(fixture.by_label("Recent brushes").is_none(), "the row is gone");
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
//! `PaintBar`: which members each tool disables, the smoothing options, the gestures, the combinations list, what the
|
||||
//! load swatch shows, a click on its menu and the percents each field holds.
|
||||
//! `PaintBar`: which members each tool disables, the smoothing options, the Pencil's Angle, the gestures, the
|
||||
//! combinations list, what the load swatch shows, a click on its menu and the percents each field holds.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_behavior::EditEvent;
|
||||
use craft_behavior::{EditEvent, Mixed};
|
||||
use craft_draw::ui::{EraserMode, MIXER_COMBINATIONS, MixerLoad, PaintBar, PaintTool, PaintValues};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
@@ -235,3 +235,44 @@ fn opacity_and_flow_hold_one_to_a_hundred_percent_and_smoothing_still_takes_zero
|
||||
assert_eq!(host.values.smoothing.amount, 0.0, "Smoothing takes 0");
|
||||
assert!(host.alerts.is_empty(), "and reports nothing: {:?}", host.alerts);
|
||||
}
|
||||
|
||||
/// The Pencil's bar has the smoothing gear after Smoothing, its options waiting for an amount as on the Brush, and the
|
||||
/// brush tip's Angle after it (photocraft#11963, photocraft#11964): whole degrees from -180 to 180, a typed value past
|
||||
/// them kept at the closest end and reported once. The edit's `before` keeps the host's own angle, a fraction too, so
|
||||
/// an undo restores it. The Brush's bar has no Angle.
|
||||
#[trial]
|
||||
fn the_pencil_has_the_smoothing_options_and_an_angle_field() {
|
||||
for (amount, expect_disabled) in [(0.0, true), (0.1, false)] {
|
||||
let (mut fixture, _) = harness(PaintTool::Pencil, EraserMode::Brush, |v| v.smoothing.amount = amount);
|
||||
page_to_end(&mut fixture);
|
||||
let gear = fixture.by_label("Smoothing options").expect("the Pencil's bar shows the smoothing gear");
|
||||
fixture.click(&gear);
|
||||
fixture.idle(3);
|
||||
assert_eq!(disabled(&fixture, "Pulled String Mode"), expect_disabled, "amount {amount}");
|
||||
}
|
||||
|
||||
for (typed, kept, alerts) in [("400", 180.0, 1), ("-200", -180.0, 1), ("-45", -45.0, 0)] {
|
||||
let (mut fixture, host) = harness(PaintTool::Pencil, EraserMode::Brush, |v| v.angle = 30.4);
|
||||
page_to_end(&mut fixture);
|
||||
type_into(&mut fixture, "Angle", typed);
|
||||
let host = host.borrow();
|
||||
assert_eq!(host.values.angle, kept, "{typed} keeps {kept}");
|
||||
assert_eq!(host.alerts.len(), alerts, "{typed}: {:?}", host.alerts);
|
||||
if let Some(alert) = host.alerts.first() {
|
||||
assert_eq!(alert.range, -180.0..=180.0, "the alert names -180 to 180");
|
||||
}
|
||||
assert!(!host.edits.is_empty(), "{typed} is an edit");
|
||||
for edit in &host.edits {
|
||||
let before = match edit {
|
||||
EditEvent::Begin { before, .. } | EditEvent::Commit { before, .. } | EditEvent::Set { before, .. } => Some(before),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(Mixed::Same(before)) = before {
|
||||
assert_eq!(before.angle, 30.4, "{typed}: the edit's before keeps the host's angle");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (fixture, _) = harness(PaintTool::Brush, EraserMode::Brush, |_| {});
|
||||
assert!(fixture.by_label("Angle").is_none(), "the Brush's bar has no Angle");
|
||||
}
|
||||
@@ -27,8 +27,9 @@ pub(crate) mod stories;
|
||||
/// The bend of both arcs the Cylinder starts with, in units of the half axis: about a quarter of the width.
|
||||
const DEFAULT_DEPTH: f64 = 0.5;
|
||||
|
||||
/// How far the wrap handle starts along its travel from the centre: about 15 %.
|
||||
const DEFAULT_WRAP_POS: f64 = 0.15;
|
||||
/// How far the wrap handle starts along its travel from the centre: 10 %, so a fresh cylinder stores wrap 0.9, as the
|
||||
/// reference application starts it (photocraft#12513: on a 400 px box the handle sits 20 px right of the centre).
|
||||
const DEFAULT_WRAP_POS: f64 = 0.1;
|
||||
|
||||
/// The silhouettes never cross, nor do the edges: the moved one stops this far (document units) short of the other.
|
||||
const MIN_SIDE: f64 = 1.0;
|
||||
@@ -82,7 +83,7 @@ pub struct CylinderValues {
|
||||
|
||||
impl CylinderValues {
|
||||
/// The values of the cylinder the Warp menu starts with over `rect` (left, top, right, bottom): its corners on the
|
||||
/// box, both arcs half an axis deep and the wrap handle 15 % along its travel.
|
||||
/// box, both arcs half an axis deep and the wrap handle 10 % along its travel (wrap 0.9).
|
||||
pub fn for_box(rect: [f64; 4]) -> Self {
|
||||
let [left, top, right, bottom] = rect;
|
||||
Self { left, bottom, right, top, top_depth: DEFAULT_DEPTH, bottom_depth: DEFAULT_DEPTH, wrap: wrap_of_pos(DEFAULT_WRAP_POS) }
|
||||
@@ -115,8 +116,9 @@ impl CylinderValues {
|
||||
}
|
||||
|
||||
/// The values after `handle` is dragged by `by` from the press, where they were `self`. A corner takes its
|
||||
/// silhouette and its edge along (the opposite corner stays); Bend moves both arcs' depth by the same step; Bottom
|
||||
/// moves the lower edge; Wrap follows the pointer along its travel; the surface moves the whole cylinder. The
|
||||
/// silhouette and its edge along (the opposite corner stays) and keeps both arcs' depth in document units; Bend
|
||||
/// moves both arcs' depth by the same step; Bottom moves the lower arc's depth alone (the lower edge and its corner
|
||||
/// stay); Wrap follows the pointer along its travel; the surface moves the whole cylinder. The
|
||||
/// silhouettes and the edges keep their order (a moved one stops 1 unit short of the other) and a depth stays
|
||||
/// within the half axis, or within its own reach when it already lies past that (a cylinder read from a file). A
|
||||
/// drag by nothing changes nothing.
|
||||
@@ -137,7 +139,9 @@ impl CylinderValues {
|
||||
v.top_depth = depth_dragged(self.top_depth, step);
|
||||
v.bottom_depth = depth_dragged(self.bottom_depth, step);
|
||||
}
|
||||
CylinderHandle::Bottom => v.bottom += by.y,
|
||||
// Only the lower arc's depth, by the drag over the half axis (photocraft#12513: +40 px on a 400 px
|
||||
// cylinder takes 0.5 to about 0.7).
|
||||
CylinderHandle::Bottom => v.bottom_depth = depth_dragged(self.bottom_depth, by.y / a),
|
||||
CylinderHandle::Wrap => v.wrap = wrap_of_pos(pos_of_wrap(self.wrap) + by.x / a),
|
||||
CylinderHandle::Surface => {
|
||||
v.left += by.x;
|
||||
@@ -162,6 +166,13 @@ impl CylinderValues {
|
||||
v.bottom = v.top + MIN_SIDE;
|
||||
}
|
||||
}
|
||||
// A corner keeps both arcs' depth in document units (photocraft#12513): in half-axis units each depth grows as
|
||||
// the half axis shrinks (200 → 189.75 px takes 0.5 to 0.527), up to the half axis like the other handles.
|
||||
if matches!(handle, CylinderHandle::TopRight | CylinderHandle::BottomLeft) {
|
||||
let k = a / ((v.right - v.left) / 2.0).max(MIN_SIDE / 2.0);
|
||||
v.top_depth = depth_scaled(self.top_depth, k);
|
||||
v.bottom_depth = depth_scaled(self.bottom_depth, k);
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
@@ -184,6 +195,12 @@ fn depth_dragged(depth0: f64, step: f64) -> f64 {
|
||||
(depth0 + step).clamp(-limit, limit)
|
||||
}
|
||||
|
||||
/// `depth0` scaled by `k`, kept within the half axis, or within its own reach when it already lies past that.
|
||||
fn depth_scaled(depth0: f64, k: f64) -> f64 {
|
||||
let limit = DEPTH_LIMIT.max(depth0.abs());
|
||||
(depth0 * k).clamp(-limit, limit)
|
||||
}
|
||||
|
||||
/// A handle of the cylinder editor.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
@@ -194,7 +211,7 @@ pub enum CylinderHandle {
|
||||
BottomLeft,
|
||||
/// The bend of the top edge.
|
||||
Bend,
|
||||
/// The bottom edge.
|
||||
/// The middle of the bottom edge: the lower arc's depth.
|
||||
Bottom,
|
||||
/// The wrap.
|
||||
Wrap,
|
||||
@@ -202,8 +219,8 @@ pub enum CylinderHandle {
|
||||
Surface,
|
||||
}
|
||||
|
||||
/// The look of the cylinder editor: its lines in `overlay.line` over `overlay.halo`, the corners as handle squares and
|
||||
/// the other handles as small handle circles.
|
||||
/// The look of the cylinder editor: its lines in `overlay.line` over `overlay.halo` and all five handles as handle
|
||||
/// squares, as the reference application draws them (photocraft#12513).
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct CylinderWarpStyle {
|
||||
@@ -213,10 +230,8 @@ pub struct CylinderWarpStyle {
|
||||
line: StyleColor,
|
||||
/// Under the lines, so they read over any picture.
|
||||
halo: StyleColor,
|
||||
/// The two corners.
|
||||
anchor: HandleLook,
|
||||
/// Bend, Bottom and Wrap.
|
||||
end: HandleLook,
|
||||
/// The five handles.
|
||||
handle: HandleLook,
|
||||
/// How far from a handle a press takes it.
|
||||
reach: f32,
|
||||
}
|
||||
@@ -244,8 +259,8 @@ struct Report {
|
||||
/// The cylinder editor over `values`, drawn over `mesh` (the mesh the app builds from the values).
|
||||
///
|
||||
/// - Look: the cylinder's outline and a 3 × 2 grid (two vertical curves and the centre line across, four horizontal
|
||||
/// curves) traced on the mesh; squares at the top-right and bottom-left corners, circles at the middle of each arc,
|
||||
/// and one for the wrap.
|
||||
/// curves) traced on the mesh; squares at the top-right and bottom-left corners, at the middle of each arc and for
|
||||
/// the wrap.
|
||||
/// - Pointer: a handle within the hit reach takes the press; elsewhere on the cylinder a press moves the whole of it;
|
||||
/// off it nothing. One drag is one gesture (`Begin` on the first move, `Commit` on release); Esc cancels it. A press
|
||||
/// that does not move changes nothing.
|
||||
@@ -348,14 +363,11 @@ impl Component for CylinderWarp<'_> {
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: CylinderWarpStyleKey) -> CylinderWarpStyle {
|
||||
let overlay = &cx.tokens.color.overlay;
|
||||
let mut end = cx.handle();
|
||||
end.side = cx.tokens.size.handle.sm;
|
||||
CylinderWarpStyle {
|
||||
metrics: Metrics::new(),
|
||||
line: cx.color(overlay.line),
|
||||
halo: cx.color(overlay.halo),
|
||||
anchor: cx.handle(),
|
||||
end,
|
||||
handle: cx.handle(),
|
||||
reach: cx.tokens.size.hit.target,
|
||||
}
|
||||
}
|
||||
@@ -438,22 +450,15 @@ impl Component for CylinderWarp<'_> {
|
||||
draw.stroke(&PaintShape::Path(line), StrokeWidth::Thin, style.line);
|
||||
}
|
||||
}
|
||||
for (index, (handle, at)) in HANDLES.into_iter().zip(values.handle_points()).enumerate() {
|
||||
let look = &style.handle;
|
||||
for (index, at) in values.handle_points().into_iter().enumerate() {
|
||||
let center = view.to_screen(at);
|
||||
let part = HANDLE.at(index as u64);
|
||||
let corner = matches!(handle, CylinderHandle::TopRight | CylinderHandle::BottomLeft);
|
||||
let look = if corner { &style.anchor } else { &style.end };
|
||||
// An edit of this pass can have changed the values since `parts` declared the handles; those draw at rest.
|
||||
let fill = if cx.part_if_declared(part).is_some() { cx.resolve_part(part, &look.fill) } else { cx.resolve(&look.fill) };
|
||||
if corner {
|
||||
let square = PaintShape::Rect(Rect::from_center_size(center, Vec2::splat(look.side)), CornerRadius::ZERO);
|
||||
draw.fill(&square, fill);
|
||||
draw.stroke(&square, StrokeWidth::Thin, look.stroke);
|
||||
} else {
|
||||
let circle = PaintShape::Circle(center, look.side / 2.0);
|
||||
draw.fill(&circle, fill);
|
||||
draw.stroke(&circle, StrokeWidth::Thin, look.stroke);
|
||||
}
|
||||
let square = PaintShape::Rect(Rect::from_center_size(center, Vec2::splat(look.side)), CornerRadius::ZERO);
|
||||
draw.fill(&square, fill);
|
||||
draw.stroke(&square, StrokeWidth::Thin, look.stroke);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,8 +56,10 @@ pub struct WarpStyleEntry {
|
||||
pub label: String,
|
||||
/// A preset style: the orientation and Bend, H and V act on it.
|
||||
pub preset: bool,
|
||||
/// The style is offered over a type layer (false for Custom and Cylinder).
|
||||
/// The style is offered over a type layer (false for None and Cylinder).
|
||||
pub over_type: bool,
|
||||
/// Over a type layer the style is listed greyed: shown, never picked (Custom).
|
||||
pub greyed_over_type: bool,
|
||||
/// Split and Grid act on the style (false for Cylinder).
|
||||
pub splits: bool,
|
||||
}
|
||||
@@ -65,7 +67,7 @@ pub struct WarpStyleEntry {
|
||||
impl WarpStyleEntry {
|
||||
/// A style `key` shown as `label`, not a preset, offered over a type layer and enabling Split and Grid.
|
||||
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
|
||||
Self { key: key.into(), label: label.into(), preset: false, over_type: true, splits: true }
|
||||
Self { key: key.into(), label: label.into(), preset: false, over_type: true, greyed_over_type: false, splits: true }
|
||||
}
|
||||
|
||||
/// Whether the style is offered over a type layer.
|
||||
@@ -75,6 +77,13 @@ impl WarpStyleEntry {
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the style is listed greyed over a type layer (when [`over_type`](Self::over_type)).
|
||||
#[must_use]
|
||||
pub fn greyed_over_type(mut self, on: bool) -> Self {
|
||||
self.greyed_over_type = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the style enables Split and Grid.
|
||||
#[must_use]
|
||||
pub fn splits(mut self, on: bool) -> Self {
|
||||
@@ -218,9 +227,10 @@ pub struct WarpFieldsOutput {
|
||||
/// one pressed, a press on it disarms), a divider, "Grid" and a select (Custom, Default,
|
||||
/// 3 x 3, 4 x 4, 5 x 5), a divider, "Warp" and the style select, the orientation toggle
|
||||
/// (pressed when vertical), and Bend, H, V number fields (−100 to 100 %).
|
||||
/// - [`on_type`](Self::on_type): Split and Grid draw disabled and the styles with no
|
||||
/// [`over_type`](WarpStyleEntry::over_type) are not offered (PhotoCraft #3004). Split and Grid are also
|
||||
/// disabled while the current style has no [`splits`](WarpStyleEntry::splits).
|
||||
/// - [`on_type`](Self::on_type): Split is not drawn, Grid draws disabled, the styles with no
|
||||
/// [`over_type`](WarpStyleEntry::over_type) are not offered (PhotoCraft #3004) and the ones
|
||||
/// [`greyed_over_type`](WarpStyleEntry::greyed_over_type) are listed disabled (PhotoCraft #12499). Split and
|
||||
/// Grid are also disabled while the current style has no [`splits`](WarpStyleEntry::splits).
|
||||
/// - The orientation and the three fields are always there and enabled only on a preset style.
|
||||
/// - The group reports and never changes the warp.
|
||||
#[must_use = "show the group with `show`"]
|
||||
@@ -231,7 +241,7 @@ pub struct WarpFields<'a> {
|
||||
/// The armed Split tool, shown pressed.
|
||||
#[prop]
|
||||
split: Option<WarpSplit>,
|
||||
/// The warp is on a type layer: Split and Grid disabled, only the styles offered over a type layer.
|
||||
/// The warp is on a type layer: no Split, Grid disabled, only the styles offered over a type layer.
|
||||
#[prop(flag)]
|
||||
on_type: bool,
|
||||
}
|
||||
@@ -253,23 +263,11 @@ impl<'a> WarpFields<'a> {
|
||||
// The groups hold the bar's members, spaced as the bar spaces them.
|
||||
Row::new().gap(Gap::Item).show(ui, |ui, _| {
|
||||
Row::new().gap(Gap::Item).enabled(splits).show(ui, |ui, _| {
|
||||
Field::new(words.split.clone()).layout(caption).sizing(Sizing::Content).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let tools = [
|
||||
(WarpSplit::Cross, "split_cross", &words.split_crosswise),
|
||||
(WarpSplit::Vertical, "split_vertical", &words.split_vertically),
|
||||
(WarpSplit::Horizontal, "split_horizontal", &words.split_horizontally),
|
||||
];
|
||||
for (tool, icon, name) in tools {
|
||||
let armed = split == Some(tool);
|
||||
let button = ToggleButton::new(name.clone(), Bind::given(armed)).icon(IconId::new(icon)).icon_only().show(ui);
|
||||
if button.value().is_some() {
|
||||
edits.push(WarpFieldsEdit::Split(if armed { None } else { Some(tool) }));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
Divider::vertical().show(ui);
|
||||
// Over type the Split tools are not shown at all; Grid stays, greyed.
|
||||
if !on_type {
|
||||
split_tools(ui, &words, split, &mut edits);
|
||||
Divider::vertical().show(ui);
|
||||
}
|
||||
Field::new(words.grid.clone()).layout(caption).sizing(Sizing::Content).show(ui, |ui, _| {
|
||||
let entries = [
|
||||
Entry::new(WarpGridChoice::Custom, words.custom.clone()),
|
||||
@@ -292,7 +290,7 @@ impl<'a> WarpFields<'a> {
|
||||
let entries: Vec<Entry<String>> = styles
|
||||
.iter()
|
||||
.filter(|entry| !(on_type && !entry.over_type))
|
||||
.map(|entry| Entry::new(entry.key.clone(), entry.label.clone()))
|
||||
.map(|entry| Entry::new(entry.key.clone(), entry.label.clone()).enabled(!(on_type && entry.greyed_over_type)))
|
||||
.collect();
|
||||
let pick = Select::new(words.warp.clone(), Bind::given(values.style.clone()), &entries).sizing(Sizing::Content).show(ui);
|
||||
if let Some(picked) = pick.value()
|
||||
@@ -338,3 +336,23 @@ impl<'a> WarpFields<'a> {
|
||||
WarpFieldsOutput { edits }
|
||||
}
|
||||
}
|
||||
|
||||
/// "Split" and its three toggle buttons: the armed one pressed, a press on it disarms.
|
||||
fn split_tools(ui: &mut Ui, words: &WarpFieldsWords, split: Option<WarpSplit>, edits: &mut Vec<WarpFieldsEdit>) {
|
||||
Field::new(words.split.clone()).layout(FieldLayout::Beside).sizing(Sizing::Content).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let tools = [
|
||||
(WarpSplit::Cross, "split_cross", &words.split_crosswise),
|
||||
(WarpSplit::Vertical, "split_vertical", &words.split_vertically),
|
||||
(WarpSplit::Horizontal, "split_horizontal", &words.split_horizontally),
|
||||
];
|
||||
for (tool, icon, name) in tools {
|
||||
let armed = split == Some(tool);
|
||||
let button = ToggleButton::new(name.clone(), Bind::given(armed)).icon(IconId::new(icon)).icon_only().show(ui);
|
||||
if button.value().is_some() {
|
||||
edits.push(WarpFieldsEdit::Split(if armed { None } else { Some(tool) }));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -60,15 +60,15 @@ fn lines_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
on_canvas(ui, mesh, |ui, rect, mesh| WarpGrid::new("Warp", mesh_at.bind(mesh), picture()).lines_only().show_at(ui, rect))
|
||||
}
|
||||
|
||||
/// The app's style list: None, four presets, Custom and Cylinder.
|
||||
/// The app's style list: None, four presets, Custom and Cylinder. Over type: no None and no Cylinder, Custom greyed.
|
||||
fn styles() -> Vec<WarpStyleEntry> {
|
||||
vec![
|
||||
WarpStyleEntry::new("none", "None"),
|
||||
WarpStyleEntry::new("none", "None").over_type(false),
|
||||
WarpStyleEntry::new("arc", "Arc").preset(true),
|
||||
WarpStyleEntry::new("bulge", "Bulge").preset(true),
|
||||
WarpStyleEntry::new("flag", "Flag").preset(true),
|
||||
WarpStyleEntry::new("wave", "Wave").preset(true),
|
||||
WarpStyleEntry::new("custom", "Custom").over_type(false),
|
||||
WarpStyleEntry::new("custom", "Custom").greyed_over_type(true),
|
||||
WarpStyleEntry::new("cylinder", "Cylinder").over_type(false).splits(false),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2 as DocVec};
|
||||
use craft_behavior::{CanvasView, EditEvent};
|
||||
use craft_imaging::ui::warp::{CylinderValues, CylinderWarp, WarpEdit, WarpGrid, WarpMesh, WarpSplit};
|
||||
use craft_imaging::ui::warp::{CylinderValues, CylinderWarp, WarpEdit, WarpFieldValues, WarpFields, WarpGrid, WarpMesh, WarpSplit, WarpStyleEntry};
|
||||
use craft_ui::canvas::Canvas;
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
@@ -323,22 +323,29 @@ type HandleCase = ((f64, f64), (f32, f32), [f64; 7], &'static str);
|
||||
|
||||
#[trial]
|
||||
fn cylinder_handles_drag_their_values_and_keep_them_sound() {
|
||||
// RECT is 180 wide: the half axis is 90, the centre 190. Depths 0.5, wrap 0.85 (its handle 0.15 of the half axis out).
|
||||
let start = [100.0, 200.0, 280.0, 80.0, 0.5, 0.5, 0.85];
|
||||
// RECT is 180 wide: the half axis is 90, the centre 190. Depths 0.5, wrap 0.9 (its handle 0.1 of the half axis out).
|
||||
let start = [100.0, 200.0, 280.0, 80.0, 0.5, 0.5, 0.9];
|
||||
let (top_right, bottom_left, bend, bottom, wrap, surface) =
|
||||
((280.0, 80.0), (100.0, 200.0), (190.0, 125.0), (190.0, 245.0), (203.5, 185.0), (130.0, 160.0));
|
||||
((280.0, 80.0), (100.0, 200.0), (190.0, 125.0), (190.0, 245.0), (199.0, 185.0), (130.0, 160.0));
|
||||
// A corner keeps the arcs' depth in document units: 45 units deep over a half axis of 75 is 0.6, over 85 it is 45 / 85.
|
||||
let narrower = 45.0 / 85.0;
|
||||
// (handle's place, the drag in document units, the values after)
|
||||
let cases: [HandleCase; 10] = [
|
||||
(top_right, (-30.0, 15.0), [100.0, 200.0, 250.0, 95.0, 0.5, 0.5, 0.85], "the top right corner takes its silhouette and its edge"),
|
||||
(bottom_left, (10.0, -20.0), [110.0, 180.0, 280.0, 80.0, 0.5, 0.5, 0.85], "the bottom left corner takes its silhouette and its edge"),
|
||||
(bend, (0.0, 9.0), [100.0, 200.0, 280.0, 80.0, 0.6, 0.6, 0.85], "Bend moves both depths by the drag over the half axis"),
|
||||
(bend, (0.0, 150.0), [100.0, 200.0, 280.0, 80.0, 1.0, 1.0, 0.85], "a depth stays within the half axis"),
|
||||
(bottom, (0.0, 30.0), [100.0, 230.0, 280.0, 80.0, 0.5, 0.5, 0.85], "Bottom moves the lower edge"),
|
||||
(bottom, (0.0, -150.0), [100.0, 81.0, 280.0, 80.0, 0.5, 0.5, 0.85], "the lower edge stops 1 short of the top"),
|
||||
(wrap, (9.0, 0.0), [100.0, 200.0, 280.0, 80.0, 0.5, 0.5, 0.75], "Wrap follows the pointer along the axis"),
|
||||
(surface, (15.0, 5.0), [115.0, 205.0, 295.0, 85.0, 0.5, 0.5, 0.85], "the surface moves all four edges"),
|
||||
(top_right, (-190.0, 0.0), [100.0, 200.0, 101.0, 80.0, 0.5, 0.5, 0.85], "the right silhouette stops 1 short of the left"),
|
||||
(bottom_left, (190.0, 0.0), [279.0, 200.0, 280.0, 80.0, 0.5, 0.5, 0.85], "the left silhouette stops 1 short of the right"),
|
||||
(top_right, (-30.0, 15.0), [100.0, 200.0, 250.0, 95.0, 0.6, 0.6, 0.9], "the top right corner takes its silhouette and its edge"),
|
||||
(
|
||||
bottom_left,
|
||||
(10.0, -20.0),
|
||||
[110.0, 180.0, 280.0, 80.0, narrower, narrower, 0.9],
|
||||
"the bottom left corner takes its silhouette and its edge",
|
||||
),
|
||||
(bend, (0.0, 9.0), [100.0, 200.0, 280.0, 80.0, 0.6, 0.6, 0.9], "Bend moves both depths by the drag over the half axis"),
|
||||
(bend, (0.0, 150.0), [100.0, 200.0, 280.0, 80.0, 1.0, 1.0, 0.9], "a depth stays within the half axis"),
|
||||
(bottom, (0.0, 30.0), [100.0, 200.0, 280.0, 80.0, 0.5, 0.5 + 30.0 / 90.0, 0.9], "Bottom moves the lower arc's depth alone"),
|
||||
(bottom, (0.0, -150.0), [100.0, 200.0, 280.0, 80.0, 0.5, -1.0, 0.9], "the lower arc's depth stays within the half axis"),
|
||||
(wrap, (9.0, 0.0), [100.0, 200.0, 280.0, 80.0, 0.5, 0.5, 0.8], "Wrap follows the pointer along the axis"),
|
||||
(surface, (15.0, 5.0), [115.0, 205.0, 295.0, 85.0, 0.5, 0.5, 0.9], "the surface moves all four edges"),
|
||||
(top_right, (-190.0, 0.0), [100.0, 200.0, 101.0, 80.0, 1.0, 1.0, 0.9], "the right silhouette stops 1 short of the left"),
|
||||
(bottom_left, (190.0, 0.0), [279.0, 200.0, 280.0, 80.0, 1.0, 1.0, 0.9], "the left silhouette stops 1 short of the right"),
|
||||
];
|
||||
for (at, (dx, dy), want, what) in cases {
|
||||
let mut h = cylinder_harness();
|
||||
@@ -379,8 +386,37 @@ fn cylinder_handles_drag_their_values_and_keep_them_sound() {
|
||||
let at = h.screen(top_right.0, top_right.1);
|
||||
h.fixture.click_at(at);
|
||||
h.fixture.key(egui::Key::ArrowRight, Modifiers::NONE);
|
||||
near(h.values(), [100.0, 200.0, 281.0, 80.0, 0.5, 0.5, 0.85], "an arrow");
|
||||
near(h.values(), [100.0, 200.0, 281.0, 80.0, 45.0 / 90.5, 45.0 / 90.5, 0.9], "an arrow");
|
||||
h.fixture.key(egui::Key::ArrowRight, Modifiers::SHIFT);
|
||||
near(h.values(), [100.0, 200.0, 291.0, 80.0, 0.5, 0.5, 0.85], "Shift and an arrow");
|
||||
near(h.values(), [100.0, 200.0, 291.0, 80.0, 45.0 / 95.5, 45.0 / 95.5, 0.9], "Shift and an arrow");
|
||||
assert_eq!(h.count(Seen::Set), 2);
|
||||
}
|
||||
|
||||
/// Over a type layer the Warp group shows no Split tools, greys Grid, and lists a style marked
|
||||
/// greyed over type (Custom) disabled, with the styles not offered over type (None) left out
|
||||
/// (PhotoCraft #12499).
|
||||
#[trial]
|
||||
fn over_type_the_group_hides_split_greys_grid_and_lists_custom_greyed() {
|
||||
let styles = vec![
|
||||
WarpStyleEntry::new("none", "None").over_type(false),
|
||||
WarpStyleEntry::new("arc", "Arc").preset(true),
|
||||
WarpStyleEntry::new("custom", "Custom").greyed_over_type(true),
|
||||
];
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = WarpFields::new(&styles, WarpFieldValues::new("arc")).on_type().show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
assert!(fixture.by_label("Split Warp Crosswise").is_none(), "no Split tools over type");
|
||||
let grid = fixture.by_label("Grid").expect("the Grid select is shown");
|
||||
assert!(fixture.tree().is_disabled_key(grid.node), "Grid is greyed over type");
|
||||
let warp = fixture.by_label("Warp").expect("the style select");
|
||||
fixture.click(&warp);
|
||||
fixture.settle();
|
||||
let tree = fixture.tree();
|
||||
let named = |name: &str| tree.keys().into_iter().filter(|key| tree.name_of(*key) == Some(name)).collect::<Vec<_>>();
|
||||
let custom = named("Custom");
|
||||
assert!(!custom.is_empty(), "Custom is listed over type");
|
||||
assert!(custom.iter().all(|key| tree.is_disabled_key(*key)), "and greyed");
|
||||
assert!(named("Arc").iter().any(|key| !tree.is_disabled_key(*key)), "a preset stays enabled");
|
||||
assert!(named("None").is_empty(), "None is not offered over type");
|
||||
}
|
||||
@@ -31,12 +31,17 @@ pub(super) fn dismissal(
|
||||
if let Some(reason) = escape(ctx, layer, scope, inside) {
|
||||
return Some(reason);
|
||||
}
|
||||
if dismiss.anchor_gone && layer.overlay.opener.as_ref().is_some_and(|first| !first.active(ctx, None).0.enabled) {
|
||||
// A layer that stays open under a modal (an alert its own field raised) leaves the modal's presses and focus to it,
|
||||
// and its opener, blocked by the modal, is still there.
|
||||
let under_modal = !dismiss.modal && overlay::modal_above(ctx, layer.id);
|
||||
if dismiss.anchor_gone && !under_modal && layer.overlay.opener.as_ref().is_some_and(|first| !first.active(ctx, None).0.enabled) {
|
||||
return Some(CloseReason::AnchorGone);
|
||||
}
|
||||
// The input hook recorded the press (and removed a primary one) as the lone point it landed on; the record stands
|
||||
// for the layers the pass already had, and presses inside the family and its anchors never get here.
|
||||
if dismiss.outside == Outside::Absorb {
|
||||
if under_modal {
|
||||
// The modal's press, not one beside this layer.
|
||||
} else if dismiss.outside == Outside::Absorb {
|
||||
// A layer that appears in this pass opened after the press was made, so the press is not outside it: `opening`
|
||||
// is what tells it from the layers the record stands for.
|
||||
if overlay::absorbed_press(ctx).is_some() && !overlay::opening(ctx, layer.id) {
|
||||
@@ -57,6 +62,7 @@ pub(super) fn dismissal(
|
||||
return Some(CloseReason::Enter);
|
||||
}
|
||||
if dismiss.focus_left
|
||||
&& !under_modal
|
||||
&& let Some(policy) = scope
|
||||
&& policy.kind != craft_behavior::ScopeKind::Group
|
||||
&& was_inside
|
||||
|
||||
@@ -219,7 +219,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
|
||||
// A modal closes the popups beneath it in the pass it first shows; `appears` is false in a discard pass that repeats
|
||||
// the frame, so the close is queued once. A popup opened above it later is not touched.
|
||||
if overlay.rank.is_modal() && appears {
|
||||
overlay::close_popups_outside(ctx, &[layer.id]);
|
||||
overlay::close_popups_under_modal(ctx, layer.id);
|
||||
}
|
||||
overlay::begin_layer(ctx, layer.id, tier, layer.exiting, placed.side);
|
||||
let shown = areas::show_layer(ctx, &spec, |ui| {
|
||||
@@ -274,6 +274,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
|
||||
entry.scoped = scope.is_some();
|
||||
entry.absorbs = overlay.dismiss.outside == Outside::Absorb;
|
||||
entry.closes_on_commands = overlay.dismiss.commands;
|
||||
entry.closes_under_modal = overlay.dismiss.modal;
|
||||
overlay::record(ctx, entry);
|
||||
let dismissed = if layer.exiting { None } else { dismissal(ctx, layer, shown.rect, anchor, scope, &mut memory) };
|
||||
// The layer closes after its body ran: the run shows it open, so a record of the run is not replayed.
|
||||
@@ -323,7 +324,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut
|
||||
let tier = overlay.tier(ctx);
|
||||
let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus);
|
||||
if overlay.rank.is_modal() && appears {
|
||||
overlay::close_popups_outside(ctx, &[layer.id]);
|
||||
overlay::close_popups_under_modal(ctx, layer.id);
|
||||
}
|
||||
// The body reports in its parent's space: the popup's points are the opener's screen less the layer's place.
|
||||
let to_parent = overlay::parent_space(ctx, layer.id);
|
||||
@@ -353,6 +354,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut
|
||||
entry.scoped = scope.is_some();
|
||||
entry.absorbs = overlay.dismiss.outside == Outside::Absorb;
|
||||
entry.closes_on_commands = overlay.dismiss.commands;
|
||||
entry.closes_under_modal = overlay.dismiss.modal;
|
||||
entry.window = true;
|
||||
entry.popup = true;
|
||||
overlay::record(ctx, entry);
|
||||
|
||||
@@ -67,6 +67,10 @@ pub struct Dismiss {
|
||||
pub anchor_gone: bool,
|
||||
/// A command a key, a native menu pick or the palette ran, from outside the layer and the layers opened from it.
|
||||
pub commands: bool,
|
||||
/// A modal layer opened above it: a popup closes in the pass the modal first shows. Off, it stays open under the
|
||||
/// modal, and the presses and the focus the modal takes do not close it either (a picker whose field raised a
|
||||
/// range alert, open again for the next value after OK).
|
||||
pub modal: bool,
|
||||
/// Seconds after opening.
|
||||
pub timeout: Option<f32>,
|
||||
}
|
||||
@@ -82,6 +86,7 @@ impl Dismiss {
|
||||
on_activate: false,
|
||||
anchor_gone: true,
|
||||
commands: true,
|
||||
modal: true,
|
||||
timeout: None,
|
||||
}
|
||||
}
|
||||
@@ -124,6 +129,12 @@ impl Dismiss {
|
||||
self
|
||||
}
|
||||
|
||||
/// Closes when a modal layer opens above it; off, it stays open under the modal ([`Dismiss::modal`]).
|
||||
pub const fn modal(mut self, on: bool) -> Self {
|
||||
self.modal = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Closes after `seconds`.
|
||||
pub const fn timeout(mut self, seconds: Option<f32>) -> Self {
|
||||
self.timeout = seconds;
|
||||
|
||||
@@ -174,6 +174,8 @@ pub struct OpenEntry {
|
||||
pub(crate) absorbs: bool,
|
||||
/// A command run from outside it closes it (`Dismiss::commands`).
|
||||
pub(crate) closes_on_commands: bool,
|
||||
/// A modal opened above it closes it (`Dismiss::modal`).
|
||||
pub(crate) closes_under_modal: bool,
|
||||
/// The entry is an OS window of the integration: it takes its place in the stack's order and facts, and no egui
|
||||
/// layer is shown for it.
|
||||
pub(crate) window: bool,
|
||||
@@ -235,6 +237,7 @@ impl OpenEntry {
|
||||
scoped: false,
|
||||
absorbs: false,
|
||||
closes_on_commands: true,
|
||||
closes_under_modal: true,
|
||||
window: false,
|
||||
popup: false,
|
||||
region: None,
|
||||
@@ -404,6 +407,16 @@ pub fn close_popups(ctx: &Context) {
|
||||
|
||||
/// `close_popups`, keeping the layers `inside` and the layers each was opened from.
|
||||
pub(crate) fn close_popups_outside(ctx: &Context, inside: &[Id]) {
|
||||
close_popups_except(ctx, inside, false);
|
||||
}
|
||||
|
||||
/// The popups a modal layer `modal` closes in the pass it first shows: those `close_popups_outside` closes, except the
|
||||
/// ones that stay open under a modal (`Dismiss::modal` off).
|
||||
pub(crate) fn close_popups_under_modal(ctx: &Context, modal: Id) {
|
||||
close_popups_except(ctx, &[modal], true);
|
||||
}
|
||||
|
||||
fn close_popups_except(ctx: &Context, inside: &[Id], for_modal: bool) {
|
||||
if !crate::runtime::measure::effect(ctx, "overlay::close_popups") {
|
||||
return;
|
||||
}
|
||||
@@ -419,6 +432,7 @@ pub(crate) fn close_popups_outside(ctx: &Context, inside: &[Id]) {
|
||||
pass.last
|
||||
.iter()
|
||||
.filter(|entry| entry.rank == Rank::Popup && entry.closes_on_commands && !entry.exiting && !kept.contains(&entry.id))
|
||||
.filter(|entry| !for_modal || entry.closes_under_modal)
|
||||
.map(|entry| entry.id)
|
||||
.collect()
|
||||
});
|
||||
@@ -1156,6 +1170,19 @@ pub(crate) fn beneath(ctx: &Context, layer: Id) -> (bool, Option<Id>) {
|
||||
(root.is_some() || modal_elsewhere(ctx, viewport), root)
|
||||
}
|
||||
|
||||
/// Whether a modal layer stands above the layer `layer` in the running viewport, as of the last pass: a dialog or alert
|
||||
/// opened over a popup that stays open under it (`Dismiss::modal` off), whose press and focus move are not the popup's
|
||||
/// to close on.
|
||||
pub(crate) fn modal_above(ctx: &Context, layer: Id) -> bool {
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let stack = with_persist(ctx, viewport, |persist| persist.stack.clone());
|
||||
let at = |id: Id| stack.iter().position(|shown| *shown == id);
|
||||
let Some(floor) = at(layer) else { return false };
|
||||
with_pass(ctx, |pass| {
|
||||
pass.last.iter().any(|entry| entry.blocks_window() && !entry.exiting && entry.id != layer && at(entry.id).is_some_and(|shown| shown > floor))
|
||||
})
|
||||
}
|
||||
|
||||
/// The live viewports with a modal open, each with its place in the modal stack: a modal layer as of their last
|
||||
/// finished pass (`Persist::modal`), or the app's own egui modal (`FrameInput::app_modal`), which blocks the app's other
|
||||
/// windows as a modal layer does. With both, the one that opened later is the window's top modal.
|
||||
|
||||
@@ -640,6 +640,8 @@ pub(crate) struct RowOptions {
|
||||
codec: Option<NumberCodec>,
|
||||
/// The step arrows of a number row's field.
|
||||
step_arrows: Option<StepArrows>,
|
||||
/// A number row takes whole numbers only ([`Param::whole_only`]).
|
||||
whole_only: bool,
|
||||
/// The labelled marks of a range row's slider.
|
||||
marks: Vec<(f64, Label)>,
|
||||
/// The link the row's help button reports ([`Param::help_link`]).
|
||||
@@ -697,6 +699,11 @@ impl RowOptions {
|
||||
self.step_arrows
|
||||
}
|
||||
|
||||
/// Whether a number row takes whole numbers only.
|
||||
pub(crate) fn whole_only(&self) -> bool {
|
||||
self.whole_only
|
||||
}
|
||||
|
||||
/// The labelled marks of a range row's slider.
|
||||
pub(crate) fn marks(&self) -> &[(f64, Label)] {
|
||||
&self.marks
|
||||
@@ -1102,6 +1109,17 @@ impl Param {
|
||||
self
|
||||
}
|
||||
|
||||
/// The `Number` row takes whole numbers only (`NumberField::whole_only`): a typed number with a fraction commits
|
||||
/// rounded to the nearest whole number with the range alert ([`HostedParamDialog::take_range_alert`](super::HostedParamDialog::take_range_alert)), and the
|
||||
/// Enter that commits it leaves the dialog open, as one past the range does in such a row. It applies to a plain
|
||||
/// number row and to one shown in a shared unit ([`Param::number_in_units`]); a row with a unit menu of its own
|
||||
/// ([`Param::number_with_units`]) does not take it.
|
||||
#[must_use]
|
||||
pub fn whole_only(mut self) -> Self {
|
||||
self.options.get_or_insert_default().whole_only = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Passes labelled `marks` to the `Range` row's slider.
|
||||
#[must_use]
|
||||
pub fn marks_labelled<L: Into<Label>>(mut self, marks: impl IntoIterator<Item = (f64, L)>) -> Self {
|
||||
|
||||
@@ -1007,6 +1007,9 @@ impl<'p> Pass<'p> {
|
||||
if let Some(arrows) = option.step_arrows() {
|
||||
field = field.step_arrows(arrows);
|
||||
}
|
||||
if option.whole_only() {
|
||||
field = field.whole_only(true);
|
||||
}
|
||||
let shown = field.show(ui);
|
||||
self.alert(shown.out_of_range);
|
||||
self.unparsed |= shown.edit.unparsed;
|
||||
@@ -1038,6 +1041,9 @@ impl<'p> Pass<'p> {
|
||||
if let Some(range) = range.clone() {
|
||||
field = field.range(range);
|
||||
}
|
||||
if option.whole_only() {
|
||||
field = field.whole_only(true);
|
||||
}
|
||||
let shown = field.show(ui);
|
||||
self.alert(shown.out_of_range);
|
||||
self.unparsed |= shown.edit.unparsed;
|
||||
|
||||
@@ -258,6 +258,24 @@ impl<'a> BrowserTools<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
type BrowserBandFn<'a, K> = Box<dyn FnMut(&mut Ui) -> Vec<PresetEvent<K>> + 'a>;
|
||||
|
||||
/// The host's content between the toolbar and the presets (a picker's row of recently used presets); the events it
|
||||
/// returns join the browser's, before the presets' own.
|
||||
pub struct BrowserBand<'a, K>(BrowserBandFn<'a, K>);
|
||||
|
||||
impl<'a, K> BrowserBand<'a, K> {
|
||||
/// The content that `show` adds, reporting its events.
|
||||
pub fn new(show: impl FnMut(&mut Ui) -> Vec<PresetEvent<K>> + 'a) -> Self {
|
||||
BrowserBand(Box::new(show))
|
||||
}
|
||||
|
||||
/// Adds the content and returns its events: how a picker hands its own to the browser it opens.
|
||||
pub(super) fn show(&mut self, ui: &mut Ui) -> Vec<PresetEvent<K>> {
|
||||
(self.0)(ui)
|
||||
}
|
||||
}
|
||||
|
||||
/// A library of named presets shown as thumbnails.
|
||||
///
|
||||
/// - **Rows.** The host's flat display list: groups with their depth, then presets. The grid view shows each group as
|
||||
@@ -330,6 +348,9 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 's
|
||||
/// Off by default, preserving the existing toolbar order.
|
||||
#[prop]
|
||||
tools_at_start: bool,
|
||||
/// The host's content between the toolbar and the presets, whose events join the browser's.
|
||||
#[prop(func = "FnMut(&mut Ui) -> Vec<PresetEvent<K>>")]
|
||||
band: Option<BrowserBand<'a, K>>,
|
||||
/// What a secondary click or the context-menu key opens: the standard row menu, the host's `row_items` alone, or
|
||||
/// nothing.
|
||||
#[prop]
|
||||
@@ -412,6 +433,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> PresetBrowser
|
||||
search: true,
|
||||
tools: None,
|
||||
tools_at_start: false,
|
||||
band: None,
|
||||
row_menu: PresetRowMenu::Standard,
|
||||
row_items: None,
|
||||
drags: false,
|
||||
@@ -752,6 +774,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> PresetBrowser<'_,
|
||||
search,
|
||||
mut tools,
|
||||
tools_at_start,
|
||||
mut band,
|
||||
row_menu,
|
||||
row_items,
|
||||
drags,
|
||||
@@ -830,6 +853,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> PresetBrowser<'_,
|
||||
if toolbar && !search {
|
||||
local.filter.clear();
|
||||
}
|
||||
let band_events = band.as_mut().map(|band| band.show(ui)).unwrap_or_default();
|
||||
// Under `Rule` every group is open and the state's open groups are not read.
|
||||
let open: Vec<bool> = if group_heads == GroupHeads::Rule {
|
||||
vec![true; rows.len()]
|
||||
@@ -876,7 +900,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> PresetBrowser<'_,
|
||||
sent: Outbox::new(&mut sent),
|
||||
};
|
||||
let _ = MemoView::new("presets", props, list_view::<K>).show(ui);
|
||||
let mut events = Vec::new();
|
||||
let mut events = band_events;
|
||||
let mut menu_target = cx.keep::<BrowserMemory<K>>().menu_target.clone();
|
||||
for run in sent {
|
||||
for event in run.events {
|
||||
|
||||
@@ -21,7 +21,7 @@ pub(crate) mod named;
|
||||
pub(crate) mod picker;
|
||||
|
||||
pub use crate::tile_grid::GroupHeads;
|
||||
pub use browser::{BrowserTools, PresetBrowser, PresetDrop, PresetItemCommands, PresetReorder, RowItems};
|
||||
pub use browser::{BrowserBand, BrowserTools, PresetBrowser, PresetDrop, PresetItemCommands, PresetReorder, RowItems};
|
||||
pub use event::{PresetEvent, PresetOutput};
|
||||
pub use files::{PresetExport, PresetFileEvent, PresetFileFailure, PresetFileRequest, PresetFiles};
|
||||
pub use footer::{PresetFooter, PresetFooterEvent, PresetFooterOptions, PresetFooterOutput};
|
||||
|
||||
@@ -10,7 +10,7 @@ pub(crate) mod stories;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::browser::{BrowserTools, PresetBrowser, TipFn};
|
||||
use super::browser::{BrowserBand, BrowserTools, PresetBrowser, TipFn};
|
||||
use super::event::{PresetEvent, PresetOutput};
|
||||
use super::footer::PresetFooterOptions;
|
||||
use super::model::{CellShape, PresetRow, PresetRowMenu};
|
||||
@@ -176,6 +176,10 @@ pub struct PresetPicker<'a, K: Value + Eq + Hash + MemoProps + 'static> {
|
||||
/// The host's controls at the reading end of the browser's toolbar.
|
||||
#[prop(func = "FnMut(&mut Ui)")]
|
||||
tools: Option<BrowserTools<'a>>,
|
||||
/// The host's content between the browser's toolbar and its presets, whose events join the browser's (a pick
|
||||
/// there picks as a pick of a preset does).
|
||||
#[prop(func = "FnMut(&mut Ui) -> Vec<PresetEvent<K>>")]
|
||||
band: Option<BrowserBand<'a, K>>,
|
||||
/// The id of the browser in the popover, which `PresetBrowser::request_rename` names: a host that starts a rename
|
||||
/// from its own control (a menu's Rename) gives one.
|
||||
#[prop]
|
||||
@@ -210,6 +214,10 @@ pub struct PresetPicker<'a, K: Value + Eq + Hash + MemoProps + 'static> {
|
||||
/// A click on a preset picks it and keeps the popover open; a double click or Enter picks it and closes.
|
||||
#[prop(flag)]
|
||||
keep_open: bool,
|
||||
/// The popover stays open under a modal layer opened above it (`Popover::stays_under_modal`): a range alert its
|
||||
/// head's field raised shows over it, and it is still open after OK.
|
||||
#[prop(flag)]
|
||||
stays_under_modal: bool,
|
||||
/// The browser's footer.
|
||||
#[prop]
|
||||
footer: Option<PresetFooterOptions<'a>>,
|
||||
@@ -264,6 +272,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps + 'static> PresetPicker<'a, K> {
|
||||
toolbar: self.toolbar,
|
||||
search: self.search,
|
||||
tools: self.tools.as_mut().map(|tools| BrowserTools::new(move |ui| tools.show(ui))),
|
||||
band: self.band.as_mut().map(|band| BrowserBand::new(move |ui| band.show(ui))),
|
||||
browser_id: self.browser_id,
|
||||
row_menu: self.row_menu,
|
||||
tip: self.tip.as_deref().map(|tip| Box::new(move |ui: &mut Ui, key: &K| tip(ui, key)) as TipFn<'_, K>),
|
||||
@@ -274,6 +283,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps + 'static> PresetPicker<'a, K> {
|
||||
tooltip: self.tooltip.clone(),
|
||||
head: self.head.as_mut().map(|head| PickerHead::new(move |ui, body| (head.0)(ui, body))),
|
||||
keep_open: self.keep_open,
|
||||
stays_under_modal: self.stays_under_modal,
|
||||
footer: self.footer.clone(),
|
||||
thumb_range: self.thumb_range,
|
||||
edit_face: self.edit_face,
|
||||
@@ -306,6 +316,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps + 'static> PresetPicker<'a, K> {
|
||||
toolbar: false,
|
||||
search: true,
|
||||
tools: None,
|
||||
band: None,
|
||||
browser_id: None,
|
||||
row_menu: PresetRowMenu::Standard,
|
||||
tip: None,
|
||||
@@ -316,6 +327,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps + 'static> PresetPicker<'a, K> {
|
||||
tooltip: None,
|
||||
head: None,
|
||||
keep_open: false,
|
||||
stays_under_modal: false,
|
||||
footer: None,
|
||||
thumb_range: TileZoom::Ladder,
|
||||
edit_face: false,
|
||||
@@ -363,6 +375,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps + 'static> PresetPicker<'a, K> {
|
||||
toolbar,
|
||||
search,
|
||||
mut tools,
|
||||
mut band,
|
||||
browser_id,
|
||||
row_menu,
|
||||
tip,
|
||||
@@ -373,6 +386,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps + 'static> PresetPicker<'a, K> {
|
||||
tooltip,
|
||||
mut head,
|
||||
keep_open,
|
||||
stays_under_modal,
|
||||
footer,
|
||||
thumb_range,
|
||||
edit_face,
|
||||
@@ -422,6 +436,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps + 'static> PresetPicker<'a, K> {
|
||||
(popover, Some(edit), edit_requested)
|
||||
}
|
||||
};
|
||||
let popover = if stays_under_modal { popover.stays_under_modal() } else { popover };
|
||||
let current = match value.reborrow().read(cx) {
|
||||
Some(Mixed::Same(held)) => held,
|
||||
_ => None,
|
||||
@@ -449,6 +464,9 @@ impl<'a, K: Value + Eq + Hash + MemoProps + 'static> PresetPicker<'a, K> {
|
||||
if let Some(tools) = tools.as_mut() {
|
||||
browser = browser.tools(|ui| tools.show(ui));
|
||||
}
|
||||
if let Some(band) = band.as_mut() {
|
||||
browser = browser.band(|ui| band.show(ui));
|
||||
}
|
||||
if let Some(id) = browser_id {
|
||||
browser = browser.browser_id(id);
|
||||
}
|
||||
|
||||
@@ -146,8 +146,9 @@ impl<'a, K: Clone + PartialEq + Send + Sync + 'static> PresetSource<'a, K> {
|
||||
}
|
||||
|
||||
impl<'a, K: Clone + PartialEq + MemoProps + Send + Sync + 'static> PresetSource<'a, K> {
|
||||
/// The prebuilt `rows`, for a host that builds them itself. Keyed by each row's key, name, depth and kind, which
|
||||
/// are all a named preset row shows.
|
||||
/// The prebuilt `rows`, for a host that builds them itself. Keyed by everything a row shows or is found by: its
|
||||
/// key, name, depth, kind, count, caption, icon, picture (by its key and aspect), faded look, tooltip,
|
||||
/// accessible name, search name and trailing icons, so a row that changes under the same name shows the change.
|
||||
pub fn listed(rows: &'a [PresetRow<K>]) -> Self {
|
||||
PresetSource::new(ListedRows(rows), PresetFns::new(|listed: &ListedRows<'_, K>, _| listed.0.to_vec()))
|
||||
}
|
||||
@@ -163,6 +164,19 @@ impl<K: MemoProps> MemoProps for ListedRows<'_, K> {
|
||||
row.label.key(key);
|
||||
row.depth.key(key);
|
||||
(row.kind == PresetKind::Item).key(key);
|
||||
row.count.key(key);
|
||||
row.caption.key(key);
|
||||
row.icon.key(key);
|
||||
row.preview.as_ref().map(|preview| (preview.paint.key(), preview.aspect)).key(key);
|
||||
row.dimmed.key(key);
|
||||
row.tooltip.key(key);
|
||||
row.accessible_name.key(key);
|
||||
row.search_name.key(key);
|
||||
row.trailing.len().key(key);
|
||||
for (icon, name) in &row.trailing {
|
||||
icon.key(key);
|
||||
name.key(key);
|
||||
}
|
||||
}
|
||||
self.0.len().key(key);
|
||||
}
|
||||
|
||||
@@ -8,11 +8,11 @@ use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, Outcome as _, Props as _, Role, SaveKey, Show as _, clicked};
|
||||
use craft_ui::dialog::{DialogHost, DialogResult, HeldAnswer, HeldOk, dialog_id};
|
||||
use craft_ui::patterns::form_dialogs::{
|
||||
DialogFields, FieldValue, FormButtons, FormDialog, HostedParamDialog, PagerStep, PanePager, Param, ParamDialog, ParamKind, ParamLayout,
|
||||
ParamResult, PreviewState,
|
||||
DialogFields, FieldValue, FormButtons, FormDialog, HostedParamDialog, NumberUnit, PagerStep, PanePager, Param, ParamDialog, ParamKind,
|
||||
ParamLayout, ParamResult, PreviewState,
|
||||
};
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::env::{Label, UnitKind};
|
||||
use craft_ui::runtime::memory::{Lifetime, saved_value};
|
||||
use craft_ui::runtime::overlay::CloseReason;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
@@ -1016,6 +1016,87 @@ fn a_row_whose_text_does_not_parse_holds_ok() {
|
||||
assert_eq!(answered.borrow().as_ref().and_then(|fields| fields.int("size")), Some(42), "OK answers the typed value");
|
||||
}
|
||||
|
||||
/// Where a test dialog files the values of its answer.
|
||||
type Answered = Rc<RefCell<Option<DialogFields>>>;
|
||||
|
||||
/// An Opacity row of whole percents from 1 to 100.
|
||||
fn opacity() -> Param {
|
||||
Param::new("opacity", "Opacity", ParamKind::number(Some(1.0), Some(100.0), 100.0, 1.0, 0))
|
||||
}
|
||||
|
||||
/// Runs a one-row dialog over `row`, labelled Opacity; the values of its answer and the number of range alerts it
|
||||
/// raised are filed in the returned cells.
|
||||
fn opacity_row(row: Param) -> (Fixture, Answered, Rc<Cell<usize>>) {
|
||||
let (answered, alerts) = (Rc::new(RefCell::new(None::<DialogFields>)), Rc::new(Cell::new(0)));
|
||||
let (out, seen) = (Rc::clone(&answered), Rc::clone(&alerts));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let shown = ParamDialog::new("row", "Row", vec![row.clone()]).show(ui);
|
||||
if shown.rows.is_some_and(|rows| rows.out_of_range.is_some()) {
|
||||
seen.set(seen.get() + 1);
|
||||
}
|
||||
if let Some(result) = shown.result {
|
||||
*out.borrow_mut() = Some(result.fields);
|
||||
}
|
||||
});
|
||||
// A decimal point, whatever the machine's region is. English is the source language, not a catalog.
|
||||
let (i18n, problems) = craft_i18n::I18n::from_owned(
|
||||
[(
|
||||
"de".to_owned(),
|
||||
String::new(),
|
||||
"@id trial.save Speichern
|
||||
"
|
||||
.to_owned(),
|
||||
)],
|
||||
&["de"],
|
||||
);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
i18n.set_format(craft_i18n::Format::from_tag("en"));
|
||||
fixture.host(std::sync::Arc::new(
|
||||
craft_host::Host::builder(craft_host::AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(std::sync::Arc::new(i18n)).build(),
|
||||
));
|
||||
(fixture, answered, alerts)
|
||||
}
|
||||
|
||||
// In a whole-only row, the Enter that commits a typed fraction raises the range alert and leaves the dialog open with
|
||||
// the rounded value, which the next Enter answers; a whole number answers at once. A row shown in a shared unit does
|
||||
// the same. A row that is not whole-only keeps the fraction and answers it.
|
||||
#[trial]
|
||||
fn enter_over_a_fraction_in_a_whole_only_row_raises_the_alert_and_holds_ok() {
|
||||
let typed_enter = |fixture: &mut Fixture, text: &str| {
|
||||
let field = fixture.by_label("Opacity").expect("the opacity row has a field");
|
||||
fixture.click(&field).settle();
|
||||
fixture.key(Key::A, Modifiers::COMMAND).type_text(text);
|
||||
fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
};
|
||||
let opacity_of = |answered: &Answered| answered.borrow().as_ref().and_then(|fields| fields.number("opacity"));
|
||||
|
||||
let percent = vec![NumberUnit::new("percent", UnitKind::Percent, "Percent", 1.0)];
|
||||
let rows = [
|
||||
("a plain row", opacity().whole_only()),
|
||||
("a row in a shared unit", Param::number_in_units("opacity", "Opacity", 100.0, 1.0, 0, "units", percent).whole_only()),
|
||||
];
|
||||
for (kind, row) in rows {
|
||||
let (mut fixture, answered, alerts) = opacity_row(row);
|
||||
fixture.settle();
|
||||
typed_enter(&mut fixture, "20.5");
|
||||
assert_eq!(alerts.get(), 1, "{kind}: the fraction raises the range alert");
|
||||
assert!(answered.borrow().is_none(), "{kind}: the Enter that raised it answers nothing");
|
||||
fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert_eq!(opacity_of(&answered), Some(21.0), "{kind}: the next Enter answers the rounded value");
|
||||
assert_eq!(alerts.get(), 1, "{kind}: and raises no second alert");
|
||||
}
|
||||
|
||||
let (mut fixture, answered, alerts) = opacity_row(opacity().whole_only());
|
||||
fixture.settle();
|
||||
typed_enter(&mut fixture, "50.0");
|
||||
assert_eq!((opacity_of(&answered), alerts.get()), (Some(50.0), 0), "a whole number answers at once");
|
||||
|
||||
let (mut fixture, answered, alerts) = opacity_row(opacity());
|
||||
fixture.settle();
|
||||
typed_enter(&mut fixture, "20.5");
|
||||
assert_eq!((opacity_of(&answered), alerts.get()), (Some(20.5), 0), "a row that is not whole-only answers the fraction");
|
||||
}
|
||||
|
||||
// Shift+Enter in a row's field confirms the dialog with the typed value.
|
||||
#[trial]
|
||||
fn shift_enter_in_a_row_answers_ok() {
|
||||
|
||||
@@ -168,6 +168,10 @@ pub struct SliderField<'a> {
|
||||
/// rounds to zero unsigned: the slider and its field show that value the same way.
|
||||
#[prop(flag)]
|
||||
explicit_plus: bool,
|
||||
/// A typed value is cut toward zero to the typed decimals instead of rounded ([`NumberField::truncate_typed`]): 2.5
|
||||
/// in a whole-number field is 2. A slider drag or a step is unchanged.
|
||||
#[prop(flag)]
|
||||
truncate_typed: bool,
|
||||
/// The number field's width from this pass's measure (its `Proposal::Ideal` call, which runs before `paint`).
|
||||
field_width: f32,
|
||||
/// The field's range alert of this pass, which `finish` reports.
|
||||
@@ -235,6 +239,7 @@ impl<'a> SliderField<'a> {
|
||||
short: false,
|
||||
select_on_focus: false,
|
||||
explicit_plus: false,
|
||||
truncate_typed: false,
|
||||
field_width: 0.0,
|
||||
out_of_range: None,
|
||||
}
|
||||
@@ -281,6 +286,7 @@ impl<'a> SliderField<'a> {
|
||||
short: self.short,
|
||||
select_on_focus: self.select_on_focus,
|
||||
explicit_plus: self.explicit_plus,
|
||||
truncate_typed: self.truncate_typed,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -320,6 +326,7 @@ struct Look {
|
||||
short: bool,
|
||||
select_on_focus: bool,
|
||||
explicit_plus: bool,
|
||||
truncate_typed: bool,
|
||||
}
|
||||
|
||||
/// The composite's check, which its children check their values with.
|
||||
@@ -460,6 +467,7 @@ impl Look {
|
||||
};
|
||||
let field = if self.select_on_focus { field.select_on_focus() } else { field };
|
||||
let field = if self.explicit_plus { field.explicit_plus() } else { field };
|
||||
let field = if self.truncate_typed { field.truncate_typed() } else { field };
|
||||
let field = match self.field_sizing {
|
||||
Some(sizing) => field.sizing(sizing),
|
||||
None => field,
|
||||
|
||||
@@ -176,6 +176,16 @@ impl<'a> Popover<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Keeps the popover open under a modal layer opened above it ([`Dismiss::modal`] off): a range alert its field
|
||||
/// raised shows over it, and the popover is still open after OK.
|
||||
#[must_use]
|
||||
pub fn stays_under_modal(self) -> Self {
|
||||
self.overlay(|mut overlay| {
|
||||
overlay.dismiss = overlay.dismiss.modal(false);
|
||||
overlay
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether Enter, pressed with the focus inside and left untaken by the focused part, closes the popover with
|
||||
/// `CloseReason::Enter`: pickers that commit by closing.
|
||||
#[must_use]
|
||||
|
||||
@@ -21,8 +21,8 @@ use crate::runtime::frame;
|
||||
use crate::style::{ComponentStyle, StyleColor, StyleCx, SurfaceLook, TextLook, TypeRole};
|
||||
use craft_behavior::nav::{LARGE_STEPS, StepResult, ValueAxes, ValueSteps};
|
||||
use craft_behavior::{
|
||||
Codec, ColumnKey, Granularity, HitLevel, HitPriority, HoldRepeat, Metrics, MoveMods, NavMove, NumberCodec, PartKey, PressPhase, Sense, ValueDrag,
|
||||
decimals_for_step, wheel_step,
|
||||
Codec, ColumnKey, Granularity, HitLevel, HitPriority, HoldRepeat, Intent, Metrics, MoveMods, NavMove, NumberCodec, PartKey, PressPhase, Sense,
|
||||
ValueDrag, decimals_for_step, wheel_step,
|
||||
};
|
||||
use craft_theme::{Rgba, Stateful, States};
|
||||
use egui::{CornerRadius, Rect, Vec2};
|
||||
@@ -200,10 +200,20 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option<f64>> {
|
||||
/// A typed value goes to the nearest multiple of the step when it commits.
|
||||
#[prop]
|
||||
snap_typed: bool,
|
||||
/// A typed value is cut toward zero to the commit decimals instead of rounded: with `commit_decimals(0)`, 2.5 is 2
|
||||
/// and -2.5 is -2. The range alert still reports the number as typed.
|
||||
#[prop(flag)]
|
||||
truncate_typed: bool,
|
||||
/// The decimals a committed value is rounded to; the display keeps the codec's, except that a percent field with no
|
||||
/// decimals of its own shows none when this is 0 ("10%").
|
||||
#[prop]
|
||||
commit_decimals: Option<usize>,
|
||||
/// The field takes whole numbers only, as `commit_decimals(0)` does, and a typed number with a fraction is
|
||||
/// reported like one past the range ([`NumberOutput::out_of_range`]): it commits rounded to the nearest whole
|
||||
/// number, half away from zero, then held to the range. The Enter that commits a reported value stays with the
|
||||
/// field, so an enclosing dialog's default button waits until the host has shown its alert.
|
||||
#[prop]
|
||||
whole_only: bool,
|
||||
/// An empty field means automatic: it shows the "Auto" word as its placeholder.
|
||||
#[prop]
|
||||
automatic: bool,
|
||||
@@ -315,10 +325,12 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
popup_slider: None,
|
||||
snap_popup_slider: true,
|
||||
snap_typed: false,
|
||||
truncate_typed: false,
|
||||
automatic: false,
|
||||
mixed_word: false,
|
||||
derived: false,
|
||||
commit_decimals: None,
|
||||
whole_only: false,
|
||||
fixed_decimals: None,
|
||||
explicit_plus: false,
|
||||
name_number: None,
|
||||
@@ -506,6 +518,11 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
value.and_then(NumberValue::number).map(|stored| self.to_shown(stored))
|
||||
}
|
||||
|
||||
/// The decimals a committed value is rounded to: none for a field that takes whole numbers only.
|
||||
fn commit_places(&self) -> Option<usize> {
|
||||
if self.whole_only { Some(0) } else { self.commit_decimals }
|
||||
}
|
||||
|
||||
/// Whether the field counts percent: it shows its sign right after the number.
|
||||
fn is_percent(&self) -> bool {
|
||||
self.codec.is_none() && self.unit_kind == Some(UnitKind::Percent)
|
||||
@@ -516,7 +533,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
/// (`commit_decimals(0)`).
|
||||
fn percent_decimals(&self) -> Option<usize> {
|
||||
(self.is_percent() && self.fixed_decimals.is_none() && self.max_decimals.is_none()).then(|| match self.precision {
|
||||
NumberPrecision::Standard => self.commit_decimals.unwrap_or(1).min(1),
|
||||
NumberPrecision::Standard => self.commit_places().unwrap_or(1).min(1),
|
||||
NumberPrecision::Measured => 0,
|
||||
})
|
||||
}
|
||||
@@ -586,7 +603,9 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
inner: self.number_codec(&env.units()),
|
||||
rule: self.rule(),
|
||||
snap: self.snap_typed,
|
||||
decimals: self.commit_decimals,
|
||||
truncate: self.truncate_typed,
|
||||
decimals: self.commit_places(),
|
||||
whole_only: self.whole_only,
|
||||
mixed,
|
||||
positive_only: self.positive_only,
|
||||
names,
|
||||
@@ -696,7 +715,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
typed,
|
||||
kept: kept.unwrap_or_else(|| rule.settle(typed)),
|
||||
range: rule.bounds(),
|
||||
whole: self.commit_decimals == Some(0) || self.decimals() == 0,
|
||||
whole: self.commit_places() == Some(0) || self.decimals() == 0,
|
||||
unit: self.unit.clone(),
|
||||
unit_kind: self.unit_kind,
|
||||
decimals: self.shown_decimals(),
|
||||
@@ -976,6 +995,11 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
|
||||
}
|
||||
cx.set(V::of_number(self.to_stored(rule.settle(next))));
|
||||
}
|
||||
// The Enter that committed a value the host reports is the alert's: the enclosing dialog does not take it as
|
||||
// its default button.
|
||||
if self.whole_only && cx.text(&text_part::<V>()).and_then(|outcome| outcome.committed).is_some_and(|note| note.held.is_some()) {
|
||||
cx.intents().take(Intent::Submit);
|
||||
}
|
||||
}
|
||||
|
||||
/// The edit menu, the presets list and the popup slider.
|
||||
|
||||
@@ -82,6 +82,17 @@ pub(super) fn round_to(value: f64, decimals: usize) -> f64 {
|
||||
(value * scale).round() / scale
|
||||
}
|
||||
|
||||
/// `value` cut toward zero to `decimals` decimal places. A value already at that precision stays: 1.15 scaled by 100 is
|
||||
/// a hair under 115 in binary, and is still 1.15, while 1.159 is 1.15 and 2.5 at no decimals is 2. Only a few units of
|
||||
/// the last place count as "already there", so a fraction just past the precision is still cut at many decimals.
|
||||
fn truncate_to(value: f64, decimals: usize) -> f64 {
|
||||
let scale = 10f64.powi(i32::try_from(decimals).unwrap_or(0));
|
||||
let scaled = value * scale;
|
||||
let nearest = scaled.round();
|
||||
let cut = if (scaled - nearest).abs() <= 16.0 * f64::EPSILON * nearest.abs().max(1.0) { nearest } else { scaled.trunc() };
|
||||
cut / scale
|
||||
}
|
||||
|
||||
/// The scale of a step by an arrow key: Shift moves `LARGE_STEPS` steps, Alt a share of one where the field's
|
||||
/// decimals show that share (`fine_shows`), both together one.
|
||||
pub(super) fn key_scale(mods: MoveMods, fine_shows: bool) -> f64 {
|
||||
@@ -107,7 +118,11 @@ pub(super) struct Ruled<V> {
|
||||
pub(super) inner: NumberCodec,
|
||||
pub(super) rule: Rule,
|
||||
pub(super) snap: bool,
|
||||
/// A typed number is cut toward zero to `decimals` instead of rounded.
|
||||
pub(super) truncate: bool,
|
||||
pub(super) decimals: Option<usize>,
|
||||
/// A typed number with a fraction is held like one past the range (`NumberField::whole_only`).
|
||||
pub(super) whole_only: bool,
|
||||
pub(super) mixed: bool,
|
||||
pub(super) positive_only: bool,
|
||||
pub(super) names: Vec<(u32, String)>,
|
||||
@@ -125,7 +140,9 @@ impl<V> Clone for Ruled<V> {
|
||||
inner: self.inner.clone(),
|
||||
rule: self.rule.clone(),
|
||||
snap: self.snap,
|
||||
truncate: self.truncate,
|
||||
decimals: self.decimals,
|
||||
whole_only: self.whole_only,
|
||||
mixed: self.mixed,
|
||||
positive_only: self.positive_only,
|
||||
names: self.names.clone(),
|
||||
@@ -157,6 +174,10 @@ impl<V: NumberValue> Ruled<V> {
|
||||
}
|
||||
|
||||
fn held(&self, number: f64) -> f64 {
|
||||
let number = match self.decimals {
|
||||
Some(decimals) if self.truncate => truncate_to(number, decimals),
|
||||
_ => number,
|
||||
};
|
||||
let snapped = if self.snap { self.rule.snap(number) } else { number };
|
||||
self.rule.settle(self.decimals.map_or(snapped, |decimals| round_to(snapped, decimals)))
|
||||
}
|
||||
@@ -207,8 +228,9 @@ impl<V: NumberValue> Codec for Ruled<V> {
|
||||
self.parse_tagged(text, start).map(|(value, _)| value)
|
||||
}
|
||||
|
||||
/// The inner codec's note, with `held` set to the number read (in shown units) when it lies outside the range;
|
||||
/// snapping and rounding are not holding. A name or a blank gives the default note.
|
||||
/// The inner codec's note, with `held` set to the number read (in shown units) when it lies outside the range, or
|
||||
/// has a fraction in a field that takes whole numbers only; snapping and other rounding are not holding. A name or
|
||||
/// a blank gives the default note.
|
||||
fn parse_tagged(&self, text: &str, start: &V) -> Result<(V, ParseNote), NotAValue> {
|
||||
if let Some(name) = self.name_of(text) {
|
||||
return Ok((name, ParseNote::default()));
|
||||
@@ -222,7 +244,8 @@ impl<V: NumberValue> Codec for Ruled<V> {
|
||||
if self.positive_only && number <= 0.0 {
|
||||
return Err(NotAValue);
|
||||
}
|
||||
note.held = (number < self.rule.low || number > self.rule.high).then_some(number);
|
||||
let fraction = self.whole_only && number.fract() != 0.0;
|
||||
note.held = (fraction || number < self.rule.low || number > self.rule.high).then_some(number);
|
||||
Ok((V::of_number(self.held(number) / self.scale), note))
|
||||
}
|
||||
None => V::blank().map(|blank| (blank, ParseNote::default())).ok_or(NotAValue),
|
||||
@@ -259,3 +282,17 @@ impl<V: NumberValue> Codec for Ruled<V> {
|
||||
Cow::Owned(self.samples(current).max_by_key(|text| text.chars().count()).unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::truncate_to;
|
||||
|
||||
#[test]
|
||||
fn truncation_cuts_toward_zero_and_keeps_values_at_the_precision() {
|
||||
for (value, decimals, want) in
|
||||
[(2.5, 0, 2.0), (-2.5, 0, -2.0), (1.159, 2, 1.15), (1.15, 2, 1.15), (-1.15, 2, -1.15), (0.29, 2, 0.29), (1.2345678919, 9, 1.234567891)]
|
||||
{
|
||||
assert_eq!(truncate_to(value, decimals), want, "{value} at {decimals} decimals");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -210,6 +210,87 @@ fn a_localised_decimal_types_in() {
|
||||
assert_eq!(typed(Some(host), None, "12,5"), Some(12.5));
|
||||
}
|
||||
|
||||
/// A whole-only field over 1 to 100 under `host`'s locale, with `text` typed over 50 and committed with Tab: the value
|
||||
/// kept and the range alert the commit reported.
|
||||
fn whole_typed(host: Option<Arc<Host>>, text: &str) -> (Option<f64>, Option<craft_ui::text::RangeAlert>) {
|
||||
let mut frames = Frames::new();
|
||||
if let Some(host) = host {
|
||||
frames.host(host);
|
||||
}
|
||||
let value = RefCell::new(Some(50.0));
|
||||
let alert = RefCell::new(None);
|
||||
let at = Cell::new(Pos2::ZERO);
|
||||
let mut show = |ui: &mut Ui| {
|
||||
let mut guard = value.borrow_mut();
|
||||
let out = NumberField::new("Opacity", Bind::bound(&mut *guard)).id_salt("opacity").range(1.0..=100.0).whole_only(true).show(ui);
|
||||
at.set(out.response.rect.center());
|
||||
if out.out_of_range.is_some() {
|
||||
*alert.borrow_mut() = out.out_of_range.clone();
|
||||
}
|
||||
// Where Tab takes the focus, so the field commits.
|
||||
NumberField::new("Other", Bind::bound(&mut Some(1.0))).id_salt("other").show(ui);
|
||||
};
|
||||
frames.idle(3, &mut show);
|
||||
click(&mut frames, at.get(), &mut show);
|
||||
frames.frame(vec![key_press(Key::A, Modifiers::COMMAND)], &mut show);
|
||||
frames.frame(vec![Event::Text(text.into())], &mut show);
|
||||
frames.idle(1, &mut show);
|
||||
frames.frame(vec![key_press(Key::Tab, Modifiers::NONE)], &mut show);
|
||||
frames.idle(3, &mut show);
|
||||
(value.into_inner(), alert.into_inner())
|
||||
}
|
||||
|
||||
/// A host whose number format is the region `tag`'s, whatever the machine's region is.
|
||||
fn region_host(tag: &str) -> Arc<Host> {
|
||||
// English is the source language, not a catalog: one catalog loaded, the format set apart.
|
||||
let (i18n, problems) = craft_i18n::I18n::from_owned(
|
||||
[(
|
||||
"de".to_owned(),
|
||||
String::new(),
|
||||
"@id trial.save Speichern
|
||||
"
|
||||
.to_owned(),
|
||||
)],
|
||||
&["de"],
|
||||
);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
i18n.set_format(craft_i18n::Format::from_tag(tag));
|
||||
Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(Arc::new(i18n)).build())
|
||||
}
|
||||
|
||||
/// A field that takes whole numbers only rounds a typed fraction to the nearest whole number, half up, and reports it
|
||||
/// as it reports a value past the range, written with the locale's decimal symbol; a zero fraction or a trailing
|
||||
/// separator is a whole number and reports nothing. A fraction past the range is held to its end.
|
||||
#[trial]
|
||||
fn a_whole_only_field_rounds_a_typed_fraction_and_reports_it() {
|
||||
let comma = region_host("de");
|
||||
for (text, kept) in [
|
||||
("12,3", 12.0),
|
||||
("12,4", 12.0),
|
||||
("12,5", 13.0),
|
||||
("12,7", 13.0),
|
||||
("1,5", 2.0),
|
||||
("99,5", 100.0),
|
||||
("50,01", 50.0),
|
||||
("0,4", 1.0),
|
||||
("150,5", 100.0),
|
||||
] {
|
||||
let (value, alert) = whole_typed(Some(Arc::clone(&comma)), text);
|
||||
assert_eq!(value, Some(kept), "{text}");
|
||||
let alert = alert.unwrap_or_else(|| panic!("{text} is reported"));
|
||||
assert!(alert.whole && alert.kept == kept && alert.typed != kept, "{text}: {alert:?}");
|
||||
}
|
||||
for (text, kept) in [("50,0", 50.0), ("50,00", 50.0), ("12,", 12.0)] {
|
||||
assert_eq!(whole_typed(Some(Arc::clone(&comma)), text), (Some(kept), None), "{text} is a whole number");
|
||||
}
|
||||
for (text, kept) in [("12.3", 12.0), ("12.7", 13.0)] {
|
||||
let (value, alert) = whole_typed(Some(region_host("en")), text);
|
||||
assert_eq!(value, Some(kept), "{text} under a decimal point");
|
||||
assert!(alert.is_some(), "{text} is reported");
|
||||
}
|
||||
assert_eq!(whole_typed(Some(region_host("en")), "42"), (Some(42.0), None), "a whole number in range reports nothing");
|
||||
}
|
||||
|
||||
/// A field over 0 to 100 with a popup slider.
|
||||
fn with_slider(ui: &mut Ui, data: &mut craft_ui::testing::StoryData) -> craft_ui::testing::StoryOutput {
|
||||
NumberField::new("Opacity", data.bind("value", Some(50.0))).range(0.0..=100.0).popup_slider(0.0..=100.0).show(ui).into()
|
||||
|
||||
Reference in new issue
Block a user