mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 02:36:54 +01:00
Merge main into lightcraft-pr/fw-value-editing
This commit is contained in:
commit
1f42f701dc
64 files changed
+2762
-321
No files matched your search
@@ -449,8 +449,9 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
let taken = column.groups.remove(group);
|
||||
let part = !column.groups.is_empty();
|
||||
let id = self.drop_if_empty(&place);
|
||||
return Ok(Moving { id, ..Moving::taken(taken, source) });
|
||||
return Ok(Moving { id, part, ..Moving::taken(taken, source) });
|
||||
};
|
||||
if let Some(Node::Stack { entries }) = self.node_of_mut(&place)
|
||||
&& entries.len() > 1
|
||||
@@ -478,14 +479,14 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
if columns.is_empty() {
|
||||
self.take_node(&path);
|
||||
}
|
||||
Ok(Moving { column: taken, id: None })
|
||||
Ok(Moving { column: taken, id: None, part: false })
|
||||
}
|
||||
Some(PanelPlace::Floating { window, .. }) => {
|
||||
if window >= self.floating.len() {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
let taken = self.floating.remove(window);
|
||||
Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id) })
|
||||
Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id), part: false })
|
||||
}
|
||||
Some(PanelPlace::Node(_)) | None => Err(DockError::InvalidPlacement),
|
||||
}
|
||||
@@ -500,7 +501,8 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
|
||||
/// Insert groups taken by [`Self::take_unit`] (or a new single-panel group). A new column, docked or floating,
|
||||
/// keeps the moving column's state; groups that join a column take that column's.
|
||||
/// keeps the moving column's state, expanded when they are part of a collapsed column; groups that join a column
|
||||
/// take that column's.
|
||||
/// `canvas` is the protected-panel test an outer edge drop narrows by ([`Self::edge_path`]).
|
||||
pub(super) fn insert_moving(&mut self, moving: Moving<P>, to: Target<P>, canvas: &dyn Fn(&P) -> bool) -> Result<(), DockError> {
|
||||
let mut moving = moving;
|
||||
@@ -517,7 +519,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
Some(id) => id,
|
||||
None => self.fresh_window_id(),
|
||||
};
|
||||
let window = Floating::new(id, Column { width: None, ..moving.column }, rect);
|
||||
let window = Floating::new(id, moving.into_window_column(), rect);
|
||||
let edge = edge.filter(|_| window.column.iconic);
|
||||
self.floating.push(Floating { edge, ..window });
|
||||
Ok(())
|
||||
|
||||
@@ -330,12 +330,14 @@ pub(super) enum Unit {
|
||||
}
|
||||
|
||||
/// Groups in transit, in a column that carries the state of the column they came from: a new column, docked or
|
||||
/// floating, keeps that state (an icon group taken out of a collapsed column stays icons), and a column they
|
||||
/// join keeps its own.
|
||||
/// floating, keeps that state, except that part of a collapsed column makes an expanded one (the last group of a
|
||||
/// collapsed column stays icons); a column they join keeps its own.
|
||||
pub(super) struct Moving<P> {
|
||||
pub column: Column<P>,
|
||||
/// The id of a floating window whose last group is in transit, which a new window keeps.
|
||||
pub id: Option<u64>,
|
||||
/// Panels stay in the column the groups left, so a new column made of them is expanded.
|
||||
pub part: bool,
|
||||
}
|
||||
|
||||
impl<P> Moving<P> {
|
||||
@@ -344,14 +346,26 @@ impl<P> Moving<P> {
|
||||
Self::taken(group, Column::new(Vec::new()))
|
||||
}
|
||||
|
||||
/// `group` taken out of a column whose state is `source` ([`Column::emptied`]).
|
||||
/// `group` taken out of a column whose state is `source` ([`Column::emptied`]), as all of that column.
|
||||
pub(super) fn taken(group: Group<P>, source: Column<P>) -> Self {
|
||||
Self { column: Column { groups: vec![group], ..source }, id: None }
|
||||
Self { column: Column { groups: vec![group], ..source }, id: None, part: false }
|
||||
}
|
||||
|
||||
/// The column a new dock column gets: the moving column, `width` points wide unless it brings a width.
|
||||
/// `panel` alone, taken out of a column whose state is `source`, with whether other panels stay in it.
|
||||
pub(super) fn panel(panel: P, source: (Column<P>, bool)) -> Self {
|
||||
let (column, part) = source;
|
||||
Self { part, ..Self::taken(Group::new(vec![panel], 0), column) }
|
||||
}
|
||||
|
||||
/// The column a new floating window gets: the moving column, expanded when it is part of a collapsed one.
|
||||
pub(super) fn into_window_column(self) -> Column<P> {
|
||||
Column { width: None, iconic: self.column.iconic && !self.part, ..self.column }
|
||||
}
|
||||
|
||||
/// The column a new dock column gets: the moving column, `width` points wide unless it brings a width, and
|
||||
/// expanded when it is part of a collapsed one.
|
||||
pub(super) fn into_column(self, width: Option<f32>) -> Column<P> {
|
||||
Column { width: self.column.width.or(width), ..self.column }
|
||||
Column { width: self.column.width.or(width), iconic: self.column.iconic && !self.part, ..self.column }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
let source = self.source_of(&panel);
|
||||
// A panel the layout does not hold opens in the new window.
|
||||
let entry = self.take(&panel).unwrap_or(StackEntry { panel: panel.clone(), open: true, height: None });
|
||||
let moving = Moving { id: lone, ..Moving::taken(Group::new(vec![entry.panel], 0), source) };
|
||||
let moving = Moving { id: lone, ..Moving::panel(entry.panel, source) };
|
||||
self.insert_moving(moving, Target::Float { rect, edge: None }, canvas)
|
||||
}
|
||||
Action::Close { panel } => self.take(&panel).map(|_| ()).ok_or(DockError::MissingPanel),
|
||||
@@ -72,7 +72,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
let entry = StackEntry { panel, open: true, height: None };
|
||||
if let Some(anchor) = anchor {
|
||||
self.insert(entry, Column::new(Vec::new()), &anchor, DockPlacement::Tab { before: None }, canvas)
|
||||
self.insert(entry, (Column::new(Vec::new()), false), &anchor, DockPlacement::Tab { before: None }, canvas)
|
||||
} else if self.root.is_none() {
|
||||
self.root = Some(Node::Tabs { panels: vec![entry.panel], active: 0 });
|
||||
Ok(())
|
||||
@@ -89,7 +89,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
{
|
||||
return Err(DockError::MissingTarget);
|
||||
}
|
||||
self.insert(StackEntry { panel, open: true, height: None }, Column::new(Vec::new()), &anchor, placement, canvas)
|
||||
self.insert(StackEntry { panel, open: true, height: None }, (Column::new(Vec::new()), false), &anchor, placement, canvas)
|
||||
}
|
||||
Action::MoveFloating { panel, rect, edge } => {
|
||||
if !valid_rect(rect) {
|
||||
@@ -142,7 +142,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
to => {
|
||||
let source = self.source_of(&panel);
|
||||
let entry = self.take(&panel).ok_or(DockError::MissingPanel)?;
|
||||
self.insert_moving(Moving::taken(Group::new(vec![entry.panel], 0), source), to, canvas)
|
||||
self.insert_moving(Moving::panel(entry.panel, source), to, canvas)
|
||||
}
|
||||
},
|
||||
Action::Restore { panel, location } => {
|
||||
@@ -256,9 +256,11 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
|
||||
/// The state a new column made of `panel` keeps: its column's ([`Self::source_column`]), or none for a panel
|
||||
/// outside a column or absent.
|
||||
pub(super) fn source_of(&self, panel: &P) -> Column<P> {
|
||||
self.place(panel).map_or_else(|| Column::new(Vec::new()), |place| self.source_column(&place))
|
||||
/// outside a column or absent; and whether other panels stay in that column ([`Moving::part`]).
|
||||
pub(super) fn source_of(&self, panel: &P) -> (Column<P>, bool) {
|
||||
let Some(place) = self.place(panel) else { return (Column::new(Vec::new()), false) };
|
||||
let part = self.column(&place).is_some_and(|column| column.panels().any(|other| other != panel));
|
||||
(self.source_column(&place), part)
|
||||
}
|
||||
|
||||
/// The accordion entry of `panel` in the docked tree.
|
||||
@@ -327,7 +329,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
pub(super) fn insert(
|
||||
&mut self,
|
||||
entry: StackEntry<P>,
|
||||
source: Column<P>,
|
||||
source: (Column<P>, bool),
|
||||
anchor: &P,
|
||||
placement: DockPlacement<P>,
|
||||
canvas: &dyn Fn(&P) -> bool,
|
||||
@@ -338,8 +340,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
.filter(|_| !matches!(placement, DockPlacement::Group { .. } | DockPlacement::Column { .. } | DockPlacement::Edge(_)))
|
||||
.map(<[bool]>::to_vec)
|
||||
else {
|
||||
let moving = Moving::taken(Group::new(vec![entry.panel], 0), source);
|
||||
return self.insert_moving(moving, Target::At { anchor: anchor.clone(), placement }, canvas);
|
||||
return self.insert_moving(Moving::panel(entry.panel, source), Target::At { anchor: anchor.clone(), placement }, canvas);
|
||||
};
|
||||
let root = self.root.as_mut().ok_or(DockError::MissingTarget)?;
|
||||
if let DockPlacement::Split(zone) = placement
|
||||
|
||||
@@ -310,7 +310,7 @@ fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleare
|
||||
assert_eq!(layout.floating[0].edge, None, "collapsing hangs the strip from the edge nearer the window");
|
||||
|
||||
let mut moved = columns();
|
||||
moved.apply(Action::move_group(3, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap();
|
||||
moved.apply(Action::move_column(3, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap();
|
||||
let floated = moved.floating.iter().find(|window| window.contains(&3)).unwrap();
|
||||
assert_eq!(floated.edge, Some(DockEdge::End), "a collapsed column floats at the edge its strip was dropped near");
|
||||
let mut moved = columns();
|
||||
@@ -356,10 +356,21 @@ fn a_group_docked_into_a_collapsed_column_keeps_its_width_as_the_flyout_width()
|
||||
layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap();
|
||||
layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap();
|
||||
assert_eq!(flyout(&layout, 3), Some(350.0), "a group from another collapsed column keeps its own");
|
||||
|
||||
let source = Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_width(300.0).with_iconic(true);
|
||||
let target = Column::new(vec![g(&[7], 0)]).with_iconic(true);
|
||||
let mut layout = Layout::new(
|
||||
Some(Node::split(Axis::X, SplitSize::Ratio(0.5), Node::dock(DockEdge::Start, vec![target]), Node::dock(DockEdge::End, vec![source]))),
|
||||
vec![],
|
||||
);
|
||||
layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap();
|
||||
layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap();
|
||||
assert_eq!(flyout(&layout, 3), Some(350.0), "a group from a collapsed column of its own width keeps its flyout width");
|
||||
}
|
||||
|
||||
/// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a
|
||||
/// column float in its state; groups joining a column, docked or floating, take that column's state.
|
||||
/// Collapse to icons is a state of every column: a floating window collapses and stays floating; a whole column
|
||||
/// leaving floats in its state, and part of a collapsed column floats expanded; groups joining a column, docked or
|
||||
/// floating, take that column's state.
|
||||
#[test]
|
||||
fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides() {
|
||||
let mut layout = columns();
|
||||
@@ -369,15 +380,24 @@ fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides
|
||||
layout.apply(Action::set_iconic(6, false)).unwrap();
|
||||
assert_eq!(layout.panel_state(&6), PanelState::Front);
|
||||
|
||||
for action in [
|
||||
Action::move_column(3, Target::float(window())),
|
||||
Action::move_group(3, Target::float(window())),
|
||||
Action::move_panel(3, Target::float(window())),
|
||||
] {
|
||||
let mut moved = columns();
|
||||
moved.apply(Action::move_column(3, Target::float(window()))).unwrap();
|
||||
assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "the whole collapsed column floats as icons");
|
||||
for action in [Action::move_group(3, Target::float(window())), Action::move_panel(3, Target::float(window()))] {
|
||||
let mut moved = columns();
|
||||
moved.apply(action.clone()).unwrap();
|
||||
assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "{action:?} floats as icons");
|
||||
assert!(floats(&moved, 3) && !column_of(&moved, 3).iconic, "{action:?} out of a column with another group floats expanded");
|
||||
assert!(column_of(&moved, 4).iconic, "the column it left stays collapsed");
|
||||
moved.apply(Action::move_group(4, Target::float(window()))).unwrap();
|
||||
assert!(floats(&moved, 4) && column_of(&moved, 4).iconic, "the column's last group floats as icons");
|
||||
}
|
||||
let mut tabbed = Layout::new(None, vec![Floating::new(102, Column::new(vec![g(&[3, 4, 5], 0)]).with_iconic(true), window())]);
|
||||
tabbed.apply(Action::move_panel(3, Target::float(window()))).unwrap();
|
||||
assert!(!column_of(&tabbed, 3).iconic, "a tab out of a collapsed column's only group floats expanded");
|
||||
tabbed.apply(Action::move_panel(5, Target::new_dock(DockEdge::End))).unwrap();
|
||||
assert!(!column_of(&tabbed, 5).iconic, "a tab out of a collapsed column docks expanded");
|
||||
tabbed.apply(Action::move_panel(4, Target::new_dock(DockEdge::Start))).unwrap();
|
||||
assert!(column_of(&tabbed, 4).iconic, "the column's last panel docks as icons");
|
||||
let mut moved = columns();
|
||||
moved.apply(Action::move_group(2, Target::float(window()))).unwrap();
|
||||
assert!(floats(&moved, 2) && !column_of(&moved, 2).iconic, "out of an expanded column it floats expanded");
|
||||
|
||||
+91
-20
@@ -113,6 +113,57 @@ fn time_expr(t: Tick, rate: Option<FrameRate>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The caption text as the tag parser sees it: one byte at a time, counted in tests.
|
||||
mod reader {
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Calls to [`Reader::byte`] on this thread (tests: the tag parser's work is linear in the text).
|
||||
pub(super) static READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The bytes of a caption text, read only through [`Reader::byte`].
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Reader<'a> {
|
||||
bytes: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
pub(super) fn new(bytes: &'a [u8]) -> Self {
|
||||
Self { bytes }
|
||||
}
|
||||
|
||||
/// The byte at `index`, or `None` past the end.
|
||||
pub(super) fn byte(self, index: usize) -> Option<u8> {
|
||||
#[cfg(test)]
|
||||
READS.with(|r| r.set(r.get().saturating_add(1)));
|
||||
self.bytes.get(index).copied()
|
||||
}
|
||||
|
||||
/// The bytes from `start` to the end, each read through [`Reader::byte`].
|
||||
pub(super) fn suffix(self, start: usize) -> Suffix<'a> {
|
||||
Suffix { reader: self, next: start }
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator returned by [`Reader::suffix`].
|
||||
pub(super) struct Suffix<'a> {
|
||||
reader: Reader<'a>,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl Iterator for Suffix<'_> {
|
||||
type Item = u8;
|
||||
|
||||
fn next(&mut self) -> Option<u8> {
|
||||
let c = self.reader.byte(self.next)?;
|
||||
self.next = self.next.saturating_add(1);
|
||||
Some(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use reader::Reader;
|
||||
|
||||
/// Memoised "next occurrence of a quote byte" searches, so unterminated quotes are not rescanned.
|
||||
#[derive(Default)]
|
||||
struct QuoteCache {
|
||||
@@ -121,7 +172,7 @@ struct QuoteCache {
|
||||
|
||||
impl QuoteCache {
|
||||
/// Index of the next `quote` byte at or after `from`.
|
||||
fn next(&mut self, bytes: &[u8], quote: u8, from: usize) -> Option<usize> {
|
||||
fn next(&mut self, bytes: Reader<'_>, quote: u8, from: usize) -> Option<usize> {
|
||||
let slot = usize::from(quote == b'\'');
|
||||
if let Some((searched, result)) = self.found[slot]
|
||||
&& searched <= from
|
||||
@@ -129,7 +180,7 @@ impl QuoteCache {
|
||||
{
|
||||
return result;
|
||||
}
|
||||
let result = bytes.get(from..).and_then(|t| t.iter().position(|&c| c == quote)).map(|i| from + i);
|
||||
let result = bytes.suffix(from).position(|c| c == quote).map(|i| from + i);
|
||||
self.found[slot] = Some((from, result));
|
||||
result
|
||||
}
|
||||
@@ -139,42 +190,42 @@ impl QuoteCache {
|
||||
/// letters/digits starting with a letter immediately after, then whitespace-separated
|
||||
/// `name="value"` / `name='value'` attributes, optional `/` before `>`. A `>` inside a quoted
|
||||
/// value does not end the tag. Returns `(index after '>', closing, lowercase name)`; the name is empty for a self-closing tag.
|
||||
fn parse_tag(bytes: &[u8], start: usize, cache: &mut QuoteCache) -> Option<(usize, bool, String)> {
|
||||
fn parse_tag(bytes: Reader<'_>, start: usize, cache: &mut QuoteCache) -> Option<(usize, bool, String)> {
|
||||
let mut i = start + 1;
|
||||
let closing = bytes.get(i) == Some(&b'/');
|
||||
let closing = bytes.byte(i) == Some(b'/');
|
||||
if closing {
|
||||
i += 1;
|
||||
}
|
||||
let name_start = i;
|
||||
if !bytes.get(i)?.is_ascii_alphabetic() {
|
||||
if !bytes.byte(i)?.is_ascii_alphabetic() {
|
||||
return None;
|
||||
}
|
||||
while bytes.get(i).is_some_and(u8::is_ascii_alphanumeric) {
|
||||
let mut name = String::new();
|
||||
while let Some(c) = bytes.byte(i).filter(u8::is_ascii_alphanumeric) {
|
||||
name.push(char::from(c.to_ascii_lowercase()));
|
||||
i += 1;
|
||||
}
|
||||
let name = String::from_utf8_lossy(bytes.get(name_start..i)?).to_ascii_lowercase();
|
||||
loop {
|
||||
let ws_start = i;
|
||||
while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
|
||||
while bytes.byte(i).is_some_and(|c| c.is_ascii_whitespace()) {
|
||||
i += 1;
|
||||
}
|
||||
match bytes.get(i)? {
|
||||
match bytes.byte(i)? {
|
||||
b'>' => return Some((i + 1, closing, name)),
|
||||
// self-closing: no markup
|
||||
b'/' if !closing && bytes.get(i + 1) == Some(&b'>') => return Some((i + 2, closing, String::new())),
|
||||
b'/' if !closing && bytes.byte(i + 1) == Some(b'>') => return Some((i + 2, closing, String::new())),
|
||||
_ => {}
|
||||
}
|
||||
if i == ws_start {
|
||||
return None;
|
||||
}
|
||||
let key_start = i;
|
||||
while bytes.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b':' | b'_')) {
|
||||
while bytes.byte(i).is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b':' | b'_')) {
|
||||
i += 1;
|
||||
}
|
||||
if i == key_start || bytes.get(i) != Some(&b'=') {
|
||||
if i == key_start || bytes.byte(i) != Some(b'=') {
|
||||
return None;
|
||||
}
|
||||
let quote = *bytes.get(i + 1)?;
|
||||
let quote = bytes.byte(i + 1)?;
|
||||
if quote != b'"' && quote != b'\'' {
|
||||
return None;
|
||||
}
|
||||
@@ -204,10 +255,11 @@ fn inline(text: &str) -> String {
|
||||
};
|
||||
let mut rest = text;
|
||||
let mut cache = QuoteCache::default();
|
||||
let bytes = Reader::new(text.as_bytes());
|
||||
while !rest.is_empty() {
|
||||
// Only a well-formed tag is markup; "1 < 2 and 3 > 2" and "a<b and c>d" are text.
|
||||
if rest.starts_with('<')
|
||||
&& let Some((end, closing, name)) = parse_tag(text.as_bytes(), text.len() - rest.len(), &mut cache)
|
||||
&& let Some((end, closing, name)) = parse_tag(bytes, text.len() - rest.len(), &mut cache)
|
||||
{
|
||||
let attr = match name.as_str() {
|
||||
"i" => Some("tts:fontStyle=\"italic\""),
|
||||
@@ -1171,15 +1223,34 @@ mod tests {
|
||||
assert_eq!(out, "<span tts:fontStyle=\"italic\">x</span>");
|
||||
}
|
||||
|
||||
/// `inline(text)` and the number of bytes the tag parser read for it.
|
||||
fn inline_cost(text: &str) -> (String, usize) {
|
||||
reader::READS.with(|r| r.set(0));
|
||||
let out = inline(text);
|
||||
(out, reader::READS.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// The tag parser reads each byte of `text` a bounded number of times, and twice the text costs about twice the work.
|
||||
fn assert_linear(make: impl Fn(usize) -> String, escaped: impl Fn(usize) -> String) {
|
||||
let (out, small) = inline_cost(&make(50_000));
|
||||
assert_eq!(out, escaped(50_000));
|
||||
let text = make(100_000);
|
||||
let (out, large) = inline_cost(&text);
|
||||
assert_eq!(out, escaped(100_000));
|
||||
assert!(large <= 3 * text.len(), "{large} byte reads in a text of {}", text.len());
|
||||
assert!(large < 3 * small, "twice the text, {small} then {large} byte reads");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unclosed_angle_brackets_are_escaped_in_one_pass() {
|
||||
// Every `<` used to search the rest of the text for a `>`, which made this quadratic.
|
||||
let text = "<".repeat(200_000);
|
||||
let started = std::time::Instant::now();
|
||||
let out = inline(&text);
|
||||
assert_eq!(out, "<".repeat(200_000));
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
assert_linear(|n| "<".repeat(n), |n| "<".repeat(n));
|
||||
// A tag before the unclosed tail is still markup; the tail stays literal text.
|
||||
assert_eq!(inline("<i>a</i> 1 < 2"), "<span tts:fontStyle=\"italic\">a</span> 1 < 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_unmatched_angle_brackets_before_one_gt_are_read_once() {
|
||||
assert_linear(|n| format!("{}>", "<".repeat(n)), |n| format!("{}>", "<".repeat(n)));
|
||||
}
|
||||
}
|
||||
@@ -66,11 +66,10 @@ fn whitespace_after_lt_is_literal_text() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The work for this text is checked in `ttml.rs`'s `many_unmatched_angle_brackets_before_one_gt_are_read_once`.
|
||||
#[test]
|
||||
fn many_unmatched_lt_is_fast() {
|
||||
fn many_unmatched_lt_stay_text() {
|
||||
let input = format!("{}>", "<".repeat(256_000));
|
||||
let start = std::time::Instant::now();
|
||||
let text = export(&input, Format::Ttml);
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(2), "took {:?}", start.elapsed());
|
||||
assert!(text.contains(&format!("{}>", "<".repeat(256_000))));
|
||||
}
|
||||
@@ -19,7 +19,7 @@ use std::sync::Arc;
|
||||
use super::picker::{ChannelRow, ChannelRule};
|
||||
use super::{ColorDisc, DiscHit, DiscLook, DiscRadius};
|
||||
use crate::harmony::{Guide, GuideOptions, Harmony, Variation};
|
||||
use craft_ui::choice::{CellMarks, SwatchTable, SwatchTableOutput};
|
||||
use craft_ui::choice::{CellMarks, SwatchSpacing, SwatchTable, SwatchTableOutput};
|
||||
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
@@ -503,6 +503,7 @@ impl<'a> HarmonyPanel<'a> {
|
||||
.multiple(true)
|
||||
.per_row(columns)
|
||||
.span(true)
|
||||
.spacing(SwatchSpacing::Spaced)
|
||||
.marks(move |&at| CellMarks::default().edge(at % columns == centre))
|
||||
.selection(Bind::bound(&mut selection));
|
||||
let SwatchTableOutput { selected, chosen: clicked, .. } = dragging(table, payload.as_ref(), &grid_cells).show_all(ui);
|
||||
|
||||
@@ -1451,3 +1451,23 @@ fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() {
|
||||
assert!(shades.left() <= grid.left() + 1.0 && shades.right() < grid.center().x, "Shades {shades:?} starts at the left edge of {grid:?}");
|
||||
assert!(tints.right() >= grid.right() - 1.0 && tints.left() > grid.center().x, "Tints {tints:?} ends at the right edge of {grid:?}");
|
||||
}
|
||||
|
||||
/// The Color Guide's variation cells stand apart: each cell's left edge lies right of the cell before it on its row,
|
||||
/// and each row's top lies below the row above it.
|
||||
#[trial]
|
||||
fn the_color_guide_variation_cells_stand_apart() {
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
let (mut state, mut picked) = (HarmonyPanelState::default(), HarmonyPicked::default());
|
||||
let _ = HarmonyPanel::new(Bind::bound(&mut state), Bind::bound(&mut picked), RED).show(ui);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let grid = fixture.by_label("Variations").expect("the variations grid");
|
||||
let cells: Vec<egui::Rect> =
|
||||
fixture.tree().children_of(grid.node).into_iter().filter_map(|key| fixture.target(key)).map(|cell| cell.rect).collect();
|
||||
assert!(cells.len() >= 4, "the grid holds its cells: {cells:?}");
|
||||
let (first, next) = (cells[0], cells[1]);
|
||||
assert!((first.center().y - next.center().y).abs() < 0.5, "the first two cells share a row: {cells:?}");
|
||||
assert!(next.left() >= first.right() + 1.0, "a gap lies between two cells of a row: {first:?}, {next:?}");
|
||||
let below = cells.iter().find(|cell| cell.top() > first.center().y).expect("a second row of cells");
|
||||
assert!(below.top() >= first.bottom() + 1.0, "a gap lies between two rows: {first:?}, {below:?}");
|
||||
}
|
||||
@@ -11,7 +11,11 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form
|
||||
glTF 2.0 recommends for meshes without tangents
|
||||
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>): `w` holds the bitangent sign.
|
||||
- **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting
|
||||
vertices where charts meet.
|
||||
vertices where charts meet. It checks the mesh against its size limits and its attribute data
|
||||
first and returns an error without changing the mesh when a check fails. Charts are projected
|
||||
and packed in `f64`. Padding uses the
|
||||
requested resolution, with a minimum resolution of 16. A layout that cannot fit returns an
|
||||
error without changing the mesh. Missing normals use area-weighted `f64` accumulation and normalization.
|
||||
- **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle
|
||||
and barycentrics under the texel center; `surface_at` turns them into a position, normal and
|
||||
tangent frame. `UvGBuffer::new` returns an error for a side of 0 or above `MAX_SIDE` (16,384),
|
||||
@@ -22,6 +26,9 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form
|
||||
return `Result<Mesh>`. They reject non-finite or nonpositive dimensions and dimensions whose
|
||||
doubled half extents overflow. A box bevel must be finite and between zero and 95% of its
|
||||
smallest half extent; an invalid bevel returns `GeomError::Invalid`.
|
||||
Sphere and torus seam endpoints have identical positions and retain distinct UV endpoints.
|
||||
Cylinder caps share exact rim positions with the side, and rounded-box faces share exact boundary positions.
|
||||
Lathe profile lengths and direction normalization use `f64` before the UVs and normals are stored as `f32`.
|
||||
- **BVH.** `Bvh` is a binned SAH tree on all three axes with a median split when no split beats a
|
||||
leaf. It answers closest-hit, any-hit and filtered ray casts, nearest-point queries and box
|
||||
queries.
|
||||
|
||||
+73
-11
@@ -110,34 +110,69 @@ impl Mesh {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`
|
||||
/// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`.
|
||||
/// An edge between two vertices at one position is not listed, and a triangle with two corners at one position
|
||||
/// connects its two other edges in UV space, as the corners of a pole row do.
|
||||
pub fn uv_seam_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
// Signed zero denotes the same position on either side of an imported seam
|
||||
let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() });
|
||||
let mut seams = vec![Vec::new(); self.materials.len().max(1)];
|
||||
// Match across materials before grouping the lines for texture-set visibility
|
||||
let mut sides: std::collections::HashMap<EdgePositions, Vec<(u32, u32, usize)>> = std::collections::HashMap::new();
|
||||
// A triangle with two corners at one position joins its two edges to the third corner in UV space
|
||||
let mut joins: std::collections::HashMap<EdgePositions, Vec<[(u32, u32); 2]>> = std::collections::HashMap::new();
|
||||
let canonical = |from: u32, to: u32, from_bits: [u32; 3], to_bits: [u32; 3]| {
|
||||
if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) }
|
||||
};
|
||||
for material in 0..seams.len() {
|
||||
for triangle in self.triangles_of(material) {
|
||||
let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue };
|
||||
let Some(corner_bits) =
|
||||
corners.iter().map(|&corner| self.positions.get(corner as usize).map(|p| bits(*p))).collect::<Option<Vec<_>>>()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] {
|
||||
let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else {
|
||||
for (a, b) in [(0, 1), (1, 2), (2, 0)] {
|
||||
// An edge between two vertices at one position has no length to draw
|
||||
if corner_bits[a] == corner_bits[b] {
|
||||
let c = 3 - a - b;
|
||||
if corner_bits[c] != corner_bits[a] {
|
||||
let (edge, first) = canonical(corners[a], corners[c], corner_bits[a], corner_bits[c]);
|
||||
let (_, second) = canonical(corners[b], corners[c], corner_bits[b], corner_bits[c]);
|
||||
joins.entry(edge).or_default().push([first, second]);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
|
||||
let (from_bits, to_bits) = (bits(*from_position), bits(*to_position));
|
||||
let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) };
|
||||
}
|
||||
let (edge, pair) = canonical(corners[a], corners[b], corner_bits[a], corner_bits[b]);
|
||||
sides.entry(edge).or_default().push((pair.0, pair.1, material));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let uv = |index: u32| self.uvs.get(index as usize).copied();
|
||||
for pairs in sides.into_values() {
|
||||
let Some(&(first_from, first_to, _)) = pairs.first() else { continue };
|
||||
for (edge, pairs) in sides {
|
||||
// Group the UV layouts of this edge, joining the layouts a collapsed triangle connects
|
||||
let mut layouts = Vec::new();
|
||||
for &(from, to, _) in &pairs {
|
||||
if !layouts.contains(&(uv(from), uv(to))) {
|
||||
layouts.push((uv(from), uv(to)));
|
||||
}
|
||||
}
|
||||
let mut group: Vec<usize> = (0..layouts.len()).collect();
|
||||
for [first, second] in joins.get(&edge).into_iter().flatten() {
|
||||
let find = |(from, to): (u32, u32)| layouts.iter().position(|layout| *layout == (uv(from), uv(to)));
|
||||
if let (Some(first), Some(second)) = (find(*first), find(*second)) {
|
||||
let (kept, merged) = (group[first], group[second]);
|
||||
for g in &mut group {
|
||||
if *g == merged {
|
||||
*g = kept;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) {
|
||||
if group.iter().any(|&g| g != group[0]) {
|
||||
for (from, to, material) in pairs {
|
||||
if let Some(edges) = seams.get_mut(material) {
|
||||
edges.push((from.min(to), from.max(to)));
|
||||
@@ -401,14 +436,22 @@ impl Mesh {
|
||||
(m.positions.len() - 1) as u32
|
||||
})
|
||||
};
|
||||
for t in self.indices.as_chunks::<3>().0 {
|
||||
// Each child keeps the hidden bits of the halves of the parent's edges it has; the edges
|
||||
// inside the parent are real.
|
||||
let mut diagonals = Vec::with_capacity(if self.diagonals.is_empty() { 0 } else { self.diagonals.len().saturating_mul(4) });
|
||||
for (k, t) in self.indices.as_chunks::<3>().0.iter().enumerate() {
|
||||
if t.iter().any(|&i| i as usize >= self.positions.len()) {
|
||||
continue;
|
||||
}
|
||||
let (a, b, c) = (t[0], t[1], t[2]);
|
||||
let (ab, bc, ca) = (mid(&mut m, a, b), mid(&mut m, b, c), mid(&mut m, c, a));
|
||||
m.indices.extend_from_slice(&[a, ab, ca, ab, b, bc, ca, bc, c, ab, bc, ca]);
|
||||
if !self.diagonals.is_empty() {
|
||||
let h = self.diagonals.get(k).copied().unwrap_or(0);
|
||||
diagonals.extend_from_slice(&[h & 0b101, h & 0b011, h & 0b110, 0]);
|
||||
}
|
||||
}
|
||||
m.diagonals = diagonals;
|
||||
for s in &mut m.submeshes {
|
||||
s.start *= 4;
|
||||
s.count *= 4;
|
||||
@@ -530,6 +573,12 @@ mod tests {
|
||||
a.append(&m);
|
||||
assert_eq!(a.diagonals, vec![0, 0b100, 0b001]);
|
||||
assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges");
|
||||
// Subdividing hides both halves of the diagonal and nothing else: 16 edges less 2.
|
||||
let sub = m.subdivided();
|
||||
assert_eq!(sub.diagonals.len(), sub.triangle_count());
|
||||
let edges = &sub.wire_edges()[0];
|
||||
assert_eq!(edges.len(), 14);
|
||||
assert!(edges.iter().all(|&(a, b)| !matches!((a, b), (0, 6) | (2, 6))), "diagonal halves {edges:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -564,6 +613,19 @@ mod tests {
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_skip_edges_between_vertices_at_one_position() {
|
||||
let (segments, rings) = (3, 2);
|
||||
let mesh = crate::primitives::sphere(1.0, segments, rings);
|
||||
let seams = mesh.uv_seam_edges();
|
||||
assert!(
|
||||
seams[0].iter().all(|&(from, to)| mesh.positions[from as usize] != mesh.positions[to as usize]),
|
||||
"zero-length seam edges at a pole: {seams:?}"
|
||||
);
|
||||
// Only the meridian where u = 0 meets u = 1 is a seam: columns 0 and 3, with the collapsed pole triangles
|
||||
assert_eq!(seams, vec![vec![(0, 4), (2, 7), (3, 7), (4, 8), (4, 9), (7, 11)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_between_materials_belong_to_both_materials() {
|
||||
let mut mesh = quad();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::f32::consts::{PI, TAU};
|
||||
|
||||
use glam::{Vec2, Vec3};
|
||||
use glam::{DVec2, Vec2, Vec3};
|
||||
|
||||
use crate::mesh::{Mesh, SubMesh};
|
||||
use crate::{GeomError, Result};
|
||||
@@ -88,7 +88,8 @@ impl Builder {
|
||||
}
|
||||
}
|
||||
|
||||
/// UV sphere of `radius` centred at `center`.
|
||||
/// A UV sphere of `radius` centered at the origin. The seam endpoints have identical positions
|
||||
/// at each ring. Vertices at each pole share one position.
|
||||
pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh {
|
||||
let mut b = Builder::default();
|
||||
sphere_into(&mut b, Vec3::ZERO, radius, segments.max(3), rings.max(2), UvRect::FULL);
|
||||
@@ -98,8 +99,14 @@ pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh {
|
||||
fn sphere_into(b: &mut Builder, center: Vec3, radius: f32, segs: usize, rings: usize, r: UvRect) {
|
||||
b.grid(rings, segs, |i, j| {
|
||||
let (u, v) = (j as f32 / segs as f32, i as f32 / rings as f32);
|
||||
let (theta, phi) = (v * PI, u * TAU + PI * 1.5);
|
||||
let n = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin());
|
||||
let (theta, phi) = (v * PI, if j == segs { PI * 1.5 } else { u * TAU + PI * 1.5 });
|
||||
let n = if i == 0 {
|
||||
Vec3::Y
|
||||
} else if i == rings {
|
||||
-Vec3::Y
|
||||
} else {
|
||||
Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin())
|
||||
};
|
||||
(center + n * radius, n, r.map(u, v))
|
||||
});
|
||||
}
|
||||
@@ -153,7 +160,10 @@ fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: Uv
|
||||
v.push(inner * (2.0 * (i as f32 / kc as f32) - 1.0));
|
||||
}
|
||||
for i in 1..=kb {
|
||||
v.push(inner + bevel * (i as f32 / kb as f32));
|
||||
v.push(if i == kb { h } else { inner + bevel * (i as f32 / kb as f32) });
|
||||
}
|
||||
for i in 0..v.len() / 2 {
|
||||
v[i] = -v[v.len() - 1 - i];
|
||||
}
|
||||
v
|
||||
};
|
||||
@@ -167,7 +177,7 @@ fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: Uv
|
||||
let (a, c) = (cu[j], cv[i]);
|
||||
let q = *n * hn + *u * a + *v * c;
|
||||
let clamped = q.clamp(-inner, inner);
|
||||
let dir = (q - clamped).try_normalize().unwrap_or(*n);
|
||||
let dir = (q - clamped).as_dvec3().try_normalize().map(|v| v.as_vec3()).unwrap_or(*n);
|
||||
let p = if bevel > 0.0 { clamped + dir * bevel } else { q };
|
||||
let nn = if bevel > 0.0 { dir } else { *n };
|
||||
(center + p, nn, cell.map((a + hu) / (2.0 * hu), (c + hv) / (2.0 * hv)))
|
||||
@@ -181,26 +191,28 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize
|
||||
if profile.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let mut len = vec![0.0f32];
|
||||
let mut len = vec![0.0f64];
|
||||
for w in profile.windows(2) {
|
||||
let d = Vec2::new(w[1].0 - w[0].0, w[1].1 - w[0].1).length();
|
||||
let d = DVec2::new(f64::from(w[1].0) - f64::from(w[0].0), f64::from(w[1].1) - f64::from(w[0].1)).length();
|
||||
len.push(len.last().copied().unwrap_or(0.0) + d);
|
||||
}
|
||||
let total = len.last().copied().unwrap_or(1.0).max(1e-6);
|
||||
let total = len.last().copied().filter(|total| *total > 0.0).unwrap_or(1.0);
|
||||
let rows = profile.len() - 1;
|
||||
b.grid(rows, segs, |i, j| {
|
||||
let (rad, y) = profile[i];
|
||||
// Profile tangent (downwards) → outward normal in the (r, y) plane.
|
||||
let prev = profile[i.saturating_sub(1)];
|
||||
let next = profile[(i + 1).min(rows)];
|
||||
let t = Vec2::new(next.0 - prev.0, next.1 - prev.1).try_normalize().unwrap_or(Vec2::NEG_Y);
|
||||
let t = DVec2::new(f64::from(next.0) - f64::from(prev.0), f64::from(next.1) - f64::from(prev.1))
|
||||
.try_normalize()
|
||||
.map(|t| t.as_vec2())
|
||||
.unwrap_or(Vec2::NEG_Y);
|
||||
let n2 = Vec2::new(-t.y, t.x);
|
||||
let u = j as f32 / segs as f32;
|
||||
let phi = u * TAU + PI * 1.5;
|
||||
let dir = Vec3::new(phi.cos(), 0.0, -phi.sin());
|
||||
let dir = circle_sample(j, segs);
|
||||
let p = center + dir * rad + Vec3::Y * y;
|
||||
let n = dir * n2.x + Vec3::Y * n2.y;
|
||||
(p, n, r.map(u, len[i] / total))
|
||||
(p, n, r.map(u, (len[i] / total) as f32))
|
||||
});
|
||||
}
|
||||
|
||||
@@ -331,14 +343,19 @@ fn preview_orb_radius(d: Vec3) -> f32 {
|
||||
radius + relief
|
||||
}
|
||||
|
||||
fn circle_sample(column: usize, segments: usize) -> Vec3 {
|
||||
let angle = if column == segments { PI * 1.5 } else { column as f32 / segments as f32 * TAU + PI * 1.5 };
|
||||
Vec3::new(angle.cos(), 0.0, -angle.sin())
|
||||
}
|
||||
|
||||
/// A flat disk facing up (+Y) or down, with planar UVs inside `r`.
|
||||
fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) {
|
||||
let n = if up { Vec3::Y } else { Vec3::NEG_Y };
|
||||
let c = b.vert(center, n, r.map(0.5, 0.5));
|
||||
let first = b.p.len() as u32;
|
||||
for j in 0..segs {
|
||||
let a = j as f32 / segs as f32 * TAU;
|
||||
let (x, z) = (a.cos(), a.sin());
|
||||
let sample = circle_sample(j, segs);
|
||||
let (x, z) = (sample.x, sample.z);
|
||||
// Top view: +X right, +Z down the texture; bottom view mirrors X.
|
||||
let uv = if up { r.map(0.5 + x * 0.5, 0.5 + z * 0.5) } else { r.map(0.5 + x * 0.5, 0.5 - z * 0.5) };
|
||||
b.vert(center + Vec3::new(x, 0.0, z) * radius, n, uv);
|
||||
@@ -346,9 +363,9 @@ fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize,
|
||||
for j in 0..segs as u32 {
|
||||
let (a, bb) = (first + j, first + (j + 1) % segs as u32);
|
||||
if up {
|
||||
b.idx.extend_from_slice(&[c, bb, a]);
|
||||
} else {
|
||||
b.idx.extend_from_slice(&[c, a, bb]);
|
||||
} else {
|
||||
b.idx.extend_from_slice(&[c, bb, a]);
|
||||
}
|
||||
b.diag.push(0);
|
||||
}
|
||||
@@ -370,8 +387,8 @@ pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh {
|
||||
let (segs, sides) = (segs.max(3), sides.max(3));
|
||||
b.grid(sides, segs, |i, j| {
|
||||
let (u, v) = (j as f32 / segs as f32, i as f32 / sides as f32);
|
||||
let phi = u * TAU + PI * 1.5;
|
||||
let theta = v * TAU;
|
||||
let phi = if j == segs { PI * 1.5 } else { u * TAU + PI * 1.5 };
|
||||
let theta = if i == sides { 0.0 } else { v * TAU };
|
||||
let dir = Vec3::new(phi.cos(), 0.0, -phi.sin());
|
||||
let n = dir * theta.cos() - Vec3::Y * theta.sin();
|
||||
(dir * major + n * minor, n, Vec2::new(u, v))
|
||||
@@ -503,6 +520,145 @@ pub const BUILTINS: [(&str, &str); 9] = [
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn lathe_profile_uvs_are_independent_of_height() {
|
||||
let side_range = |mesh: &Mesh| {
|
||||
mesh.uvs
|
||||
.iter()
|
||||
.zip(&mesh.normals)
|
||||
.filter(|(_, normal)| normal.y.abs() < 0.5)
|
||||
.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), (uv, _)| (lo.min(uv.y), hi.max(uv.y)))
|
||||
};
|
||||
let expected = side_range(&cylinder(1.0, 1.0, 16));
|
||||
let actual = side_range(&cylinder(1.0, 1e-20, 16));
|
||||
assert!((actual.0 - expected.0).abs() < 1e-6 && (actual.1 - expected.1).abs() < 1e-6, "{actual:?} {expected:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tall_cylinders_keep_finite_profile_uvs_and_unit_normals() {
|
||||
let mesh = cylinder(1.0, 1e20, 16);
|
||||
mesh.validate().unwrap();
|
||||
assert!(mesh.uvs.iter().all(|uv| uv.is_finite() && uv.min_element() >= 0.0 && uv.max_element() <= 1.0));
|
||||
assert!(mesh.normals.iter().all(|normal| normal.is_finite() && (normal.length_squared() - 1.0).abs() < 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepted_small_box_dimensions_are_preserved() {
|
||||
let cube = cube(1e-7).unwrap();
|
||||
let (lo, hi) = cube.bounds();
|
||||
assert_eq!(hi - lo, Vec3::splat(1e-7));
|
||||
let half = Vec3::new(5e-8, 2e-7, 3e-7);
|
||||
let mesh = rounded_box(half, 0.0).unwrap();
|
||||
let (lo, hi) = mesh.bounds();
|
||||
assert_eq!((lo, hi), (-half, half));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounded_box_face_boundaries_share_exact_positions() {
|
||||
for (half, bevel) in [(1.038, 0.037), (1e21, 1e20)] {
|
||||
let mut builder = Builder::default();
|
||||
rounded_box_into(&mut builder, Vec3::ZERO, Vec3::splat(half), bevel, UvRect::FULL);
|
||||
assert!(builder.n[0].abs().min_element() > 0.5, "rounded corner normal {:?}, half={half}", builder.n[0]);
|
||||
let key = |p: Vec3| p.to_array().map(|v| if v == 0.0 { 0 } else { v.to_bits() });
|
||||
let mut counts = std::collections::HashMap::new();
|
||||
for &position in &builder.p {
|
||||
*counts.entry(key(position)).or_insert(0usize) += 1;
|
||||
}
|
||||
let side = 23;
|
||||
for face in 0..6 {
|
||||
for row in 0..side {
|
||||
for column in 0..side {
|
||||
if row == 0 || column == 0 || row == side - 1 || column == side - 1 {
|
||||
let position = builder.p[face * side * side + row * side + column];
|
||||
assert!(counts[&key(position)] >= 2, "unmatched boundary {position:?}, half={half}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cylinder_caps_match_the_wall_at_every_segment_count() {
|
||||
for segments in [3, 6, 7, 32] {
|
||||
let mesh = cylinder(1.0, 2.0, segments);
|
||||
for row in 0..=1 {
|
||||
let (first, last) = (row * (segments + 1), row * (segments + 1) + segments);
|
||||
assert_eq!(mesh.positions[first], mesh.positions[last]);
|
||||
assert_eq!(mesh.normals[first], mesh.normals[last]);
|
||||
assert!(mesh.uvs[first].x < mesh.uvs[last].x);
|
||||
}
|
||||
for y in [-1.0, 1.0] {
|
||||
let wall: Vec<_> = mesh
|
||||
.positions
|
||||
.iter()
|
||||
.zip(&mesh.normals)
|
||||
.filter_map(|(position, normal)| (position.y == y && normal.y == 0.0).then_some(*position))
|
||||
.collect();
|
||||
let rim: Vec<_> = mesh
|
||||
.positions
|
||||
.iter()
|
||||
.zip(&mesh.normals)
|
||||
.filter_map(|(position, normal)| {
|
||||
(position.y == y && normal.y != 0.0 && position.x * position.x + position.z * position.z > 0.5).then_some(*position)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(rim.len(), segments);
|
||||
assert!(rim.iter().all(|position| wall.contains(position)), "{segments} segments at height {y}: {rim:?} vs {wall:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sphere_poles_use_identical_endpoint_positions() {
|
||||
for segments in [3, 7, 32] {
|
||||
let rings = 8;
|
||||
let mesh = sphere(1.0, segments, rings);
|
||||
for (row, expected) in [(0, Vec3::Y), (rings, -Vec3::Y)] {
|
||||
for column in 0..=segments {
|
||||
let index = row * (segments + 1) + column;
|
||||
assert_eq!(mesh.positions[index], expected);
|
||||
assert_eq!(mesh.normals[index], expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sphere_geometry_closes_its_longitudinal_uv_seam_exactly() {
|
||||
for segments in [3, 7, 32] {
|
||||
let rings = 8;
|
||||
let mesh = sphere(1.0, segments, rings);
|
||||
let width = segments + 1;
|
||||
for row in 0..=rings {
|
||||
let (a, b) = (row * width, row * width + segments);
|
||||
assert_eq!(mesh.positions[a], mesh.positions[b], "seam row {row}");
|
||||
assert_eq!(mesh.normals[a], mesh.normals[b], "seam normal row {row}");
|
||||
assert_eq!((mesh.uvs[a].x, mesh.uvs[b].x), (0.0, 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn torus_geometry_closes_both_uv_seams_exactly() {
|
||||
for (segs, sides) in [(3, 3), (7, 5), (32, 12)] {
|
||||
let mesh = torus(1.0, 0.35, segs, sides);
|
||||
let width = segs + 1;
|
||||
for row in 0..=sides {
|
||||
let (a, b) = (row * width, row * width + segs);
|
||||
assert_eq!(mesh.positions[a], mesh.positions[b], "u seam row {row}");
|
||||
assert_eq!(mesh.normals[a], mesh.normals[b], "u seam normal row {row}");
|
||||
assert_eq!((mesh.uvs[a].x, mesh.uvs[b].x), (0.0, 1.0));
|
||||
}
|
||||
for col in 0..=segs {
|
||||
let (a, b) = (col, sides * width + col);
|
||||
assert_eq!(mesh.positions[a], mesh.positions[b], "v seam column {col}");
|
||||
assert_eq!(mesh.normals[a], mesh.normals[b], "v seam normal column {col}");
|
||||
assert_eq!((mesh.uvs[a].y, mesh.uvs[b].y), (0.0, 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
|
||||
+403
-125
@@ -1,32 +1,36 @@
|
||||
//! Automatic UV unwrapping for meshes imported without texture coordinates.
|
||||
//!
|
||||
//! Triangles are grouped into charts by flood fill across shared (welded) edges while each face
|
||||
//! normal stays within 60° of the chart's seed face, so every chart is a height field over its
|
||||
//! seed plane and projects onto it without flipping. Charts are rotated to their principal axes
|
||||
//! and shelf-packed per material into 0..1 with one uniform scale, so texel density is the same
|
||||
//! normal stays within 60° of the chart's seed face. Charts are rotated to their principal axes
|
||||
//! and shelf-packed per material into 0..1 with one uniform scale. Texel density is the same
|
||||
//! everywhere within a material.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
use glam::{Vec2, Vec3};
|
||||
use glam::{DVec2, DVec3, Vec2, Vec3};
|
||||
|
||||
use crate::{GeomError, Mesh, Result};
|
||||
|
||||
/// Vertices an unwrap accepts, and the most it produces.
|
||||
const MAX_UNWRAP_VERTICES: usize = 20_000_000;
|
||||
/// Triangles an unwrap accepts, counting a triangle once for each submesh that lists it.
|
||||
const MAX_UNWRAP_TRIANGLES: usize = 4_000_000;
|
||||
|
||||
/// Faces of a chart stay within this angle of the seed face normal (cos 60°).
|
||||
const CHART_COS: f32 = 0.5;
|
||||
/// Packing never goes beyond this virtual resolution (texels per side).
|
||||
const MAX_PACK_RES: f32 = 65_536.0;
|
||||
|
||||
/// Welded vertex id per vertex: vertices at the same position (snapped to a grid of 1e-6 of
|
||||
/// the bounding diagonal) share an id. Ids are dense, in order of first appearance.
|
||||
pub fn weld_ids(positions: &[Vec3]) -> Vec<u32> {
|
||||
let (lo, hi) = positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
|
||||
let cell = ((hi - lo).length() * 1e-6).max(1e-12);
|
||||
let (lo, hi) =
|
||||
positions.iter().map(|p| p.as_dvec3()).fold((DVec3::splat(f64::MAX), DVec3::splat(f64::MIN)), |(lo, hi), p| (lo.min(p), hi.max(p)));
|
||||
let diagonal = (hi - lo).length();
|
||||
let cell = if diagonal > 0.0 && diagonal.is_finite() { diagonal * 1e-6 } else { 1.0 };
|
||||
let mut map: HashMap<[i64; 3], u32> = HashMap::with_capacity(positions.len());
|
||||
positions
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let q = ((*p - lo) / cell).round();
|
||||
let q = ((p.as_dvec3() - lo) / cell).round();
|
||||
let next = map.len() as u32;
|
||||
*map.entry([q.x as i64, q.y as i64, q.z as i64]).or_insert(next)
|
||||
})
|
||||
@@ -44,62 +48,163 @@ pub fn all_triangles_degenerate(mesh: &Mesh) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn face_has_area(positions: [Vec3; 3]) -> bool {
|
||||
(0..3).any(|axis| {
|
||||
let next = (axis + 1) % 3;
|
||||
let [a, b, c] = positions.map(|position| [f64::from(position[axis]), f64::from(position[next])]);
|
||||
let products = [a[0] * b[1], b[0] * c[1], c[0] * a[1], -a[1] * b[0], -b[1] * c[0], -c[1] * a[0]];
|
||||
let (mut expansion, mut len) = ([0.0; 6], 0);
|
||||
for mut value in products {
|
||||
let mut kept = 0;
|
||||
for index in 0..len {
|
||||
let part = expansion[index];
|
||||
let sum = value + part;
|
||||
let part_virtual = sum - value;
|
||||
let value_virtual = sum - part_virtual;
|
||||
let error = (value - value_virtual) + (part - part_virtual);
|
||||
if error != 0.0 {
|
||||
expansion[kept] = error;
|
||||
kept += 1;
|
||||
}
|
||||
value = sum;
|
||||
}
|
||||
expansion[kept] = value;
|
||||
len = kept + 1;
|
||||
}
|
||||
expansion[..len].iter().any(|part| *part != 0.0)
|
||||
})
|
||||
}
|
||||
|
||||
struct Chart {
|
||||
material: usize,
|
||||
/// The seed face's first corner. Projections are taken relative to it, in `f64`, so they
|
||||
/// keep the chart's own detail wherever the chart lies.
|
||||
origin: DVec3,
|
||||
/// Projection basis (right-handed with the seed normal).
|
||||
t: Vec3,
|
||||
b: Vec3,
|
||||
t: DVec3,
|
||||
b: DVec3,
|
||||
/// Rotation to the chart's principal axes (cos, sin).
|
||||
rot: Vec2,
|
||||
lo: Vec2,
|
||||
hi: Vec2,
|
||||
/// Texel offset of the chart's packed rectangle and the material's scale and resolution.
|
||||
offset: Vec2,
|
||||
rot: DVec2,
|
||||
/// Bounds of the rotated chart. Charts are measured and packed in `f64`, where the extent of
|
||||
/// any chart of finite `f32` positions and the scale that packs it neither overflow nor
|
||||
/// round to zero.
|
||||
lo: DVec2,
|
||||
hi: DVec2,
|
||||
/// Texel offset of the chart's packed rectangle.
|
||||
offset: DVec2,
|
||||
}
|
||||
|
||||
impl Chart {
|
||||
fn local(&self, p: Vec3) -> Vec2 {
|
||||
let q = Vec2::new(p.dot(self.t), p.dot(self.b));
|
||||
Vec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x)
|
||||
fn local(&self, p: Vec3) -> DVec2 {
|
||||
let d = p.as_dvec3() - self.origin;
|
||||
let q = DVec2::new(d.dot(self.t), d.dot(self.b));
|
||||
DVec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x)
|
||||
}
|
||||
fn size(&self) -> Vec2 {
|
||||
(self.hi - self.lo).max(Vec2::ZERO)
|
||||
fn size(&self) -> DVec2 {
|
||||
(self.hi - self.lo).max(DVec2::ZERO)
|
||||
}
|
||||
}
|
||||
|
||||
/// The material each triangle is unwrapped for; triangles in no submesh count as material 0. Returns an error when submeshes of two
|
||||
/// materials share a triangle.
|
||||
fn triangle_materials(mesh: &Mesh) -> Result<Vec<usize>> {
|
||||
let mut material = vec![None; mesh.triangle_count()];
|
||||
for s in &mesh.submeshes {
|
||||
for t in (s.start / 3) as usize..((s.start as usize + s.count as usize) / 3) {
|
||||
if let Some(m) = material.get_mut(t) {
|
||||
if let Some(other) = *m
|
||||
&& other != s.material
|
||||
{
|
||||
return Err(GeomError::Invalid(format!("triangle {t} is in submeshes of materials {other} and {}", s.material)));
|
||||
}
|
||||
*m = Some(s.material);
|
||||
/// Area-weighted smooth normals over the index buffer, as [`Mesh::compute_normals`] computes
|
||||
/// them, returned instead of stored.
|
||||
fn smooth_normals(mesh: &Mesh) -> Vec<Vec3> {
|
||||
let mut normals = vec![DVec3::ZERO; mesh.positions.len()];
|
||||
for &[a, b, c] in mesh.indices.as_chunks::<3>().0 {
|
||||
let (a, b, c) = (a as usize, b as usize, c as usize);
|
||||
let (Some(pa), Some(pb), Some(pc)) = (mesh.positions.get(a), mesh.positions.get(b), mesh.positions.get(c)) else { continue };
|
||||
let face = (pb.as_dvec3() - pa.as_dvec3()).cross(pc.as_dvec3() - pa.as_dvec3());
|
||||
for v in [a, b, c] {
|
||||
if let Some(x) = normals.get_mut(v) {
|
||||
*x += face;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(material.into_iter().map(|m| m.unwrap_or(0)).collect())
|
||||
normals.into_iter().map(|v| v.try_normalize().map(|normal| normal.as_vec3()).unwrap_or(Vec3::Y)).collect()
|
||||
}
|
||||
|
||||
/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its
|
||||
/// own 0..1 space with charts at least `padding_texels` (minimum 1) away from each other and
|
||||
/// the borders at `resolution`. Vertices are split at chart borders; tangents are recomputed.
|
||||
/// Returns the number of charts, or an error, before any change to the mesh, when submeshes of
|
||||
/// two materials share a triangle.
|
||||
pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result<usize> {
|
||||
/// The checks [`auto_unwrap`] makes before it changes anything. The size limits come first.
|
||||
fn check_input(mesh: &Mesh) -> Result<()> {
|
||||
if mesh.positions.len() > MAX_UNWRAP_VERTICES {
|
||||
return Err(GeomError::Invalid(format!("mesh has {} vertices; unwrapping accepts at most {MAX_UNWRAP_VERTICES}", mesh.positions.len())));
|
||||
}
|
||||
if mesh.triangle_count() > MAX_UNWRAP_TRIANGLES {
|
||||
return Err(GeomError::Invalid(format!("mesh has {} triangles; unwrapping accepts at most {MAX_UNWRAP_TRIANGLES}", mesh.triangle_count())));
|
||||
}
|
||||
let listed = mesh.submeshes.iter().fold(0u64, |sum, s| sum.saturating_add(u64::from(s.count / 3)));
|
||||
if listed > MAX_UNWRAP_TRIANGLES as u64 {
|
||||
return Err(GeomError::Invalid(format!("submeshes list {listed} triangles; unwrapping accepts at most {MAX_UNWRAP_TRIANGLES}")));
|
||||
}
|
||||
mesh.validate_indices()?;
|
||||
for s in &mesh.submeshes {
|
||||
if !s.start.is_multiple_of(3) || !s.count.is_multiple_of(3) {
|
||||
return Err(GeomError::Invalid(format!("submesh {} is not triangle-aligned", s.name)));
|
||||
}
|
||||
if u64::from(s.start) + u64::from(s.count) > mesh.indices.len() as u64 || s.material >= mesh.materials.len().max(1) {
|
||||
return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name)));
|
||||
}
|
||||
}
|
||||
if mesh.positions.iter().any(|p| !p.is_finite()) {
|
||||
return Err(GeomError::Invalid("mesh has non-finite positions".into()));
|
||||
}
|
||||
if mesh.normals.len() == mesh.positions.len() && mesh.normals.iter().any(|v| !v.is_finite()) {
|
||||
return Err(GeomError::Invalid("mesh has non-finite normals".into()));
|
||||
}
|
||||
if !mesh.colors.is_empty() && (mesh.colors.len() != mesh.positions.len() || mesh.colors.iter().any(|c| !c.is_finite())) {
|
||||
return Err(GeomError::Invalid("mesh colors are not one finite color per vertex".into()));
|
||||
}
|
||||
if all_triangles_degenerate(mesh) {
|
||||
return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into()));
|
||||
}
|
||||
let material = triangle_materials(mesh)?;
|
||||
if mesh.normals.len() != mesh.positions.len() {
|
||||
mesh.compute_normals();
|
||||
if !mesh.indices.is_empty()
|
||||
&& mesh.indices.as_chunks::<3>().0.iter().all(|vertices| !face_has_area(vertices.map(|vertex| mesh.positions[vertex as usize])))
|
||||
{
|
||||
return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The material of every triangle. Each material is packed into its own 0..1 square, so a
|
||||
/// triangle that submeshes of two materials list would be laid out over another chart of one of
|
||||
/// them, and is an error. Every triangle must be listed by a submesh.
|
||||
fn face_materials(mesh: &Mesh) -> Result<Vec<usize>> {
|
||||
let n = mesh.triangle_count();
|
||||
let mut material = vec![usize::MAX; n];
|
||||
for s in &mesh.submeshes {
|
||||
let end = (u64::from(s.start) + u64::from(s.count)) / 3;
|
||||
for t in (s.start / 3) as usize..(end as usize).min(n) {
|
||||
if let Some(m) = material.get_mut(t) {
|
||||
if *m != usize::MAX && *m != s.material {
|
||||
return Err(GeomError::Invalid(format!("triangle {t} is in submeshes of materials {} and {}", *m, s.material)));
|
||||
}
|
||||
*m = s.material;
|
||||
}
|
||||
}
|
||||
}
|
||||
if material.contains(&usize::MAX) {
|
||||
return Err(GeomError::Invalid("submeshes do not cover every triangle".into()));
|
||||
}
|
||||
Ok(material)
|
||||
}
|
||||
|
||||
/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its
|
||||
/// own 0..1 space with charts at least `padding_texels` (minimum 1, which a NaN counts as) away
|
||||
/// from each other and the borders at `resolution`. Vertices are split at chart borders;
|
||||
/// tangents are recomputed. Returns the number of charts.
|
||||
/// The effective resolution is at least 16. A layout that cannot fit with the requested
|
||||
/// padding returns an error without changing the mesh.
|
||||
///
|
||||
/// A mesh that fails a check is returned unchanged: indices, triangle-aligned submesh ranges
|
||||
/// that cover every triangle, materials, no
|
||||
/// triangle listed by submeshes of two materials, finite positions, finite normals and colors
|
||||
/// when it has them, at least one triangle that is not degenerate, and the size limits (20
|
||||
/// million vertices; 4 million triangles, counting a triangle once for each submesh that lists
|
||||
/// it). The limits are checked before any other work. More than 20 million new vertices is an
|
||||
/// error as well.
|
||||
pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result<usize> {
|
||||
check_input(mesh)?;
|
||||
// Kept apart from the mesh until the layout is packed, so an error leaves the mesh as it was.
|
||||
let computed_normals = if mesh.normals.len() != mesh.positions.len() { Some(smooth_normals(mesh)) } else { None };
|
||||
let old_normals = computed_normals.as_deref().unwrap_or(&mesh.normals);
|
||||
let n = mesh.triangle_count();
|
||||
let weld = weld_ids(&mesh.positions);
|
||||
let pos = |v: usize| mesh.positions.get(v).copied().unwrap_or_default();
|
||||
@@ -109,11 +214,12 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res
|
||||
let mut normal: Vec<Option<Vec3>> = Vec::with_capacity(n);
|
||||
let mut area = Vec::with_capacity(n);
|
||||
for t in 0..n {
|
||||
let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]);
|
||||
let cr = (pos(b) - pos(a)).cross(pos(c) - pos(a));
|
||||
let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]).map(|v| pos(v).as_dvec3());
|
||||
let cr = (b - a).cross(c - a);
|
||||
area.push(cr.length() * 0.5);
|
||||
normal.push(cr.try_normalize());
|
||||
normal.push(cr.try_normalize().map(|n| n.as_vec3()));
|
||||
}
|
||||
let material = face_materials(mesh)?;
|
||||
|
||||
// Manifold edge adjacency over welded vertices: edge → (face, face, count).
|
||||
let mut edges: HashMap<(u32, u32), (u32, u32, u8)> = HashMap::with_capacity(n * 2);
|
||||
@@ -151,7 +257,20 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res
|
||||
let id = charts.len() as u32;
|
||||
let sn = normal[seed].unwrap_or(Vec3::Z);
|
||||
let t = sn.any_orthonormal_vector();
|
||||
charts.push(Chart { material: material[seed], t, b: sn.cross(t), rot: Vec2::X, lo: Vec2::ZERO, hi: Vec2::ZERO, offset: Vec2::ZERO });
|
||||
let b = sn.cross(t);
|
||||
// Relative to the seed's first corner, so the rounding of a projection follows the
|
||||
// chart's size rather than its distance from the origin.
|
||||
let origin = pos(mesh.tri(seed).unwrap_or([0; 3])[0]).as_dvec3();
|
||||
charts.push(Chart {
|
||||
material: material[seed],
|
||||
origin,
|
||||
t: t.as_dvec3(),
|
||||
b: b.as_dvec3(),
|
||||
rot: DVec2::X,
|
||||
lo: DVec2::ZERO,
|
||||
hi: DVec2::ZERO,
|
||||
offset: DVec2::ZERO,
|
||||
});
|
||||
chart_of[seed] = id;
|
||||
queue.push_back(seed);
|
||||
while let Some(f) = queue.pop_front() {
|
||||
@@ -167,30 +286,30 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res
|
||||
}
|
||||
}
|
||||
|
||||
// Principal axes and bounds of every chart.
|
||||
let mut cov = vec![(Vec2::ZERO, [0.0f64; 3], 0usize); charts.len()];
|
||||
// Principal axes and bounds of every chart, in f64 from the positions as given.
|
||||
let mut cov = vec![(DVec2::ZERO, [0.0f64; 3], 0usize); charts.len()];
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let c = c as usize;
|
||||
for v in mesh.tri(t).unwrap_or([0; 3]) {
|
||||
if let (Some(ch), Some(acc)) = (charts.get(c), cov.get_mut(c)) {
|
||||
let q = ch.local(pos(v));
|
||||
acc.0 += q;
|
||||
acc.1[0] += (q.x * q.x) as f64;
|
||||
acc.1[1] += (q.y * q.y) as f64;
|
||||
acc.1[2] += (q.x * q.y) as f64;
|
||||
acc.1[0] += q.x * q.x;
|
||||
acc.1[1] += q.y * q.y;
|
||||
acc.1[2] += q.x * q.y;
|
||||
acc.2 += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (ch, (sum, m, k)) in charts.iter_mut().zip(&cov) {
|
||||
let k = (*k).max(1) as f64;
|
||||
let (mx, my) = (sum.x as f64 / k, sum.y as f64 / k);
|
||||
let (mx, my) = (sum.x / k, sum.y / k);
|
||||
let (cxx, cyy, cxy) = (m[0] / k - mx * mx, m[1] / k - my * my, m[2] / k - mx * my);
|
||||
let angle = 0.5 * (2.0 * cxy).atan2(cxx - cyy);
|
||||
// Rotate so the principal axis lies along x.
|
||||
ch.rot = Vec2::new((-angle).cos() as f32, (-angle).sin() as f32);
|
||||
ch.lo = Vec2::splat(f32::MAX);
|
||||
ch.hi = Vec2::splat(f32::MIN);
|
||||
ch.rot = DVec2::new((-angle).cos(), (-angle).sin());
|
||||
ch.lo = DVec2::splat(f64::MAX);
|
||||
ch.hi = DVec2::splat(f64::MIN);
|
||||
}
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let c = c as usize;
|
||||
@@ -205,20 +324,22 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res
|
||||
for ch in &mut charts {
|
||||
if ch.size().y > ch.size().x {
|
||||
// Quarter turn (x, y) → (y, −x) so shelves stay low.
|
||||
ch.rot = Vec2::new(ch.rot.y, -ch.rot.x);
|
||||
ch.rot = DVec2::new(ch.rot.y, -ch.rot.x);
|
||||
let (lo, hi) = (ch.lo, ch.hi);
|
||||
ch.lo = Vec2::new(lo.y, -hi.x);
|
||||
ch.hi = Vec2::new(hi.y, -lo.x);
|
||||
ch.lo = DVec2::new(lo.y, -hi.x);
|
||||
ch.hi = DVec2::new(hi.y, -lo.x);
|
||||
}
|
||||
}
|
||||
|
||||
// Pack each material's charts into its own 0..1 square.
|
||||
let pad = padding_texels.max(1.0);
|
||||
let mut scale = HashMap::new();
|
||||
let mats: std::collections::BTreeSet<usize> = charts.iter().map(|c| c.material).collect();
|
||||
for m in mats {
|
||||
let ids: Vec<usize> = (0..charts.len()).filter(|i| charts[*i].material == m).collect();
|
||||
let sizes: Vec<Vec2> = ids.iter().map(|i| charts[*i].size()).collect();
|
||||
let mut by_material: std::collections::BTreeMap<usize, Vec<usize>> = std::collections::BTreeMap::new();
|
||||
for (id, chart) in charts.iter().enumerate() {
|
||||
by_material.entry(chart.material).or_default().push(id);
|
||||
}
|
||||
for (m, ids) in by_material {
|
||||
let sizes: Vec<DVec2> = ids.iter().map(|i| charts[*i].size()).collect();
|
||||
let (s, res, offsets) = pack(&sizes, resolution.max(16) as f32, pad)?;
|
||||
for (i, o) in ids.iter().zip(offsets) {
|
||||
charts[*i].offset = o;
|
||||
@@ -227,52 +348,67 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res
|
||||
}
|
||||
|
||||
// Rebuild vertices: one per (vertex, chart).
|
||||
let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len() * 2);
|
||||
let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len().saturating_mul(2).min(mesh.indices.len()));
|
||||
let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
|
||||
let mut indices = Vec::with_capacity(mesh.indices.len());
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let Some(ch) = charts.get(c as usize) else { continue };
|
||||
let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0));
|
||||
let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0f32));
|
||||
for v in mesh.tri(t).unwrap_or([0; 3]) {
|
||||
let idx = *remap.entry((v as u32, c)).or_insert_with(|| {
|
||||
let q = ch.local(pos(v));
|
||||
// Chart y points up; UV v points down the image.
|
||||
let texel = ch.offset + Vec2::splat(pad) + Vec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s;
|
||||
let texel = ch.offset + DVec2::splat(f64::from(pad)) + DVec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s;
|
||||
positions.push(pos(v));
|
||||
normals.push(mesh.normals.get(v).copied().unwrap_or(Vec3::Y));
|
||||
normals.push(old_normals.get(v).copied().unwrap_or(Vec3::Y));
|
||||
if let Some(c) = mesh.colors.get(v) {
|
||||
colors.push(*c);
|
||||
}
|
||||
uvs.push((texel / res).clamp(Vec2::ZERO, Vec2::ONE));
|
||||
uvs.push((texel / f64::from(res)).as_vec2().clamp(Vec2::ZERO, Vec2::ONE));
|
||||
(positions.len() - 1) as u32
|
||||
});
|
||||
indices.push(idx);
|
||||
}
|
||||
if positions.len() > MAX_UNWRAP_VERTICES {
|
||||
return Err(GeomError::Invalid(format!("unwrapping would produce more than {MAX_UNWRAP_VERTICES} vertices")));
|
||||
}
|
||||
}
|
||||
mesh.positions = positions;
|
||||
mesh.normals = normals;
|
||||
mesh.uvs = uvs;
|
||||
mesh.colors = colors;
|
||||
mesh.indices = indices;
|
||||
let charts = charts.len();
|
||||
// The new arrays replace the mesh's only once the tangents and the final check have passed.
|
||||
let old = (
|
||||
std::mem::replace(&mut mesh.positions, positions),
|
||||
std::mem::replace(&mut mesh.normals, normals),
|
||||
std::mem::replace(&mut mesh.uvs, uvs),
|
||||
std::mem::replace(&mut mesh.colors, colors),
|
||||
std::mem::replace(&mut mesh.indices, indices),
|
||||
std::mem::take(&mut mesh.tangents),
|
||||
);
|
||||
mesh.compute_tangents();
|
||||
mesh.validate()?;
|
||||
Ok(charts.len())
|
||||
if let Err(e) = mesh.validate() {
|
||||
(mesh.positions, mesh.normals, mesh.uvs, mesh.colors, mesh.indices, mesh.tangents) = old;
|
||||
return Err(e);
|
||||
}
|
||||
Ok(charts)
|
||||
}
|
||||
|
||||
/// Shelf-pack rectangles of world `sizes` (each grown by `pad` texels per side) into a square of
|
||||
/// `res` texels with the largest uniform scale that fits. Returns (texels per world unit,
|
||||
/// resolution used, texel offset per rectangle). The resolution doubles when the padding alone
|
||||
/// cannot fit (very many charts), so the result always fits in 0..1.
|
||||
fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec<Vec2>)> {
|
||||
/// resolution used, texel offset per rectangle). A layout without room for a positive scale
|
||||
/// returns an error. The sizes and the scale are in
|
||||
/// `f64`, where the scale of any chart of finite `f32` positions is finite and above zero.
|
||||
fn pack(sizes: &[DVec2], res: f32, pad: f32) -> Result<(f64, f32, Vec<DVec2>)> {
|
||||
let mut order: Vec<usize> = (0..sizes.len()).collect();
|
||||
order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y));
|
||||
let place = |s: f32, res: f32| -> Option<Vec<Vec2>> {
|
||||
let mut out = vec![Vec2::ZERO; sizes.len()];
|
||||
let (mut x, mut y, mut shelf) = (0.0f32, 0.0f32, 0.0f32);
|
||||
let mut out = vec![DVec2::ZERO; sizes.len()];
|
||||
let pad = f64::from(pad);
|
||||
// Shelf-place every rectangle at scale `s` into `out`; false when they do not fit.
|
||||
let place = |s: f64, res: f32, out: &mut [DVec2]| -> bool {
|
||||
let res = f64::from(res);
|
||||
let (mut x, mut y, mut shelf) = (0.0f64, 0.0f64, 0.0f64);
|
||||
for &i in &order {
|
||||
let r = sizes[i] * s + Vec2::splat(2.0 * pad);
|
||||
let r = sizes[i] * s + DVec2::splat(2.0 * pad);
|
||||
if r.x > res {
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
if x + r.x > res {
|
||||
y += shelf;
|
||||
@@ -280,36 +416,44 @@ fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec<Vec2>)>
|
||||
shelf = 0.0;
|
||||
}
|
||||
if y + r.y > res {
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
if let Some(o) = out.get_mut(i) {
|
||||
*o = DVec2::new(x, y);
|
||||
}
|
||||
out[i] = Vec2::new(x, y);
|
||||
x += r.x;
|
||||
shelf = shelf.max(r.y);
|
||||
}
|
||||
Some(out)
|
||||
true
|
||||
};
|
||||
while place(0.0, res).is_none() {
|
||||
res *= 2.0;
|
||||
if res > MAX_PACK_RES {
|
||||
return Err(GeomError::Invalid("too many UV charts to pack".into()));
|
||||
let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f64, f64::max);
|
||||
if place(0.0, res, &mut out) {
|
||||
if largest <= 0.0 {
|
||||
return Ok((0.0, res, out));
|
||||
}
|
||||
let (mut lo, mut hi) = (0.0f64, (f64::from(res) - 2.0 * pad).max(0.0) / largest);
|
||||
// Halve the upper bound until a positive scale fits, so the refinement below starts
|
||||
// from a feasible lower bound however far below the first guess the answer lies.
|
||||
while hi > 0.0 {
|
||||
if place(hi, res, &mut out) {
|
||||
lo = hi;
|
||||
break;
|
||||
}
|
||||
hi *= 0.5;
|
||||
}
|
||||
hi = if lo > 0.0 { (2.0 * lo).min((f64::from(res) - 2.0 * pad).max(0.0) / largest) } else { hi };
|
||||
for _ in 0..40 {
|
||||
if hi - lo <= lo * 1e-4 {
|
||||
break;
|
||||
}
|
||||
let mid = 0.5 * (lo + hi);
|
||||
if place(mid, res, &mut out) { lo = mid } else { hi = mid }
|
||||
}
|
||||
if lo > 0.0 && place(lo, res, &mut out) {
|
||||
return Ok((lo, res, out));
|
||||
}
|
||||
}
|
||||
let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f32, f32::max);
|
||||
if largest <= 0.0 {
|
||||
return Ok((0.0, res, place(0.0, res).unwrap_or_default()));
|
||||
}
|
||||
let (mut lo, mut hi) = (0.0f32, (res - 2.0 * pad).max(0.0) / largest);
|
||||
if place(hi, res).is_some() {
|
||||
lo = hi;
|
||||
}
|
||||
for _ in 0..40 {
|
||||
if hi - lo <= lo * 1e-4 {
|
||||
break;
|
||||
}
|
||||
let mid = 0.5 * (lo + hi);
|
||||
if place(mid, res).is_some() { lo = mid } else { hi = mid }
|
||||
}
|
||||
Ok((lo, res, place(lo, res).unwrap_or_default()))
|
||||
Err(GeomError::Invalid("UV charts cannot fit with the requested padding and resolution".into()))
|
||||
}
|
||||
|
||||
impl Mesh {
|
||||
@@ -328,6 +472,81 @@ impl Mesh {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn tiny_quads_keep_their_shared_chart_edge() {
|
||||
let mut mesh = quad();
|
||||
for position in &mut mesh.positions {
|
||||
*position *= 2.0_f32.powi(-42);
|
||||
}
|
||||
assert_eq!(auto_unwrap(&mut mesh, 4.0, 16).unwrap(), 1);
|
||||
assert_eq!(weld_ids(&[Vec3::ONE; 4]), vec![0; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonempty_all_collinear_meshes_are_rejected_unchanged() {
|
||||
for positions in [vec![Vec3::ZERO, Vec3::X, Vec3::X * 2.0], {
|
||||
let d = Vec3::new(1.0, 17.0, 0.0);
|
||||
vec![Vec3::ZERO, d * (3.0 * 2.0_f32.powi(-49)), d]
|
||||
}] {
|
||||
let mut mesh = Mesh::from_parts(positions, Some(vec![Vec3::Z; 3]), Vec::new(), vec![0, 1, 2], "m").unwrap();
|
||||
let before = mesh.clone();
|
||||
assert!(auto_unwrap(&mut mesh, 4.0, 256).is_err());
|
||||
assert_eq!(mesh, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_normals_keep_tiny_and_large_face_directions() {
|
||||
for scale in [1e-25, 1e25] {
|
||||
let mesh = Mesh { positions: vec![Vec3::ZERO, Vec3::Y * scale, Vec3::Z * scale], indices: vec![0, 1, 2], ..Mesh::default() };
|
||||
assert_eq!(smooth_normals(&mesh), vec![Vec3::X; 3], "scale={scale}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_or_unaligned_submeshes_leave_the_layout_unchanged() {
|
||||
let original = primitives::cube(1.0).unwrap();
|
||||
for variant in 0..3 {
|
||||
let mut mesh = original.clone();
|
||||
match variant {
|
||||
0 => mesh.submeshes.clear(),
|
||||
1 => mesh.submeshes[0].count -= 3,
|
||||
_ => {
|
||||
mesh.submeshes[0].start = 1;
|
||||
mesh.submeshes[0].count = 3;
|
||||
}
|
||||
}
|
||||
let before = mesh.clone();
|
||||
assert!(auto_unwrap(&mut mesh, 4.0, 256).is_err(), "variant {variant}");
|
||||
assert_eq!(mesh, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packing_preserves_the_requested_resolution_and_border() {
|
||||
assert!(pack(&[DVec2::ONE; 2000], 128.0, 4.0).is_err());
|
||||
assert!(pack(&[DVec2::ONE], 16.0, 8.0).is_err());
|
||||
let (_, resolution, offsets) = pack(&[DVec2::ONE; 2], 128.0, 4.0).unwrap();
|
||||
assert_eq!(resolution, 128.0);
|
||||
assert_eq!((offsets[0].x + 4.0) / f64::from(resolution) * 128.0, 4.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packing_finds_a_small_scale_far_below_the_first_guess() {
|
||||
let pad = 1.0 + 262_657.0 / 8_388_608.0;
|
||||
let (scale, _, _) = pack(&vec![DVec2::ONE; 511 * 511], 1054.0, pad as f32).unwrap();
|
||||
assert!(scale > 0.0);
|
||||
assert!(pack(&vec![DVec2::ONE; 600 * 600], 1054.0, pad as f32).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weld_grid_keeps_distinct_extreme_positions() {
|
||||
let positions = [Vec3::splat(-f32::MAX), Vec3::ZERO, Vec3::splat(f32::MAX)];
|
||||
assert_eq!(weld_ids(&positions), vec![0, 1, 2]);
|
||||
}
|
||||
|
||||
use glam::Vec4;
|
||||
|
||||
use super::*;
|
||||
use crate::{UvGBuffer, primitives};
|
||||
|
||||
@@ -367,23 +586,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangles_in_two_materials_are_rejected_unchanged() {
|
||||
// Two congruent triangles in material 0; material 1 also lists the first.
|
||||
let p = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z * 5.0, Vec3::Z * 5.0 + Vec3::X, Vec3::Z * 5.0 + Vec3::Y];
|
||||
let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 3, 4, 5], "a").unwrap();
|
||||
m.materials.push("b".into());
|
||||
m.submeshes.push(crate::SubMesh { name: "b".into(), material: 1, start: 0, count: 3 });
|
||||
let before = m.clone();
|
||||
assert!(auto_unwrap(&mut m, 2.0, 64).is_err());
|
||||
assert_eq!(m, before);
|
||||
// The same material listed twice is not a conflict.
|
||||
m.submeshes[1].material = 0;
|
||||
assert_eq!(auto_unwrap(&mut m, 2.0, 64).unwrap(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_tiny_charts_still_fit() {
|
||||
// 2000 disconnected triangles: the packer grows its virtual resolution.
|
||||
fn many_tiny_charts_require_room_at_the_requested_resolution() {
|
||||
let mut p = Vec::new();
|
||||
let mut idx = Vec::new();
|
||||
for i in 0..2000u32 {
|
||||
@@ -392,7 +595,10 @@ mod tests {
|
||||
idx.extend([i * 3, i * 3 + 1, i * 3 + 2]);
|
||||
}
|
||||
let mut m = Mesh::from_parts(p, None, Vec::new(), idx, "m").unwrap();
|
||||
auto_unwrap(&mut m, 4.0, 128).unwrap();
|
||||
let before = m.clone();
|
||||
assert!(auto_unwrap(&mut m, 4.0, 128).is_err());
|
||||
assert_eq!(m, before);
|
||||
auto_unwrap(&mut m, 4.0, 512).unwrap();
|
||||
assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y)));
|
||||
}
|
||||
|
||||
@@ -409,4 +615,76 @@ mod tests {
|
||||
assert!(all_triangles_degenerate(&point));
|
||||
assert!(auto_unwrap(&mut point, 4.0, 256).is_err());
|
||||
}
|
||||
|
||||
fn quad() -> Mesh {
|
||||
let p = vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y];
|
||||
Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 0, 2, 3], "m").unwrap()
|
||||
}
|
||||
|
||||
fn submesh(material: usize, start: u32, count: u32) -> crate::SubMesh {
|
||||
crate::SubMesh { name: "s".into(), material, start, count }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_meshes_are_left_unchanged() {
|
||||
let mut two_materials = quad();
|
||||
two_materials.materials = vec!["a".into(), "b".into()];
|
||||
two_materials.submeshes = vec![submesh(0, 0, 6), submesh(1, 3, 3)];
|
||||
let mut nan_normal = quad();
|
||||
nan_normal.normals = vec![Vec3::INFINITY; 4];
|
||||
let mut short_colors = quad();
|
||||
short_colors.colors = vec![Vec4::ONE; 2];
|
||||
let mut range = quad();
|
||||
range.submeshes = vec![submesh(0, 6, 3)];
|
||||
let mut nan_position = quad();
|
||||
nan_position.positions[2] = Vec3::INFINITY;
|
||||
for (name, mut m) in [
|
||||
("two materials", two_materials),
|
||||
("infinite normal", nan_normal),
|
||||
("short colors", short_colors),
|
||||
("range", range),
|
||||
("infinite position", nan_position),
|
||||
] {
|
||||
m.uvs.clear();
|
||||
let before = m.clone();
|
||||
assert!(auto_unwrap(&mut m, 4.0, 256).is_err(), "{name}");
|
||||
assert_eq!(m, before, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_limits_are_checked_before_anything_else() {
|
||||
// Indices out of range as well: the limit is the error reported.
|
||||
let mut m = quad();
|
||||
m.indices = vec![0, 1, 9];
|
||||
m.submeshes = vec![submesh(0, 0, u32::MAX)];
|
||||
let before = m.clone();
|
||||
let message = auto_unwrap(&mut m, 4.0, 256).unwrap_err().to_string();
|
||||
assert!(message.contains("accepts at most"), "{message}");
|
||||
assert_eq!(m, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_charts_far_from_the_origin_keep_their_shape() {
|
||||
// A right triangle with 16-unit legs at 1e8, where an f32 position is 8 units apart.
|
||||
let o = Vec3::splat(1e8);
|
||||
let p = vec![o, o + Vec3::X * 16.0, o + Vec3::Y * 16.0];
|
||||
let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2], "m").unwrap();
|
||||
auto_unwrap(&mut m, 4.0, 256).unwrap();
|
||||
let (a, b, c) = (m.uvs[m.indices[0] as usize], m.uvs[m.indices[1] as usize], m.uvs[m.indices[2] as usize]);
|
||||
let (e1, e2) = (b - a, c - a);
|
||||
assert!(e1.length() > 0.1 && (e1.length() - e2.length()).abs() < 1e-3, "legs {e1} and {e2}");
|
||||
assert!(e1.dot(e2).abs() < 1e-3, "legs {e1} and {e2} are not at a right angle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_that_fills_the_square_does_not_replace_the_mesh() {
|
||||
let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, Vec::new(), vec![0, 1, 2], "m").unwrap();
|
||||
let before = m.clone();
|
||||
assert!(auto_unwrap(&mut m, 128.0, 256).is_err());
|
||||
assert_eq!(m, before);
|
||||
auto_unwrap(&mut m, 128.0, 512).unwrap();
|
||||
let (a, b, c) = (m.uvs[m.indices[0] as usize], m.uvs[m.indices[1] as usize], m.uvs[m.indices[2] as usize]);
|
||||
assert!((b - a).length() > 1e-4 && (c - a).length() > 1e-4, "uvs {a} {b} {c}");
|
||||
}
|
||||
}
|
||||
@@ -23,12 +23,16 @@ pub(super) const SOURCES: [(&str, &str); 12] = [
|
||||
("vectorcraft-modern-medium", include_str!("../themes/vectorcraft-modern-medium.json")),
|
||||
];
|
||||
|
||||
static BUILTINS: LazyLock<Vec<ThemeDef>> = LazyLock::new(load);
|
||||
|
||||
/// Parses every embedded file, without the search for reference cycles that
|
||||
/// `every_builtin_passes_the_full_check` runs on each of them.
|
||||
// An invalid embedded file is a build defect that the built-in tests catch.
|
||||
#[allow(clippy::panic)]
|
||||
static BUILTINS: LazyLock<Vec<ThemeDef>> = LazyLock::new(|| {
|
||||
fn load() -> Vec<ThemeDef> {
|
||||
SOURCES
|
||||
.iter()
|
||||
.map(|(name, text)| match format::parse(text.as_bytes()) {
|
||||
.map(|(name, text)| match format::parse_builtin(text.as_bytes()) {
|
||||
Ok(file) => file.theme,
|
||||
Err(errors) => {
|
||||
let list: Vec<String> = errors.0.iter().map(ToString::to_string).collect();
|
||||
@@ -36,7 +40,7 @@ static BUILTINS: LazyLock<Vec<ThemeDef>> = LazyLock::new(|| {
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
}
|
||||
|
||||
/// The built-in themes, in picker order. Panics if an embedded file is invalid, which the
|
||||
/// built-in tests rule out.
|
||||
@@ -50,3 +54,30 @@ pub fn builtins() -> &'static [ThemeDef] {
|
||||
pub(super) fn suite_default() -> &'static ThemeDef {
|
||||
builtins().iter().find(|t| t.id.as_str() == SUITE_DEFAULT).expect("SUITE_DEFAULT is a built-in")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every embedded file passes the full check of a theme file, the reference cycles included.
|
||||
#[test]
|
||||
fn every_builtin_passes_the_full_check() {
|
||||
for (name, text) in SOURCES {
|
||||
if let Err(errors) = format::parse(text.as_bytes()) {
|
||||
panic!("{name}.json: {errors:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Loading the built-ins parses each file once and does not search it for reference cycles.
|
||||
#[test]
|
||||
fn loading_the_builtins_does_not_search_for_reference_cycles() {
|
||||
format::CYCLE_SEARCHES.set(0);
|
||||
let themes = load();
|
||||
assert_eq!(themes.len(), SOURCES.len());
|
||||
assert_eq!(format::CYCLE_SEARCHES.get(), 0, "cycle searches while loading the built-ins");
|
||||
// A file read with the full check is searched.
|
||||
assert!(format::parse(SOURCES[0].1.as_bytes()).is_ok());
|
||||
assert_eq!(format::CYCLE_SEARCHES.get(), 1);
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,10 @@ mod sizes;
|
||||
mod validate;
|
||||
mod write;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use parse::CYCLE_SEARCHES;
|
||||
pub use parse::parse;
|
||||
pub(crate) use parse::parse_builtin;
|
||||
|
||||
/// Reads an app's size overrides: [`AppSizes::parse`](crate::AppSizes::parse).
|
||||
pub fn parse_app_sizes(bytes: &[u8]) -> Result<crate::AppSizes, FormatErrors> {
|
||||
|
||||
@@ -21,6 +21,22 @@ use crate::{AppId, IconPackId, ThemeId};
|
||||
/// kept for [`write`](super::write). Every field error is reported, not
|
||||
/// only the first.
|
||||
pub fn parse(bytes: &[u8]) -> Result<ThemeFile, FormatErrors> {
|
||||
parse_with(bytes, true)
|
||||
}
|
||||
|
||||
/// [`parse`] without the search for reference cycles, for the built-in themes. The built-in tests
|
||||
/// run [`parse`] on each of them.
|
||||
pub(crate) fn parse_builtin(bytes: &[u8]) -> Result<ThemeFile, FormatErrors> {
|
||||
parse_with(bytes, false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times this thread searched a parsed theme for reference cycles.
|
||||
pub(crate) static CYCLE_SEARCHES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
fn parse_with(bytes: &[u8], find_cycles: bool) -> Result<ThemeFile, FormatErrors> {
|
||||
let stop = |path: &[&str], kind| Err(FormatErrors(vec![FormatError { path: path.iter().map(|s| (*s).to_owned()).collect(), kind }]));
|
||||
if bytes.len() > MAX_THEME_BYTES {
|
||||
return stop(&[], ErrorKind::TooLarge { len: bytes.len() });
|
||||
@@ -46,7 +62,10 @@ pub fn parse(bytes: &[u8]) -> Result<ThemeFile, FormatErrors> {
|
||||
let mut p = Parser::new();
|
||||
let theme = p.theme(&raw);
|
||||
match theme {
|
||||
Some(theme) if p.errors.is_empty() && !find_cycles => Ok(ThemeFile { theme, raw }),
|
||||
Some(theme) if p.errors.is_empty() => {
|
||||
#[cfg(test)]
|
||||
CYCLE_SEARCHES.set(CYCLE_SEARCHES.get() + 1);
|
||||
let cycles = theme.reference_errors();
|
||||
if cycles.is_empty() { Ok(ThemeFile { theme, raw }) } else { Err(FormatErrors(cycles)) }
|
||||
}
|
||||
|
||||
@@ -1861,10 +1861,10 @@ impl BodyHooks<'_> {
|
||||
if took.x > 0.0 {
|
||||
took.x += offset + 2.0 * inset;
|
||||
}
|
||||
// A footer that drew nothing takes no band, gap or rule: a rule over nothing would part the body from empty room.
|
||||
if took.y > 0.0 {
|
||||
took.y += lead + inset;
|
||||
took.y += lead + inset + self.rules.footer;
|
||||
}
|
||||
took.y += self.rules.footer;
|
||||
if slot.is_none() {
|
||||
self.footer_size = Some(took);
|
||||
}
|
||||
|
||||
@@ -553,7 +553,7 @@ impl<'b> BodyHooks<'b> {
|
||||
} else {
|
||||
header
|
||||
};
|
||||
let footer_rule = (self.rules.footer > 0.0).then(|| {
|
||||
let footer_rule = (self.rules.footer > 0.0 && (sizes.footer.y > 0.0 || footer_in_body(props))).then(|| {
|
||||
// A footer across the container rules the whole width; one beside or in the end region rules its own.
|
||||
let x = if full { footer.x_range() } else { inner.x_range() };
|
||||
let w = self.rules.footer;
|
||||
|
||||
@@ -68,7 +68,7 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
rect,
|
||||
enabled: enabled && self.source.enabled(at),
|
||||
focusable: false,
|
||||
clickable: true,
|
||||
clickable: enabled && self.source.enabled(at),
|
||||
active: false,
|
||||
face: None,
|
||||
label: "",
|
||||
@@ -77,10 +77,10 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
access::report_sub(ctx, &decl);
|
||||
}
|
||||
|
||||
/// AccessKit requests on an item row's node or on a section row's collection node (`report_section_node`): Focus
|
||||
/// moves the lead to the row and key focus to the collection; Click also picks an item and activates it when the
|
||||
/// collection activates on click, or activates a section it does not select. Expand and Collapse open and
|
||||
/// close rows with children.
|
||||
/// AccessKit requests on an item row's node or on a section row's collection node (`report_section_node`), while the
|
||||
/// collection is enabled: Focus moves the lead to the row and key focus to the collection; Click also picks an item and
|
||||
/// activates it when the collection activates on click, or activates a section it does not select. Expand and
|
||||
/// Collapse open and close rows with children.
|
||||
pub(super) fn node_by_access(
|
||||
&mut self,
|
||||
comp: &C,
|
||||
@@ -90,6 +90,9 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
place: Placement,
|
||||
) {
|
||||
use craft_behavior::AccessAction;
|
||||
if !cx.core.resolved.enabled {
|
||||
return;
|
||||
}
|
||||
let (_, built) = self.built(layout, place.rect, place.offset);
|
||||
let rows: Vec<(u64, usize)> = built
|
||||
.into_iter()
|
||||
|
||||
@@ -1329,9 +1329,27 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
// Under a body sized from its content along the height, the rows take up to the room, as a content-sized
|
||||
// collection's do: the body has no room of its own to hand it.
|
||||
Sizing::Fill | Sizing::FillHeight => Vec2::new(wide, if self.from_content.1 || self.capped { height.min(room.y) } else { 0.0 }),
|
||||
Sizing::Content | Sizing::FillWidth => Vec2::new(wide, height.min(room.y)),
|
||||
Sizing::Content | Sizing::FillWidth => Vec2::new(wide, self.whole_rows(height, room.y)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `height` within `room`: where the rows run past the room, the height down to the last row that fits whole, so
|
||||
/// the collection ends on a whole row and scrolls the rest. A room too short for the first row is taken whole.
|
||||
fn whole_rows(&self, height: f32, room: f32) -> f32 {
|
||||
let len = self.source.len();
|
||||
let Some(layout) = self.layout.as_deref().filter(|_| height > room && len > 0) else { return height.min(room) };
|
||||
let rows = room - self.header.height;
|
||||
let mut fit = 0.0;
|
||||
// From the top of the content, an inset before the first row included.
|
||||
for at in 0..len {
|
||||
let bottom = layout.rect(at, ScrollPos::default()).max.y;
|
||||
if bottom > rows + 0.5 {
|
||||
break;
|
||||
}
|
||||
fit = bottom;
|
||||
}
|
||||
if fit > 0.0 { (fit + self.header.height).min(room) } else { room }
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a body around the collection, as its scope `env` names it, scrolls along the rows' overflow axis too: the
|
||||
|
||||
@@ -508,13 +508,22 @@ fn wrap_before(ui: &mut Ui, env: &Env, (label, side): (&Label, &SideLabel), cont
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a leaf placed under `env` sits directly in the body of `container`, the container of the innermost label
|
||||
/// scope, or in no body's flow at all: that scope's label then names the leaf. A leaf in a row, a grid or any other
|
||||
/// container inside the labeled one is one of the controls the label groups.
|
||||
fn named_directly(env: &Env, container: Id) -> bool {
|
||||
env.flow_body.is_none_or(|flow| flow == sub(container, "layout"))
|
||||
}
|
||||
|
||||
/// Shows `child` in the flow of `ui`. A component whose `LABELLED_AFTER` is set and that carries a label shows it
|
||||
/// through the label step, after the control, unless a label scope already names the control (a `Field`, `labelled`;
|
||||
/// a member of a group, a radio, is named by the group and keeps its own text):
|
||||
/// that scope's label is the visible text, so the control's own is not shown twice. Every other leaf shows as it is.
|
||||
/// that scope's label is the visible text, so the control's own is not shown twice. A control in a row or grid inside
|
||||
/// the scope is part of the field's arrangement, as the accessibility tree has it (`ScopeNode::arranged`): the label
|
||||
/// names the group, and the control shows its own label. Every other leaf shows as it is.
|
||||
pub(crate) fn show_leaf_in_flow<C: Show>(mut child: C, ui: &mut Ui) -> C::Output {
|
||||
let env = Env::of(ui);
|
||||
let named_by_scope = env.arena.is_none() && scope::in_label(ui.ctx());
|
||||
let named_by_scope = env.arena.is_none() && scope::label_container(ui.ctx()).is_some_and(|container| named_directly(&env, container));
|
||||
let shows = C::LABELLED_AFTER && child.shows_label() && child.common(crate::contract::Internal::new()).label != Label::Empty && !named_by_scope;
|
||||
if !shows {
|
||||
return crate::contract::run::show_leaf(&mut Some(child), ui, (crate::contract::run::ShowAt::Flow, env), None);
|
||||
|
||||
@@ -222,7 +222,21 @@ pub(crate) fn measuring_room(
|
||||
let bounds = screen_for(ctx, env, overlay);
|
||||
let resolved = resolve_anchor(ctx, id, overlay, own, own_to_screen);
|
||||
let anchor = resolved_anchor(ctx, overlay, resolved, bounds, inset, &mut MemoryStage::peek::<LayerMemory>(ctx, memory_slot(id)).pointer_at);
|
||||
Some(content_room(overlay, covers, bounds, kept_in(overlay, resolved, bounds, inset), anchor, rtl))
|
||||
let kept = off_edge(overlay, kept_in(overlay, resolved, bounds, inset), anchor, inset);
|
||||
Some(content_room(overlay, covers, bounds, kept, anchor, rtl))
|
||||
}
|
||||
|
||||
/// The rect an anchored layer of `overlay` is placed in from the rect `bounds` it is kept in: for a layer that keeps
|
||||
/// off the edges ([`Overlay::off_edge`]) `bounds` less `inset` on every side, widened to take in the part of its
|
||||
/// `anchor` inside `bounds`, so a list still lines up with a control nearer the edge than `inset`. `bounds` when the
|
||||
/// inset leaves no room, and for every other layer. The fit's cap stays a share of `bounds`.
|
||||
fn off_edge(overlay: &Overlay, bounds: Rect, anchor: Rect, inset: f32) -> Rect {
|
||||
let shrunk = bounds.shrink(inset);
|
||||
if !overlay.off_edge || !shrunk.is_positive() {
|
||||
return bounds;
|
||||
}
|
||||
let held = anchor.intersect(bounds);
|
||||
if held.is_negative() { shrunk } else { shrunk.union(held) }
|
||||
}
|
||||
|
||||
/// The most a layer's body may take: the fit's share of the safe rect `bounds`, at least as wide as the layer's
|
||||
@@ -280,7 +294,7 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Op
|
||||
let cap = cap(layer.overlay, bounds, anchor);
|
||||
match &layer.overlay.place {
|
||||
Place::Anchored { side, align, flips_across, offset, clear, .. } => {
|
||||
let kept = layer_bounds(layer, bounds);
|
||||
let kept = off_edge(layer.overlay, layer_bounds(layer, bounds), anchor, layer.env.tokens.space.pad.regular);
|
||||
let Some(size) = size else {
|
||||
let room = content_room(layer.overlay, covers, bounds, kept, anchor, rtl);
|
||||
return Placed { at: anchor.left_bottom().clamp(kept.min, kept.max), side: None, asked: None, room };
|
||||
|
||||
@@ -171,6 +171,9 @@ pub struct Overlay {
|
||||
/// them shown, pressed or raised is on top, and the app's own egui windows stack with it. Unset, a `Rank::Popup`
|
||||
/// stands above every window instead; a collapsed dock column's flyout sets it.
|
||||
pub among_windows: bool,
|
||||
/// Whether an anchored layer stays `space.pad.regular` inside the room it is kept in, except where its anchor
|
||||
/// reaches nearer the edge: a dropdown list hung from a control near the window's edge.
|
||||
pub off_edge: bool,
|
||||
/// Set only by [`Overlay::full_window`].
|
||||
full_window: bool,
|
||||
}
|
||||
@@ -214,6 +217,7 @@ impl Overlay {
|
||||
continue_move: None,
|
||||
role: LayerRole::default(),
|
||||
among_windows: false,
|
||||
off_edge: false,
|
||||
full_window: false,
|
||||
}
|
||||
}
|
||||
@@ -255,15 +259,16 @@ impl Overlay {
|
||||
overlay
|
||||
}
|
||||
|
||||
/// A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It
|
||||
/// closes when a row is activated or the focus leaves the anchor. The opener's list keys go to the collection
|
||||
/// [`Overlay::list`] names.
|
||||
/// A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor, and
|
||||
/// `space.pad.regular` off the window's edges ([`Overlay::off_edge`]). It closes when a row is activated or the
|
||||
/// focus leaves the anchor. The opener's list keys go to the collection [`Overlay::list`] names.
|
||||
pub fn dropdown() -> Overlay {
|
||||
let focus = FocusPolicy::POPUP.trap(false).restore(false).initial(Initial::KeepAnchor);
|
||||
let mut overlay = Overlay::base(Rank::Popup, Overlay::below(), OverlayFit::ContentCapped(DROPDOWN_SHARE), OwnerClass::PassivePopup, focus);
|
||||
overlay.dismiss = Dismiss::new().on_activate(true).focus_left(true);
|
||||
overlay.min_width = MinWidth::Anchor;
|
||||
overlay.popup = PopupKind::Listbox;
|
||||
overlay.off_edge = true;
|
||||
overlay
|
||||
}
|
||||
|
||||
|
||||
@@ -220,11 +220,19 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_>
|
||||
toggle,
|
||||
ltr_axis: resolved.ltr_axis,
|
||||
};
|
||||
let editor_record = || {
|
||||
let widget = core.editor.as_ref()?.widget;
|
||||
pass_state::with::<EditorRecords, _>(ctx, |records| records.0.remove(&widget))
|
||||
};
|
||||
let text_facts = core.text_access.take().or_else(editor_record);
|
||||
if let Some(owner) = inner_of {
|
||||
// Shown as the owner's control: the owner's node is the one node, and stands for this root's key focus.
|
||||
access::hide(ctx, id);
|
||||
scope::leave(ctx, id);
|
||||
access::fold::offer(ctx, owner, access::fold::Folded { inner: id, value: access.value.clone() });
|
||||
// Disabled with its own inner component as well, so the state reaches every owner of a nested `inner`.
|
||||
let disabled =
|
||||
!resolved.enabled || folded.as_ref().is_some_and(|folded| folded.disabled) || text_facts.as_ref().is_some_and(|facts| facts.disabled);
|
||||
access::fold::offer(ctx, owner, access::fold::Folded { inner: id, value: access.value.clone(), disabled });
|
||||
if flags.contains(Flags::FOCUSED) {
|
||||
access::set_focus(ctx, owner);
|
||||
}
|
||||
@@ -236,12 +244,12 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_>
|
||||
}
|
||||
if let Some(folded) = &folded {
|
||||
keys::register_node(ctx, id, folded.inner, None, focusable);
|
||||
// Disabled with the inner component it stands for, or with that component's text part.
|
||||
if !resolved.enabled || folded.disabled {
|
||||
keys::register_disabled(ctx, id);
|
||||
}
|
||||
}
|
||||
let editor_record = || {
|
||||
let widget = core.editor.as_ref()?.widget;
|
||||
pass_state::with::<EditorRecords, _>(ctx, |records| records.0.remove(&widget))
|
||||
};
|
||||
if let Some(facts) = core.text_access.take().or_else(editor_record) {
|
||||
if let Some(facts) = text_facts {
|
||||
crate::runtime::access::text::report_text(ctx, id, &facts, access.unit.as_deref(), access.value.as_deref());
|
||||
} else if let Some(editor) = &core.editor {
|
||||
crate::runtime::access::text::fold_editor(ctx, editor.widget, id);
|
||||
|
||||
@@ -77,8 +77,9 @@ pub enum RowAlign {
|
||||
/// At the end edge.
|
||||
End,
|
||||
/// Spread over the row: the first child at the start edge, the last at the end edge, and the room left shared
|
||||
/// equally between the children (a footer's leading slot and its buttons). One child sits at the start edge, and so
|
||||
/// do the children of a row that wraps.
|
||||
/// equally between the children (a footer's leading slot and its buttons). One child sits at the start edge. A row
|
||||
/// that wraps spreads its children the same way while they fit one line; once they take more lines, each line
|
||||
/// starts at the start edge.
|
||||
SpaceBetween,
|
||||
}
|
||||
|
||||
@@ -238,6 +239,9 @@ pub(crate) struct WrapRows(IdMap<WrapTook>);
|
||||
struct WrapTook {
|
||||
/// Each child placed so far: its line, counted from the row's first, and its height.
|
||||
children: Vec<(usize, f32)>,
|
||||
/// What the children took about a line, as an unwrapped row's children do (`RowLines`): the line a real run that
|
||||
/// spreads them on one line sets them on.
|
||||
line: LineTook,
|
||||
/// The top of the last child's slot.
|
||||
top: Option<f32>,
|
||||
/// In a real run, each child's line and that line's height in this pass's measuring run, while every child so far
|
||||
@@ -255,11 +259,14 @@ fn open_wraps(ctx: &egui::Context, sizing: bool, id: Id) {
|
||||
}
|
||||
|
||||
/// Ends the children of the wrapping `Row` body `id`, `room` wide; a measuring run records each child's line and the
|
||||
/// height of its tallest child.
|
||||
fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2) {
|
||||
/// height of its tallest child. A measuring run returns how many children the row placed and what they took about a
|
||||
/// line when every one of them sits on its first line and the row's `content`, how far below its top everything in it
|
||||
/// reaches (direct egui allocations included), is no taller than its tallest child: egui sets anything it wraps below
|
||||
/// the first line.
|
||||
fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2, content: f32) -> Option<(usize, LineTook)> {
|
||||
let took = pass_state::with::<WrapRows, _>(ctx, |rows| rows.0.remove(&id)).unwrap_or_default();
|
||||
if !sizing {
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
let mut heights: Vec<f32> = Vec::new();
|
||||
for &(line, height) in &took.children {
|
||||
@@ -272,6 +279,8 @@ fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2) {
|
||||
for (i, &(line, _)) in took.children.iter().enumerate() {
|
||||
found(ctx, true, sub(id, ("wrap", i)), room, Vec2::new(line as f32, heights.get(line).copied().unwrap_or_default()));
|
||||
}
|
||||
let first = heights.first().copied().unwrap_or_default();
|
||||
(heights.len() <= 1 && content <= first + ONE_LINE_SLACK).then_some((took.children.len(), took.line))
|
||||
}
|
||||
|
||||
/// Whether egui puts the next child `width` wide in `ui`, a wrapping row's block, on a new line (`Layout::next_frame`):
|
||||
@@ -283,10 +292,11 @@ fn wraps(ui: &Ui, width: f32) -> bool {
|
||||
}
|
||||
|
||||
/// Counts the next child of `size` placed in `ui`, the block of the wrapping `Row` body that places the children under
|
||||
/// `env`, on its line: the line egui sets it on, or a line another allocation started. Returns the height of that line
|
||||
/// `env`, on its line: the line egui sets it on, or a line another allocation started. `first` is how far below its
|
||||
/// top the child's first line's centre lies, as a child of an unwrapped row reports it. Returns the height of that line
|
||||
/// in this pass's measuring run while each child so far went on the line it went on there; `None` outside a wrapping
|
||||
/// row, in a measuring run, and once the lines differ.
|
||||
fn wrap_line(ui: &Ui, env: &Env, size: Vec2) -> Option<f32> {
|
||||
fn wrap_line(ui: &Ui, env: &Env, size: Vec2, first: Option<f32>) -> Option<f32> {
|
||||
let body = env.flow_body.filter(|_| ui.layout().main_wrap)?;
|
||||
let (starts, top) = (wraps(ui, size.x), ui.cursor().top());
|
||||
pass_state::with::<WrapRows, _>(ui.ctx(), |rows| {
|
||||
@@ -298,6 +308,7 @@ fn wrap_line(ui: &Ui, env: &Env, size: Vec2) -> Option<f32> {
|
||||
};
|
||||
let i = took.children.len();
|
||||
took.children.push((line, size.y));
|
||||
took.line.add(first, size.y);
|
||||
let planned = took.planned.as_ref().and_then(|planned| planned.get(i)).filter(|(at, _)| *at == line).map(|(_, height)| *height);
|
||||
if planned.is_none() {
|
||||
took.planned = None;
|
||||
@@ -1361,8 +1372,17 @@ impl Spread {
|
||||
/// records the natural width and count, and the leasts (none for a row that fits). The real run, including one a kept
|
||||
/// transcript serves, builds the same cursor from those records, so each child measures in the same room in both.
|
||||
/// Every sweep runs in a child of `ui` with its layout, so the children get the same ids in each.
|
||||
/// `env` is the row's env, installed for `ui`.
|
||||
fn run_spread<R>(ui: &mut Ui, env: &Env, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Option<f32>) {
|
||||
/// `env` is the row's env, installed for `ui`. `fits` is the natural width and count of the children of a wrapping row
|
||||
/// that fit its first line in this pass's measuring run (`one_line_spread`): the real run spreads them from it, with no
|
||||
/// leasts.
|
||||
fn run_spread<R>(
|
||||
ui: &mut Ui,
|
||||
env: &Env,
|
||||
(id, fits): (Id, Option<Vec2>),
|
||||
gap: f32,
|
||||
rtl: bool,
|
||||
body: &mut dyn FnMut(&mut Ui) -> R,
|
||||
) -> (R, Option<f32>) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let layout = child::row_layout(rtl, false);
|
||||
let sweep = |ui: &mut Ui, env: &Env, last: Option<Vec2>, leasts: Vec<f32>, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| {
|
||||
@@ -1378,6 +1398,10 @@ fn run_spread<R>(ui: &mut Ui, env: &Env, id: Id, gap: f32, rtl: bool, body: &mut
|
||||
};
|
||||
let natural = |spread: &Option<Spread>| spread.as_ref().map(|spread| spread.measured().x);
|
||||
let leasts_id = sub(id, "leasts");
|
||||
if let Some(fits) = fits.filter(|_| !measure::active(&ctx)) {
|
||||
let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, env, Some(fits), Vec::new(), false, body)).0;
|
||||
return (inner, natural(&spread));
|
||||
}
|
||||
if !measure::active(&ctx) {
|
||||
let count = this_pass(&ctx, false, leasts_id).map_or(0, |count| count.x as usize);
|
||||
let leasts = (0..count).map(|i| this_pass(&ctx, false, sub(id, ("least", i))).map_or(0.0, |least| least.x)).collect();
|
||||
@@ -1480,7 +1504,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, env: &Env, size: Vec2, child: InFlow) -
|
||||
let centre = bracket.and_then(|(_, centre)| centre).or_else(|| line.and_then(|line| line.centre));
|
||||
let above = centre.zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0));
|
||||
// A child of a wrapping row takes the height of its line; a one-line child sits at its middle.
|
||||
let wrapped = if line.is_none() { wrap_line(ui, env, size) } else { None };
|
||||
let wrapped = if line.is_none() { wrap_line(ui, env, size, child.first) } else { None };
|
||||
let height = line.and_then(|line| line.height).or(wrapped);
|
||||
let slot = Vec2::new(size.x, height.map_or(above + size.y, |height| height.max(above + size.y)));
|
||||
let (rect, in_cell) = take_in_flow(ui, env, slot);
|
||||
@@ -1998,9 +2022,12 @@ pub(crate) fn run_body_measured<R>(
|
||||
};
|
||||
// Each layout runs in its own function, so a body nested in bodies keeps only its own layout's frame on the stack.
|
||||
let line = RowIn { id, gap, shared, sizing, rtl };
|
||||
let fits =
|
||||
matches!(layout, BodyLayout::Row { wrap: true, align: RowAlign::SpaceBetween }).then(|| one_line_spread(ui, env, sizing, id)).flatten();
|
||||
match layout {
|
||||
BodyLayout::Stack => (run_stack(ui, env, &line, body), None),
|
||||
BodyLayout::Row { wrap: false, align: RowAlign::SpaceBetween } => run_spread_row(ui, env, &line, body),
|
||||
BodyLayout::Row { wrap: false, align: RowAlign::SpaceBetween } => run_spread_row(ui, env, &line, None, body),
|
||||
BodyLayout::Row { wrap: true, align: RowAlign::SpaceBetween } if fits.is_some() => run_spread_row(ui, env, &line, fits, body),
|
||||
BodyLayout::Row { wrap: false, align: RowAlign::Start } => (run_start_row(ui, env, &line, body), None),
|
||||
BodyLayout::Row { wrap, align } => run_row(ui, env, &line, (*wrap, *align), body),
|
||||
BodyLayout::Grid { columns, fit, cells } => (run_grid(ui, env, id, (&columns[..], *fit, *cells), gap, body), None),
|
||||
@@ -2039,11 +2066,34 @@ fn run_stack<R>(ui: &mut Ui, env: &Env, at: &RowIn, body: impl FnMut(&mut Ui) ->
|
||||
inner
|
||||
}
|
||||
|
||||
/// An unwrapped `Row` that spreads its children over its room.
|
||||
fn run_spread_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mut Ui) -> R) -> (R, Option<f32>) {
|
||||
/// The rect a wrapping `Start` or `SpaceBetween` row lays its lines in, when its container sets a line length for
|
||||
/// paragraphs (`Scoped::measure`, a dialog's) narrower than the room `ui` offers: the row wraps at that length, as the
|
||||
/// paragraphs beside it do, so a dialog sized from its content stays as wide as its text and a row of radios that
|
||||
/// would not fit there takes a second line instead of widening the dialog. A room unbounded at its end edge (a
|
||||
/// measuring run's) is cut from its start edge. `None` where the row takes the room `ui` offers.
|
||||
fn wrap_rect(ui: &Ui, env: &Env, rtl: bool) -> Option<Rect> {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
env.measure.filter(|measure| *measure < room.width() && (!rtl || room.right().is_finite())).map(|measure| Flow::new(room, rtl).span(0.0, measure))
|
||||
}
|
||||
|
||||
/// The natural width and count of the children of the wrapping `SpaceBetween` row `id` in a real run, when this pass's
|
||||
/// measuring run set two or more of them on its first line and they fit the rect the row wraps in (`wrap_rect`): the
|
||||
/// row then spreads them over that rect as an unwrapped row does over its room. `None` in a measuring run, and for a
|
||||
/// row that wraps.
|
||||
fn one_line_spread(ui: &Ui, env: &Env, sizing: bool, id: Id) -> Option<Vec2> {
|
||||
let fits = this_pass(ui.ctx(), sizing, sub(id, "one_line"))?;
|
||||
let room = wrap_rect(ui, env, env.direction.is_rtl()).unwrap_or_else(|| ui.available_rect_before_wrap()).width();
|
||||
// Half a point: less than a pixel shows at any scale the box runs.
|
||||
(fits.y >= 2.0 && room.is_finite() && fits.x <= room + 0.5).then_some(fits)
|
||||
}
|
||||
|
||||
/// An unwrapped `Row` that spreads its children over its room, or a wrapping one whose children `fits` one line
|
||||
/// (`one_line_spread`), spread over the rect it wraps in (`wrap_rect`).
|
||||
fn run_spread_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, fits: Option<Vec2>, mut body: impl FnMut(&mut Ui) -> R) -> (R, Option<f32>) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let RowIn { id, gap, shared, sizing, rtl } = *at;
|
||||
let (inner, _) = child::block(ui, None, child::row_layout(rtl, false), |ui| {
|
||||
let rect = fits.and_then(|_| wrap_rect(ui, env, rtl));
|
||||
let (inner, _) = child::block(ui, rect, child::row_layout(rtl, false), |ui| {
|
||||
let line = on_line(id, row_line(&ctx, sizing, id, shared), shared);
|
||||
let row = env.derive_local(|scoped| {
|
||||
scoped.grid = Some(id);
|
||||
@@ -2053,7 +2103,7 @@ fn run_spread_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&m
|
||||
scoped.flow_body = Some(id);
|
||||
});
|
||||
let installed = Env::install_for(ui, row.clone());
|
||||
let inner = run_spread(ui, &row, id, gap.x, rtl, &mut body);
|
||||
let inner = run_spread(ui, &row, (id, fits), gap.x, rtl, &mut body);
|
||||
Env::restore(&ctx, installed);
|
||||
record_line(ui, sizing, id, shared, env.first_line);
|
||||
inner
|
||||
@@ -2089,14 +2139,7 @@ fn run_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign
|
||||
let RowIn { id, shared, sizing, rtl, .. } = *at;
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let rect = match align {
|
||||
// A wrapping row wraps at the line length its container sets for paragraphs (a dialog's), as the paragraphs
|
||||
// beside it do: a dialog sized from its content stays as wide as its text, and a row of radios that would not
|
||||
// fit there takes a second line instead of widening the dialog. A room unbounded at its end edge (a measuring
|
||||
// run's) is cut from its start edge.
|
||||
RowAlign::Start | RowAlign::SpaceBetween if wrap => env
|
||||
.measure
|
||||
.filter(|measure| *measure < room.width() && (!rtl || room.right().is_finite()))
|
||||
.map(|measure| Flow::new(room, rtl).span(0.0, measure)),
|
||||
RowAlign::Start | RowAlign::SpaceBetween if wrap => wrap_rect(ui, env, rtl),
|
||||
RowAlign::Start | RowAlign::SpaceBetween => None,
|
||||
RowAlign::Center | RowAlign::End => {
|
||||
let last = this_pass(&ctx, sizing, id);
|
||||
@@ -2117,6 +2160,11 @@ fn run_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign
|
||||
// Where its least is asked, a wrapping row is as narrow as its widest child at its least: every child on a
|
||||
// line of its own.
|
||||
let block_layout = if wrap && env.least { child::column_layout(rtl) } else { child::row_layout(rtl, wrap) };
|
||||
let mut one_line = None;
|
||||
// The children of a wrapping `SpaceBetween` row report their first line to the row, which reports the line they
|
||||
// sit on when the real run spreads them on one line, and the first child's otherwise.
|
||||
let spreads = lines && align == RowAlign::SpaceBetween;
|
||||
let first_target = env.first_line.filter(|_| spreads && sizing).map(|target| (target, sub(id, "first_line")));
|
||||
let (inner, took) = child::block(ui, rect, block_layout, |ui| {
|
||||
let row = env.derive_local(|scoped| {
|
||||
scoped.row_room = Some(room.width());
|
||||
@@ -2125,6 +2173,9 @@ fn run_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign
|
||||
if line.is_some() {
|
||||
scoped.first_line = None;
|
||||
}
|
||||
if let Some((_, own)) = first_target {
|
||||
scoped.first_line = Some(own);
|
||||
}
|
||||
// A leaf wider than a whole line takes the line, never below its least, as in a stack.
|
||||
if wrap {
|
||||
scoped.shrink = Some(Shrink::Fit);
|
||||
@@ -2134,9 +2185,49 @@ fn run_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign
|
||||
if lines {
|
||||
open_wraps(&ctx, sizing, id);
|
||||
}
|
||||
let inner = if wrap { body(ui) } else { run_shrinking(ui, &row, id, &mut body) };
|
||||
if let Some((_, own)) = first_target {
|
||||
open_first_lines(&ctx, &[own]);
|
||||
}
|
||||
// How far below the row's top its content reaches, direct egui allocations included, which the children's
|
||||
// lines (`close_wraps`) do not count.
|
||||
let mut content = 0.0;
|
||||
let inner = if wrap && align == RowAlign::SpaceBetween {
|
||||
// In a child, as the spread row runs its children (`run_spread`): they take the same ids whether the real
|
||||
// run spreads them on one line or wraps them, and keep their state when the row starts or stops wrapping.
|
||||
let layout = *ui.layout();
|
||||
child::block(ui, None, layout, |ui| {
|
||||
let top = ui.max_rect().top();
|
||||
let inner = Env::run_in(ui, row.clone(), &mut body);
|
||||
content = (ui.min_rect().bottom() - top).max(0.0);
|
||||
inner
|
||||
})
|
||||
.0
|
||||
} else if wrap {
|
||||
body(ui)
|
||||
} else {
|
||||
run_shrinking(ui, &row, id, &mut body)
|
||||
};
|
||||
if lines {
|
||||
close_wraps(&ctx, sizing, id, room.size());
|
||||
one_line = close_wraps(&ctx, sizing, id, room.size(), content);
|
||||
// Children that the real run may spread on one line sit on the line they take there, as an unwrapped
|
||||
// row's do: the block takes that line's height, which may be more than its tallest child's (a check box
|
||||
// with a detail line under its label sits its first line on the line).
|
||||
let spread = one_line.filter(|(count, _)| align == RowAlign::SpaceBetween && *count >= 2);
|
||||
let top = ui.max_rect().top();
|
||||
let line = spread.and_then(|(_, took)| spread_line(id, took, shared));
|
||||
if let Some(line) = line {
|
||||
alloc::reach_down_to(ui, top + line.y);
|
||||
}
|
||||
// The row's first line is the line the real run spreads its children on, as `record_line` reports an
|
||||
// unwrapped row's, else the first child's.
|
||||
if let Some((target, own)) = first_target {
|
||||
let child = close_first_line(&ctx, own);
|
||||
if let Some(line) = line {
|
||||
report_first_line(&ctx, target, Some(top + line.x));
|
||||
} else if let Some(at) = child {
|
||||
report_first_line(&ctx, target, at);
|
||||
}
|
||||
}
|
||||
}
|
||||
Env::restore(&ctx, installed);
|
||||
if !wrap {
|
||||
@@ -2147,5 +2238,24 @@ fn run_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign
|
||||
if align != RowAlign::Start {
|
||||
found(&ctx, sizing, id, room.size(), took.size());
|
||||
}
|
||||
if wrap && align == RowAlign::SpaceBetween {
|
||||
// Children that all fit the first line are spread over the row by the real run (`one_line_spread`): their
|
||||
// width at the gap alone and their count, and the line they sit on (`spread_line`), as `record_line` records
|
||||
// an unwrapped row's. A row that wraps records no count and no line, so it wraps again.
|
||||
let count = one_line.map_or(0, |(count, _)| count);
|
||||
found(&ctx, sizing, sub(id, "one_line"), room.size(), Vec2::new(took.width(), count as f32));
|
||||
let line = one_line.and_then(|(_, took)| spread_line(id, took, shared)).unwrap_or(Vec2::ZERO);
|
||||
found(&ctx, sizing, sub(id, "line"), Vec2::new(0.0, shared.unwrap_or(0.0)), line);
|
||||
}
|
||||
(inner, (align != RowAlign::Start).then(|| took.width()))
|
||||
}
|
||||
|
||||
/// The line the children of the wrapping `SpaceBetween` row `id` sit on when they `took` one line, with the line
|
||||
/// `shared` it shares with its container's inline header or end region: how far below the row's top the line's centre
|
||||
/// lies, and the row's height once every child sits on it, as `record_line` finds an unwrapped row's. `None` when the
|
||||
/// line has no height.
|
||||
fn spread_line(id: Id, took: LineTook, shared: Option<f32>) -> Option<Vec2> {
|
||||
let own = (took.height() > 0.0).then(|| (took.centre.unwrap_or(0.0), took.height()));
|
||||
let line = on_line(id, own, shared);
|
||||
line.centre.zip(line.height).filter(|(_, height)| *height > 0.0).map(|(centre, height)| Vec2::new(centre, height))
|
||||
}
|
||||
@@ -126,7 +126,7 @@ fn named(name: &Name, label: &str, fallbacks: &[Option<&str>]) -> Named {
|
||||
|
||||
/// The expanded state of a node: an explicit value, else open when `OPEN` or `EXPANDED` is shown this pass. A
|
||||
/// component that can be open and is closed says so with `Access::expanded`; a node with no state is not
|
||||
/// expandable, so `Expand` and `Collapse` are declared only where the state exists.
|
||||
/// expandable, so `Expand` and `Collapse` are declared only where the state exists and the node is enabled.
|
||||
fn expanded_of(flags: Flags, explicit: Option<bool>) -> Option<bool> {
|
||||
explicit.or_else(|| flags.intersects(Flags::OPEN | Flags::EXPANDED).then_some(true))
|
||||
}
|
||||
@@ -160,7 +160,8 @@ fn write_position(spec: &mut NodeSpec, position: Option<SetPosition>, level: Opt
|
||||
}
|
||||
}
|
||||
|
||||
/// The actions the interaction and the numeric facts declare.
|
||||
/// The actions the interaction and the numeric facts declare. Called after `write_states`: a disabled node offers no
|
||||
/// context menu and no value action.
|
||||
fn declare_actions(
|
||||
spec: &mut NodeSpec,
|
||||
focusable: bool,
|
||||
@@ -169,15 +170,15 @@ fn declare_actions(
|
||||
numeric: Option<&Numeric>,
|
||||
variable_steps: Option<(bool, bool)>,
|
||||
) {
|
||||
// A read-only value offers no action that would change it.
|
||||
let numeric = numeric.filter(|_| !spec.read_only);
|
||||
// A read-only or disabled value offers no action that would change it.
|
||||
let numeric = numeric.filter(|_| !spec.read_only && !spec.disabled);
|
||||
if focusable {
|
||||
spec.actions.push(NodeAction::Focus);
|
||||
}
|
||||
if clickable {
|
||||
spec.actions.push(NodeAction::Click);
|
||||
}
|
||||
if context_menu {
|
||||
if context_menu && !spec.disabled {
|
||||
spec.actions.push(NodeAction::ContextMenu);
|
||||
}
|
||||
if let Some(numeric) = numeric {
|
||||
@@ -213,7 +214,11 @@ fn declare_scroll_actions(spec: &mut NodeSpec, (vertical, horizontal): (bool, bo
|
||||
}
|
||||
}
|
||||
|
||||
/// The custom actions of a node, none while it is disabled. Called after `write_states`.
|
||||
fn custom_actions(spec: &mut NodeSpec, actions: &[(i32, Label)]) {
|
||||
if spec.disabled {
|
||||
return;
|
||||
}
|
||||
spec.custom_actions = actions.iter().map(|(id, label)| (*id, label.as_str().to_owned())).collect();
|
||||
}
|
||||
|
||||
@@ -317,7 +322,7 @@ pub(crate) fn report(ctx: &Context, own: &Own<'_>) {
|
||||
write_states(&mut spec, own.flags, own.selected, own.enabled, own.read_only);
|
||||
spec.ltr_axis = own.ltr_axis;
|
||||
spec.busy |= access.busy;
|
||||
if let Some(expanded) = expanded {
|
||||
if let Some(expanded) = expanded.filter(|_| own.enabled) {
|
||||
spec.actions.push(if expanded { NodeAction::Collapse } else { NodeAction::Expand });
|
||||
}
|
||||
declare_actions(&mut spec, own.focusable, own.clickable, own.context_menu, numeric, access.variable_steps);
|
||||
@@ -346,6 +351,9 @@ pub(crate) fn report(ctx: &Context, own: &Own<'_>) {
|
||||
);
|
||||
keys::register_node(ctx, own.id, own.id, None, own.focusable);
|
||||
keys::register_expanded(ctx, own.id, expanded, own.toggle);
|
||||
if !own.enabled {
|
||||
keys::register_disabled(ctx, own.id);
|
||||
}
|
||||
scope::register(
|
||||
ctx,
|
||||
scope::ScopeNode {
|
||||
@@ -383,6 +391,9 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) {
|
||||
},
|
||||
);
|
||||
keys::register_node(ctx, id, decl.owner, Some(node.part), false);
|
||||
if !decl.enabled {
|
||||
keys::register_disabled(ctx, id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let face_name = decl.face.as_ref().map(|face| face.name);
|
||||
@@ -408,7 +419,7 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) {
|
||||
spec.url = node.url.clone();
|
||||
spec.has_popup = node.has_popup;
|
||||
spec.current = node.current || flags.contains(Flags::CURRENT);
|
||||
if let Some(expanded) = expanded {
|
||||
if let Some(expanded) = expanded.filter(|_| decl.enabled) {
|
||||
spec.actions.push(if expanded { NodeAction::Collapse } else { NodeAction::Expand });
|
||||
}
|
||||
write_position(&mut spec, node.position, node.level);
|
||||
@@ -417,7 +428,7 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) {
|
||||
spec.sortable = node.sortable;
|
||||
write_states(&mut spec, flags, None, decl.enabled, false);
|
||||
declare_actions(&mut spec, decl.focusable, decl.clickable, false, numeric, None);
|
||||
if node.steps && numeric.is_none() {
|
||||
if node.steps && numeric.is_none() && decl.enabled {
|
||||
spec.actions.extend([NodeAction::Increment, NodeAction::Decrement]);
|
||||
}
|
||||
custom_actions(&mut spec, &node.custom_actions);
|
||||
@@ -440,6 +451,9 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) {
|
||||
);
|
||||
keys::register_node(ctx, id, decl.owner, Some(node.part), decl.focusable);
|
||||
keys::register_expanded(ctx, id, expanded, None);
|
||||
if !decl.enabled {
|
||||
keys::register_disabled(ctx, id);
|
||||
}
|
||||
if decl.active {
|
||||
adapter::set_focus(ctx, id);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ pub(crate) struct Folded {
|
||||
pub inner: Id,
|
||||
/// The inner component's value text.
|
||||
pub value: Option<String>,
|
||||
/// The inner component, or the text part it shows, is disabled: a request that acts on the owner's node reaches
|
||||
/// no one.
|
||||
pub disabled: bool,
|
||||
}
|
||||
|
||||
fn owner_slot(inner: Id) -> Id {
|
||||
|
||||
@@ -373,6 +373,11 @@ pub(crate) fn in_label(ctx: &Context) -> bool {
|
||||
pass_state::with::<Stack, _>(ctx, |stack| stack.0.iter().any(|scope| matches!(scope.kind, Kind::Label(_))))
|
||||
}
|
||||
|
||||
/// The container of the innermost open label scope.
|
||||
pub(crate) fn label_container(ctx: &Context) -> Option<Id> {
|
||||
pass_state::with::<Stack, _>(ctx, |stack| stack.0.iter().rev().find(|scope| matches!(scope.kind, Kind::Label(_))).map(|scope| scope.container))
|
||||
}
|
||||
|
||||
/// Records the narrowest width of a control inside the innermost label scope. The first control to report wins.
|
||||
pub(crate) fn record_control_min(ctx: &Context, width: f32) {
|
||||
let container = pass_state::with::<Stack, _>(ctx, |stack| {
|
||||
|
||||
@@ -114,6 +114,9 @@ pub(crate) fn report_text(ctx: &Context, owner: Id, facts: &TextFacts, unit: Opt
|
||||
);
|
||||
let index = u64::try_from(entries.len()).ok();
|
||||
keys::register_node(ctx, id, owner, Some(PartRef { key: RUN, index }), false);
|
||||
if facts.disabled {
|
||||
keys::register_disabled(ctx, id);
|
||||
}
|
||||
entries.push(Entry { node: adapter::node_key(id), line: line_at, bytes: run.bytes.clone(), text: text.to_owned() });
|
||||
}
|
||||
}
|
||||
@@ -134,6 +137,10 @@ pub(crate) fn report_text(ctx: &Context, owner: Id, facts: &TextFacts, unit: Opt
|
||||
}
|
||||
});
|
||||
adapter::write_text(ctx, owner, &TextNode { value: value.as_deref(), editable: facts.editable, disabled: facts.disabled, selection });
|
||||
// The owner's node, registered with its common facts, is disabled with the text part it stands for.
|
||||
if facts.disabled {
|
||||
keys::register_disabled(ctx, owner);
|
||||
}
|
||||
Service::<Tables>::run(ctx, |tables| tables.0.insert(owner, entries));
|
||||
}
|
||||
|
||||
|
||||
@@ -1548,6 +1548,8 @@ pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &Comma
|
||||
/// `command` as `reader` is shown it, noted as its read: the kept resolution while its inputs are unchanged, else a new
|
||||
/// one, kept.
|
||||
fn read(ctx: &Context, reader: Reader, command: &CommandRef) -> Arc<ResolvedCommand> {
|
||||
#[cfg(feature = "testing")]
|
||||
measure::count_command_read(ctx);
|
||||
// The resolved command carries the chord the keymap shows, kept or made now.
|
||||
crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap);
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
|
||||
@@ -275,6 +275,24 @@ impl Action {
|
||||
matches!(self.0.action, A::ScrollIntoView | A::ScrollUp | A::ScrollDown | A::ScrollLeft | A::ScrollRight | A::SetScrollOffset)
|
||||
}
|
||||
|
||||
/// Whether the request acts on its node: activates, opens or closes it, shows its context menu, steps or sets its
|
||||
/// value, edits its text or runs one of its custom actions. A disabled node takes none of these.
|
||||
pub(crate) fn acts(&self) -> bool {
|
||||
use accesskit::Action as A;
|
||||
matches!(
|
||||
self.0.action,
|
||||
A::Click
|
||||
| A::Expand
|
||||
| A::Collapse
|
||||
| A::ShowContextMenu
|
||||
| A::Increment
|
||||
| A::Decrement
|
||||
| A::SetValue
|
||||
| A::ReplaceSelectedText
|
||||
| A::CustomAction
|
||||
)
|
||||
}
|
||||
|
||||
/// The request as an `Intent::Access` payload for the sub-node `part`.
|
||||
pub(crate) fn request(&self, part: Option<craft_behavior::PartRef>) -> craft_behavior::AccessRequest {
|
||||
craft_behavior::AccessRequest::new(self.0.action, part, self.0.data.clone())
|
||||
|
||||
@@ -51,7 +51,7 @@ pub(crate) use intents::{
|
||||
take_cancel, take_every_escape, take_window_cancel,
|
||||
};
|
||||
pub use intents::{with_canvas_window_intents, with_window_intents};
|
||||
pub(crate) use nodes::{redirect_node, register_expanded, register_node};
|
||||
pub(crate) use nodes::{redirect_node, register_disabled, register_expanded, register_node};
|
||||
pub(crate) use route::{
|
||||
activated_member, begin, focus_in_modal_dialog, layout_of, note_fired, owner_at, pasted, pasted_text, queue_edit, routed_to, take_shortcuts,
|
||||
};
|
||||
@@ -293,6 +293,8 @@ struct Node {
|
||||
owner: Id,
|
||||
part: Option<PartRef>,
|
||||
focusable: bool,
|
||||
/// The node is enabled this pass: a request that acts on a disabled node reaches no one.
|
||||
enabled: bool,
|
||||
/// The node's expanded state this pass, `None` when it has none.
|
||||
expanded: Option<bool>,
|
||||
/// The part of the owner that opens the popup whose state the node reports, when that part has no node of its own:
|
||||
|
||||
@@ -37,6 +37,17 @@ pub(crate) fn register_expanded(ctx: &Context, node: Id, expanded: Option<bool>,
|
||||
});
|
||||
}
|
||||
|
||||
/// Marks the node registered by `register_node` as disabled: a request that would act on it (`Action::acts`) reaches
|
||||
/// no one, while Focus, the scroll requests and a text selection still go to its owner.
|
||||
pub(crate) fn register_disabled(ctx: &Context, node: Id) {
|
||||
crate::runtime::replay::journal(ctx, || node, |ctx, &node| register_disabled(ctx, node));
|
||||
current(ctx, |stage| {
|
||||
if let Some(entry) = stage.nodes.get_mut(&node_key(node)) {
|
||||
entry.enabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Registers an AccessKit node so a request that targets it reaches `owner`.
|
||||
pub(crate) fn register_node(ctx: &Context, node: Id, owner: Id, part: Option<PartRef>, focusable: bool) {
|
||||
crate::runtime::replay::journal(
|
||||
@@ -46,6 +57,6 @@ pub(crate) fn register_node(ctx: &Context, node: Id, owner: Id, part: Option<Par
|
||||
);
|
||||
crate::runtime::replay::note_node_owner(ctx, owner);
|
||||
current(ctx, |stage| {
|
||||
stage.nodes.insert(node_key(node), Node { owner, part, focusable, expanded: None, toggle: None });
|
||||
stage.nodes.insert(node_key(node), Node { owner, part, focusable, enabled: true, expanded: None, toggle: None });
|
||||
});
|
||||
}
|
||||
@@ -1056,7 +1056,8 @@ fn nudge_of(press: &Press) -> Option<Nudge> {
|
||||
Some(Nudge { direction, mods: press.mods, held: press.held.clone() })
|
||||
}
|
||||
|
||||
/// Routes an AccessKit action request to the owner of its target node, whatever the focus (9.2 rule 2).
|
||||
/// Routes an AccessKit action request to the owner of its target node, whatever the focus (9.2 rule 2). A request
|
||||
/// that acts on a disabled node is dropped before it moves focus.
|
||||
fn route_access(
|
||||
ctx: &Context,
|
||||
request: &Action,
|
||||
@@ -1067,6 +1068,9 @@ fn route_access(
|
||||
press_captured: bool,
|
||||
) {
|
||||
let Some(node) = nodes.get(&request.node()).copied() else { return };
|
||||
if !node.enabled && request.acts() {
|
||||
return;
|
||||
}
|
||||
let owner = Some(node.owner);
|
||||
// A request that only scrolls (a screen reader's Scroll Into View) shows the node and leaves focus where it is.
|
||||
if node.focusable && !request.scrolls() {
|
||||
|
||||
@@ -420,6 +420,18 @@ pub fn last_pass_resolves(ctx: &Context, what: Resolve) -> u32 {
|
||||
last_totals(ctx, |log| log.resolves[what as usize], 0)
|
||||
}
|
||||
|
||||
/// Counts a reader's read of a command's state in this pass, kept or resolved.
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) fn count_command_read(ctx: &Context) {
|
||||
totals(ctx, |log| log.command_reads += 1);
|
||||
}
|
||||
|
||||
/// The reads of command states the readers of the last pass made, kept or resolved.
|
||||
#[cfg(feature = "testing")]
|
||||
pub fn last_pass_command_reads(ctx: &Context) -> u32 {
|
||||
last_totals(ctx, |log| log.command_reads, 0)
|
||||
}
|
||||
|
||||
/// Counts a kept resolution a wake walked to compare its key.
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) fn count_wake_walk(ctx: &Context) {
|
||||
@@ -535,6 +547,7 @@ pub(crate) struct Totals {
|
||||
access_builds: u32,
|
||||
tip_texts: u32,
|
||||
resolves: [u32; 3],
|
||||
command_reads: u32,
|
||||
wake_walks: u32,
|
||||
asks: Vec<(&'static str, u32)>,
|
||||
}
|
||||
|
||||
@@ -608,21 +608,18 @@ impl Fixture {
|
||||
|
||||
/// The node named `label`: the interactive node whose name resolves to it (its own, or the node that labels it
|
||||
/// through `labelled_by`) and that labels no other node, so a field's control comes before its caption link;
|
||||
/// else the first node that carries the text.
|
||||
/// else such a node that is disabled; else the first node that carries the text.
|
||||
pub fn by_label(&self, label: &str) -> Option<Target> {
|
||||
let tree = &self.tree;
|
||||
let reported: HashSet<NodeKey> = tree.keys().into_iter().collect();
|
||||
let labels: HashSet<NodeKey> = reported.iter().flat_map(|key| tree.labelled_by_key(*key)).collect();
|
||||
let ordered = self.in_tree_order(&reported);
|
||||
let named = |key: NodeKey| super::access::name(tree, key) == Some(label) && tree.role_of(key) != Some(Role::LABEL) && !labels.contains(&key);
|
||||
let node = ordered
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|key| {
|
||||
super::access::name(tree, *key) == Some(label)
|
||||
&& tree.role_of(*key) != Some(Role::LABEL)
|
||||
&& !labels.contains(key)
|
||||
&& super::access::is_interactive(tree, *key)
|
||||
})
|
||||
.find(|key| named(*key) && super::access::is_interactive(tree, *key))
|
||||
.or_else(|| ordered.iter().copied().find(|key| named(*key) && tree.is_disabled_key(*key)))
|
||||
.or_else(|| ordered.iter().copied().find(|key| tree.name_of(*key) == Some(label)))?;
|
||||
self.target(node)
|
||||
}
|
||||
|
||||
@@ -59,9 +59,9 @@ pub use crate::runtime::layout_memory::forget_kept as forget_measurements;
|
||||
pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves;
|
||||
pub use crate::runtime::measure::{
|
||||
MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_derived_builds,
|
||||
last_frame_memo_runs, last_pass_access_builds, last_pass_body_runs as last_pass_measuring_runs, last_pass_derived_builds, last_pass_measure_asks,
|
||||
last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, last_pass_tip_texts, least_runs as shrink_least_runs,
|
||||
row_builds, row_measures, run as measuring_run, take_effects, widest_runs,
|
||||
last_frame_memo_runs, last_pass_access_builds, last_pass_body_runs as last_pass_measuring_runs, last_pass_command_reads,
|
||||
last_pass_derived_builds, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts,
|
||||
last_pass_tip_texts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs,
|
||||
};
|
||||
#[cfg(feature = "testing")]
|
||||
pub use crate::runtime::pass_state::unbound_reads as unbound_pass_state_reads;
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! A disabled node offers no action that would act on it: no Expand or Collapse, no context menu, no value step and no
|
||||
//! custom action, on a component's own node and on its sub-nodes, while it still reports its state.
|
||||
|
||||
use craft_behavior::PartKey;
|
||||
use craft_ui::contract::{Access, Common, Component, Cx, MeasureCx, Name, Numeric, Overlays as _, Props as _, Role, Show as _, Trigger};
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui::testing::access::Declared;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui_test_kit::contract::PlainStyle;
|
||||
use egui::{Id, Vec2};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
const SECTION: PartKey = PartKey::new("section");
|
||||
const KNOB: PartKey = PartKey::new("knob");
|
||||
const NUDGE: PartKey = PartKey::new("nudge");
|
||||
|
||||
/// A closed disclosure button with a custom action and a context menu, and three sub-nodes: an open heading, a stepped
|
||||
/// knob and a part that steps something with no number and serves a custom action.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
struct Fold {
|
||||
#[common]
|
||||
common: Common,
|
||||
}
|
||||
|
||||
impl Component for Fold {
|
||||
const ROLE: Role = Role::BUTTON;
|
||||
type Style = PlainStyle;
|
||||
type Output = egui::Response;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: FoldStyleKey) -> PlainStyle {
|
||||
PlainStyle::default()
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(120.0, 30.0)
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
|
||||
access.expanded(false).custom_action(1, "Reset".into());
|
||||
let section = access.node(SECTION, Role::HEADING).expanded(true);
|
||||
section.name = Name::Text("Section".to_owned());
|
||||
let knob = access.node(KNOB, Role::SLIDER);
|
||||
knob.name = Name::Text("Knob".to_owned());
|
||||
knob.numeric = Some(Numeric::new(3.0, 0.0..=10.0).step(1.0));
|
||||
let nudge = access.node(NUDGE, Role::BUTTON).steps().custom_action(2, "Center".into());
|
||||
nudge.name = Name::Text("Nudge".to_owned());
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
cx.popup("menu").trigger(Trigger::Context, cx);
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stepped value in the middle of its range.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
struct Dial {
|
||||
#[common]
|
||||
common: Common,
|
||||
}
|
||||
|
||||
impl Component for Dial {
|
||||
const ROLE: Role = Role::SLIDER;
|
||||
type Style = PlainStyle;
|
||||
type Output = egui::Response;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: DialStyleKey) -> PlainStyle {
|
||||
PlainStyle::default()
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(120.0, 30.0)
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
|
||||
access.numeric(Numeric::new(5.0, 0.0..=10.0).step(1.0));
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_disabled_node_offers_no_action_and_keeps_its_state() {
|
||||
let enabled = Rc::new(Cell::new(true));
|
||||
let fold = Rc::new(Cell::new(Id::NULL));
|
||||
let (gate, shown) = (enabled.clone(), fold.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
shown.set(Fold { common: Common::new() }.label("Fold").enabled(gate.get()).show(ui).id);
|
||||
Dial { common: Common::new() }.label("Dial").enabled(gate.get()).show(ui);
|
||||
});
|
||||
for on in [true, false] {
|
||||
enabled.set(on);
|
||||
fixture.settle();
|
||||
let tree = fixture.tree();
|
||||
let own = fixture.by_label("Fold").expect("the disclosure");
|
||||
let dial = fixture.by_label("Dial").expect("the value");
|
||||
let part = |key: PartKey| fixture.part(fold.get(), key).expect("the part's node");
|
||||
let (section, knob, nudge) = (part(SECTION), part(KNOB), part(NUDGE));
|
||||
assert_eq!(tree.expanded_of(own.node), Some(false), "the disclosure reports it is closed (enabled: {on})");
|
||||
assert_eq!(tree.expanded_of(section.node), Some(true), "the heading reports it is open (enabled: {on})");
|
||||
let offers = [
|
||||
(own.node, Declared::Expand, "the disclosure's Expand"),
|
||||
(own.node, Declared::Custom, "the disclosure's custom action"),
|
||||
(own.node, Declared::ContextMenu, "the disclosure's context menu"),
|
||||
(section.node, Declared::Collapse, "the heading's Collapse"),
|
||||
(knob.node, Declared::SetValue, "the knob's SetValue"),
|
||||
(knob.node, Declared::Increment, "the knob's Increment"),
|
||||
(knob.node, Declared::Decrement, "the knob's Decrement"),
|
||||
(nudge.node, Declared::Increment, "the nudge's Increment"),
|
||||
(nudge.node, Declared::Decrement, "the nudge's Decrement"),
|
||||
(nudge.node, Declared::Custom, "the nudge's custom action"),
|
||||
(dial.node, Declared::SetValue, "the dial's SetValue"),
|
||||
(dial.node, Declared::Increment, "the dial's Increment"),
|
||||
(dial.node, Declared::Decrement, "the dial's Decrement"),
|
||||
];
|
||||
for (node, action, what) in offers {
|
||||
assert_eq!(tree.declares_key(node, action), on, "{what} is offered only while enabled (enabled: {on})");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
pub(crate) mod bounds;
|
||||
pub(crate) mod controls;
|
||||
pub(crate) mod disabled_actions;
|
||||
pub(crate) mod face_record;
|
||||
pub(crate) mod face_state;
|
||||
pub(crate) mod focus;
|
||||
|
||||
@@ -597,6 +597,101 @@ fn a_memoized_view_sits_on_the_rows_line() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapping `SpaceBetween` row whose children fit on one line spreads them over its room: the first starts at the
|
||||
/// row's start, the last ends at its end, and the short child sits at the middle of the tall one's line. Too narrow
|
||||
/// for one line, it wraps the last child onto a second line from the row's start. The children keep their ids when
|
||||
/// the row starts wrapping.
|
||||
#[trial]
|
||||
fn a_wrapping_space_between_row_spreads_children_that_fit_one_line() {
|
||||
let seen: Rc<[RefCell<Seen>; 2]> = Rc::new(Default::default());
|
||||
let row = Rc::new(Cell::new(Rect::NOTHING));
|
||||
let (shown, shown_row) = (Rc::clone(&seen), Rc::clone(&row));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let layout = BodyLayout::row().wrap(true).align(RowAlign::SpaceBetween);
|
||||
let panel = Panel::new().layout(layout).sizing(Sizing::FillWidth).id_salt("spread").show(ui, |ui, _| {
|
||||
for (i, (seen, size)) in shown.iter().zip([ITEM, Vec2::new(40.0, 30.0)]).enumerate() {
|
||||
Probe::new(seen).size(size).id_salt(i).show(ui);
|
||||
}
|
||||
});
|
||||
shown_row.set(panel.output.rect);
|
||||
});
|
||||
let mut ids = Vec::new();
|
||||
for (width, fits) in [(300.0, true), (70.0, false)] {
|
||||
fixture.room(Vec2::new(width, 400.0)).settle();
|
||||
ids.push(seen.each_ref().map(|seen| seen.borrow().id));
|
||||
let rects = || seen.each_ref().map(|seen| seen.borrow().rect);
|
||||
let ([first, last], row) = (rects(), row.get());
|
||||
let dump = format!("width {width}: row {row:?}, first {first:?}, last {last:?}");
|
||||
assert!((first.min.x - row.min.x).abs() < SLACK, "the first child starts at the row's start: {dump}");
|
||||
if fits {
|
||||
assert!((last.max.x - row.max.x).abs() < SLACK, "the last child ends at the row's end: {dump}");
|
||||
assert!((first.center().y - last.center().y).abs() < SLACK, "the children share one line: {dump}");
|
||||
} else {
|
||||
assert!(last.top() >= first.bottom() - SLACK, "the last child wraps onto a second line: {dump}");
|
||||
assert!((last.min.x - row.min.x).abs() < SLACK, "the second line starts at the row's start: {dump}");
|
||||
}
|
||||
let settled = rects();
|
||||
fixture.idle(3);
|
||||
assert_eq!(rects(), settled, "width {width}: the frames that reuse the measurement place the children alike");
|
||||
}
|
||||
assert_eq!(ids[0], ids[1], "the children keep their ids when the row starts wrapping");
|
||||
}
|
||||
|
||||
/// A wrapping `SpaceBetween` row whose children fit one line but whose direct egui allocation after them wraps onto a
|
||||
/// second line wraps: the allocation stays inside the row instead of running past its end.
|
||||
#[trial]
|
||||
fn a_spread_wrapping_row_wraps_a_direct_allocation_that_takes_a_second_line() {
|
||||
let seen: Rc<[RefCell<Seen>; 2]> = Rc::new(Default::default());
|
||||
let rects = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING)));
|
||||
let (shown, shown_rects) = (Rc::clone(&seen), Rc::clone(&rects));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let layout = BodyLayout::row().wrap(true).align(RowAlign::SpaceBetween);
|
||||
let direct = Cell::new(Rect::NOTHING);
|
||||
let panel = Panel::new().layout(layout).sizing(Sizing::FillWidth).id_salt("spread").show(ui, |ui, _| {
|
||||
for (i, seen) in shown.iter().enumerate() {
|
||||
Probe::new(seen).size(Vec2::new(20.0, 10.0)).id_salt(i).show(ui);
|
||||
}
|
||||
direct.set(ui.allocate_exact_size(Vec2::new(60.0, 10.0), egui::Sense::hover()).0);
|
||||
});
|
||||
shown_rects.set((panel.output.rect, direct.get()));
|
||||
});
|
||||
fixture.room(Vec2::new(100.0, 400.0)).settle();
|
||||
let (row, direct) = rects.get();
|
||||
let first = seen[0].borrow().rect;
|
||||
let dump = format!("row {row:?}, first {first:?}, direct {direct:?}");
|
||||
assert!(direct.max.x <= row.max.x + SLACK, "the direct allocation ends inside the row: {dump}");
|
||||
assert!(direct.top() >= first.bottom() - SLACK, "the direct allocation wraps onto a second line: {dump}");
|
||||
}
|
||||
|
||||
/// A wrapping `SpaceBetween` row that spreads children of different heights on one line, in an unwrapped row beside a
|
||||
/// taller block, reports the line its children sit on as its first line: its children sit on the outer row's line.
|
||||
#[trial]
|
||||
fn a_spread_wrapping_row_reports_its_spread_line_as_its_first_line() {
|
||||
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING, Rect::NOTHING)));
|
||||
let shown = Rc::clone(&seen);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
Panel::new().layout(BodyLayout::row()).id_salt("outer").show(ui, |ui, _| {
|
||||
let tall = Block::new(Vec2::new(20.0, 50.0)).show(ui).rect;
|
||||
let layout = BodyLayout::row().wrap(true).align(RowAlign::SpaceBetween);
|
||||
let inner = Panel::new().layout(layout).id_salt("inner").show(ui, |ui, _| {
|
||||
let short = Block::new(ITEM).show(ui).rect;
|
||||
let big = Block::new(Vec2::new(40.0, 30.0)).show(ui).rect;
|
||||
(short, big)
|
||||
});
|
||||
if !is_measuring(ui.ctx()) {
|
||||
let (short, big) = inner.inner.unwrap_or((Rect::NOTHING, Rect::NOTHING));
|
||||
shown.set((tall, short, big));
|
||||
}
|
||||
});
|
||||
});
|
||||
fixture.room(Vec2::splat(400.0)).settle();
|
||||
let (tall, short, big) = seen.get();
|
||||
let dump = format!("tall {tall:?}, short {short:?}, big {big:?}");
|
||||
assert!(short.height() > 0.0 && big.height() > 0.0, "the inner row showed its blocks: {dump}");
|
||||
assert!((short.center().y - big.center().y).abs() < SLACK, "the inner row's blocks share one line: {dump}");
|
||||
assert!((short.center().y - tall.center().y).abs() < SLACK, "the inner row's line is the outer row's line: {dump}");
|
||||
}
|
||||
|
||||
/// An unwrapped row in a row sits on the outer row's line by its own line, whatever its alignment: a row that places
|
||||
/// its block from its start, at its end, centred or spread reports its line as its first line alike.
|
||||
#[trial]
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
//! An AccessKit request that would act on a disabled node does not reach its component: no Expand, Collapse, Click,
|
||||
//! context menu, step, value or custom action, on the component's own node or on its sub-nodes. The same requests on
|
||||
//! an enabled component do.
|
||||
|
||||
use craft_behavior::{AccessAction, AccessData, Input, PartKey, PlainText, Sense};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, Numeric, Overlays as _, PaintUi, PartsCx,
|
||||
Pointer as _, Props as _, Role, Show as _, Trigger,
|
||||
};
|
||||
use craft_ui::primitives::{TextKey, TextOptions};
|
||||
use craft_ui::runtime::focus::KeyUse;
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui_test_kit::contract::PlainStyle;
|
||||
use egui::accesskit::{ActionRequest, NodeId, TreeId};
|
||||
use egui::{Event, Id, Rect, Vec2, pos2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
const CHEVRON: PartKey = PartKey::new("chevron");
|
||||
const SECTION: PartKey = PartKey::new("section");
|
||||
const KNOB: PartKey = PartKey::new("knob");
|
||||
const NUDGE: PartKey = PartKey::new("nudge");
|
||||
const TEXT: PartKey = PartKey::new("text");
|
||||
|
||||
/// What reached the components in their latest run.
|
||||
#[derive(Default)]
|
||||
struct Seen {
|
||||
menu_open: Cell<bool>,
|
||||
context_open: Cell<bool>,
|
||||
activations: Cell<usize>,
|
||||
moves: Cell<usize>,
|
||||
values: RefCell<Vec<f64>>,
|
||||
requests: RefCell<Vec<AccessAction>>,
|
||||
opener: Cell<Option<Id>>,
|
||||
dial: Cell<Option<Id>>,
|
||||
}
|
||||
|
||||
impl Seen {
|
||||
fn requested(&self, action: AccessAction) -> bool {
|
||||
self.requests.borrow().contains(&action)
|
||||
}
|
||||
}
|
||||
|
||||
/// A button whose chevron part, with no node of its own, opens a menu, with a context menu, a custom action and three
|
||||
/// sub-nodes: an open heading, a stepped knob and a part that steps something with no number.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
struct Opener {
|
||||
#[common]
|
||||
common: Common,
|
||||
seen: Rc<Seen>,
|
||||
}
|
||||
|
||||
impl Component for Opener {
|
||||
const ROLE: Role = Role::BUTTON;
|
||||
type Style = PlainStyle;
|
||||
type Output = egui::Response;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: OpenerStyleKey) -> PlainStyle {
|
||||
PlainStyle::default()
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(160.0, 30.0)
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let chevron = Rect::from_min_max(pos2(rect.max.x - 30.0, rect.min.y), rect.max);
|
||||
cx.part(CHEVRON, chevron).sense(Sense::CLICK).toggles("menu");
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
|
||||
access.custom_action(1, "Reset".into());
|
||||
let section = access.node(SECTION, Role::HEADING).expanded(true);
|
||||
section.name = Name::Text("Section".to_owned());
|
||||
let knob = access.node(KNOB, Role::SLIDER);
|
||||
knob.name = Name::Text("Knob".to_owned());
|
||||
knob.numeric = Some(Numeric::new(3.0, 0.0..=10.0).step(1.0));
|
||||
let nudge = access.node(NUDGE, Role::BUTTON).steps();
|
||||
nudge.name = Name::Text("Nudge".to_owned());
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
cx.popup("context").trigger(Trigger::Context, cx);
|
||||
self.seen.menu_open.set(cx.popup("menu").is_open(cx));
|
||||
self.seen.context_open.set(cx.popup("context").is_open(cx));
|
||||
if cx.activation().is_some() {
|
||||
self.seen.activations.set(self.seen.activations.get() + 1);
|
||||
}
|
||||
if let Some(value) = cx.intents().take_set_value_at(KNOB) {
|
||||
self.seen.values.borrow_mut().push(value);
|
||||
}
|
||||
while let Some(request) = cx.intents().take_access() {
|
||||
self.seen.requests.borrow_mut().push(request.action);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stepped value in the middle of its range that takes the moves and values routed to it.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
struct Dial {
|
||||
#[common]
|
||||
common: Common,
|
||||
seen: Rc<Seen>,
|
||||
}
|
||||
|
||||
impl Component for Dial {
|
||||
const ROLE: Role = Role::SLIDER;
|
||||
type Style = PlainStyle;
|
||||
type Output = egui::Response;
|
||||
|
||||
fn keys(&self) -> KeyUse {
|
||||
KeyUse::of(Input::Pointer).with_moves()
|
||||
}
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: DialStyleKey) -> PlainStyle {
|
||||
PlainStyle::default()
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(120.0, 30.0)
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
|
||||
access.numeric(Numeric::new(5.0, 0.0..=10.0).step(1.0));
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
while cx.intents().take_move().is_some() {
|
||||
self.seen.moves.set(self.seen.moves.get() + 1);
|
||||
}
|
||||
if let Some(value) = cx.intents().take_set_value() {
|
||||
self.seen.values.borrow_mut().push(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The node a request targets.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Aim {
|
||||
Opener,
|
||||
Dial,
|
||||
Part(PartKey),
|
||||
}
|
||||
|
||||
/// One request and how the components show that it reached them.
|
||||
struct Case {
|
||||
what: &'static str,
|
||||
aim: Aim,
|
||||
action: AccessAction,
|
||||
data: Option<AccessData>,
|
||||
reached: fn(&Seen) -> bool,
|
||||
}
|
||||
|
||||
/// Shows the two components, enabled or not, sends the request of `case` and returns what reached them.
|
||||
fn send(case: &Case, enabled: bool) -> Rc<Seen> {
|
||||
let seen = Rc::new(Seen::default());
|
||||
let shown = seen.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let opener = Opener { common: Common::new(), seen: shown.clone() }.label("Opener").enabled(enabled).show(ui);
|
||||
shown.opener.set(Some(opener.id));
|
||||
let dial = Dial { common: Common::new(), seen: shown.clone() }.label("Dial").enabled(enabled).show(ui);
|
||||
shown.dial.set(Some(dial.id));
|
||||
});
|
||||
fixture.settle();
|
||||
let opener = seen.opener.get().expect("the opener ran");
|
||||
let node = match case.aim {
|
||||
Aim::Opener => opener.accesskit_id(),
|
||||
Aim::Dial => seen.dial.get().expect("the dial ran").accesskit_id(),
|
||||
Aim::Part(part) => NodeId(fixture.part(opener, part).expect("the part's node").node.raw()),
|
||||
};
|
||||
let request = ActionRequest { action: case.action, target_tree: TreeId::ROOT, target_node: node, data: case.data.clone() };
|
||||
fixture.frame(vec![Event::AccessKitActionRequest(request)]).settle();
|
||||
seen
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_disabled_component_takes_no_access_request_that_acts_on_it() {
|
||||
let cases = [
|
||||
Case {
|
||||
what: "Expand on the component opens its menu",
|
||||
aim: Aim::Opener,
|
||||
action: AccessAction::Expand,
|
||||
data: None,
|
||||
reached: |seen| seen.menu_open.get(),
|
||||
},
|
||||
Case {
|
||||
what: "ShowContextMenu on the component opens its context menu",
|
||||
aim: Aim::Opener,
|
||||
action: AccessAction::ShowContextMenu,
|
||||
data: None,
|
||||
reached: |seen| seen.context_open.get(),
|
||||
},
|
||||
Case {
|
||||
what: "Click on the component activates it",
|
||||
aim: Aim::Opener,
|
||||
action: AccessAction::Click,
|
||||
data: None,
|
||||
reached: |seen| seen.activations.get() > 0,
|
||||
},
|
||||
Case {
|
||||
what: "a custom action on the component reaches it",
|
||||
aim: Aim::Opener,
|
||||
action: AccessAction::CustomAction,
|
||||
data: Some(AccessData::CustomAction(1)),
|
||||
reached: |seen| seen.requested(AccessAction::CustomAction),
|
||||
},
|
||||
Case {
|
||||
what: "a text SetValue on the component reaches it",
|
||||
aim: Aim::Opener,
|
||||
action: AccessAction::SetValue,
|
||||
data: Some(AccessData::Value("Typed".into())),
|
||||
reached: |seen| seen.requested(AccessAction::SetValue),
|
||||
},
|
||||
Case {
|
||||
what: "Increment on the value steps it",
|
||||
aim: Aim::Dial,
|
||||
action: AccessAction::Increment,
|
||||
data: None,
|
||||
reached: |seen| seen.moves.get() > 0,
|
||||
},
|
||||
Case {
|
||||
what: "SetValue on the value sets it",
|
||||
aim: Aim::Dial,
|
||||
action: AccessAction::SetValue,
|
||||
data: Some(AccessData::NumericValue(8.0)),
|
||||
reached: |seen| !seen.values.borrow().is_empty(),
|
||||
},
|
||||
Case {
|
||||
what: "Collapse on the heading reaches the component",
|
||||
aim: Aim::Part(SECTION),
|
||||
action: AccessAction::Collapse,
|
||||
data: None,
|
||||
reached: |seen| seen.requested(AccessAction::Collapse),
|
||||
},
|
||||
Case {
|
||||
what: "Click on the heading reaches the component",
|
||||
aim: Aim::Part(SECTION),
|
||||
action: AccessAction::Click,
|
||||
data: None,
|
||||
reached: |seen| seen.requested(AccessAction::Click),
|
||||
},
|
||||
Case {
|
||||
what: "Increment on the nudge reaches the component",
|
||||
aim: Aim::Part(NUDGE),
|
||||
action: AccessAction::Increment,
|
||||
data: None,
|
||||
reached: |seen| seen.requested(AccessAction::Increment),
|
||||
},
|
||||
Case {
|
||||
what: "SetValue on the knob sets it",
|
||||
aim: Aim::Part(KNOB),
|
||||
action: AccessAction::SetValue,
|
||||
data: Some(AccessData::NumericValue(8.0)),
|
||||
reached: |seen| !seen.values.borrow().is_empty(),
|
||||
},
|
||||
];
|
||||
let mut wrong = Vec::new();
|
||||
for case in &cases {
|
||||
for enabled in [true, false] {
|
||||
if (case.reached)(&send(case, enabled)) != enabled {
|
||||
wrong.push(format!("{} (enabled: {enabled})", case.what));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "each request reaches the components only while they are enabled: {wrong:#?}");
|
||||
}
|
||||
|
||||
/// An enabled field over a string whose text part is enabled or not, recording the access requests that reach it.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
struct Field<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
value: Bind<'a, String>,
|
||||
text_enabled: bool,
|
||||
requests: Rc<RefCell<Vec<AccessAction>>>,
|
||||
}
|
||||
|
||||
impl Component for Field<'_> {
|
||||
const ROLE: Role = Role::TEXT_INPUT;
|
||||
const INPUT: Input = Input::Text;
|
||||
type Style = PlainStyle;
|
||||
type Output = EditResponse<String>;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: FieldStyleKey) -> PlainStyle {
|
||||
PlainStyle::default()
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(120.0, 24.0)
|
||||
}
|
||||
|
||||
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let options = TextOptions { enabled: self.text_enabled, ..TextOptions::default() };
|
||||
let (shown, rect) = (cx.value().cloned().unwrap_or_default(), cx.content_rect);
|
||||
cx.text(TextKey::<String>::new(TEXT), rect, &PlainText, &shown, &options);
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, String>> {
|
||||
Some(self.value.reborrow())
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
while let Some(request) = cx.intents().take_access() {
|
||||
self.requests.borrow_mut().push(request.action);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<String> {
|
||||
cx.edit_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the field with its text part enabled or not, sends `action` to the field's node and returns the access
|
||||
/// requests that reached the field and its value.
|
||||
fn send_to_field(text_enabled: bool, action: AccessAction, data: AccessData) -> (Vec<AccessAction>, String) {
|
||||
let value = Rc::new(RefCell::new(String::from("Kept")));
|
||||
let requests = Rc::new(RefCell::new(Vec::new()));
|
||||
let id = Rc::new(Cell::new(Id::NULL));
|
||||
let (held, taken, seen) = (value.clone(), requests.clone(), id.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut text = held.borrow_mut();
|
||||
let field = Field { common: Common::new(), value: Bind::bound(&mut *text), text_enabled, requests: taken.clone() };
|
||||
seen.set(field.label("Field").show(ui).response.id);
|
||||
});
|
||||
fixture.settle();
|
||||
requests.borrow_mut().clear();
|
||||
let request = ActionRequest { action, target_tree: TreeId::ROOT, target_node: id.get().accesskit_id(), data: Some(data) };
|
||||
fixture.frame(vec![Event::AccessKitActionRequest(request)]).settle();
|
||||
let reached = requests.borrow().clone();
|
||||
let value = value.borrow().clone();
|
||||
(reached, value)
|
||||
}
|
||||
|
||||
/// The node of an enabled field stands for its text part and is disabled with it: a request that acts on the node
|
||||
/// reaches the field, or sets its value, only while the text part is enabled.
|
||||
#[trial]
|
||||
fn a_disabled_text_part_disables_its_owners_node_for_requests_that_act_on_it() {
|
||||
let replace = |enabled| send_to_field(enabled, AccessAction::ReplaceSelectedText, AccessData::Value("Typed".into())).0;
|
||||
assert!(replace(true).contains(&AccessAction::ReplaceSelectedText), "an enabled text part takes ReplaceSelectedText");
|
||||
assert!(replace(false).is_empty(), "a disabled text part takes no ReplaceSelectedText");
|
||||
let set = |enabled| send_to_field(enabled, AccessAction::SetValue, AccessData::Value("Typed".into())).1;
|
||||
assert_eq!(set(true), "Typed", "an enabled text part takes the value");
|
||||
assert_eq!(set(false), "Kept", "a disabled text part keeps its value");
|
||||
}
|
||||
|
||||
/// An enabled component that shows the field as its own control (`PaintUi::inner`), recording the access requests
|
||||
/// that reach it.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
struct Wrapper {
|
||||
#[common]
|
||||
common: Common,
|
||||
value: Rc<RefCell<String>>,
|
||||
text_enabled: bool,
|
||||
requests: Rc<RefCell<Vec<AccessAction>>>,
|
||||
}
|
||||
|
||||
impl Component for Wrapper {
|
||||
const ROLE: Role = Role::TEXT_INPUT;
|
||||
type Style = PlainStyle;
|
||||
type Output = egui::Response;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: WrapperStyleKey) -> PlainStyle {
|
||||
PlainStyle::default()
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(120.0, 24.0)
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let mut text = self.value.borrow_mut();
|
||||
let field = Field { common: Common::new(), value: Bind::bound(&mut *text), text_enabled: self.text_enabled, requests: self.requests.clone() };
|
||||
ui.inner("field", cx.rect, field.label("Field"));
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
while let Some(request) = cx.intents().take_access() {
|
||||
self.requests.borrow_mut().push(request.action);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the wrapper with its inner field's text part enabled or not, sends `action` to the wrapper's node and returns
|
||||
/// the access requests that reached the inner field and its value.
|
||||
fn send_to_wrapper(text_enabled: bool, action: AccessAction, data: AccessData) -> (Vec<AccessAction>, String) {
|
||||
let value = Rc::new(RefCell::new(String::from("Kept")));
|
||||
let requests = Rc::new(RefCell::new(Vec::new()));
|
||||
let id = Rc::new(Cell::new(Id::NULL));
|
||||
let (held, taken, seen) = (value.clone(), requests.clone(), id.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let wrapper = Wrapper { common: Common::new(), value: held.clone(), text_enabled, requests: taken.clone() };
|
||||
seen.set(wrapper.label("Wrapper").show(ui).id);
|
||||
});
|
||||
fixture.settle();
|
||||
requests.borrow_mut().clear();
|
||||
let request = ActionRequest { action, target_tree: TreeId::ROOT, target_node: id.get().accesskit_id(), data: Some(data) };
|
||||
fixture.frame(vec![Event::AccessKitActionRequest(request)]).settle();
|
||||
let reached = requests.borrow().clone();
|
||||
let value = value.borrow().clone();
|
||||
(reached, value)
|
||||
}
|
||||
|
||||
/// The node of a component that shows a field through `PaintUi::inner` stands for the field's text part and is
|
||||
/// disabled with it: a request that acts on the node reaches the field, or sets its value, only while the text part
|
||||
/// is enabled.
|
||||
#[trial]
|
||||
fn a_disabled_inner_text_part_disables_the_wrappers_node_for_requests_that_act_on_it() {
|
||||
let replace = |enabled| send_to_wrapper(enabled, AccessAction::ReplaceSelectedText, AccessData::Value("Typed".into())).0;
|
||||
assert!(replace(true).contains(&AccessAction::ReplaceSelectedText), "an enabled inner text part takes ReplaceSelectedText");
|
||||
assert!(replace(false).is_empty(), "a disabled inner text part takes no ReplaceSelectedText");
|
||||
let set = |enabled| send_to_wrapper(enabled, AccessAction::SetValue, AccessData::Value("Typed".into())).1;
|
||||
assert_eq!(set(true), "Typed", "an enabled inner text part takes the value");
|
||||
assert_eq!(set(false), "Kept", "a disabled inner text part keeps its value");
|
||||
}
|
||||
|
||||
/// An enabled component that shows the wrapper as its own control (`PaintUi::inner`), so the field is nested two
|
||||
/// owners deep.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
struct Outer {
|
||||
#[common]
|
||||
common: Common,
|
||||
value: Rc<RefCell<String>>,
|
||||
text_enabled: bool,
|
||||
requests: Rc<RefCell<Vec<AccessAction>>>,
|
||||
}
|
||||
|
||||
impl Component for Outer {
|
||||
const ROLE: Role = Role::TEXT_INPUT;
|
||||
type Style = PlainStyle;
|
||||
type Output = egui::Response;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: OuterStyleKey) -> PlainStyle {
|
||||
PlainStyle::default()
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(120.0, 24.0)
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let wrapper = Wrapper { common: Common::new(), value: self.value.clone(), text_enabled: self.text_enabled, requests: self.requests.clone() };
|
||||
ui.inner("wrapper", cx.rect, wrapper.label("Wrapper"));
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the outer component with the nested field's text part enabled or not, sends `action` to the outer node and
|
||||
/// returns the access requests that reached the wrapper or the field.
|
||||
fn send_to_outer(text_enabled: bool, action: AccessAction, data: AccessData) -> Vec<AccessAction> {
|
||||
let value = Rc::new(RefCell::new(String::from("Kept")));
|
||||
let requests = Rc::new(RefCell::new(Vec::new()));
|
||||
let id = Rc::new(Cell::new(Id::NULL));
|
||||
let (taken, seen) = (requests.clone(), id.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let outer = Outer { common: Common::new(), value: value.clone(), text_enabled, requests: taken.clone() };
|
||||
seen.set(outer.label("Outer").show(ui).id);
|
||||
});
|
||||
fixture.settle();
|
||||
requests.borrow_mut().clear();
|
||||
let request = ActionRequest { action, target_tree: TreeId::ROOT, target_node: id.get().accesskit_id(), data: Some(data) };
|
||||
fixture.frame(vec![Event::AccessKitActionRequest(request)]).settle();
|
||||
requests.borrow().clone()
|
||||
}
|
||||
|
||||
/// A disabled text part two `PaintUi::inner` owners deep disables the outermost node too: the intermediate owner
|
||||
/// passes its inner component's disabled state on to its own owner, so a request that acts on the outer node reaches
|
||||
/// the wrapper only while the text part is enabled.
|
||||
#[trial]
|
||||
fn a_disabled_text_part_nested_two_owners_deep_disables_the_outer_node() {
|
||||
let replace = |enabled| send_to_outer(enabled, AccessAction::ReplaceSelectedText, AccessData::Value("Typed".into()));
|
||||
assert!(replace(true).contains(&AccessAction::ReplaceSelectedText), "an enabled nested text part takes ReplaceSelectedText");
|
||||
assert!(replace(false).is_empty(), "a disabled nested text part takes no ReplaceSelectedText");
|
||||
}
|
||||
@@ -6,6 +6,7 @@ pub(crate) mod clipboard;
|
||||
pub(crate) mod control_click;
|
||||
pub(crate) mod cursor;
|
||||
pub(crate) mod derived;
|
||||
pub(crate) mod disabled_requests;
|
||||
pub(crate) mod elapsed;
|
||||
pub(crate) mod env;
|
||||
pub(crate) mod fingers;
|
||||
|
||||
@@ -7,7 +7,8 @@ use super::dock_column::{
|
||||
};
|
||||
use super::group::GripMarks;
|
||||
use super::{
|
||||
CardInset, DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, FlyoutHeight, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag,
|
||||
CardInset, DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, FlyoutHeight, GroupAt, PanelKey, PanelSpec, Splitter, start_group_drag,
|
||||
start_icon_drag,
|
||||
};
|
||||
use crate::buttons::{ActiveLook, IconButton};
|
||||
use crate::contract::overlay::Anchor;
|
||||
@@ -633,6 +634,9 @@ impl<P: Value + Hash + Debug + 'static> Component for IconicColumn<'_, P> {
|
||||
let dragging =
|
||||
|phase: PressPhase| matches!(phase, PressPhase::DragStart { start, .. } if start.button == craft_behavior::PointerButton::Primary);
|
||||
let mut began = false;
|
||||
// All of the column floats collapsed with its strip under the pointer; part of it floats expanded, as the
|
||||
// layout makes it.
|
||||
let panels = self.column.panels().count();
|
||||
for (group, extent) in &plan.groups {
|
||||
if dragging(cx.part(GRIP.at(*group as u64)).press.phase)
|
||||
&& let Some(lead) = self.column.groups.get(*group)
|
||||
@@ -640,7 +644,12 @@ impl<P: Value + Hash + Debug + 'static> Component for IconicColumn<'_, P> {
|
||||
{
|
||||
let shown = lead.active_panel().unwrap_or(anchor);
|
||||
let label = Label::from((self.spec)(shown).label.as_str().to_owned());
|
||||
start_icon_drag(cx, DragUnit::Group(anchor.clone()), PanelKey::of(shown), extent.size(), label);
|
||||
let unit = DragUnit::Group(anchor.clone());
|
||||
if lead.panels.len() == panels {
|
||||
start_icon_drag(cx, unit, PanelKey::of(shown), extent.size(), label);
|
||||
} else {
|
||||
start_group_drag(cx, unit, PanelKey::of(shown), None, Some(label));
|
||||
}
|
||||
began = true;
|
||||
}
|
||||
}
|
||||
@@ -650,7 +659,11 @@ impl<P: Value + Hash + Debug + 'static> Component for IconicColumn<'_, P> {
|
||||
&& let Some(panel) = self.panel(*group, *panel)
|
||||
{
|
||||
let label = Label::from((self.spec)(panel).label.as_str().to_owned());
|
||||
start_icon_drag(cx, DragUnit::Panel(panel.clone()), PanelKey::of(panel), cell.size(), label);
|
||||
if panels == 1 {
|
||||
start_icon_drag(cx, DragUnit::Panel(panel.clone()), PanelKey::of(panel), cell.size(), label);
|
||||
} else {
|
||||
start_group_drag(cx, DragUnit::Panel(panel.clone()), PanelKey::of(panel), None, Some(label));
|
||||
}
|
||||
began = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use super::words::RailWords;
|
||||
use crate::buttons::{Button, IconButton};
|
||||
use crate::contract::overlay::{Anchor, Dismiss, Overlay, Place};
|
||||
use crate::contract::{
|
||||
ActivateOn, Bind, CollectionEvent, Gap, ListDrag, NoValue, Outcome, PopupKind, Props as _, SelectMode, Show as _, ShowCollection as _,
|
||||
ActivateOn, Bind, CollectionEvent, Gap, ListDrag, NoValue, Outcome, Pad, PopupKind, Props as _, SelectMode, Show as _, ShowCollection as _,
|
||||
ShowContainer as _, Sizing, Trigger, clicked,
|
||||
};
|
||||
use crate::display::{Shade, TargetMark, Text};
|
||||
@@ -383,7 +383,10 @@ impl<T: Value + 'static> ToolbarDrawer<'_, T> {
|
||||
let list_id = ui.scope_id().with("drawer-tools");
|
||||
// The search field is the stack's header and the list its body; both read the query from the stack's
|
||||
// memory, which lives while the drawer is open.
|
||||
// The stack fills the drawer, so the footer stands at its foot and the list takes the room between. The
|
||||
// header's text starts where the list's headings do.
|
||||
Stack::new()
|
||||
.fill()
|
||||
.gap(Gap::Row)
|
||||
.header(|ui, stack| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
@@ -407,6 +410,8 @@ impl<T: Value + 'static> ToolbarDrawer<'_, T> {
|
||||
below(ui);
|
||||
restore |= clicked(&Button::new(words.drawer_restore.clone()).show(ui));
|
||||
})
|
||||
.footer_rule()
|
||||
.header_inset(Pad::Control)
|
||||
.show(ui, |ui, stack| {
|
||||
let query = stack.memory::<DrawerSearch>().query.clone();
|
||||
let mut list = List::<DrawerKey>::new(words.drawer_tools.clone())
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::style::{ComponentStyle, FocusLook, GlyphRole, StyleColor, StyleCx};
|
||||
use craft_behavior::overlay::{Align, Side};
|
||||
use craft_behavior::{CursorIcon, HitLevel, HitPriority, IconId, Metrics, PartKey, PointerButton, PressPhase, Sense, Value};
|
||||
use egui::{Pos2, Rect, Response, Vec2};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
@@ -102,9 +103,9 @@ struct Held(bool);
|
||||
|
||||
/// What the parts step resolved for the tools this pass.
|
||||
struct Laid {
|
||||
resolved: Vec<Option<std::sync::Arc<ResolvedCommand>>>,
|
||||
resolved: Vec<Option<Arc<ResolvedCommand>>>,
|
||||
/// The click command as resolved, when the button has one.
|
||||
click: Option<std::sync::Arc<ResolvedCommand>>,
|
||||
click: Option<Arc<ResolvedCommand>>,
|
||||
shown: usize,
|
||||
}
|
||||
|
||||
@@ -156,6 +157,10 @@ pub struct FlyoutButton<'a, T: Value + 'static> {
|
||||
/// The index of the tool among `tools` whose row wears the target mark while the flyout is open.
|
||||
#[prop(vis = "pub(crate)")]
|
||||
marked_row: Option<usize>,
|
||||
/// The tools' commands as the rail resolved them in this pass, one per tool in order: the button shows these in
|
||||
/// place of resolving each command again.
|
||||
#[prop(vis = "pub(crate)")]
|
||||
resolved: Option<&'a [Option<Arc<ResolvedCommand>>]>,
|
||||
laid: Option<Laid>,
|
||||
picked: Option<T>,
|
||||
open: bool,
|
||||
@@ -181,6 +186,7 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> {
|
||||
tips: None,
|
||||
reveal_row: None,
|
||||
marked_row: None,
|
||||
resolved: None,
|
||||
laid: None,
|
||||
picked: None,
|
||||
open: false,
|
||||
@@ -222,11 +228,11 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> {
|
||||
}
|
||||
|
||||
fn resolve(&self, cx: &MeasureCx<'_, Self>) -> Laid {
|
||||
Laid {
|
||||
resolved: self.tools.iter().map(|tool| cx.resolve_command(tool.command.clone())).collect(),
|
||||
click: self.click.clone().and_then(|command| cx.resolve_command(command)),
|
||||
shown: self.shown_at(),
|
||||
}
|
||||
let resolved = match self.resolved.filter(|resolved| resolved.len() == self.tools.len()) {
|
||||
Some(resolved) => resolved.to_vec(),
|
||||
None => self.tools.iter().map(|tool| cx.resolve_command(tool.command.clone())).collect(),
|
||||
};
|
||||
Laid { resolved, click: self.click.clone().and_then(|command| cx.resolve_command(command)), shown: self.shown_at() }
|
||||
}
|
||||
|
||||
/// The command the face stands for: the click command when there is one, else the shown tool's.
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::docking::{DockGrid, DockSizes};
|
||||
use crate::layout::RowAlign;
|
||||
use crate::layout_components::{Row, Stack};
|
||||
use crate::runtime::access::Name;
|
||||
use crate::runtime::commands::resolver_in;
|
||||
use crate::runtime::commands::{ResolvedCommand, resolver_in};
|
||||
use crate::runtime::env::{AppValues, EnvValue, Label};
|
||||
use crate::style::{ComponentStyle, GlyphRole, StyleCx, SurfaceKind, TypeRole, UiTokens};
|
||||
use crate::tabs::TornOff;
|
||||
@@ -22,8 +22,10 @@ use craft_behavior::overlay::Side;
|
||||
use craft_behavior::{IconId, Metrics, NavShape, Proposal, Roving, Sense, Value};
|
||||
use craft_theme::ControlSize;
|
||||
use egui::{Id, Rect, Response, Ui, Vec2};
|
||||
use std::borrow::Cow;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
mod data;
|
||||
mod drag;
|
||||
@@ -129,7 +131,8 @@ type FooterFn<'a> = Box<dyn FnMut(&mut Ui, RailFooter) + 'a>;
|
||||
/// ([`DockGrid::rail`] in the scope's style): it is a button and the control padding wide at one column and a button and the tight gap wider for each further column,
|
||||
/// and the slots fill the rows in reading order. The control padding surrounds the buttons; a slot that ends a group
|
||||
/// leaves `space.gap.inline` after its row; slots within a group sit `space.gap.tight` apart. The Edit Toolbar button
|
||||
/// follows the last slot; the host's footer stays in view under the slots, which scroll when the room is short under
|
||||
/// follows the last slot; the host's footer stays in view under the slots, a divider rule and `space.gap.inline` below
|
||||
/// them when that footer draws content, and the slots scroll when the room is short under
|
||||
/// an overlay bar in the end padding that shows only under the pointer (`Scroll::overlay`), or at rest too with
|
||||
/// [`bar_at_rest`](ToolRail::bar_at_rest), and its
|
||||
/// buttons show the rail's glyphs. The rail is exactly as tall as its rows and footer at the width it gets
|
||||
@@ -208,7 +211,7 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> {
|
||||
.child_size(ControlSize::Md)
|
||||
.child_glyphs(GlyphRole::ToolRail)
|
||||
.scroll(Scroll::vertical().overlay())
|
||||
.footer(FooterRegion::new());
|
||||
.footer(FooterRegion::new().rule(true).gap(Gap::Inline));
|
||||
ToolRail {
|
||||
common: Common::new(),
|
||||
props,
|
||||
@@ -320,10 +323,27 @@ struct GridProps<'a, T: PlainData> {
|
||||
sent: Outbox<'a, RailEvent<T>>,
|
||||
}
|
||||
|
||||
/// The host's tool tips, which the grid reads through a trait object: while the host sets them the grid runs every pass.
|
||||
/// The host's tool tips, which the grid reads through a trait object, keyed by which of the slots' tools have a tip and
|
||||
/// by the host's revision of them.
|
||||
#[derive(MemoProps)]
|
||||
#[memo_props(every_pass = "the host's tips are a trait object, whose answers no key can follow")]
|
||||
struct HostTips<'a, T>(&'a dyn ToolTips<T>);
|
||||
struct HostTips<'a, T> {
|
||||
#[memo_props(
|
||||
covered_by = "has",
|
||||
reason = "away from the pointer the grid reads only which tools have a tip; a tip's body shows only while the pointer rests on its button, and the view runs in every pass the pointer is over it"
|
||||
)]
|
||||
tips: &'a dyn ToolTips<T>,
|
||||
/// Whether each tool of the slots, in order, has a tip.
|
||||
has: Vec<bool>,
|
||||
revision: u64,
|
||||
}
|
||||
|
||||
impl<'a, T> HostTips<'a, T> {
|
||||
/// The tips of `tips` for the tools of `slots`.
|
||||
fn new(tips: &'a dyn ToolTips<T>, slots: &[ToolSlot<T>]) -> Self {
|
||||
let has = slots.iter().flat_map(|slot| &slot.tools).map(|tool| tips.has(&tool.id)).collect();
|
||||
HostTips { tips, has, revision: tips.revision() }
|
||||
}
|
||||
}
|
||||
|
||||
/// What the body of one pass draws from.
|
||||
struct Draw<'a, T: PlainData> {
|
||||
@@ -347,7 +367,7 @@ impl<T: Value + MemoProps + PlainData> Draw<'_, T> {
|
||||
/// Shows the grid as a memoized view; what the buttons report goes into `events` (nothing on a replay). Returns the
|
||||
/// Edit Toolbar button's id while the rail shows it, and the host's index and rect of each slot button.
|
||||
fn run(&self, ui: &mut Ui, events: &mut Vec<RailEvent<T>>) -> (Option<Id>, Vec<(usize, Rect)>) {
|
||||
let tips = self.tips.map(HostTips);
|
||||
let tips = self.tips.map(|tips| HostTips::new(tips, self.slots));
|
||||
let props = GridProps {
|
||||
slots: self.slots,
|
||||
current: self.current,
|
||||
@@ -374,11 +394,13 @@ impl<T: Value + MemoProps + PlainData> Draw<'_, T> {
|
||||
/// each slot button, around which the rail takes drops.
|
||||
fn grid<T: Value + MemoProps + PlainData>(props: &mut GridProps<'_, T>, ui: &mut Ui) -> (Option<Id>, Vec<(usize, Rect)>) {
|
||||
let GridProps { slots, current, last_used, hidden, editing, columns, opens, captions, tear_off, tips, mark, reveal, .. } = *props;
|
||||
let tips = tips.map(|tips| tips.0);
|
||||
let tips = tips.map(|tips| tips.tips);
|
||||
let visible = visible_slots(slots, hidden_in(hidden));
|
||||
let cells = visible.len() + usize::from(props.edit_label.is_some());
|
||||
// Each visible tool's command, resolved once for the pass: the buttons show these and read none again.
|
||||
let resolve = resolver_in(ui);
|
||||
let enabled = |tool: &RailTool<T>| resolve(tool.command.clone()).is_some_and(|resolved| resolved.enabled);
|
||||
let commands: Vec<Vec<Option<Arc<ResolvedCommand>>>> =
|
||||
visible.iter().map(|(_, tools)| tools.iter().map(|tool| resolve(tool.command.clone())).collect()).collect();
|
||||
let at: Vec<usize> = visible.iter().map(|(index, _)| *index).collect();
|
||||
// The first caption among a group's slots heads the group.
|
||||
let caption_of = |group: &[usize]| {
|
||||
@@ -403,13 +425,22 @@ fn grid<T: Value + MemoProps + PlainData>(props: &mut GridProps<'_, T>, ui: &mut
|
||||
match visible.get(k) {
|
||||
Some((index, tools)) => {
|
||||
let slot = &slots[*index];
|
||||
let owned: Vec<RailTool<T>> = tools.iter().map(|tool| (*tool).clone()).collect();
|
||||
let states = commands.get(k).map_or(&[][..], Vec::as_slice);
|
||||
let on = |at: usize| states.get(at).and_then(Option::as_ref).is_some_and(|resolved| resolved.enabled);
|
||||
let enabled = |tool: &RailTool<T>| tools.iter().position(|own| std::ptr::eq(*own, tool)).is_some_and(on);
|
||||
// The slot's own tools, unless the host hides some of them.
|
||||
let owned: Cow<'_, [RailTool<T>]> = if tools.len() == slot.tools.len() {
|
||||
Cow::Borrowed(slot.tools.as_slice())
|
||||
} else {
|
||||
Cow::Owned(tools.iter().map(|tool| (*tool).clone()).collect())
|
||||
};
|
||||
let Some(shown) = shown_tool(current, slot.id, tools, last_used, enabled) else { continue };
|
||||
let selected = tools.iter().any(|tool| tool.id == *current);
|
||||
let mut button = FlyoutButton::new(&owned, &shown.id)
|
||||
.id_salt(("slot", slot.id))
|
||||
.selected(selected)
|
||||
.enabled(tools.iter().any(|tool| enabled(tool)))
|
||||
.enabled((0..tools.len()).any(on))
|
||||
.resolved(states)
|
||||
.opens(opens);
|
||||
if editing {
|
||||
button = button.edit(SlotEdit::new(slot.id, *index, slot.tools.len(), columns == 1));
|
||||
|
||||
@@ -74,12 +74,22 @@ impl<T> ToolSlot<T> {
|
||||
|
||||
/// The tips of a rail's tools: where a tool `has` one, its button (and the flyout's row) shows it in place of the
|
||||
/// command tooltip.
|
||||
///
|
||||
/// The rail's grid replays its last run while the pointer is away from it and its inputs are unchanged. Its key holds
|
||||
/// which tools `has` a tip and the [`revision`](ToolTips::revision); a tip's body shows only while the pointer rests on
|
||||
/// a button, and the grid runs in every pass the pointer is over it.
|
||||
pub trait ToolTips<T> {
|
||||
/// Whether `tool` has a tip.
|
||||
fn has(&self, tool: &T) -> bool;
|
||||
|
||||
/// Shows the tip of `tool`.
|
||||
fn show(&self, tool: &T, ui: &mut Ui);
|
||||
|
||||
/// A number the host changes when a tip's body changes while the tip may show without the pointer over the rail.
|
||||
/// `0` unless the host sets one.
|
||||
fn revision(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool each slot showed last. Plain data the host keeps with its workspace.
|
||||
|
||||
@@ -246,3 +246,111 @@ fn the_edit_toolbar_button_takes_the_apps_icon() {
|
||||
fixture.idle(12);
|
||||
assert!(fixture.by_label("Customize").is_some(), "the button keeps its name with another icon");
|
||||
}
|
||||
|
||||
/// The level lines in `shapes` that lie strictly between `top` and `bottom` and run at least `width` across.
|
||||
fn level_rules(shapes: &[egui::Shape], top: f32, bottom: f32, width: f32) -> Vec<f32> {
|
||||
shapes
|
||||
.iter()
|
||||
.filter_map(|shape| match shape {
|
||||
egui::Shape::LineSegment { points: [from, to], .. } if (from.y - to.y).abs() < 0.01 && (from.x - to.x).abs() >= width => Some(from.y),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|&y| y > top && y < bottom)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A divider rule parts the rail's footer from its tools, with room on both sides of it.
|
||||
#[trial]
|
||||
fn a_rule_parts_the_rails_footer_from_its_tools() {
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::rails::{LastUsed, ToolRail};
|
||||
let slots = Tracked::new(vec![slot(0, &[UNDO]), slot(1, &[REDO]), slot(2, &[CUT])]);
|
||||
let last = Tracked::new(LastUsed::default());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
ToolRail::new("Tools", &slots, &UNDO, &last).show_rail(ui, |ui, _| {
|
||||
Button::new("Swap").show(ui);
|
||||
});
|
||||
});
|
||||
fixture.room(Vec2::new(60.0, 400.0)).settle();
|
||||
let cut = fixture.by_label("Cut").expect("the rail shows Cut").rect;
|
||||
let footer = fixture.by_label("Swap").expect("the rail shows its footer").rect;
|
||||
let shapes = fixture.frame_shapes();
|
||||
let rules = level_rules(&shapes, cut.bottom(), footer.top(), cut.width());
|
||||
assert_eq!(rules.len(), 1, "one rule lies between the last tool {cut:?} and the footer {footer:?}: {rules:?}");
|
||||
}
|
||||
|
||||
/// The drawer `menu`d with one row beside a 48-point rail, listing the Edit tools and then `more` copies of Copy, with
|
||||
/// "Below" drawn above Restore Defaults.
|
||||
fn drawer_fixture(more: u8) -> Fixture {
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::menu::PanelRow;
|
||||
use craft_ui::rails::{DrawerGroup, ToolbarDrawer};
|
||||
use craft_ui::runtime::commands::CommandRef;
|
||||
use egui::{Pos2, Rect};
|
||||
Fixture::new(move |ui| {
|
||||
let mut tools = vec![tool(UNDO), tool(REDO), tool(CUT)];
|
||||
tools.extend((10..10 + more).map(tool));
|
||||
let groups = [DrawerGroup::new("Edit", tools)];
|
||||
let toolbar = [slot(0, &[UNDO])];
|
||||
let rail = Rect::from_min_size(Pos2::ZERO, Vec2::new(48.0, 400.0));
|
||||
let menu = vec![PanelRow::Command(CommandRef::from(EditCommands::Copy))];
|
||||
ToolbarDrawer::new(rail, &groups, &toolbar, None).menu(menu).show_with(ui, |ui| {
|
||||
Text::new("Below").show(ui);
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
/// The drawer's title and hint start where the list's group headings do.
|
||||
#[trial]
|
||||
fn the_drawer_title_and_hint_line_up_with_the_headings() {
|
||||
let mut fixture = drawer_fixture(0);
|
||||
fixture.room(Vec2::new(480.0, 400.0)).settle();
|
||||
let text = |label: &str| fixture.texts().iter().find(|text| text.text == label).unwrap_or_else(|| panic!("the text {label}")).rect;
|
||||
let (title, hint, heading) = (text("Edit Toolbar"), text("Drag tools to or from the toolbar."), text("Edit"));
|
||||
assert!((title.left() - heading.left()).abs() <= 1.0, "the title {title:?} starts where the heading {heading:?} does");
|
||||
assert!((hint.left() - heading.left()).abs() <= 1.0, "the hint {hint:?} starts where the heading {heading:?} does");
|
||||
}
|
||||
|
||||
/// In a drawer too short for its list, a divider rule parts the list from the footer, and the footer stands at the
|
||||
/// drawer's foot with no more room under Restore Defaults than above the title.
|
||||
#[trial]
|
||||
fn a_rule_parts_the_drawers_list_from_its_footer_at_the_drawers_foot() {
|
||||
use craft_ui::contract::Role;
|
||||
let mut fixture = drawer_fixture(40);
|
||||
fixture.room(Vec2::new(480.0, 240.0)).idle(30);
|
||||
let drawer = fixture.by_role(Role::DIALOG).first().expect("the drawer is open").rect;
|
||||
let restore = fixture.by_label("Restore Defaults").expect("the Restore Defaults button").rect;
|
||||
let text = |label: &str| fixture.texts().iter().find(|text| text.text == label).unwrap_or_else(|| panic!("the text {label}")).rect;
|
||||
let (title, hint, below) = (text("Edit Toolbar"), text("Drag tools to or from the toolbar."), text("Below"));
|
||||
let row = fixture.by_label("Cut").expect("the Cut row").rect;
|
||||
assert!(
|
||||
drawer.right() < row.right() + row.width() / 4.0,
|
||||
"the drawer {drawer:?} stays about as wide as its list {row:?}: filling it does not stretch it across the room"
|
||||
);
|
||||
let shapes = fixture.frame_shapes();
|
||||
let rules = level_rules(&shapes, hint.bottom(), below.top(), drawer.width() / 2.0);
|
||||
assert_eq!(rules.len(), 1, "one rule lies between the list and the footer {below:?}: {rules:?}");
|
||||
assert!(drawer.bottom() - restore.bottom() >= -1.0, "Restore Defaults {restore:?} stays inside the drawer {drawer:?}");
|
||||
assert!(
|
||||
drawer.bottom() - restore.bottom() <= title.top() - drawer.top() + 1.0,
|
||||
"the room under Restore Defaults {restore:?} is no more than the room above the title {title:?} in {drawer:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A rail whose host draws no footer shows no rule under its last tool.
|
||||
#[trial]
|
||||
fn a_rail_without_a_footer_shows_no_rule_under_its_tools() {
|
||||
use craft_ui::rails::{LastUsed, ToolRail};
|
||||
let slots = Tracked::new(vec![slot(0, &[UNDO]), slot(1, &[REDO]), slot(2, &[CUT])]);
|
||||
let last = Tracked::new(LastUsed::default());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
ToolRail::new("Tools", &slots, &UNDO, &last).show_rail(ui, |_, _| {});
|
||||
});
|
||||
fixture.room(Vec2::new(60.0, 400.0)).settle();
|
||||
let cut = fixture.by_label("Cut").expect("the rail shows Cut").rect;
|
||||
let shapes = fixture.frame_shapes();
|
||||
let rules = level_rules(&shapes, cut.bottom(), f32::MAX, cut.width());
|
||||
assert!(rules.is_empty(), "no rule lies under the last tool {cut:?} of a rail with no footer: {rules:?}");
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
pub(crate) mod drawer;
|
||||
pub(crate) mod locate;
|
||||
pub(crate) mod work;
|
||||
|
||||
use craft_behavior::{GesturePhase, Mixed, PartKey};
|
||||
use craft_ui::contract::overlay::{PlacementChange, PlacementKind};
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
//! The work a rail does in a pass: its grid replays while the pointer is away, tips included, and a grid that runs reads
|
||||
//! each tool's command once.
|
||||
|
||||
use super::{CUT, REDO, UNDO, tools};
|
||||
use craft_ui::contract::tooltip::DELAY;
|
||||
use craft_ui::contract::{Role, Show as _, Tracked};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::rails::{LastUsed, ToolRail, ToolSlot, ToolTips};
|
||||
use craft_ui::testing::pointer::moved;
|
||||
use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_pass_command_reads, last_pass_memo_runs, trial};
|
||||
use egui::Ui;
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// Undo's tip, while `on`.
|
||||
struct Tips {
|
||||
on: bool,
|
||||
}
|
||||
|
||||
impl ToolTips<u8> for Tips {
|
||||
fn has(&self, tool: &u8) -> bool {
|
||||
self.on && *tool == UNDO
|
||||
}
|
||||
|
||||
fn show(&self, _: &u8, ui: &mut Ui) {
|
||||
Text::new("Steps back one edit").show(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// A rail of two slots, Undo and Redo then Cut, with Undo's tip while `on` holds.
|
||||
fn rig(on: Rc<Cell<bool>>) -> Fixture {
|
||||
let slots = Tracked::new(vec![ToolSlot::new(0, tools(&[UNDO, REDO])), ToolSlot::new(1, tools(&[CUT]))]);
|
||||
let last = Tracked::new(LastUsed::default());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let tips = Tips { on: on.get() };
|
||||
ToolRail::new("Tools", &slots, &UNDO, &last).tips(&tips).show_rail(ui, |_, _| {});
|
||||
});
|
||||
fixture.settle();
|
||||
fixture
|
||||
}
|
||||
|
||||
/// How the slot grid took part in the last pass: `(ran, replayed)`.
|
||||
fn grid_runs(fixture: &Fixture) -> (u32, u32) {
|
||||
let runs = last_pass_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, _)| name.contains("GridProps"));
|
||||
runs.fold((0, 0), |(ran, replayed), (_, _, run)| match run {
|
||||
MemoRun::Ran => (ran + 1, replayed),
|
||||
MemoRun::Replayed => (ran, replayed + 1),
|
||||
_ => (ran, replayed),
|
||||
})
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_rail_with_tips_replays_its_grid_while_the_pointer_is_away_and_still_shows_the_tip() {
|
||||
let on = Rc::new(Cell::new(true));
|
||||
let mut fixture = rig(Rc::clone(&on));
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(grid_runs(&fixture), (0, 1), "with the pointer away and nothing changed, the grid replays");
|
||||
|
||||
let undo = fixture.by_role(Role::BUTTON).into_iter().next().expect("the Undo slot's button shows");
|
||||
fixture.frame(vec![moved(undo.center())]);
|
||||
fixture.advance(DELAY);
|
||||
fixture.settle();
|
||||
assert!(fixture.texts().iter().any(|run| run.text == "Steps back one edit"), "resting on Undo's button shows its tip");
|
||||
|
||||
// The grid runs on while the hover it ended winds down, about a second.
|
||||
fixture.frame(vec![egui::Event::PointerGone]);
|
||||
fixture.advance(2.0);
|
||||
fixture.settle();
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(grid_runs(&fixture), (0, 1), "once the pointer has left, the grid replays again");
|
||||
|
||||
// The audit runs the grid where it would replay and fails on any difference between the two.
|
||||
audit_replays(fixture.ctx(), true);
|
||||
fixture.idle(3);
|
||||
audit_replays(fixture.ctx(), false);
|
||||
|
||||
on.set(false);
|
||||
fixture.frame(vec![]);
|
||||
assert_eq!(grid_runs(&fixture), (1, 0), "a change in which tools have a tip runs the grid");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_grid_that_runs_reads_each_tool_command_once() {
|
||||
let mut fixture = rig(Rc::new(Cell::new(false)));
|
||||
let undo = fixture.by_role(Role::BUTTON).into_iter().next().expect("the Undo slot's button shows");
|
||||
fixture.frame(vec![moved(undo.center())]);
|
||||
fixture.frame(vec![moved(undo.center() + egui::vec2(1.0, 0.0))]);
|
||||
assert_eq!(grid_runs(&fixture).0, 1, "with the pointer over it, the grid runs");
|
||||
let reads = last_pass_command_reads(fixture.ctx());
|
||||
assert!(reads <= READS, "a pass of the grid reads {reads} command states, at most {READS}");
|
||||
}
|
||||
|
||||
/// The command reads of a pass in which the grid runs: each of the 3 tools once, and those of the two buttons' faces.
|
||||
/// A grid whose buttons resolve each tool again reads 18.
|
||||
const READS: u32 = 9;
|
||||
@@ -34,9 +34,9 @@ impl Outcome for WorkspaceSwitcherOutput {
|
||||
}
|
||||
|
||||
/// The switcher at the end of an options bar: a small select showing the current workspace's name. Its list has the
|
||||
/// built-in and saved workspaces, then Reset, New, Delete and Lock Workspace as the `WorkspaceCommands` rows. A row
|
||||
/// fires its command, which the host takes with its other app commands and runs with `run_workspace`; the host
|
||||
/// switches with `WorkspaceSet::select`. The switcher edits nothing.
|
||||
/// built-in and saved workspaces, and the More options button in the list's header opens Reset, New, Delete and Lock
|
||||
/// Workspace as the `WorkspaceCommands` rows. A row fires its command, which the host takes with its other app
|
||||
/// commands and runs with `run_workspace`; the host switches with `WorkspaceSet::select`. The switcher edits nothing.
|
||||
#[must_use = "show the switcher with `show`"]
|
||||
#[derive(crate::contract::Pattern)]
|
||||
#[pattern(probe(WorkspaceSwitcher<'static, u32>))]
|
||||
|
||||
@@ -12,7 +12,7 @@ use craft_ui::docking::{
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::runtime::env::{Direction, RootEnv};
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
use egui::{Pos2, Rect, Ui, Vec2};
|
||||
use egui::{Modifiers, Pos2, Rect, Ui, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
@@ -423,6 +423,56 @@ fn rail_icons_stay_beside_the_expanded_column_and_the_open_panels_icon_collapses
|
||||
assert!(!shown(&fixture, "Alpha body"), "and its panel no longer shows");
|
||||
}
|
||||
|
||||
/// An icon dragged out of a docked column collapsed to icons and released outside the dock area: from a column that
|
||||
/// keeps other panels it floats expanded, its title row's middle at the pointer and no edge kept; from a column of its
|
||||
/// own panel alone it floats collapsed at the edge nearer its strip.
|
||||
#[trial]
|
||||
fn an_icon_dragged_out_of_a_collapsed_column_floats_expanded_unless_it_is_the_whole_column() {
|
||||
for groups in [vec![Group::new(vec![10], 0), Group::new(vec![11], 0)], vec![Group::new(vec![10], 0)]] {
|
||||
let whole = groups.len() == 1;
|
||||
let side = Column::new(groups).with_iconic(true);
|
||||
let root = Node::split(Axis::X, SplitSize::Ratio(0.6), Node::tabs(vec![1], 0), Node::dock(DockEdge::End, vec![side]));
|
||||
let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())))));
|
||||
let (held, specs) = (Rc::clone(&workspace), Tracked::new(Sides));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut workspace = Arc::clone(&held.borrow());
|
||||
let out = DockArea::new("Icon drag dock", Bind::given(Arc::clone(&workspace)), &specs, &mut Sides, DockConfig::default()).show(ui);
|
||||
for action in out.actions {
|
||||
drop(Arc::make_mut(&mut workspace).apply(action, false, |_: &u32| Permissions::ALL));
|
||||
}
|
||||
*held.borrow_mut() = workspace;
|
||||
});
|
||||
fixture.room(Vec2::new(900.0, 500.0)).settle();
|
||||
let tree = fixture.tree();
|
||||
let alpha = fixture
|
||||
.by_role(Role::BUTTON)
|
||||
.into_iter()
|
||||
.find(|button| craft_ui::testing::access::name(tree, button.node) == Some("Alpha"))
|
||||
.expect("the column shows the Alpha icon")
|
||||
.rect;
|
||||
// Released over the canvas with the key that floats.
|
||||
let outside = Pos2::new(300.0, 250.0);
|
||||
fixture.frame(vec![pointer::moved(alpha.center())]).frame(vec![pointer::press(alpha.center())]);
|
||||
for step in 1..=4 {
|
||||
fixture.frame(vec![pointer::moved(alpha.center() + (outside - alpha.center()) * (step as f32 / 4.0))]);
|
||||
}
|
||||
fixture.hold(Modifiers::COMMAND);
|
||||
fixture.frame(vec![pointer::moved(outside)]).frame(vec![pointer::release(outside)]);
|
||||
fixture.hold(Modifiers::NONE);
|
||||
fixture.settle();
|
||||
let layout = workspace.borrow().layout().clone();
|
||||
let window = layout.floating.iter().find(|window| window.contains(&10)).unwrap_or_else(|| panic!("Alpha floats: {layout:?}"));
|
||||
assert_eq!(window.column.iconic, whole, "whole column {whole}: {window:?}");
|
||||
if whole {
|
||||
assert!(window.edge.is_some(), "the collapsed window keeps to an edge: {window:?}");
|
||||
} else {
|
||||
assert_eq!(window.edge, None, "the expanded window keeps no edge: {window:?}");
|
||||
assert!((window.rect.center().x - outside.x).abs() <= 1.0, "its title row's middle is at the pointer: {window:?}, {outside:?}");
|
||||
assert!(end_columns(&layout)[0].iconic, "the column it left stays collapsed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How tall the flyout of [`UnderWindow`]'s Alpha group measures.
|
||||
const FLYOUT_HEIGHT: f32 = 300.0;
|
||||
|
||||
|
||||
@@ -126,3 +126,35 @@ fn the_switcher_lists_the_apps_command_rows_in_place_of_the_default_ones() {
|
||||
assert_eq!(switcher_rows(None), (true, true), "the default rows");
|
||||
assert_eq!(switcher_rows(Some(vec![WorkspaceCommands::New.into()])), (false, true), "only the app's rows");
|
||||
}
|
||||
|
||||
/// A switcher over more workspaces than its list has room for ends its list on a whole row and scrolls the rest,
|
||||
/// and its header menu button still opens the workspace commands.
|
||||
#[trial]
|
||||
fn a_long_switcher_list_ends_on_a_whole_row_and_keeps_its_commands() {
|
||||
use craft_ui::contract::Role;
|
||||
for height in [640.0, 700.0, 733.0, 811.0] {
|
||||
let mut set: WorkspaceSet<u32> = WorkspaceSet::new(vec![NamedWorkspace::new("essentials", "Essentials", Workspace::default())]);
|
||||
for at in 0..40 {
|
||||
set.save(&format!("Workspace {at}"), Workspace::default(), WorkspaceChrome::default(), WorkspaceKeeps::NONE).unwrap();
|
||||
}
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = WorkspaceSwitcher::new(&set).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(900.0, height)).settle();
|
||||
let select = fixture.by_label("Choose a workspace").expect("the switcher");
|
||||
fixture.click(&select).settle();
|
||||
let list = fixture.by_role(Role::LIST_BOX).first().expect("the switcher's list opens").rect;
|
||||
let rows: Vec<_> = fixture.by_role(Role::LIST_BOX_OPTION).into_iter().map(|row| row.rect).collect();
|
||||
assert!(rows.len() < 41, "the list {list:?} scrolls at {height}");
|
||||
// A row cut off by an end of the list reaches past it, or reports only its shown part. The list opens
|
||||
// scrolled to the current workspace, the last one.
|
||||
let full = rows.iter().map(|row| row.height()).fold(0.0, f32::max);
|
||||
for row in rows.iter().filter(|row| row.top() < list.bottom() - 0.5 && row.bottom() > list.top() + 0.5) {
|
||||
let whole = row.top() >= list.top() - 0.5 && row.bottom() <= list.bottom() + 0.5 && row.height() >= full - 0.5;
|
||||
assert!(whole, "a row {row:?} is cut off by an end of the list {list:?} in a window {height} high");
|
||||
}
|
||||
let more = fixture.by_label("More options").expect("the list's header menu button");
|
||||
fixture.click(&more).settle();
|
||||
assert!(shows(&fixture, "New Workspace…"), "the header menu opens the workspace commands at {height}");
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,8 @@ impl Outcome for TitleBarOutput {
|
||||
/// A double click follows the desktop's setting (GNOME's `action-double-click-titlebar`), and elsewhere
|
||||
/// maximizes or restores.
|
||||
///
|
||||
/// An end with no caption buttons or lights keeps the content `space.pad.regular` off the window's edge.
|
||||
/// An end with no caption buttons or lights keeps the content `space.pad.regular` off the window's edge. The leading
|
||||
/// controls, and the trailing controls of a fitted bar, stand `space.gap.item` apart.
|
||||
///
|
||||
/// In full screen the bar shows no captions and reserves no room. The free area is the container's move band:
|
||||
/// pressing and dragging it moves the window, and a double click acts as above.
|
||||
@@ -208,7 +209,7 @@ impl<'a> TitleBar<'a> {
|
||||
.surface(SurfaceKind::Chrome)
|
||||
.pad(Pad::None)
|
||||
.sizing(Sizing::FillWidth)
|
||||
.body_gap(Gap::Row)
|
||||
.body_gap(Gap::Item)
|
||||
.layout(BodyLayout::row())
|
||||
.header(HeaderRegion::new().band(DragBand::Move).inline(true))
|
||||
.end(EndRegion::new());
|
||||
@@ -264,9 +265,9 @@ impl<'a> TitleBar<'a> {
|
||||
mut trailing: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'a,
|
||||
) -> TitleBarOutput {
|
||||
self.props = self.props.end(EndRegion::new().fit(true));
|
||||
// The ranked members fit as units of the first row in the end region.
|
||||
// The ranked members fit as units of the first row in the end region, `space.gap.item` apart.
|
||||
self.trailing(move |ui: &mut Ui, cx: &mut BodyCx<'_>| {
|
||||
let _ = Row::new().show(ui, |ui, _| trailing(ui, cx));
|
||||
let _ = Row::new().gap(Gap::Item).show(ui, |ui, _| trailing(ui, cx));
|
||||
})
|
||||
.show(ui, leading)
|
||||
.output
|
||||
|
||||
@@ -604,6 +604,49 @@ fn fitted(width: f32, direction: craft_i18n::Direction, fitted: bool) -> impl Fn
|
||||
move |label: &str| fixture.by_label(label).map(|node| node.rect)
|
||||
}
|
||||
|
||||
/// A fitted bar with a Home button and a menu bar at its start and two buttons at its end puts `space.gap.item`
|
||||
/// between Home and the first menu title and between the two trailing buttons.
|
||||
#[trial]
|
||||
fn a_fitted_bar_keeps_its_controls_an_item_gap_apart() {
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{BodyCx, Show as _};
|
||||
use craft_ui::menu::MenuItem;
|
||||
use craft_ui::menu::bar::{MenuBar, MenuTitle};
|
||||
use craft_ui::runtime::env::Env;
|
||||
let item = Rc::new(Cell::new(0.0f32));
|
||||
let seen = Rc::clone(&item);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
seen.set(Env::of(ui).tokens.tokens().space.gap.item);
|
||||
let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] };
|
||||
let frame = Frame::Integrated(Captions { family: CaptionFamily::Windows, layout });
|
||||
let leading = |ui: &mut Ui, _: &mut BodyCx<'_>| {
|
||||
Button::new("Home").show(ui);
|
||||
let titles = ["&File", "&Edit"]
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
MenuTitle::new(name, |ui| {
|
||||
MenuItem::new("Row").show(ui);
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
MenuBar::new("Main menu", titles).show(ui);
|
||||
};
|
||||
let trailing = |ui: &mut Ui, _: &mut BodyCx<'_>| {
|
||||
Button::new("Community").show(ui);
|
||||
Button::new("Search").show(ui);
|
||||
};
|
||||
let _ = TitleBar::new().frame(frame).show_fitted(ui, leading, trailing);
|
||||
});
|
||||
fixture.room(vec2(1000.0, 80.0)).settle();
|
||||
let item = item.get();
|
||||
assert!(item > 0.0, "the theme has an item gap");
|
||||
let rect = |label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("{label} is shown")).rect;
|
||||
let leading = rect("File").left() - rect("Home").right();
|
||||
assert!(leading >= item - 0.5, "Home and File stand {leading} apart, less than the item gap {item}");
|
||||
let trailing = rect("Search").left() - rect("Community").right();
|
||||
assert!(trailing >= item - 0.5, "Community and Search stand {trailing} apart, less than the item gap {item}");
|
||||
}
|
||||
|
||||
/// The leading button of the fitted bar trial: menus wider than the trailing content.
|
||||
const MENUS: &str = "File Edit Object Type Select Effect View Window Help";
|
||||
|
||||
|
||||
@@ -280,6 +280,15 @@ impl<'a> Stack<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// A divider rule between the body and the footer, in a band of its own. Set it after [`footer`](Stack::footer).
|
||||
#[must_use]
|
||||
pub fn footer_rule(mut self) -> Self {
|
||||
if let Some(footer) = self.props.footer {
|
||||
self.props = self.props.footer(footer.rule(true));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The least width of the stack's content from the size role `least`: a stack sized from its content is at least
|
||||
/// that wide (a page's side menu, `LeastWidth::SideMenu`), and wider content still widens it.
|
||||
#[must_use]
|
||||
|
||||
@@ -511,7 +511,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
|
||||
/// the picture plus what the tile adds around it in every tiling.
|
||||
fn laid_out(&self, previous: Option<GridLayout>, source: &dyn ItemSource<K>, width: f32, item: Option<Vec2>, cx: &StyleCx<'_>) -> GridLayout {
|
||||
let style = GridSizes::of(cx, self.card, self.card_text, self.items.row_height, self.regular_card_padding, self.action_place);
|
||||
let spacing = style.spacing(self.caption);
|
||||
let spacing = style.spacing(self.caption).ruled(self.group_heads == GroupHeads::Rule);
|
||||
let around = style.around.get(self.caption, self.detail_line);
|
||||
// A card never outgrows the grid: in a column narrower than a card the card takes the column.
|
||||
let mut side = self.picture_side(&style, item, around).min(width - 2.0 * spacing.inset - around.size().x).max(1.0);
|
||||
@@ -532,6 +532,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
|
||||
justified: self.justified,
|
||||
around,
|
||||
group_header: spacing.group_header,
|
||||
ruled: spacing.ruled,
|
||||
groups: groups.iter().map(|group| (group.start, group.count, group.open)).collect(),
|
||||
tail: (self.tail.len(), tail_height),
|
||||
});
|
||||
|
||||
@@ -369,12 +369,21 @@ pub struct ArrangeSpacing {
|
||||
pub inset: f32,
|
||||
/// A group header's height.
|
||||
pub group_header: f32,
|
||||
/// The group headers are dividers (`GroupHeads::Rule`): a header that opens the grid draws nothing, so it takes no
|
||||
/// height and the first tiles keep the inset at the top.
|
||||
pub ruled: bool,
|
||||
}
|
||||
|
||||
impl ArrangeSpacing {
|
||||
/// Spacing of `gap` between tiles, `inset` around the content and headers `group_header` high.
|
||||
pub fn new(gap: f32, inset: f32, group_header: f32) -> Self {
|
||||
ArrangeSpacing { gap, inset, group_header }
|
||||
ArrangeSpacing { gap, inset, group_header, ruled: false }
|
||||
}
|
||||
|
||||
/// The spacing with group headers that are dividers when `ruled`.
|
||||
#[must_use]
|
||||
pub fn ruled(self, ruled: bool) -> Self {
|
||||
ArrangeSpacing { ruled, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -401,11 +410,12 @@ pub fn aspects_of<K>(source: &dyn ItemSource<K>) -> Vec<f32> {
|
||||
/// - `groups` are in display order and cover only the tiles they name; tiles outside every group sit in rows
|
||||
/// without a header. A closed group has its header only.
|
||||
/// - `inset` pads the sides and the bottom, and the top unless a group header opens the grid: that header sits at
|
||||
/// the top edge.
|
||||
/// the top edge. A divider header (`ArrangeSpacing::ruled`) that opens the grid takes no height, and the inset pads
|
||||
/// the top.
|
||||
pub fn arrange<K>(aspects: &[f32], groups: &[TileGroup<K>], width: f32, tiling: Tiling, spacing: ArrangeSpacing, around: Around) -> TileArrangement {
|
||||
let sanitized: Vec<f32> = aspects.iter().map(|a| if a.is_finite() && *a > 0.0 { *a } else { 1.0 }).collect();
|
||||
let n = sanitized.len();
|
||||
let ArrangeSpacing { gap, inset, group_header } = spacing;
|
||||
let ArrangeSpacing { gap, inset, group_header, ruled } = spacing;
|
||||
let content = (width - 2.0 * inset).max(1.0);
|
||||
let mut out = TileArrangement { tiles: vec![Rect::NOTHING; n], ..TileArrangement::default() };
|
||||
|
||||
@@ -424,17 +434,21 @@ pub fn arrange<K>(aspects: &[f32], groups: &[TileGroup<K>], width: f32, tiling:
|
||||
}
|
||||
out.starts = spans.iter().map(|span| span.start).collect();
|
||||
|
||||
// A leading group header sits at the top edge, as the old grids put it; tiles that open the grid keep the inset.
|
||||
let mut y = if segments.first().is_some_and(|(group, _)| group.is_some()) { 0.0 } else { inset };
|
||||
// A leading group header sits at the top edge, as the old grids put it; tiles that open the grid keep the inset,
|
||||
// and so do those under a leading divider, which draws nothing and takes no height.
|
||||
let leading = segments.first().is_some_and(|(group, _)| group.is_some());
|
||||
let mut y = if leading && !ruled { 0.0 } else { inset };
|
||||
let mut started = false;
|
||||
for (group, range) in segments {
|
||||
let first = !started;
|
||||
if started {
|
||||
y += gap;
|
||||
}
|
||||
started = true;
|
||||
if let Some(index) = group {
|
||||
out.headers.push(Rect::from_min_size(pos2(inset, y), vec2(content, group_header)));
|
||||
y += group_header;
|
||||
let height = if first && ruled { 0.0 } else { group_header };
|
||||
out.headers.push(Rect::from_min_size(pos2(inset, y), vec2(content, height)));
|
||||
y += height;
|
||||
if !groups[index].open {
|
||||
continue;
|
||||
}
|
||||
@@ -524,6 +538,8 @@ pub(super) struct Recipe {
|
||||
pub(super) around: Around,
|
||||
/// A group header's height.
|
||||
pub(super) group_header: f32,
|
||||
/// The group headers are dividers.
|
||||
pub(super) ruled: bool,
|
||||
/// Each group's first tile, count and open state.
|
||||
pub(super) groups: Vec<(usize, usize, bool)>,
|
||||
/// How many tail rows follow, and their height.
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Check boxes inside a field: the field's label names the control its body holds directly, and the check boxes of a
|
||||
//! row inside the field show their own labels.
|
||||
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::Vec2;
|
||||
|
||||
const CREATE: &str = "Create";
|
||||
const FILLS: &str = "Fills";
|
||||
const STROKES: &str = "Strokes";
|
||||
const SNAP: &str = "Snap";
|
||||
|
||||
/// A field holding a row of two labelled check boxes paints the field's label and both check boxes' labels. A field
|
||||
/// holding one labelled check box directly paints only the field's label, which names it.
|
||||
#[trial]
|
||||
fn check_boxes_in_a_row_inside_a_field_show_their_labels() {
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
Field::new(CREATE).id_salt("create").show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Checkbox::new(Bind::given(true)).label(FILLS).id_salt("fills").show(ui);
|
||||
Checkbox::new(Bind::given(false)).label(STROKES).id_salt("strokes").show(ui);
|
||||
});
|
||||
});
|
||||
Field::new(SNAP).id_salt("snap").show(ui, |ui, _| {
|
||||
Checkbox::new(Bind::given(true)).label("Snap to grid").id_salt("snap box").show(ui);
|
||||
});
|
||||
});
|
||||
fixture.room(Vec2::new(400.0, 300.0));
|
||||
fixture.settle();
|
||||
let texts = fixture.texts();
|
||||
let painted = |text: &str| texts.iter().any(|run| run.text == text);
|
||||
for text in [CREATE, FILLS, STROKES, SNAP] {
|
||||
assert!(painted(text), "{text:?} is painted: {texts:?}");
|
||||
}
|
||||
assert!(!painted("Snap to grid"), "the field's label names the check box its body holds directly: {texts:?}");
|
||||
}
|
||||
@@ -5,6 +5,7 @@ pub(crate) mod align;
|
||||
pub(crate) mod baseline;
|
||||
pub(crate) mod bracket;
|
||||
pub(crate) mod caption;
|
||||
pub(crate) mod field_row;
|
||||
pub mod group;
|
||||
pub(crate) mod hit;
|
||||
pub(crate) mod inside;
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::{Radio, RadioGroup};
|
||||
use craft_ui::contract::{Bind, FieldLayout, Gap, LeastWidth, Pad, Props as _, Scroll, Show as _, ShowContainer as _, SideLabel, Sizing, WrapWidth};
|
||||
use craft_ui::contract::{
|
||||
Bind, FieldLayout, Gap, LeastWidth, Pad, Props as _, RowAlign, Scroll, Show as _, ShowContainer as _, SideLabel, Sizing, WrapWidth,
|
||||
};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
@@ -191,6 +193,83 @@ fn labelled_radios_in_a_wrapping_row_break_onto_a_new_line() {
|
||||
assert!(starts >= 2, "a radio that wraps starts its line at the row's start edge: {starts} radios do");
|
||||
}
|
||||
|
||||
/// A wrapping `SpaceBetween` row that fills a stack its least width makes wider than its wrap width, and whose children
|
||||
/// fit one line, spreads them over the wrap width, the line length it wraps them at. Without a wrap width it spreads
|
||||
/// them over the whole stack.
|
||||
#[trial]
|
||||
fn a_spread_wrapping_row_keeps_to_the_stacks_wrap_width() {
|
||||
use craft_ui::runtime::env::Env;
|
||||
let shown = |wrap_width: bool| {
|
||||
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING, Rect::NOTHING, 0.0)));
|
||||
let out = Rc::clone(&seen);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let (first, last, wrap) = (Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING), Cell::new(0.0));
|
||||
let stack = Stack::new().least_width(LeastWidth::WideDialog);
|
||||
let stack = if wrap_width { stack.wrap_width(WrapWidth::Dialog) } else { stack };
|
||||
let shown = stack.show(ui, |ui, _| {
|
||||
wrap.set(WrapWidth::Dialog.points(Env::of(ui).tokens.tokens()));
|
||||
Row::new().wrap(true).align(RowAlign::SpaceBetween).sizing(Sizing::FillWidth).show(ui, |ui, _| {
|
||||
first.set(Button::new("Home").id_salt("home").show(ui).rect);
|
||||
last.set(Button::new("Next").id_salt("next").show(ui).rect);
|
||||
});
|
||||
});
|
||||
if !ui.is_sizing_pass() {
|
||||
out.set((shown.output.rect, first.get(), last.get(), wrap.get()));
|
||||
}
|
||||
});
|
||||
fixture.room(Vec2::new(1600.0, 600.0)).settle();
|
||||
seen.get()
|
||||
};
|
||||
let (stack, first, last, wrap) = shown(true);
|
||||
let dump = format!("stack {stack:?}, first {first:?}, last {last:?}, wrap width {wrap}");
|
||||
assert!(stack.width() > wrap + 1.0, "the least width makes the stack wider than its wrap width: {dump}");
|
||||
assert!((first.center().y - last.center().y).abs() < 1.0, "the children share one line: {dump}");
|
||||
assert!(last.max.x <= first.min.x + wrap + 0.5, "the last child ends within the wrap width: {dump}");
|
||||
assert!(last.max.x > first.min.x + wrap - 0.5, "the last child ends at the wrap width's end: {dump}");
|
||||
let (stack, first, last, _) = shown(false);
|
||||
let dump = format!("stack {stack:?}, first {first:?}, last {last:?}");
|
||||
assert!((first.center().y - last.center().y).abs() < 1.0, "without a wrap width the children share one line: {dump}");
|
||||
assert!((last.max.x - stack.max.x).abs() < 0.5, "without a wrap width the last child ends at the stack's end: {dump}");
|
||||
}
|
||||
|
||||
/// A wrapping `SpaceBetween` row whose children fit one line sets them on the line an unwrapped row sets them on, and
|
||||
/// takes that line's height: a nested row whose line is its first button's, above a column of two buttons beside it,
|
||||
/// stays inside the row and clear of the button below it.
|
||||
#[trial]
|
||||
fn a_spread_wrapping_row_keeps_a_child_whose_line_is_above_its_middle_inside_it() {
|
||||
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING, Rect::NOTHING, Rect::NOTHING)));
|
||||
let out = Rc::clone(&seen);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let (row, nested, next, below) = (Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING));
|
||||
let _ = Stack::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
let shown = Row::new().wrap(true).align(RowAlign::SpaceBetween).show(ui, |ui, _| {
|
||||
let shown = Row::new().show(ui, |ui, _| {
|
||||
let _ = Button::new("Home").id_salt("home").show(ui);
|
||||
let _ = Stack::new().show(ui, |ui, _| {
|
||||
let _ = Button::new("Up").id_salt("up").show(ui);
|
||||
let _ = Button::new("Down").id_salt("down").show(ui);
|
||||
});
|
||||
});
|
||||
nested.set(shown.output.rect);
|
||||
next.set(Button::new("Next").id_salt("next").show(ui).rect);
|
||||
});
|
||||
row.set(shown.output.rect);
|
||||
below.set(Button::new("Below").id_salt("below").show(ui).rect);
|
||||
});
|
||||
if !ui.is_sizing_pass() {
|
||||
out.set((row.get(), nested.get(), next.get(), below.get()));
|
||||
}
|
||||
});
|
||||
fixture.room(Vec2::new(800.0, 600.0)).settle();
|
||||
let (row, nested, next, below) = seen.get();
|
||||
let dump = format!("row {row:?}, nested row {nested:?}, next {next:?}, below {below:?}");
|
||||
assert!(nested.height() > next.height() * 1.5, "the nested row is two buttons tall: {dump}");
|
||||
assert!(next.min.x > nested.max.x, "the children share one line: {dump}");
|
||||
assert!(nested.max.y <= row.max.y + 0.5, "the nested row stays inside the row: {dump}");
|
||||
assert!(nested.max.y <= below.min.y + 0.5, "the nested row stays clear of the button below: {dump}");
|
||||
assert!((next.center().y - (nested.min.y + next.height() / 2.0)).abs() < 1.0, "the button sits on the nested row's line: {dump}");
|
||||
}
|
||||
|
||||
/// A body that scrolls keeps the bar's lane clear: a child that fills the width stops where the bar starts, not under it
|
||||
/// (a Print page's buttons ran under the settings column's bar).
|
||||
#[trial]
|
||||
|
||||
@@ -140,6 +140,92 @@ fn accessibility_click_respects_current_toggle_availability() {
|
||||
assert_eq!(seen.borrow().iter().filter(|event| matches!(event, CollectionEvent::Toggle(_))).count(), 1);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn accessibility_actions_respect_a_section_headings_availability() {
|
||||
use craft_behavior::{DisplayOrder, ItemSource};
|
||||
use craft_ui::testing::access::Declared;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use std::borrow::Cow;
|
||||
use std::cell::Cell;
|
||||
|
||||
const ROWS: [&str; 2] = ["Inks", "Cyan"];
|
||||
struct Source {
|
||||
heading_enabled: bool,
|
||||
}
|
||||
impl DisplayOrder<usize> for Source {
|
||||
fn len(&self) -> usize {
|
||||
ROWS.len()
|
||||
}
|
||||
fn key(&self, at: usize) -> usize {
|
||||
at
|
||||
}
|
||||
fn has_children(&self, at: usize) -> bool {
|
||||
at == 0
|
||||
}
|
||||
fn is_section(&self, at: usize) -> bool {
|
||||
at == 0
|
||||
}
|
||||
fn section_stop(&self, at: usize) -> bool {
|
||||
at == 0
|
||||
}
|
||||
fn section_stops_before(&self, at: usize) -> usize {
|
||||
usize::from(at > 0)
|
||||
}
|
||||
fn enabled(&self, at: usize) -> bool {
|
||||
at != 0 || self.heading_enabled
|
||||
}
|
||||
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
|
||||
Some(Cow::Borrowed(ROWS[at]))
|
||||
}
|
||||
}
|
||||
impl ItemSource<usize> for Source {}
|
||||
|
||||
let enabled = Rc::new(Cell::new((true, true)));
|
||||
let gates = enabled.clone();
|
||||
let seen = Rc::new(RefCell::new(Vec::new()));
|
||||
let held = seen.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let (list_enabled, heading_enabled) = gates.get();
|
||||
let source = Source { heading_enabled };
|
||||
let out = List::new("Plates").enabled(list_enabled).show_items(ui, &source, &mut |key, _| ListRow::new(ROWS[*key]));
|
||||
held.borrow_mut().extend(out.events);
|
||||
});
|
||||
let acted = |event: &CollectionEvent<usize, RowEvent>| {
|
||||
matches!(
|
||||
event,
|
||||
CollectionEvent::Activate(_) | CollectionEvent::Open(_) | CollectionEvent::Selection { .. } | CollectionEvent::LeadMoved { .. }
|
||||
)
|
||||
};
|
||||
for (list_enabled, heading_enabled, denied) in [(false, true, "disabled list"), (true, false, "disabled section")] {
|
||||
enabled.set((true, true));
|
||||
fixture.settle();
|
||||
let heading = fixture.by_label("Inks").expect("the heading");
|
||||
assert!(fixture.tree().declares_key(heading.node, Declared::Click));
|
||||
seen.borrow_mut().clear();
|
||||
enabled.set((list_enabled, heading_enabled));
|
||||
fixture.access(AccessActionKind::Click, &heading).settle();
|
||||
fixture.access(AccessActionKind::Expand, &heading).settle();
|
||||
assert!(!seen.borrow().iter().any(acted), "accessibility acted on the heading of a {denied}: {:?}", seen.borrow());
|
||||
let heading = fixture.by_label("Inks").expect("disabled heading remains visible to accessibility");
|
||||
assert!(!fixture.tree().declares_key(heading.node, Declared::Click), "the heading of a {denied} still offers accessibility Click");
|
||||
}
|
||||
enabled.set((true, true));
|
||||
fixture.settle();
|
||||
let row = fixture.by_label("Cyan").expect("the row");
|
||||
seen.borrow_mut().clear();
|
||||
enabled.set((false, true));
|
||||
fixture.access(AccessActionKind::Click, &row).settle();
|
||||
assert!(!seen.borrow().iter().any(acted), "accessibility acted on a row of a disabled list: {:?}", seen.borrow());
|
||||
enabled.set((true, true));
|
||||
fixture.settle();
|
||||
let heading = fixture.by_label("Inks").expect("the enabled heading");
|
||||
seen.borrow_mut().clear();
|
||||
fixture.access(AccessActionKind::Click, &heading).settle();
|
||||
fixture.access(AccessActionKind::Expand, &heading).settle();
|
||||
assert!(seen.borrow().iter().any(|event| matches!(event, CollectionEvent::Activate(0))), "Click activates the enabled heading");
|
||||
assert!(seen.borrow().iter().any(|event| matches!(event, CollectionEvent::Open(_))), "Expand opens the enabled heading");
|
||||
}
|
||||
|
||||
/// The rects of the three rows of a list shown with `rows`.
|
||||
fn row_rects(rows: RowHeight) -> Vec<egui::Rect> {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
@@ -2304,3 +2390,74 @@ fn tight_thumbnail_rows_stand_lower_and_indent_less() {
|
||||
assert!(tight_height < roomy_height, "the tight row ({tight_height}) is lower than the roomy one ({roomy_height})");
|
||||
assert!(0.0 < tight_indent && tight_indent < roomy_indent, "a level indents less ({tight_indent}) than an icon slot ({roomy_indent})");
|
||||
}
|
||||
|
||||
/// A section heading with children offers Expand while closed and Collapse while open, and neither while its list or
|
||||
/// its own row is disabled.
|
||||
#[trial]
|
||||
fn a_disabled_section_heading_offers_no_expand_or_collapse() {
|
||||
use craft_behavior::{DisplayOrder, ItemSource};
|
||||
use craft_ui::testing::access::Declared;
|
||||
use std::borrow::Cow;
|
||||
use std::cell::Cell;
|
||||
|
||||
const ROWS: [&str; 2] = ["Inks", "Cyan"];
|
||||
struct Source {
|
||||
heading_enabled: bool,
|
||||
open: bool,
|
||||
}
|
||||
impl DisplayOrder<usize> for Source {
|
||||
fn len(&self) -> usize {
|
||||
if self.open { ROWS.len() } else { 1 }
|
||||
}
|
||||
fn key(&self, at: usize) -> usize {
|
||||
at
|
||||
}
|
||||
fn has_children(&self, at: usize) -> bool {
|
||||
at == 0
|
||||
}
|
||||
fn open(&self, at: usize) -> bool {
|
||||
at == 0 && self.open
|
||||
}
|
||||
fn is_section(&self, at: usize) -> bool {
|
||||
at == 0
|
||||
}
|
||||
fn section_stop(&self, at: usize) -> bool {
|
||||
at == 0
|
||||
}
|
||||
fn section_stops_before(&self, at: usize) -> usize {
|
||||
usize::from(at > 0)
|
||||
}
|
||||
fn enabled(&self, at: usize) -> bool {
|
||||
at != 0 || self.heading_enabled
|
||||
}
|
||||
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
|
||||
Some(Cow::Borrowed(ROWS[at]))
|
||||
}
|
||||
}
|
||||
impl ItemSource<usize> for Source {}
|
||||
|
||||
let state = Rc::new(Cell::new((true, true, false)));
|
||||
let shown = state.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let (list_enabled, heading_enabled, open) = shown.get();
|
||||
let source = Source { heading_enabled, open };
|
||||
let _ = List::new("Plates").enabled(list_enabled).show_items(ui, &source, &mut |key, _| ListRow::new(ROWS[*key]));
|
||||
});
|
||||
for (open, offered, other) in [(false, Declared::Expand, Declared::Collapse), (true, Declared::Collapse, Declared::Expand)] {
|
||||
state.set((true, true, open));
|
||||
fixture.settle();
|
||||
let heading = fixture.by_label("Inks").expect("the heading");
|
||||
assert_eq!(fixture.tree().expanded_of(heading.node), Some(open), "the heading reports its open state");
|
||||
assert!(fixture.tree().declares_key(heading.node, offered), "an enabled heading offers {offered:?} (open: {open})");
|
||||
assert!(!fixture.tree().declares_key(heading.node, other), "an enabled heading offers no {other:?} (open: {open})");
|
||||
for (list_enabled, heading_enabled, denied) in [(false, true, "disabled list"), (true, false, "disabled section")] {
|
||||
state.set((list_enabled, heading_enabled, open));
|
||||
fixture.settle();
|
||||
let heading = fixture.by_label("Inks").expect("a disabled heading stays in the accessibility tree");
|
||||
assert_eq!(fixture.tree().expanded_of(heading.node), Some(open), "the heading of a {denied} still reports its open state");
|
||||
for action in [Declared::Expand, Declared::Collapse] {
|
||||
assert!(!fixture.tree().declares_key(heading.node, action), "the heading of a {denied} still offers {action:?} (open: {open})");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,8 @@ fn held_popup_retires(disabled: &'static str) {
|
||||
fixture.room(Room::Window.size()).settle();
|
||||
let trigger = *fixture.by_role(Role::COMBO_BOX).first().expect("the Select");
|
||||
fixture.click(&trigger).settle();
|
||||
assert_eq!(fixture.tree().with_role(Role::LIST_BOX_OPTION).len(), 12, "the twelve options are open before the owner is disabled");
|
||||
// The list ends on its last whole row, so the window shows the options that fit and scrolls the rest.
|
||||
assert!(!fixture.tree().with_role(Role::LIST_BOX_OPTION).is_empty(), "the options are open before the owner is disabled");
|
||||
let option = fixture.by_label("Two").expect("the real second option");
|
||||
fixture.press(&option);
|
||||
assert!(fixture.ctx().input(|input| input.pointer.primary_down()), "the real option press is still physically held");
|
||||
|
||||
@@ -14,6 +14,7 @@ use craft_ui::testing::input::{key_press, text};
|
||||
use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, trial};
|
||||
use egui::{Event, Key, Modifiers, Ui, Vec2};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A select over One to Four.
|
||||
@@ -335,6 +336,73 @@ fn the_wheel_steps_the_open_select_a_line_an_entry_and_commits_when_it_stops() {
|
||||
assert_eq!(*value.borrow(), 4);
|
||||
}
|
||||
|
||||
/// What an open list shows: the window, the select's field, the popup, the list, its option rows and
|
||||
/// `space.pad.regular`.
|
||||
struct OpenList {
|
||||
window: egui::Rect,
|
||||
field: egui::Rect,
|
||||
popup: egui::Rect,
|
||||
list: egui::Rect,
|
||||
rows: Vec<egui::Rect>,
|
||||
pad: f32,
|
||||
}
|
||||
|
||||
/// The open list of a long select in a short window, whose list may be wider than the window.
|
||||
fn opened_long_list(room: Vec2, list_width: Option<f32>) -> OpenList {
|
||||
use craft_ui::runtime::env::Env;
|
||||
let pad = Rc::new(Cell::new(0.0f32));
|
||||
let seen = Rc::clone(&pad);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
seen.set(Env::of(ui).tokens.tokens().space.pad.regular);
|
||||
let entries: Vec<Entry<u8>> = (0..60u8).map(|at| Entry::new(at, format!("Item {at}"))).collect();
|
||||
let select = Select::new("Pick", Bind::given(0u8), &entries);
|
||||
let _ = match list_width {
|
||||
Some(width) => select.list_width(width),
|
||||
None => select,
|
||||
}
|
||||
.show(ui);
|
||||
});
|
||||
fixture.room(room).settle();
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.key(Key::ArrowDown, Modifiers::ALT);
|
||||
fixture.settle();
|
||||
let window = fixture.ctx().content_rect();
|
||||
let field = fixture.by_role(Role::COMBO_BOX).first().expect("the select's field").rect;
|
||||
let list = fixture.by_role(Role::LIST_BOX).first().expect("Alt+Down opens the list").rect;
|
||||
let rows = fixture.by_role(Role::LIST_BOX_OPTION).into_iter().map(|row| row.rect).collect();
|
||||
let layers = craft_ui::testing::snapshot::layer_rects(fixture.ctx());
|
||||
let popup = layers.into_iter().find(|layer| layer.contains_rect(list)).expect("the list's popup layer");
|
||||
OpenList { window, field, popup, list, rows, pad: pad.get() }
|
||||
}
|
||||
|
||||
/// A popup that asks to be as wide as the window or wider keeps `space.pad.regular` off the window's edges, except
|
||||
/// where its field reaches nearer the edge than that.
|
||||
#[trial]
|
||||
fn a_long_list_keeps_a_margin_from_the_window_edges() {
|
||||
for (room, wide) in [(Vec2::new(900.0, 640.0), None), (Vec2::new(900.0, 640.0), Some(2000.0)), (Vec2::new(1000.0, 700.0), Some(1000.0))] {
|
||||
let OpenList { window, field, popup, pad, .. } = opened_long_list(room, wide);
|
||||
assert!(pad > 0.0, "the theme has a regular pad");
|
||||
let inside = window.shrink(pad).union(field);
|
||||
assert!(inside.expand(0.5).contains_rect(popup), "the popup {popup:?} in a {room:?} window keeps {pad} off its edges {window:?}");
|
||||
if wide.is_some() {
|
||||
assert!(popup.right() <= window.right() - pad + 0.5, "the wide popup {popup:?} keeps {pad} off the window's end edge {window:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A list too long for its popup ends on a whole row and scrolls the rest: no row is cut off at its bottom edge.
|
||||
#[trial]
|
||||
fn a_long_list_ends_on_a_whole_row() {
|
||||
for height in [640.0, 700.0, 733.0, 811.0, 917.0] {
|
||||
let OpenList { list, rows, .. } = opened_long_list(Vec2::new(900.0, height), None);
|
||||
assert!(rows.len() < 60 || rows.iter().any(|row| row.top() >= list.bottom()), "the list scrolls in a window {height} high");
|
||||
for row in rows.iter().filter(|row| row.top() < list.bottom() - 0.5 && row.bottom() > list.top() + 0.5) {
|
||||
let whole = row.top() >= list.top() - 0.5 && row.bottom() <= list.bottom() + 0.5;
|
||||
assert!(whole, "a row {row:?} is cut off by an end of the list {list:?} in a window {height} high");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry a long select holds.
|
||||
const HELD: u8 = 40;
|
||||
|
||||
|
||||
@@ -58,6 +58,38 @@ fn a_leading_group_header_sits_at_the_top_edge_and_ungrouped_tiles_keep_the_inse
|
||||
assert!((loose.rows[0].top - INSET).abs() < EPS, "tiles that open the grid keep the inset above them");
|
||||
}
|
||||
|
||||
/// A divider header that opens the grid takes no height: the first tiles sit the inset below the top edge. A divider
|
||||
/// between two groups keeps the header height.
|
||||
#[craft_ui::testing::trial]
|
||||
fn a_leading_divider_header_takes_no_height() {
|
||||
let aspects = [1.0; 6];
|
||||
let groups = [TileGroup::new(0usize, 0, 3, "Alpha"), TileGroup::new(1usize, 3, 3, "Beta")];
|
||||
let laid = arrange(&aspects, &groups, WIDTH, Tiling::justified(ROW), spacing().ruled(true), Around::default());
|
||||
assert!(laid.headers[0].height().abs() < EPS, "the leading divider takes no height: {:?}", laid.headers[0]);
|
||||
assert!((laid.rows[0].top - INSET).abs() < EPS, "the first tiles keep the inset above them: {:?}", laid.rows[0]);
|
||||
assert!((laid.headers[1].height() - HEADER).abs() < EPS, "a divider between groups keeps its height: {:?}", laid.headers[1]);
|
||||
}
|
||||
|
||||
/// In a grid with `GroupHeads::Rule`, the first tile sits as close to the grid's top as in a grid with no groups.
|
||||
#[craft_ui::testing::trial]
|
||||
fn a_rule_grid_starts_its_tiles_at_the_top() {
|
||||
let top = |ruled: bool| {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let keys: Vec<usize> = (0..6).collect();
|
||||
let source = keyed(&keys, |key: &usize| *key);
|
||||
let groups = [TileGroup::new(100usize, 0, 3, "Alpha"), TileGroup::new(101usize, 3, 3, "Beta")];
|
||||
let grid = TileGrid::new("Library");
|
||||
let grid = if ruled { grid.groups(&groups).group_heads(GroupHeads::Rule) } else { grid };
|
||||
let _ = grid.show_items(ui, &source, &mut |key, _| Tile::new(format!("Tile {}", key + 1)));
|
||||
});
|
||||
fixture.room(Vec2::new(600.0, 600.0));
|
||||
fixture.settle();
|
||||
fixture.by_label("Tile 1").expect("the first tile").rect.top()
|
||||
};
|
||||
let (ruled, plain) = (top(true), top(false));
|
||||
assert!((ruled - plain).abs() < 0.5, "the first tile of a rule grid sits at {ruled}, of a plain grid at {plain}");
|
||||
}
|
||||
|
||||
/// Under `GroupHeads::Rule` a head is a divider: it paints no title, a click on it reports no group event, and a group
|
||||
/// declared closed still shows its tiles; the group's title stays the heading's name.
|
||||
#[craft_ui::testing::trial]
|
||||
|
||||
Reference in new issue
Block a user