Merge pull request #2804 from aiongg/rework-d2

Menus, panels, options bar, Preferences: title bar, panel groups, context menus, Info, prefs labels
This commit is contained in:
aiongg authored and GitHub committed 2026-11-21 12:43:24 -05:00
commit fefaff4b05
50 files changed
+1478 -293

No files matched your search

Generated
+14 -14
View File
@@ -5450,7 +5450,7 @@ dependencies = [
[[package]]
name = "ecolor"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
dependencies = [
"bytemuck",
"emath",
@@ -5506,7 +5506,7 @@ dependencies = [
[[package]]
name = "eframe"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
dependencies = [
"ahash",
"bytemuck",
@@ -5541,7 +5541,7 @@ dependencies = [
[[package]]
name = "egui"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
dependencies = [
"accesskit",
"ahash",
@@ -5560,7 +5560,7 @@ dependencies = [
[[package]]
name = "egui-wgpu"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
dependencies = [
"ahash",
"bytemuck",
@@ -5579,7 +5579,7 @@ dependencies = [
[[package]]
name = "egui-winit"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
dependencies = [
"block2 0.6.2",
"bytemuck",
@@ -5599,7 +5599,7 @@ dependencies = [
[[package]]
name = "egui_glow"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
dependencies = [
"bytemuck",
"egui",
@@ -5612,7 +5612,7 @@ dependencies = [
[[package]]
name = "egui_kittest"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
dependencies = [
"eframe",
"egui",
@@ -5689,7 +5689,7 @@ dependencies = [
[[package]]
name = "emath"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
dependencies = [
"bytemuck",
]
@@ -5762,7 +5762,7 @@ dependencies = [
[[package]]
name = "epaint"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
dependencies = [
"ahash",
"bytemuck",
@@ -5788,7 +5788,7 @@ dependencies = [
[[package]]
name = "epaint_default_fonts"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
[[package]]
name = "equator"
@@ -15119,19 +15119,19 @@ dependencies = [
[[patch.unused]]
name = "egui_demo_lib"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
[[patch.unused]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
[[patch.unused]]
name = "egui_system_font_provider"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
+14 -14
View File
@@ -310,20 +310,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
linesweeper = { path = "vendor/linesweeper" }
vello_common = { path = "vendor/vello_common" }
vello_cpu = { path = "vendor/vello_cpu" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
emath = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
egui = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
emath = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
egui = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
+22 -3
View File
@@ -303,13 +303,18 @@ impl Codec for NumberCodec {
fn format(&self, v: &Option<f64>) -> String {
let Some(number) = v else { return String::new() };
let fixed = format!("{number:.*}", self.decimals);
let written = format!("{number:.*}", self.decimals);
// A value that rounds to zero at these decimals carries no sign.
let fixed = match written.strip_prefix('-') {
Some(digits) if digits.bytes().all(|byte| matches!(byte, b'0' | b'.')) => digits,
_ => &written,
};
let trimmed = if self.fixed {
&fixed
fixed
} else if fixed.contains('.') {
fixed.trim_end_matches('0').trim_end_matches('.')
} else {
&fixed
fixed
};
trimmed.replace('.', &self.reader.decimal_separator().to_string())
}
@@ -345,3 +350,17 @@ impl Codec for NumberCodec {
Cow::Borrowed(NUMBER_SAMPLE)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_value_that_rounds_to_zero_is_written_without_a_sign() {
let one = NumberCodec::new(Reader::new(), 1);
assert_eq!(one.format(&Some(-0.0)), "0");
assert_eq!(one.format(&Some(-0.04)), "0");
assert_eq!(one.format(&Some(-0.06)), "-0.1");
assert_eq!(NumberCodec::new(Reader::new(), 1).fixed().format(&Some(-0.04)), "0.0");
}
}
+6 -1
View File
@@ -93,6 +93,11 @@ pub struct Location<P> {
/// restoring creates a new group, column, dock or window for the panel.
#[serde(default)]
pub group: Option<GroupLocation>,
/// The panels of its group that closed in the same batch of actions, itself included, in group order; empty
/// when it closed alone. Reopening any of them brings back the others that are still hidden and were closed with
/// it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub closed_with: Vec<P>,
}
/// Groups, columns and floating windows are named by a panel they contain.
@@ -340,7 +345,7 @@ pub enum Action<P> {
impl<P> Location<P> {
/// A location relative to `anchor` by `placement`, with no recorded sizes or siblings.
pub fn new(anchor: Option<P>, placement: DockPlacement<P>) -> Self {
Self { floating: None, anchor, placement, size: None, stack: None, sibling: Vec::new(), group: None }
Self { floating: None, anchor, placement, size: None, stack: None, sibling: Vec::new(), group: None, closed_with: Vec::new() }
}
}
+1 -1
View File
@@ -554,7 +554,7 @@ pub(super) fn group_location<P: Clone + Eq>(panels: &[P], panel: &P) -> Option<L
let index = panels.iter().position(|p| p == panel)?;
let anchor = panels.iter().find(|p| *p != panel).cloned();
let before = panels.get(index + 1).cloned();
Some(Location { floating: None, anchor, placement: DockPlacement::Tab { before }, size: None, stack: None, sibling: Vec::new(), group: None })
Some(Location::new(anchor, DockPlacement::Tab { before }))
}
pub(super) fn first_panel<P>(node: &Node<P>) -> Option<&P> {
+90 -20
View File
@@ -12,7 +12,7 @@ use super::{
DockSide,
action::{Action, DockPlacement, Location},
edit::tree_panels,
groups::{Column, DockEdge, PanelPlace, Target},
groups::{Column, DockEdge, PanelPlace, Target, Unit},
layout::Layout,
limits::MAX_PANELS,
node::Node,
@@ -163,7 +163,7 @@ impl<P> Workspace<P> {
impl<P: Clone + Eq + Hash> Workspace<P> {
/// Check the version, the layout, that every hidden panel is hidden once and absent
/// from the layout, and that the floated records are bounded and one per panel.
/// from the layout and its record is bounded, and that the floated records are bounded and one per panel.
pub fn validate(&self) -> Result<(), DockError> {
if self.version > Self::VERSION {
return Err(DockError::UnsupportedVersion);
@@ -174,10 +174,13 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
}
let visible: HashSet<&P> = self.layout.panels().into_iter().collect();
let mut seen = HashSet::new();
for (panel, _) in &self.hidden {
for (panel, location) in &self.hidden {
if visible.contains(panel) || !seen.insert(panel) {
return Err(DockError::DuplicatePanel);
}
if location.closed_with.len() > MAX_PANELS {
return Err(DockError::LimitExceeded);
}
}
if self.floated.len() > MAX_PANELS {
return Err(DockError::LimitExceeded);
@@ -211,8 +214,11 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
let policy = |panel: &P| if locked { permissions(panel).locked() } else { permissions(panel) };
let mut proposed = self.clone();
let mut all_closed = Vec::new();
// The group of each panel as it closes, in closing order.
let mut closing_groups = Vec::new();
for action in actions {
let closed = proposed.layout.closed_by(&action)?;
closing_groups.extend(closed.iter().map(|panel| proposed.layout.members(panel, Unit::Group).unwrap_or_else(|_| vec![panel.clone()])));
let locations = close_locations(&proposed.layout, &closed);
let before = proposed.layout.clone();
// Opening a hidden panel puts it back where it was.
@@ -240,6 +246,7 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
proposed.hidden.retain(|(p, _)| !visible.contains(p));
let mut seen = HashSet::new();
all_closed.retain(|p| !visible.contains(p) && seen.insert(p.clone()));
proposed.record_closed_together(&all_closed, &closing_groups);
proposed.validate()?;
let Workspace { layout, hidden, floated, .. } = proposed;
(self.layout, self.hidden, self.floated) = (layout, hidden, floated);
@@ -248,10 +255,11 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
}
/// Show or hide one panel. Showing restores its recorded location, following the chain of
/// hidden anchors when its own anchor is hidden too; otherwise it opens as
/// [`Action::Open`] with `fallback` as the anchor, following `permissions`. The hidden
/// panels on that chain reopen beside it later, so a group or window closed one panel at a
/// time comes back as one.
/// hidden anchors when its own anchor is hidden too, and brings back the hidden panels of its
/// group that closed with it in one batch (Close Tab Group, a preset) as tabs of its group;
/// otherwise it opens as [`Action::Open`] with `fallback` as the anchor, following
/// `permissions`. The other hidden panels on that chain reopen beside it later, so a group or
/// window closed one panel at a time comes back as one.
/// A shown panel becomes the active tab of its group. Hiding follows `permissions` and
/// `locked`, as [`Self::apply`] does, so a protected canvas stays shown.
pub fn set_visible(
@@ -276,29 +284,91 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
self.apply_all([open, Action::Activate { panel }], locked, permissions).map(drop)
}
/// Restore a hidden `panel` to its recorded place and make it the active tab. `Ok(false)` when the record
/// cannot be restored, or the place it restores to refuses the panel under `permissions`; the workspace stays
/// as it was and the caller opens the panel by the ordinary, checked path.
/// Restore a hidden `panel` to its recorded place, with the hidden panels closed with it, and make it the
/// active tab. The set is restored in group order, each panel by its own record, so the group comes back in
/// the order it had; a panel closed with it whose place refuses it stays hidden. `Ok(false)` when `panel`'s
/// record cannot be restored, or the place it restores to refuses the panel under `permissions`; the workspace
/// stays as it was and the caller opens the panel by the ordinary, checked path.
fn reopen(&mut self, panel: &P, permissions: &impl Fn(&P) -> Permissions) -> Result<bool, DockError> {
// The restore also rewrites the records of the hidden panels it passed, so it runs on a copy.
let mut restored = self.clone();
for member in self.closed_together(panel) {
match restored.restored(&member, permissions) {
Some(next) => restored = next,
None if &member == panel => return Ok(false),
None => {}
}
}
restored.layout.apply(Action::Activate { panel: panel.clone() })?;
self.layout = restored.layout;
self.hidden = restored.hidden;
Ok(true)
}
/// The workspace with the hidden `panel` restored to its recorded place, `None` when the record cannot be
/// restored or the place refuses the panel under `permissions`. The restore also rewrites the records of the
/// hidden panels it passed, so it runs on a copy.
fn restored(&self, panel: &P, permissions: &impl Fn(&P) -> Permissions) -> Option<Self> {
let mut trial = self.clone();
let mut layout = self.layout.clone();
if trial.restore_from_hidden(&mut layout, panel).is_err() {
return Ok(false);
}
trial.restore_from_hidden(&mut layout, panel).ok()?;
let allowed = layout
.location(panel)
.ok()
.and_then(|location| location.anchor.map(|anchor| location.placement.allowed_by(permissions(&anchor))))
.unwrap_or(true);
if !allowed || layout.breaks_columns_beyond(&self.layout, permissions) {
return Ok(false);
return None;
}
trial.layout = layout;
trial.hidden.retain(|(p, _)| p != panel);
Some(trial)
}
/// The hidden `panel` and the hidden panels closed with it, in group order: those its record's
/// [`closed_with`](Location::closed_with) names whose own records name it back. A panel that closed again on
/// its own since names it no more. `[panel]` when it closed alone.
fn closed_together(&self, panel: &P) -> Vec<P> {
let record = |p: &P| self.hidden.iter().find(|(q, _)| q == p).map(|(_, location)| location);
let mut seen = HashSet::new();
let together: Vec<P> = record(panel)
.map(|location| &location.closed_with[..])
.unwrap_or_default()
.iter()
.filter(|&p| p == panel || record(p).is_some_and(|location| location.closed_with.contains(panel)))
.filter(|&p| seen.insert(p))
.cloned()
.collect();
if together.len() > 1 && together.contains(panel) { together } else { vec![panel.clone()] }
}
/// Records on the hidden panels `closed`, which this batch closed, the panels of their group that closed with
/// them. `groups` holds each closing panel's group as it closed, in closing order. The closed panels of one
/// group, or of groups that share one, form one set in the order the groups name them.
fn record_closed_together(&mut self, closed: &[P], groups: &[Vec<P>]) {
let closed: HashSet<&P> = closed.iter().collect();
let mut sets: Vec<Vec<P>> = Vec::new();
for group in groups {
let members: Vec<&P> = group.iter().filter(|p| closed.contains(p)).collect();
let (joined, rest): (Vec<Vec<P>>, Vec<Vec<P>>) =
std::mem::take(&mut sets).into_iter().partition(|set| set.iter().any(|p| members.contains(&p)));
let mut set: Vec<P> = joined.into_iter().flatten().collect();
for panel in members {
if !set.contains(panel) {
set.push(panel.clone());
}
}
sets = rest;
if !set.is_empty() {
sets.push(set);
}
}
for set in sets.into_iter().filter(|set| set.len() > 1) {
for (panel, location) in &mut self.hidden {
if set.contains(panel) {
location.closed_with.clone_from(&set);
}
}
}
layout.apply(Action::Activate { panel: panel.clone() })?;
self.layout = layout;
self.hidden = trial.hidden;
self.hidden.retain(|(p, _)| p != panel);
Ok(true)
}
/// Update the floated records after an action that turned `before` into the current layout: drop the records of
+35 -5
View File
@@ -97,6 +97,10 @@ pub struct PlaceRequest {
/// Beside the anchor, the overlay lines up with the anchor's other end when it runs past the bounds from the
/// aligned end and fits from the other, instead of sliding: a submenu of a low row opens upward.
pub flips_across: bool,
/// Below or above the anchor, an overlay that fits on neither side but fits the bounds keeps its height and slides
/// over the anchor from the preferred side; only one taller than the bounds is capped. For a context menu, whose
/// anchor is a point or a row.
pub covers_anchor: bool,
}
impl PlaceRequest {
@@ -113,6 +117,7 @@ impl PlaceRequest {
bounds,
kept: None,
flips_across: false,
covers_anchor: false,
}
}
@@ -163,6 +168,12 @@ impl PlaceRequest {
self.flips_across = on;
self
}
/// Below or above the anchor, slides over the anchor when the overlay fits neither side but fits the bounds.
pub const fn covers_anchor(mut self, on: bool) -> Self {
self.covers_anchor = on;
self
}
}
/// Where `place` put the overlay.
@@ -200,9 +211,10 @@ fn room(anchor: Rect, bounds: Rect, side: Side, rtl: bool, gap: f32) -> f32 {
}
/// Places an overlay: the preferred side unless the other has more room and the content does not fit, shifted to
/// stay inside the bounds, its height (or width, beside the anchor) capped to the room. Beside the anchor, a request that
/// flips across lines up with the anchor's other end when it runs past the bounds from the aligned end and fits from the
/// other. The rect is always finite and inside the bounds.
/// stay inside the bounds, its height (or width, beside the anchor) capped to the room. Below or above the anchor, a
/// request that covers its anchor and fits neither side keeps the preferred side and its height up to the bounds' and
/// slides over the anchor. Beside the anchor, a request that flips across lines up with the anchor's other end when it
/// runs past the bounds from the aligned end and fits from the other. The rect is always finite and inside the bounds.
pub fn place(request: &PlaceRequest) -> Placement {
let anchor = clean(request.anchor);
let bounds = clean(request.bounds);
@@ -213,12 +225,15 @@ pub fn place(request: &PlaceRequest) -> Placement {
let need = if request.side.vertical() { wanted.y } else { wanted.x };
let preferred = room(anchor, bounds, request.side, rtl, gap);
let other = room(anchor, bounds, request.side.flipped(), rtl, gap);
let covers = request.covers_anchor && request.side.vertical();
let side = match request.kept {
Some(kept) => kept,
None if preferred >= need || preferred >= other => request.side,
None if covers && other < need => request.side,
None => request.side.flipped(),
};
let available = room(anchor, bounds, side, rtl, gap).max(0.0);
// Covering the anchor, the overlay may take the bounds' height: the shift inside them moves it over the anchor.
let available = if covers { bounds.height() } else { room(anchor, bounds, side, rtl, gap).max(0.0) };
let size = if side.vertical() {
Vec2::new(wanted.x.min(bounds.width()), wanted.y.min(available).min(bounds.height()))
} else {
@@ -275,6 +290,20 @@ mod tests {
assert_eq!(neither.bottom(), BOUNDS.bottom(), "fits neither way: slides up to stay inside");
}
#[test]
fn a_menu_that_covers_its_anchor_and_fits_neither_side_keeps_its_height_and_slides_over_the_anchor() {
let point = rect(300.0, 400.0, 0.0, 0.0);
let request = PlaceRequest::new(point, Vec2::new(200.0, 450.0), BOUNDS).covers_anchor(true);
let placed = place(&request).rect;
assert_eq!(placed.height(), 450.0, "fits the bounds: its whole height");
assert!(BOUNDS.contains_rect(placed) && placed.top() < point.top(), "slides up over the point: {placed:?}");
assert_eq!(place(&request.size(Vec2::new(200.0, 700.0))).rect.height(), BOUNDS.height(), "taller than the bounds: capped");
let above = place(&request.size(Vec2::new(200.0, 350.0)));
assert!(above.side == Side::Above && above.rect.bottom() == point.top(), "fits above: opens above the point: {above:?}");
let without = place(&request.covers_anchor(false));
assert!(without.side == Side::Above && without.rect.height() < 450.0, "without it: capped to the larger side: {without:?}");
}
#[test]
fn an_overlay_at_least_as_wide_as_its_anchor_takes_that_width_below_it_but_not_beside_it() {
let field = rect(100.0, 100.0, 300.0, 24.0);
@@ -298,7 +327,8 @@ mod tests {
.side(side)
.align(align)
.rtl(i % 2 == 0)
.gap(if i == 1 { 4.0 } else { 0.0 });
.gap(if i == 1 { 4.0 } else { 0.0 })
.covers_anchor(align != Align::Start);
let placed = place(&request).rect;
assert!(placed.min.is_finite() && placed.max.is_finite(), "{request:?}");
assert!(BOUNDS.contains_rect(placed), "{request:?} gave {placed:?}");
+36
View File
@@ -188,6 +188,42 @@ fn opening_a_closed_floating_panel_restores_its_window_place() {
assert_eq!(group_members(workspace.layout(), 11), [11, 12, 50]);
}
/// The active tab of the dock or floating group holding `panel`.
fn front(layout: &Layout<u32>, panel: u32) -> u32 {
*layout.group(&layout.place(&panel).unwrap()).unwrap().active_panel().unwrap()
}
/// Tabs closed in one batch (one at a time, as a preset does, or by Close Tab Group) come back together with whichever
/// of them reopens, in their order and with that one in front, after a save and a load; a tab closed in a batch of its
/// own stays closed.
#[test]
fn tabs_closed_together_reopen_together_and_a_tab_closed_alone_stays_closed() {
let batches = [vec![Action::close(2), Action::close(3)], vec![Action::close(3), Action::close(2)], vec![Action::close_group(2)]];
for batch in batches {
for open in [2, 3] {
let mut workspace = Workspace::new(docked());
workspace.apply_all(batch.clone(), false, allow).unwrap();
let saved = serde_json::to_string(&workspace).unwrap();
let mut workspace: Workspace<u32> = serde_json::from_str(&saved).unwrap();
workspace.apply(Action::open(open, None), false, allow).unwrap();
let layout = workspace.layout();
assert_eq!(group_members(layout, open), [2, 3], "{batch:?}, then {open} opens");
assert_eq!(front(layout, open), open, "{batch:?}: the reopened tab is in front");
assert_eq!(end_dock(layout)[0].groups[0].panels, [2, 3], "{batch:?}: back above 4 in its column");
assert!(workspace.hidden().is_empty());
}
}
let mut workspace = Workspace::new(docked());
workspace.apply(Action::close(3), false, allow).unwrap();
workspace.apply(Action::close(2), false, allow).unwrap();
workspace.apply(Action::open(2, None), false, allow).unwrap();
assert_eq!(group_members(workspace.layout(), 2), [2]);
assert!(workspace.layout().place(&3).is_none(), "3 closed on its own stays closed");
workspace.apply(Action::open(3, None), false, allow).unwrap();
assert_eq!(group_members(workspace.layout(), 2), [2, 3], "it reopens beside 2");
}
/// A panel that floats keeps its docked place until it docks or closes; floating again from the float keeps the first.
#[test]
fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() {
+57 -51
View File
@@ -4,8 +4,10 @@ use craft_behavior::ColumnWidth;
use craft_cms::convert::CmykConverter;
use craft_theme::Srgba;
use craft_theme::variant::Tone;
use craft_ui::contract::{Outcome as _, Pattern, Props as _, Show as _, ShowContainer as _};
use craft_ui::display::Text;
use craft_ui::contract::{Gap, Outcome as _, Pattern, Props as _, Show as _, ShowContainer as _};
use craft_ui::display::{Divider, Text};
use craft_ui::form::{Field, FieldGroup};
use craft_ui::layout::{CellAlign, GridFit};
use craft_ui::layout_components::{Grid, Stack};
use craft_ui::notices::{Notice, NoticeLayout};
use craft_ui::runtime::env::{Env, Label};
@@ -19,9 +21,8 @@ pub(crate) mod stories;
/// What a missing value shows.
const DASH: &str = "–";
/// The grid's columns: a name and its value, twice, so that the two readouts of a line stand side by side and each
/// column lines up down the grid.
const COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content];
/// A block's two halves, equal in width.
const HALVES: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)];
craft_ui::words! {
/// The words of the Info panel, in the installed language unless set.
@@ -179,9 +180,10 @@ impl<'a> InfoReadings<'a> {
}
}
/// A read-only grid: RGB beside CMYK, the Ruler tool's measure (the angle A beside the length L, or a protractor's arms
/// L1 and L2 stacked beside it), X/Y beside W/H, the document size, then one row group per sampler; a dash for a
/// missing value; `document: None` shows "No document" as a centred notice in place of the grid.
/// A read-only panel of blocks, a rule between them, each block two equal halves of labelled readouts: RGB beside CMYK
/// (in percent), the Ruler tool's measure (the angle A beside the length L, or a protractor's arms L1 and L2 stacked
/// beside it), X/Y beside W/H, the document size, then a position block and a colour block per sampler; a dash for a
/// missing value; `document: None` shows "No document" as a centred notice in place of the blocks.
#[must_use = "show the panel with `show`"]
#[derive(Pattern)]
pub struct InfoPanel<'a> {
@@ -192,43 +194,38 @@ pub struct InfoPanel<'a> {
/// A name and its value, or `None` for a dash.
type Cell = (Label, Option<Label>);
/// One block: the readouts of its left and right halves.
type Block = [Vec<Cell>; 2];
/// The value of a number, or `None` when it is missing.
fn number(value: Option<impl ToString>) -> Option<Label> {
value.map(|value| Label::from(value.to_string()))
}
/// A name and its value in two grid cells, or two empty cells.
fn pair(ui: &mut Ui, cell: Option<Cell>) {
match cell {
Some((name, value)) => {
Text::new(name).show(ui);
Text::new(value.unwrap_or_else(|| Label::from(DASH))).show(ui);
}
None => {
Text::new(Label::from("")).show(ui);
Text::new(Label::from("")).show(ui);
}
}
/// The value of a CMYK percent, or `None` when it is missing.
fn percent(value: Option<u8>) -> Option<Label> {
value.map(|value| Label::from(format!("{value}%")))
}
/// A grid of lines, each two name and value pairs.
fn table(ui: &mut Ui, lines: Vec<[Option<Cell>; 2]>) {
let _ = Grid::new(&COLUMNS).show(ui, |ui, _| {
for [left, right] in lines.iter().cloned() {
pair(ui, left);
pair(ui, right);
/// A half of a block: its readouts as the fields of one form group, so the names carry their colons and share a
/// column and the values line up.
fn half(ui: &mut Ui, cells: &[Cell]) {
let _ = FieldGroup::new(Label::from("")).gap(Gap::Tight).show(ui, |ui, _| {
for (name, value) in cells {
let value = value.clone().unwrap_or_else(|| Label::from(DASH));
let _ = Field::new(name.clone()).value(value.as_str()).show(ui, |ui, _| {
Text::new(value.clone()).show(ui);
});
}
});
}
/// `cells` two to a line.
fn in_pairs(cells: Vec<Cell>) -> Vec<[Option<Cell>; 2]> {
let mut cells = cells.into_iter();
let mut lines = Vec::new();
while let Some(left) = cells.next() {
lines.push([Some(left), cells.next()]);
}
lines
/// A block: two equal halves, which stay beside each other in a narrow panel.
fn block(ui: &mut Ui, [left, right]: &Block) {
let _ = Grid::new(&HALVES).fit(GridFit::Fixed).cells(CellAlign::Top).show(ui, |ui, _| {
half(ui, left);
half(ui, right);
});
}
impl<'a> InfoPanel<'a> {
@@ -250,38 +247,47 @@ impl<'a> InfoPanel<'a> {
Stack::new()
.label(label)
.show(ui, |ui, _| {
let mut lines = Vec::new();
for (at, cmyk_name) in cmyk_names.iter().enumerate() {
let rgb = rgb_names.get(at).map(|rgb_name| (rgb_name.clone(), number(readings.color.map(|color| color.rgb[at]))));
lines.push([rgb, Some((cmyk_name.clone(), number(readings.color.map(|color| color.cmyk[at]))))]);
}
let color = readings.color;
let rgb = rgb_names.iter().enumerate().map(|(at, name)| (name.clone(), number(color.map(|color| color.rgb[at])))).collect();
let cmyk = cmyk_names.iter().enumerate().map(|(at, name)| (name.clone(), percent(color.map(|color| color.cmyk[at])))).collect();
let mut blocks = vec![[rgb, cmyk]];
match &readings.measure {
Some(InfoMeasure::Line { angle, length }) => {
lines.push([Some((name(&words.angle), Some(angle.clone()))), Some((name(&words.length), Some(length.clone())))]);
blocks.push([vec![(name(&words.angle), Some(angle.clone()))], vec![(name(&words.length), Some(length.clone()))]]);
}
Some(InfoMeasure::Protractor { angle, first, second }) => {
lines.push([Some((name(&words.angle), Some(angle.clone()))), Some((name(&words.length1), Some(first.clone())))]);
lines.push([None, Some((name(&words.length2), Some(second.clone())))]);
blocks.push([
vec![(name(&words.angle), Some(angle.clone()))],
vec![(name(&words.length1), Some(first.clone())), (name(&words.length2), Some(second.clone()))],
]);
}
None => {}
}
let (position, extent) = (readings.position.as_ref(), readings.extent.as_ref());
let axes = [(name(&words.x), name(&words.w)), (name(&words.pos_y), name(&words.h))];
let (mut at, mut size) = (Vec::new(), Vec::new());
for (axis, (position_name, extent_name)) in axes.into_iter().enumerate() {
lines.push([
Some((position_name, position.map(|at| at[axis].clone()))),
Some((extent_name, extent.map(|size| size[axis].clone()))),
]);
at.push((position_name, position.map(|at| at[axis].clone())));
size.push((extent_name, extent.map(|size| size[axis].clone())));
}
blocks.push([at, size]);
for (at, readings) in blocks.iter().enumerate() {
if at > 0 {
Divider::horizontal().show(ui);
}
block(ui, readings);
}
table(ui, lines);
let size = words.document.fill(&[("width", &width.to_string()), ("height", &height.to_string())]);
Divider::horizontal().show(ui);
Text::new(Label::from(size)).show(ui);
for (readout, position) in readings.samplers {
Divider::horizontal().show(ui);
Text::new(Label::from(format!("#{}", readout.number))).show(ui);
let mut lines = vec![[Some((name(&words.x), Some(position[0].clone()))), Some((name(&words.pos_y), Some(position[1].clone())))]];
lines.extend(in_pairs(rgb_names.iter().zip(readout.rgb).map(|(name, value)| (name.clone(), number(Some(value)))).collect()));
lines.extend(in_pairs(cmyk_names.iter().zip(readout.cmyk).map(|(name, value)| (name.clone(), number(Some(value)))).collect()));
table(ui, lines);
let place = [vec![(name(&words.x), Some(position[0].clone()))], vec![(name(&words.pos_y), Some(position[1].clone()))]];
let rgb = rgb_names.iter().zip(readout.rgb).map(|(name, value)| (name.clone(), number(Some(value)))).collect();
let cmyk = cmyk_names.iter().zip(readout.cmyk).map(|(name, value)| (name.clone(), percent(Some(value)))).collect();
block(ui, &place);
block(ui, &[rgb, cmyk]);
}
})
.output
+24
View File
@@ -421,6 +421,30 @@ fn measure_names(measure: Option<craft_color_ui::ui::InfoMeasure>) -> [bool; 4]
["A", "L", "L1", "L2"].map(|name| fixture.by_label(name).is_some())
}
/// The painted run whose text is `text`, without a colon.
fn run(fixture: &Fixture, text: &str) -> egui::Rect {
fixture.texts().iter().find(|run| run.text.trim_end_matches(':') == text).unwrap_or_else(|| panic!("no run \"{text}\"")).rect
}
#[trial]
fn the_info_panel_shows_rgb_and_cmyk_as_two_aligned_columns() {
let mut fixture = Fixture::new(|ui| {
let color = craft_color_ui::ui::InfoColor::from_parts([10, 200, 30], [1, 22, 33, 44]);
let readings = craft_color_ui::ui::InfoReadings::new().color(Some(color)).document(Some([640, 480]));
let _ = craft_color_ui::ui::InfoPanel::new("Info", &readings).show(ui);
});
fixture.settle();
let [r, g, b] = ["10", "200", "30"].map(|value| run(&fixture, value));
let [c, m, y, k] = ["1%", "22%", "33%", "44%"].map(|value| run(&fixture, value));
assert!(c.left() > r.right().max(g.right()).max(b.right()), "CMYK starts right of RGB: {r:?} {c:?}");
assert!(r.left() == g.left() && g.left() == b.left(), "the RGB values share a column");
assert!(c.left() == m.left() && m.left() == y.left() && y.left() == k.left(), "the CMYK values share a column");
let [rn, gn, bn] = ["R", "G", "B"].map(|name| run(&fixture, name));
assert!(rn.right() == gn.right() && gn.right() == bn.right(), "the RGB labels end at one x");
assert!(rn.right() < r.left(), "the labels sit left of their values");
assert!(fixture.texts().iter().any(|run| run.text == ":"), "a label carries its colon");
}
#[trial]
fn the_info_panel_shows_the_rulers_measure_while_it_has_one() {
use craft_color_ui::ui::InfoMeasure;
+1 -1
View File
@@ -3,7 +3,7 @@
/// The egui fork the library is built and tested with. Apps patch egui to exactly this.
pub const GIT: &str = "https://github.com/storytold/egui.git";
/// The commit of [`GIT`].
pub const REV: &str = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f";
pub const REV: &str = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1";
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
pub const PACKAGES: &[&str] = &[
+6 -2
View File
@@ -132,7 +132,9 @@ app translates. The dialog never opens a file dialog or touches the file system.
## Windows, Linux and web: the in-window bar
`MenuBarUi` draws a laid-out bar in a top panel and returns the titles' rect (`MenuBarOutput`).
`MenuBarUi` draws a laid-out bar and returns the titles' rect (`MenuBarOutput`). Show it inside a
`Stack` (a top panel's body) or the title bar's row: there the titles that don't fit its room fold
into "…".
Each item is a command row: its enabled state, check mark and chord follow the command in the
runtime's command state and keymap, and a choice is a `Fired` with `FireSource::Menu` in the
frame's output. `.help_search(true)` starts the Help menu with a search field over every command
@@ -141,7 +143,9 @@ frame's output. `.help_search(true)` starts the Help menu with a search field ov
```rust
let laid_out = craft_menu::layout(&menu_bar, Target::current(), &LayoutOptions::new("Sample")).bar;
egui::Panel::top("menu-bar").show(ui, |ui| {
MenuBarUi::new(&laid_out).keyboard(!dialog_open).help_search(true).show(ui);
Stack::new().show(ui, |ui, _| {
MenuBarUi::new(&laid_out).keyboard(!dialog_open).help_search(true).show(ui);
});
});
// The commands chosen arrive in `FrameOutput.fired`.
```
+2 -1
View File
@@ -65,7 +65,8 @@ pub struct MenuBarOutput {
pub titles: Rect,
}
/// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, in a top panel.
/// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, inside a `Stack` (a top
/// panel's body) or the title bar's row: there it folds the titles that don't fit its room into "…".
/// The commands chosen come back through the command queue, not from `show`.
///
/// The bar is a memoized view: while its model, options, place and environment are those of its last run and nothing
+1
View File
@@ -12,6 +12,7 @@ pub(crate) mod ribbon;
pub(crate) mod ribbon_gallery;
mod sample;
pub(crate) mod shortcuts;
pub(crate) mod title_bar;
craft_ui::registry!();
+133
View File
@@ -0,0 +1,133 @@
//! The in-window menu bar in an app's title bar: every title shows while the bar has room for them, the document title
//! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…". In a `Stack`
//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge.
use std::cell::Cell;
use std::rc::Rc;
use craft_host::target::{Os, WindowChrome};
use craft_menu::{CommandRef, MenuBar, MenuBarUi, Row, Target, from_items};
use craft_ui::contract::{Role, Show as _, ShowContainer as _, Tracked};
use craft_ui::display::Picture;
use craft_ui::layout_components::Stack;
use craft_ui::runtime::env::WindowKey;
use craft_ui::shell::{AppShell, Caption, CaptionFamily, Captions, Frame, Title, TitleBar};
use craft_ui::testing::{Fixture, trial};
use egui::vec2;
const MENUS: [&str; 10] = ["File", "Edit", "Image", "Layer", "Type", "Select", "Filter", "View", "Window", "Help"];
const PREFERRED: [(&str, char); 10] = [
("File", 'F'),
("Edit", 'E'),
("Image", 'I'),
("Layer", 'L'),
("Type", 'Y'),
("Select", 'S'),
("Filter", 'T'),
("View", 'V'),
("Window", 'W'),
("Help", 'H'),
];
const DOCUMENT: &str = "Untitled-1.psd";
fn model() -> Tracked<MenuBar> {
let rows: Vec<Row> = MENUS.iter().map(|menu| Row::new(&[menu], CommandRef::new(format!("{}.first", menu.to_lowercase())), "First")).collect();
Tracked::new(from_items(&MENUS, &rows))
}
fn brand() -> egui::ColorImage {
egui::ColorImage::filled([128, 128], egui::Color32::RED)
}
/// An app window `width` points wide at `pixels_per_point` whose frame the app draws (Windows), with the title bar as
/// PhotoCraft lays it out: a brand picture, the menu bar, then the document title, and the captions at the end.
fn window(width: f32, pixels_per_point: f32) -> Fixture {
let bar = Rc::new(model());
let mut fixture = Fixture::new(move |ui| {
let bar = Rc::clone(&bar);
AppShell::new(WindowKey::main())
.title_bar(move |ui, _, _: &mut ()| {
let bar = Rc::clone(&bar);
let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] };
TitleBar::new().frame(Frame::Integrated(Captions { family: CaptionFamily::Windows, layout })).show_titled(
ui,
Title::new(DOCUMENT),
move |ui, _| {
Picture::new("", 7, &brand).show(ui);
MenuBarUi::new(&bar).target(Target::Windows).mnemonics(&PREFERRED).help_search(true).show(ui);
},
|_, _| {},
);
})
.body(|ui, _, _| {
ui.label("Document");
})
.show(ui, &mut ());
});
fixture.os(Os::Windows).chrome(WindowChrome::Integrated).pixels_per_point(pixels_per_point).room(vec2(width, 600.0)).settle();
fixture
}
/// The bar's title nodes by name.
fn titles(fixture: &Fixture) -> Vec<String> {
let tree = fixture.tree();
fixture.by_role(Role::MENU_ITEM).iter().filter_map(|title| tree.name_of(title.node).map(str::to_owned)).collect()
}
/// Where `text` was painted, and whether it was cut.
fn painted(fixture: &Fixture, text: &str) -> Option<(egui::Rect, bool)> {
fixture.texts().iter().find(|run| run.text == text).map(|run| (run.rect, run.elided))
}
#[trial]
fn every_menu_title_and_the_document_title_show_in_a_wide_title_bar() {
for pixels_per_point in [1.0, 1.25] {
for width in [960.0, 1280.0, 1520.0] {
let fixture = window(width, pixels_per_point);
let at = format!("{width} pt at {pixels_per_point}x");
assert_eq!(titles(&fixture), MENUS, "{at} shows every title and no \"…\"");
let (help, _) = painted(&fixture, "Help").unwrap_or_else(|| panic!("{at}: Help is painted"));
let (title, cut) = painted(&fixture, DOCUMENT).unwrap_or_else(|| panic!("{at}: the document title is painted"));
assert!(title.left() > help.right(), "{at}: the document title {title:?} lies after Help {help:?}");
assert!(!cut, "{at}: the document title is whole");
}
}
}
#[trial]
fn a_narrow_title_bar_folds_the_last_menus_into_more() {
for pixels_per_point in [1.0, 1.25] {
let mut fixture = window(400.0, pixels_per_point);
let shown = titles(&fixture);
assert_eq!(shown.last().map(String::as_str), Some("…"), "{pixels_per_point}x: {shown:?}");
assert!(!shown.iter().any(|title| title == "Help"), "{pixels_per_point}x: Help is not a title: {shown:?}");
let more = fixture.by_label("…").expect("the \"…\" title");
fixture.click(&more).settle();
assert!(fixture.by_label("Help").is_some(), "{pixels_per_point}x: Help is a row of the \"…\" menu");
}
}
#[trial]
fn a_bar_in_a_stack_narrower_than_its_titles_folds_them_and_draws_nothing_past_its_edge() {
let bar = Rc::new(model());
let stack = Rc::new(Cell::new(egui::Rect::NOTHING));
let seen = Rc::clone(&stack);
let mut fixture = Fixture::new(move |ui| {
let bar = Rc::clone(&bar);
let shown = Stack::new().show(ui, |ui, _| {
MenuBarUi::new(&bar).target(Target::Windows).show(ui);
});
seen.set(shown.output.rect);
});
fixture.os(Os::Windows).room(vec2(240.0, 600.0)).settle();
let shown = titles(&fixture);
assert_eq!(shown.last().map(String::as_str), Some("…"), "{shown:?}");
assert!(!shown.iter().any(|title| title == "Help"), "Help is not a title: {shown:?}");
let edge = stack.get().right();
for run in fixture.texts().iter().filter(|run| MENUS.contains(&run.text.as_str()) || run.text == "…") {
assert!(run.rect.right() <= edge + 0.5, "{:?} at {:?} reaches past the stack's edge {edge}", run.text, run.rect);
}
let more = fixture.by_label("…").expect("the \"…\" title");
fixture.click(&more).settle();
assert!(fixture.by_label("Help").is_some(), "Help is a row of the \"…\" menu");
}
+3 -3
View File
@@ -8,8 +8,8 @@ use craft_theme::{ContrastChoice, ModeChoice, MotionChoice, Size, TextSize, Them
use craft_ui::choice::RadioGroup;
use craft_ui::contract::{Bind, Entry, Held, NoValue, Outcome, Props as _, Show as _, ShowContainer as _};
use craft_ui::display::Text;
use craft_ui::form::{Field, FieldGroup};
use craft_ui::layout_components::Row;
use craft_ui::form::Field;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::menu::Menu;
use craft_ui::pickers::Select;
use craft_ui::runtime::env::{Env, Label};
@@ -110,7 +110,7 @@ impl<'a> AppearancePage<'a> {
let mut held = Held::new(draft);
let mut toggled = None;
let mut changed = false;
let mut shown = FieldGroup::new(words.appearance.clone()).show(ui, |ui, cx| {
let mut shown = Stack::new().label(words.appearance.clone()).show(ui, |ui, cx| {
let before = held.read(cx).unwrap_or_default();
let mut now = before.clone();
let shown = now.applied_to(&suite.shown);
+8 -2
View File
@@ -5,6 +5,7 @@ use crate::{SelectionChange, SuiteClient};
use craft_theme::{ThemeId, builtins};
use craft_ui::choice::RadioGroup;
use craft_ui::contract::{Props as _, Show as _, ShowContainer as _};
use craft_ui::form::FieldGroup;
use craft_ui::layout_components::Row;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
@@ -18,13 +19,18 @@ fn favorites() -> Vec<ThemeId> {
fn appearance_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let client = SuiteClient::memory().view();
let favorites = favorites();
AppearancePage::new(&client, data.bind("draft", SelectionChange::default())).favorites(&favorites).show(ui).into()
let mut draft = data.bind("draft", SelectionChange::default());
FieldGroup::new("Appearance").show(ui, |ui, _| AppearancePage::new(&client, draft.reborrowed()).favorites(&favorites).show(ui)).output.into()
}
#[story(AppearancePage<'static>, covers = [], drive = Drive::Never)]
fn appearance_page_without_text_size(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let client = SuiteClient::memory().view();
AppearancePage::new(&client, data.bind("plain", SelectionChange::default())).text_size(false).system_dark(true).show(ui).into()
let mut draft = data.bind("plain", SelectionChange::default());
FieldGroup::new("Appearance")
.show(ui, |ui, _| AppearancePage::new(&client, draft.reborrowed()).text_size(false).system_dark(true).show(ui))
.output
.into()
}
/// One theme's chips in a group: plain, chosen, favourite, and both. A click on a star toggles the chip's favourite.
@@ -416,10 +416,15 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
layout_memory::measured(ctx, sub(id, "first")).map(|found| found.took.y)
}
/// A container with no header whose body is an unwrapped row reports that row's line as its first line.
/// A container with no header whose body is an unwrapped row reports that row's line as its first line, and one
/// labelled above its body the line of its body's first control: it sits on a row's line by that control, as a
/// control labelled above does.
fn first_is_row_line(&self, comp: &C) -> bool {
let props = comp.props(Internal::new());
props.header.is_none() && super::size::unwrapped_row(props)
let above = props.label.as_ref().is_some_and(|side| {
matches!(side.layout, label::FieldLayout::Above | label::FieldLayout::Caption(_)) && side.kind != label::LabelKind::Hidden
});
props.header.is_none() && (above || super::size::unwrapped_row(props))
}
fn member(&self, comp: &C) -> bool {
+133 -43
View File
@@ -110,55 +110,124 @@ impl LeafPlaced {
}
}
/// The label step for one leaf child: measures the child's narrowest width, runs the step in `row` with the
/// `trailing` content inside the label and returns the rect left for the child. The caller shows the child there and
/// then calls `LeafPlaced::finish`.
pub(crate) fn leaf<C: Show>(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option<Trailing<'_>>) -> LeafPlaced {
let scope = sub(at.id, "field");
let enabled = at.under.enabled;
/// The label step for one leaf child, decided: measures the child's narrowest width and decides where the label, with
/// content of `trailing` size inside it, and the child sit in `at.row`. Nothing shows and no room is taken; `show_leaf`
/// then shows the label where the row's place in flow puts it, and the caller shows the child at the control's rect
/// and calls `LeafPlaced::finish`.
pub(crate) fn decide_leaf<C: Show>(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Vec2) -> Decided {
// Read before the child measures: nothing it does there may count as a child placed in flow.
let in_column = in_column(ui);
let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), craft_behavior::Proposal::Min, Some(at.under)).x;
let input = LabelIn {
scope,
let facts = LeafFacts { control_min, in_column, claims: C::LABELLED_AFTER };
decide_step(ui, env, &leaf_input(env, at, at.row, facts, trailing))
}
/// Shows the label of a leaf child's step `decided` for `at`, moved down by `down`, with the `trailing` content inside
/// it, and returns the rect left for the child.
pub(crate) fn show_leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, decided: Decided, down: f32, trailing: Option<Trailing<'_>>) -> LeafPlaced {
let size = trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size);
let input = leaf_input(env, at, at.row.translate(Vec2::new(0.0, down)), decided.facts, size);
let placed = show(ui, env, &input, decided.moved(down), trailing);
LeafPlaced { control: placed.control, label: placed.label, scope: input.scope }
}
/// What a label step reads of its control before it decides.
#[derive(Clone, Copy)]
struct LeafFacts {
control_min: f32,
in_column: bool,
claims: bool,
}
/// The step's input for the leaf child of `at` in `row`, with content of `trailing` size inside the label.
fn leaf_input<'a>(env: &Env, at: &LeafLabel<'a>, row: Rect, facts: LeafFacts, trailing: Vec2) -> LabelIn<'a> {
LabelIn {
scope: sub(at.id, "field"),
owner: at.owner,
parent: at.parent,
row: at.row,
room: at.row.width(),
row,
room: row.width(),
content_row: env.content.0,
text: at.text,
side: at.side,
help: None,
enabled,
enabled: at.under.enabled,
size: at.under.size,
control_min,
control_min: facts.control_min,
leaf: true,
in_column,
claims: C::LABELLED_AFTER,
in_column: facts.in_column,
claims: facts.claims,
status: false,
trailing: trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size),
};
let placed = run(ui, env, &input, trailing);
LeafPlaced { control: placed.control, label: placed.label, scope }
trailing,
}
}
/// The label step for one leaf child in `at.row`, decided and shown where it was decided: returns the rect left for
/// the child. The caller shows the child there and then calls `LeafPlaced::finish`.
pub(crate) fn leaf<C: Show>(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option<Trailing<'_>>) -> LeafPlaced {
let decided = decide_leaf(ui, env, at, child, trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size));
show_leaf(ui, env, at, decided, 0.0, trailing)
}
/// Runs the label step in `ui`: shows the label and the `trailing` content inside it (`input.trailing` is its size),
/// opens the label scope and returns where the label and the control sit. The caller closes the scope with
/// `scope::finish` after the control ran.
pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option<Trailing<'_>>) -> Placed {
let decided = decide_step(ui, env, input);
show(ui, env, input, decided, trailing)
}
/// The label step decided for a row, before anything shows: where the label and the control sit, and the label leaf
/// measured in the child `Ui` it shows in.
pub(crate) struct Decided {
placed: Placed,
/// `None` for a label that shows no leaf.
leaf: Option<DecidedLeaf>,
/// What the step read of its control.
facts: LeafFacts,
}
struct DecidedLeaf {
leaf: LabelLeaf,
kids: Ui,
installed: crate::runtime::env::Installed,
reset: Option<scope::ResetFact>,
}
impl Decided {
/// The rect left for the control.
pub(crate) fn control(&self) -> Rect {
self.placed.control
}
/// The label's rect; `Rect::NOTHING` for a hidden label.
pub(crate) fn label(&self) -> Rect {
self.placed.label
}
/// The step moved down by `down`, as the row's place in flow moves it.
fn moved(mut self, down: f32) -> Self {
let by = Vec2::new(0.0, down);
self.placed.label = self.placed.label.translate(by);
self.placed.control = self.placed.control.translate(by);
self.placed.trailing = self.placed.trailing.translate(by);
self
}
}
/// Decides the label step for `input`: measures the label in the child `Ui` it shows in and places it and the control
/// in `input.row`. Nothing shows.
fn decide_step(ui: &mut Ui, env: &Env, input: &LabelIn<'_>) -> Decided {
let ctx = ui.ctx().clone();
let rtl = env.direction.is_rtl();
let tokens = &env.tokens;
let (gap, slot_side) = (label_gap(env), tokens.size.handle.sm);
let (gap, slot_side) = (label_gap(env), env.tokens.size.handle.sm);
let reset = scope::last_reset(&ctx, input.scope);
let flow = Flow::new(input.row, rtl);
let label_id = sub(input.scope, "label");
let content = input.trailing.x > 0.0;
let facts = LeafFacts { control_min: input.control_min, in_column: input.in_column, claims: input.claims };
if input.side.shows_no_leaf(content) {
scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(field_label(env, input, label_id, Rect::NOTHING)));
let control = hidden_control(&ctx, input, flow, gap);
scope::place_controls(&ctx, input.scope, control.top());
return Placed { label: Rect::NOTHING, control, trailing: Rect::NOTHING, caption: 0.0 };
return Decided { placed: Placed { label: Rect::NOTHING, control, trailing: Rect::NOTHING, caption: 0.0 }, leaf: None, facts };
}
let slot = if reset.is_some() && input.side.reset_dot { slot_side } else { 0.0 };
let mut leaf = LabelLeaf::new(input.side.kind.shown(input.text).clone(), slot);
@@ -192,24 +261,41 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option<
Some(parent) => access::with_parent(builder, parent),
None => builder,
};
let mut kids = alloc::child(ui, builder);
let kids = alloc::child(ui, builder);
let kid_env = crate::contract::cx::child_env(env, &Under::new(input.enabled, input.size));
let installed = Env::install_for(&kids, kid_env);
let glyph = leaf.glyph.is_some();
let mut placed = decide(&ctx, env, input, &kids, &mut leaf, glyph, flow);
// The label without its reset dot, which keeps its own press; the content sits at its end, on the first line.
let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot);
if input.trailing.x > 0.0 {
// The label without its reset dot, which keeps its own press; the content sits at its end, on the first line.
let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot);
let cell = unslotted.take_end(input.trailing.x).0;
let middle = cell.top() + leaf.first_line.get() / 2.0;
placed.trailing = Rect::from_min_size(egui::pos2(cell.min.x, middle - input.trailing.y / 2.0), input.trailing);
}
let label_id_for_scope = sub(input.scope, "label");
Decided { placed, leaf: Some(DecidedLeaf { leaf, kids, installed, reset }), facts }
}
/// Shows the label step `decided` for `input`: the label and the `trailing` content inside it, and opens the label
/// scope. Returns where the label and the control sit.
fn show(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, decided: Decided, trailing: Option<Trailing<'_>>) -> Placed {
let ctx = ui.ctx().clone();
let rtl = env.direction.is_rtl();
let label_id = sub(input.scope, "label");
let Decided { placed, leaf, .. } = decided;
let Some(DecidedLeaf { leaf, mut kids, installed, reset }) = leaf else {
scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(field_label(env, input, label_id, Rect::NOTHING)));
scope::place_controls(&ctx, input.scope, placed.control.top());
return placed;
};
let slot = if reset.is_some() && input.side.reset_dot { env.tokens.size.handle.sm } else { 0.0 };
// The label without its reset dot, which keeps its own press.
let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot);
// A label shows with the control it names: where a bar's view shows the two only in part, neither shows.
if crate::contract::run::cut_by_bar_view(env, placed.label.union(placed.control)) {
kids.set_clip_rect(Rect::NOTHING);
}
let shown = Props::id(leaf, label_id_for_scope).show_at(&mut kids, placed.label);
let shown = Props::id(leaf, label_id).show_at(&mut kids, placed.label);
Env::restore(&ctx, installed);
if let Some(fact) = reset.filter(|_| shown.double_click || shown.dot_click) {
keys::route_whole_reset(&ctx, fact.control);
@@ -219,8 +305,7 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option<
if let Some(trailing) = trailing {
(trailing.show)(ui, placed.trailing);
}
let label =
field_label(env, input, label_id_for_scope, placed.label).with_press(shown.press).with_hover(shown.hovered).activated(shown.activated);
let label = field_label(env, input, label_id, placed.label).with_press(shown.press).with_hover(shown.hovered).activated(shown.activated);
scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(label));
scope::place_controls(&ctx, input.scope, placed.control.top());
if input.claims {
@@ -302,28 +387,36 @@ fn flow_leaf_row<C: Show>(
region if in_cell => Rect::from_min_size(region.min, Vec2::new(flow.width(), region.height())),
_ => flow,
};
// The child's own height: a stacked label pushes the control down, and the allocation below follows the placement.
// The row spans the room's own edges: a room that scrolls along x is unbounded at its start edge, the left one
// under RTL.
// The label step decides where the label and the control sit at the flow's top, and the row then takes its place
// in flow as any other child does: its control's line is the row's line, on a row's or bracket's line, centred in a
// grid's cell or a horizontal layout. The row spans the room's own edges: a room that scrolls along x is unbounded
// at its start edge, the left one under RTL.
let row = Rect::from_min_max(avail.min, egui::pos2(avail.max.x, avail.min.y + ideal.y));
let at = LeafLabel { id, owner, parent: None, row, text: &label, side: &side, under: &under };
let placed = leaf(ui, &env, &at, &mut child, trailing);
let decided = decide_leaf(ui, &env, &at, &mut child, trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size));
// In a column that sizes from its content the row is the label plus the control, never the room around them.
// A row of a horizontal flow is as wide as its label and control: the room it has there is unbounded.
// So is a grid's cell: the room before it is the whole grid's, and a row spanning it measures its column as wide
// as the grid, so the grid could never set two such cells beside each other (two columns of check boxes).
let content = env.content.0 || ui.layout().is_horizontal() || in_cell;
let control_width = if content { placed.control.width().min(ideal.x) } else { placed.control.width() };
let control_width = if content { decided.control().width().min(ideal.x) } else { decided.control().width() };
let rtl = env.direction.is_rtl();
let cell = Rect::from_min_max(placed.control.min, egui::pos2(placed.control.max.x, placed.control.min.y + ideal.y));
let control = Flow::new(cell, rtl).span(0.0, control_width);
let span = |cell: Rect| Flow::new(Rect::from_min_size(cell.min, Vec2::new(cell.width(), ideal.y)), rtl).span(0.0, control_width);
let (decided_control, decided_label) = (span(decided.control()), decided.label());
let extent = if !content {
avail.width()
} else if rtl {
avail.max.x - control.min.x.min(placed.label.min.x)
avail.max.x - decided_control.min.x.min(decided_label.min.x)
} else {
control.max.x.max(placed.label.max.x) - avail.min.x
decided_control.max.x.max(decided_label.max.x) - avail.min.x
};
// The child's own height: a stacked label pushes the control down, and a label taller than the control reaches
// below it.
let height = (decided_control.bottom().max(decided_label.bottom()) - row.top()).max(ideal.y);
let first = decided_control.top() - row.top() + ideal.y / 2.0;
let took = crate::layout::place_in_cell(ui, Vec2::new(extent, height), crate::layout::InFlow { fill: false, first: Some(first), line: true });
let placed = show_leaf(ui, &env, &at, decided, took.top() - row.top(), trailing);
let control = span(placed.control);
// A control beside its label in a content-sized column reports how far it reaches past the label column, so
// the column's container measures its rows at the widest label.
if content && ui.is_sizing_pass() && side.layout == FieldLayout::Beside && placed.label.bottom() > placed.control.top() {
@@ -353,10 +446,7 @@ fn flow_leaf_row<C: Show>(
if let Some(installed) = installed {
Env::restore(ui.ctx(), installed);
}
let bottom = control.bottom().max(placed.label.bottom());
placed.finish(ui.ctx());
// The grid's cursor takes the row as its next cell (outside a grid, the next allocation of `ui`'s layout).
let _ = crate::layout::take_in_flow(ui, Vec2::new(extent, (bottom - row.top()).max(ideal.y)));
output
}
+33 -4
View File
@@ -3,7 +3,7 @@
use crate::layout::{flow_region, take_cell, take_in_flow};
use crate::runtime::egui::alloc;
use crate::runtime::env::Env;
use crate::runtime::env::{Env, Shrink};
use crate::runtime::focus;
use crate::runtime::layout_memory;
use crate::runtime::lazy::{self, Decision, Key, Place};
@@ -76,9 +76,19 @@ impl Lazy {
Some(view) => sub(view.owner, ("lazy", self.key)),
None => sub(ui.scope_id(), ("lazy", self.key)),
};
let available = flow_region(ui);
let available = if matches!(key, Key::Memo(_)) { on_row_line(ui, id, available) } else { available };
let rtl = ui.layout().prefer_right_to_left();
let memo = matches!(key, Key::Memo(_));
// A memoized view is one unit of the shrinking row around it. A row that narrows it gives it at most the width
// its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not
// narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a
// new content runs it once and the discard pass its new size asks for replays that run.
let shrink = Env::of(ui).shrink.filter(|_| memo);
let cap = match shrink {
Some(Shrink::Apply(row)) => crate::layout::shrink_cap(&ctx, row, id).filter(|cap| cap.narrowed),
_ => None,
};
let available = cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width));
let available = if memo { on_row_line(ui, id, available) } else { available };
let sizing = ui.is_sizing_pass();
// The child is not part of its body's transcript: in a real run it counts there by its extent, whether it
// runs or not, so what scrolls into reach does not change the body's content.
@@ -116,8 +126,8 @@ impl Lazy {
atlas: ctx.fonts(|fonts| fonts.atlas_generation()),
opacity: ui.opacity(),
env: Env::of(ui).key,
fits: Env::of(ui).view_fits(),
};
let memo = matches!(key, Key::Memo(_));
if real && memo {
crate::runtime::memory::claim_id(&ctx, id, "two memoized views share an id in one pass");
}
@@ -140,6 +150,7 @@ impl Lazy {
} else {
lazy::kept_output(&ctx, id)
};
report_unit(&ctx, shrink, id, rect.size());
#[cfg(feature = "testing")]
count_memo_run(&ctx, name, id, MemoRun::Replayed, real);
return Shown::Replayed(kept, shift);
@@ -177,6 +188,7 @@ impl Lazy {
}
if memo {
place_view(ui, rect);
report_unit(&ctx, shrink, id, rect.size());
} else {
crate::layout::close_flow_start_in(ui);
alloc::advance_past(ui, rect);
@@ -266,6 +278,23 @@ fn at_start(region: Rect, rtl: bool, size: Vec2) -> Pos2 {
Pos2::new(if rtl { region.max.x - size.x } else { region.min.x }, region.min.y)
}
/// `region` cut to `width` at most, from its start edge.
fn at_most(region: Rect, rtl: bool, width: f32) -> Rect {
let size = Vec2::new(width.min(region.width()), region.height());
Rect::from_min_size(at_start(region, rtl, size), size)
}
/// Reports the extent `size` of the memoized view `id` to the shrinking row around it: what it takes, in the row's
/// counting sweep, and its least, in the sweep that asks the row's body units for theirs. Like a body unit, it narrows
/// from what it takes in no room down to what it takes with every leaf at its least.
fn report_unit(ctx: &egui::Context, shrink: Option<Shrink>, id: egui::Id, size: Vec2) {
match shrink {
Some(Shrink::Count(row)) => crate::layout::report_shrink(ctx, row, id, size.x, size.x, None, false),
Some(Shrink::Least(row)) => crate::layout::report_least(ctx, row, id, size.x),
_ => {}
}
}
/// Places a memoized view's extent `rect` in flow in `ui`, as its run and its replay both do, and returns `rect`: in the
/// `Grid` or spread `Row` body that encloses `ui` directly the view takes the next cell at its extent, as its content
/// starts a layout room of its own and takes none; elsewhere the flow moves past `rect`.
+16 -6
View File
@@ -3,7 +3,7 @@
use super::lazy::{Lazy, Shown};
use super::memo::{MemoKey, MemoProps};
use crate::runtime::env::{Env, Scoped};
use crate::runtime::env::{Env, Scoped, Shrink};
use crate::runtime::shift::Shift;
use egui::Ui;
use std::fmt;
@@ -56,9 +56,13 @@ use std::sync::Arc;
/// - the clock, read through `frame::stepped_clock`: the view runs at the next step;
/// - commands sent to a command scope instance inside it: it runs while one waits.
///
/// Its content is a layout room of its own, as a pane's is: the flow of the body around it (a row's shrink, a column's
/// sweep, a grid's cursor) does not reach in, so the room it is given reaches it only through its place. To the body
/// around it the view is one unit, sized by its content's measure.
/// Its content is a layout room of its own, as a pane's is: the flow of the body around it (a column's sweep, a grid's
/// cursor) does not reach in, so the room it is given reaches it only through its place. To the body
/// around it the view is one unit, sized by its content's measure. In a shrinking `Row` it is a unit the row narrows
/// as it narrows a body unit: from what its content takes in no room down to what it takes with every leaf at its
/// least. When the row narrows it, the width the row gives it is the room of its place; otherwise it shows as in no
/// room, in the row's flow region. Its content sizes from its content along x, and its leaves fit the view's room, as
/// they fit the room of a `Stack` the view is shown in.
///
/// What `show` returns holds layout facts only (a size, a rect, which part took the room). A replay returns the kept
/// value again, moved with the record when the room moved (`Shift`), so an event returned through it would arrive once
@@ -107,12 +111,15 @@ impl<P: MemoProps, R: Clone + PartialEq + Shift + Send + Sync + 'static> MemoVie
pub fn show(self, ui: &mut Ui) -> Option<R> {
let MemoView { lazy, mut props, show } = self;
let ctx = ui.ctx().clone();
// In the counting sweep of a shrinking row the view reports what it takes in no room, as a leaf there does.
let counting = matches!(Env::of(ui).shrink, Some(Shrink::Count(_)));
let unbounded = counting.then(|| Env::install_for(ui, Env::of(ui).derive_local(|scoped| scoped.unbounded.0 = true)));
let env = Env::of(ui);
let key = Self::key(&ctx, &env, &props, show);
let shown = lazy.run_keyed(ui, std::any::type_name::<P>(), crate::runtime::lazy::Key::Memo(key), |ui, run| {
// The content is a layout room of its own: the flow of the body around it does not reach in. It keeps how
// that body sizes from its content, so the view takes what its content used there, as the same content
// shown without the view would.
// that body sizes from its content and whether its leaves fit their room (`Scoped::start_view_room`), so
// the view takes what its content used there, as the same content shown without the view would.
let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room));
let out = show(&mut props, ui);
Env::restore(&ctx, installed);
@@ -123,6 +130,9 @@ impl<P: MemoProps, R: Clone + PartialEq + Shift + Send + Sync + 'static> MemoVie
}
out
});
if let Some(installed) = unbounded {
Env::restore(&ctx, installed);
}
match shown {
Shown::Ran(out) => Some(out),
// A replay at another place moves what the run returned with its record.
@@ -3,7 +3,7 @@
use super::dismissal::{dismissal, popup_dismissal};
use super::opener::{Opening, Trigger};
use super::place::{OverlayFit, Place};
use super::placement::{anchor_rect, opened_overlay, placement};
use super::placement::{anchor_rect, layer_covers_anchor, opened_overlay, placement};
use super::props::{Outside, Overlay};
use crate::runtime::access::{self};
use crate::runtime::egui::areas::{self, LayerSpec};
@@ -134,6 +134,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
if let Some((_, opening)) = &opened {
memory.opening.get_or_insert(*opening);
}
let covers = layer_covers_anchor(ctx, layer.overlay, memory.opening);
let layer = &Layer { overlay: opened.as_ref().map_or(layer.overlay, |(overlay, _)| overlay), ..*layer };
let overlay = layer.overlay;
let bounds = layer.region.map_or_else(|| areas::safe_rect(ctx), |region| region.intersect(areas::safe_rect(ctx)));
@@ -155,7 +156,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
Some(size) => Some(egui::vec2(size.x.max(min_width), size.y)),
None => areas::layer_rect(ctx, area).map(|rect| rect.size()),
};
let mut placed = placement(ctx, layer, size, bounds, anchor);
let mut placed = placement(ctx, layer, covers, size, bounds, anchor);
let nudge = Nudge::of(ctx, layer, appears);
if let Some(nudge) = &nudge {
placed.at += nudge.offset();
@@ -287,6 +288,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut
if let Some((_, opening)) = &opened {
memory.opening.get_or_insert(*opening);
}
let covers = layer_covers_anchor(ctx, layer.overlay, memory.opening);
// The popup window lies outside any region of the opener: the work area is its room.
let layer = &Layer { overlay: opened.as_ref().map_or(layer.overlay, |(overlay, _)| overlay), region: None, ..*layer };
let overlay = layer.overlay;
@@ -294,7 +296,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut
let anchor = anchor_rect(ctx, layer, bounds, &mut memory);
let min_width = overlay.least_width(anchor.width());
let measured = layer.size.map(|size| egui::vec2(size.x.max(min_width), size.y));
let unplaced = placement(ctx, layer, measured, bounds, anchor);
let unplaced = placement(ctx, layer, covers, measured, bounds, anchor);
let parent = overlay::drawing_parent(ctx);
let tier = overlay::layer_tier(ctx, overlay.rank);
let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus);
@@ -314,7 +316,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut
shown = Some(show_in_popup(ui, layer, &unplaced, min_width, scope, &mut memory, &mut *body));
});
let (size, dismissed) = shown.unwrap_or((measured.unwrap_or_default(), None));
let placed = if known.is_some() { unplaced } else { placement(ctx, layer, Some(size), bounds, anchor) };
let placed = if known.is_some() { unplaced } else { placement(ctx, layer, covers, Some(size), bounds, anchor) };
let rect = Rect::from_min_size(placed.at, size);
if known.is_none() {
windows::place_popup(ctx, layer.id, rect.translate(popup.origin.to_vec2()));
@@ -8,6 +8,7 @@ use crate::runtime::egui::areas::{self};
use crate::runtime::env::Env;
use crate::runtime::memory::MemoryStage;
use crate::runtime::overlay::{self};
use craft_behavior::OwnerClass;
use craft_behavior::overlay::{PlaceRequest, Side};
use egui::{Context, Id, Pos2, Rect};
@@ -51,6 +52,31 @@ pub(super) fn opened_overlay(ctx: &Context, overlay: &Overlay, stored: Option<Op
Some((resolved, opening))
}
/// Whether a layer of `overlay` may cover its anchor when it fits on neither side of it: a menu's layer (its key class
/// is [`OwnerClass::Menu`]) hung at the pointer, at a point, or at the rect a context request named. No other overlay
/// covers its anchor: a tooltip or a popover at the pointer stays off it. `stored` is the opening the layer decided.
pub(super) fn layer_covers_anchor(ctx: &Context, overlay: &Overlay, stored: Option<Opening>) -> bool {
if overlay.keys != OwnerClass::Menu {
return false;
}
let (anchor, requested) = match &overlay.opener {
Some(first) => {
let (opener, opening) = first.active(ctx, stored);
(opener_anchor(opener, opening, &overlay.place), opener.anchor.is_none() && matches!(opening, Opening::At(_)))
}
None => match &overlay.place {
Place::Anchored { anchor, .. } => (anchor.clone(), false),
Place::Float(_) => return false,
},
};
match anchor {
Anchor::Pointer | Anchor::Point(_) => true,
// `opener_anchor` gives a requested rect only for a context request's opening.
Anchor::Rect(_) => requested,
_ => false,
}
}
/// The opening the layer `id` decided when it appeared, `None` before the host has run for it.
fn stored_opening(ctx: &Context, id: Id) -> Option<Opening> {
MemoryStage::peek::<LayerMemory>(ctx, memory_slot(id)).opening
@@ -172,7 +198,9 @@ pub(crate) fn measuring_room(
inset: f32,
rtl: bool,
) -> Option<egui::Vec2> {
let opened = opened_overlay(ctx, overlay, stored_opening(ctx, id));
let stored = stored_opening(ctx, id);
let covers = layer_covers_anchor(ctx, overlay, stored);
let opened = opened_overlay(ctx, overlay, stored);
let overlay = opened.as_ref().map_or(overlay, |(overlay, _)| overlay);
if !matches!(overlay.place, Place::Anchored { .. }) {
return None;
@@ -183,7 +211,7 @@ 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, bounds, kept_in(overlay, resolved, bounds, inset), anchor, rtl))
Some(content_room(overlay, covers, bounds, kept_in(overlay, resolved, bounds, inset), anchor, rtl))
}
/// 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
@@ -198,13 +226,13 @@ fn cap(overlay: &Overlay, bounds: Rect, anchor: Rect) -> egui::Vec2 {
}
/// The room a layer offers its content before it is placed: the cap (a share of the safe rect `bounds`), and for an
/// anchored layer the cap within the larger side of its anchor along the side's axis, inside `kept` (`kept_in`).
/// Content measured in it fits wherever `placement` puts it: on its preferred side when it fits there, else on the
/// larger side.
pub(crate) fn content_room(overlay: &Overlay, bounds: Rect, kept: Rect, anchor: Rect, rtl: bool) -> egui::Vec2 {
/// anchored layer the cap within the larger side of its anchor along the side's axis, inside `kept` (`kept_in`), or
/// within `kept` for a layer that `covers` its anchor. Content measured in it fits wherever `placement` puts it: on its
/// preferred side when it fits there, else on the larger side, or over the anchor.
pub(crate) fn content_room(overlay: &Overlay, covers: bool, bounds: Rect, kept: Rect, anchor: Rect, rtl: bool) -> egui::Vec2 {
let cap = cap(overlay, bounds, anchor);
let Place::Anchored { side, .. } = &overlay.place else { return cap.min(bounds.size()) };
let request = PlaceRequest::new(anchor, cap, kept).side(*side).rtl(rtl).min_width(overlay.min_width);
let request = PlaceRequest::new(anchor, cap, kept).side(*side).rtl(rtl).min_width(overlay.min_width).covers_anchor(covers);
let on = |side: Side| craft_behavior::overlay::place(&request.kept(Some(side))).rect.size();
let (vertical, other) = match side {
Side::Below => (true, Side::Above),
@@ -228,17 +256,18 @@ pub(super) struct Placed {
/// The pure placement of the anchored forms; the centre or the given position for floats, kept inside the safe rect
/// within the overlay's bounds (`within_bounds`) by the keep rule moves follow. An anchored layer takes its side by its
/// size: below its anchor, above when the room below is too short and the room above is larger, and keeps that side
/// while it stays open and the content fits there or that side is the larger. Before its size is known (a popup's
/// first, hidden pass) it takes no side and its body is offered `content_room`, so the size it measures decides the
/// side.
pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, size: Option<egui::Vec2>, bounds: Rect, anchor: Rect) -> Placed {
/// while it stays open and the content fits there or that side is the larger. A layer that `covers` its anchor
/// ([`layer_covers_anchor`]) and fits neither side keeps its height within the bounds and slides over the anchor.
/// Before its size is known (a popup's first, hidden pass) it takes no side and its body is offered `content_room`, so
/// the size it measures decides the side.
pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Option<egui::Vec2>, bounds: Rect, anchor: Rect) -> Placed {
let rtl = layer.env.direction.is_rtl();
let cap = cap(layer.overlay, bounds, anchor);
match &layer.overlay.place {
Place::Anchored { side, align, flips_across, .. } => {
let kept = layer_bounds(layer, bounds);
let Some(size) = size else {
let room = content_room(layer.overlay, bounds, kept, anchor, rtl);
let room = content_room(layer.overlay, covers, bounds, kept, anchor, rtl);
return Placed { at: anchor.left_bottom().clamp(kept.min, kept.max), side: None, room };
};
// The side taken in an earlier pass is the preferred one while the layer stays open: it stays while the
@@ -249,9 +278,11 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, size: Option<egui::Vec
.align(*align)
.rtl(rtl)
.min_width(layer.overlay.min_width)
.flips_across(*flips_across);
.flips_across(*flips_across)
.covers_anchor(covers);
let placed = craft_behavior::overlay::place(&request);
// The room is what the side the layer took leaves for a body as large as the cap.
// The room is what the side the layer took leaves for a body as large as the cap, or for a layer that covers
// its anchor, what the bounds leave.
let room = craft_behavior::overlay::place(&request.kept(Some(placed.side)).size(cap)).rect.size();
Placed { at: placed.rect.min, side: Some(placed.side), room }
}
+26 -11
View File
@@ -560,11 +560,18 @@ pub(crate) struct ShrinkCap {
pub width: f32,
/// The unit dropped out of the row (`shrink_or_drop`): it shows nothing and takes no place.
pub dropped: bool,
/// The row gave the unit less than it asks for in no room, or dropped it: what the unit shows depends on the row's
/// room. A unit the row did not narrow shows as in no room.
pub narrowed: bool,
}
/// What the shrink step of the row `row` gave its unit `leaf` in this pass's measuring run.
pub(crate) fn shrink_cap(ctx: &egui::Context, row: Id, leaf: Id) -> Option<ShrinkCap> {
layout_memory::shrink(ctx, shrink_key(row, leaf)).map(|(found, dropped)| ShrinkCap { width: found.took.x, dropped })
layout_memory::shrink(ctx, shrink_key(row, leaf)).map(|(found, given)| ShrinkCap {
width: found.took.x,
dropped: given.dropped,
narrowed: given.narrowed,
})
}
fn shrink_key(row: Id, leaf: Id) -> Id {
@@ -668,9 +675,13 @@ fn shrink_or_drop(
let shown_first: Vec<bool> = first.iter().zip(&kept).filter(|(_, kept)| **kept).map(|(first, _)| *first).collect();
let mut widths = shrink_in_turns(&shown, &pick(whole), &shown_first, fixed, room, order).into_iter();
kept.iter()
.map(|kept| match kept {
true => ShrinkCap { width: widths.next().unwrap_or_default(), dropped: false },
false => ShrinkCap { width: 0.0, dropped: true },
.zip(units)
.map(|(kept, unit)| match kept {
true => {
let width = widths.next().unwrap_or_default();
ShrinkCap { width, dropped: false, narrowed: unit.ideal - width >= 0.5 }
}
false => ShrinkCap { width: 0.0, dropped: true, narrowed: true },
})
.collect()
}
@@ -751,21 +762,23 @@ fn run_shrinking<R>(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) ->
let widths = if room.is_finite() {
shrink_or_drop(&units, &whole, &first, (fixed + held, gap), room, order, drops)
} else {
units.iter().map(|unit| ShrinkCap { width: unit.ideal, dropped: false }).collect()
units.iter().map(|unit| ShrinkCap { width: unit.ideal, dropped: false, narrowed: false }).collect()
};
// A levelled unit took no place of its own content in the first sweep (it measured each level apart), so the
// records its content's run leaves for the real run come from a sweep at the levels given.
let mut again = !levelled.is_empty();
for (leaf, cap) in continuous.iter().zip(widths) {
let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(cap.width, 0.0));
layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, cap.dropped);
let given = layout_memory::ShrinkGiven { dropped: cap.dropped, narrowed: cap.narrowed };
layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, given);
// Half a point: less than a pixel shows at any scale the box runs.
again |= (leaf.took - cap.width).abs() >= 0.5;
}
for (leaf, level) in levelled.iter().zip(levels) {
// The level travels as the record's height (`level_of`).
let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(width_at(leaf, level), level as f32));
layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, false);
let given = layout_memory::ShrinkGiven { dropped: false, narrowed: level > 0 };
layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, given);
}
again
};
@@ -1180,8 +1193,10 @@ pub(crate) struct InFlow {
/// rows run along Y, or a container whose first child is one. The child is one line when that centre lies at
/// half its height (`one_line`).
pub first: Option<f32>,
/// `first` is the line of the child's own unwrapped `Row` body: the child sits on a row's line by it even when it
/// is more than one line (a nested row with a child of two lines).
/// `first` is the line of the child's own unwrapped `Row` body, of the control of a labelled control's row, or of
/// the first control of a container labelled above its body: the child sits on a row's line by it even when it is
/// more than one line (a nested row with a child of two lines, a check box whose label has a detail line under it,
/// a control or a field under its label).
pub line: bool,
}
@@ -1190,8 +1205,8 @@ const ONE_LINE_SLACK: f32 = 0.5;
/// The centre of the line of a child `height` tall whose first line's centre lies `first` below its top, when the
/// child is one line: a control, a row of one-line children, a container around one line (a field with its label
/// beside its control). A child of more than one line (a column, a field with its label above or a help line below)
/// has its first line above its middle.
/// beside its control). A child of more than one line (a column, a field with a help line below) has its first line
/// above its middle.
fn one_line(first: Option<f32>, height: f32) -> Option<f32> {
first.filter(|first| (2.0 * first - height).abs() <= ONE_LINE_SLACK)
}
+27 -6
View File
@@ -409,14 +409,32 @@ impl Scoped {
self.offered = None;
}
/// Starts a memoized view's layout room (`start_room`), keeping whether the enclosing body is a content-sized or a
/// given column, as `start_room` keeps the content axes. The view's content then measures and fills as it would
/// shown without the view: a child that fills takes its measured size where the body sizes from content, never the
/// open room.
/// Starts the layout room of a memoized view's content (`start_room`), keeping whether the enclosing body is a
/// content-sized or a given column, as `start_room` keeps the content axes. The view's content then measures and
/// fills as it would shown without the view: a child that fills takes its measured size where the body sizes from
/// content, never the open room. Where a leaf shown here would fit its room (`view_fits`), the leaves of the view's
/// content fit the room the view is given (`Shrink::Fit`). A view that is a unit of a shrinking `Row` sizes from its
/// content along x, as the row counted it: a child that fills there takes its measured width, not the row's flow
/// region a view the row does not narrow is shown in.
pub(crate) fn start_view_room(&mut self) {
let fits = self.view_fits();
let row_unit = matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_)));
let (content_column, given_column) = (self.content_column, self.given_column);
self.start_room();
(self.content_column, self.given_column) = (content_column, given_column);
if fits {
self.shrink = Some(Shrink::Fit);
}
if row_unit {
self.content.0 = true;
}
}
/// Whether a memoized view shown in flow here fits its content to its room, as a leaf here would: in a `Stack` body,
/// whose leaves show at most its room, and as one of the units a shrinking `Row` narrows. In a `Grid` cell, a
/// wrapping `Row` or a `Ui` with no body around it a leaf keeps its measured width, and so does the view's content.
pub(crate) const fn view_fits(&self) -> bool {
matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_) | Shrink::Fit))
}
/// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its
@@ -691,9 +709,12 @@ impl Env {
Env { scoped: Arc::new(scoped) }
}
/// Reuse a sweep's scope while it is uniquely held. A captured child env keeps its snapshot.
/// Reuse a sweep's scope while it is uniquely held. A captured child env keeps its snapshot. The scope key is
/// computed again by the first view that asks after the edit.
pub(crate) fn local_mut(&mut self) -> &mut Scoped {
Arc::make_mut(&mut self.scoped)
let scoped = Arc::make_mut(&mut self.scoped);
scoped.scope_key = std::sync::OnceLock::new();
scoped
}
/// This env's container scope on top of `root`, the root env of the viewport the scope now runs in: the scale,
+18 -10
View File
@@ -97,8 +97,8 @@ pub(crate) type TakeBack = Box<dyn FnOnce(&Context) + Send + Sync>;
#[derive(Clone, Debug, PartialEq)]
enum Recorded {
Measured(Measured),
/// The width a row's shrink step gave a unit, as a measure, and whether the unit dropped out of the row.
Shrink(Measured, bool),
/// The width a row's shrink step gave a unit, as a measure, and whether it narrowed the unit or dropped it.
Shrink(Measured, ShrinkGiven),
Text(Option<Arc<str>>),
}
@@ -499,10 +499,18 @@ pub(crate) fn emit_record(ctx: &Context, id: Id, measured: Measured) {
emit(ctx, id, Recorded::Measured(measured));
}
/// Hands forward what a row's shrink step gave a unit under `id`: its width as `measured` and whether it `dropped`
/// out of the row. It serves as [`emit_record`]'s measure does.
pub(crate) fn emit_shrink(ctx: &Context, id: Id, measured: Measured, dropped: bool) {
emit(ctx, id, Recorded::Shrink(measured, dropped));
/// Whether a row's shrink step narrowed a unit below what it asks for in no room, and whether it dropped the unit out
/// of the row.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ShrinkGiven {
pub dropped: bool,
pub narrowed: bool,
}
/// Hands forward what a row's shrink step gave a unit under `id`: its width as `measured` and what else it `given`.
/// It serves as [`emit_record`]'s measure does.
pub(crate) fn emit_shrink(ctx: &Context, id: Id, measured: Measured, given: ShrinkGiven) {
emit(ctx, id, Recorded::Shrink(measured, given));
}
/// Hands forward a text a run found under `id` that content outside the body it runs in shows, as `emit_record`
@@ -565,7 +573,7 @@ fn kept_differs(last: &Found, now: &Recorded, pass: u64, tolerance: f32) -> Opti
};
let differs = match (was, now) {
(Recorded::Measured(was), Recorded::Measured(now)) => measures(was, now, false),
(Recorded::Shrink(was, was_dropped), Recorded::Shrink(now, now_dropped)) => measures(was, now, was_dropped != now_dropped),
(Recorded::Shrink(was, was_given), Recorded::Shrink(now, now_given)) => measures(was, now, was_given != now_given),
(was, now) => was != now,
};
if *at != pass || !differs {
@@ -922,12 +930,12 @@ pub(crate) fn measured(ctx: &Context, id: Id) -> Option<Measured> {
}
/// What a row's shrink step of this pass gave the unit under `id` ([`emit_shrink`]): its width as a measure and
/// whether it dropped out of the row.
pub(crate) fn shrink(ctx: &Context, id: Id) -> Option<(Measured, bool)> {
/// whether it narrowed or dropped the unit.
pub(crate) fn shrink(ctx: &Context, id: Id) -> Option<(Measured, ShrinkGiven)> {
let moment = Moment::of(ctx);
let pass = ctx.cumulative_pass_nr();
with(ctx, &moment, |memory| match memory.measured.get(&id).filter(|found| found.pass == pass && !memory.probing()) {
Some(Found { recorded: Recorded::Shrink(measured, dropped), .. }) => Some((*measured, *dropped)),
Some(Found { recorded: Recorded::Shrink(measured, given), .. }) => Some((*measured, *given)),
_ => None,
})
}
+25 -16
View File
@@ -166,8 +166,8 @@ pub(crate) struct Measured {
pub(crate) room: Rect,
}
/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity and environment, and
/// its record moves with the room's position (`Place::shift_to`).
/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity, fit and
/// environment, and its record moves with the room's position (`Place::shift_to`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Place {
/// The region its parent offered it.
@@ -185,6 +185,9 @@ pub(crate) struct Place {
/// The scope's environment (`Env::key`): its tokens (theme, density), scale, direction, language and whether the
/// window is active.
pub(crate) env: EnvKey,
/// Whether the leaves of the view's content fit the view's room, as in a `Stack` or a shrinking `Row`
/// (`Scoped::view_fits`).
pub(crate) fits: bool,
}
/// How a kept run replays at another place: the shift its record moves by, and whether the clip moved with the room.
@@ -196,9 +199,9 @@ struct Moved {
impl Place {
/// How a run at this place that took `rect` replays at `now`, or `None` when it cannot. The room may have moved; its
/// size, the layer, layout, scale, font atlas, opacity and environment are the ones the run had. A record that shows
/// an overlay replays only at the room and clip of its run (`Record::pinned`). Any other record moves by the room's move
/// when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there gives) and,
/// size, the layer, layout, scale, font atlas, opacity, fit and environment are the ones the run had. A record that
/// shows an overlay replays only at the room and clip of its run (`Record::pinned`). Any other record moves by the
/// room's move when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there gives) and,
/// for a move, the record holds nothing a move cannot place (`Record::movable`: no paint callback) on an
/// untransformed layer (`transformed`: egui's AccessKit bounds are layer space only there). Its clip rects follow
/// the clip when either:
@@ -216,7 +219,8 @@ impl Place {
&& now.pixels_per_point == self.pixels_per_point
&& now.atlas == self.atlas
&& now.opacity == self.opacity
&& now.env == self.env;
&& now.env == self.env
&& now.fits == self.fits;
let placeable = if record.pinned() {
offset == Vec2::ZERO && now.clip == self.clip
} else {
@@ -460,10 +464,12 @@ pub(crate) fn replay(ctx: &Context, id: Id) {
/// Whether the memoized view `id` adds its last real run to this pass in place of running, the extent that run took in
/// a run of this kind (`sizing`: the room a sizing run offers it, `None` outside a sizing pass), the rect the kept real
/// run takes now and the shift its record moves by. The first run of a pass decides from what changed since that run; a
/// real run also needs a `place` the run can move to (`Place::shift_to`), which a measuring run cannot tell. A sizing
/// run of a pass that replays takes the extent the last sizing run measured of the content the kept run showed (its
/// key) in the room it offers now; when that sizing run showed other content or had another room, or there was none, it
/// runs once as a measuring run, which keeps no record and leaves the decision of the pass alone, so the real run still
/// real run also needs a `place` the run can move to (`Place::shift_to`), which a measuring run cannot tell. Each call
/// also needs the key of the kept run: any other call with another key (a row's counting sweep shows the content
/// unbounded, and the scope key holds that) runs, and leaves the decision of the pass alone for the calls after it. A
/// sizing run of a pass that replays takes the extent the last sizing run measured of the content it shows (its key) in
/// the room it offers now; when that sizing run showed other content or had another room, or there was none, it runs
/// once as a measuring run, which keeps no record and leaves the decision of the pass alone, so the real run still
/// replays.
///
/// It replays when its last run was in an earlier pass, of this frame or an earlier one, and since then:
@@ -477,8 +483,8 @@ pub(crate) fn replay(ctx: &Context, id: Id) {
/// - no intent of this pass is routed to a component in it (an AccessKit request on one of its nodes);
/// - no value it read (a bound value, an inspection record, a command's state) changed this frame (`note_edit`), or,
/// replaying a run of this frame, after that run started;
/// - its key is the one of its last run (its props key after that run), and its environment (theme, density, scale,
/// language, window active) the one it ran in;
/// - the call's key is the one of its last run (its props key after that run), and its environment (theme, density,
/// scale, language, window active) the one it ran in;
/// - the run did nothing a replay cannot repeat (`runtime::replay`) and asked for no discard pass: what it added is
/// what the pass was thrown away for;
/// - the shown life of no component it showed ended (`memory::ended_since`): a replay would show memory state that is
@@ -506,6 +512,10 @@ pub(crate) fn settled(
// Usually `None`: only the values written this frame.
let edited = changes.edited_in(frame);
let entry = store.touch(owner, id, frame);
// The decision of the pass covers the kept run; the key is the call's own. A call that shows other content (a
// row's counting sweep, which shows it unbounded) leaves the decision alone for the calls after it: a sizing call
// takes the extent the last sizing run measured of its own content, and any other runs.
let keyed = entry.settled.as_ref().is_some_and(|settled| settled.key == key) || sizing.is_some();
let replays = match entry.replays {
Some((decided_in, replays)) if decided_in == pass_nr => replays,
_ => {
@@ -514,7 +524,6 @@ pub(crate) fn settled(
// A run of this frame read the values edited before it started.
let edited = edited_since(edited.as_ref(), if settled.frame < frame { 0 } else { settled.edits });
(settled.frame < frame || settled.pass < pass_nr)
&& settled.key == key
&& !settled.engaged
&& !facts.blocked
&& !facts.discards
@@ -533,14 +542,14 @@ pub(crate) fn settled(
Some(place) => settled.place.shift_to(settled.rect, place, &settled.record, transformed),
None => Some(Moved { shift: RecordShift::none(settled.place.clip), with_clip: true }),
};
let settled = entry.settled.clone().filter(|_| replays).and_then(|settled| Some((moved(&settled)?, settled)));
if replays && settled.is_none() {
let settled = entry.settled.clone().filter(|_| replays && keyed).and_then(|settled| Some((moved(&settled)?, settled)));
if replays && keyed && settled.is_none() {
entry.replays = Some((pass_nr, false));
}
settled.and_then(|(moved, settled)| {
// An extent depends on the room's size, not on where the room is.
let size = match sizing {
Some(room) => entry.sizes[0].filter(|measured| measured.key == settled.key && measured.room.size() == room.size())?.size,
Some(room) => entry.sizes[0].filter(|measured| measured.key == key && measured.room.size() == room.size())?.size,
None => entry.sizes[1].filter(|measured| measured.key == settled.key).map_or(settled.rect.size(), |measured| measured.size),
};
Some((size, moved, settled))
@@ -0,0 +1,59 @@
//! A memoized view that is one unit of a shrinking row: the row's counting sweep calls it with another key than its
//! real run, and that call leaves the replay decision of the pass to the calls after it and reuses its own measure.
use craft_ui::contract::{MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Sizing};
use craft_ui::layout::BodyLayout;
use craft_ui::testing::layout::in_region;
use craft_ui::testing::{Frames, MemoRun, last_frame_memo_runs, last_pass_memo_runs, trial};
use craft_ui_test_kit::contract::{Panel, Probe, Seen};
use egui::{Pos2, Rect, Ui, Vec2};
use std::cell::{Cell, RefCell};
/// A view that shows one probe `width` wide.
#[derive(MemoProps)]
struct Widened {
width: f32,
}
fn widened(props: &mut Widened, ui: &mut Ui) {
let seen = RefCell::new(Seen::default());
Probe::new(&seen).size(Vec2::new(props.width, 20.0)).id_salt("content").show(ui);
}
/// How the `Widened` views took part in `runs`.
fn of_view(runs: Vec<(&'static str, egui::Id, MemoRun)>) -> Vec<MemoRun> {
runs.into_iter().filter(|(name, _, _)| name.contains("Widened")).map(|(_, _, run)| run).collect()
}
/// A memoized view in a row that is not short, whose new content is wider: it runs once in the real run that meets the
/// new props and once as a measuring run in the row's counting sweep, whose call keys apart from the real run's
/// (the content shows unbounded there). The real run of the discard pass that sweep belongs to replays, and so does
/// every call of the next frame, a counting sweep's included.
#[trial]
fn a_memoized_row_unit_replays_after_the_rows_counting_call_with_another_key() {
let width = Cell::new(60.0);
let mut frames = Frames::new();
let frame = |frames: &mut Frames| {
frames.frame(vec![], |ui| {
in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(400.0, 40.0)), |ui| {
Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("row").show(ui, |ui, _| {
let _ = MemoView::new("view", Widened { width: width.get() }, widened).show(ui);
let seen = RefCell::new(Seen::default());
Probe::new(&seen).id_salt("after").show(ui);
});
});
});
};
for _ in 0..30 {
frame(&mut frames);
}
assert_eq!(of_view(last_frame_memo_runs(&frames.ctx)), [MemoRun::Replayed], "an idle frame replays the view");
width.set(90.0);
frame(&mut frames);
let calls = of_view(last_frame_memo_runs(&frames.ctx));
assert_eq!(calls.iter().filter(|run| **run == MemoRun::Ran).count(), 2, "one real run and one measuring run: {calls:?}");
assert_eq!(of_view(last_pass_memo_runs(&frames.ctx)), [MemoRun::Replayed], "the discard pass's real call replays: {calls:?}");
frame(&mut frames);
let calls = of_view(last_frame_memo_runs(&frames.ctx));
assert!(calls.iter().all(|run| *run == MemoRun::Replayed), "the next frame replays the view in every call: {calls:?}");
}
@@ -5,6 +5,7 @@ pub(crate) mod gesture;
pub(crate) mod hit_order;
pub(crate) mod level;
pub(crate) mod memo_key;
pub(crate) mod memo_row;
pub(crate) mod pages;
pub(crate) mod pointer;
pub(crate) mod style;
+75
View File
@@ -0,0 +1,75 @@
//! A run laid out in room equal to its own width.
use craft_behavior::Sense;
use craft_ui::contract::{Common, Component, Cx, MeasureCx, Props as _, Role, Show as _};
use craft_ui::primitives::{TextRun, Wrap};
use craft_ui::style::StyleCx;
use craft_ui::testing::{Fixture, trial};
use craft_ui_test_kit::contract::PlainStyle;
use egui::{Response, Vec2};
use std::cell::Cell;
use std::rc::Rc;
const WORDS: [&str; 9] = ["200", "100", "44%", "40%", "201", "45%", "Hello", "Width", "mm"];
/// Lays each word out unbounded and again in room equal to that width, and counts the words whose width is less than
/// half a point past a whole point: the widths a whole-point wrap width would round down.
#[derive(Component)]
struct OwnWidth {
#[common]
common: Common,
below_half: Rc<Cell<usize>>,
}
impl Component for OwnWidth {
const ROLE: Role = Role::GROUP;
type Style = PlainStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: OwnWidthStyleKey) -> PlainStyle {
PlainStyle::default()
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let mut below_half = 0;
for word in WORDS {
for wrap in [Wrap::Wrap, Wrap::Elide] {
let run = TextRun::new(word).wrap(wrap);
let whole = cx.layout_at(&run, f32::INFINITY);
let width = whole.size().x;
let fitted = cx.layout_at(&run, width);
assert_eq!(fitted.galley.rows.len(), 1, "{word:?} {wrap:?}");
assert!(!fitted.elided, "{word:?} {wrap:?}");
assert_eq!(fitted.size().x, width, "{word:?} {wrap:?}: room equal to its width keeps its width");
}
let width = cx.layout_at(&TextRun::new(word), f32::INFINITY).size().x;
if width.fract() > 0.0 && width.fract() < 0.5 {
below_half += 1;
}
}
self.below_half.set(below_half);
Vec2::ZERO
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
#[trial]
fn room_equal_to_its_width_keeps_a_word_whole() {
for pixels_per_point in [1.0, 2.0] {
let below_half = Rc::new(Cell::new(0));
let output = below_half.clone();
let mut fixture = Fixture::new(move |ui| {
OwnWidth { common: Common::new(), below_half: output.clone() }.id_salt("own-width").show(ui);
});
fixture.pixels_per_point(pixels_per_point);
fixture.frame(Vec::new());
assert!(below_half.get() > 0, "at {pixels_per_point}x some word must be less than half a point past a whole point");
}
}
+1
View File
@@ -1,3 +1,4 @@
pub(crate) mod band;
pub(crate) mod editor;
pub(crate) mod input_cap;
pub(crate) mod memo;
@@ -91,7 +91,7 @@ impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSet
(PrefValue::Int(n), Value::Float(_)) => Value::Float(clamp_float(n as f64)),
(PrefValue::Float(x), Value::Float(_)) if x.is_finite() => Value::Float(clamp_float(x)),
(PrefValue::Float(x), Value::Integer(_)) if x.is_finite() => Value::Integer(clamp_int(x.round() as i64)),
(PrefValue::Text(text), Value::String(_)) if matches!(kind, None | Some(RuleKind::Custom)) => Value::String(text),
(PrefValue::Text(text), Value::String(_)) if matches!(kind, None | Some(RuleKind::Custom | RuleKind::CustomRows)) => Value::String(text),
(PrefValue::Choice(id), Value::String(_) | Value::Integer(_)) => match kind {
Some(RuleKind::Choice(options)) if options.iter().any(|(option, _)| *option == id) => match id.parse::<i64>() {
Ok(n) if self.rules.get(key).is_some_and(|rule| rule.integer) => Value::Integer(n),
@@ -71,8 +71,10 @@ pub enum RuleKind {
Choice(Vec<(String, String)>),
/// A `#rrggbb` string as a swatch and hex field.
Color,
/// The app draws it ([`CustomSettings::row`]).
/// The app draws it ([`CustomSettings::row`]); the window labels it.
Custom,
/// The app draws whole rows, labels included ([`CustomSettings::row`]).
CustomRows,
}
impl SettingRule {
@@ -158,13 +160,21 @@ impl SettingRule {
self
}
/// The app draws the control ([`CustomSettings::row`]).
/// The app draws the control ([`CustomSettings::row`]); the window labels it beside the control.
#[must_use]
pub fn custom(mut self) -> Self {
self.kind = Some(RuleKind::Custom);
self
}
/// The app draws whole rows with their labels ([`CustomSettings::row`]): the window adds none. The rule's label
/// stays the row's search text and its group's name.
#[must_use]
pub fn custom_rows(mut self) -> Self {
self.kind = Some(RuleKind::CustomRows);
self
}
/// Shows the row only while the setting at `key` has `value`. Called again, the row shows only while every
/// condition holds.
#[must_use]
@@ -57,6 +57,7 @@ enum Shape {
Choice(Vec<(String, Label)>, Option<UnitKind>),
Color,
Custom,
CustomRows,
}
/// The range of a number without a rule.
@@ -65,8 +66,10 @@ pub(super) const OPEN_RANGE: f64 = 1e9;
fn shape_of(rule: Option<&SettingRule>, value: Option<&toml::Value>) -> Option<Shape> {
use toml::Value;
let kind = rule.and_then(|rule| rule.kind.as_ref());
if matches!(kind, Some(RuleKind::Custom)) {
return Some(Shape::Custom);
match kind {
Some(RuleKind::Custom) => return Some(Shape::Custom),
Some(RuleKind::CustomRows) => return Some(Shape::CustomRows),
_ => {}
}
Some(match (kind, value?) {
(Some(RuleKind::Choice(options)), Value::String(_) | Value::Integer(_)) => {
@@ -169,7 +172,7 @@ impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSet
let prefix = format!("{}.", page.id);
for (path, rule) in self.rules.range(prefix.clone()..).take_while(|(path, _)| path.starts_with(&prefix)) {
let key = &path[prefix.len()..];
if matches!(rule.kind, Some(RuleKind::Custom)) && !keys.iter().any(|k| k == key) {
if matches!(rule.kind, Some(RuleKind::Custom | RuleKind::CustomRows)) && !keys.iter().any(|k| k == key) {
keys.push(key.to_owned());
}
}
@@ -235,6 +238,7 @@ impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSet
(Shape::Choice(options, counted), Some(Value::String(id))) => choice_kind(options, *counted, id),
(Shape::Color, Some(Value::String(text))) => RowKind::Color(Rgba::from_hex(text).unwrap_or(Rgba::rgb(128, 128, 128))),
(Shape::Custom, _) => RowKind::Custom,
(Shape::CustomRows, _) => RowKind::CustomRows,
_ => return None,
};
let spec = RowSpec::new(&row.key, &row.label, kind).keywords(&row.keywords).visible(self.row_visible(&row.key));
@@ -102,8 +102,8 @@ pub struct RowSpec<'a> {
pub key: &'a str,
/// Translated; also the row's accessible name.
pub label: &'a str,
/// Extra search text: the key, the English label, synonyms. A [`RowKind::Custom`] row, which the search can't look
/// into, lists the terms of its control here.
/// Extra search text: the key, the English label, synonyms. A [`RowKind::Custom`] or [`RowKind::CustomRows`] row,
/// which the search can't look into, lists the terms of what the host draws here.
pub keywords: &'a str,
/// Help under the control: "Applies at next launch." A line break starts a new paragraph. The search matches it.
pub help: Option<&'a str>,
@@ -204,8 +204,12 @@ pub enum RowKind<'a> {
},
/// A text field.
Text(&'a str),
/// The host draws the control ([`PreferencesModel::custom_row`]).
/// The host draws the control ([`PreferencesModel::custom_row`]); the window labels it beside the control.
Custom,
/// The host draws whole rows, labels included ([`PreferencesModel::custom_row`]): the window adds no label, and
/// shows the row's help under them and its enabled state on them. The row's label stays its search text and its
/// group's name.
CustomRows,
}
impl<'a> RowKind<'a> {
@@ -298,7 +302,8 @@ pub trait PreferencesModel {
fn set_color(&mut self, key: &str, color: Srgba) {
self.set(key, PrefValue::Color(color.into()));
}
/// Draws a [`RowKind::Custom`] row's control.
/// Draws a [`RowKind::Custom`] row's control, which the window labels from the row's label (an empty label shows
/// an empty one), or a [`RowKind::CustomRows`] row's whole rows, labels included.
fn custom_row(&mut self, ui: &mut Ui, key: &str);
/// Draws a [`PageSpec::custom`] page.
fn custom_page(&mut self, ui: &mut Ui, page: &str);
@@ -284,21 +284,24 @@ fn show_page<H: PreferencesModel + ?Sized>(
} else if page.groups.is_empty() && !searching {
Notice::new(Tone::Info, words.empty_page.clone()).layout(NoticeLayout::Centred).show(ui);
}
for (at, group) in page.groups.iter().enumerate() {
let mut rows = |ui: &mut Ui| {
let name = group.title.clone().unwrap_or_else(|| page.title.clone());
FieldGroup::new(name).show(ui, |ui, _| {
for row in &group.rows {
show_row(ui, host, row, units, &mut out.rows);
if !page.groups.is_empty() {
FieldGroup::new(page.title.clone()).show(ui, |ui, _| {
for (at, group) in page.groups.iter().enumerate() {
let mut rows = |ui: &mut Ui| {
Stack::new().id_salt(at).show(ui, |ui, _| {
for row in &group.rows {
show_row(ui, host, row, units, &mut out.rows);
}
});
};
match &group.title {
Some(title) => {
Section::fixed(title.clone()).id_salt(at).show(ui, |ui, _| rows(ui));
}
None => rows(ui),
}
});
};
match &group.title {
Some(title) => {
Section::fixed(title.clone()).id_salt(at).show(ui, |ui, _| rows(ui));
}
None => rows(ui),
}
});
}
if let Some(note) = &page.footnote {
Text::new(note.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
@@ -35,6 +35,7 @@ pub(super) enum Kind {
Float { value: f64, range: RangeInclusive<f64>, decimals: u8, step: Option<f64>, unit: Option<UnitKind> },
Text(String),
Custom,
CustomRows,
}
impl ShownRow {
@@ -59,6 +60,7 @@ impl ShownRow {
}
RowKind::Text(text) => Kind::Text((*text).to_owned()),
RowKind::Custom => Kind::Custom,
RowKind::CustomRows => Kind::CustomRows,
};
Self {
key: row.key.to_owned(),
@@ -176,8 +178,14 @@ pub(super) fn show_row<H: PreferencesModel + ?Sized>(ui: &mut Ui, host: &mut H,
out.pick_color = ask;
}
}
Kind::Custom if label.as_str().is_empty() => {
Stack::new().id_salt(key).show(ui, |ui, _| host.custom_row(ui, key));
Kind::CustomRows => {
// The host draws the rows and their labels; the rule's enabled state and help apply to them as to a field.
Stack::new().id_salt(key).enabled(row.enabled).show(ui, |ui, _| {
host.custom_row(ui, key);
if let Some(help) = &row.help {
Help::Text(help.clone()).text().show(ui);
}
});
}
Kind::Custom => {
field().show(ui, |ui, _| {
+69 -2
View File
@@ -1,20 +1,23 @@
//! Native dock windows: when a float gets an OS window, what the dock records when the OS moves it, the OS close, and
//! docking the whole window by dragging its title row.
//! docking the whole window by dragging its title row. A context menu opened in a palette places its popup window as
//! it places the menu in the main window.
use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, Workspace};
use craft_behavior::placement::Placement;
use craft_host::target::{Backend, Caps, Os, ShellInfo};
use craft_ui::buttons::Button;
use craft_ui::contract::Role;
use craft_ui::contract::{Bind, BodyCx, DropMark, PlainData, Show as _, ShowContainer as _, SizeLimits, Tracked};
use craft_ui::display::Text;
use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec, PanelSpecs};
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::patterns::dock::DockArea;
use craft_ui::popover::DropVeil;
use craft_ui::runtime::InstallSpec;
use craft_ui::runtime::drag;
use craft_ui::testing::access::AccessTree;
use craft_ui::testing::input::key_press;
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::pointer::{moved, press, release, secondary};
use craft_ui::testing::trial;
use craft_ui::testing::windows::FakeSystem;
use craft_ui_test_kit::windows::{Out, Windows};
@@ -1218,3 +1221,67 @@ fn scaled(focused: bool, rect: Rect, pixels_per_point: f32) -> ViewportInfo {
..ViewportInfo::default()
}
}
/// How far down panel 1's body the context menu's target sits, and the menu's rows: in the native palette at
/// `FLOAT_AT`, the pointer on the target has about 300 points above it and below it in the windows' span, and the
/// menu is taller than either and shorter than the span.
const CONTEXT_DROP: f32 = 220.0;
const CONTEXT_ROWS: usize = 18;
/// A palette whose panel 1 holds a button with a context menu of `CONTEXT_ROWS` rows.
struct ContextTarget;
impl DockPanels<u32> for ContextTarget {
fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) {
if *panel != 1 {
return;
}
ui.add_space(CONTEXT_DROP);
let target = Button::new("Target").show(ui);
let _ = Menu::context("Target menu", &target).show(ui, |ui, _| {
for at in 0..CONTEXT_ROWS {
MenuItem::new(format!("Row {at}")).show(ui);
}
});
}
}
/// A context menu opened in a native palette shows in a popup OS window; too tall for the room on either side of the
/// pointer but not for the room the popup has, it covers the pointer and shows every row, as it does in the main window.
#[trial]
fn a_context_menu_from_a_native_palette_too_tall_for_either_side_covers_the_pointer_in_its_popup_window() {
let mut dock = NativeDock::on(Os::Windows, Arc::new(FakeSystem::new()));
dock.windows.root_info(scaled(true, MAIN_AT, COLLAPSED_SCALE));
let mut at = FLOAT_AT;
dock.windows.child_info(scaled(true, at, COLLAPSED_SCALE));
let mut panels = ContextTarget;
let out = collapsed_frame(&mut dock, &mut panels, &mut at, vec![], vec![]);
let palette = dock.palette.expect("the palette's window opened");
let target = node_rect(tree_of_viewport(&out, palette), "Target", Role::BUTTON).expect("the palette shows the target").center();
for events in [vec![moved(target)], vec![secondary(target, true)], vec![secondary(target, false)]] {
collapsed_frame(&mut dock, &mut panels, &mut at, vec![], events);
}
let mut out = collapsed_frame(&mut dock, &mut panels, &mut at, vec![], vec![]);
for _ in 0..4 {
out = collapsed_frame(&mut dock, &mut panels, &mut at, vec![], vec![]);
}
let menu = popups(&dock, &out)
.into_iter()
.find(|viewport| !tree_of_viewport(&out, *viewport).with_role(Role::MENU).is_empty())
.expect("the menu shows in a popup window");
let rect = window_rect(&dock, menu);
let pointer = at.min + target.to_vec2();
let room = MAIN_AT.union(at);
assert!(
rect.height() > pointer.y - room.top() && rect.height() > room.bottom() - pointer.y,
"the menu {rect:?} fits on neither side of {pointer:?}"
);
assert!(room.contains_rect(rect.shrink(0.5)), "the menu {rect:?} stays inside the windows' span {room:?}");
assert!(rect.contains(pointer), "the menu {rect:?} covers the pointer at {pointer:?}");
let tree = tree_of_viewport(&out, menu);
let window = Rect::from_min_size(Pos2::ZERO, rect.size()).expand(FIT_ROUNDING);
for row in [0, CONTEXT_ROWS - 1] {
let shown = node_rect(tree, &format!("Row {row}"), Role::MENU_ITEM).unwrap_or_else(|| panic!("row {row} shows"));
assert!(window.contains_rect(shown), "row {row} {shown:?} lies whole in the menu's window {window:?}");
}
}
@@ -1,8 +1,11 @@
//! The settings document without a window: rows, applied edits, rebase and row conditions.
use craft_i18n::Folder;
use craft_i18n::matcher::Matcher;
use craft_theme::Rgba;
use craft_ui::patterns::preferences::{
CustomSettings, PageInfo, PrefValue, PreferencesDraft, PreferencesModel, RowKind, SettingRule, SettingsDocument, SettingsDraft, StandardPage,
list_pages, row_shown,
};
use craft_ui::testing::trial;
use serde::{Deserialize, Serialize};
@@ -276,3 +279,23 @@ fn a_removed_draft_value_applies_as_no_value() {
assert_eq!(edits, vec![("memory.percent".to_owned(), None)]);
assert_eq!(doc.saved().memory.percent, None);
}
/// A row whose app draws its own labels is found by its rule's label: the search lists its page and shows it.
#[trial]
fn the_search_finds_a_host_labelled_row_by_its_rules_label() {
let rules = vec![
SettingRule::new("export.format").choices(&[("png", "PNG"), ("webp", "WebP")]),
SettingRule::new("export.tablet").label("Tablet pressure").custom_rows(),
];
let doc = SettingsDocument::new(ExportPrefs::default()).expect("serializes").rules(rules);
let pages = PreferencesModel::pages(&doc);
let matcher = Matcher::new(&Folder::new("en"), "tablet");
let listed = list_pages(&pages, &matcher);
let found: Vec<(&str, bool)> = listed
.iter()
.flat_map(|listed| pages[listed.index].groups.iter().flat_map(|group| group.rows.iter()).map(move |row| (row, listed)))
.filter(|(row, listed)| row_shown(&matcher, listed, row))
.map(|(row, _)| (row.key, matches!(row.kind, RowKind::CustomRows)))
.collect();
assert_eq!(found, [("export.tablet", true)], "the search shows the host-labelled row alone");
}
@@ -1,7 +1,12 @@
//! `PreferencesPage` over a model with no draft: each edit reaches the model in the pass it lands in.
use craft_ui::contract::{Bind, Role};
use craft_ui::patterns::preferences::{PageSpec, PrefValue, PreferencesModel, PreferencesPage, PreferencesState, PreferencesWords, RowKind, RowSpec};
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _};
use craft_ui::display::Text;
use craft_ui::form::Field;
use craft_ui::patterns::preferences::{
GroupSpec, PageSpec, PrefValue, PreferencesModel, PreferencesPage, PreferencesState, PreferencesWords, RowKind, RowSpec,
};
use craft_ui::runtime::env::Env;
use craft_ui::runtime::words::CommonWords;
use craft_ui::testing::pointer::{moved, press, release};
@@ -83,3 +88,91 @@ fn a_page_edit_reaches_the_model_in_the_same_pass_and_no_draft_method_runs() {
assert_eq!(live.borrow().sets.len(), 1, "later passes apply nothing again");
assert!(live.borrow().snap, "the model holds the value");
}
/// A page of two titled groups with labels of different lengths, and a host-labelled row that draws its own field.
struct Grouped;
impl PreferencesModel for Grouped {
fn pages(&self) -> Vec<PageSpec<'_>> {
let text = |key, label| RowSpec::new(key, label, RowKind::Text("v"));
let mut page = PageSpec::new("general", "General", Vec::new());
page.groups = vec![
GroupSpec::new(Some("First"), vec![text("general.a", "Aa"), RowSpec::new("general.host", "Hosted", RowKind::CustomRows)]),
GroupSpec::new(Some("Second"), vec![text("general.b", "A much longer label")]),
];
vec![page]
}
fn set(&mut self, _: &str, _: PrefValue) {}
fn custom_row(&mut self, ui: &mut Ui, _: &str) {
let _ = Field::new("Hosted").show(ui, |ui, _| {
Text::new("hosted value").show(ui);
});
}
fn custom_page(&mut self, _: &mut Ui, _: &str) {}
fn reset_page(&mut self, _: &str) {}
}
fn grouped_page() -> Fixture {
let mut state = PreferencesState::default();
let mut fixture = Fixture::new(move |ui| {
PreferencesPage::new(Bind::bound(&mut state)).show(ui, &mut Grouped);
});
fixture.settle();
fixture
}
#[trial]
fn the_rows_of_every_group_of_a_page_share_one_label_column() {
let fixture = grouped_page();
let end = |label: &str| {
let run = fixture.texts().iter().find(|run| run.text.trim_end_matches(':') == label).unwrap_or_else(|| panic!("no label {label}"));
run.rect.right()
};
assert_eq!(end("Aa"), end("A much longer label"), "the labels of both groups end at one x");
}
#[trial]
fn a_host_labelled_custom_row_shows_its_label_once() {
let fixture = grouped_page();
let tree = fixture.tree();
let fields = tree.keys().into_iter().filter(|key| tree.name_of(*key) == Some("Hosted") && tree.role_of(*key) == Some(Role::GROUP)).count();
assert_eq!(fields, 1, "the host's field is the row's only labelled group");
}
/// A disabled host-labelled row with help: the host draws a button.
struct HelpedRows;
impl PreferencesModel for HelpedRows {
fn pages(&self) -> Vec<PageSpec<'_>> {
let row = RowSpec::new("general.host", "Hosted", RowKind::CustomRows).help("Drawn with its note").enabled(false);
vec![PageSpec::new("general", "General", vec![row])]
}
fn set(&mut self, _: &str, _: PrefValue) {}
fn custom_row(&mut self, ui: &mut Ui, _: &str) {
Button::new("Hosted button").show(ui);
}
fn custom_page(&mut self, _: &mut Ui, _: &str) {}
fn reset_page(&mut self, _: &str) {}
}
/// The rule's help shows under the rows the host draws, and a disabled rule disables them.
#[trial]
fn a_host_labelled_row_shows_its_rules_help_and_follows_its_enabled_state() {
let mut state = PreferencesState::default();
let mut fixture = Fixture::new(move |ui| {
PreferencesPage::new(Bind::bound(&mut state)).show(ui, &mut HelpedRows);
});
fixture.settle();
let button = fixture.by_label("Hosted button").expect("the host's button");
let help = fixture.texts().iter().find(|run| run.text == "Drawn with its note").map(|run| run.rect).expect("the help shows");
assert!(help.top() >= button.rect.bottom(), "the help {help:?} sits under the host's rows {:?}", button.rect);
assert!(fixture.tree().is_disabled_key(button.node), "the disabled rule disables the host's button");
}
+31 -1
View File
@@ -5,7 +5,8 @@
use craft_host::target::ShellInfo;
use craft_ui::bars::{Bar, BarKind};
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Scroll, Show as _, ShowContainer as _};
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Props as _, Scroll, Show as _, ShowContainer as _};
use craft_ui::dialog::Dialog;
use craft_ui::display::Text;
use craft_ui::layout_components::{Row, Stack};
@@ -137,6 +138,35 @@ fn a_top_slot_sized_by_its_content_stacks_it_and_takes_its_height() {
assert!(body.min.y >= row.max.y - SLACK, "the body {body:?} starts under the row {row:?}");
}
/// A check box with its label after it sits on the options slot's middle, as a button beside it does: the slot is
/// shorter than the bar asks for, and the bar centres its members in it.
#[trial]
fn a_labelled_check_box_in_the_options_slot_sits_on_its_middle() {
let seen = Rc::new(Cell::new(None::<(Rect, Rect, Rect)>));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let (mut check, mut button) = (Rect::NOTHING, Rect::NOTHING);
let mut on = true;
let shown = AppShell::new(WindowKey::main())
.options_bar(true, |ui, _, _: &mut ()| {
let _ = Bar::new("Options", BarKind::Options).show(ui, |ui, _| {
check = Checkbox::new(Bind::bound(&mut on)).label("Anti-alias").show(ui).response.rect;
button = Button::new("Select and Mask").show(ui).rect;
});
})
.body(|_, _, _| {})
.show(ui, &mut ());
if let Some(slot) = shown.regions.slots.iter().find(|(key, _)| *key == "options").map(|(_, rect)| *rect) {
out.set(Some((slot, check, button)));
}
});
fixture.room(Vec2::new(600.0, 300.0)).settle();
let (slot, check, button) = seen.get().expect("the options slot shows");
assert!(check.height() > 0.0 && button.height() > 0.0, "both members show (check box {check:?}, button {button:?})");
assert!((button.center().y - slot.center().y).abs() <= 1.0, "the button {button:?} sits on the slot's middle {slot:?}");
assert!((check.center().y - slot.center().y).abs() <= 1.0, "the check box {check:?} sits on the slot's middle {slot:?}");
}
/// A title bar in the title slot shows its leading content inside the slot, on the slot's middle.
#[trial]
fn a_title_bar_in_the_title_slot_shows_its_content_there() {
+4 -1
View File
@@ -11,7 +11,7 @@ use crate::layout_components::Row;
use crate::runtime::access::Name;
use crate::runtime::commands::{CommandSet as _, Commands as _};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, StyleCx, SurfaceKind};
use crate::style::{ComponentStyle, GlyphRole, StyleCx, SurfaceKind};
use craft_behavior::{IconId, Metrics, NavShape, Roving, Sense};
use craft_theme::ControlSize;
use egui::{Response, Ui};
@@ -129,6 +129,9 @@ impl<'a> Bar<'a> {
if kind == BarKind::Status {
props = props.live(Politeness::Polite);
}
if kind == BarKind::Options {
props = props.child_glyphs(GlyphRole::Tool);
}
Bar { common: Common::new(), props, kind, commit_cancel: None, committed: false, cancelled: false, trailing: None }.label(label)
}
+13 -5
View File
@@ -21,6 +21,16 @@ pub enum Help {
Status(Tone, Label),
}
impl Help {
/// The help line as a field shows it under its control.
pub fn text(&self) -> Text {
match self {
Help::Text(text) => Text::new(text.clone()).role(TypeRole::Caption).shade(Shade::Muted),
Help::Status(tone, text) => Text::new(text.clone()).role(TypeRole::Caption).tone(*tone),
}
}
}
/// The style of a field: no look of its own; the label step and the help line carry it.
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
#[non_exhaustive]
@@ -116,10 +126,8 @@ impl Container for Field {
Text::new(message.text.clone()).role(TypeRole::Caption).tone(tone).show(ui);
return;
}
match &self.help {
Some(Help::Text(text)) => Text::new(text.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui),
Some(Help::Status(tone, text)) => Text::new(text.clone()).role(TypeRole::Caption).tone(*tone).show(ui),
None => return,
};
if let Some(help) = &self.help {
help.text().show(ui);
}
}
}
+6 -9
View File
@@ -37,7 +37,7 @@ use crate::runtime::words::common::CommonWords;
use crate::style::{ComponentStyle, FocusLook, IconLook, StyleCx, SurfaceLook, TextLook, TypeRole};
use crate::text::TextField;
use craft_behavior::fit::{FitItem, FitKeep, fit_items};
use craft_behavior::{Arrows, Axis, Flow, Intent, Metrics, NavMove, NavShape, PartKey, PartRef, Roving, Sense};
use craft_behavior::{Arrows, Flow, Intent, Metrics, NavMove, NavShape, PartKey, PartRef, Proposal, Roving, Sense};
use craft_host::target::MenuPlacement;
use craft_keymap::mnemonic;
use craft_theme::Flags;
@@ -436,18 +436,15 @@ impl Component for MenuBar<'_> {
MenuBarStyle { metrics: Metrics::new() }
}
/// Every title's width when the room allows it; the bar fills the row, so what is left over is room for the
/// overflow.
/// Every title's width; at its least (`Proposal::Min`) the width of the "…" title alone. A row that has less room
/// than every title needs narrows the bar, and the titles that no longer fit go into "…".
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
if !Self::in_window(&cx.env) {
return Vec2::ZERO;
}
let (widths, height, _) = self.widths(cx);
Vec2::new(widths.iter().sum(), height)
}
fn fills(&self) -> Option<Axis> {
Some(Axis::X)
let (widths, height, more) = self.widths(cx);
let width = if cx.proposal == Proposal::Min { more } else { widths.iter().sum() };
Vec2::new(width, height)
}
fn sense(&self) -> Sense {
+21
View File
@@ -14,6 +14,7 @@ use craft_ui::display::Text;
use craft_ui::form::Field;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::pickers::Select;
use craft_ui::style::GlyphRole;
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::layout::Block;
use craft_ui::testing::{Fixture, shrink_least_runs, trial};
@@ -449,6 +450,26 @@ fn a_labelled_check_box_in_a_row_in_a_bar_lays_out_under_rtl() {
assert!(label.max.x <= alpha.min.x + SLACK, "the check box {label:?} follows Alpha {alpha:?} from the right");
}
/// An icon-only button in an options bar draws its icon at the tool size, as the align strip's buttons do.
#[trial]
fn an_icon_button_in_an_options_bar_draws_its_icon_at_the_tool_size() {
let mut fixture = Fixture::new(|ui| {
Bar::new("Options", BarKind::Options).show(ui, |ui, _| {
IconButton::new(IconId::new("settings")).label("Plain").show(ui);
IconButton::new(IconId::new("settings")).label("Tool").glyphs(GlyphRole::Tool).show(ui);
});
});
fixture.room(Vec2::new(400.0, 80.0)).settle();
let sides: Vec<f32> = fixture
.styles_of(std::any::type_name::<IconButton<'static>>())
.iter()
.flat_map(|seen| seen.looks.icons.iter().map(|icon| icon.side))
.collect();
// Buttons that resolve the same looks share one recorded style, so a single side means they agree.
assert!(!sides.is_empty(), "the buttons resolved a style");
assert!(sides.iter().all(|side| (side - sides[0]).abs() <= 0.01), "the options bar's button and the tool button differ: {sides:?}");
}
/// Each pass's stops, each with the roving group it registered in.
type StopGroups = Rc<std::cell::RefCell<Vec<Vec<(egui::Id, Option<egui::Id>)>>>>;
+61 -1
View File
@@ -7,7 +7,7 @@ use craft_ui::choice::Checkbox;
use craft_ui::contract::{
Bind, CollectionEvent, MemoProps, MemoView, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Tracked, request_rename,
};
use craft_ui::display::Text;
use craft_ui::display::{Elide, Text};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::list::{List, ListRow};
use craft_ui::popover::Popover;
@@ -1595,3 +1595,63 @@ fn a_view_in_a_content_sized_column_lays_out_its_fill_width_row_as_outside_a_vie
assert!(outside.0.width() < outside.1.width(), "the column outside a view is as narrow as its button: {outside:?}");
assert_eq!(inside, outside, "the view's column and its sibling lie as without the view");
}
#[derive(MemoProps)]
struct Line {
line: String,
}
/// One line of text cut with an ellipsis where its room is short.
fn line(props: &mut Line, ui: &mut Ui) -> Rect {
Text::new(props.line.clone()).elide(Elide::End).show(ui).rect
}
/// A memoized view is one unit of the shrinking row around it: with room it is as wide as its content, and when a
/// sibling after it grows it narrows so the row fits, though the region it is offered stays the same. It replays while
/// the row's width for it is unchanged and runs once when that width changes.
#[trial]
fn a_view_in_a_row_narrows_with_it_and_runs_only_when_its_width_changes() {
const ROOM: Rect = Rect { min: Pos2::new(10.0, 10.0), max: Pos2::new(310.0, 50.0) };
let mut frames = Frames::new();
let frame = |frames: &mut Frames, after: &str| {
let mut rects = (Rect::NOTHING, Rect::NOTHING);
frames.frame(vec![], |ui| {
in_region(ui, ROOM, |ui| {
Row::new().fill_width().show(ui, |ui, _| {
let view = MemoView::new("line", Line { line: "A line of text long enough to be cut".to_owned() }, line).show(ui);
let after = Button::new(after.to_owned()).show(ui).response.rect;
rects = (view.unwrap_or(Rect::NOTHING), after);
});
});
});
rects
};
for _ in 0..WARM {
frame(&mut frames, "B");
}
let (wide, _) = frame(&mut frames, "B");
assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "an idle frame replays the view");
assert!(measuring_runs_of(&frames, "Line") <= SWEEPS, "an idle frame runs the view at most once per measuring sweep of the row");
let (narrow, after) = frame(&mut frames, "A much longer button label");
assert_eq!(runs_of(&frames, "Line"), [MemoRun::Ran], "a new width runs the view");
assert!(narrow.width() < wide.width(), "the view narrows: {narrow:?} from {wide:?}");
assert!(narrow.right() <= after.left() && after.right() <= ROOM.right() + 0.5, "the row fits: {narrow:?}, {after:?} in {ROOM:?}");
for _ in 0..WARM {
frame(&mut frames, "A much longer button label");
}
assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "at the same width it replays again");
assert!(measuring_runs_of(&frames, "Line") <= SWEEPS, "at the same width the view runs at most once per measuring sweep of the row");
}
/// The sweeps of a shrinking row's measuring run that show its units: the counting sweep and, for a short row, the
/// sweep that asks its body units for their least. Until FW-310 moves `unbounded` out of the scope key, the counting
/// sweep's call keys apart from the real call's and a memoized unit runs in each sweep; FW-310 tightens this to none.
const SWEEPS: usize = 2;
/// How many times the views named `name` ran in the last frame outside the real run of its last pass: in sizing and
/// measuring runs.
fn measuring_runs_of(frames: &Frames, name: &str) -> usize {
let ran =
|runs: Vec<(&'static str, egui::Id, MemoRun)>| runs.into_iter().filter(|(of, _, run)| of.contains(name) && *run == MemoRun::Ran).count();
ran(last_frame_memo_runs(&frames.ctx)) - ran(last_pass_memo_runs(&frames.ctx))
}
+54 -7
View File
@@ -1,15 +1,21 @@
//! The row line: a child of an unwrapped row that is one line sits with its centre on the row's line; a child of more
//! than one line (a column, a field with its label above or a help line below) sits at the row's top.
//! than one line (a column, a field with a help line below) sits at the row's top. A control with its label after it
//! or above it, and a field labelled above, sit on the line by their control, as a bare control does, in a row and in
//! a grid's cell.
use craft_behavior::ColumnWidth;
use craft_theme::ControlSize;
use craft_ui::buttons::Button;
use craft_ui::contract::{FieldLayout, Props as _, Show as _, ShowContainer as _, Sizing};
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _, Sizing};
use craft_ui::display::Text;
use craft_ui::form::{Field, Help};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::layout_components::{Grid, Row, Stack};
use craft_ui::runtime::env::Label;
use craft_ui::testing::{Fixture, last_pass_measuring_runs, trial};
use egui::Rect;
use std::cell::Cell;
use std::rc::Rc;
/// Half a pixel at the scales the box runs.
const ROUNDING: f32 = 0.5;
@@ -102,10 +108,10 @@ fn columns_sit_at_the_rows_top_and_lines_on_the_line() {
assert!(four.top() <= control(&fixture, &["Go"]).top() + ROUNDING, "the four-line column starts below the button's top");
}
/// A field labelled above its control is two lines and sits at the row's top, so a button beside it sits level with
/// the label, not the control.
/// A field labelled above its control sits on the row's line by its control, as a control labelled above does: a
/// button beside it sits level with the control, and the label stands above the line.
#[trial]
fn a_field_labelled_above_sits_at_the_rows_top() {
fn a_field_labelled_above_sits_on_the_row_line_by_its_control() {
let fixture = settled(|ui| {
Row::new().show(ui, |ui, _| {
Field::new("Caption").layout(FieldLayout::Above).sizing(Sizing::Content).show(ui, |ui, _| {
@@ -116,5 +122,46 @@ fn a_field_labelled_above_sits_at_the_rows_top() {
});
let (caption, control, button) = (text(&fixture, "Caption"), text(&fixture, "X"), text(&fixture, "Y"));
assert!(caption.bottom() < control.top(), "the label sits above its control");
assert!(button.center().y < control.top(), "the button {button:?} sits level with the label, above the control {control:?}");
assert!((button.center().y - control.center().y).abs() <= ROUNDING, "the button {button:?} sits on the control's line {control:?}");
}
/// A check box whose label runs to a second line under it, beside a button in a row: its box sits on the button's
/// line and the label's second line hangs below. In a grid's cell, beside a taller cell, a check box with its label
/// after it sits on the line of the button in the next cell.
#[trial]
fn a_labelled_check_box_sits_with_its_box_on_a_buttons_line_in_a_row_and_a_grid_cell() {
const LONG: &str = "Smooth the edges of every selection the tool makes";
for grid in [false, true] {
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING)));
let out = Rc::clone(&seen);
let fixture = settled(move |ui| {
let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(260.0, 400.0));
let out = Rc::clone(&out);
Stack::new().fill().show_at(ui, room, move |ui, _| {
if grid {
Grid::new(&[ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
Text::new("A").show(ui);
Text::new("B").show(ui);
});
let button = Button::new("Go").show(ui).rect;
let check = Checkbox::new(Bind::given(true)).label("Snap").show(ui).response.rect;
out.set((button, check));
});
} else {
Row::new().show(ui, |ui, _| {
let button = Button::new("Go").show(ui).rect;
let check = Checkbox::new(Bind::given(true)).label(LONG).show(ui).response.rect;
out.set((button, check));
});
}
});
});
let (button, check) = seen.get();
let at = if grid { "in a grid's cell" } else { "in a row" };
if !grid {
assert!(text(&fixture, LONG).bottom() > check.bottom() + ROUNDING, "the label runs to a second line under the box {check:?}");
}
assert!((button.center().y - check.center().y).abs() <= ROUNDING, "{at}: the box {check:?} sits on the button's line {button:?}");
}
}
+82 -2
View File
@@ -1,10 +1,12 @@
//! A menu taller than its room: it stays inside the room at the width of its rows, scrolls by the strips above and
//! below its rows and by the wheel, and reopens at its first row; one that fits shows no strips. A tall submenu of a
//! low row opens upward.
//! low row opens upward. A context menu that fits on neither side of the pointer, or of the control a key asked it
//! for, but fits the window covers its anchor instead of scrolling; a tooltip at the pointer never covers the pointer.
use craft_host::target::Os;
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Entry, Role, STRIP_BACK, STRIP_FORWARD, Show as _, ShowContainer as _, Trigger};
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, Entry, Props as _, Role, STRIP_BACK, STRIP_FORWARD, Show as _, ShowContainer as _, TooltipAt, TooltipSpec, Trigger};
use craft_ui::menu::bar::{MenuBar, MenuTitle};
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::pickers::Select;
@@ -108,6 +110,84 @@ fn a_menu_that_fits_shows_no_strips_and_hugs_its_rows() {
assert!(((first.top() - rect.top()) - (rect.bottom() - last.bottom())).abs() < 0.5, "as tall as its rows: {rect:?}, rows {first:?} to {last:?}");
}
/// A context menu of `rows` rows on a target `top` down the fixture's 800 x 600 window, right-clicked at the target's
/// centre: the fixture, the menu's id and the pointer.
fn context_menu(top: f32, rows: usize) -> (Fixture, Id, egui::Pos2) {
let menu = Rc::new(Cell::new(None));
let seen = Rc::clone(&menu);
let mut fixture = Fixture::new(move |ui| {
ui.add_space(top);
let target = Button::new("Target").show(ui);
let shown = Menu::context("Target menu", &target).show(ui, |ui, _| {
for at in 0..rows {
MenuItem::new(row(at)).show(ui);
}
});
seen.set(Some(shown.output.response.id));
});
fixture.settle();
let at = fixture.by_label("Target").expect("the target").center();
fixture.frame(vec![pointer::moved(at)]);
fixture.frame(vec![pointer::secondary(at, true)]);
fixture.frame(vec![pointer::secondary(at, false)]);
fixture.settle();
(fixture, menu.get().expect("the menu's id"), at)
}
#[trial]
fn a_context_menu_too_tall_for_either_side_of_the_pointer_covers_it_and_shows_every_row_without_strips() {
let rows = 18;
let (fixture, menu, at) = context_menu(290.0, rows);
let room = fixture.ctx().content_rect();
let rect = menu_rect(&fixture);
assert!(strips(&fixture, menu).is_none(), "the menu {rect:?} fits the window {room:?}: no strips");
let (first, last) = (fixture.by_label(&row(0)).expect("the first row").rect, fixture.by_label(&row(rows - 1)).expect("the last row").rect);
let tall = last.bottom() - first.top();
assert!(tall > at.y - room.top() && tall > room.bottom() - at.y, "the rows ({tall}) fit on neither side of the pointer at {at:?}");
assert!(room.contains_rect(rect), "the menu {rect:?} stays inside the window {room:?}");
assert!(rect.contains_rect(first) && rect.contains_rect(last), "every row shows: {first:?} to {last:?} in {rect:?}");
}
/// The same menu asked for with Shift+F10 on the focused target: it hangs from the target's rect, which it covers.
#[trial]
fn a_context_menu_a_key_asked_for_covers_its_target_when_it_fits_neither_side() {
let rows = 18;
let (mut fixture, menu, _) = context_menu(290.0, rows);
fixture.key(Key::Escape, Modifiers::NONE).settle();
assert!(fixture.by_role(Role::MENU).is_empty(), "Escape closes the menu the pointer opened");
let target = fixture.by_label("Target").expect("the target").rect;
fixture.key(Key::Tab, Modifiers::NONE);
fixture.key(Key::F10, Modifiers::SHIFT).settle();
let room = fixture.ctx().content_rect();
let rect = menu_rect(&fixture);
assert!(strips(&fixture, menu).is_none(), "the menu {rect:?} fits the window {room:?}: no strips");
let (first, last) = (fixture.by_label(&row(0)).expect("the first row").rect, fixture.by_label(&row(rows - 1)).expect("the last row").rect);
assert!(rect.contains_rect(first) && rect.contains_rect(last), "every row shows: {first:?} to {last:?} in {rect:?}");
assert!(rect.intersects(target), "the menu {rect:?} covers its target {target:?}");
}
/// A tooltip at the pointer too tall for either side of it stays off the pointer: it opens on its preferred side,
/// below, where the room is larger, and does not slide up over the pointer as a menu does.
#[trial]
fn a_tooltip_at_the_pointer_too_tall_for_either_side_does_not_cover_the_pointer() {
let text = (0..40).map(|line| format!("Line {line}")).collect::<Vec<_>>().join("\n");
let mut fixture = Fixture::new(move |ui| {
ui.add_space(200.0);
Button::new("Target").tooltip(TooltipSpec::new(text.clone()).at(TooltipAt::Pointer)).show(ui);
});
fixture.settle();
let at = fixture.by_label("Target").expect("the target").center();
fixture.frame(vec![pointer::moved(at)]);
fixture.advance(DELAY);
fixture.settle();
let tips = fixture.by_role(Role::TOOLTIP);
let tip = tips.first().expect("the tooltip shows").rect;
let room = fixture.ctx().content_rect();
let lines = fixture.texts().iter().filter(|run| run.text.starts_with("Line ")).fold(Rect::NOTHING, |all, run| all.union(run.rect));
assert!(lines.height() > at.y - room.top() && lines.height() > room.bottom() - at.y, "the text ({lines:?}) fits on neither side of {at:?}");
assert!(tip.top() >= at.y, "the tooltip {tip:?} opens below the pointer at {at:?} and does not cover it");
}
/// A menu of `above` rows over a submenu row whose submenu has `rows` rows, in the fixture's 800 x 600 window.
fn low_submenu(above: usize, rows: usize) -> Fixture {
let mut fixture = Fixture::new(move |ui| {
+34 -1
View File
@@ -1,6 +1,7 @@
//! The table's header row and column widths: a double click on a column's edge fits the column to its widest cell in
//! view, the header menu hides, shows and resets columns, Ctrl or Cmd with an arrow moves the focused column, and the
//! metadata table's name column follows its widest name up to a third of the table.
//! metadata table's name column follows its widest name up to a third of the table. A header menu too tall for either
//! side of its point covers the point instead of scrolling.
use craft_behavior::{ColumnKey, ColumnWidth, keyed};
use craft_host::target::Os;
@@ -217,6 +218,38 @@ fn the_header_menu_hides_shows_and_resets_columns() {
assert!(menu_row(&fixture, Role::MENU_ITEM, "Move Column Right").is_none(), "with no column there are no column commands");
}
/// The hideable columns of a table whose header menu is taller than the room on either side of the point it opens at.
const EXTRA: [&str; 14] =
["Kind", "Owner", "Group", "Created", "Modified", "Opened", "Tags", "Rating", "Label", "Path", "Format", "Pixels", "Profile", "Author"];
/// A header menu opened at a point mid-window, too tall for the room above or below the point but not for the window,
/// covers the point and shows every row.
#[trial]
fn a_header_menu_too_tall_for_either_side_of_its_point_covers_it_and_shows_every_row() {
let mut fixture = Fixture::new(|ui| {
ui.add_space(270.0);
let mut columns = vec![ColumnSpec::new(NAME, "Name", ColumnWidth::Controls(4.0)).movable()];
columns.extend(EXTRA.iter().map(|name| ColumnSpec::new(ColumnKey::new(name), *name, ColumnWidth::Controls(2.0)).hideable()));
let keys = [0_usize];
let source = keyed(&keys, |key: &usize| *key);
Table::new("Files", columns).show_items(ui, &source, &mut |key, icx| ListRow::new(format!("File {key}")).cells(icx.cells()));
});
fixture.settle();
let at = fixture.by_label("Name").expect("the header cell").center();
secondary_click(&mut fixture, at);
let room = fixture.ctx().content_rect();
let first = menu_row(&fixture, Role::MENU_ITEM_CHECK_BOX, EXTRA[0]).expect("the first column's row").rect;
let last = menu_row(&fixture, Role::MENU_ITEM, "Reset Columns").expect("the last row").rect;
let tall = last.bottom() - first.top();
assert!(tall > at.y - room.top() && tall > room.bottom() - at.y, "the rows ({tall}) fit on neither side of the point {at:?}");
let menus = fixture.by_role(Role::MENU);
assert!(!menus.is_empty(), "the header menu is open");
for menu in menus {
assert!(room.contains_rect(menu.rect), "the menu {:?} stays inside the window {room:?}", menu.rect);
assert!(menu.rect.contains_rect(first) && menu.rect.contains_rect(last), "every row shows: {first:?} to {last:?} in {:?}", menu.rect);
}
}
/// Ctrl or Cmd with Right on a focused movable header moves its column one place on; Right alone moves the focus.
/// macOS makes Cmd+Right a move to the line's end, which the header reads the same.
#[trial]
+5 -3
View File
@@ -564,7 +564,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop
- `pub fn panel_state(&self, panel: &P) -> PanelState`. Hidden, open behind another tab or in a collapsed container, or showing. In a column, docked or floating,
- `pub fn restore(&mut self, panel: P, location: &Location<P>) -> Result<(), DockError>`. Restore an absent panel at a captured location. Missing anchors are reported without
- `pub fn open_at_edge(&mut self, panel: P) -> Result<(), DockError>`. Open an absent panel as a frame at the outer edge of the docked area, taking most of it:
- `craft_behavior::dock::Location`: `pub struct Location<P> { pub floating: Option<Rect>, pub anchor: Option<P>, pub placement: DockPlacement<P>, pub size: Option<SplitSize>, pub stack: Option<(bool, Option<f32>)>, pub sibling: Vec<P>, pub group: Option<GroupLocation> }`. A closed panel's former placement. Applications may retain this beside visibility flags.
- `craft_behavior::dock::Location`: `pub struct Location<P> { pub floating: Option<Rect>, pub anchor: Option<P>, pub placement: DockPlacement<P>, pub size: Option<SplitSize>, pub stack: Option<(bool, Option<f32>)>, pub sibling: Vec<P>, pub group: Option<GroupLocation>, pub closed_with: Vec<P> }`. A closed panel's former placement. Applications may retain this beside visibility flags.
- `pub fn new(anchor: Option<P>, placement: DockPlacement<P>) -> Self`. A location relative to `anchor` by `placement`, with no recorded sizes or siblings.
- `craft_behavior::dock::MAX_DEPTH`: `pub const MAX_DEPTH: usize`. Limits are checked before cloning or recursively modifying an application layout.
- `craft_behavior::dock::MAX_PANELS`: `pub const MAX_PANELS: usize`. Most panels a layout may hold. Larger layouts fail with [`DockError::LimitExceeded`](super::DockError::LimitExceeded).
@@ -1384,7 +1384,7 @@ The one-press-per-pass rule: a pass carries at most one press, as its last point
- `craft_behavior::overlay::Align`: `pub enum Align { Start, Center, End }`. How the overlay lines up with the anchor along the edge it hangs from.
- `craft_behavior::overlay::MinWidth`: `pub enum MinWidth { None, Anchor, Points(f32) }`. The narrowest an overlay may be.
- `pub fn points(self, anchor_width: f32, side: Side) -> f32`. The width in points, given the anchor's width and the side the overlay takes: beside its anchor (`Start`,
- `craft_behavior::overlay::PlaceRequest`: `pub struct PlaceRequest { pub anchor: Rect, pub size: Vec2, pub side: Side, pub align: Align, pub rtl: bool, pub gap: f32, pub min_width: MinWidth, pub bounds: Rect, pub kept: Option<Side>, pub flips_across: bool }`. What `place` reads.
- `craft_behavior::overlay::PlaceRequest`: `pub struct PlaceRequest { pub anchor: Rect, pub size: Vec2, pub side: Side, pub align: Align, pub rtl: bool, pub gap: f32, pub min_width: MinWidth, pub bounds: Rect, pub kept: Option<Side>, pub flips_across: bool, pub covers_anchor: bool }`. What `place` reads.
- `pub const fn new(anchor: Rect, size: Vec2, bounds: Rect) -> Self`. A request for `size` around `anchor` inside `bounds`: below, aligned to the start, no gap, free width.
- `pub const fn size(mut self, size: Vec2) -> Self`. Sets the content size.
- `pub const fn side(mut self, side: Side) -> Self`. Sets the preferred side.
@@ -1394,6 +1394,7 @@ The one-press-per-pass rule: a pass carries at most one press, as its last point
- `pub const fn min_width(mut self, min_width: MinWidth) -> Self`. Sets the narrowest width.
- `pub const fn kept(mut self, side: Option<Side>) -> Self`. Keeps `side` instead of flipping.
- `pub const fn flips_across(mut self, on: bool) -> Self`. Lines up with the anchor's other end, beside it, when that fits and the aligned end does not.
- `pub const fn covers_anchor(mut self, on: bool) -> Self`. Below or above the anchor, slides over the anchor when the overlay fits neither side but fits the bounds.
- `craft_behavior::overlay::Placement`: `pub struct Placement { pub rect: Rect, pub side: Side }`. Where `place` put the overlay.
- `craft_behavior::overlay::Side`: `pub enum Side { Below, Above, Start, End }`. The side of the anchor an overlay prefers. `Start` and `End` follow the reading direction.
- `craft_behavior::overlay::place`: `pub fn place(request: &PlaceRequest) -> Placement`. Places an overlay: the preferred side unless the other has more room and the content does not fit, shifted to
@@ -4223,7 +4224,7 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con
- `craft_ui::runtime::toast::ToastEnd`: `pub enum ToastEnd { Action(usize), Dismissed, Expired, Dropped }`. How a toast left the queue.
- `craft_ui::runtime::toast::ToastId`: `pub struct ToastId`. A posted toast's handle.
- `pub fn value(self) -> u64`. The handle as a number, unique among the toasts of one queue: what a host reports to automation.
- `craft_ui::runtime::toast::cards`: `pub fn cards(ctx: &Context, window: &WindowKey) -> Vec<Card>`. The cards of the window `window` in the running viewport, oldest first.
- `craft_ui::runtime::toast::cards`: `pub fn cards(ctx: &Context, window: &WindowKey) -> Vec<Card>`. The cards of the window `window` in the running viewport, oldest first. A tracked input (`Input::Toasts`).
- `craft_ui::runtime::toast::dismiss`: `pub fn dismiss(ctx: &Context, id: ToastId)`. Removes a toast before its timer ends, from whichever viewport holds it. The app asked for it, so no end is
- `craft_ui::runtime::toast::end`: `pub fn end(ctx: &Context, id: ToastId) -> Option<ToastEnd>`. How the toast `id` ended, once: `Dropped` for a card the cap removed; `None` while it is queued, after the report
- `craft_ui::runtime::toast::keep`: `pub fn keep(ctx: &Context, id: ToastId)`. Keeps the toast `id` until it is closed, whatever its timeout (an error the user must read).
@@ -4587,6 +4588,7 @@ What the accessibility trials read: the AccessKit tree a frame produced, and the
- `craft_ui::testing::access::Declared`: `pub enum Declared { Focus, Click, Increment, Decrement, SetValue, SetTextSelection, Expand, Collapse, Custom, ScrollUp, ScrollDown, ScrollLeft, ScrollRight }`. An action a node declares.
- `craft_ui::testing::access::NodeKey`: `pub struct NodeKey`. A node's number in the tree.
- `pub fn of(id: Id) -> NodeKey`. The key of the node of `id`.
- `craft_ui::testing::access::layer_root`: `pub fn layer_root(id: Id) -> Id`. The id of the root node of the overlay layer `id`. The root has an id of its own: the layer's container component
- `craft_ui::testing::access::prune_controls`: re-export of `craft_ui::runtime::egui::access::prune_controls`.
## `craft_ui::testing::bypass`