Merge storytold/next into rework-d2

Brings in craft-libs#2756 (frame-t3), #2810 (a memoized view in a row sits on the row's line) and #2838 (home rail look).

- egui pin and Cargo.lock: rework-d2's egui rev, which contains #2756's; frame-t3's serde line for craft-tracked.
- menu bar: EnglishFn goes with frame-t3's removal of english; rework-d2's docs stay.
- Env::start_view_room: keeps both column flags, then Shrink::Fit when the view fits.
- lazy::Place: both opacity and fits.
- Lazy::run_keyed: a memoized view's room is the row's cap when the row narrows it, else the flow region, and then moves down onto the row's line (on_row_line); the cap is horizontal and the move vertical, and the move keeps the room's size, so a kept run replays moved with it.
This commit is contained in:
aiongg committed 2026-11-21 14:23:08 +00:00
commit f016e24751
131 files changed
+3237 -1423

No files matched your search

Generated
+1
View File
@@ -4252,6 +4252,7 @@ name = "craft-tracked"
version = "0.1.0"
dependencies = [
"craft-ui-macros",
"serde",
]
[[package]]
+4
View File
@@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};
/// How a gradient's opacity is stored, which decides the rows of its stop bar.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
#[non_exhaustive]
pub enum StopRows {
/// Opacity stops in their own row above the ramp, colour stops below; a colour's alpha is
@@ -36,6 +37,7 @@ pub enum StopRow {
/// A colour stop.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ColorStop {
@@ -56,6 +58,7 @@ pub struct ColorStop {
/// An opacity stop of a [`StopRows::Split`] gradient.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct OpacityStop {
@@ -120,6 +123,7 @@ impl OpacityStop {
/// A gradient's stops, each list sorted by location.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct GradientStops {
+4
View File
@@ -97,6 +97,7 @@ impl SwatchFormat {
/// A swatch colour in its own model.
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
#[serde(tag = "model", content = "values", rename_all = "camelCase")]
pub enum SwatchColor {
/// Encoded RGB, 0–1 each, in the RGB working space.
@@ -148,6 +149,7 @@ impl SwatchColor {
/// How an `.ase` file marks a colour.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
#[serde(rename_all = "camelCase")]
pub enum SwatchKind {
#[default]
@@ -161,6 +163,7 @@ pub enum SwatchKind {
/// One named swatch.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
pub struct SwatchEntry {
/// The swatch's label.
pub name: String,
@@ -181,6 +184,7 @@ impl SwatchEntry {
/// A named group of swatches, as the Swatches panel shows them. A file without groups reads as
/// one group named after the file.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
pub struct SwatchGroup {
/// The group's label.
pub name: String,
+1 -1
View File
@@ -87,7 +87,7 @@ pub use screen_picker::{CaptureResult, CaptureSource, LOUPE_PIXELS, LOUPE_ZOOM,
pub use strip::{ColorStrip, ColorStripStyle};
pub use swatches::{
MAX_GROUPS, MAX_SWATCHES, SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput,
SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords, swatch_rows,
SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords, swatch_rows, swatch_source,
};
pub use warning::{ColorWarning, ColorWarningArrangement, ColorWarningChip, ColorWarningChipOutput, ColorWarningChipStyle};
pub use wheel::{
+5 -13
View File
@@ -14,14 +14,14 @@ use craft_behavior::{Axis, EditEvent, EditEvents, Metrics, PartKey};
use craft_cms::convert::CmykConverter;
use craft_theme::Srgba;
use craft_ui::buttons::Button;
use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchFace};
use craft_ui::choice::{ChoiceWords, Segmented, Swatch};
use craft_ui::contract::{
Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _, Pages,
PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _,
};
use craft_ui::display::{Shade, Text};
use craft_ui::layout_components::Row;
use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState, ThumbInfo};
use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState};
use craft_ui::primitives::textures::CachedTexture;
use craft_ui::primitives::{ContentPainterCx, PaintShape, StrokeWidth};
use craft_ui::runtime::env::{Env, Label};
@@ -30,7 +30,7 @@ use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx}
use egui::{Color32, Pos2, Rect, Response, Ui, pos2, vec2};
use super::popover::compact_picker;
use super::{PickedColor, ScreenPickGesture, SwatchKey, SwatchPalette, SwatchesWords, swatch_rows};
use super::{PickedColor, ScreenPickGesture, SwatchKey, SwatchPalette, swatch_source};
use crate::palette::{SwatchColor, SwatchGroup};
pub(crate) mod paint_list;
@@ -475,7 +475,6 @@ impl Component for PaintChip<'_> {
let solid = cx.memory::<LastSolid>().0.unwrap_or(self.fallback);
let current = FillKind::of(&paint);
let sampled = self.sampled;
let swatch_words = cx.words::<SwatchesWords>();
let recent_cells: Vec<(Label, Srgba)> = self.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
let full_picker = self.full_picker;
let cmyk = self.cmyk.unwrap_or_else(|| CmykConverter::coated());
@@ -514,21 +513,14 @@ impl Component for PaintChip<'_> {
}
if let Some((groups, state)) = swatches.as_mut() {
let groups: &[SwatchGroup] = groups;
let rows = swatch_rows(groups, &swatch_words);
let source = swatch_source(groups, cmyk);
let colors: HashMap<&str, &SwatchColor> =
groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect();
let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &rows)
let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &source)
.toolbar(false)
.row_menu(false)
.default_open(DefaultOpen::None)
.room_height(Env::of(ui).tokens.size.control.sm * SWATCH_ROWS)
.thumb(|painter: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| {
if let SwatchKey::Swatch(name) = info.key
&& let Some(color) = colors.get(name.as_str())
{
SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(painter, rect);
}
})
.show(ui);
for event in out.events {
if let PresetEvent::Select { key: SwatchKey::Swatch(name), .. } = event
+1 -1
View File
@@ -11,7 +11,7 @@ pub(crate) mod panel;
#[cfg(feature = "suite")]
pub(crate) mod stories;
pub use library::{SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesState, swatch_rows};
pub use library::{SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesState, swatch_rows, swatch_source};
pub use menu::{SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput};
pub use panel::{SwatchesPanel, SwatchesPanelOutput};
+38 -4
View File
@@ -2,8 +2,15 @@
use std::collections::HashSet;
use craft_cms::convert::CmykConverter;
use craft_theme::Srgba;
use craft_ui::choice::SwatchFace;
use craft_ui::contract::ReorderMove;
use craft_ui::patterns::presets::{PresetRow, PresetState};
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource, PresetState, ThumbInfo};
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::env::Env;
use egui::Rect;
use std::collections::BTreeMap;
use super::{MAX_GROUPS, MAX_SWATCHES, SWATCH_ZOOM, SwatchesWords};
use crate::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchReport};
@@ -11,7 +18,7 @@ use crate::ui::PickedColor;
/// What the browser names its rows by. Swatch names are unique across the library and group names among groups, so
/// both survive reordering.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub enum SwatchKey {
/// A group, by name.
@@ -556,8 +563,27 @@ impl SwatchLibrary {
}
}
/// The rows of the swatch list: each group at depth 0 with its count, each swatch at depth 1 with "name, value" as its
/// tooltip and accessible name. `SwatchesPanel` and `PaintChip`'s swatches list build their rows with it.
/// The swatch list's inputs: the library's groups and each swatch's colour as drawn, by name.
#[derive(craft_ui::contract::MemoProps)]
struct SwatchInputs<'a> {
groups: &'a [SwatchGroup],
drawn: BTreeMap<&'a str, Srgba>,
}
/// The presets of the swatch list: each group at depth 0 with its count, each swatch at depth 1 with "name, value" as
/// its tooltip and accessible name, painted in its colour through `cmyk`. `SwatchesPanel` and `PaintChip`'s swatches
/// list show it.
pub fn swatch_source<'a>(groups: &'a [SwatchGroup], cmyk: &CmykConverter) -> PresetSource<'a, SwatchKey> {
let drawn = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), e.color.to_srgb(cmyk)))).collect();
PresetSource::new(SwatchInputs { groups, drawn }, PresetFns::new(source_rows).thumb(paint_swatch))
}
fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec<PresetRow<SwatchKey>> {
swatch_rows(inputs.groups, &env.words::<SwatchesWords>())
}
/// The rows the Swatches panel lists for `groups`: each group's header, then its swatches, each named by its name and
/// colour value.
pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetRow<SwatchKey>> {
let mut rows = Vec::with_capacity(groups.len() + groups.iter().map(|g| g.entries.len()).sum::<usize>());
for group in groups {
@@ -570,6 +596,14 @@ pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetR
rows
}
fn paint_swatch(inputs: &SwatchInputs<'_>, cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>) {
if let SwatchKey::Swatch(name) = info.key
&& let Some(color) = inputs.drawn.get(name.as_str())
{
SwatchFace::new(*color).selected(info.selected).paint(cx, rect);
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
+7 -19
View File
@@ -1,24 +1,20 @@
//! `SwatchesPanel`: the panel body, its state and what it reports.
use std::collections::HashMap;
use craft_cms::convert::CmykConverter;
use craft_i18n::Format;
use craft_theme::Srgba;
use craft_theme::variant::Tone;
use craft_ui::bars::StatusMessage;
use craft_ui::choice::SwatchFace;
use craft_ui::contract::{Bind, Held, NoValue, Outcome, Pattern, ShowContainer as _, request_rename};
use craft_ui::layout_components::Stack;
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetWords, ThumbInfo};
use craft_ui::primitives::ContentPainterCx;
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetWords};
use craft_ui::runtime::env::{Count, Env};
use egui::{Rect, Response, Ui};
use egui::{Response, Ui};
use super::library::{find_swatch, has};
use super::menu::event_edits;
use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_rows};
use crate::palette::{SwatchColor, SwatchGroup, SwatchNote, SwatchReport};
use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_source};
use crate::palette::{SwatchGroup, SwatchNote, SwatchReport};
/// What [`SwatchesPanel::show`] reports.
#[derive(Debug)]
@@ -99,21 +95,13 @@ impl<'a> SwatchesPanel<'a> {
if st.selected.as_ref().is_some_and(|k| !has(groups, k)) {
st.selected = None;
}
let rows = swatch_rows(groups, &words);
let source = swatch_source(groups, cmyk);
let out = {
let colors: HashMap<&str, &SwatchColor> = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect();
let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &rows)
let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &source)
.thumb_range(SWATCH_ZOOM)
.toolbar(true)
.reorder(PresetReorder::items_and_groups())
.footer(PresetFooterOptions::new().can_delete(st.selected.is_some()))
.thumb(|cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| {
if let SwatchKey::Swatch(name) = info.key
&& let Some(color) = colors.get(name.as_str())
{
SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(cx, rect);
}
});
.footer(PresetFooterOptions::new().can_delete(st.selected.is_some()));
if let Some(key) = &st.selected {
browser = browser.selected(key.clone());
}
+1
View File
@@ -910,6 +910,7 @@ timeline-otio = ["timeline", "craft-timeline/otio"]
timeline-xml = ["timeline", "craft-timeline/xml"]
tracked = ["dep:craft-tracked"]
tracked-serde = ["tracked", "craft-tracked/serde"]
ui-app = ["ui", "craft-ui/app"]
ui-cloud = ["ui", "craft-ui/cloud"]
+3
View File
@@ -161,6 +161,9 @@ const NO_GLOBAL_STATE: &[(&str, &str)] = &[
("crates/ui-patterns/src/patterns/presets/model/library.rs", "MemoProps"),
// Settled fact: a name check keys by its inputs and its `fn` behind `dyn NameChecker`, as `Bind::check_with` does.
("crates/ui-patterns/src/patterns/presets/named.rs", "MemoProps"),
// Settled fact: `PresetSource` erases its inputs behind a trait object; it keys on those inputs (themselves
// `MemoProps`) and on the addresses of its capture-free `fn`s, which stand for the code that reads them.
("crates/ui-patterns/src/patterns/presets/source.rs", "MemoProps"),
// Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init.
("crates/ui-contract/src/fonts/defaults.rs", "HACK"),
("crates/ui-contract/src/fonts/defaults.rs", "EGUI_ICONS"),
+16 -10
View File
@@ -3,9 +3,9 @@
use std::hash::Hash;
use craft_behavior::{EditEvents, IconId};
use craft_ui::contract::{Bind, EditResponse, Outcome, Props as _, ShowContainer as _};
use craft_ui::contract::{Bind, EditResponse, MemoProps, Outcome, Props as _, ShowContainer as _};
use craft_ui::layout_components::Stack;
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetRow, PresetState};
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetSource, PresetState};
use craft_ui::runtime::drag::DropZone;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::sections::FooterAction;
@@ -29,9 +29,9 @@ pub(super) const BRUSH_THUMBS: TileZoom =
#[must_use = "show the panel with `show`"]
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
#[pattern(probe(BrushesPanel<'static, u32>))]
pub struct BrushesPanel<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
pub struct BrushesPanel<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> {
label: Label,
rows: &'a [PresetRow<K>],
source: &'a PresetSource<'a, K>,
state: Bind<'a, PresetState<K>>,
diameter: Bind<'a, f64>,
max_size: f64,
@@ -67,16 +67,22 @@ impl<K> Outcome for BrushesPanelOutput<K> {
}
}
impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> BrushesPanel<'a, K> {
/// A panel named `label` over the presets in `rows`, with its view in `state` and the brush
impl<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> BrushesPanel<'a, K> {
/// A panel named `label` over the presets of `source`, with its view in `state` and the brush
/// size in `diameter` up to `max_size`.
pub fn new(label: impl Into<Label>, rows: &'a [PresetRow<K>], state: Bind<'a, PresetState<K>>, diameter: Bind<'a, f64>, max_size: f64) -> Self {
BrushesPanel { label: label.into(), rows, state, diameter, max_size, selected: None, drop_zone: None, import: false }
pub fn new(
label: impl Into<Label>,
source: &'a PresetSource<'a, K>,
state: Bind<'a, PresetState<K>>,
diameter: Bind<'a, f64>,
max_size: f64,
) -> Self {
BrushesPanel { label: label.into(), source, state, diameter, max_size, selected: None, drop_zone: None, import: false }
}
/// Shows the panel.
pub fn show(self, ui: &mut Ui) -> BrushesPanelOutput<K> {
let BrushesPanel { label, rows, mut state, mut diameter, max_size, mut selected, mut drop_zone, import } = self;
let BrushesPanel { label, source, mut state, mut diameter, max_size, mut selected, mut drop_zone, import } = self;
let words = Env::of(ui).words::<BrushPresetWords>();
let shown = Stack::new().label(label.clone()).fill().show(ui, |ui, _| {
let size = BrushSizeField::new(words.size.clone(), diameter.reborrowed(), max_size).show(ui);
@@ -84,7 +90,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> BrushesPanel<'a, K> {
if import {
footer = footer.action(FooterAction::new(IconId::new("folder_open"), words.menu_import.clone()));
}
let mut browser = PresetBrowser::new(label.clone(), state.reborrowed(), rows)
let mut browser = PresetBrowser::new(label.clone(), state.reborrowed(), source)
.toolbar(true)
.row_menu(true)
.reorder(PresetReorder::items_and_groups())
+181 -123
View File
@@ -7,14 +7,15 @@ use std::hash::Hash;
use craft_behavior::{Codec as _, EditEvent, EditEvents, IconId, Mixed, NumberCodec, Value};
use craft_ui::buttons::IconButton;
use craft_ui::contract::{
Bind, BodyCx, EditResponse, Outcome, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _, TooltipSpec, Trigger, clicked,
Bind, BodyCx, EditResponse, MemoProps, MemoView, Outbox, Outcome, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _, TooltipSpec,
Trigger, clicked,
};
use craft_ui::display::Divider;
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, PresetRow, PresetState, PresetView, PreviewPaint,
CellShape, PickerField, PresetBrowser, PresetEvent, PresetFooterOptions, PresetPicker, PresetSource, PresetState, PresetView, PreviewPaint,
};
use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::{Env, Label, UnitKind};
@@ -30,7 +31,7 @@ use crate::ui::brush_settings::{BrushSizeField, TipAngle, TipEllipse};
const DEFAULT_MAX_DIAMETER: f64 = 5000.0;
/// The brush values the picker's head edits, given by the app each pass.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct BrushPickerValues {
/// The diameter in pixels: the Size field and its log slider.
@@ -103,21 +104,13 @@ pub enum GearSection {
End,
}
type GearRowsFn<'a> = Box<dyn FnMut(&mut Ui, GearSection) + 'a>;
/// The app's own rows of the gear menu: called once per [`GearSection`], after the picker's rows of that section.
pub struct GearRows<'a>(GearRowsFn<'a>);
impl<'a> GearRows<'a> {
/// The rows that `show` adds to each section.
pub fn new(show: impl FnMut(&mut Ui, GearSection) + 'a) -> Self {
GearRows(Box::new(show))
}
}
/// The app's own rows of the gear menu: called once per [`GearSection`], after the picker's rows of that section. A
/// `fn`, which captures nothing, so the picker's tools view keys it by its address.
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.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub struct BrushPickerState<K> {
/// The browser's view settings; its zoom is the thumbnail scale.
@@ -233,7 +226,8 @@ impl Opened {
/// brush live and report [`BrushPresetPickerOutput::tip`], [`diameter`](BrushPresetPickerOutput::diameter) and
/// [`hardness`](BrushPresetPickerOutput::hardness).
/// - **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.
/// 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.
/// - **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
@@ -251,10 +245,10 @@ impl Opened {
#[must_use = "show the picker with `show`"]
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
#[pattern(probe(BrushPresetPicker<'static, u32>))]
pub struct BrushPresetPicker<'a, K: Value + Eq + Hash> {
pub struct BrushPresetPicker<'a, K: Value + Eq + Hash + MemoProps> {
label: Label,
current: Bind<'a, Option<K>>,
rows: &'a [PresetRow<K>],
source: &'a PresetSource<'a, K>,
state: Bind<'a, BrushPickerState<K>>,
values: BrushPickerValues,
/// The largest diameter the app's engine paints; 5000 until set.
@@ -264,8 +258,8 @@ pub struct BrushPresetPicker<'a, K: Value + Eq + Hash> {
#[prop(flag)]
import: bool,
/// The app's rows of the gear menu, added to each section.
#[prop(func = "FnMut(&mut Ui, GearSection)")]
gear_rows: Option<GearRows<'a>>,
#[prop]
gear_rows: Option<GearRows>,
/// Edge grips resize the popover, and the size the user leaves it at is saved under this key.
#[prop]
resizable: Option<SaveKey>,
@@ -289,20 +283,20 @@ pub struct BrushPresetPicker<'a, K: Value + Eq + Hash> {
/// The app's own rows of the picker's gear menu.
type AppRows<'a> = Box<dyn FnOnce(&mut Ui) + 'a>;
impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
/// A picker named `label` over the presets in `rows` (build each with [`brush_row`](super::brush_row)), holding the
/// preset the brush was picked from in `current`, its view in `state` and the brush's `values`.
impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
/// A picker named `label` over the presets of `source` (build each row with [`brush_row`](super::brush_row)),
/// holding the preset the brush was picked from in `current`, its view in `state` and the brush's `values`.
pub fn new(
label: impl Into<Label>,
current: Bind<'a, Option<K>>,
rows: &'a [PresetRow<K>],
source: &'a PresetSource<'a, K>,
state: Bind<'a, BrushPickerState<K>>,
values: BrushPickerValues,
) -> Self {
Self {
label: label.into(),
current,
rows,
source,
state,
values,
max_diameter: DEFAULT_MAX_DIAMETER,
@@ -329,12 +323,12 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
let BrushPresetPicker {
label,
mut current,
rows,
source,
mut state,
values,
max_diameter,
import,
mut gear_rows,
gear_rows,
resizable,
mut opened_at,
compact,
@@ -355,116 +349,45 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
Some(Mixed::Same(held)) => held,
_ => None,
};
let has_current = held.as_ref().is_some_and(|key| rows.iter().any(|row| !row.is_group() && row.key == *key));
let has_current = held.as_ref().is_some_and(|key| source.rows(ui.ctx(), &env).iter().any(|row| !row.is_group() && row.key == *key));
let mut browser = before.browser.clone();
let next_parts = Cell::new(parts);
let next_search = Cell::new(before.search);
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 browser_id = ui.scope_id().with("browser");
let has_app_rows = gear_rows.is_some();
let head = |ui: &mut Ui, _: &mut BodyCx<'_>| {
Row::new().show(ui, |ui, _| {
tip = match values.tip {
Some(angle) => TipEllipse::new(words.tip.clone(), Bind::given(angle)).show(ui).events,
None => EditEvents::new(),
};
Stack::new().show(ui, |ui, _| {
let size = BrushSizeField::new(words.size.clone(), Bind::given(values.diameter), max_diameter).show(ui);
diameter = size.edit.events;
hardness = EditEvents::new();
if let Some(value) = values.hardness {
let field = SliderField::new(words.hardness.clone(), Bind::given(value * 100.0), 0.0..=100.0)
.step(1.0)
.unit_kind(UnitKind::Percent)
.show(ui);
hardness = field.edit.events.map(|percent| (percent / 100.0).clamp(0.0, 1.0));
}
});
});
Divider::horizontal().show(ui);
let mut sent = Vec::new();
let props = HeadProps { values, max_diameter, sent: Outbox::new(&mut sent) };
let _ = MemoView::new("head", props, head_view).show(ui);
for edits in sent {
(diameter, hardness, tip) = (edits.diameter, edits.hardness, edits.tip);
}
if let Some(rows) = app_rows.take() {
rows(ui);
}
};
// The buttons and the gear at the reading end of the browser's search row.
let tools = |ui: &mut Ui| {
let mut picks = tool_picks.borrow_mut();
picks.clear();
next_parts.set(parts);
next_search.set(before.search);
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);
if clicked(&settings) {
picks.push(BrushPick::OpenSettings);
}
let new_preset = IconButton::new(icon("plus")).label(words.new_preset.clone()).tooltip(words.new_preset.clone()).show(ui);
if clicked(&new_preset) {
picks.push(BrushPick::NewPreset);
}
let gear = IconButton::new(icon("settings")).label(words.options.clone()).tooltip(words.options.clone()).show(ui);
let _ = Menu::new(words.options.clone()).opened_by(&gear, Trigger::Click).show(ui, |ui, _| {
let mut app_rows = |ui: &mut Ui, section: GearSection| {
if let Some(rows) = gear_rows.as_mut() {
(rows.0)(ui, section);
}
};
if MenuItem::new(words.menu_new.clone()).show(ui).ran {
picks.push(BrushPick::NewPreset);
}
app_rows(ui, GearSection::Create);
Divider::horizontal().show(ui);
let on_current = |row: MenuItem<'static>| {
let row = row.enabled(has_current);
if has_current {
row
} else {
row.tooltip(TooltipSpec::new(words.no_current.clone()).disabled_text(words.no_current.clone()))
}
};
if on_current(MenuItem::new(words.menu_rename.clone())).show(ui).ran
&& let Some(key) = held.as_ref()
{
PresetBrowser::request_rename(ui.ctx(), browser_id, key);
}
if on_current(MenuItem::new(words.menu_delete.clone())).show(ui).ran
&& let Some(key) = held.clone()
{
picks.push(BrushPick::List(PresetEvent::Delete(key)));
}
app_rows(ui, GearSection::Preset);
Divider::horizontal().show(ui);
for (part, label) in [
(BrushCardPart::Name, &words.part_name),
(BrushCardPart::Stroke, &words.part_stroke),
(BrushCardPart::Tip, &words.part_tip),
] {
let on = next_parts.get().get(part);
if MenuItem::new(label.clone()).check(on).keep_open(true).show(ui).ran {
next_parts.set(next_parts.get().set(part, !on));
}
}
app_rows(ui, GearSection::Parts);
Divider::horizontal().show(ui);
let search = next_search.get();
if MenuItem::new(words.search_bar.clone()).check(search).keep_open(true).show(ui).ran {
next_search.set(!search);
}
app_rows(ui, GearSection::View);
Divider::horizontal().show(ui);
if import && MenuItem::new(words.menu_import.clone()).show(ui).ran {
picks.push(BrushPick::Import);
}
app_rows(ui, GearSection::Library);
if has_app_rows {
Divider::horizontal().show(ui);
app_rows(ui, GearSection::End);
}
});
});
let mut sent = Vec::new();
let props = ToolsProps {
has_current,
held: held.clone(),
parts,
search: before.search,
import,
browser_id,
gear_rows,
sent: Outbox::new(&mut sent),
};
let _ = MemoView::new("tools", props, tools_view::<K>).show(ui);
for run in sent {
*tool_picks.borrow_mut() = run.picks;
next_parts.set(run.parts);
next_search.set(run.search);
}
};
let mut picker = PresetPicker::new(words.picker.clone(), current.reborrowed(), rows, Bind::bound(&mut browser))
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())))
.caption_range((1.0..=max_diameter.round(), 0))
@@ -531,6 +454,141 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
}
}
/// Every input of the picker's head: the brush values it shows and the largest diameter, and an outbox for its edits.
#[derive(MemoProps)]
struct HeadProps<'a> {
values: BrushPickerValues,
max_diameter: f64,
sent: Outbox<'a, HeadEdits>,
}
/// What a run of the head reports: the Size, Hardness and angle widget edits.
struct HeadEdits {
diameter: EditEvents<f64>,
hardness: EditEvents<f64>,
tip: EditEvents<TipAngle>,
}
/// The head: the angle widget, Size and Hardness, then a divider. A memoized view, so a drag of its Size runs it
/// alone and the presets below replay.
fn head_view(props: &mut HeadProps<'_>, ui: &mut Ui) {
let words = Env::of(ui).words::<BrushPresetWords>();
let (values, max_diameter) = (props.values, props.max_diameter);
let mut edits = HeadEdits { diameter: EditEvents::new(), hardness: EditEvents::new(), tip: EditEvents::new() };
Row::new().show(ui, |ui, _| {
if let Some(angle) = values.tip {
edits.tip = TipEllipse::new(words.tip.clone(), Bind::given(angle)).show(ui).events;
}
Stack::new().show(ui, |ui, _| {
edits.diameter = BrushSizeField::new(words.size.clone(), Bind::given(values.diameter), max_diameter).show(ui).edit.events;
if let Some(value) = values.hardness {
let field =
SliderField::new(words.hardness.clone(), Bind::given(value * 100.0), 0.0..=100.0).step(1.0).unit_kind(UnitKind::Percent).show(ui);
edits.hardness = field.edit.events.map(|percent| (percent / 100.0).clamp(0.0, 1.0));
}
});
});
Divider::horizontal().show(ui);
props.sent.send(edits);
}
/// Every input of the search row's buttons and gear menu, and an outbox for what a run reports.
#[derive(MemoProps)]
struct ToolsProps<'a, K: 'static> {
has_current: bool,
held: Option<K>,
parts: BrushCardParts,
search: bool,
import: bool,
browser_id: egui::Id,
#[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")]
gear_rows: Option<GearRows>,
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.
struct ToolsRun<K> {
picks: Vec<BrushPick<K>>,
parts: BrushCardParts,
search: 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 held = held.clone();
let mut picks = Vec::new();
let next_parts = Cell::new(parts);
let next_search = Cell::new(search);
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);
if clicked(&settings) {
picks.push(BrushPick::OpenSettings);
}
let new_preset = IconButton::new(icon("plus")).label(words.new_preset.clone()).tooltip(words.new_preset.clone()).show(ui);
if clicked(&new_preset) {
picks.push(BrushPick::NewPreset);
}
let gear = IconButton::new(icon("settings")).label(words.options.clone()).tooltip(words.options.clone()).show(ui);
let _ = Menu::new(words.options.clone()).opened_by(&gear, Trigger::Click).show(ui, |ui, _| {
let app_rows = |ui: &mut Ui, section: GearSection| {
if let Some(rows) = gear_rows {
rows(ui, section);
}
};
if MenuItem::new(words.menu_new.clone()).show(ui).ran {
picks.push(BrushPick::NewPreset);
}
app_rows(ui, GearSection::Create);
Divider::horizontal().show(ui);
let on_current = |row: MenuItem<'static>| {
let row = row.enabled(has_current);
if has_current { row } else { row.tooltip(TooltipSpec::new(words.no_current.clone()).disabled_text(words.no_current.clone())) }
};
if on_current(MenuItem::new(words.menu_rename.clone())).show(ui).ran
&& let Some(key) = held.as_ref()
{
PresetBrowser::request_rename(ui.ctx(), browser_id, key);
}
if on_current(MenuItem::new(words.menu_delete.clone())).show(ui).ran
&& let Some(key) = held.clone()
{
picks.push(BrushPick::List(PresetEvent::Delete(key)));
}
app_rows(ui, GearSection::Preset);
Divider::horizontal().show(ui);
for (part, label) in
[(BrushCardPart::Name, &words.part_name), (BrushCardPart::Stroke, &words.part_stroke), (BrushCardPart::Tip, &words.part_tip)]
{
let on = next_parts.get().get(part);
if MenuItem::new(label.clone()).check(on).keep_open(true).show(ui).ran {
next_parts.set(next_parts.get().set(part, !on));
}
}
app_rows(ui, GearSection::Parts);
Divider::horizontal().show(ui);
let shown = next_search.get();
if MenuItem::new(words.search_bar.clone()).check(shown).keep_open(true).show(ui).ran {
next_search.set(!shown);
}
app_rows(ui, GearSection::View);
Divider::horizontal().show(ui);
if import && MenuItem::new(words.menu_import.clone()).show(ui).ran {
picks.push(BrushPick::Import);
}
app_rows(ui, GearSection::Library);
if gear_rows.is_some() {
Divider::horizontal().show(ui);
app_rows(ui, GearSection::End);
}
});
});
props.sent.send(ToolsRun { picks, parts: next_parts.get(), search: next_search.get() });
}
/// Keeps what Escape goes back to while the popover is open and returns the values Escape sets back, if any.
///
/// The pass the popover shows open first takes `values` as the opening values; the head's edits become the values
+2 -2
View File
@@ -23,7 +23,7 @@ pub enum BrushCardPart {
///
/// - The tip alone is the browser's grid of thumbnails with the size as each caption.
/// - The name or the stroke is the browser's list: the stroke as the row's picture while it is on, else the tip.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[serde(default)]
#[non_exhaustive]
pub struct BrushCardParts {
@@ -80,7 +80,7 @@ impl BrushCardParts {
/// 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.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui::contract::MemoProps)]
#[serde(default)]
#[non_exhaustive]
pub struct BrushPickerSettings {
+15 -18
View File
@@ -1,7 +1,7 @@
//! Stories of the Brush Preset picker.
use craft_behavior::Mixed;
use craft_ui::patterns::presets::PresetRow;
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource};
use craft_ui::runtime::env::Env;
use craft_ui::testing::pictures::{SampleTip, paint_tip, paint_wave};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
@@ -28,7 +28,8 @@ fn paint(tip: SampleTip) -> BrushRowPaint {
)
}
fn rows(env: &Env, parts: BrushCardParts) -> Vec<PresetRow<u32>> {
fn rows(parts: &BrushCardParts, env: &Env) -> Vec<PresetRow<u32>> {
let parts = *parts;
vec![
brush_row(SOFT, "Soft Round", 0, SOFT_SIZE, parts, env, &paint(SampleTip::Soft)),
brush_row(HARD, "Hard Round", 0, HARD_SIZE, parts, env, &paint(SampleTip::Hard)),
@@ -37,11 +38,10 @@ fn rows(env: &Env, parts: BrushCardParts) -> Vec<PresetRow<u32>> {
#[story(BrushPresetPicker<'static, u32>, covers = [Default], drive = Drive::Never)]
fn picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let env = Env::of(ui);
let ((current, state), brush_at) = data.value_at("brush", (Some(SOFT), BrushPickerState::<u32>::new()));
let rows = rows(&env, state.parts);
let source = PresetSource::new(state.parts, PresetFns::new(rows));
let values = BrushPickerValues::new(SOFT_SIZE, Some(0.8));
BrushPresetPicker::new("Brush Preset picker", brush_at.bind(current), &rows, brush_at.bind(state), values)
BrushPresetPicker::new("Brush Preset picker", brush_at.bind(current), &source, brush_at.bind(state), values)
.max_diameter(MAX_SIZE)
.import()
.show(ui)
@@ -52,12 +52,11 @@ fn picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
/// and Hardness in the head.
#[story(BrushPresetPicker<'static, u32>, covers = [Open], drive = Drive::Never)]
fn picker_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let env = Env::of(ui);
let at = ui.max_rect().min;
let ((current, state, open), open_at2) = data.value_at("open", (Some(SOFT), BrushPickerState::<u32>::new(), true));
let rows = rows(&env, state.parts);
let source = PresetSource::new(state.parts, PresetFns::new(rows));
let values = BrushPickerValues::new(SOFT_SIZE, Some(0.8)).with_tip(TipAngle::new(30.0, 0.6));
BrushPresetPicker::new("Brush Preset picker", open_at2.bind(current), &rows, open_at2.bind(state), values)
BrushPresetPicker::new("Brush Preset picker", open_at2.bind(current), &source, open_at2.bind(state), values)
.max_diameter(MAX_SIZE)
.import()
.open_at(at, open_at2.bind(open))
@@ -67,27 +66,24 @@ fn picker_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
#[story(BrushesPanel<'static, u32>, covers = [Default], drive = Drive::Never)]
fn panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let env = Env::of(ui);
let ((state, diameter), panel_at) = data.value_at("panel", (PresetState::<u32>::new(), SOFT_SIZE));
let rows = rows(&env, BrushCardParts::ALL);
BrushesPanel::new("Brushes", &rows, panel_at.bind(state), panel_at.bind(diameter), MAX_SIZE).selected(SOFT).import(true).show(ui).into()
let source = PresetSource::new(BrushCardParts::ALL, PresetFns::new(rows));
BrushesPanel::new("Brushes", &source, panel_at.bind(state), panel_at.bind(diameter), MAX_SIZE).selected(SOFT).import(true).show(ui).into()
}
#[story(BrushPresetPicker<'static, u32>, covers = [Mixed], drive = Drive::Never)]
fn picker_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let env = Env::of(ui);
let ((current, state), mixed_at) = data.value_at("mixed", (Mixed::<Option<u32>>::Mixed, BrushPickerState::<u32>::new()));
let rows = rows(&env, state.parts);
let source = PresetSource::new(state.parts, PresetFns::new(rows));
let values = BrushPickerValues::new(HARD_SIZE, None);
BrushPresetPicker::new("Brush Preset picker", mixed_at.bind_mixed(current), &rows, mixed_at.bind(state), values).show(ui).into()
BrushPresetPicker::new("Brush Preset picker", mixed_at.bind_mixed(current), &source, mixed_at.bind(state), values).show(ui).into()
}
#[story(BrushPresetPicker<'static, u32>, covers = [], drive = Drive::Never)]
fn picker_sampled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let env = Env::of(ui);
let ((current, state), sampled_at) = data.value_at("sampled", (Some(HARD), BrushPickerState::<u32>::new()));
let rows = rows(&env, state.parts);
BrushPresetPicker::new("Brush Preset picker", sampled_at.bind(current), &rows, sampled_at.bind(state), BrushPickerValues::new(HARD_SIZE, None))
let source = PresetSource::new(state.parts, PresetFns::new(rows));
BrushPresetPicker::new("Brush Preset picker", sampled_at.bind(current), &source, sampled_at.bind(state), BrushPickerValues::new(HARD_SIZE, None))
.show(ui)
.into()
}
@@ -95,7 +91,8 @@ fn picker_sampled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
#[story(BrushPresetPicker<'static, u32>, covers = [], drive = Drive::Never)]
fn picker_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let ((current, state), empty_at) = data.value_at("empty", (None::<u32>, BrushPickerState::<u32>::new()));
BrushPresetPicker::new("Brush Preset picker", empty_at.bind(current), &[], empty_at.bind(state), BrushPickerValues::new(SOFT_SIZE, Some(1.0)))
let source = PresetSource::new((), PresetFns::new(|_, _| Vec::new()));
BrushPresetPicker::new("Brush Preset picker", empty_at.bind(current), &source, empty_at.bind(state), BrushPickerValues::new(SOFT_SIZE, Some(1.0)))
.show(ui)
.into()
}
+3 -3
View File
@@ -34,7 +34,7 @@ const ROUND_STEP: f64 = 0.01;
const ROUND_MIN: f64 = 0.01;
/// A tip's angle and roundness.
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct TipAngle {
/// The major axis's angle in whole degrees, counter-clockwise from the right, −180 to 180.
@@ -235,12 +235,12 @@ impl Component for TipEllipse<'_> {
let value = cx.value().copied().unwrap_or_default();
let dots = ellipse_handles(value, radius);
cx.part(ARROW, HitShape::circle(center, disc))
.sense(Sense::CLICK | Sense::DRAG)
.sense(Sense::CLICK | Sense::DRAG | Sense::TAKE_FOCUS)
.value_part()
.pointer_only("the arrow keys turn the angle, Alt with them squashes the ellipse");
for (at, dot) in dots.into_iter().enumerate() {
cx.part(DOT.at(at as u64), HitShape::circle(center + dot, reach))
.sense(Sense::CLICK | Sense::DRAG)
.sense(Sense::CLICK | Sense::DRAG | Sense::TAKE_FOCUS)
.priority(HitPriority::new(HitLevel::Handle, 0))
.value_part()
.pointer_only("Alt with the arrow keys squashes the ellipse");
+1 -1
View File
@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
use super::fill_editor::GradientFillWords;
/// How a gradient runs from its line.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub enum GradientStyle {
/// Along the line.
+19 -14
View File
@@ -14,7 +14,7 @@ use craft_ui::contract::{Bind, Pattern, Props as _, Remember as _, Show as _, Sh
use craft_ui::display::{Shade, Text};
use craft_ui::form::Field;
use craft_ui::layout_components::Stack;
use craft_ui::patterns::presets::{PickerField, PresetPicker, PresetRow};
use craft_ui::patterns::presets::{PickerField, PresetFns, PresetPicker, PresetRow, PresetSource};
use craft_ui::runtime::env::{Env, Label};
use craft_ui::style::TypeRole;
use egui::{Response, Ui};
@@ -136,26 +136,18 @@ impl<'a> GradientMapEditor<'a> {
(words.preset.clone(), words.custom.clone(), words.import_presets.clone(), words.stops.clone());
let (reverse_label, dither_label) = (words.reverse.clone(), words.dither.clone());
let shown = Stack::new().label(self.label.clone()).show(ui, |ui, cx| {
let rows: Vec<PresetRow<GradientRef>> = self
.presets
.iter()
.enumerate()
.flat_map(|(group, g)| {
let header = PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0);
let items =
g.items.iter().enumerate().map(move |(item, p)| PresetRow::item(GradientRef::Item { group, item }, p.name.clone(), 1));
std::iter::once(header).chain(items)
})
.collect();
let source = PresetSource::new(self.presets, PresetFns::new(preset_rows));
// Stop tags identify host data, so they do not determine which preset's colours match.
let matches = |&key: &GradientRef| {
self.preset_colors(key).is_some_and(|colors| colors.map(|s| s.with_tag(0)).eq(base.stops.color.iter().map(|s| s.with_tag(0))))
};
let preferred = cx.keep::<PickedPreset>().0.filter(matches);
let current = preferred.or_else(|| rows.iter().map(|row| row.key).find(matches));
let mut items =
self.presets.iter().enumerate().flat_map(|(group, g)| (0..g.items.len()).map(move |item| GradientRef::Item { group, item }));
let current = preferred.or_else(|| items.find(matches));
let picked = Field::new(preset_label.clone())
.show(ui, |ui, _| {
PresetPicker::new(preset_label.clone(), Bind::given(current), &rows, Bind::kept())
PresetPicker::new(preset_label.clone(), Bind::given(current), &source, Bind::kept())
.field(PickerField::Name)
.placeholder(custom.clone())
.show(ui)
@@ -200,3 +192,16 @@ impl<'a> GradientMapEditor<'a> {
GradientMapOutput { response: shown.output, event, color_requested, import }
}
}
/// The picker's rows: each group's header, then its presets. A header's key names no preset (`item == usize::MAX`).
fn preset_rows(presets: &&[GradientGroup], _: &Env) -> Vec<PresetRow<GradientRef>> {
presets
.iter()
.enumerate()
.flat_map(|(group, g)| {
let header = PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0);
let items = g.items.iter().enumerate().map(move |(item, p)| PresetRow::item(GradientRef::Item { group, item }, p.name.clone(), 1));
std::iter::once(header).chain(items)
})
.collect()
}
+1 -1
View File
@@ -21,6 +21,6 @@ pub use fill_editor::{GradientFillEditor, GradientFillEditorOutput, GradientFill
pub use gradient_line::{GradientLine, LineGradient, LinePart};
pub use gradient_overlay::{GradientLineWords, GradientOverlay, GradientOverlayOutput, GradientOverlayStyle};
pub use map::{GradientMap, GradientMapEditor, GradientMapOutput};
pub use palette::{GradientGroup, GradientItem, GradientPalette, GradientPaletteOutput, GradientRef};
pub use palette::{GradientGroup, GradientItem, GradientPalette, GradientPaletteOutput, GradientRef, RampSampler};
pub use swatch::{GradientSwatch, GradientSwatchOutput};
pub use tile::{FocusOutline, GradientTile};
+71 -48
View File
@@ -2,10 +2,12 @@
//! family's [`PresetBrowser`]: the browser owns the grid, the list, the roving focus, the keys and the accessible tree;
//! the palette supplies the rows and paints each preset's thumbnail as a gradient ramp.
use craft_theme::Srgba;
use craft_ui::contract::{Bind, NoValue, Outcome, Pattern};
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetEvent, PresetRow, PresetState, PresetTiles};
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetEvent, PresetFns, PresetRow, PresetSource, PresetState, PresetTiles, ThumbInfo};
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::env::{Env, Label};
use egui::{Response, Ui};
use egui::{Rect, Response, Ui};
#[cfg(feature = "suite")]
pub(crate) mod stories;
@@ -18,7 +20,7 @@ use super::GradientTile;
const MAX_ROWS: f32 = 6.0;
/// A named group of gradient presets.
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct GradientGroup {
/// The group's heading.
@@ -35,7 +37,7 @@ impl GradientGroup {
}
/// A named gradient preset.
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct GradientItem {
/// The preset's name.
@@ -62,7 +64,7 @@ impl GradientItem {
/// The preset a pick names: a recent gradient by its place in the list the host passed, or an
/// item of a group.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub enum GradientRef {
/// Place in the Recent list.
@@ -163,9 +165,10 @@ pub struct GradientPalette<'a> {
/// The row layout the ramps are sampled with.
#[prop]
rows: StopRows,
/// Samples a ramp; the default sampler of the rows by default.
/// Samples a ramp; the default sampler of the rows by default. A `fn`, which captures nothing, so the palette's
/// presets key it by its address.
#[prop]
sampler: Option<&'a Sampler>,
sampler: Option<RampSampler>,
/// The selected preset.
#[prop]
selected: Option<GradientRef>,
@@ -186,55 +189,17 @@ impl<'a> GradientPalette<'a> {
}
}
/// The rows of the groups: the header of each group, then its presets. A header's key names no preset
/// (`item == usize::MAX`).
fn preset_rows(&self) -> Vec<PresetRow<GradientRef>> {
let mut rows = Vec::new();
if !self.recent.is_empty() {
rows.push(PresetRow::group(GradientRef::Recent(usize::MAX), self.recent_label.clone(), 0));
for i in 0..self.recent.len() {
rows.push(PresetRow::item(GradientRef::Recent(i), format!("{} {}", self.recent_label, i + 1), 1));
}
}
for (group, g) in self.groups.iter().enumerate() {
rows.push(PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0));
for (item, preset) in g.items.iter().enumerate() {
rows.push(PresetRow::item(GradientRef::Item { group, item }, preset.name.clone(), 1));
}
}
rows
}
/// Shows the palette across the available width.
pub fn show(self, ui: &mut Ui) -> GradientPaletteOutput {
let rows = self.preset_rows();
let default = default_sampler(self.rows);
let sampler: &Sampler = self.sampler.unwrap_or(&default);
let (groups, recent) = (self.groups, self.recent);
let (wide, high) = GradientRamp::CHIP_ASPECT;
// The browser has one cell shape for the grid and the list, so any tile makes every cell square.
let square = groups.iter().flat_map(|g| &g.items).any(|item| item.tile != GradientTile::Ramp);
let thumb =
move |cx: &craft_ui::primitives::ContentPainterCx, rect: egui::Rect, info: craft_ui::patterns::presets::ThumbInfo<'_, GradientRef>| {
if let Some(stops) = stops_of(groups, recent, *info.key) {
let (radius, edge) = GradientRamp::chip_look(&cx.style_cx());
let tile = item_of(groups, *info.key).map_or(GradientTile::Ramp, |item| item.tile);
if tile != GradientTile::Ramp {
tile.paint(cx, rect, radius, stops, sampler, edge);
return;
}
let chip = if square {
egui::Rect::from_center_size(rect.center(), egui::vec2(rect.width(), rect.width() * f32::from(high) / f32::from(wide)))
} else {
rect
};
GradientRamp::paint_chip(cx, chip, radius, &GradientRamp::colors(stops, sampler), edge);
}
};
let inputs = PaletteInputs { groups, recent, recent_label: self.recent_label, rows: self.rows, sampler: self.sampler, square };
let source = PresetSource::new(inputs, PresetFns::new(preset_rows).thumb(paint_thumb));
let most = Env::of(ui).tokens.size.control.sm * MAX_ROWS;
let shape = if square { CellShape::Square } else { CellShape::ratio(wide, high) };
let mut browser =
PresetBrowser::new(self.label, self.state, &rows).cell_shape(shape).tiles(PresetTiles::Chips).room_height(most).thumb(thumb);
let mut browser = PresetBrowser::new(self.label, self.state, &source).cell_shape(shape).tiles(PresetTiles::Chips).room_height(most);
if let Some(selected) = self.selected {
browser = browser.selected(selected);
}
@@ -251,6 +216,64 @@ impl<'a> GradientPalette<'a> {
}
}
/// Samples a gradient's ramp at a location 0..=1.
pub type RampSampler = fn(&GradientStops, f32) -> Srgba;
/// What the palette's presets are built from.
#[derive(craft_ui::contract::MemoProps)]
struct PaletteInputs<'a> {
groups: &'a [GradientGroup],
recent: &'a [GradientStops],
recent_label: String,
rows: StopRows,
#[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")]
sampler: Option<RampSampler>,
/// Whether every cell is square: some preset has a tile other than the ramp.
square: bool,
}
/// The rows of the groups: the header of each group, then its presets. A header's key names no preset
/// (`item == usize::MAX`).
fn preset_rows(inputs: &PaletteInputs<'_>, _: &Env) -> Vec<PresetRow<GradientRef>> {
let mut rows = Vec::new();
if !inputs.recent.is_empty() {
rows.push(PresetRow::group(GradientRef::Recent(usize::MAX), inputs.recent_label.clone(), 0));
for i in 0..inputs.recent.len() {
rows.push(PresetRow::item(GradientRef::Recent(i), format!("{} {}", inputs.recent_label, i + 1), 1));
}
}
for (group, g) in inputs.groups.iter().enumerate() {
rows.push(PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0));
for (item, preset) in g.items.iter().enumerate() {
rows.push(PresetRow::item(GradientRef::Item { group, item }, preset.name.clone(), 1));
}
}
rows
}
/// Paints a preset's thumbnail: its tile, or its ramp chip, which keeps the chip's aspect in a square cell.
fn paint_thumb(inputs: &PaletteInputs<'_>, cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, GradientRef>) {
let Some(stops) = stops_of(inputs.groups, inputs.recent, *info.key) else { return };
let (radius, edge) = GradientRamp::chip_look(&cx.style_cx());
let default = default_sampler(inputs.rows);
let sampler: &Sampler = match &inputs.sampler {
Some(sampler) => sampler,
None => &default,
};
let tile = item_of(inputs.groups, *info.key).map_or(GradientTile::Ramp, |item| item.tile);
if tile != GradientTile::Ramp {
tile.paint(cx, rect, radius, stops, sampler, edge);
return;
}
let (wide, high) = GradientRamp::CHIP_ASPECT;
let chip = if inputs.square {
Rect::from_center_size(rect.center(), egui::vec2(rect.width(), rect.width() * f32::from(high) / f32::from(wide)))
} else {
rect
};
GradientRamp::paint_chip(cx, chip, radius, &GradientRamp::colors(stops, sampler), edge);
}
/// The stops of the preset `key` names; none for a group header.
pub(super) fn stops_of<'a>(groups: &'a [GradientGroup], recent: &'a [GradientStops], key: GradientRef) -> Option<&'a GradientStops> {
match key {
+2 -2
View File
@@ -18,7 +18,7 @@ const TILE_STEPS: usize = 17;
///
/// A tile other than [`Ramp`](GradientTile::Ramp) is one `craft_color_ui::ui::smooth_mesh` sampled through
/// [`t_at`](GradientTile::t_at). `p` below is a point in the tile's unit square (0 to 1, y down) and `c` its centre.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub enum GradientTile {
/// The ramp chip: the gradient along its length.
@@ -56,7 +56,7 @@ impl GradientTile {
}
/// The outline a [`GradientTile::Focus`] gradient follows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub enum FocusOutline {
/// A circle.
+2 -4
View File
@@ -79,7 +79,7 @@ pub use crop::{
pub use crop::{PerspectiveCropQuad, PerspectiveQuad};
pub use gradient::{
FocusOutline, GradientGroup, GradientItem, GradientLine, GradientMap, GradientMapEditor, GradientMapOutput, GradientOverlay, GradientPalette,
GradientRef, GradientSwatch, GradientTile, LineGradient, LinePart,
GradientRef, GradientSwatch, GradientTile, LineGradient, LinePart, RampSampler,
};
pub use gradient::{GradientFill, GradientFillEditor, GradientFillEditorOutput, GradientFillWords, GradientStyle};
pub use measure::{
@@ -89,9 +89,7 @@ pub use paint_bar::{
EraserMode, MIXER_COMBINATIONS, MIXER_GROUP_STARTS, MixerValues, PaintBar, PaintBarOutput, PaintBarWords, PaintTool, PaintValues, Smoothing,
};
pub use paths::{PathKind, PathRow, PathsCommands, PathsEvent, PathsFooterButton, PathsOutput, PathsPanel, PathsWords};
pub use pattern::{
PatternColors, PatternFillDialog, PatternFillEditor, PatternFillOptions, PatternFillOutput, PatternSwatch, PatternWords, SwatchPainter,
};
pub use pattern::{PatternColors, PatternFillDialog, PatternFillEditor, PatternFillOptions, PatternFillOutput, PatternSwatch, PatternWords};
pub use pen::{AnchorDelete, AnchorTool, PenEnd};
pub use pen::{AnchorsShown, HitMark, PATH_OPTIONS_COLOR_KEY, PathMode, PathOptionsPopover, PathOptionsSettings, PathTool, PenMode, SegmentMark};
pub use pen::{
+6 -12
View File
@@ -30,7 +30,7 @@ pub use words::PaintBarWords;
const PRESSURE: &str = "target";
/// The painting tools the bar serves.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub enum PaintTool {
/// The Brush tool.
@@ -43,14 +43,10 @@ pub enum PaintTool {
MixerBrush,
}
/// The bar's values.
#[derive(Clone, Debug, PartialEq)]
/// The bar's values. The size and the hardness are the preset picker's, which comes before the bar.
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct PaintValues<M> {
/// The brush size.
pub size: f64,
/// The brush hardness.
pub hardness: f64,
/// The opacity.
pub opacity: f64,
/// The flow.
@@ -78,8 +74,6 @@ impl<M> PaintValues<M> {
/// options overwrites every field.
pub fn new(mode: M) -> Self {
PaintValues {
size: 30.0,
hardness: 0.5,
opacity: 1.0,
flow: 1.0,
smoothing: Smoothing::default(),
@@ -95,7 +89,7 @@ impl<M> PaintValues<M> {
}
/// The stroke smoothing options.
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct Smoothing {
/// The amount, 0 to 1.
@@ -118,7 +112,7 @@ impl Default for Smoothing {
}
/// The Mixer Brush's values.
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct MixerValues {
/// Load the brush after each stroke.
@@ -162,7 +156,7 @@ impl Default for MixerValues {
}
/// What the Eraser tool erases with.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub enum EraserMode {
/// A brush.
+4 -18
View File
@@ -1,15 +1,14 @@
//! [`PatternFillDialog`].
use super::editor::{ANGLE_RANGE, SwatchPainter};
use super::editor::ANGLE_RANGE;
use super::{PatternColors, PatternFillEditor, PatternFillOptions, PatternSwatch, PatternWords};
use craft_theme::Srgba;
use craft_ui::contract::{Bind, CanvasGesture, Sampler as _, ShowContainer as _};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft_ui::layout_components::Stack;
use craft_ui::patterns::form_dialogs::FormDialog;
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::env::Env;
use egui::{Rect, Ui};
use egui::Ui;
use serde_json::{Value, json};
/// Photoshop's Pattern Fill dialog (Layer, New Fill Layer, Pattern...; a Pattern Fill layer's thumbnail; Layer Content
@@ -25,7 +24,6 @@ pub struct PatternFillDialog {
initial: PatternFillOptions,
current: PatternFillOptions,
swatches: Vec<PatternSwatch>,
thumbnails: Option<SwatchPainter>,
changed: bool,
canvas: Option<egui::Id>,
/// Whether the dialog is open: bound to the form's open state, so the host's dialog closes with it.
@@ -40,20 +38,12 @@ impl PatternFillDialog {
initial: options.clone(),
current: options,
swatches,
thumbnails: None,
changed: false,
canvas: None,
open: true,
}
}
/// Paints a swatch's tile (see [`PatternFillEditor::thumbnails`]).
#[must_use]
pub fn thumbnails(mut self, paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self {
self.thumbnails = Some(SwatchPainter::new(paint));
self
}
/// The canvas whose primary drag moves the pattern while Link with Layer is on: the body passes
/// that gesture to it each pass.
#[must_use]
@@ -148,7 +138,7 @@ impl StackDialog for PatternFillDialog {
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<PatternFillOptions>> {
let words = Env::of(ui).words::<PatternWords>();
let PatternFillDialog { current, swatches, thumbnails, changed, canvas, open, .. } = self;
let PatternFillDialog { current, swatches, changed, canvas, open, .. } = self;
let before = current.clone();
let form = FormDialog::new(words.title.clone(), Bind::bound(&mut *current)).opened(Bind::bound(open));
let shown = form.show(ui, |ui, _, value| {
@@ -159,11 +149,7 @@ impl StackDialog for PatternFillDialog {
if let (Some(canvas), true) = (*canvas, link) {
cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY);
}
let mut editor = PatternFillEditor::new(words.pattern.clone(), Bind::bound(&mut *value), swatches);
if let Some(painter) = thumbnails.clone() {
editor = editor.thumbnails(move |cx, rect, swatch| painter.paint(cx, rect, swatch));
}
editor.show(ui);
PatternFillEditor::new(words.pattern.clone(), Bind::bound(&mut *value), swatches).show(ui);
});
true
});
+23 -48
View File
@@ -11,7 +11,7 @@ use craft_ui::contract::{Bind, FieldLayout, Outcome, Props as _, Remember as _,
use craft_ui::display::{Shade, Text};
use craft_ui::form::{Field, FieldGroup};
use craft_ui::layout_components::Row;
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetPicker, PresetRow, PresetState, PresetView, ThumbInfo};
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetFns, PresetPicker, PresetRow, PresetSource, PresetState, PresetView};
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::env::{Env, Label, UnitKind};
use craft_ui::text::NumberField;
@@ -21,22 +21,6 @@ use egui::{Rect, Response, Ui};
/// The angle of the dial runs over half a turn each way.
pub(super) const ANGLE_RANGE: std::ops::RangeInclusive<f64> = -180.0..=180.0;
type SwatchPaintFn = Arc<dyn Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync>;
/// The host's painter of a swatch's tile, shared with the preset rows that paint it.
#[derive(Clone)]
pub struct SwatchPainter(SwatchPaintFn);
impl SwatchPainter {
pub(super) fn new(paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self {
SwatchPainter(Arc::new(paint))
}
pub(super) fn paint(&self, cx: &ContentPainterCx<'_>, rect: Rect, swatch: &PatternSwatch) {
(self.0)(cx, rect, swatch);
}
}
/// What [`PatternFillEditor`] reports.
#[derive(Debug)]
#[non_exhaustive]
@@ -67,7 +51,7 @@ impl Outcome for PatternFillOutput {
/// Preset mode (`colors` set, PowerPoint's Pattern fill): a grid of the swatches, then Foreground and Background
/// colour chips.
///
/// The tiles come from [`thumbnails`](Self::thumbnails); without it a tile shows the swatch's name. Keyboard: Tab
/// A tile shows its swatch's [`picture`](PatternSwatch::picture); without one, the swatch's name. Keyboard: Tab
/// through the fields; the grid takes arrows. Right to left the rows mirror. The editor is the body a host passes to
/// a paint chip's pattern editor.
#[must_use = "show the editor with `show`"]
@@ -76,29 +60,22 @@ pub struct PatternFillEditor<'a> {
label: Label,
options: Bind<'a, PatternFillOptions>,
swatches: &'a [PatternSwatch],
thumbnails: Option<SwatchPainter>,
}
impl<'a> PatternFillEditor<'a> {
/// The editor named `label` over `options`, offering `swatches`.
pub fn new(label: impl Into<Label>, options: Bind<'a, PatternFillOptions>, swatches: &'a [PatternSwatch]) -> Self {
PatternFillEditor { label: label.into(), options, swatches, thumbnails: None }
}
/// Paints a swatch's tile into a rect (the picker's field and cells, the preset grid).
pub fn thumbnails(mut self, paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self {
self.thumbnails = Some(SwatchPainter::new(paint));
self
PatternFillEditor { label: label.into(), options, swatches }
}
/// Draws the editor and reports the edit.
pub fn show(self, ui: &mut Ui) -> PatternFillOutput {
let PatternFillEditor { label, mut options, swatches, thumbnails } = self;
let PatternFillEditor { label, mut options, swatches } = self;
let env = Env::of(ui);
let words = env.words::<PatternWords>();
let units = env.units();
let name: Arc<str> = label.as_str().into();
let rows: Vec<PresetRow<String>> = swatches.iter().map(|swatch| tile_row(swatch, thumbnails.as_ref())).collect();
let rows = PresetSource::new(swatches, PresetFns::new(tile_rows));
let mut events = EditEvents::new();
let shown = FieldGroup::new(label).show(ui, |ui, cx| {
events = EditEvents::new();
@@ -108,20 +85,13 @@ impl<'a> PatternFillEditor<'a> {
let mut take = |edits: EditEvents<PatternFillOptions>| next.extend(edits);
if let Some(colors) = current.colors {
let browser = Field::new(words.pattern.clone()).id_salt("grid").show(ui, |ui, _| {
let thumbs = thumbnails.clone();
let mut browser = PresetBrowser::new(words.pattern.clone(), Bind::bound(&mut state), &rows)
PresetBrowser::new(words.pattern.clone(), Bind::bound(&mut state), &rows)
.selected(current.pattern.clone())
.cell_shape(CellShape::Square)
.view_lock(PresetView::Grid)
.row_menu(false);
if let Some(thumbs) = thumbs {
browser = browser.thumb(move |cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, String>| {
if let Some(swatch) = swatches.iter().find(|swatch| swatch.id == *info.key) {
thumbs.paint(cx, rect, swatch);
}
});
}
browser.show(ui).events
.row_menu(false)
.show(ui)
.events
});
for picked in browser.inner.into_iter().flatten().filter_map(selected_key) {
if picked != current.pattern {
@@ -206,16 +176,21 @@ impl<'a> PatternFillEditor<'a> {
/// The most decimals the Scale field shows.
const SCALE_DECIMALS: usize = 2;
/// The preset row of `swatch`: its name, with the tile painter when the host gave one.
fn tile_row(swatch: &PatternSwatch, thumbnails: Option<&SwatchPainter>) -> PresetRow<String> {
let row = PresetRow::item(swatch.id.clone(), swatch.name.clone(), 0);
match thumbnails {
Some(painter) => {
let (painter, swatch) = (painter.clone(), swatch.clone());
row.preview(CellShape::Square.aspect(), move |cx, rect| painter.paint(cx, rect, &swatch))
/// The preset row of each swatch: its name, with the tile painter when the host gave one.
fn tile_rows(swatches: &&[PatternSwatch], _: &Env) -> Vec<PresetRow<String>> {
let tile_row = |swatch: &PatternSwatch| {
let row = PresetRow::item(swatch.id.clone(), swatch.name.clone(), 0);
match swatch.picture {
Some(picture) => row.preview(CellShape::Square.aspect(), move |cx, rect| paint_picture(cx, rect, picture)),
None => row,
}
None => row,
}
};
swatches.iter().map(tile_row).collect()
}
/// Paints the whole of a swatch's `picture` into `rect`.
fn paint_picture(cx: &ContentPainterCx<'_>, rect: Rect, picture: egui::TextureId) {
cx.picture(picture, rect, Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), 0.0);
}
/// The key a browser event picked: a click or Enter on a tile.
+15 -5
View File
@@ -11,25 +11,35 @@ pub(crate) mod stories;
mod words;
pub use dialog::PatternFillDialog;
pub use editor::{PatternFillEditor, PatternFillOutput, SwatchPainter};
pub use editor::{PatternFillEditor, PatternFillOutput};
pub use words::PatternWords;
/// A pattern the editor offers: the app's pattern library (PhotoCraft's Patterns, a bitmap each)
/// or its preset patterns (PowerPoint's "pct25", "dkHorz", …). The app paints each swatch's tile
/// ([`PatternFillEditor::thumbnails`]).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
/// or its preset patterns (PowerPoint's "pct25", "dkHorz", …), with the app's picture of its tile
/// ([`picture`](Self::picture)); a swatch without one shows its name.
#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct PatternSwatch {
/// The app's id, which [`PatternFillOptions::pattern`] holds.
pub id: String,
/// The name in the tooltip and for a screen reader ("Bubbles", "25 %").
pub name: String,
/// The tile's picture, a texture the app made: the picker's field and cells and the preset grid show it.
#[memo_props(hash = "a texture handle: the texture store keeps one picture under it")]
pub picture: Option<egui::TextureId>,
}
impl PatternSwatch {
/// A swatch of the app's pattern `id`, named `name`.
pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
PatternSwatch { id: id.into(), name: name.into() }
PatternSwatch { id: id.into(), name: name.into(), picture: None }
}
/// This swatch with its tile's `picture`.
#[must_use]
pub fn with_picture(mut self, picture: egui::TextureId) -> Self {
self.picture = Some(picture);
self
}
}
+18 -15
View File
@@ -1,46 +1,49 @@
//! Stories of the pattern fill editor: the bitmap mode, the two-colour preset mode and the editor in Photoshop's
//! dialog. The tiles are painted from the theme's colours by a closure, as a host paints its patterns.
//! dialog. Each tile shows a texture the story makes, as a host hands in its patterns' pictures.
use super::{PatternColors, PatternFillEditor, PatternFillOptions, PatternSwatch};
use craft_theme::Srgba;
use craft_ui::contract::Bind;
use craft_ui::patterns::form_dialogs::FormDialog;
use craft_ui::primitives::ContentPainterCx;
use craft_ui::primitives::textures::TextureCache;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::{Rect, Ui};
use egui::{Color32, ColorImage, Ui};
fn swatches() -> Vec<PatternSwatch> {
["Stripes", "Checks", "Dots", "Grid", "Waves", "Bubbles"].iter().map(|name| PatternSwatch::new(name.to_lowercase(), *name)).collect()
}
/// A tile: a plain fill over the whole rect, the stand-in for the host's pattern bitmap.
fn tile(cx: &ContentPainterCx<'_>, rect: Rect, _: &PatternSwatch) {
cx.checker(rect);
/// The library, each tile a checker texture: the stand-in for the host's pattern bitmaps.
fn swatches(ctx: &egui::Context) -> Vec<PatternSwatch> {
let picture = TextureCache::texture(ctx, "pattern-story-tile", || {
let (light, dark) = (Color32::from_gray(225), Color32::from_gray(150));
ColorImage::new([8, 8], (0..64).map(|at| if (at % 8 < 4) == (at / 8 < 4) { light } else { dark }).collect())
});
["Stripes", "Checks", "Dots", "Grid", "Waves", "Bubbles"]
.iter()
.map(|name| PatternSwatch::new(name.to_lowercase(), *name).with_picture(picture))
.collect()
}
fn editor(ui: &mut Ui, data: &mut StoryData, start: PatternFillOptions, library: &[PatternSwatch]) -> StoryOutput {
let (options, options_at) = data.value_at("options", start);
let out = PatternFillEditor::new("Pattern fill", options_at.bind(options), library).thumbnails(tile).show(ui);
let out = PatternFillEditor::new("Pattern fill", options_at.bind(options), library).show(ui);
StoryOutput::from(out)
}
#[story(PatternFillEditor<'static>, covers = [Default], drive = Drive::Never)]
fn pattern_fill_bitmap(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
editor(ui, data, PatternFillOptions::bitmap("bubbles"), &swatches())
editor(ui, data, PatternFillOptions::bitmap("bubbles"), &swatches(ui.ctx()))
}
#[story(PatternFillEditor<'static>, covers = [Default], drive = Drive::Never)]
fn pattern_fill_preset(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let colors = PatternColors::new(Srgba::rgb(0.1, 0.1, 0.1), Srgba::rgb(0.95, 0.95, 0.9));
editor(ui, data, PatternFillOptions::preset("checks", colors), &swatches())
editor(ui, data, PatternFillOptions::preset("checks", colors), &swatches(ui.ctx()))
}
#[story(PatternFillEditor<'static>, covers = [Default], drive = Drive::Never)]
fn pattern_fill_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let library = swatches();
let library = swatches(ui.ctx());
let ((options, options_at), (open, open_at)) = data.pair_at(("options", PatternFillOptions::bitmap("bubbles")), ("open", true));
FormDialog::new("Pattern Fill", options_at.bind(options)).opened(open_at.bind(open)).show(ui, |ui, _, value| {
PatternFillEditor::new("Pattern fill", Bind::bound(value), &library).thumbnails(tile).show(ui);
PatternFillEditor::new("Pattern fill", Bind::bound(value), &library).show(ui);
true
});
StoryOutput::default()
+2 -2
View File
@@ -28,7 +28,7 @@ craft_ui::words! {
}
/// The symmetry in force, as the menu marks it.
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub enum SymmetryChoice {
/// No symmetry.
@@ -40,7 +40,7 @@ pub enum SymmetryChoice {
}
/// A path the symmetry can come from (the saved paths, the Work Path, the layer's path), in the app's order.
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct SymmetryPathRow {
/// The app's key ("work", "layer", or the saved path's name).
+1 -1
View File
@@ -9,7 +9,7 @@ pub const TURN_STEP_DEGREES: f64 = 15.0;
/// The straight symmetry modes PhotoCraft has (lead call 23). Photoshop's Wavy, Circle, Spiral,
/// Parallel Lines, Radial and Mandala modes need engine work and are not built.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum SymmetryMode {
+15
View File
@@ -205,6 +205,8 @@ pub struct TransformSession<W = ()> {
nudge_pause: Option<f64>,
/// When the latest arrow nudge was applied (the `now` of [`apply`](Self::apply)).
last_nudge: Option<f64>,
/// See [`revision`](Self::revision).
revision: u64,
}
impl<W: TransformWarp> TransformSession<W> {
@@ -230,6 +232,7 @@ impl<W: TransformWarp> TransformSession<W> {
reference_point: false,
nudge_pause: None,
last_nudge: None,
revision: 0,
}
}
@@ -424,6 +427,7 @@ impl<W: TransformWarp> TransformSession<W> {
}
}
TransformEdit::Warp(warp) => {
self.revision += u64::from(self.draft.warp.is_none());
if self.draft.warp.is_none()
&& let Some(frame) = warp.frame()
{
@@ -434,6 +438,7 @@ impl<W: TransformWarp> TransformSession<W> {
self.draft.warp = Some(warp);
}
TransformEdit::LeaveWarp => {
self.revision += u64::from(self.draft.warp.is_some());
if let Some((frame, state)) = self.draft.unwarped.take() {
self.draft.frame = frame;
self.draft.state = state;
@@ -498,6 +503,14 @@ impl<W: TransformWarp> TransformSession<W> {
self.step(Step::Redo)
}
/// Moves whenever what [`can_undo`](Self::can_undo), [`can_redo`](Self::can_redo) or whether a
/// [`warp`](Self::warp) is open report may change: an undo step recorded or taken, the Warp phase opened
/// or closed. A new session starts at 0, where nothing can be undone or redone and no warp is open, so
/// an app keys what it shows of those on this number.
pub fn revision(&self) -> u64 {
self.revision
}
/// Whether [`undo`](Self::undo) has a step to take back.
pub fn can_undo(&self) -> bool {
self.history.can_undo()
@@ -557,6 +570,7 @@ impl<W: TransformWarp> TransformSession<W> {
let step = EditEvent::set(Mixed::Same(self.rested.clone()), self.draft.clone(), Arc::from(""), None);
self.history.record(&step);
self.rested = self.draft.clone();
self.revision += 1;
}
/// One box or field event. A Begin takes the draft as `before`; a Set outside a gesture is a
@@ -600,6 +614,7 @@ impl<W: TransformWarp> TransformSession<W> {
let moved = self.history.step(&mut self.draft, step);
self.rested = self.draft.clone();
self.changed = false;
self.revision += u64::from(moved);
moved
}
}
+44 -11
View File
@@ -2,18 +2,25 @@
//! 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.
use craft_draw::ui::brush_presets::{BrushPick, BrushPickerState, BrushPickerValues, BrushPresetPicker, BrushRowPaint, brush_row};
use craft_draw::ui::brush_presets::{BrushCardParts, BrushPick, BrushPickerState, BrushPickerValues, BrushPresetPicker, BrushRowPaint, brush_row};
use craft_draw::ui::brush_settings::TipAngle;
use craft_ui::contract::{Bind, Role, SaveKey};
use craft_ui::patterns::presets::PresetEvent;
use craft_ui::patterns::presets::{PresetEvent, PresetFns, PresetRow, PresetSource};
use craft_ui::runtime::env::Env;
use craft_ui::testing::{Fixture, trial};
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, trial};
use egui::{Key, Modifiers, Pos2, Rect, Vec2};
use std::cell::RefCell;
use std::rc::Rc;
const HARD: u32 = 2;
/// Two presets, Soft Round and Hard Round, showing `parts`.
fn two_rows(parts: &BrushCardParts, env: &Env) -> Vec<PresetRow<u32>> {
let paint = BrushRowPaint::new(|_, _| {}, |_, _| {});
vec![brush_row(1, "Soft Round", 0, 45.0, *parts, env, &paint), brush_row(HARD, "Hard Round", 0, 12.0, *parts, env, &paint)]
}
struct Host {
current: Option<u32>,
state: BrushPickerState<u32>,
@@ -25,12 +32,9 @@ fn rename_brush_opens_the_name_field_on_the_current_preset() {
let host = Rc::new(RefCell::new(Host { current: Some(HARD), state: BrushPickerState::new(), picks: Vec::new() }));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| {
let env = Env::of(ui);
let paint = BrushRowPaint::new(|_, _| {}, |_, _| {});
let mut host = shown.borrow_mut();
let Host { current, state, picks } = &mut *host;
let rows =
vec![brush_row(1, "Soft Round", 0, 45.0, state.parts, &env, &paint), brush_row(HARD, "Hard Round", 0, 12.0, state.parts, &env, &paint)];
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);
@@ -88,13 +92,10 @@ fn opened_rig(at_point: bool, remember: bool) -> (Fixture, Rc<RefCell<Opened>>)
}));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| {
let env = Env::of(ui);
let paint = BrushRowPaint::new(|_, _| {}, |_, _| {});
let mut host = shown.borrow_mut();
let Opened { current, state, values, open, tip_edits, at, offset } = &mut *host;
ui.add_space(*offset);
let rows =
vec![brush_row(1, "Soft Round", 0, 45.0, state.parts, &env, &paint), brush_row(HARD, "Hard Round", 0, 12.0, state.parts, &env, &paint)];
let rows = PresetSource::new(state.parts, PresetFns::new(two_rows));
let mut picker = BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &rows, Bind::bound(state), *values);
if remember {
picker = picker.resizable(SaveKey::new("craft_draw_tests.brush_picker"));
@@ -222,3 +223,35 @@ fn escape_reverts_size_hardness_angle_and_roundness() {
fixture.idle(3);
assert_eq!(host.borrow().values, OPENED, "Escape puts all four back");
}
/// 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()
}
/// The memoized views of `props` that replayed in the last frame.
fn views_replayed(fixture: &Fixture, props: &str) -> usize {
last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Replayed).count()
}
/// While nothing changes the open picker's head and preset list replay; each move of a Size drag runs the head's view
/// and replays the list.
#[trial]
fn a_size_drag_runs_the_head_and_replays_the_preset_list() {
let (mut fixture, host) = opened_rig(true, false);
fixture.frame(vec![]);
assert_eq!((views_ran(&fixture, "HeadProps"), views_ran(&fixture, "ListProps")), (0, 0), "an idle frame runs neither view");
let slider = fixture.by_role(Role::SLIDER).into_iter().find(|target| fixture.tree().name_of(target.node) == Some("Size"));
let slider = slider.expect("the Size slider shows").rect;
let from = slider.left_center() + Vec2::new(slider.width() * 0.3, 0.0);
fixture.frame(vec![moved(from)]);
fixture.frame(vec![press(from)]);
for step in 1..=4 {
fixture.frame(vec![moved(from + Vec2::new(8.0 * step as f32, 0.0))]);
assert!(views_ran(&fixture, "HeadProps") > 0, "move {step} runs the head");
assert_eq!(views_ran(&fixture, "ListProps"), 0, "move {step} runs no list view");
assert!(views_replayed(&fixture, "ListProps") > 0, "move {step} replays the 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");
}
+27
View File
@@ -185,3 +185,30 @@ fn a_warp_with_its_own_frame_takes_the_frame_and_gives_it_back() {
s.apply(TransformEdit::LeaveWarp, 1.0);
assert_eq!((s.rect(), s.state().quad), (FRAME, BoxState::from_rect(FRAME).quad));
}
// The revision moves with every change to what Undo, Redo and the Warp phase report, and stays through a drag's moves
// and the view-like edits, so an app keys its Edit menu on it.
#[trial]
fn the_revision_follows_the_undo_steps_and_the_warp_phase() {
let mut s = session();
let start = s.revision();
let id = GestureId::new(1);
s.apply(TransformEdit::Box(begin(id)), 0.0);
s.apply(TransformEdit::Box(update(id, moved(doc(5.0, 0.0)))), 0.0);
s.apply(TransformEdit::Box(update(id, moved(doc(9.0, 0.0)))), 0.0);
assert_eq!(s.revision(), start, "a drag's moves record no step");
s.apply(TransformEdit::Box(commit(id, moved(doc(9.0, 0.0)))), 0.0);
s.settle(0.0, false);
let recorded = s.revision();
assert!(recorded != start && s.can_undo());
assert!(s.undo());
let undone = s.revision();
assert!(undone != recorded && s.can_redo());
s.apply(TransformEdit::Warp(Warp(false)), 0.0);
let warped = s.revision();
assert!(warped != undone && s.warp().is_some());
s.apply(TransformEdit::Warp(Warp(true)), 0.0);
assert_eq!(s.revision(), warped, "a warp edit inside the phase opens no phase");
s.apply(TransformEdit::LeaveWarp, 0.0);
assert!(s.revision() != warped && s.warp().is_none());
}
@@ -2,6 +2,7 @@
/// A contour point, input and output in 0..=1.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
pub struct ContourPoint {
/// Input value, 0..=1 (the horizontal axis).
pub input: f32,
@@ -15,6 +16,7 @@ pub struct ContourPoint {
/// Built-in presets carry their preset name; an edited preset is named "Custom"; imported
/// contours keep their own name and points.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))]
pub struct Contour {
#[allow(missing_docs)]
pub name: String,
@@ -15,7 +15,7 @@ use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::text::TextField;
use egui::Ui;
use super::{ContourAction, ContourRequest, ContourWords, SharedSampler, from_curve, to_curve};
use super::{ContourAction, ContourRequest, ContourSampler, ContourWords, from_curve, to_curve};
use crate::layer_style::Contour;
use crate::ui::curve::CurveEditor;
@@ -49,7 +49,7 @@ pub struct ContourEditorDialog {
key: String,
initial: Contour,
draft: Draft,
sampler: Option<SharedSampler>,
sampler: Option<ContourSampler>,
changed: bool,
action: Option<ContourAction>,
focus_name: bool,
@@ -72,8 +72,8 @@ impl ContourEditorDialog {
/// The interpolation of the points, as the engine does it. Without it the curve is a monotone cubic.
#[must_use]
pub fn sampler(mut self, sampler: impl Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync + 'static) -> Self {
self.sampler = Some(std::sync::Arc::new(sampler));
pub fn sampler(mut self, sampler: ContourSampler) -> Self {
self.sampler = Some(sampler);
self
}
@@ -121,7 +121,7 @@ impl StackDialog for ContourEditorDialog {
let extras = [(Extra::Load, &words.load), (Extra::Save, &words.save), (Extra::New, &words.new)];
let named = Cell::new(false);
let focus_name = std::mem::take(&mut self.focus_name);
let sampler = self.sampler.clone();
let sampler = self.sampler;
let shown = FormDialog::new(words.editor.clone(), Bind::bound(&mut self.draft))
.outer_gesture(true)
.history(true)
@@ -171,8 +171,8 @@ impl StackDialog for ContourEditorDialog {
.percent()
.corners()
.between(between);
if let Some(sampler) = sampler.clone() {
editor = editor.sampler(move |points| sampler(points));
if let Some(sampler) = sampler {
editor = editor.sampler(sampler);
}
let edit = editor.show(ui);
if let Some(next) = edit.events.value().and_then(|curve| from_curve(curve, &draft.contour.name)) {
@@ -5,14 +5,12 @@ mod editor;
#[cfg(feature = "suite")]
pub(crate) mod stories;
use std::sync::Arc;
use craft_behavior::{EditEvents, Mixed};
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, EditResponse, NoValue, Outcome, Pattern, Props as _, Show as _, ShowContainer as _};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::list::ThumbAspect;
use craft_ui::patterns::presets::{PickerField, PresetEvent, PresetFooterEvent, PresetPicker, PresetRow, PresetState};
use craft_ui::patterns::presets::{PickerField, PresetEvent, PresetFns, PresetFooterEvent, PresetPicker, PresetRow, PresetSource, PresetState};
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::env::{Env, Label};
use egui::{Rect, Response, Ui};
@@ -78,14 +76,15 @@ impl ContourWords {
}
}
/// A host's interpolation of a contour's points, shared with the thumbnails' painters.
pub(crate) type SharedSampler = Arc<dyn Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync>;
/// A host's interpolation of a contour's points (levels in, levels out), shared with the thumbnails' painters. A `fn`,
/// which captures nothing, so the contour presets key it by its address.
pub type ContourSampler = fn(&[[f32; 2]]) -> Vec<f32>;
/// The levels of a contour as a curve: input and output run `0..=255`.
const LEVELS: f32 = 255.0;
/// A contour a picker lists: one of the built-in contours or one of the user's.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub enum ContourKey {
/// The built-in contour at this place of [`Contour::presets`].
@@ -153,24 +152,39 @@ impl Outcome for ContourFieldOutput {
}
}
/// The rows of the contour picker: the built-in contours, then the user's, named by `words`, with a thumbnail of each
/// curve. `sampler` interpolates the points as the engine does; without it the thumbnails use a monotone cubic.
pub fn contour_rows(presets: &[Contour], user: &[Contour], words: &ContourWords, sampler: Option<SharedSampler>) -> Vec<PresetRow<ContourKey>> {
/// What the contour presets are built from.
#[derive(craft_ui::contract::MemoProps)]
struct ContourInputs<'a> {
presets: &'a [Contour],
user: &'a [Contour],
#[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")]
sampler: Option<ContourSampler>,
}
/// The presets of the contour picker: the built-in contours, then the user's, with a thumbnail of each curve; the
/// user's may be deleted. `sampler` interpolates the points as the engine does; without it the thumbnails use a
/// monotone cubic.
pub fn contour_source<'a>(presets: &'a [Contour], user: &'a [Contour], sampler: Option<ContourSampler>) -> PresetSource<'a, ContourKey> {
let fns = PresetFns::new(contour_rows).can_delete(|_, key| matches!(key, ContourKey::User(_)));
PresetSource::new(ContourInputs { presets, user, sampler }, fns)
}
/// The rows of the contour picker, named by the scope's words.
fn contour_rows(inputs: &ContourInputs<'_>, env: &Env) -> Vec<PresetRow<ContourKey>> {
let words = env.words::<ContourWords>();
let sampler = inputs.sampler;
let row = |key: ContourKey, contour: &Contour| {
let name = words.contour_name(&contour.name).to_owned();
let curve = Arc::new(to_curve(contour));
let sampler = sampler.clone();
PresetRow::item(key, name, 0).preview(ThumbAspect::SQUARE, move |painter, rect| paint_thumbnail(painter, rect, &curve, sampler.as_deref()))
let curve = to_curve(contour);
PresetRow::item(key, name, 0).preview(ThumbAspect::SQUARE, move |painter, rect| paint_thumbnail(painter, rect, &curve, sampler))
};
let presets = presets.iter().enumerate().map(|(i, contour)| row(ContourKey::Preset(i), contour));
let user = user.iter().enumerate().map(|(i, contour)| row(ContourKey::User(i), contour));
let presets = inputs.presets.iter().enumerate().map(|(i, contour)| row(ContourKey::Preset(i), contour));
let user = inputs.user.iter().enumerate().map(|(i, contour)| row(ContourKey::User(i), contour));
presets.chain(user).collect()
}
type SamplerFn = dyn Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync;
/// A thumbnail of a contour: its curve in the curve preview's look (plot, quarter grid, diagonal).
fn paint_thumbnail(painter: &ContentPainterCx<'_>, rect: Rect, curve: &Curve, sampler: Option<&SamplerFn>) {
fn paint_thumbnail(painter: &ContentPainterCx<'_>, rect: Rect, curve: &Curve, sampler: Option<ContourSampler>) {
let Curve::Points { points, corners } = curve else { return };
let outputs = Curve::through(points, corners, |points| match sampler {
Some(sampler) => sampler(points),
@@ -206,21 +220,22 @@ pub fn from_curve(curve: &Curve, name: &str) -> Option<Contour> {
pub struct ContourField<'a> {
label: Label,
contour: Bind<'a, Contour>,
rows: &'a [PresetRow<ContourKey>],
source: &'a PresetSource<'a, ContourKey>,
state: Bind<'a, PresetState<ContourKey>>,
user: &'a [Contour],
anti_alias: Option<Bind<'a, Option<bool>>>,
}
impl<'a> ContourField<'a> {
/// A field named `label` over `contour`, choosing among `rows` ([`contour_rows`]); `state` is the browser's view.
/// A field named `label` over `contour`, choosing among `source` ([`contour_source`]); `state` is the browser's
/// view.
pub fn new(
label: impl Into<Label>,
contour: Bind<'a, Contour>,
rows: &'a [PresetRow<ContourKey>],
source: &'a PresetSource<'a, ContourKey>,
state: Bind<'a, PresetState<ContourKey>>,
) -> Self {
Self { label: label.into(), contour, rows, state, user: &[], anti_alias: None }
Self { label: label.into(), contour, source, state, user: &[], anti_alias: None }
}
/// The user's contours, the targets of [`ContourKey::User`].
@@ -237,7 +252,7 @@ impl<'a> ContourField<'a> {
/// Shows the field and returns this pass's edit and requests.
pub fn show(self, ui: &mut Ui) -> ContourFieldOutput {
let Self { label, mut contour, rows, mut state, user, mut anti_alias } = self;
let Self { label, mut contour, source, mut state, user, mut anti_alias } = self;
let env = Env::of(ui);
let words = env.words::<ContourWords>();
let presets = Contour::presets();
@@ -254,10 +269,9 @@ impl<'a> ContourField<'a> {
let mut anti_events = EditEvents::new();
let mut picked = None;
Row::new().show(ui, |ui, root| {
let picker = PresetPicker::new(label.clone(), Bind::bound(&mut key), rows, state.reborrowed())
let picker = PresetPicker::new(label.clone(), Bind::bound(&mut key), source, state.reborrowed())
.field(PickerField::Thumbnail)
.columns(4)
.can_delete(|key| matches!(key, ContourKey::User(_)))
.edit_face()
.show(ui);
for event in &picker.events {
@@ -3,11 +3,10 @@
use craft_ui::contract::ShowContainer as _;
use craft_ui::form::Field;
use craft_ui::patterns::presets::PresetState;
use craft_ui::runtime::env::Env;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use super::{ContourField, ContourKey, ContourWords, contour_rows};
use super::{ContourField, ContourKey, contour_source};
use crate::layer_style::{Contour, ContourPoint};
fn user_contours() -> Vec<Contour> {
@@ -18,9 +17,9 @@ fn user_contours() -> Vec<Contour> {
/// The field over `start` with its Anti-aliased check box, in the host's Field, and the contour it holds as the
/// readout.
fn field(ui: &mut Ui, data: &mut StoryData, start: Contour, anti_alias: bool) -> StoryOutput {
let words = Env::of(ui).words::<ContourWords>();
let user = user_contours();
let rows = contour_rows(&Contour::presets(), &user, &words, None);
let presets = Contour::presets();
let rows = contour_source(&presets, &user, None);
let ((contour, state, anti_alias), field_at) = data.value_at("field", (start, PresetState::<ContourKey>::new(), Some(anti_alias)));
let shown = Field::new("Contour").show(ui, |ui, _| {
ContourField::new("Contour", field_at.bind(&mut *contour), &rows, field_at.bind(&mut *state))
+23 -31
View File
@@ -8,18 +8,17 @@ use craft_theme::{Srgba, TypeRole};
use craft_ui::contract::{CommandSet as _, Entry, NoValue, Outcome, Pattern, Props as _, Show as _, ShowContainer as _};
use craft_ui::display::{Divider, Text};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::patterns::presets::PresetRow;
use craft_ui::patterns::presets::{PresetFns, PresetSource};
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::requests::ColorRequest;
use egui::{Response, Ui};
use super::blending::{BlendingInput, blending_page};
use super::contour::SharedSampler;
use super::contour::{ContourAction, ContourRequest, ContourWords};
use super::contour::{ContourAction, ContourRequest, ContourSampler};
use super::labels::LayerStyleWords;
use super::list::{LayerStyleCommand, ListAction, effect_list};
use super::page::{PageInput, StyleOp, effect_page, push_edit, set_edit};
use super::styles::{StylePresets, styles_page};
use super::styles::styles_page;
use craft_behavior::EditEvents;
use crate::layer_style::{Contour, EffectId, EffectKind, EffectSpec, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams, StyleValue};
@@ -102,8 +101,8 @@ impl LayerStyleOutput {
/// before the page changes.
/// - The page title is the effect's name, plain. New Style… and the Preview check box are the host's, in the button
/// column under OK and Cancel (Photoshop's place), the check over [`LayerStyleDraft::preview`].
/// - The Styles page ([`StylePresets`]), the Blending Options page, or an effect page drawn from the kind's
/// [`EffectSpec`].
/// - The Styles page ([`style_presets`](Self::style_presets)), the Blending Options page, or an effect page drawn from
/// the kind's [`EffectSpec`].
/// - Use Global Light: on an effect that uses it, the Angle edits the shared light angle of every such effect
/// ([`LayerStyleDraft::set_param`]).
///
@@ -123,10 +122,10 @@ pub struct LayerStyleDialog<'a> {
specs: Option<&'a [EffectSpec]>,
blend_keys: Option<&'a HashMap<String, String>>,
blend_modes: &'a [Entry<String>],
patterns: &'a [PresetRow<String>],
patterns: Option<&'a PresetSource<'a, String>>,
user_contours: &'a [Contour],
sampler: Option<SharedSampler>,
style_presets: Option<StylePresets<'a>>,
sampler: Option<ContourSampler>,
style_presets: Option<&'a PresetSource<'a, String>>,
gradient_presets: &'a [(String, GradientStops)],
}
@@ -141,7 +140,7 @@ impl<'a> LayerStyleDialog<'a> {
specs: None,
blend_keys: None,
blend_modes: &[],
patterns: &[],
patterns: None,
user_contours: &[],
sampler: None,
style_presets: None,
@@ -177,8 +176,8 @@ impl<'a> LayerStyleDialog<'a> {
}
/// The patterns Pattern Overlay offers, keyed by the pattern's key.
pub fn patterns(mut self, patterns: &'a [PresetRow<String>]) -> Self {
self.patterns = patterns;
pub fn patterns(mut self, patterns: &'a PresetSource<'a, String>) -> Self {
self.patterns = Some(patterns);
self
}
@@ -190,19 +189,14 @@ impl<'a> LayerStyleDialog<'a> {
/// The host's interpolation of a contour's points: the output of every input level through the points, so the
/// contour fields draw the curve the engine renders; a monotone cubic by default.
pub fn sampler(mut self, sample: impl Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync + 'static) -> Self {
self.sampler = Some(std::sync::Arc::new(sample));
pub fn sampler(mut self, sample: ContourSampler) -> Self {
self.sampler = Some(sample);
self
}
/// [`sampler`](Self::sampler) as the host keeps it: `None` for the default.
pub(super) fn shared_sampler(mut self, sampler: Option<SharedSampler>) -> Self {
self.sampler = sampler;
self
}
/// The Styles page's presets; without them the page shows only its title.
pub fn style_presets(mut self, presets: StylePresets<'a>) -> Self {
/// The Styles page's presets, keyed by the preset's name and painted by the source's thumbnail painter; without
/// them the page shows only its title.
pub fn style_presets(mut self, presets: &'a PresetSource<'a, String>) -> Self {
self.style_presets = Some(presets);
self
}
@@ -225,7 +219,6 @@ impl<'a> LayerStyleDialog<'a> {
} = self;
let env = Env::of(ui);
let words = env.words::<LayerStyleWords>();
let contour_words = env.words::<ContourWords>();
let units = env.units();
let base: Cow<'_, [EffectSpec]> = match specs {
Some(specs) => Cow::Borrowed(specs),
@@ -239,6 +232,8 @@ impl<'a> LayerStyleDialog<'a> {
}
None => &base,
};
let none = PresetSource::new((), PresetFns::new(|_, _| Vec::new()));
let patterns = patterns.unwrap_or(&none);
let mut work = Work { next: draft.clone(), edit: EditEvents::new(), extras: Extras::default() };
let title = page_title(draft.page, draft, &words);
let name = label.as_str().to_owned();
@@ -255,14 +250,13 @@ impl<'a> LayerStyleDialog<'a> {
blend_modes,
patterns,
user_contours,
sampler: sampler.as_ref(),
sampler,
gradient_presets,
channel_names,
words: &words,
contour_words: &contour_words,
units: &units,
};
work.page(ui, &page, style_presets.as_ref());
work.page(ui, &page, style_presets);
});
});
let Work { next, edit, extras } = work;
@@ -333,13 +327,12 @@ struct PageEnv<'a> {
draft: &'a LayerStyleDraft,
specs: &'a [EffectSpec],
blend_modes: &'a [Entry<String>],
patterns: &'a [PresetRow<String>],
patterns: &'a PresetSource<'a, String>,
user_contours: &'a [Contour],
sampler: Option<&'a SharedSampler>,
sampler: Option<ContourSampler>,
gradient_presets: &'a [(String, GradientStops)],
channel_names: &'a [String],
words: &'a LayerStyleWords,
contour_words: &'a ContourWords,
units: &'a craft_ui::runtime::env::Units,
}
@@ -389,7 +382,7 @@ impl Work {
}
/// Draws the page of the pass; its controls add their edits to the pass's.
fn page(&mut self, ui: &mut Ui, env: &PageEnv<'_>, presets: Option<&StylePresets<'_>>) {
fn page(&mut self, ui: &mut Ui, env: &PageEnv<'_>, presets: Option<&PresetSource<'_, String>>) {
let (words, draft) = (env.words, env.draft);
let instance = match draft.page {
LayerStylePage::Effect(id) => draft.style.effect(id).cloned(),
@@ -423,7 +416,6 @@ impl Work {
sampler: env.sampler,
gradient_presets: env.gradient_presets,
words,
contour_words: env.contour_words,
units: env.units,
};
let out = effect_page(ui, &input);
+22 -25
View File
@@ -12,7 +12,7 @@ use craft_ui::contract::{
};
use craft_ui::dialog::{ButtonPlace, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft_ui::patterns::form_dialogs::FormDialog;
use craft_ui::patterns::presets::{PresetRow, ThumbInfo};
use craft_ui::patterns::presets::PresetSource;
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::requests::ColorRequest;
@@ -20,9 +20,9 @@ use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::style::{ComponentStyle, StyleCx};
use egui::{Context, Rect, Response, Ui, Vec2};
use super::contour::SharedSampler;
use super::contour::ContourSampler;
use super::labels::LayerStyleWords;
use super::{ContourAction, ContourRequest, LayerStyleDialog, LayerStyleOutput, StylePresets};
use super::{ContourAction, ContourRequest, LayerStyleDialog, LayerStyleOutput};
use crate::layer_style::{
Contour, EffectId, EffectKind, EffectSpec, FieldKind, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams, StyleValue,
};
@@ -66,9 +66,6 @@ impl LayerStyleOutput {
}
}
/// Paints a style preset's thumbnail.
type Thumb = dyn Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + Send;
/// Paints the preview swatch beside the footer buttons from the draft.
type PreviewPaint = dyn Fn(&ContentPainterCx, Rect, &LayerStyleDraft) + Send + Sync;
@@ -158,10 +155,10 @@ pub struct HostedLayerStyle {
specs: Option<Vec<EffectSpec>>,
blend_keys: Option<HashMap<String, String>>,
blend_modes: Vec<Entry<String>>,
patterns: Vec<PresetRow<String>>,
patterns: Option<PresetSource<'static, String>>,
user_contours: Vec<Contour>,
sampler: Option<SharedSampler>,
styles: Option<(Vec<PresetRow<String>>, Box<Thumb>)>,
sampler: Option<ContourSampler>,
styles: Option<PresetSource<'static, String>>,
gradient_presets: Vec<(String, GradientStops)>,
canvas: Option<egui::Id>,
preview_thumb: Option<Arc<PreviewPaint>>,
@@ -187,7 +184,7 @@ impl HostedLayerStyle {
specs: None,
blend_keys: None,
blend_modes: Vec::new(),
patterns: Vec::new(),
patterns: None,
user_contours: Vec::new(),
sampler: None,
styles: None,
@@ -224,8 +221,8 @@ impl HostedLayerStyle {
/// [`LayerStyleDialog::patterns`].
#[must_use]
pub fn patterns(mut self, patterns: Vec<PresetRow<String>>) -> Self {
self.patterns = patterns;
pub fn patterns(mut self, patterns: PresetSource<'static, String>) -> Self {
self.patterns = Some(patterns);
self
}
@@ -238,19 +235,15 @@ impl HostedLayerStyle {
/// [`LayerStyleDialog::sampler`].
#[must_use]
pub fn sampler(mut self, sample: impl Fn(&[[f32; 2]]) -> Vec<f32> + Send + Sync + 'static) -> Self {
self.sampler = Some(std::sync::Arc::new(sample));
pub fn sampler(mut self, sample: ContourSampler) -> Self {
self.sampler = Some(sample);
self
}
/// The Styles page's presets `rows`, each thumbnail painted by `thumb` ([`StylePresets::new`]).
/// [`LayerStyleDialog::style_presets`].
#[must_use]
pub fn style_presets(
mut self,
rows: Vec<PresetRow<String>>,
thumb: impl Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + Send + 'static,
) -> Self {
self.styles = Some((rows, Box::new(thumb)));
pub fn style_presets(mut self, presets: PresetSource<'static, String>) -> Self {
self.styles = Some(presets);
self
}
@@ -379,18 +372,22 @@ impl StackDialog for HostedLayerStyle {
}
let mut body = LayerStyleDialog::new(label.clone(), draft, channel_names.as_slice())
.blend_modes(blend_modes.as_slice())
.patterns(patterns.as_slice())
.user_contours(user_contours.as_slice())
.shared_sampler(sampler.clone())
.gradient_presets(gradient_presets.as_slice());
if let Some(patterns) = patterns.as_ref() {
body = body.patterns(patterns);
}
if let Some(sampler) = *sampler {
body = body.sampler(sampler);
}
if let Some(specs) = specs.as_deref() {
body = body.specs(specs);
}
if let Some(map) = blend_keys.as_ref() {
body = body.blend_keys(map);
}
if let Some((rows, thumb)) = styles.as_ref() {
body = body.style_presets(StylePresets::new(rows, |cx, rect, info| thumb(cx, rect, info)));
if let Some(presets) = styles.as_ref() {
body = body.style_presets(presets);
}
let out = body.show(ui);
#[cfg(feature = "screen-testing")]
+2 -3
View File
@@ -36,13 +36,12 @@ mod styles;
pub use blend_if::{BlendIfBar, BlendIfWords};
pub use contour::{
ContourAction, ContourEditorDialog, ContourField, ContourFieldOutput, ContourKey, ContourRequest, ContourWords, contour_rows, from_curve,
to_curve,
ContourAction, ContourEditorDialog, ContourField, ContourFieldOutput, ContourKey, ContourRequest, ContourSampler, ContourWords, contour_source,
from_curve, to_curve,
};
pub use dialog::{LayerStyleDialog, LayerStyleOutput};
pub use hosted::{HostedLayerStyle, LayerStyleAsk};
pub use labels::LayerStyleWords;
pub use list::LayerStyleCommand;
pub use styles::StylePresets;
pub use crate::layer_style::LayerStylePage;
+7 -8
View File
@@ -12,16 +12,16 @@ use craft_ui::display::Text;
use craft_ui::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
use craft_ui::layout::RowAlign;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::patterns::presets::{PresetPicker, PresetRow, PresetState};
use craft_ui::patterns::presets::{PresetPicker, PresetSource, PresetState};
use craft_ui::pickers::Select;
use craft_ui::runtime::env::{Label, UnitKind, Units};
use craft_ui::runtime::env::{Env, Label, UnitKind, Units};
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::text::NumberField;
use craft_ui::value_drag::AngleDial;
use egui::Ui;
use super::blending::BlendingOp;
use super::contour::{ContourAction, ContourField, ContourKey, ContourRequest, ContourWords, SharedSampler, contour_rows};
use super::contour::{ContourAction, ContourField, ContourKey, ContourRequest, ContourSampler, contour_source};
use super::labels::LayerStyleWords;
use crate::layer_style::{
Contour, EffectField, EffectId, EffectInstance, EffectKind, EffectSpec, FieldKind, FieldUnit, LayerStyle, LayerStyleDraft, StyleParams,
@@ -86,12 +86,11 @@ pub(super) struct PageInput<'a> {
pub instance: &'a EffectInstance,
pub style: &'a LayerStyle,
pub blend_modes: &'a [Entry<String>],
pub patterns: &'a [PresetRow<String>],
pub patterns: &'a PresetSource<'a, String>,
pub user_contours: &'a [Contour],
pub sampler: Option<&'a SharedSampler>,
pub sampler: Option<ContourSampler>,
pub gradient_presets: &'a [(String, GradientStops)],
pub words: &'a LayerStyleWords,
pub contour_words: &'a ContourWords,
pub units: &'a Units,
}
@@ -329,7 +328,7 @@ fn field_row(ui: &mut Ui, input: &PageInput<'_>, field: &EffectField, shown: &St
}
FieldKind::Pattern => {
let stored = text_of(shown.get(key)).filter(|t| !t.is_empty());
let first = input.patterns.iter().find(|row| !row.is_group()).map(|row| row.key.clone());
let first = input.patterns.rows(ui.ctx(), &Env::of(ui)).iter().find(|row| !row.is_group()).map(|row| row.key.clone());
let current = stored.map(str::to_owned).or(first.clone());
let picker = Field::new(label.clone())
.id_salt(key)
@@ -351,7 +350,7 @@ fn field_row(ui: &mut Ui, input: &PageInput<'_>, field: &EffectField, shown: &St
let before = anti_alias.as_deref().map(|k| shown.bool(k).unwrap_or(false));
let mut checked = before;
let presets = Contour::presets();
let rows = contour_rows(&presets, input.user_contours, input.contour_words, input.sampler.cloned());
let rows = contour_source(&presets, input.user_contours, input.sampler);
// A field with no visible label (Emboss's contour under its check box) is still named for assistive tech.
let name = if label.as_str().is_empty() {
words.field("contour").cloned().unwrap_or_else(|| Label::from(field.key.to_string()))
+14 -6
View File
@@ -7,10 +7,11 @@ use craft_theme::Srgba;
use craft_ui::contract::Entry;
use craft_ui::dialog::stories::hosted;
use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut, blend_entries};
use craft_ui::patterns::presets::PresetRow;
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource, ThumbInfo};
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use egui::{Rect, Ui};
use super::{HostedLayerStyle, LayerStyleDialog};
use crate::layer_style::{BlendIf, Blending, EffectId, EffectInstance, EffectKind, EffectSpec, LayerStyle, LayerStyleDraft, LayerStylePage};
@@ -71,7 +72,8 @@ fn gradient_presets(words: &LayerStyleStoryWords) -> Vec<(String, GradientStops)
]
}
fn patterns(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
fn pattern_rows(_: &(), env: &Env) -> Vec<PresetRow<String>> {
let words = env.words::<LayerStyleStoryWords>();
vec![
PresetRow::group("group".to_owned(), words.pattern_group.as_str(), 0),
PresetRow::item("bubbles".to_owned(), words.pattern_bubbles.as_str(), 1),
@@ -79,7 +81,8 @@ fn patterns(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
]
}
fn style_rows(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
fn style_rows(_: &(), env: &Env) -> Vec<PresetRow<String>> {
let words = env.words::<LayerStyleStoryWords>();
vec![
PresetRow::group("group".to_owned(), words.style_group.as_str(), 0),
PresetRow::item("Soft".to_owned(), words.style_soft.as_str(), 1),
@@ -87,6 +90,11 @@ fn style_rows(words: &LayerStyleStoryWords) -> Vec<PresetRow<String>> {
]
}
/// The Styles page's fake thumbnails.
fn checker(_: &(), cx: &ContentPainterCx<'_>, rect: Rect, _: ThumbInfo<'_, String>) {
cx.checker(rect);
}
/// A style with one instance of each of `kinds`, turned on, in `kinds` order.
fn style_of(kinds: &[EffectKind]) -> LayerStyle {
let effects = kinds
@@ -105,9 +113,9 @@ fn host(ui: &mut Ui, data: &mut StoryData, start: impl FnOnce() -> LayerStyleDra
hosted(ui, data, (), || {
HostedLayerStyle::new("Layer Style", start(), names)
.blend_modes(blend_modes(&words))
.patterns(patterns(&words))
.patterns(PresetSource::new((), PresetFns::new(pattern_rows)))
.gradient_presets(gradient_presets(&words))
.style_presets(style_rows(&words), |cx, rect, _| cx.checker(rect))
.style_presets(PresetSource::new((), PresetFns::new(style_rows).thumb(checker)))
})
}
+7 -27
View File
@@ -3,9 +3,8 @@
use craft_theme::TypeRole;
use craft_ui::contract::{Bind, Show as _};
use craft_ui::display::Text;
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetRow, PresetState, ThumbInfo};
use craft_ui::primitives::ContentPainterCx;
use egui::{Rect, Ui};
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetSource, PresetState};
use egui::Ui;
use super::labels::LayerStyleWords;
@@ -13,23 +12,6 @@ use super::labels::LayerStyleWords;
/// dialog page around it scrolls too.
const STYLE_ROWS: u16 = 5;
/// The host's style presets for the Styles page: the rows (groups and presets keyed by the preset's name) and the
/// painter of one preset's thumbnail. The page shows them in the library [`PresetBrowser`] grid and keeps the
/// browser's view state itself.
pub struct StylePresets<'a> {
pub(super) rows: &'a [PresetRow<String>],
pub(super) thumb: Thumb<'a>,
}
type Thumb<'a> = Box<dyn Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + 'a>;
impl<'a> StylePresets<'a> {
/// The presets `rows`, each thumbnail painted by `thumb`.
pub fn new(rows: &'a [PresetRow<String>], thumb: impl Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + 'a) -> Self {
StylePresets { rows, thumb: Box::new(thumb) }
}
}
/// What the Styles page asked for.
#[derive(Clone, Debug, Default, PartialEq)]
pub(super) struct StylesOutput {
@@ -39,15 +21,13 @@ pub(super) struct StylesOutput {
pub apply_style: Option<String>,
}
/// Draws the page: the title, then the browser. Without presets the page shows only the title.
pub(super) fn styles_page(ui: &mut Ui, presets: Option<&StylePresets<'_>>, words: &LayerStyleWords) -> StylesOutput {
/// Draws the page: the title, then the host's style presets (groups and presets keyed by the preset's name) in the
/// library browser grid, whose view state the page keeps. Without presets the page shows only the title.
pub(super) fn styles_page(ui: &mut Ui, presets: Option<&PresetSource<'_, String>>, words: &LayerStyleWords) -> StylesOutput {
Text::new(words.styles.clone()).role(TypeRole::Title).show(ui);
let mut out = StylesOutput { apply_style: None };
if let Some(StylePresets { rows, thumb }) = presets {
let browser = PresetBrowser::new(words.styles.clone(), Bind::<PresetState<String>>::kept(), rows)
.thumb(move |cx, rect, info| thumb(cx, rect, info))
.row_menu(false)
.max_rows(STYLE_ROWS);
if let Some(presets) = presets {
let browser = PresetBrowser::new(words.styles.clone(), Bind::<PresetState<String>>::kept(), presets).row_menu(false).max_rows(STYLE_ROWS);
for event in browser.show(ui).events {
if let PresetEvent::Select { key, .. } | PresetEvent::Activate { key, .. } = event {
out.apply_style = Some(key);
+1 -1
View File
@@ -86,7 +86,7 @@ pub use histogram::{
};
pub use layer_style::{
BlendIfBar, BlendIfWords, ContourField, ContourFieldOutput, ContourWords, HostedLayerStyle, LayerStyleAsk, LayerStyleDialog, LayerStyleOutput,
LayerStyleWords, StylePresets,
LayerStyleWords,
};
pub use liquify::{
LiquifyCommands, LiquifyDone, LiquifyEvent, LiquifyOpen, LiquifyPanel, LiquifyPanelOutput, LiquifySession, LiquifySettings, LiquifySource,
+3 -4
View File
@@ -4,10 +4,9 @@ use std::cell::RefCell;
use std::rc::Rc;
use craft_imaging::layer_style::Contour;
use craft_imaging::ui::layer_style::{ContourField, ContourKey, ContourRequest, ContourWords, contour_rows};
use craft_imaging::ui::layer_style::{ContourField, ContourKey, ContourRequest, contour_source};
use craft_ui::contract::{Bind, Role};
use craft_ui::patterns::presets::PresetState;
use craft_ui::runtime::env::Env;
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, pos2};
@@ -18,8 +17,8 @@ fn rig() -> (Fixture, Rc<RefCell<Vec<ContourRequest>>>) {
let mut contour = Contour::linear();
let mut state = PresetState::<ContourKey>::new();
let mut fixture = Fixture::new(move |ui| {
let words = Env::of(ui).words::<ContourWords>();
let rows = contour_rows(&Contour::presets(), &[], &words, None);
let presets = Contour::presets();
let rows = contour_source(&presets, &[], None);
let out = ContourField::new("Contour", Bind::bound(&mut contour), &rows, Bind::bound(&mut state)).show(ui);
seen.borrow_mut().extend(out.edit_contour);
});
+12 -15
View File
@@ -10,9 +10,9 @@ use craft_imaging::layer_style::{
EffectField, EffectId, EffectInstance, EffectKind, EffectSpec, FieldKind, FieldUnit, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams,
StyleValue,
};
use craft_imaging::ui::layer_style::{LayerStyleDialog, StylePresets};
use craft_imaging::ui::layer_style::LayerStyleDialog;
use craft_ui::contract::Role;
use craft_ui::patterns::presets::PresetRow;
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource};
use craft_ui::testing::access::{NodeKey, name};
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::{Fixture, Target, trial};
@@ -26,7 +26,6 @@ struct Host {
draft: LayerStyleDraft,
specs: Vec<EffectSpec>,
channels: Vec<String>,
patterns: Vec<PresetRow<String>>,
edits: Vec<EditEvent<LayerStyle>>,
made: Vec<StyleParams>,
}
@@ -40,26 +39,24 @@ fn instance(id: u32, kind: EffectKind, on: bool) -> EffectInstance {
}
fn host(draft: LayerStyleDraft, specs: Vec<EffectSpec>) -> Host {
Host { draft, specs, channels: ["R", "G", "B"].map(String::from).to_vec(), patterns: Vec::new(), edits: Vec::new(), made: Vec::new() }
Host { draft, specs, channels: ["R", "G", "B"].map(String::from).to_vec(), edits: Vec::new(), made: Vec::new() }
}
fn rig_of(host: Host) -> (Fixture, Rc<RefCell<Host>>) {
let host = Rc::new(RefCell::new(host));
let shown = host.clone();
let rows = vec![
PresetRow::group("g".to_owned(), "Basics", 0),
PresetRow::item("Soft".to_owned(), "Soft", 1),
PresetRow::item("Hard".to_owned(), "Hard", 1),
];
let rows = |_: &(), _: &_| {
vec![
PresetRow::group("g".to_owned(), "Basics", 0),
PresetRow::item("Soft".to_owned(), "Soft", 1),
PresetRow::item("Hard".to_owned(), "Hard", 1),
]
};
let presets = PresetSource::new((), PresetFns::new(rows).thumb(|_, cx, rect, _| cx.checker(rect)));
let mut fixture = Fixture::new(move |ui| {
let mut guard = shown.borrow_mut();
let host = &mut *guard;
let presets = StylePresets::new(&rows, |cx, rect, _| cx.checker(rect));
let out = LayerStyleDialog::new("Layer Style", &host.draft, &host.channels)
.specs(&host.specs)
.patterns(&host.patterns)
.style_presets(presets)
.show(ui);
let out = LayerStyleDialog::new("Layer Style", &host.draft, &host.channels).specs(&host.specs).style_presets(&presets).show(ui);
out.apply_view(&mut host.draft);
for event in out.edit {
if let Some(value) = event.value() {
+1 -1
View File
@@ -160,7 +160,7 @@ egui::Panel::top("menu-bar").show(ui, |ui| {
they are off unless set. `.mnemonics(&[("View", 'W'), ("file.open", 'P')])` names preferred
letters by title as shown or by command id. A label without an ASCII letter or digit shows its
English label's letter after it, "文件(F)", before a trailing ellipsis ("開く(O)…"), when
`.english(&hook)` returns that English label for the `Labeled::Command` or `Labeled::Title`.
the item, submenu or menu carries that English label (`Item::english`, `Node::english`, `Menu::english`).
- **Items:** a command the runtime's gate forbids, or whose state is disabled, is greyed and never
fires. A submenu whose items are all disabled is greyed. The shortcut column shows the command's
chord, else the item's own shortcut, in the shell's names (⌘ glyphs on a Mac). `.target(..)`
+17 -54
View File
@@ -13,8 +13,8 @@ pub(crate) mod stories;
use craft_host::target::Os;
use craft_i18n::Words;
use craft_keymap::{CommandRef, Platform};
use craft_ui::contract::{MemoProps, MemoView, Show as _, Stateless, Tracked};
use craft_keymap::Platform;
use craft_ui::contract::{MemoProps, MemoView, Show as _, Tracked};
use craft_ui::menu::{MenuBar as Bar, MenuHelp, MenuTitle};
use craft_ui::runtime::env::{Env, Label};
use egui::{Rect, Ui};
@@ -27,19 +27,6 @@ use crate::palette::entries_of;
/// Whether a menu of the bar is open; the app's single-key shortcuts wait while it is true.
pub use craft_ui::menu::bar::{is_focused, is_open};
/// A row or title, as the bar names it to the app's mnemonic hooks ([`MenuBarUi::english`]).
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum Labeled<'s> {
/// An item, by its command.
Command(&'s CommandRef),
/// A menu or submenu, by its title as shown.
Title(&'s str),
}
/// The app's English labels ([`MenuBarUi::english`]).
pub type EnglishHook<'h> = dyn Fn(Labeled<'_>) -> Option<String> + 'h;
craft_ui::words! {
/// The words of the in-window bar that the menu family does not hold.
struct BarWords {
@@ -78,9 +65,6 @@ pub struct MenuBarOutput {
pub titles: Rect,
}
/// The English-label hook a bar takes by default: none is set, so this type only names the slot.
pub type EnglishFn = fn(Labeled<'_>) -> Option<String>;
/// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, inside a `Stack` (a top
/// panel's body) or the title bar's row: there it folds the titles that don't fit its room into "…".
/// The commands chosen come back through the command queue, not from `show`.
@@ -88,12 +72,10 @@ pub type EnglishFn = fn(Labeled<'_>) -> Option<String>;
/// The bar is a memoized view: while its model, options, place and environment are those of its last run and nothing
/// reaches it (pointer, focus, keys, an open menu), it adds that run again in place of running.
#[derive(craft_ui::contract::Pattern)]
#[pattern(probe(MenuBarUi<'static, EnglishFn>))]
pub struct MenuBarUi<'a, E = EnglishFn> {
pub struct MenuBarUi<'a> {
bar: &'a Tracked<MenuBar>,
/// The platform set with [`target`](Self::target); the shell's when none is.
target: Option<Target>,
english: Option<Stateless<E>>,
preferred: &'a [(&'a str, char)],
keyboard: Option<bool>,
help_search: bool,
@@ -101,10 +83,9 @@ pub struct MenuBarUi<'a, E = EnglishFn> {
/// Every input of the bar's view.
#[derive(MemoProps)]
struct BarProps<'a, #[memo_props(stateless)] E> {
struct BarProps<'a> {
bar: &'a Tracked<MenuBar>,
target: Target,
english: Option<Stateless<E>>,
preferred: &'a [(&'a str, char)],
keyboard: bool,
help: Option<usize>,
@@ -114,47 +95,37 @@ struct BarProps<'a, #[memo_props(stateless)] E> {
impl<'a> MenuBarUi<'a> {
/// The bar for `bar`, already laid out ([`crate::layout`]), on the shell's platform ([`Target::of_shell`]).
pub fn new(bar: &'a Tracked<MenuBar>) -> MenuBarUi<'a> {
MenuBarUi { bar, target: None, english: None, preferred: &[], keyboard: None, help_search: false }
MenuBarUi { bar, target: None, preferred: &[], keyboard: None, help_search: false }
}
}
impl<'a, E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static> MenuBarUi<'a, E> {
impl<'a> MenuBarUi<'a> {
/// The platform the bar is on, for the shortcut column ([`craft_keymap::Chord::display`]): ⌘ glyphs on
/// [`Target::Mac`] and in a browser on a Mac, Ctrl names everywhere else. On [`Target::Mac`] the native bar
/// has the keys, and this one takes none unless [`keyboard`](Self::keyboard) says so.
pub fn target(mut self, target: Target) -> MenuBarUi<'a, E> {
pub fn target(mut self, target: Target) -> MenuBarUi<'a> {
self.target = Some(target);
self
}
/// Whether the bar takes F10, Alt and Alt with a letter. By default it does, except on [`Target::Mac`]. The
/// app turns it off while a modal dialog or the shortcut recorder has the keys.
pub fn keyboard(mut self, on: bool) -> MenuBarUi<'a, E> {
pub fn keyboard(mut self, on: bool) -> MenuBarUi<'a> {
self.keyboard = Some(on);
self
}
/// The English label of a row or title, for labels the keyboard can't type a letter of (Chinese, Japanese,
/// Korean…): such a label shows its English label's mnemonic after it, "文件(F)", before a trailing ellipsis
/// ("開く(O)…"), as Windows menus do. Without this hook (or when it returns `None`) such a label has no
/// mnemonic. The Help menu's search also matches the English labels, on every target. The hook is a fn item or a
/// closure that captures nothing ([`Stateless`]): the bar's key follows its type.
pub fn english<F: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(self, english: F) -> MenuBarUi<'a, F> {
let MenuBarUi { bar, target, english: _, preferred, keyboard, help_search } = self;
MenuBarUi { bar, target, english: Some(Stateless::new(english)), preferred, keyboard, help_search }
}
/// Preferred mnemonics, each for a menu or submenu by its title as shown or for an item by its command id:
/// the row takes that letter when its label has it and no row before it in its menu took it. Every other row
/// takes the first unused letter of its label, word starts first.
pub fn mnemonics(mut self, preferred: &'a [(&'a str, char)]) -> MenuBarUi<'a, E> {
pub fn mnemonics(mut self, preferred: &'a [(&'a str, char)]) -> MenuBarUi<'a> {
self.preferred = preferred;
self
}
/// Start the [`MenuRole::Help`] menu with a search field over every command of the bar
/// ([`MenuBar::help_entries`]). A bar with no Help menu has no field.
pub fn help_search(mut self, on: bool) -> MenuBarUi<'a, E> {
pub fn help_search(mut self, on: bool) -> MenuBarUi<'a> {
self.help_search = on;
self
}
@@ -169,24 +140,18 @@ impl<'a, E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static> MenuBarUi<'a, E>
let props = BarProps {
bar: self.bar,
target,
english: self.english,
preferred: self.preferred,
keyboard: self.keyboard.unwrap_or(target != Target::Mac),
help,
label: env.words::<BarWords>().label.clone(),
};
MemoView::new("menu-bar", props, show_bar::<E>).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING })
MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING })
}
}
/// The bar's view: the titles through [`craft_ui::menu::MenuBar`], each menu's rows as command rows.
fn show_bar<E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(props: &mut BarProps<'_, E>, ui: &mut Ui) -> MenuBarOutput {
let hook = props.english.map(|english| {
let english = english.get();
move |labeled: Labeled<'_>| english(labeled)
});
let english: Option<&EnglishHook<'_>> = hook.as_ref().map(|hook| hook as &EnglishHook<'_>);
let rows = Rows::new(props.target).english(english).preferred(props.preferred);
fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput {
let rows = Rows::new(props.target).preferred(props.preferred);
let env = Env::of(ui);
let os = env.view().shell().os;
// The text of every menu is worked out once for these inputs and kept: a pass that shows an open menu again writes none of it.
@@ -195,7 +160,6 @@ fn show_bar<E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(props: &mut B
target: props.target,
os,
preferred: props.preferred,
english: props.english,
words: &env.words,
keymap: craft_ui::runtime::commands::keymap_generation(ui.ctx()),
};
@@ -213,7 +177,7 @@ fn show_bar<E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(props: &mut B
.collect();
// Collecting the search's commands walks every row of every menu: the bar does it only while Help is open.
let bar_model: &MenuBar = props.bar;
let entries = move || entries_of(bar_model, english);
let entries = move || entries_of(bar_model);
let mut bar = Bar::new(props.label.clone(), titles).keyboard(props.keyboard);
if let Some(menu) = props.help {
bar = bar.help(MenuHelp::new(menu, &entries));
@@ -221,15 +185,14 @@ fn show_bar<E: Fn(Labeled<'_>) -> Option<String> + Copy + 'static>(props: &mut B
MenuBarOutput { titles: bar.show(ui).titles }
}
/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the mnemonic and English
/// hooks, the language and the keymap.
/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the preferred mnemonics,
/// the language and the keymap. The English names are part of the model.
#[derive(MemoProps)]
struct LabelKey<'a, #[memo_props(stateless)] E> {
struct LabelKey<'a> {
bar: &'a Tracked<MenuBar>,
target: Target,
os: Os,
preferred: &'a [(&'a str, char)],
english: Option<Stateless<E>>,
words: &'a Words,
keymap: u64,
}
+7 -17
View File
@@ -15,7 +15,7 @@ use craft_ui::runtime::pointer;
use craft_ui::runtime::windows::{WindowAction, WindowHost};
use egui::{Ui, ViewportId};
use crate::bar::{EnglishHook, Labeled, keymap_platform};
use crate::bar::keymap_platform;
use crate::layout::Target;
use crate::model::{Builtin, Item, ItemKind, Node};
@@ -54,22 +54,16 @@ pub(crate) struct BarLabels {
pub(crate) menus: Vec<LevelLabels>,
}
/// How the rows of a menu are written: the target that names the shortcuts, the app's English labels and its
/// preferred mnemonic letters.
/// How the rows of a menu are written: the target that names the shortcuts and the app's preferred mnemonic
/// letters.
pub(crate) struct Rows<'a> {
target: Target,
english: Option<&'a EnglishHook<'a>>,
preferred: &'a [(&'a str, char)],
}
impl<'a> Rows<'a> {
pub(crate) fn new(target: Target) -> Self {
Rows { target, english: None, preferred: &[] }
}
pub(crate) fn english(mut self, english: Option<&'a EnglishHook<'a>>) -> Self {
self.english = english;
self
Rows { target, preferred: &[] }
}
pub(crate) fn preferred(mut self, preferred: &'a [(&'a str, char)]) -> Self {
@@ -112,10 +106,6 @@ impl<'a> Rows<'a> {
self.preferred.iter().find(|(k, _)| *k == key).map(|(_, c)| *c)
}
pub(crate) fn english_of(&self, labeled: Labeled<'_>) -> Option<String> {
self.english.and_then(|hook| hook(labeled))
}
/// The label a node shows as the menu's sibling, for the preferred letters and the English labels.
pub(crate) fn node_labels(&self, nodes: &[Node]) -> Vec<String> {
let shown: Vec<&Node> = nodes.iter().filter(|node| !matches!(node, Node::Separator | Node::Standard { .. })).collect();
@@ -133,8 +123,8 @@ impl<'a> Rows<'a> {
_ => "",
},
|node| match node {
Node::Item(item) => self.english_of(Labeled::Command(&item.command)),
Node::Submenu { label, .. } => self.english_of(Labeled::Title(label)),
Node::Item(item) => item.english.clone(),
Node::Submenu { english, .. } => english.clone(),
_ => None,
},
)
@@ -164,7 +154,7 @@ impl<'a> Rows<'a> {
/// The text of a whole bar: the titles and each menu's rows.
pub(crate) fn bar_labels(&self, menus: &[crate::model::Menu], platform: Platform) -> BarLabels {
let titles = self.labels(menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| self.english_of(Labeled::Title(&menu.title)));
let titles = self.labels(menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| menu.english.clone());
BarLabels { titles, menus: menus.iter().map(|menu| self.level_labels(&menu.children, platform)).collect() }
}
+26 -8
View File
@@ -103,6 +103,11 @@ impl<'a> LayoutOptions<'a> {
(self.label)(english).replace("{app}", self.app_name)
}
/// The English text of a label `text` writes, `{app}` filled in.
fn english_text(&self, english: &'static str) -> String {
english.replace("{app}", self.app_name)
}
fn standard(&self, kind: Standard) -> Node {
Node::Standard { kind, label: self.text(kind.english()) }
}
@@ -181,6 +186,7 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout {
let mut menu = Vec::new();
if let Some(Node::Item(mut it)) = about {
it.label = options.text("About {app}");
it.english = Some(options.english_text("About {app}"));
menu.extend([Node::Item(it), Node::Separator]);
}
if let Some(s) = settings {
@@ -188,8 +194,9 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout {
menu.push(settings_node(s, comma, options, &mut clashes));
}
if let Some(mut l) = language {
if let Node::Submenu { label, .. } = &mut l {
if let Node::Submenu { label, english, .. } = &mut l {
*label = options.text("Language");
*english = Some("Language".to_owned());
}
menu.push(l);
}
@@ -228,6 +235,7 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout {
_ => Item::new(Builtin::Quit.command(), "").role(ItemRole::Quit),
};
quit.label = options.text("Quit {app}");
quit.english = Some(options.english_text("Quit {app}"));
match taken(CMD_Q, std::slice::from_ref(&quit.command)) {
Some(command) => {
clashes.push(Clash { shortcut: CMD_Q, system: "Quit", command, resolution: "Quit has no shortcut" });
@@ -349,15 +357,19 @@ fn desktop_bar(bar: &MenuBar, target: Target, quit: Option<&'static str>, option
_ => Item::new(Builtin::Quit.command(), "").role(ItemRole::Quit),
};
it.label = options.text(label);
it.english = Some(options.english_text(label));
ensure_menu(&mut bar, MenuRole::File, "File", options).children.extend([Node::Separator, Node::Item(it)]);
}
if let Some(s) = settings {
let s = match s {
Node::Item(mut it) => {
it.label = options.text("Preferences…");
it.english = Some("Preferences…".to_owned());
Node::Item(it)
}
Node::Submenu { children, role, platforms, .. } => Node::Submenu { label: options.text("Preferences"), children, role, platforms },
Node::Submenu { children, role, platforms, .. } => {
Node::Submenu { label: options.text("Preferences"), english: Some("Preferences".to_owned()), children, role, platforms }
}
other => other,
};
ensure_menu(&mut bar, MenuRole::Edit, "Edit", options).children.extend([Node::Separator, s]);
@@ -370,6 +382,7 @@ fn desktop_bar(bar: &MenuBar, target: Target, quit: Option<&'static str>, option
}
if let Some(Node::Item(mut it)) = about {
it.label = options.text("About {app}");
it.english = Some(options.english_text("About {app}"));
ensure_menu(&mut bar, MenuRole::Help, "Help", options).children.extend([Node::Separator, Node::Item(it)]);
}
finish(&mut bar, |_| false);
@@ -383,9 +396,13 @@ fn shown_on(bar: &MenuBar, target: Target) -> MenuBar {
let shown = nodes.iter().filter_map(|n| match n {
Node::Item(it) if !it.platforms.contains(on) => None,
Node::Submenu { platforms, .. } if !platforms.contains(on) => None,
Node::Submenu { label, children, role, platforms } => {
Some(Node::Submenu { label: label.clone(), children: keep(children, on, appkit), role: *role, platforms: *platforms })
}
Node::Submenu { label, english, children, role, platforms } => Some(Node::Submenu {
label: label.clone(),
english: english.clone(),
children: keep(children, on, appkit),
role: *role,
platforms: *platforms,
}),
Node::Standard { .. } if !appkit => None,
other => Some(other.clone()),
});
@@ -420,7 +437,7 @@ fn ensure_menu<'b>(bar: &'b mut MenuBar, role: MenuRole, english: &'static str,
MenuRole::Help => bar.menus.len(),
_ => bar.menus.iter().position(|m| m.role == MenuRole::Help).unwrap_or(bar.menus.len()),
};
bar.menus.insert(at, Menu::new(options.text(english), Vec::new()).role(role));
bar.menus.insert(at, Menu::new(options.text(english), Vec::new()).english(english).role(role));
at
}
};
@@ -450,6 +467,7 @@ fn settings_node(node: Node, comma_taken: Option<CommandRef>, options: &LayoutOp
match node {
Node::Item(mut it) => {
it.label = options.text("Settings…");
it.english = Some("Settings…".to_owned());
give(&mut it);
Node::Item(it)
}
@@ -457,7 +475,7 @@ fn settings_node(node: Node, comma_taken: Option<CommandRef>, options: &LayoutOp
if let Some(Node::Item(first)) = children.iter_mut().find(|n| matches!(n, Node::Item(i) if i.enabled)) {
give(first);
}
Node::Submenu { label: options.text("Settings"), children, role, platforms }
Node::Submenu { label: options.text("Settings"), english: Some("Settings".to_owned()), children, role, platforms }
}
other => other,
}
@@ -478,7 +496,7 @@ fn appearance_node(bar: &mut MenuBar, options: &LayoutOptions) -> Vec<Node> {
children.push(Node::Separator);
children.extend(items);
}
vec![Node::Submenu { label: options.text("Appearance"), children, role, platforms }]
vec![Node::Submenu { label: options.text("Appearance"), english: Some("Appearance".to_owned()), children, role, platforms }]
}
_ => items,
}
+1 -1
View File
@@ -114,7 +114,7 @@ pub mod mac;
pub mod ribbon;
pub mod shortcuts;
pub use bar::{EnglishHook, Labeled, MenuBarOutput, MenuBarUi};
pub use bar::{MenuBarOutput, MenuBarUi};
pub use craft_keymap::{Chord, CommandRef};
pub use customize::Customization;
pub use documents::DOCUMENT_COMMAND_PREFIX;
+43 -2
View File
@@ -57,6 +57,9 @@ impl Document {
pub struct Menu {
/// The title in the bar.
pub title: String,
/// The title's English name, when `title` is a translation: the bar takes the mnemonic of a title the keyboard
/// can't type from it.
pub english: Option<String>,
/// What the menu is for.
pub role: MenuRole,
/// The menu's entries, top to bottom.
@@ -145,6 +148,8 @@ pub enum Node {
Submenu {
/// The submenu's title.
label: String,
/// The title's English name, when `label` is a translation ([`Menu::english`]).
english: Option<String>,
/// The submenu's entries.
children: Vec<Node>,
/// The place a layout gives it, if any.
@@ -172,6 +177,9 @@ pub struct Item {
pub command: CommandRef,
/// The text shown.
pub label: String,
/// The label's English name, when `label` is a translation. A label the keyboard can't type (Chinese, Japanese,
/// Korean…) takes its mnemonic from it in the in-window bar, and the Help search matches it on every target.
pub english: Option<String>,
/// `cmd` is ⌘ and `ctrl` the Control key: ⌃⌘M and ⌘M are different shortcuts.
pub shortcut: Option<Chord>,
/// Whether the item can be chosen.
@@ -354,6 +362,7 @@ impl Item {
Item {
command: command.into(),
label: label.into(),
english: None,
shortcut: None,
enabled: true,
kind: ItemKind::Plain,
@@ -402,6 +411,12 @@ impl Item {
self
}
/// Set the label's English name ([`Item::english`] field).
pub fn english(mut self, english: impl Into<String>) -> Item {
self.english = Some(english.into());
self
}
/// Show the item only on `platforms`.
pub fn platforms(mut self, platforms: Platforms) -> Item {
self.platforms = platforms;
@@ -435,7 +450,17 @@ impl Node {
/// A submenu shown on every platform.
pub fn submenu(label: impl Into<String>, children: Vec<Node>) -> Node {
Node::Submenu { label: label.into(), children, role: None, platforms: Platforms::ALL }
Node::Submenu { label: label.into(), english: None, children, role: None, platforms: Platforms::ALL }
}
/// Set the English name of an item's label or a submenu's title.
pub fn english(mut self, english: impl Into<String>) -> Node {
match &mut self {
Node::Item(it) => it.english = Some(english.into()),
Node::Submenu { english: e, .. } => *e = Some(english.into()),
Node::Separator | Node::Standard { .. } => {}
}
self
}
/// Give an item or a submenu a role: `Node::submenu("Theme", pages).role(ItemRole::Appearance)`.
@@ -462,7 +487,13 @@ impl Node {
impl Menu {
/// A menu with no special role.
pub fn new(title: impl Into<String>, children: Vec<Node>) -> Menu {
Menu { title: title.into(), role: MenuRole::Other, children }
Menu { title: title.into(), english: None, role: MenuRole::Other, children }
}
/// Set the title's English name ([`Menu::english`] field).
pub fn english(mut self, english: impl Into<String>) -> Menu {
self.english = Some(english.into());
self
}
/// Set the menu's role.
@@ -580,6 +611,8 @@ pub struct Row {
pub command: CommandRef,
/// The text shown.
pub label: String,
/// The label's English name, when `label` is a translation ([`Item::english`]).
pub english: Option<String>,
/// The row's shortcut.
pub shortcut: Option<Chord>,
/// Whether the row can be chosen.
@@ -601,6 +634,7 @@ impl Row {
path: path.iter().map(|s| (*s).to_owned()).collect(),
command: command.into(),
label: label.into(),
english: None,
shortcut: None,
enabled: true,
kind: ItemKind::Plain,
@@ -610,6 +644,12 @@ impl Row {
}
}
/// Set the label's English name.
pub fn english(mut self, english: impl Into<String>) -> Row {
self.english = Some(english.into());
self
}
/// Whether the row can be chosen.
pub fn enabled(mut self, on: bool) -> Row {
self.enabled = on;
@@ -682,6 +722,7 @@ pub fn from_items(tops: &[&str], rows: &[Row]) -> MenuBar {
match slot {
Slot::Leaf(it) if it.label == "---" => out.push(Node::Separator),
Slot::Leaf(it) => out.push(Node::Item(Item {
english: it.english.clone(),
shortcut: it.shortcut,
enabled: it.enabled,
kind: it.kind,
+10 -12
View File
@@ -2,7 +2,6 @@
use craft_ui::menu::HelpEntry;
use crate::bar::{EnglishHook, Labeled};
use crate::model::{Builtin, MenuBar, Node};
use crate::{LayoutOptions, Target, layout};
@@ -18,39 +17,38 @@ impl MenuBar {
/// Building the list lays out the whole bar, so a host caches the result and rebuilds it when the bar
/// changes, not every frame.
///
/// `english` gives a command's or menu title's English name (as [`crate::MenuBarUi::english`]), asked on
/// every target, so the search finds a translated command by its English name.
pub fn help_entries(&self, target: Target, options: &LayoutOptions, english: Option<&EnglishHook<'_>>) -> Vec<HelpEntry> {
entries_of(&layout(self, target, options).bar, english)
/// An item's [`english`](crate::Item::english) name is listed with it, on every target, so the search finds a
/// translated command by its English name.
pub fn help_entries(&self, target: Target, options: &LayoutOptions) -> Vec<HelpEntry> {
entries_of(&layout(self, target, options).bar)
}
}
/// The entries of an already laid-out bar.
pub(crate) fn entries_of(bar: &MenuBar, english: Option<&EnglishHook<'_>>) -> Vec<HelpEntry> {
let english_of = |labeled: Labeled<'_>| english.and_then(|hook| hook(labeled));
pub(crate) fn entries_of(bar: &MenuBar) -> Vec<HelpEntry> {
let mut entries = Vec::new();
let mut path: Vec<String> = Vec::new();
for menu in &bar.menus {
path.push(menu.title.clone());
collect(&menu.children, &mut path, &english_of, &mut entries);
collect(&menu.children, &mut path, &mut entries);
path.pop();
}
entries
}
fn collect(nodes: &[Node], path: &mut Vec<String>, english_of: &dyn Fn(Labeled<'_>) -> Option<String>, entries: &mut Vec<HelpEntry>) {
fn collect(nodes: &[Node], path: &mut Vec<String>, entries: &mut Vec<HelpEntry>) {
for node in nodes {
match node {
Node::Item(item) if Builtin::of(&item.command).is_none() => {
let mut entry = HelpEntry::new(item.command.clone(), item.label.clone()).with_path(path.iter().cloned());
if let Some(english) = english_of(Labeled::Command(&item.command)) {
entry = entry.with_english(english);
if let Some(english) = &item.english {
entry = entry.with_english(english.clone());
}
entries.push(entry);
}
Node::Submenu { label, children, .. } => {
path.push(label.clone());
collect(children, path, english_of, entries);
collect(children, path, entries);
path.pop();
}
Node::Item(_) | Node::Separator | Node::Standard { .. } => {}
+17 -7
View File
@@ -1,5 +1,5 @@
//! The in-window bar is a memoized view: idle frames replay it, a title rename or Alt runs it once, and an open menu
//! runs it while it is open.
//! replays with it while nothing reaches the menu.
use std::cell::RefCell;
use std::rc::Rc;
@@ -67,18 +67,26 @@ fn alt_runs_the_menu_bar_once_each_way() {
assert_eq!(counted(&fixture).0, 1, "Alt up runs the bar once");
}
/// A menu the bar opens is an overlay inside its run, which keeps the run from being replayed while it is open. The
/// run in which the menu's fade ends is the last that shows it, so the replays after it match a real run (the audit).
/// A menu the bar opens is an overlay of its run: with the focus on the menu's first row, an idle frame replays the bar
/// and the open menu, and a key the menu takes runs the bar in its frame.
#[trial]
fn an_open_menu_runs_the_bar_and_closing_it_replays_it() {
fn an_idle_open_menu_replays_and_a_key_in_it_runs_the_bar() {
let bar = Rc::new(RefCell::new(model("File")));
let mut fixture = fixture(&bar);
audit_replays(fixture.ctx(), true);
fixture.key(Key::F, Modifiers::ALT);
fixture.settle();
assert!(fixture.by_label("New").is_some(), "Alt+F opened File");
for _ in 0..3 {
fixture.frame(vec![]);
assert_eq!(counted(&fixture), (0, 1), "an idle frame replays the bar and its open menu");
assert!(fixture.by_label("New").is_some(), "the replayed menu keeps its rows' nodes");
}
fixture.key(Key::ArrowDown, Modifiers::NONE);
assert!(counted(&fixture).0 > 0, "a key in the open menu runs the bar in its frame");
fixture.settle();
fixture.frame(vec![]);
assert!(counted(&fixture).0 > 0, "the bar runs while a menu is open");
assert_eq!(counted(&fixture), (0, 1), "then the bar replays again");
// The first Escape closes the menu; the bar keeps the keyboard until the second one hands it back.
fixture.key(Key::Escape, Modifiers::NONE);
fixture.settle();
@@ -104,10 +112,12 @@ fn an_idle_bar_and_an_open_menu_build_no_labels() {
fixture.key(Key::F, Modifiers::ALT);
fixture.settle();
assert!(fixture.by_label("New").is_some(), "Alt+F opened File");
fixture.key(Key::ArrowDown, Modifiers::NONE);
assert!(counted(&fixture).0 > 0, "a key in the open menu runs the bar");
assert_eq!(label_builds(&fixture), 0, "and builds no labels");
for _ in 0..3 {
fixture.frame(vec![]);
assert!(counted(&fixture).0 > 0, "the bar runs each pass while a menu is open");
assert_eq!(label_builds(&fixture), 0, "and builds no labels");
assert_eq!(label_builds(&fixture), 0, "an idle open menu builds no labels");
}
}
+13 -8
View File
@@ -5,21 +5,18 @@ use std::sync::Arc;
use craft_host::target::Os;
use craft_host::{AppInfo, Host};
use craft_menu::{CommandRef, Labeled, MenuBarUi, Row, from_items};
use craft_menu::{CommandRef, LayoutOptions, MenuBarUi, Row, Target, from_items};
use craft_ui::contract::Tracked;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers};
#[trial]
fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() {
let bar = Tracked::new(from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建")]));
let english = |labeled: Labeled<'_>| match labeled {
Labeled::Title("文件") => Some("File".to_owned()),
Labeled::Command(command) if *command == CommandRef::new("file.new") => Some("New".to_owned()),
_ => None,
};
let mut bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建").english("New")]);
bar.menus[0].english = Some("File".to_owned());
let bar = Tracked::new(bar);
let mut fixture = Fixture::new(move |ui| {
MenuBarUi::new(&bar).english(english).show(ui);
MenuBarUi::new(&bar).show(ui);
});
// A Mac bar has no letters.
fixture.os(Os::Linux);
@@ -30,6 +27,14 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() {
assert!(fixture.by_label("新建(N)").is_some(), "Alt+F opens the title's menu, whose row shows its own English letter");
}
#[trial]
fn help_search_lists_an_item_by_its_english_name_in_a_translated_model() {
let bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建").english("New")]);
let entries = bar.help_entries(Target::Linux, &LayoutOptions::new("Sample"));
let entry = entries.iter().find(|entry| *entry.command() == CommandRef::new("file.new")).expect("the command is listed");
assert_eq!(entry.english().map(|label| label.as_str()), Some("New"));
}
/// A host whose interface language is Turkish, with an empty catalog.
pub(crate) fn turkish() -> Arc<Host> {
let (i18n, _) = craft_i18n::I18n::from_owned([("tr".to_owned(), String::new(), String::new())], &["tr"]);
+1 -1
View File
@@ -22,7 +22,7 @@ mod picker;
#[cfg(feature = "suite")]
pub(crate) mod stories;
pub use picker::{NamedStyleRow, StylePreview, style_rows};
pub use picker::{NamedStyleRow, StylePreview, style_source};
craft_ui::words! {
/// The panels' words, English by default.
+12 -7
View File
@@ -1,13 +1,14 @@
//! The rows of the style picker: the document's named styles as the rows of a `PresetPicker`.
//! The presets of the style picker: the document's named styles as the source of a `PresetPicker`.
use crate::styles::{group_by_folder, style_leaf};
use craft_behavior::IconId;
use craft_theme::Rgba;
use craft_ui::patterns::presets::{PresetKey, PresetRow};
use craft_ui::patterns::presets::{PresetFns, PresetKey, PresetRow, PresetSource};
use craft_ui::runtime::env::Env;
use craft_ui::style::TypeRole;
/// What a style row shows before its name.
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub enum StylePreview {
/// A swatch (colour and fill styles).
@@ -25,7 +26,7 @@ pub enum StylePreview {
}
/// One style in the picker; its folder is the name's ([`crate::styles::style_folder`]).
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct NamedStyleRow {
/// The style's id.
@@ -59,11 +60,15 @@ impl NamedStyleRow {
}
}
/// The picker's rows: styles with no folder first, then each folder as a group row over its styles, in order of
/// The picker's presets: styles with no folder first, then each folder as a group row over its styles, in order of
/// first appearance. A style's key is `PresetKey::Item(id)`.
pub fn style_rows(styles: &[NamedStyleRow]) -> Vec<PresetRow<PresetKey<u64>>> {
pub fn style_source(styles: &[NamedStyleRow]) -> PresetSource<'_, PresetKey<u64>> {
PresetSource::new(styles, PresetFns::new(style_rows))
}
fn style_rows(styles: &&[NamedStyleRow], _: &Env) -> Vec<PresetRow<PresetKey<u64>>> {
let mut rows = Vec::new();
for (folder, group) in group_by_folder(styles, |style: &NamedStyleRow| style.name.as_str()) {
for (folder, group) in group_by_folder(*styles, |style: &NamedStyleRow| style.name.as_str()) {
let depth = usize::from(!folder.is_empty());
if depth == 1 {
rows.push(PresetRow::group(PresetKey::group([folder.clone()]), folder.clone(), 0).count(group.len()));
+3 -2
View File
@@ -1,6 +1,6 @@
//! Stories of `TextStylesPanel` and of the style picker built on `PresetPicker`.
use super::{NamedStyleRow, StylePreview, TextStyleKind, TextStyleRow, TextStylesPanel, style_rows};
use super::{NamedStyleRow, StylePreview, TextStyleKind, TextStyleRow, TextStylesPanel, style_source};
use craft_behavior::{IconId, Mixed, Selection};
use craft_ui::patterns::presets::{PresetKey, PresetPicker, PresetState};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
@@ -54,7 +54,8 @@ fn picker_styles() -> Vec<NamedStyleRow> {
#[story(TextStylesPanel<'static>, covers = [], drive = Drive::Never)]
fn style_picker_over_style_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rows = style_rows(&picker_styles());
let styles = picker_styles();
let rows = style_source(&styles);
let ((applied, state), picker_at) = data.value_at("picker", (Mixed::Same(Some(PresetKey::Item(2_u64))), PresetState::<PresetKey<u64>>::new()));
PresetPicker::new("Style", picker_at.bind_mixed(applied), &rows, picker_at.bind(state)).show(ui).into()
}
+7 -1
View File
@@ -10,7 +10,13 @@ description = "Tracked<T>: app data whose every write moves a revision, so a rea
[lints]
workspace = true
# No dependencies, so engine crates can hold and move a revision without the UI.
# No dependencies but an optional serde, so engine crates can hold and move a revision without the UI.
[dependencies]
serde = { workspace = true, optional = true }
[features]
# `Serialize` and `Deserialize` for `Tracked<T>`: saved as its value, loaded as a new source.
serde = ["dep:serde"]
[dev-dependencies]
# `#[derive(PlainData)]` in the doc tests.
+27 -2
View File
@@ -326,13 +326,38 @@ impl<T: PlainData + Clone> Clone for Tracked<T> {
}
}
/// Two values are equal when what they hold is: the revision says which writes a value saw, not what it is.
/// `value`, as a new source at count 0 ([`Tracked::new`]).
impl<T: PlainData> From<T> for Tracked<T> {
fn from(value: T) -> Tracked<T> {
Tracked::new(value)
}
}
/// Equal values compare equal, whatever their revisions.
impl<T: PlainData + PartialEq> PartialEq for Tracked<T> {
fn eq(&self, other: &Self) -> bool {
fn eq(&self, other: &Tracked<T>) -> bool {
self.value == other.value
}
}
impl<T: PlainData + Eq> Eq for Tracked<T> {}
/// Saved as its value.
#[cfg(feature = "serde")]
impl<T: PlainData + serde::Serialize> serde::Serialize for Tracked<T> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.value.serialize(serializer)
}
}
/// Loaded as a new source.
#[cfg(feature = "serde")]
impl<'de, T: PlainData + serde::Deserialize<'de>> serde::Deserialize<'de> for Tracked<T> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Tracked<T>, D::Error> {
T::deserialize(deserializer).map(Tracked::new)
}
}
impl<T: PlainData> Deref for Tracked<T> {
type Target = T;
+6 -1
View File
@@ -70,6 +70,9 @@ pub(super) struct Rules {
pub image: bool,
pub auto_center: bool,
pub fills_uncovered: bool,
/// An edge or corner drag may take the frame past `bounds`: the crop grows the canvas there, as in the reference
/// application (a document crop, not one bounded by a placed picture's source).
pub resize_grows: bool,
/// The canvas's snapping, with this pass's tolerance.
pub snap: Option<Snap>,
pub os: Platform,
@@ -89,6 +92,7 @@ impl Rules {
/// as it was (a draw not yet sized) or cannot be kept inside.
pub fn proposal(&self, drag: &mut Drag, to: Point, mods: Mods, space: bool) -> Option<CropBox> {
let at = drag.at_press;
let mut grows = false;
let (next, resizing, held) = match &mut drag.kind {
Kind::Draw { anchor, cur, last } => {
if space {
@@ -115,6 +119,7 @@ impl Rules {
} else {
at.resized(*part, by, hold, mods.alt)
};
grows = self.resize_grows;
(next, true, self.ratio.is_some() || mods.shift)
}
Kind::Turn { grab } => {
@@ -137,7 +142,7 @@ impl Rules {
if !next.is_finite() {
return None;
}
match self.bounds {
match self.bounds.filter(|_| !grows) {
Some(bounds) => next.within(bounds, resizing, held).or(Some(drag.last)),
None => Some(next),
}
+3 -1
View File
@@ -154,7 +154,8 @@ pub struct CropOverlay<'a> {
#[prop(flag)]
straighten: bool,
/// The area the frame may not leave, in document units. An image-mode turn moves or shrinks the frame to keep it
/// inside (Command keeps it as it was at the press).
/// inside (Command keeps it as it was at the press). An edge or corner drag of a document crop may still take it
/// past them: the crop grows the canvas.
#[prop]
bounds: Option<DocRect>,
/// Image mode: the frame stays upright on screen and a move or turn moves or turns the view instead.
@@ -232,6 +233,7 @@ impl<'a> CropOverlay<'a> {
image: self.image_mode,
auto_center: self.auto_center,
fills_uncovered: self.fills_uncovered,
resize_grows: matches!(self.scope, CropScope::Document),
snap: canvas_snap(env),
os: env.shell().os,
}
+27
View File
@@ -803,6 +803,33 @@ fn a_shift_corner_follows_the_diagonal_and_snaps_along_it() {
assert!(rig.seen.borrow().snapped.is_empty(), "no snap line reported");
}
#[trial]
fn a_document_crop_grows_past_its_bounds_on_an_edge_or_corner_drag_only() {
// The canvas as the bounds, as the Crop tool sets them with Delete Cropped Pixels on.
let canvas = Rect::new(50.0, 50.0, 350.0, 250.0);
for (what, base) in [("classic", Setup::new()), ("image mode", Setup::image(0.0, false))] {
let mut setup = base;
setup.bounds = Some(canvas);
// An edge dragged past the canvas takes the frame with it: the crop grows the canvas there.
let mut rig = Rig::new(CropBox::upright(RECT), setup.clone());
rig.drag(rig.at(RECT.x1, 150.0), rig.at(380.0, 150.0), Modifiers::NONE);
let r = rig.rect();
assert!((r.x1 - 380.0).abs() < 1e-6 && r.x0 == RECT.x0, "{what}: the right edge follows past the canvas: {r:?}");
// So does a corner.
let mut rig = Rig::new(CropBox::upright(RECT), setup.clone());
rig.drag(rig.at(RECT.x1, RECT.y1), rig.at(380.0, 280.0), Modifiers::NONE);
let r = rig.rect();
assert!(r.x1 > canvas.x1 + 1.0 && r.y1 > canvas.y1 + 1.0, "{what}: the corner follows past the canvas: {r:?}");
}
// A classic move still stops at the canvas.
let mut setup = Setup::new();
setup.bounds = Some(canvas);
let mut rig = Rig::new(CropBox::upright(RECT), setup);
rig.drag(rig.at(200.0, 150.0), rig.at(300.0, 150.0), Modifiers::NONE);
let r = rig.rect();
assert!(r.x1 <= canvas.x1 + 1e-6 && (r.width() - RECT.width()).abs() < 1e-6, "a move stays inside: {r:?}");
}
#[trial]
fn an_object_crop_is_bounded_by_its_source_and_a_press_outside_it_reaches_what_lies_beneath() {
let source = Rect::new(50.0, 50.0, 350.0, 250.0);
@@ -70,7 +70,13 @@ impl BodyHooks<'_> {
if core.resolved.ltr_axis {
scoped.direction = Direction::Ltr;
}
scoped.ink = core.ink;
// A container that paints a fill reads in that fill's ink, so what it holds (an app icon's accent parts, text with
// no colour of its own) does too: OnDark on a brand rail or scrim, OnPanel on a panel nested inside one. A frame
// paints no fill, and a container with no surface paints none either: both keep the ink they sit in.
scoped.ink = match props.surface {
None | Some(SurfaceKind::Frame) => core.ink,
Some(kind) => kind.ink(),
};
scoped.start_room();
// An inside label and a filling cell are their control's alone: a container shows neither to what it holds.
scoped.inside_label = None;
+3 -3
View File
@@ -10,19 +10,19 @@ const NO_LABEL: Label = Label::Empty;
/// A row of entries: an item that reports its value when picked, a heading over a group of items, or a separator
/// between groups of items.
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)]
pub struct Entry<T> {
row: Row<T>,
}
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)]
enum Row<T> {
Item(Item<T>),
Heading(Label),
Separator,
}
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)]
struct Item<T> {
value: T,
label: Label,
@@ -1,6 +1,8 @@
//! Requests to a collection's item step from outside it, taken at the collection's next pass.
//! Requests to a collection's item step from outside it, taken at the collection's next pass. Each request moves the
//! `Requests` input and each take reads it, so a pending request runs the memoized view that takes it.
use crate::runtime::egui::memory as store;
use crate::runtime::inputs::{self, Input};
use egui::{Context, Id};
/// The rename requests not yet taken: the collection and the key to rename.
@@ -24,11 +26,13 @@ pub fn request_rename<K: Clone + Send + Sync + 'static>(ctx: &Context, collectio
requests.0.retain(|(id, _)| *id != collection);
requests.0.push((collection, key.clone()));
});
inputs::bump(ctx, Input::Requests);
crate::runtime::egui::repaint::request_of(ctx, crate::runtime::egui::pass::current_viewport(ctx));
}
/// The rename request addressed to `collection`, once.
pub(super) fn take_rename<K: Send + Sync + 'static>(ctx: &Context, collection: Id) -> Option<K> {
crate::runtime::replay::note_input(ctx, Input::Requests);
store::Service::<RenameRequests<K>>::run(ctx, |requests| {
let at = requests.0.iter().position(|(id, _)| *id == collection)?;
Some(requests.0.remove(at).1)
+20
View File
@@ -88,6 +88,7 @@ impl Lazy {
_ => None,
};
let available = cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width));
let available = if memo { on_row_line(ui, id, available) } else { available };
let sizing = ui.is_sizing_pass();
// The child is not part of its body's transcript: in a real run it counts there by its extent, whether it
// runs or not, so what scrolls into reach does not change the body's content.
@@ -123,6 +124,7 @@ impl Lazy {
layout,
pixels_per_point: ctx.pixels_per_point(),
atlas: ctx.fonts(|fonts| fonts.atlas_generation()),
opacity: ui.opacity(),
env: Env::of(ui).key,
fits: Env::of(ui).view_fits(),
};
@@ -304,6 +306,24 @@ fn place_view(ui: &mut Ui, rect: Rect) -> Rect {
rect
}
/// The room of the memoized view `id` in the flow region `room` of `ui`. Its content starts a layout room of its own
/// (`Env::start_room`), so it would sit at the top of the unwrapped `Row` around it; as a child placed in flow
/// (`place_in_cell`), a view of one line sits with its centre on the row's line instead: its room moves down by the
/// whole pixels that put the centre of the extent it took (in this pass's measuring run, else its last run) there. A
/// view taller than that reaches, and a view no run showed yet, stays at the row's top. The room keeps its size, so a
/// kept run replays moved with it.
fn on_row_line(ui: &Ui, id: egui::Id, room: Rect) -> Rect {
let Some(centre) = Env::of(ui).row_line.and_then(|line| line.centre) else {
return room;
};
let Some(size) = lazy::last_extent(ui.ctx(), id) else {
return room;
};
let pixels_per_point = ui.ctx().pixels_per_point();
let above = ((centre - size.y / 2.0) * pixels_per_point).round() / pixels_per_point;
if above.is_finite() && above > 0.0 { room.translate(Vec2::new(0.0, above)) } else { room }
}
/// What a child came to in a pass.
pub(super) enum Shown<R> {
/// It ran and returned this.
+21
View File
@@ -951,6 +951,20 @@ impl MemoProps for craft_theme::Srgba {
}
}
impl MemoProps for craft_theme::Rgba {
fn key(&self, key: &mut MemoKey) {
let craft_theme::Rgba(channels) = *self;
channels.key(key);
}
}
/// Derived `Hash` over a unit enum.
impl MemoProps for craft_theme::TypeRole {
fn key(&self, key: &mut MemoKey) {
key.feed_hash(self);
}
}
/// Derived `Hash` (`#[non_exhaustive]`).
impl MemoProps for craft_theme::variant::Tone {
fn key(&self, key: &mut MemoKey) {
@@ -1041,6 +1055,13 @@ impl MemoProps for craft_host::target::WindowKind {
}
}
/// Derived `Hash` (the layer's order and id).
impl MemoProps for crate::runtime::egui::areas::LayerKey {
fn key(&self, key: &mut MemoKey) {
key.feed_hash(self);
}
}
/// Derived `Hash` (an opaque hash value).
impl MemoProps for egui::Id {
fn key(&self, key: &mut MemoKey) {
+16 -7
View File
@@ -15,15 +15,22 @@ use std::sync::Arc;
/// it adds that run again (paint, widgets, accessibility nodes, focus stops and the other per-pass
/// registrations) and returns what that run returned. It runs in a pass where its key differs, or where any of these
/// holds:
/// - the pointer is over it or was in its last run, a press started on it, or one of its widgets is dragged or holds
/// focus, or did;
/// - the pointer is over it or an overlay layer it shows, or was in its last run, a press started on either, or one of
/// its widgets is dragged, or was;
/// - the focus moved into, out of or within it, or, while the focus is in it, a key, text, IME, clipboard or AccessKit
/// event came;
/// - an intent of the pass is routed to a component in it (an AccessKit request on one of its nodes);
/// - an animation in it is not at its end, a texture it shows is still loading, something in it asked for a repaint
/// (`frame::request_repaint`), or a wake time it asked for came;
/// - a bound value, inspection record or command state it read changed;
/// - its place differs from its last run (see below), or the shown life of a component it showed ended;
/// - its last run asked for a discard pass or did something a replay cannot repeat (an overlay, paint on another
/// layer).
/// - it shows an overlay layer and a press came anywhere, a close waits for the layer, or the layers or the window's
/// safe rect changed;
/// - its last run asked for a discard pass or did something a replay cannot repeat (paint on a layer that is neither
/// its own nor an overlay it shows, a window of another viewport).
///
/// An overlay it shows is part of its run: a replay shows the layer again, with its paint, widgets, nodes, focus scope
/// and layer stack entry, at the place of the run. A view that shows one replays only at the room and clip it ran in.
///
/// Input elsewhere in the window and repaint requests outside it do not run it: what they change in the data it shows
/// reaches it through its props.
@@ -44,8 +51,8 @@ use std::sync::Arc;
/// - what the scope around it hands down beyond those (enabled, read-only, size, ink, the command chain, motion, every
/// app value, and the rest of `Scoped::scope_key`), in the key;
/// - the framework inputs it reads outside its props (`runtime::inputs`: the modifiers, the pointer, the keys held, the
/// window facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the scroll view of a nested
/// `Lazy`): a change of one runs only the views that read it;
/// window facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the requests to collections,
/// the scroll view of a nested `Lazy`): a change of one runs only the views that read it;
/// - the clock, read through `frame::stepped_clock`: the view runs at the next step;
/// - commands sent to a command scope instance inside it: it runs while one waits.
///
@@ -110,7 +117,9 @@ impl<P: MemoProps, R: Clone + PartialEq + Shift + Send + Sync + 'static> MemoVie
let env = Env::of(ui);
let key = Self::key(&ctx, &env, &props, show);
let shown = lazy.run_keyed(ui, std::any::type_name::<P>(), crate::runtime::lazy::Key::Memo(key), |ui, run| {
// The content is a layout room of its own: the flow of the body around it does not reach in.
// The content is a layout room of its own: the flow of the body around it does not reach in. It keeps how
// that body sizes from its content and whether its leaves fit their room (`Scoped::start_view_room`), so
// the view takes what its content used there, as the same content shown without the view would.
let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room));
let out = show(&mut props, ui);
Env::restore(&ctx, installed);
+2
View File
@@ -342,6 +342,8 @@ impl Host for ViewportHost {
return;
}
let ctx = parent.ctx().clone();
// The window's content runs in its own viewport's pass, which no record of this one holds.
crate::runtime::replay::block(&ctx);
let focus = self.overlay.focus;
let mut window_rules = self.overlay.clone();
window_rules.dismiss.outside = Outside::Keep;
@@ -96,8 +96,7 @@ pub(super) fn popup_dismissal(
/// Whether a primary press landed outside the layer, its anchor and the layers opened from inside it.
fn press_outside(ctx: &Context, layer: &Layer<'_>, rect: Rect, anchor: Rect) -> bool {
let Some(press) = pointer::frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin)
else {
let Some(press) = pointer::primary_press(ctx) else {
return false;
};
let inside_family = overlay::family(ctx, layer.id).iter().filter_map(|id| overlay::entry(ctx, *id)).any(|entry| entry.rect.contains(press));
@@ -125,6 +124,8 @@ fn escape(ctx: &Context, layer: &Layer<'_>, scope: Option<FocusPolicy>, inside:
if inside != Some(true) && !(owns_loose && focus_in_no_layer(ctx)) {
return None;
}
// The focus may be in no record of the layer's host: the Escape is read from the events of the frame.
crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Sent);
let step = keys::scope_escape(ctx, policy.cancel, pointer::press_captured(ctx), false)?;
matches!(step, craft_behavior::focus::EscapeStep::CloseScope).then_some(CloseReason::Escape)
}
@@ -181,7 +181,12 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
};
let parent = overlay::drawing_parent(ctx);
let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus);
let spec = LayerSpec { id: area, tier, at: placed.at, interactable: overlay.rank != Rank::Tooltip && !layer.exiting };
let mut spec = LayerSpec { id: area, tier, at: placed.at, interactable: overlay.rank != Rank::Tooltip && !layer.exiting, root: None };
// A popup's or a modal's layer, and any layer while it fades out, has a root node, made before its `Area` shows so
// egui hangs the layer's content below it. A sizing pass of the `Area` reports nothing.
if layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. }) {
spec.root = areas::content_rect(ctx, &spec).map(|rect| access::report_layer(ctx, layer.id, rect, layer.exiting));
}
// The opener of the layer's scope is the stop focused when the layer first appears: egui's modal gate takes focus
// from the widgets below a modal layer by the first pass that shows the layer. A dropdown that keeps its anchor's key
// focus belongs to the component that opened it: a press moves the key focus onto that component only at the end of
@@ -208,8 +213,8 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
// from the opener's inherited env with the layer-local fields fresh, and outside the opener's scopes.
let installed = Env::install_for(ui, layer.env.capture().env());
let real = !ui.is_sizing_pass();
if real && (layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. })) {
access::report_layer(ctx, layer.id, ui.unique_id(), ui.max_rect(), overlay.rank.is_modal(), layer.exiting);
if spec.root.is_some() && layer.exiting {
access::hide_exiting_content(ctx, ui.unique_id());
}
// Every layer is a focus scope, one without a policy (`FocusPolicy::NONE`) included: its stops are the layer's,
// not those of the scope it was opened in, so a trap around it leaves them out (a menu's companion bar).
@@ -226,6 +231,9 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
// checks them. Without the boundary a tooltip's text was checked against the body's kept transcript, which
// asked for a discard pass every other frame while the tooltip showed.
access::scope::outside(ctx, || layout_memory::boundary(ctx, true, || body(ui)));
if real && overlay.rank.is_modal() {
access::report_modal(ctx, layer.id);
}
if real {
focus::pop_scope(ctx);
}
@@ -246,6 +254,10 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
entry.absorbs = overlay.dismiss.outside == Outside::Absorb;
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.
if dismissed.is_some() {
crate::runtime::replay::note_unsettled(ctx);
}
if let Some(nudge) = &nudge {
// `dismissal` above records the press beside the layer (`dismissal.rs`, `note_pressed_outside`), so the nudge
// starts after it and moves the layer from the next pass on.
@@ -359,14 +371,18 @@ fn show_in_popup(
// The layer's content starts from its opener's env, on the popup window's own root: its scale and window facts.
let opener = layer.env.capture().env();
let env = Env::root_of(&ctx).map_or_else(|| opener.clone(), |root| opener.rebase(&root));
let spec = LayerSpec { id: area, tier, at: window.min, interactable: overlay.rank != Rank::Tooltip && !layer.exiting };
let mut spec = LayerSpec { id: area, tier, at: window.min, interactable: overlay.rank != Rank::Tooltip && !layer.exiting, root: None };
// The layer's root node, made before its `Area` shows, as in `host`.
if layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. }) {
spec.root = areas::content_rect(&ctx, &spec).map(|rect| access::report_layer(&ctx, layer.id, rect, layer.exiting));
}
overlay::begin_layer(&ctx, layer.id, tier, layer.exiting, placed.side);
let shown = areas::show_layer(&ctx, &spec, |ui| {
areas::fade(ui, layer.fade * overlay.opacity);
let installed = Env::install_for(ui, env.clone());
let real = !ui.is_sizing_pass();
if real && (layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. })) {
access::report_layer(&ctx, layer.id, ui.unique_id(), ui.max_rect(), overlay.rank.is_modal(), layer.exiting);
if spec.root.is_some() && layer.exiting {
access::hide_exiting_content(&ctx, ui.unique_id());
}
// The focused stop the scope returns to is in the opener's window; the opener's window takes the OS focus
// back when the popup closes (`windows::close_popup`).
@@ -379,6 +395,9 @@ fn show_in_popup(
ui.set_min_size(overlay.size_limits.min.min(placed.room));
}
access::scope::outside(&ctx, || layout_memory::boundary(&ctx, true, || body(ui)));
if real && overlay.rank.is_modal() {
access::report_modal(&ctx, layer.id);
}
if real {
focus::pop_scope(&ctx);
}
@@ -489,6 +508,8 @@ impl Nudge {
/// The layer-stack side of an OS-window mount: records the window as an entry of its viewport's stack (rank, key
/// class, scope; no egui layer) and decides its dismissal after the body ran. `rect` is the window's inner rect.
pub(crate) fn host_window(ctx: &Context, layer: &Layer<'_>, rect: Rect) -> LayerOut {
// The entry stands for a window of another viewport, whose pass no record of this one holds.
crate::runtime::replay::block(ctx);
let overlay = layer.overlay;
let mut memory = recall(layer, ctx);
let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus);
@@ -10,12 +10,11 @@ use craft_behavior::{CancelReason, EditEvent, Gesture, Mixed, Value};
use egui::{Context, Id};
use std::sync::Arc;
/// What a component showed last pass, in one shown slot under its id: the shown copy of its value, the pass its value
/// step last ran in, the `(hovered, focus_visible)` that `PartsCx::hovered` and `focus_visible` read, and its eased
/// What a component showed last pass, in one shown slot under its id: the shown copy of its value, the
/// `(hovered, focus_visible)` that `PartsCx::hovered` and `focus_visible` read, and its eased
/// hover, press and on.
pub(crate) struct Shown<V> {
pub copy: Option<Arc<V>>,
pub drawn: u64,
pub state: ShownState,
}
@@ -38,13 +37,13 @@ impl ShownState {
impl<V> Clone for Shown<V> {
fn clone(&self) -> Self {
Shown { copy: self.copy.clone(), drawn: self.drawn, state: self.state.clone() }
Shown { copy: self.copy.clone(), state: self.state.clone() }
}
}
impl<V> Default for Shown<V> {
fn default() -> Self {
Shown { copy: None, drawn: 0, state: ShownState::default() }
Shown { copy: None, state: ShownState::default() }
}
}
@@ -99,10 +98,9 @@ fn resolve_value<V: Value>(comp: &mut dyn ValueSource<V>, stage: &mut MemoryStag
let slot = gesture_key(id);
let (serial, all_reason) = crate::runtime::edit::latest(stage.ctx());
let mut cancelled = None;
// A component not drawn for a pass loses its press at the end hook; its running gesture ends here, the first pass it is
// drawn again.
let pass_nr = crate::runtime::pointer::pass_of(stage.ctx());
let removed = std::mem::replace(&mut stage.shown::<Shown<V>>(id).drawn, pass_nr).saturating_add(1) < pass_nr;
// A component not shown for a pass, by a run or a replay of one, loses its press at the end hook; its running gesture
// ends here, the first pass it is shown again.
let removed = !crate::runtime::memory::shown_last_pass(stage.ctx(), id);
if stage.shown::<Gesture<V>>(slot).is_running() {
// `(given, value)` of a single-valued binding the app owns.
let host = comp.binding().and_then(|bind| match bind.get() {
+9 -1
View File
@@ -400,7 +400,15 @@ impl<'a> Draw<'a> {
self.initial(rect, letter, StyleColor(color));
return;
}
_ => super::icon::paint(self.painter, self.env.tokens, self.env.direction, rect, icon, self.data != DataMode::Full),
_ => super::icon::paint(
self.painter,
self.env.tokens,
self.env.direction,
rect,
icon,
self.data != DataMode::Full,
self.env.ink == Ink::OnDark,
),
}
match icon.badge {
Some(super::IconMark::Dot(badge)) => {
+12 -5
View File
@@ -268,8 +268,10 @@ pub fn icon_names() -> &'static [&'static str] {
}
/// Paints `spec`'s glyph centred in the square of `rect`'s shorter side; `Draw::icon` adds the badge. `single_ink` paints
/// every layer of an app icon in the one colour: the icon of a component in its disabled state.
pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, rect: Rect, spec: &IconSpec<'_>, single_ink: bool) {
/// every layer of an app icon in the one colour: the icon of a component in its disabled state. `on_dark` is whether
/// the icon stands on a strong fill or scrim (the surface's ink is `Ink::OnDark`): its accent parts then paint in the
/// icon's colour, since `accent.solid` would vanish on the brand fill.
pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, rect: Rect, spec: &IconSpec<'_>, single_ink: bool, on_dark: bool) {
let color = spec.color_in(tokens);
let rtl = direction == Direction::Rtl;
let side = rect.width().min(rect.height());
@@ -283,7 +285,7 @@ pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction,
IconSource::Glyph(glyph) => glyph.paint(painter, tokens, square, color, rtl && glyph.directional() && spec.mirror == Mirror::Auto),
IconSource::Svg(id) => {
if let Some(icon) = SvgIcon::of(tokens, direction, side, id, spec.mirror) {
icon.paint_layers(painter, square, LayerInks::of(tokens, color, single_ink));
icon.paint_layers(painter, square, LayerInks::of(tokens, color, single_ink, on_dark || spec.ink == Ink::OnDark));
}
}
IconSource::Mark(badge) => super::pointer_art::paint_badge(painter, tokens, direction, square, *badge, color),
@@ -396,8 +398,13 @@ impl LayerInks {
}
/// The inks of an icon painted in `color`: the accent parts in `colors.accent.solid` and the fixed parts as drawn,
/// except that with `single_ink` (a disabled component) every layer paints in `color`.
pub(crate) fn of(tokens: &UiTokens, color: Color32, single_ink: bool) -> Self {
/// except that with `single_ink` (a disabled component) every layer paints in `color`, and with `on_dark` (a strong
/// fill or scrim, where the accent colour would vanish) the accent parts paint in `color` and the fixed parts stay
/// as drawn.
pub(crate) fn of(tokens: &UiTokens, color: Color32, single_ink: bool, on_dark: bool) -> Self {
if on_dark && !single_ink {
return LayerInks { ink: color, accent: color, fixed: None };
}
if single_ink {
return LayerInks::single(color);
}
@@ -486,7 +486,7 @@ fn paint_placeholder(cx: &ContentPainterCx<'_>, rect: Rect, paper: Option<DataCo
fn paint_failure(cx: &ContentPainterCx<'_>, rect: Rect) {
let side = cx.tokens.size.icon.sm.min(rect.width().min(rect.height()));
let icon = Rect::from_center_size(rect.center(), vec2(side, side));
crate::primitives::icon::paint(&cx.painter, cx.tokens, cx.direction, icon, &IconSpec::svg(IconId::new("warning")), false);
crate::primitives::icon::paint(&cx.painter, cx.tokens, cx.direction, icon, &IconSpec::svg(IconId::new("warning")), false, false);
}
/// A [`ThumbSource`] for stories and tests in every crate: pictures made from the key and a revision the test sets,
+3 -1
View File
@@ -22,10 +22,12 @@ pub use crate::runtime::egui::access::bounds;
#[doc(hidden)]
pub use emit::SubDecl;
#[doc(hidden)]
pub use emit::layer_root;
#[doc(hidden)]
pub use emit::report_sub;
#[doc(hidden)]
pub use emit::sub_node_id;
pub(crate) use emit::{FaceFacts, Own, PopupShown, report, report_layer};
pub(crate) use emit::{FaceFacts, Own, PopupShown, hide_exiting_content, report, report_layer, report_modal};
pub use live::announce;
pub(crate) use live::{begin_pass as begin_live_pass, end_pass as end_live_pass};
pub use scope::{FieldLabel, FieldLabelRole};
+29 -14
View File
@@ -52,7 +52,7 @@ pub(crate) struct Own<'a> {
/// A popup an anchor shows this pass.
#[derive(Clone, Copy, Debug)]
pub(crate) struct PopupShown {
/// The popup's layer id: the id of its root node.
/// The popup's layer id (its root node is [`layer_root`]'s).
pub id: Id,
pub kind: PopupKind,
pub open: bool,
@@ -257,7 +257,7 @@ pub(crate) fn report(ctx: &Context, own: &Own<'_>) {
let expanded = expanded_of(own.flags, access.expanded.or_else(|| popup.filter(|_| !own.popups_by_part).map(|popup| popup.open)));
let mut relations = access.relations.clone();
relations.labelled_by.extend(name.labelled_by.iter().copied());
relations.controls.extend(own.popups.iter().filter(|popup| popup.open).map(|popup| popup.id));
relations.controls.extend(own.popups.iter().filter(|popup| popup.open).map(|popup| layer_root(popup.id)));
let numeric = access.numeric.as_ref();
let mut spec = NodeSpec::new(own.role);
spec.rect = Some(own.rect);
@@ -419,19 +419,34 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) {
}
}
/// The root node of an overlay layer: the layer's content attaches below it, and a modal layer's root is modal. An
/// exiting layer's root is hidden from the first pass it fades out, so nothing under it is reported while it still
/// paints; the ids stay the same if the layer reopens.
pub(crate) fn report_layer(ctx: &Context, id: Id, content: Id, rect: Rect, modal: bool, exiting: bool) {
adapter::register_parent(ctx, content, id);
/// The id of the root node of the overlay layer `id`. The root has an id of its own: the layer's container component
/// takes the layer's id for its widget and node, inside the layer's content, which attaches below the root.
pub fn layer_root(id: Id) -> Id {
sub(id, "layer")
}
/// Writes the root node of the overlay layer `id`, whose content takes `rect`, and returns its id. The layer's content
/// hangs below it. An exiting layer's root is hidden from the first pass it fades out, so nothing under it is reported
/// while it still paints; the ids stay the same if the layer reopens. Called before the layer's `Area` shows, which
/// egui hangs below the root. The root is a plain container: a modal layer's flag sits on its container component's
/// node ([`report_modal`]), which carries the role, since screen readers drop a container without one.
pub(crate) fn report_layer(ctx: &Context, id: Id, rect: Rect, exiting: bool) -> Id {
let root = layer_root(id);
let mut spec = NodeSpec::layer_root();
spec.rect = Some(rect);
spec.modal = modal;
spec.hidden = exiting;
write_node(ctx, id, &spec);
if exiting {
// The content `Ui` can attach to the viewport rather than to the root (a popup body that names its own
// parent), so it is hidden itself.
adapter::hide(ctx, content);
}
write_node(ctx, root, &spec);
root
}
/// Marks the node of the modal overlay layer `id` modal: the node its container component wrote with the layer's id
/// and its role. Called after the layer's body ran, so the node exists when the component reported it.
pub(crate) fn report_modal(ctx: &Context, id: Id) {
adapter::set_modal(ctx, id);
}
/// Hides the node of the content `Ui` of an exiting overlay layer: a popup body that names its own parent can hang
/// its content outside the layer's root.
pub(crate) fn hide_exiting_content(ctx: &Context, content: Id) {
adapter::hide(ctx, content);
}
+1 -1
View File
@@ -180,7 +180,7 @@ pub trait WindowDropTarget<P> {
/// Where a drop target lies: a rect on an egui layer, in that layer's space. A component's own target lies over its
/// visible rect on its layer; a component that takes drops over an area it does not draw (a preset browser's canvas)
/// names the area with [`DropZone::new`] and registers with [`zone_target`].
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)]
pub struct DropZone {
layer: Layer,
rect: Rect,
+41 -1
View File
@@ -167,8 +167,17 @@ pub(crate) fn pass_through(ctx: &Context, id: Id) {
});
}
/// Reports `id` as the focused node of this pass.
/// Marks the node of `id` modal, when the pass has written it.
pub(crate) fn set_modal(ctx: &Context, id: Id) {
if ctx.has_accesskit_node(id) {
ctx.accesskit_node_builder(id, accesskit::Node::set_modal);
}
}
/// Reports `id` as the focused node of this pass. A replay of the run that reported it reports it again: a view that
/// holds focus replays while nothing reaches it.
pub(crate) fn set_focus(ctx: &Context, id: Id) {
crate::runtime::replay::journal(ctx, || id, |ctx, &id| set_focus(ctx, id));
with_emitted(ctx, |emitted| emitted.focus_set = true);
ctx.set_accesskit_focus(id);
}
@@ -209,6 +218,37 @@ pub(crate) fn register_parent(ctx: &Context, id: Id, parent: Id) {
emit(ctx, id);
}
/// The trials' pass-end check that egui's AccessKit parents of the pass hold no cycle; panics naming the ids of the
/// first one found. egui places a node under the first ancestor that has a node by walking the parents, which a cycle
/// sends into endless recursion when no node of the cycle exists yet: a replay adds a run's nodes in the order they
/// were created, and a run only tolerates a cycle while some node of it already exists.
#[cfg(feature = "testing")]
pub(crate) fn check_parents_acyclic(ctx: &Context) {
let cycle = ctx.with_accesskit_parents(|parents| {
let mut acyclic = IdSet::default();
for &start in parents.keys() {
let mut path: Vec<Id> = Vec::new();
let mut on_path = IdSet::default();
let mut at = Some(start);
while let Some(id) = at.filter(|id| !acyclic.contains(id)) {
if !on_path.insert(id) {
let from = path.iter().position(|on| *on == id).unwrap_or_default();
return Some(path.split_off(from));
}
path.push(id);
at = parents.get(&id).copied();
}
acyclic.extend(path);
}
None
});
let cycle = cycle.flatten();
assert!(
cycle.is_none(),
"the AccessKit parents of the pass hold a cycle: {cycle:?}, each the parent of the one before and the first the parent of the last"
);
}
/// Notes that the runtime emitted the node of `id`.
fn emit(ctx: &Context, id: Id) {
with_emitted(ctx, |emitted| emitted.emit(id));
@@ -86,7 +86,6 @@ pub(crate) struct NodeSpec {
pub disabled: bool,
pub read_only: bool,
pub required: bool,
pub modal: bool,
pub actions: Vec<NodeAction>,
pub custom_actions: Vec<(i32, String)>,
/// The content keeps its left-to-right order under a right-to-left interface.
@@ -133,7 +132,6 @@ impl NodeSpec {
disabled: false,
read_only: false,
required: false,
modal: false,
actions: Vec::new(),
custom_actions: Vec::new(),
ltr_axis: false,
@@ -295,7 +293,6 @@ fn write_states(node: &mut accesskit::Node, spec: &NodeSpec) {
(spec.disabled, accesskit::Node::set_disabled),
(spec.read_only, accesskit::Node::set_read_only),
(spec.required, accesskit::Node::set_required),
(spec.modal, accesskit::Node::set_modal),
] {
if on {
set(node);
+79 -4
View File
@@ -1,5 +1,6 @@
//! `Area` with its left-top pivot, `Order`, sublayers, transform layers and `set_layer_order`.
use crate::runtime::shift::Shift;
#[cfg(feature = "testing")]
use egui::Ui;
use egui::emath::TSTransform;
@@ -211,6 +212,9 @@ pub(crate) struct LayerSpec {
pub at: Pos2,
/// Whether the layer takes input; a tooltip and the ghost layer never do.
pub interactable: bool,
/// The accessibility node the layer's content hangs under, created before the layer shows: egui attaches the
/// layer's `Area`, and through it the content, below it.
pub root: Option<Id>,
}
/// What `show_layer` reports.
@@ -224,20 +228,81 @@ pub(crate) struct LayerShown {
/// Shows an overlay layer: an `Area` with its left-top pivot at `spec.at`, never egui's default pivot. The motion
/// service fades a layer in (`motion::layer_presence`), so egui's own fade-in of a new `Area` is off.
pub(crate) fn show_layer(ctx: &Context, spec: &LayerSpec, body: impl FnOnce(&mut egui::Ui)) -> LayerShown {
let shown = egui::Area::new(spec.id)
let mut sizing = false;
let mut area = egui::Area::new(spec.id)
.fade_in(false)
.order(spec.tier.order())
.pivot(egui::Align2::LEFT_TOP)
.fixed_pos(spec.at)
.constrain(false)
.interactable(spec.interactable)
.show(ctx, body);
.interactable(spec.interactable);
if let Some(root) = spec.root {
area = area.accessibility_parent(root);
}
let shown = area.show(ctx, |ui| {
sizing = ui.is_sizing_pass();
body(ui);
});
register_area(ctx, shown.response.layer_id, sizing);
// The `Area`'s own widget senses a click over the whole layer, beneath the layer's widgets: it stands for none of
// the layer's components.
crate::runtime::pointer::record_layer_widget(ctx, shown.response.id);
LayerShown { rect: shown.response.rect, layer: shown.response.layer_id }
}
/// The rect the content of the layer `spec` shows takes in this pass, before the layer shows: its left-top and the size
/// egui keeps for its `Area`. `None` when the layer shows in an egui sizing pass, which paints and reports nothing.
pub(crate) fn content_rect(ctx: &Context, spec: &LayerSpec) -> Option<Rect> {
egui::AreaState::load(ctx, spec.id).and_then(|state| state.size).map(|size| Rect::from_min_size(spec.at, size))
}
/// What an overlay layer's `Area` keeps in egui's memory for a pass it shows in: its egui layer, its left-top in
/// screen space, its size and whether it takes input.
#[derive(Clone, Copy, Debug, PartialEq)]
struct AreaRecord {
layer: LayerId,
at: Pos2,
size: Vec2,
interactable: bool,
}
/// A replay moves the left-top; the size stays.
impl Shift for AreaRecord {
fn shifted(&self, by: &egui::RecordShift) -> Self {
AreaRecord { at: self.at.shifted(by), ..*self }
}
fn snapped(&self, to: &Self, within: f32) -> Self {
AreaRecord { at: self.at.snapped(&to.at, within), ..*self }
}
}
/// Registers the `Area` of `layer` that was shown now (an egui sizing pass of it when `sizing`) as an overlay of the
/// records open around it, which journal the registration: a replay shows the area again in egui's memory, as shown
/// this pass with the place, size and input it had, so egui finds the layer and orders it. A sizing pass paints
/// nothing and asks for the next pass, so the run that made it runs again.
fn register_area(ctx: &Context, layer: LayerId, sizing: bool) {
let Some(state) = egui::AreaState::load(ctx, layer.id) else { return };
if sizing {
crate::runtime::replay::note_unsettled(ctx);
}
show_again(ctx, &AreaRecord { layer, at: state.left_top_pos(), size: state.size.unwrap_or_default(), interactable: state.interactable });
}
fn show_again(ctx: &Context, area: &AreaRecord) {
crate::runtime::replay::journal(ctx, || *area, show_again);
crate::runtime::replay::note_overlay(ctx, area.layer, Rect::from_min_size(area.at, area.size));
let became = egui::AreaState::load(ctx, area.layer.id).and_then(|state| state.last_became_visible_at);
let state = egui::AreaState {
pivot_pos: Some(area.at),
pivot: egui::Align2::LEFT_TOP,
size: Some(area.size),
interactable: area.interactable,
last_became_visible_at: became,
};
ctx.memory_mut(|memory| memory.areas_mut().set_state(area.layer, state));
}
/// What [`show_cover_layer`] shows: the layer's id and tier, the `screen` it covers, its `scrim`, the `through` canvas
/// left open, and whether it `absorbs` pointer hits.
pub(crate) struct CoverLayer {
@@ -263,6 +328,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) {
Some(clear) => bands(screen, clear).into_iter().filter(|band| band.is_positive()).collect(),
None => vec![screen],
};
let mut sizing = false;
egui::Area::new(id)
.fade_in(false)
.order(tier.order())
@@ -272,6 +338,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) {
.interactable(absorbs)
.sense(Sense::hover())
.show(ctx, |ui| {
sizing = ui.is_sizing_pass();
for rect in covered {
ui.painter().rect_filled(rect, 0.0, scrim);
let absorber = ui.allocate_rect(rect, Sense::click_and_drag());
@@ -279,6 +346,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) {
crate::runtime::egui::access::hide(ui.ctx(), absorber.id);
}
});
register_area(ctx, layer_of(tier, id), sizing);
}
/// The four rects of `screen` around `hole`: above, below, left of and right of it.
@@ -297,8 +365,15 @@ pub(crate) fn layer_rect(ctx: &Context, id: Id) -> Option<Rect> {
}
/// The viewport's safe rect: the room overlays must stay inside, the part of the content rect the user can see on
/// the monitor and above its taskbar. Without a known monitor size it is the whole content rect.
/// the monitor and above its taskbar. Without a known monitor size it is the whole content rect. A tracked input
/// (`Input::Shell`), which the frame's root env observes.
pub(crate) fn safe_rect(ctx: &Context) -> Rect {
crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Shell);
safe_rect_raw(ctx)
}
/// `safe_rect` without noting the read: for the root env, which moves `Input::Shell` by it.
pub(crate) fn safe_rect_raw(ctx: &Context) -> Rect {
let content = ctx.content_rect();
ctx.input(|input| {
let viewport = input.viewport();
+17 -9
View File
@@ -409,14 +409,19 @@ impl Scoped {
self.offered = None;
}
/// Starts the layout room of a memoized view's content (`start_room`). Where a leaf shown here would fit its room
/// (`view_fits`), the leaves of the view's content fit the room the view is given (`Shrink::Fit`). A view that is a
/// unit of a shrinking `Row` sizes from its content along x, as the row counted it: a child that fills there takes
/// its measured width, not the row's flow region a view the row does not narrow is shown in.
/// Starts the layout room of a memoized view's content (`start_room`), keeping whether the enclosing body is a
/// content-sized or a given column, as `start_room` keeps the content axes. The view's content then measures and
/// fills as it would shown without the view: a child that fills takes its measured size where the body sizes from
/// content, never the open room. Where a leaf shown here would fit its room (`view_fits`), the leaves of the view's
/// content fit the room the view is given (`Shrink::Fit`). A view that is a unit of a shrinking `Row` sizes from its
/// content along x, as the row counted it: a child that fills there takes its measured width, not the row's flow
/// region a view the row does not narrow is shown in.
pub(crate) fn start_view_room(&mut self) {
let fits = self.view_fits();
let row_unit = matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_)));
let (content_column, given_column) = (self.content_column, self.given_column);
self.start_room();
(self.content_column, self.given_column) = (content_column, given_column);
if fits {
self.shrink = Some(Shrink::Fit);
}
@@ -435,15 +440,17 @@ impl Scoped {
/// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its
/// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the
/// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line
/// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. The
/// flow fields of the enclosing body are not in it: a memoized view's content starts a layout room of its own
/// (`start_room`). Computed once per scope, on the first view that asks; the bytes it fed are counted then.
/// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. Of
/// the flow fields of the enclosing body only how it sizes from its content is in it: a memoized view's content
/// starts a layout room of its own (`start_view_room`) that keeps those facts. Computed once per scope, on the
/// first view that asks; the bytes it fed are counted then.
pub(crate) fn scope_key(&self) -> u128 {
*self.scope_key.get_or_init(|| {
use crate::contract::{MemoKey, MemoProps as _};
let mut key = MemoKey::of_view(&self.ctx);
key.feed_hash(&(self.enabled, self.read_only, self.size, self.glyphs, self.ink, self.surface, self.wheel));
key.feed_hash(&(self.direction, self.text_direction, self.ids_stable, self.cell_fills, self.least, self.unbounded, self.content));
key.feed_hash(&(self.content_column, self.given_column));
key.feed_hash(&(self.arena, self.roving, self.item, self.row, self.scroll_owner.map(|owner| (owner.id, owner.view))));
self.transform.map(|transform| (transform.scale, transform.offset)).key(&mut key);
self.footer_slot.map(|slot| (slot.owner, slot.size)).key(&mut key);
@@ -540,8 +547,9 @@ impl Env {
let shell = Arc::new(windows::shell_of(ctx, pass::current_viewport(ctx)));
let active = shell.window.active;
let keyboard = Arc::new(crate::runtime::keys::layout_of(ctx));
// The window facts and the layout are tracked inputs: a view that read them runs when they change.
crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Shell, (*shell).clone());
// The window facts, the safe rect and the layout are tracked inputs: a view that read them runs when they change.
let safe = crate::runtime::egui::areas::safe_rect_raw(ctx);
crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Shell, ((*shell).clone(), safe));
crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Keyboard, (*keyboard).clone());
let words = host_words(ctx, host.as_ref());
let key = EnvKey::new(tokens.key(), root.direction, scale, os, active, root.values.style_hash())
+2 -1
View File
@@ -386,7 +386,8 @@ pub(crate) fn replay(ctx: &Context, transcript: &Transcript) {
with(ctx, |state| {
let placed = transcript.placed(state.open.last().map(|(id, _)| *id));
for (id, mut scope) in placed.scopes {
// No replayed scope has a noted opener: an overlay, which notes one, blocks its record.
// A replayed scope keeps the opener the last pass held: an overlay's scope, the one kind that notes an opener,
// took it in the pass that first showed the layer, which ran.
scope.opener = opener(state, id, None, focused);
if scope.entering.is_none() {
state.seen.insert(id, frame);
+5 -1
View File
@@ -645,7 +645,9 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) {
// H0: one press per pass.
let frame = pass::frame_nr(ctx, viewport);
let held_back = PerViewport::<ViewportRecord>::with(ctx, viewport, |record| raw_input::hold_back_presses(&mut events, frame, &mut record.held));
// H3: the key stage strips what the runtime owns; egui decides on a repaint from the events left.
// H3: the key stage strips what the runtime owns; egui decides on a repaint from the events left. The events sent
// to the focus are counted first, before the IME and key stages take theirs.
keys::count_sent(ctx, viewport, &events);
ime::input_hook(ctx, &mut events, viewport);
let (stripped, later) = keys::input_hook(ctx, input, &mut events);
if !later.is_empty() {
@@ -755,6 +757,8 @@ pub(crate) fn end_pass(ui: &mut Ui) {
for prune in prunes {
prune(&ctx, &live);
}
#[cfg(feature = "testing")]
crate::runtime::egui::access::check_parents_acyclic(&ctx);
RUNNING.with(|running| {
let mut running = running.borrow_mut();
if let Some(at) = running.iter().rposition(|pass| pass.ctx == ctx) {
+7 -1
View File
@@ -373,8 +373,14 @@ pub(crate) fn composing(ctx: &Context, owner: Id) -> bool {
current(ctx, |engine| engine.owner == Some(owner) && engine.composing)
}
/// Records the caret rect for the OS candidate window.
/// Records the caret rect for the OS candidate window. A replay of the run that recorded it records it again, so the
/// pass writes the IME output and the OS keeps the IME open for a focused field that replays.
pub(crate) fn note_caret(ctx: &Context, owner: Id, field: Rect, caret: Rect, password: bool) {
crate::runtime::replay::journal(
ctx,
|| (owner, field, caret, password),
|ctx, &(owner, field, caret, password)| note_caret(ctx, owner, field, caret, password),
);
current(ctx, |engine| engine.caret = Some((owner, field, caret, password)));
}
+31 -9
View File
@@ -1,6 +1,7 @@
//! Tracked inputs: the framework inputs a view can read outside its props (the modifiers, the pointer, the window's
//! facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the keys held), each with a generation
//! that moves when its value changes. The accessor that reads one notes it into the records open around the running
//! Tracked inputs: the framework inputs a view can read outside its props (the modifiers, the pointer, its presses, the
//! window's facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the toast queues, the keys held,
//! the events sent to the focus, the requests to collections), each with a generation that moves when its value
//! changes. The accessor that reads one notes it into the records open around the running
//! code (`replay::note_input`); a memoized view's replay is refused when an input its run read has another generation
//! now (`runtime::lazy::settled`), so a change runs only the views that read it, and a view absent while it changed
//! runs when it is shown again.
@@ -20,9 +21,14 @@ pub(crate) enum Input {
Modifiers,
/// The pointer's frame (`pointer::frame`, `pointer::with_pass_pointer`).
Pointer,
/// The pointer's presses and releases, an outside press the layer stack absorbed included (`pointer::primary_press`,
/// `overlay::absorbed_press`): a layer's dismissal reads them, so a press anywhere runs the views that show layers,
/// and a pointer move does not.
Press,
/// The keys held, Caps Lock and whether a key arrived (`keys::input::down`, `keyed`, `lock_keys::caps_lock`).
Keys,
/// The platform and window facts (`EnvView::shell`).
/// The platform and window facts (`EnvView::shell`) and the viewport's safe rect (`areas::safe_rect`): its
/// content rect and the visible part of its monitor.
Shell,
/// The keyboard layout (`EnvView::keyboard_layout`).
Keyboard,
@@ -32,23 +38,36 @@ pub(crate) enum Input {
Drag,
/// Where key focus is (`focus::focused_rec`, `focus_in_scope`, `commands::focus_within`).
Focus,
/// The key, text, IME, clipboard and AccessKit action events of the frame: a run that ends holding focus reads them
/// (`replay::close`), so any such event runs the views the focus is in, and an idle frame replays them.
Sent,
/// The layers shown last frame (`overlay::is_open`, `any_open`, `top`, `family`, `entry`).
Overlays,
/// The cards queued in the running viewport's toast queues (`toast::cards`): a post, a close or an expiry runs the
/// views that show them.
Toasts,
/// The requests to collections from outside them (`items::request_rename`), read by the item step that takes
/// them, so a pending request runs the view that takes it.
Requests,
/// The view of the scroll area a nested `Lazy` child decides by. No generation: compared by value.
Scroll,
}
impl Input {
pub(crate) const ALL: [Input; 10] = [
pub(crate) const ALL: [Input; 14] = [
Input::Modifiers,
Input::Pointer,
Input::Press,
Input::Keys,
Input::Shell,
Input::Keyboard,
Input::Keymap,
Input::Drag,
Input::Focus,
Input::Sent,
Input::Overlays,
Input::Toasts,
Input::Requests,
Input::Scroll,
];
@@ -115,17 +134,20 @@ pub(crate) fn observe<T: PartialEq + Send + Sync + 'static>(ctx: &Context, input
});
}
/// The generation `input` has now. The inputs a pass can change while views run (keys, drag, focus, open layers) are
/// observed here; the pointer and the modifiers by the pointer's begin hook, the window facts and the layout where
/// the frame's root env is built, the keymap by the command board.
/// The generation `input` has now. The inputs a pass can change while views run (keys, drag, focus, open layers, toast
/// queues) are observed here, and so are the events sent to the focus, which the key stage counts; the pointer, its
/// presses and the modifiers by the pointer's begin hook, the window facts and the layout where the frame's root env is built, the
/// keymap by the command board, the requests by each request.
pub(crate) fn generation(ctx: &Context, input: Input) -> u64 {
match input {
Input::Keys => observe(ctx, input, crate::runtime::keys::keys_state(ctx)),
Input::Sent => observe(ctx, input, crate::runtime::keys::sent(ctx)),
Input::Drag => observe(ctx, input, crate::runtime::drag::state(ctx)),
Input::Focus => observe(ctx, input, crate::runtime::focus::focus_state(ctx)),
Input::Overlays => observe(ctx, input, crate::runtime::overlay::open_state(ctx)),
Input::Toasts => observe(ctx, input, crate::runtime::toast::queued(ctx)),
Input::Keymap => return crate::runtime::commands::keymap_built(ctx),
Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Scroll => {}
Input::Modifiers | Input::Pointer | Input::Press | Input::Shell | Input::Keyboard | Input::Requests | Input::Scroll => {}
}
with(ctx, |generations| generations.gens[input as usize])
}
+3 -1
View File
@@ -27,7 +27,7 @@ pub use claims::take_claimed;
pub(crate) use claims::take_first_claimed;
/// The types `Intents` reads and returns, for an app that reads the window's intents (`with_window_intents`).
pub use craft_behavior::{AccessRequest, Intent, MoveMods, NavMove, PartRef};
pub(crate) use input::{claims_press, input_hook, keys_state, queue_nav, take_menu_keys, take_nav};
pub(crate) use input::{claims_press, count_sent, input_hook, keys_state, queue_nav, sent, take_menu_keys, take_nav};
#[doc(hidden)]
pub use input::{down, keyed};
pub use intents::Intents;
@@ -242,6 +242,8 @@ pub(crate) struct Stage {
down: Vec<Key>,
/// The input hook read a key press, typed text or a clipboard event in this pass, withheld ones included.
keyed: bool,
/// How many inputs of the viewport held an event sent to the focus (`count_sent`).
sent: u64,
/// The keys whose press the strip took and whose release it is still to drop.
consumed: Vec<Key>,
shortcuts: Shortcuts,
@@ -2,6 +2,8 @@
use super::current;
use craft_keymap::Chord;
crate::stays!(Chord);
use egui::{Context, Id};
/// Reads the claimed chord: whether it arrived this pass for `id`, consuming it. Also true for a chord
@@ -32,8 +34,10 @@ pub(crate) fn take_first_claimed(ctx: &Context, id: Id, chords: &[Chord]) -> Opt
})
}
/// Records that `owner` has an open edit run: the next Escape cancels the run and stays with the component.
/// Records that `owner` has an open edit run: the next Escape cancels the run and stays with the component. Like the
/// claims below, a replay of the run that recorded it records it again: a focused view replays while nothing reaches it.
pub(crate) fn hold_escape(ctx: &Context, owner: Id) {
crate::runtime::replay::journal(ctx, || owner, |ctx, &owner| hold_escape(ctx, owner));
current(ctx, |stage| stage.open_edits.push(owner));
}
@@ -41,6 +45,7 @@ pub(crate) fn hold_escape(ctx: &Context, owner: Id) {
/// component.
#[doc(hidden)]
pub fn claim(ctx: &Context, owner: Id, chord: Chord) {
crate::runtime::replay::journal(ctx, || (owner, chord), |ctx, &(owner, chord)| claim(ctx, owner, chord));
current(ctx, |stage| stage.claims.push((owner, chord)));
}
@@ -49,6 +54,9 @@ pub fn claim(ctx: &Context, owner: Id, chord: Chord) {
/// keys, Enter and Escape (the window move and size modes, 16.3); the claim lapses when it is not renewed.
#[doc(hidden)]
pub fn capture(ctx: &Context, owner: Id, chord: Chord) {
crate::runtime::replay::journal(ctx, || (owner, chord), |ctx, &(owner, chord)| capture(ctx, owner, chord));
// The captured chord reaches `owner` wherever the focus is: a run that captures reads what is sent.
crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Sent);
current(ctx, |stage| {
if !stage.captures.contains(&(owner, chord)) {
stage.captures.push((owner, chord));
@@ -593,6 +593,33 @@ pub(crate) fn keys_state(ctx: &Context) -> (Vec<Key>, bool, bool) {
(down, keyed, crate::runtime::lock_keys::caps_on(ctx))
}
/// Counts an input of `viewport` whose `events` hold one sent to the focus: a key, text, IME, clipboard or AccessKit
/// action event (`Input::Sent`). Read before any stage takes events, so the IME's and the ones a shortcut takes count.
pub(crate) fn count_sent(ctx: &Context, viewport: ViewportId, events: &[Arrived]) {
let sent = events.iter().any(|arrived| {
matches!(
arrived.event,
egui::Event::Key { .. }
| egui::Event::Text(_)
| egui::Event::Ime(_)
| egui::Event::Copy
| egui::Event::Cut
| egui::Event::Paste(_)
| egui::Event::PasteImage(_)
| egui::Event::MiddleClickPaste { .. }
| egui::Event::AccessKitActionRequest(_)
)
});
if sent {
with(ctx, viewport, |stage| stage.sent += 1);
}
}
/// How many inputs of the running viewport held an event sent to the focus: its value moves with each one.
pub(crate) fn sent(ctx: &Context) -> u64 {
current(ctx, |stage| stage.sent)
}
/// Whether the running viewport's input hook read a key press, typed text or a clipboard event in this pass, the ones
/// the key stage took from egui's input included: an app that redraws state after input asks this, not egui's events.
pub fn keyed(ctx: &Context) -> bool {
+54 -27
View File
@@ -15,7 +15,7 @@
//! framework tracks has changed for it since (`settled`). Its entry outlives a few frames of absence.
use crate::runtime::egui::areas::Layer;
use crate::runtime::egui::{focus as focus_state, input as input_state, pass};
use crate::runtime::egui::{input as input_state, pass};
use crate::runtime::focus::{self, Transcript};
use crate::runtime::frame::{self, PerViewport};
use crate::runtime::inputs::{self, Input};
@@ -166,8 +166,8 @@ pub(crate) struct Measured {
pub(crate) room: Rect,
}
/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, fit and environment, and its
/// record moves with the room's position (`Place::shift_to`).
/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity, fit and
/// environment, and its record moves with the room's position (`Place::shift_to`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Place {
/// The region its parent offered it.
@@ -179,6 +179,9 @@ pub(crate) struct Place {
/// The font atlas the run's text points into (`Fonts::atlas_generation`): egui clears the atlas when it fills up
/// and rebuilds it for new text options, and a kept galley's glyphs then name other glyphs.
pub(crate) atlas: u64,
/// The opacity everything painted in the room is faded to (`Ui::opacity`, a layer fading in or out): the run's
/// colours hold it.
pub(crate) opacity: f32,
/// The scope's environment (`Env::key`): its tokens (theme, density), scale, direction, language and whether the
/// window is active.
pub(crate) env: EnvKey,
@@ -196,9 +199,10 @@ struct Moved {
impl Place {
/// How a run at this place that took `rect` replays at `now`, or `None` when it cannot. The room may have moved; its
/// size, the layer, layout, scale, font atlas and environment are the ones the run had. The record moves by the
/// room's move when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there
/// gives) and, for a move, the record holds nothing a move cannot place (`movable`: no paint callback) on an
/// size, the layer, layout, scale, font atlas, opacity, fit and environment are the ones the run had. A record that
/// shows an overlay replays only at the room and clip of its run (`Record::pinned`). Any other record moves by the
/// room's move when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there gives) and,
/// for a move, the record holds nothing a move cannot place (`Record::movable`: no paint callback) on an
/// untransformed layer (`transformed`: egui's AccessKit bounds are layer space only there). Its clip rects follow
/// the clip when either:
/// - the clip moved with the room (`with_clip`): every rect and clip moves exactly, whatever the clip cut;
@@ -207,16 +211,21 @@ impl Place {
/// so the run's clip becomes the clip now and inner clips move (`RecordShift::clip`).
///
/// Otherwise it runs: a run cut by its clip lacks what was culled.
fn shift_to(&self, rect: Rect, now: Place, movable: bool, transformed: bool) -> Option<Moved> {
fn shift_to(&self, rect: Rect, now: Place, record: &Record, transformed: bool) -> Option<Moved> {
let offset = now.room.min - self.room.min;
let same = now.room.size() == self.room.size()
&& now.layer == self.layer
&& now.layout == self.layout
&& now.pixels_per_point == self.pixels_per_point
&& now.atlas == self.atlas
&& now.opacity == self.opacity
&& now.env == self.env
&& now.fits == self.fits;
let placeable = offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && movable && !transformed);
let placeable = if record.pinned() {
offset == Vec2::ZERO && now.clip == self.clip
} else {
offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && record.movable() && !transformed)
};
if !same || !placeable {
return None;
}
@@ -437,6 +446,12 @@ pub(crate) fn shown(ctx: &Context, owner: Option<Id>, id: Id, sizing: bool, meas
});
}
/// The extent the child `id` took in the last measuring or real run that showed it (this pass's measuring run once it
/// ran), at whatever room it had; `None` before any run showed it.
pub(crate) fn last_extent(ctx: &Context, id: Id) -> Option<Vec2> {
with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.sizes[1].map(|measured| measured.size)))
}
/// Registers what the skipped child `id` registered with the focus service in the last real run that showed it, in
/// the real run that skips it.
pub(crate) fn replay(ctx: &Context, id: Id) {
@@ -460,9 +475,11 @@ pub(crate) fn replay(ctx: &Context, id: Id) {
/// It replays when its last run was in an earlier pass, of this frame or an earlier one, and since then:
/// - nothing in it moves: no animation off its end value, no repaint asked from inside it, no texture it shows still
/// loading, no wake time reached;
/// - the pointer is not over it, no press started on it and none of its widgets is dragged or holds egui focus, and
/// none of that held in its last run;
/// - none of its stops holds focus or is the target of a focus request, now or in its last run;
/// - the pointer is not over it or an overlay layer it shows, no press started on either and none of its widgets is
/// dragged, and none of that held in its last run;
/// - the focus is where its run left it (`replay::Held`: the same stop and egui widget of it, or none), and while the
/// focus is in it no key, text, IME, clipboard or AccessKit event came (`Input::Sent`, which such a run reads);
/// - none of its stops is the target of a focus request, now or in its last run;
/// - no intent of this pass is routed to a component in it (an AccessKit request on one of its nodes);
/// - no value it read (a bound value, an inspection record, a command's state) changed this frame (`note_edit`), or,
/// replaying a run of this frame, after that run started;
@@ -473,8 +490,8 @@ pub(crate) fn replay(ctx: &Context, id: Id) {
/// - the shown life of no component it showed ended (`memory::ended_since`): a replay would show memory state that is
/// gone;
/// - no framework input its run read outside its props has moved (`runtime::inputs`), the scroll view a nested `Lazy`
/// child of it decided by is the same (moved with it, `moved`), and no command waits for a command scope instance of
/// it.
/// child of it decided by is the same (moved with it, `moved`), no command waits for a command scope instance of
/// it, and no close waits for a layer it shows.
pub(crate) fn settled(
ctx: &Context,
owner: Option<Id>,
@@ -484,10 +501,11 @@ pub(crate) fn settled(
view: Option<View>,
key: Key,
) -> Option<(Vec2, Rect, RecordShift)> {
let targets = focus::targets(ctx);
let revealed = focus::targets(ctx)[1];
let routed = crate::runtime::keys::routed_to(ctx);
let now = frame::clock(ctx);
let held = (input_state::dragged(ctx), focus_state::focused(ctx));
let dragged = input_state::dragged(ctx);
let focused = replay::Held::focused(ctx);
let transformed = place.is_some_and(|place| ctx.layer_transform_to_global(place.layer).is_some());
let settled = write(ctx, id, |store, pass_nr, frame| {
let changes = &store.changes;
@@ -510,9 +528,10 @@ pub(crate) fn settled(
&& !facts.blocked
&& !facts.discards
&& facts.quiet(now, edited.as_ref())
&& !settled.record.focus.stop_ids().any(|stop| targets.contains(&Some(stop)) || routed.contains(&stop))
&& !settled.record.focus.stop_ids().any(|stop| revealed == Some(stop) || routed.contains(&stop))
&& !routed.iter().any(|id| settled.record.widgets.contains(id))
&& ![held.0, held.1].iter().flatten().any(|widget| settled.record.widgets.contains(widget))
&& !dragged.is_some_and(|widget| settled.record.widgets.contains(&widget))
&& focused.within(&settled.record.focus, &settled.record.widgets) == settled.record.held
});
entry.replays = Some((pass_nr, replays));
replays
@@ -520,7 +539,7 @@ pub(crate) fn settled(
};
// A measuring run cannot tell the place: it replays where the run was.
let moved = |settled: &Settled| match place {
Some(place) => settled.place.shift_to(settled.rect, place, settled.record.movable(), transformed),
Some(place) => settled.place.shift_to(settled.rect, place, &settled.record, transformed),
None => Some(Moved { shift: RecordShift::none(settled.place.clip), with_clip: true }),
};
let settled = entry.settled.clone().filter(|_| replays && keyed).and_then(|settled| Some((moved(&settled)?, settled)));
@@ -543,7 +562,7 @@ pub(crate) fn settled(
// The scroll view a nested child decided by: the run's, moved with the record, while the clip moved with it; a run
// that lay wholly in its clip ran every nested child, which holds at any view.
let view = place.and_then(|_| with_clip.then(|| (settled.view.map(|ran| ran.moved(shift.offset)), view)));
if engaged(ctx, settled.place.layer, rect.intersect(shift.clip))
if engaged(ctx, settled.place.layer, rect.intersect(shift.clip), &settled.record.facts.overlays)
|| crate::runtime::memory::ended_since(ctx, &settled.record.facts.owners, settled.lives)
|| moved(ctx, &settled, view)
{
@@ -560,18 +579,26 @@ pub(crate) fn settled(
/// Whether something a memoized view's run read outside its props moved since: a framework input it read has another
/// generation, the scroll view a nested `Lazy` child decided by is another than the one it needs (`view`: the view it
/// needs and the view now, in a real run whose record replays only in that view; a measuring run lays the content out
/// from offset zero, so its view is not the one the real run decided by), or a command waits for one of its instances.
/// from offset zero, so its view is not the one the real run decided by), a command waits for one of its instances,
/// or a close waits for a layer it shows.
fn moved(ctx: &Context, settled: &Settled, view: Option<(Option<View>, Option<View>)>) -> bool {
let facts = &settled.record.facts;
inputs::moved(ctx, facts.inputs, &settled.seen)
|| (facts.inputs.contains(Input::Scroll) && view.is_some_and(|(needs, now)| needs != now))
|| crate::runtime::commands::queued_for(ctx, &facts.instances)
|| crate::runtime::overlay::close_queued(ctx, &facts.layers)
}
/// Whether the pointer is over `rect` (shown) on `layer`, or a press that is held started there.
fn engaged(ctx: &Context, layer: Layer, rect: Rect) -> bool {
let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect);
ctx.rect_contains_pointer(layer, rect) || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin))
/// Whether the pointer is over `rect` (shown) on `layer` or over one of the overlay layers `overlays` shown, or a
/// press that is held started there. Both halves ask whether the layer is the top layer at the point, so a pointer or
/// a press on an overlay above the view leaves it alone.
fn engaged(ctx: &Context, layer: Layer, rect: Rect, overlays: &[replay::ShownLayer]) -> bool {
let over = |layer: Layer, rect: Rect| {
let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect);
ctx.rect_contains_pointer(layer, rect)
|| input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer))
};
over(layer, rect) || overlays.iter().any(|shown| over(shown.layer, shown.rect))
}
/// Adds the last real run of the memoized view `id` to the running pass, in place of running it, at the place `shift`
@@ -637,11 +664,11 @@ pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rec
if ctx.will_discard() {
return;
}
let targets = focus::targets(ctx);
let engaged_now = record.focus.stop_ids().any(|stop| targets.contains(&Some(stop)));
let revealed = focus::targets(ctx)[1];
let engaged_now = record.focus.stop_ids().any(|stop| revealed == Some(stop));
let lives = crate::runtime::memory::ended_generation(ctx);
let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now, key, pass: 0, edits, output, lives, seen, view };
settled.engaged |= engaged(ctx, place.layer, rect.intersect(place.clip));
settled.engaged |= engaged(ctx, place.layer, rect.intersect(place.clip), &settled.record.facts.overlays);
with(ctx, |store, pass_nr, frame| {
settled.frame = frame;
settled.pass = pass_nr;
+20 -1
View File
@@ -203,6 +203,8 @@ struct OwnerRecord {
viewport: ViewportId,
pass: u64,
at: f64,
/// The pass of the owner's registration before `pass`, in the same viewport.
before: Option<u64>,
}
/// One entry the runtime keeps for a component, and the owner that is tested for its eviction.
@@ -270,11 +272,28 @@ pub(crate) fn register_owner(ctx: &Context, owner: Id) {
crate::runtime::replay::note_owner(ctx, owner);
let facts = frame::facts(ctx);
pass_state::with::<Registry, _>(ctx, |reg| {
reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now });
let before = match reg.owners.get(&owner) {
Some(last) if last.viewport == facts.viewport && last.pass == facts.pass_nr => last.before,
Some(last) if last.viewport == facts.viewport => Some(last.pass),
_ => None,
};
reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now, before });
reg.ended.remove(&owner);
});
}
/// Whether `owner` was registered in the pass before the running one of its viewport, by a run or a replay: its
/// component was shown there.
pub(crate) fn shown_last_pass(ctx: &Context, owner: Id) -> bool {
let facts = frame::facts(ctx);
pass_state::with::<Registry, _>(ctx, |reg| {
reg.owners.get(&owner).filter(|last| last.viewport == facts.viewport).is_some_and(|last| {
let shown = if last.pass == facts.pass_nr { last.before } else { Some(last.pass) };
shown.is_some_and(|shown| shown + 1 >= facts.pass_nr)
})
})
}
/// The generation of ended shown lives now: a kept run stores it, and `ended_since` compares with it.
pub(crate) fn ended_generation(ctx: &Context) -> u64 {
pass_state::with::<Registry, _>(ctx, |reg| reg.ended_generation)
+6
View File
@@ -395,6 +395,10 @@ impl Driver<'_> {
let sizing = self.stage.is_peek();
let now = frame::clock(ctx);
let existing = if sizing { store::peek_clone::<Tween<T>>(ctx, id) } else { store::take::<Tween<T>>(ctx, id) };
// A tween that moves in this pass (a new target, also one it jumps to, or a step, also its last one) leaves the
// slot in another state than the run found it in, which the next run reads (`layer_fading` among others): a
// record of the run is not replayed. Only a tween still running asks for another frame.
let moved = existing.as_ref().is_some_and(|tween| tween.target() != target || !tween.is_settled());
let mut tween = match existing {
Some(tween) => tween,
None => {
@@ -409,6 +413,8 @@ impl Driver<'_> {
if !sizing {
if !tween.is_settled() {
note_unsettled(ctx);
} else if moved {
crate::runtime::replay::note_unsettled(ctx);
}
store::put(ctx, id, tween);
}
+49 -6
View File
@@ -9,6 +9,7 @@ use crate::runtime::egui::pass;
use crate::runtime::frame::{PassStep, PerViewport, Stamped};
use crate::runtime::pass_state;
use crate::runtime::pointer;
use crate::runtime::shift::Shift;
use craft_behavior::OwnerClass;
use craft_behavior::overlay::Side;
use egui::emath::TSTransform;
@@ -120,7 +121,7 @@ pub enum OpenFilter {
}
/// One shown egui layer.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, PartialEq)]
#[doc(hidden)]
pub struct OpenEntry {
/// The layer's id.
@@ -164,6 +165,29 @@ pub struct OpenEntry {
dialog: Option<Id>,
}
/// A replay moves the entry's screen rects with its record; the rest stays.
impl Shift for OpenEntry {
fn shifted(&self, by: &egui::RecordShift) -> Self {
OpenEntry {
anchor: self.anchor.shifted(by),
peers: self.peers.shifted(by),
rect: self.rect.shifted(by),
region: self.region.shifted(by),
..self.clone()
}
}
fn snapped(&self, to: &Self, within: f32) -> Self {
OpenEntry {
anchor: self.anchor.snapped(&to.anchor, within),
peers: self.peers.snapped(&to.peers, within),
rect: self.rect.snapped(&to.rect, within),
region: self.region.snapped(&to.region, within),
..self.clone()
}
}
}
impl OpenEntry {
/// An entry for the layer `id` of `rank`.
pub(crate) fn new(id: Id, rank: Rank, keys: OwnerClass, rect: Rect, layer: Layer) -> Self {
@@ -484,7 +508,8 @@ pub(crate) fn appears(ctx: &Context, id: Id, exiting: bool) -> bool {
/// Marks the layer `id`'s body as running, so layers opened from inside it become its children, with the `side` of
/// its anchor it was placed on. A layer shown again while it fades out opens anew: it appears in this frame and pass.
pub(crate) fn begin_layer(ctx: &Context, id: Id, tier: Tier, exiting: bool, side: Option<Side>) {
crate::runtime::replay::block(ctx);
// Which layers a press opened reads the presses and releases.
crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Press);
let reopened = reopened(ctx, id, exiting);
with_pass(ctx, |pass| {
pass.drawing.push((id, tier));
@@ -649,13 +674,27 @@ pub(crate) fn absorb_presses(ctx: &Context, input: &mut crate::runtime::egui::in
input.events.len() != before
}
/// The outside press the input hook removed for the running pass.
/// The outside press the input hook removed for the running pass. A tracked input (`Input::Press`).
pub(crate) fn absorbed_press(ctx: &Context) -> Option<Pos2> {
crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Press);
absorbed_press_raw(ctx)
}
/// `absorbed_press` without noting the read: for the pointer's begin hook, which moves `Input::Press` by it.
pub(crate) fn absorbed_press_raw(ctx: &Context) -> Option<Pos2> {
with_persist(ctx, pass::current_viewport(ctx), |persist| persist.outside_press)
}
/// Records the toggling parts that sit beside the anchor of the layer `id` shown in this pass.
/// Whether a close is queued for one of the layers `ids`: only a run of the layer's owner takes it, so a memoized view
/// that showed one of them runs while it waits.
pub(crate) fn close_queued(ctx: &Context, ids: &[Id]) -> bool {
!ids.is_empty() && pass_state::with::<Closes, _>(ctx, |closes| closes.0.iter().any(|(closed, ..)| ids.contains(closed)))
}
/// Records the toggling parts that sit beside the anchor of the layer `id` shown in this pass. A replay of the run
/// that showed the layer records them again.
pub(crate) fn note_peers(ctx: &Context, id: Id, peers: Vec<Rect>) {
crate::runtime::replay::journal(ctx, || (id, peers.clone()), |ctx, (id, peers)| note_peers(ctx, *id, peers.clone()));
with_pass(ctx, |pass| {
if let Some(entry) = pass.current.iter_mut().find(|entry| entry.id == id) {
entry.peers = peers;
@@ -697,12 +736,16 @@ pub fn end_stack_dialog(ctx: &Context, dialog: Id) {
/// Records the layer shown in this pass, parent first: a layer is recorded once its body ran, after the layers opened
/// from inside it, so it goes in front of them, and every layer then stacks above the layer it was opened from. A
/// layer shown again in a discarded pass replaces its entry.
/// layer shown again in a discarded pass replaces its entry. A replay of the run that showed the layer records the
/// entry again, its stack place and dialog filled, and the records open around it note the layer as one they show.
pub(crate) fn record(ctx: &Context, mut entry: OpenEntry) {
crate::runtime::replay::block(ctx);
with_pass(ctx, |pass| {
entry.place = entry.place.or(pass.place);
entry.dialog = entry.dialog.or(pass.dialog);
});
crate::runtime::replay::note_layer(ctx, entry.id);
crate::runtime::replay::journal(ctx, || entry.clone(), |ctx, entry| record(ctx, entry.clone()));
with_pass(ctx, |pass| {
if let Some(at) = pass.current.iter().position(|recorded| recorded.id == entry.id) {
pass.current[at] = entry;
return;
+12
View File
@@ -237,6 +237,10 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) {
if events {
inputs::bump(ctx, Input::Pointer);
}
// A press or release, or an outside press the layer stack's input hook took before egui saw it.
if frame.press.is_some() || frame.release.is_some() || crate::runtime::overlay::absorbed_press_raw(ctx).is_some() {
inputs::bump(ctx, Input::Press);
}
}
PerViewport::<Stamped<Arc<PassPointer>>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| *record = Arc::new(pass_pointer));
PerViewport::<Shapes>::with(ctx, viewport, |shapes| {
@@ -325,6 +329,13 @@ pub fn mods(ctx: &Context) -> Mods {
with_pass_raw(ctx, |pointer| pointer.frame.as_ref().map_or(Mods::NONE, |frame| frame.mods))
}
/// Where the primary press of the running pass started. A tracked input (`Input::Press`): a layer's dismissal decides by
/// it, so a memoized view that shows a layer runs on a press anywhere, and a pointer move leaves it alone.
pub(crate) fn primary_press(ctx: &Context) -> Option<Pos2> {
crate::runtime::replay::note_input(ctx, Input::Press);
frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin)
}
/// `frame` without noting the read: for the steps of the component under the pointer and the pass machinery.
pub(crate) fn frame_raw(ctx: &Context) -> PointerFrame {
with_pass_raw(ctx, |pointer| pointer.frame.clone()).unwrap_or_else(|| PointerFrame {
@@ -444,6 +455,7 @@ pub(crate) fn record_text_widget(ctx: &Context, widget: Id, owner: Id) {
/// it the press where no widget on the layer is, and the press and hover there go to the layer's shapes as if egui
/// had named no target.
pub(crate) fn record_layer_widget(ctx: &Context, widget: Id) {
crate::runtime::replay::journal(ctx, || widget, |ctx, &widget| record_layer_widget(ctx, widget));
PerViewport::<Shapes>::with(ctx, pass::current_viewport(ctx), |record| {
record.this_grounds.insert(widget);
});
+97 -12
View File
@@ -9,8 +9,11 @@
//!
//! The record also holds the facts the settled test reads (`runtime::lazy`): the values the run read, whether
//! something in it still moves (an animation that is not at its end, a repaint request) and the earliest time it asked
//! to be shown again, and whether it did something a replay cannot repeat (an overlay it shows, paint on another
//! layer, a label scope open around it). Such a record is never replayed: the view runs.
//! to be shown again, the overlay layers it shows and where the focus was in it, and whether it did something a replay
//! cannot repeat (paint on a layer that is neither its own nor an overlay it shows, such as a raw egui popup or a
//! transformed body; a window of another viewport; a label scope open around it). Such a record is never replayed:
//! the view runs. An overlay it shows is journaled as every other registration is (its `Area`, its layer stack
//! entry), so its record replays only where it ran (`Record::pinned`).
use crate::runtime::egui::areas::Layer;
use crate::runtime::focus::{self, Transcript};
@@ -19,7 +22,7 @@ use crate::runtime::inputs::{Input, Inputs};
use crate::runtime::pass_state;
use crate::runtime::reads::BindKey;
use crate::runtime::shift::Shift;
use egui::{Context, IdSet, RecordShift};
use egui::{Context, IdSet, RecordShift, Rect};
use std::any::Any;
use std::collections::HashSet;
use std::fmt;
@@ -90,6 +93,15 @@ impl PartialEq for Entry {
}
}
impl Entry {
/// The entry at the place `shift` names. A shift that leaves every record as it is (`RecordShift::is_none`, a
/// pinned record's) leaves the entry too, as it leaves egui's records: a clip a layer the record shows sets lies
/// outside the clip around the record, which `RecordShift::clip` would cut it to.
fn at(&self, shift: &RecordShift) -> Entry {
if shift.is_none() { self.clone() } else { self.0.shifted(shift) }
}
}
impl fmt::Debug for Entry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.describe(f)
@@ -164,6 +176,43 @@ pub(crate) struct Facts {
/// The command scope instances that registered in the run (`commands::register_instance`): a command queued for one
/// is taken only by a run, so a replay waits until the queue holds none.
pub(crate) instances: Vec<egui::Id>,
/// The overlay layers the run showed (`note_overlay`): their paint and widgets are the record's, and the pointer over
/// one of them engages the record.
pub(crate) overlays: Vec<ShownLayer>,
/// The layer stack entries the run recorded (`note_layer`): a close queued for one is taken only by a run.
pub(crate) layers: Vec<egui::Id>,
}
/// An overlay layer a run showed: its egui layer and its rect in screen space.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct ShownLayer {
pub(crate) layer: Layer,
pub(crate) rect: Rect,
}
/// Where the focus was in a run: the component of the focused stop when the run registered it, and the egui widget
/// that held egui focus when the run made it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Held {
pub(crate) stop: Option<egui::Id>,
pub(crate) widget: Option<egui::Id>,
}
impl Held {
/// Where the focus is now: the component of the focused stop and the egui widget that holds egui focus.
pub(crate) fn focused(ctx: &Context) -> Held {
Held { stop: focus::focused_stop(ctx).map(|key| key.0), widget: crate::runtime::egui::focus::focused(ctx) }
}
/// The part of the focus `self` that is among the stops of `focus` and the egui widgets `widgets`.
pub(crate) fn within(self, focus: &Transcript, widgets: &IdSet) -> Held {
Held { stop: self.stop.filter(|stop| focus.stop_ids().any(|id| id == *stop)), widget: self.widget.filter(|widget| widgets.contains(widget)) }
}
/// Whether the focus is in the run at all.
pub(crate) fn any(self) -> bool {
self.stop.is_some() || self.widget.is_some()
}
}
/// What one real run of a region added to its pass.
@@ -173,14 +222,22 @@ pub(crate) struct Record {
egui: egui::PassRecords,
/// The egui widgets of the run.
pub(crate) widgets: IdSet,
/// Where the focus was in the run when it ended.
pub(crate) held: Held,
pub(crate) facts: Facts,
}
impl Record {
/// Whether a replay can add the record at another place: egui's records hold no paint callback
/// (`PassRecords::paints_callback`).
/// (`PassRecords::paints_callback`) and the record is not pinned.
pub(crate) fn movable(&self) -> bool {
!self.egui.paints_callback()
!self.egui.paints_callback() && !self.pinned()
}
/// Whether the record replays only where it ran, at the offset and clip of its run: it shows an overlay, which a
/// host places in screen space by its anchor, so a move of the record is no move of the layer.
pub(crate) fn pinned(&self) -> bool {
!self.facts.overlays.is_empty()
}
}
@@ -218,7 +275,8 @@ pub(crate) fn in_audit_run(ctx: &Context) -> bool {
OPEN.load(Ordering::Acquire) > 0 && pass_state::with::<Recorder, _>(ctx, |recorder| recorder.open.iter().any(|open| open.audit))
}
/// Ends the innermost record, the one around a run on `layer`: paint or widgets on another layer block it.
/// Ends the innermost record, the one around a run on `layer`: paint or widgets on a layer that is neither `layer` nor
/// an overlay the run showed block it.
pub(crate) fn close(ctx: &Context, layer: Layer) -> Record {
OPEN.fetch_sub(1, Ordering::AcqRel);
let (open, journal) = pass_state::with::<Recorder, _>(ctx, |recorder| {
@@ -242,6 +300,8 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record {
outer.facts.reads.extend(open.facts.reads.iter().copied().filter(|key| !kept || !matches!(key, BindKey::Place(..))));
outer.facts.inputs.extend(open.facts.inputs);
outer.facts.instances.extend(open.facts.instances.iter().copied());
outer.facts.overlays.extend(open.facts.overlays.iter().copied());
outer.facts.layers.extend(open.facts.layers.iter().copied());
} else {
recorder.journal.clear();
}
@@ -254,13 +314,23 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record {
facts.layout_keeps.dedup();
facts.derived_keeps.sort_unstable_by_key(|id| id.value());
facts.derived_keeps.dedup();
// A paint callback's output depends on what its closure holds, which neither a view's key nor a comparison sees:
// its run is never replayed.
facts.blocked |= egui.layers().any(|on| on != layer) || egui.paints_callback();
// Paint on a layer that is neither the run's own nor an overlay it showed (a raw egui popup, a transformed body)
// comes from code that registers nothing to replay it with. A paint callback's output depends on what its closure
// holds, which neither a view's key nor a comparison sees. Either run is never replayed.
facts.blocked |= egui.layers().any(|on| on != layer && !facts.overlays.iter().any(|shown| shown.layer == on)) || egui.paints_callback();
// Every discard request reaches egui's output (`sizing::request_discard` and egui's own); layout memory's waits
// for the end of the pass and notes itself (`note_discard`).
facts.discards |= discard_requests(ctx) > open.discards;
Record { focus: focus::transcript(ctx, open.focus), journal, widgets: egui.widgets().iter().map(|widget| widget.id).collect(), egui, facts }
let focus = focus::transcript(ctx, open.focus);
let widgets = egui.widgets().iter().map(|widget| widget.id).collect();
// A run that ends holding focus reads where the focus is and what is sent to it: a focus move, and the next key,
// text, IME, clipboard or AccessKit event wherever the framework routes it, run it.
let held = Held::focused(ctx).within(&focus, &widgets);
if held.any() {
facts.inputs.insert(Input::Focus);
facts.inputs.insert(Input::Sent);
}
Record { focus, journal, widgets, held, egui, facts }
}
#[cfg(feature = "testing")]
@@ -280,6 +350,10 @@ impl Record {
// The display names a widget by its rect only; the difference may be in its sense, state or interact rect.
Some(egui::PassRecordsDiff::Widget { index, left, right }) => found.push(format!("widget rect {index}: left {left:?} / right {right:?}")),
// The display names a node by its bounds only; the difference may be in any other property.
// The display names a shape by its rects only; the difference may be in its colour, stroke, texture or text.
Some(egui::PassRecordsDiff::Shape { layer, index, left, right }) => {
found.push(format!("paint: shape {index} on {layer:?}: left {left:?} / right {right:?}"))
}
Some(egui::PassRecordsDiff::Node { index, left, right }) => {
found.push(format!("AccessKit node {index}: left {left:?} / right {right:?}"))
}
@@ -289,7 +363,7 @@ impl Record {
if let Some(diff) = self.focus.first_difference(&run.focus) {
found.push(format!("focus: {diff}"));
}
let shifted: Vec<Entry> = self.journal.iter().map(|entry| entry.0.shifted(shift)).collect();
let shifted: Vec<Entry> = self.journal.iter().map(|entry| entry.at(shift)).collect();
let (left, right) = (&shifted, &run.journal);
if let Some(index) = left
.iter()
@@ -355,7 +429,7 @@ pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) {
let noting = recording(ctx);
if noting {
pass_state::with::<Recorder, _>(ctx, |recorder| {
recorder.journal.extend(record.journal.iter().map(|entry| if shift.is_none() { entry.clone() } else { entry.0.shifted(shift) }));
recorder.journal.extend(record.journal.iter().map(|entry| entry.at(shift)));
recorder.replaying = true;
});
}
@@ -471,6 +545,17 @@ pub(crate) fn note_wake(ctx: &Context, at: f64) {
with_open(ctx, |facts| facts.wake = min_wake(facts.wake, Some(at)));
}
/// Notes that the running code showed the overlay layer `layer` at the screen rect `rect`. Called by the journaled
/// registration of the layer's `Area`, so a record that replays it notes it again in the records open around it.
pub(crate) fn note_overlay(ctx: &Context, layer: Layer, rect: Rect) {
with_open(ctx, |facts| facts.overlays.push(ShownLayer { layer, rect }));
}
/// Notes that the running code recorded the layer stack entry `id`, by a run or a replay.
pub(crate) fn note_layer(ctx: &Context, id: egui::Id) {
with_open(ctx, |facts| facts.layers.push(id));
}
/// Notes that the running code did something a replay cannot repeat.
pub(crate) fn block(ctx: &Context) {
with_open(ctx, |facts| facts.blocked = true);
+9 -1
View File
@@ -285,14 +285,22 @@ pub fn keep(ctx: &Context, id: ToastId) {
}
}
/// The cards of the window `window` in the running viewport, oldest first.
/// The cards of the window `window` in the running viewport, oldest first. A tracked input (`Input::Toasts`).
pub fn cards(ctx: &Context, window: &WindowKey) -> Vec<Card> {
crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Toasts);
PerViewport::<Queue>::with(ctx, pass::current_viewport(ctx), |queue| {
let cards = queue.windows.iter().find(|(key, _)| key == window);
cards.map_or_else(Vec::new, |(_, live)| live.iter().map(|live| live.card.clone()).collect())
})
}
/// The ids of the cards each window of the running viewport queues: what `Input::Toasts` observes.
pub(crate) fn queued(ctx: &Context) -> Vec<(WindowKey, Vec<ToastId>)> {
PerViewport::<Queue>::with(ctx, pass::current_viewport(ctx), |queue| {
queue.windows.iter().map(|(key, live)| (key.clone(), live.iter().map(|live| live.card.id).collect())).collect()
})
}
/// Every live viewport's cards with their windows, oldest first, for `ui.inspect`; `cards` is the running viewport's.
pub fn snapshot(ctx: &Context) -> Vec<(WindowKey, Card)> {
let mut cards = Vec::new();
+1
View File
@@ -3,6 +3,7 @@
use crate::runtime::access::{FieldLabel, scope};
use egui::{Context, Id};
pub use crate::runtime::access::layer_root;
pub use crate::runtime::egui::access::{AccessTree, Declared, NodeKey, prune_controls};
/// The AccessKit tree a finished pass of a viewport produced, taken out of its output; empty when it made none.
@@ -111,6 +111,36 @@ fn texel(image: &ColorImage, x: usize, y: usize) -> Color32 {
image.pixels[y * 24 + x]
}
/// On a strong fill or scrim (the surface's ink is `OnDark`: a brand rail) the accent parts paint in the icon's own
/// colour, since `accent.solid` would vanish on the brand fill; the fixed parts stay as drawn, and on a panel the
/// accent parts keep the accent ink.
#[trial]
fn an_accent_part_on_a_dark_surface_paints_in_the_icons_ink() {
register_app_icons(&LAYERED_SET);
let tokens = style::tokens(Mode::Light, Contrast::Standard);
let rect = Rect::from_min_max(pos2(10.0, 10.0), pos2(34.0, 34.0));
let mut frames = Frames::new();
let mut tints = |surface: Ink, spec_ink: Option<Ink>| {
let on = ink_color(&tokens, Ink::OnDark);
let mut spec = IconSpec::svg(IconId::from(std::borrow::Cow::Borrowed(LAYERED_NAME))).color(StyleColor(on));
if let Some(ink) = spec_ink {
spec = spec.ink(ink);
}
let record = RefCell::new(PaintRecord::default());
let shapes = frames.frame_shapes(|ui| {
let env = DrawEnv { tokens: &tokens, direction: Direction::Ltr, ink: surface };
Draw::new(ui.painter(), &record, env).icon(rect, &spec);
});
textured(&shapes).into_iter().map(|(_, tint)| tint).collect::<Vec<_>>()
};
let on = ink_color(&tokens, Ink::OnDark);
// design: allow[raw-colour/const](a fixed layer keeps the colours it is drawn in: the trial expects the white tint that leaves them unchanged)
let fixed = Color32::WHITE;
assert_eq!(tints(Ink::OnDark, None), [on, on, fixed], "on a brand rail the accent parts read in the icon's ink");
assert_eq!(tints(Ink::OnPanel, Some(Ink::OnDark)), [on, on, fixed], "an icon that asks for the on-dark ink does the same");
assert_eq!(tints(Ink::OnPanel, None), [on, rgba_color(tokens.color.accent.solid), fixed], "on a panel the accent ink is kept");
}
#[trial]
fn an_accent_part_paints_in_the_accent_ink_a_fixed_part_as_drawn_and_both_take_the_disabled_ink_when_disabled() {
register_app_icons(&LAYERED_SET);
+35 -1
View File
@@ -3,7 +3,8 @@
use craft_behavior::{ColumnWidth, Proposal, Sense};
use craft_ui::contract::{
BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, MeasureCx, Props as _, Role, Show as _, ShowContainer as _, Sizing,
BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, MeasureCx, MemoProps, MemoView, Props as _, Role, Show as _,
ShowContainer as _, Sizing,
};
use craft_ui::layout::{BodyLayout, RowAlign};
use craft_ui::runtime::env::{Direction, with_env};
@@ -322,6 +323,39 @@ fn the_end_region_shares_the_members_line() {
assert!((end.center().y - member.center().y).abs() < SLACK, "the end region's probe {end:?} is off the members' line {member:?}");
}
/// A memoized view of one short block.
#[derive(MemoProps)]
struct Short {}
fn short(_: &mut Short, ui: &mut Ui) -> Rect {
Block::new(Vec2::new(40.0, 10.0)).show(ui).rect
}
/// A memoized view in a row sits on the row's line, as the one-line child beside it does, also while it replays. Its
/// content starts a layout room of its own, which left it at the row's top (a menu bar beside an app icon,
/// storytold/photocraft#16113).
#[trial]
fn a_memoized_view_sits_on_the_rows_line() {
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING)));
let shown = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
Panel::new().layout(BodyLayout::row()).id_salt("row").show(ui, |ui, _| {
let tall = Block::new(Vec2::new(20.0, 30.0)).show(ui).rect;
let view = MemoView::new("short", Short {}, short).show(ui);
if !is_measuring(ui.ctx()) {
shown.set((tall, view.unwrap_or(Rect::NOTHING)));
}
});
});
fixture.room(Vec2::splat(400.0)).settle();
for frame in 0..3 {
let (tall, view) = seen.get();
assert!(view.height() > 0.0, "frame {frame}: the view showed: {view:?}");
assert!((view.center().y - tall.center().y).abs() < SLACK, "frame {frame}: the view {view:?} is off the line of {tall:?}");
fixture.settle();
}
}
/// A Row in right-to-left holding a vertically scrolling container (content-sized, then filling its height) beside a
/// probe: the container, the probe inside it and the probe beside it are finite, and the container lies in the row.
#[trial]
@@ -2,7 +2,7 @@
//! owned by a `DialogHost`. A command form is a `ParamDialog` without a preview.
use super::fields::{DialogFields, FieldValue};
use crate::patterns::presets::{PresetKind, PresetRow};
use crate::patterns::presets::{PresetKind, PresetRow, PresetSource};
use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, ListingRequest, PathRequest};
use super::form::{FormDialog, FormDialogWords};
@@ -243,9 +243,10 @@ pub struct ParamDialog<'a> {
/// dialog open; a press comes back as `ParamDialogOutput::footer_action`.
#[prop]
extra_buttons: Vec<(String, Label)>,
/// The patterns the dialog's [`ParamKind::Pattern`] rows offer.
/// The patterns the dialog's [`ParamKind::Pattern`] rows offer. A hosted dialog's build gives a source over
/// owned inputs.
#[prop]
patterns: Cow<'a, [PresetRow<String>]>,
patterns: Option<PresetSource<'a, String>>,
/// A muted line at the footer's start edge, left of the buttons (a file size estimate, say).
#[prop(into)]
footer_note: Option<Label>,
@@ -314,7 +315,7 @@ impl<'a> ParamDialog<'a> {
click_centres: true,
canvas: None,
extra_buttons: Vec::new(),
patterns: Cow::Borrowed(&[]),
patterns: None,
footer_note: None,
below: None,
shaped: None,
@@ -494,7 +495,8 @@ impl<'a> ParamDialog<'a> {
let shown = form.show(ui, |ui, cx, values| {
if cx.first() && !host_opened {
let saved = remember.as_ref().and_then(|key| cx.saved::<Option<DialogFields>>(key).clone());
Self::open_values(&params, &patterns, saved.as_ref(), values);
let offered = patterns.as_ref().map(|source| source.rows(ui.ctx(), &Env::of(ui))).unwrap_or_default();
Self::open_values(&params, &offered, saved.as_ref(), values);
}
for answer in cx.take_answers() {
let answered = match &answer {
@@ -531,10 +533,10 @@ impl<'a> ParamDialog<'a> {
live.view = live.view.centred_on(point, texture.size);
}
let mut show_rows = |ui: &mut Ui, values: &mut DialogFields| {
let mut shown = ParamRows::new(title.clone(), &params, Bind::bound(values))
.patterns(&patterns)
.preview_colors(&preview_colors)
.sliders(layout.sliders());
let mut shown = ParamRows::new(title.clone(), &params, Bind::bound(values)).preview_colors(&preview_colors).sliders(layout.sliders());
if let Some(source) = patterns.as_ref() {
shown = shown.patterns(source);
}
if let Some(canvas) = canvas {
shown = shown.canvas(canvas);
}
@@ -811,7 +813,9 @@ impl HostedParamDialog {
) -> Self {
let key = key.into();
let ParamDialog { params, remember, patterns, previews, .. } = build(&mut fields);
let (params, patterns) = (params.into_owned(), patterns.into_owned());
// No pass runs here: the rows are built in the root scope, whose words name them; only their keys are read.
let patterns = patterns.map(|source| source.rows(ctx, &Env::of_root(ctx))).unwrap_or_default();
let params = params.into_owned();
let saved = remember.and_then(|key| MemoryStage::peek_saved::<Option<DialogFields>>(ctx, &key));
ParamDialog::open_values(&params, &patterns, saved.as_ref(), &mut fields);
let id = dialog_id(key.as_str());
@@ -11,7 +11,7 @@ use crate::contract::clicked;
use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field};
use crate::patterns::form_dialogs::form::{read_bind, write_bind};
use crate::patterns::presets::{
GroupPath, NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetLibrary, PresetPicker, PresetRow, PresetState,
GroupPath, NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetFns, PresetLibrary, PresetPicker, PresetRow, PresetSource, PresetState,
};
use crate::runtime::requests::{HostAnswer, PathFilter, PathKind, PathRequest};
use crate::text::TextField;
@@ -720,7 +720,8 @@ impl Pass<'_> {
let words = self.words;
let shown = {
let presets = library.borrow();
let rows: Vec<PresetRow<String>> = presets.items().iter().map(|item| PresetRow::item(item.name.clone(), item.name.clone(), 0)).collect();
let names: Vec<String> = presets.items().iter().map(|item| item.name.clone()).collect();
let rows = PresetSource::new(names.as_slice(), PresetFns::new(name_rows));
let current = presets.items().iter().find(|item| item.value == *options).map(|item| item.name.clone());
let picker = PresetPicker::new(words.preset.clone(), Bind::given(current), &rows, Bind::bound(&mut held.picker)).field(PickerField::Name);
NamedPresetRow::new(words.preset.clone(), picker)
@@ -958,3 +959,8 @@ fn choose<T: craft_behavior::Value>(ui: &mut Ui, name: &Label, salt: &str, entri
}
});
}
/// One preset row per name, keyed by it.
fn name_rows(names: &&[String], _: &Env) -> Vec<PresetRow<String>> {
names.iter().map(|name| PresetRow::item(name.clone(), name.clone(), 0)).collect()
}
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff. Show more