Merge main into feat/unit-text

This commit is contained in:
dotCooCoo committed 2026-11-22 00:50:40 -08:00
commit d54bb6c5b1
75 files changed
+2511 -336

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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
dependencies = [
"bytemuck",
"emath",
@@ -5506,7 +5506,7 @@ dependencies = [
[[package]]
name = "eframe"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
dependencies = [
"ahash",
"bytemuck",
@@ -5541,7 +5541,7 @@ dependencies = [
[[package]]
name = "egui"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
dependencies = [
"eframe",
"egui",
@@ -5689,7 +5689,7 @@ dependencies = [
[[package]]
name = "emath"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
dependencies = [
"bytemuck",
]
@@ -5762,7 +5762,7 @@ dependencies = [
[[package]]
name = "epaint"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
[[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=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
[[patch.unused]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
[[patch.unused]]
name = "egui_system_font_provider"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
+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 = "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" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
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
+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 = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1";
pub const REV: &str = "f5025284445ea19c35f746d96fc0b75468b3f560";
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
pub const PACKAGES: &[&str] = &[
+30 -10
View File
@@ -14,16 +14,18 @@ use craft_behavior::{Codec, EditEvent, IconId, Mixed, NotAValue, PartKey, Sense,
use craft_behavior::{HitLevel, HitPriority, NavMove, Preview};
use craft_font_catalog::Catalog;
use craft_host::Section;
use craft_theme::variant::Tone;
use craft_ui::buttons::{ControlPlace, IconButton};
use craft_ui::contract::{
Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _,
};
use craft_ui::list::{ThumbSize, TrailingPart};
use craft_ui::primitives::{IconSpec, TextKey, TextOptions, TextRun};
use craft_ui::runtime::env::{EnvView, Label};
use craft_ui::runtime::memory::StageAccess;
use craft_ui::text::{Adornment, place, reserve};
use craft_ui::style::{ComponentStyle, Metrics, Stateful, States, StyleColor, StyleCx, SurfaceLook};
use craft_ui::text::{Adornment, FieldStyle, place, reserve};
use egui::{Rect, Response, Vec2};
use serde::{Deserialize, Serialize};
@@ -589,18 +591,35 @@ impl<'a> FontPicker<'a> {
}
}
/// The style of [`FontPicker`]: the field look and the colour of the missing-font warning icon.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct FontPickerStyle {
#[style(surface)]
surface: SurfaceLook,
#[style(metrics)]
metrics: Metrics,
/// The field look the adornments are placed by; `surface` and `metrics` are its own.
field: FieldStyle,
/// The ink of the missing-font warning icon (`status.warn.fg`), dimmed to `text.disabled` while disabled.
warning: Stateful<StyleColor>,
}
impl Component for FontPicker<'_> {
const ROLE: Role = Role::COMBO_BOX;
const INPUT: Input = Input::Text;
const KEYS: craft_ui::runtime::focus::KeyUse = craft_ui::runtime::focus::KeyUse::of(Input::Text).with_moves();
type Style = craft_ui::text::FieldStyle;
type Style = FontPickerStyle;
type Output = FontPickerOutput;
/// A field; in a ribbon (`ControlPlace::Ribbon`) held at the small field length (`size.length.field.sm`), as a
/// ribbon's font box is: wide enough for a family name and its menu arrow, the same width whichever it shows.
fn style(cx: &craft_ui::style::StyleCx<'_>, _: FontPickerStyleKey) -> craft_ui::text::FieldStyle {
let field = craft_ui::text::FieldStyle::at(cx);
if cx.env::<ControlPlace>() == ControlPlace::Ribbon { field.held_at(cx.tokens.size.length.field.sm) } else { field }
fn style(cx: &StyleCx<'_>, _: FontPickerStyleKey) -> FontPickerStyle {
let field = FieldStyle::at(cx);
let field = if cx.env::<ControlPlace>() == ControlPlace::Ribbon { field.held_at(cx.tokens.size.length.field.sm) } else { field };
let warn = cx.tone(Tone::Warn);
let off = cx.color(cx.tokens.color.text.disabled);
FontPickerStyle { surface: cx.field(), metrics: field.metrics(), field, warning: Stateful::new(warn).off(States::new(warn, warn, warn, off)) }
}
/// The wheel steps the family through the list.
@@ -620,7 +639,7 @@ impl Component for FontPicker<'_> {
let widest = if ribbon { Vec2::new(cx.tokens.size.length.short, widest.y) } else { widest };
let name = cx.words::<FontPickerWords>().list.clone();
let note = self.missing_note(current, &cx.words::<MissingFontsWords>());
Vec2::new(widest.x + reserve(cx.style, &[], &Self::trailing(name, note.is_some())), widest.y)
Vec2::new(widest.x + reserve(&cx.style.field, &[], &Self::trailing(name, note.is_some())), widest.y)
}
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
@@ -628,7 +647,7 @@ impl Component for FontPicker<'_> {
let family = cx.value().cloned().unwrap_or_default();
let note = self.missing_note(&family, &cx.words::<MissingFontsWords>());
let trailing = Self::trailing(name, note.is_some());
let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.flow.is_rtl());
let placed = place(cx.content_rect, &cx.style.field, &[], &trailing, cx.flow.is_rtl());
if let (Some(note), Some(at)) = (note, placed.trailing.first()) {
cx.part(WARNING, *at).tooltip(note);
}
@@ -708,9 +727,10 @@ impl Component for FontPicker<'_> {
let family = cx.value().cloned().unwrap_or_default();
let missing = self.missing_note(&family, &cx.words::<MissingFontsWords>()).is_some();
let trailing = Self::trailing(name.clone(), missing);
let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.env.direction().is_rtl());
let placed = place(cx.content_rect, &cx.style.field, &[], &trailing, cx.env.direction().is_rtl());
if let (true, Some(at)) = (missing, placed.trailing.first()) {
ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON)));
let color = cx.resolve(&cx.style.warning);
ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON)).color(color));
}
ui.face(CHEVRON, IconButton::new(IconId::new(CHEVRON_ICON)).label(name));
}
+75
View File
@@ -400,3 +400,78 @@ fn a_picker_handed_another_catalog_at_the_same_generation_builds_its_family_data
fx.frame(vec![]);
assert_eq!(family_builds(&fx), 1, "the second catalog builds the data once");
}
/// Every non-transparent vertex colour of textured meshes whose centre falls inside `rect`.
fn mesh_tints(shapes: &[egui::Shape], rect: egui::Rect, out: &mut Vec<egui::Color32>) {
for shape in shapes {
match shape {
egui::Shape::Vec(inner) => mesh_tints(inner, rect, out),
egui::Shape::Mesh(mesh) if rect.contains(mesh.calc_bounds().center()) => {
out.extend(mesh.vertices.iter().map(|vertex| vertex.color).filter(|color| color.a() > 0));
}
_ => {}
}
}
}
/// The painted tint colours of the missing-font warning icon in `mode`/`contrast`, enabled or disabled, together with
/// the theme's `status.warn.fg`, `text.normal` and `text.disabled` colours.
fn missing_warning_colors(
mode: craft_theme::Mode,
contrast: craft_theme::Contrast,
enabled: bool,
) -> (Vec<egui::Color32>, egui::Color32, egui::Color32, egui::Color32) {
use craft_ui::contract::Props as _;
use craft_ui::runtime::env::Env;
use egui::Color32;
use std::cell::Cell;
let catalog = catalog_of(&[INTER_REGULAR]);
let seen = Rc::new(Cell::new((None, Color32::TRANSPARENT, Color32::TRANSPARENT, Color32::TRANSPARENT)));
let held = Rc::clone(&seen);
let mut family = "Gotham".to_owned();
let mut fx = Fixture::new(move |ui| {
let color = |[r, g, b, a]: [u8; 4]| Color32::from_rgba_unmultiplied(r, g, b, a);
let env = Env::of(ui);
let tokens = &env.tokens.tokens().color;
let out = FontPicker::new("Font family", Bind::bound(&mut family), &catalog)
.kind(FontPickerKind::Plain)
.shown_as("Inter")
.enabled(enabled)
.show(ui);
held.set((Some(out.edit.response.id), color(tokens.status.warn.fg.0), color(tokens.text.normal.0), color(tokens.text.disabled.0)));
});
fx.theme(mode, contrast);
fx.in_room(Room::Window);
fx.settle();
let (id, warn_fg, text_normal, text_disabled) = seen.get();
let picker = id.expect("the picker");
let mark = fx.part_rect(picker, PartKey::new("missing")).expect("the field carries a mark while the family is not installed");
let mut tints = Vec::new();
mesh_tints(&fx.frame_shapes(), mark, &mut tints);
tints.dedup();
(tints, warn_fg, text_normal, text_disabled)
}
#[trial]
fn the_missing_font_warning_icon_paints_in_status_warn_fg_and_dims_when_disabled() {
use craft_theme::{Contrast, Mode};
for (mode, contrast) in [(Mode::Light, Contrast::Standard), (Mode::Dark, Contrast::Standard), (Mode::Dark, Contrast::High)] {
let (tints, warn_fg, text_normal, _) = missing_warning_colors(mode, contrast, true);
assert_ne!(warn_fg, text_normal, "{mode:?} {contrast:?}: warning ink differs from neutral text ink");
assert!(!tints.is_empty(), "{mode:?} {contrast:?}: the missing-font warning icon paints");
assert!(
tints.iter().all(|tint| *tint == warn_fg),
"{mode:?} {contrast:?}: the warning icon paints in status.warn.fg {warn_fg:?}, not {tints:?}"
);
}
let (tints, warn_fg, _, text_disabled) = missing_warning_colors(Mode::Dark, Contrast::Standard, false);
assert_ne!(text_disabled, warn_fg, "disabled ink differs from warning ink");
assert!(!tints.is_empty(), "a disabled picker still paints its warning icon");
assert!(
tints.iter().all(|tint| *tint == text_disabled),
"a disabled picker paints its warning icon in text.disabled {text_disabled:?}, not {tints:?}"
);
}
+2 -1
View File
@@ -77,6 +77,7 @@ use craft_ui::dialog::{
FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay,
WorkspaceCx, WorkspacePass, serde_fields, set_serde_field,
};
use craft_ui::layout::RowAlign;
use craft_ui::layout_components::Row;
use craft_ui::primitives::Checker;
use craft_ui::rails::{LastUsed, ToolRail, ToolSlot};
@@ -462,7 +463,7 @@ impl LiquifyWorkspace {
.opened(open)
.buttons([FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)])
.footer(|ui, _| {
ui.vertical_centered(|ui| {
let _ = Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| {
let mut guard = this.borrow_mut();
let work: &mut LiquifyWorkspace = &mut guard;
let events = Checkbox::new(Bind::given(work.preview)).label(preview_label.clone()).show(ui).events;
+3 -2
View File
@@ -249,7 +249,8 @@ fn layer_row<'r, T: LayerTree>(cx: &'r PanelContext<'r, T>, id: &T::Id) -> ListR
let contents = cx.options.thumbnail_contents;
let active = cx.selection.active.as_ref() == Some(id);
let mut eye = ToggleCell::eye(EYE, info.visible).name(named(&words.visibility, &info.name));
// A hidden layer's eye box stays empty, also under the pointer (the reference application, photocraft#16321).
let mut eye = ToggleCell::eye(EYE, info.visible).empty_off().name(named(&words.visibility, &info.name));
if let Some(color) = info.label {
eye = eye.fill(DataColor::new(paint_color(color.fill())));
}
@@ -369,7 +370,7 @@ fn sub_row<'r, T: LayerTree>(cx: &'r PanelContext<'r, T>, id: &T::Id, group: Sub
row = row.ink(RowInk::Dimmed);
}
if sub.eye_shown {
row = row.toggle(ToggleCell::eye(EYE, sub.on).name(named(&words.visibility, &sub.label)));
row = row.toggle(ToggleCell::eye(EYE, sub.on).empty_off().name(named(&words.visibility, &sub.label)));
}
let size = cx.options.thumbnail_size;
let header_mask = group == SubRowGroup::SmartFilters && index.is_none() && sub.mask && size != ThumbSize::None;
+1
View File
@@ -3,6 +3,7 @@
pub(crate) mod blend_rows;
pub(crate) mod comps;
pub(crate) mod panel_drag_menu;
pub(crate) mod panel_eye;
pub(crate) mod panel_filter;
pub(crate) mod panel_input;
pub(crate) mod panel_memo;
+47
View File
@@ -0,0 +1,47 @@
//! `LayersPanel` eye boxes: a hidden layer's box stays empty, also under the pointer (photocraft#16321).
use craft_layers::ui::mock::FakeLayers;
use craft_layers::ui::panel::LayersPanel;
use craft_layers::ui::tree::{LayerInfo, LayerKind};
use craft_ui::contract::Tracked;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Rect, Vec2};
use std::cell::RefCell;
use std::rc::Rc;
/// A visible layer over a hidden one.
fn rig() -> Fixture {
let mut tree = FakeLayers::default();
tree.add(None, LayerInfo::new("Shown", LayerKind::Pixel), false);
let mut hidden = LayerInfo::new("Hidden", LayerKind::Pixel);
hidden.visible = false;
tree.add(None, hidden, false);
let tree = Rc::new(RefCell::new(Tracked::new(tree)));
let mut fixture = Fixture::new(move |ui| {
let tree = tree.borrow();
let _ = LayersPanel::new(&tree).show(ui);
});
fixture.room(Vec2::new(420.0, 560.0));
fixture.settle();
fixture
}
/// How many shapes the frame paints wholly inside the eye box `cell`: its icon, not the row's fill around it.
fn drawn_in(fixture: &mut Fixture, cell: Rect) -> usize {
fixture.frame_shapes().iter().filter(|shape| cell.contains_rect(shape.visual_bounding_rect())).count()
}
/// The pointer over a hidden layer's eye box draws nothing there (no crossed-out eye), while a visible layer's box
/// under the pointer draws its eye.
#[trial]
fn a_hidden_layers_eye_box_stays_empty_under_the_pointer() {
let mut fixture = rig();
let shown = fixture.by_label("Visibility Shown").unwrap_or_else(|| panic!("no eye box for Shown")).rect;
let hidden = fixture.by_label("Visibility Hidden").unwrap_or_else(|| panic!("no eye box for Hidden")).rect;
fixture.frame(vec![pointer::moved(shown.center())]).idle(2);
assert!(drawn_in(&mut fixture, shown) > 0, "the visible layer's eye is drawn");
fixture.frame(vec![pointer::moved(hidden.center())]).idle(2);
assert_eq!(drawn_in(&mut fixture, hidden), 0, "the hidden layer's box stays empty under the pointer");
}
+23 -2
View File
@@ -85,6 +85,8 @@ pub struct Gallery<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
caption: CaptionPlace,
/// Each shown tile's rect.
laid: Vec<Rect>,
/// The column of stepper buttons, if shown.
column: Rect,
picked: Option<K>,
menu: Option<ContextMenuRequest<K>>,
}
@@ -118,6 +120,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> {
thumb_size: ThumbSize::Medium,
caption: CaptionPlace::None,
laid: Vec::new(),
column: Rect::NOTHING,
picked: None,
menu: None,
}
@@ -131,7 +134,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> {
self
}
/// One rounded frame on the raised surface around the tiles and the buttons, as the old Word-style ribbon drew
/// One rounded frame on the sunken well surface around the tiles and the buttons, as the old Word-style ribbon drew
/// its Styles gallery.
pub fn framed(mut self) -> Self {
self.framed = true;
@@ -509,6 +512,9 @@ pub struct GalleryStyle {
frame: (StyleColor, StyleColor, f32),
/// The room inside a frame.
inset: f32,
/// The stepper buttons column's track fill and divider.
track: StyleColor,
divider: StyleColor,
}
/// The sizes the gallery's faces measure.
@@ -527,8 +533,10 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for Gallery<'_, K>
let colors = &cx.tokens.color;
GalleryStyle {
metrics: Metrics::new().gap(cx.tokens.space.gap.inline),
frame: (cx.color(colors.surface.raised), cx.color(colors.line.control_edge), cx.tokens.shape.radius.control),
frame: (cx.color(colors.surface.sunken), cx.color(colors.line.control_edge), cx.tokens.shape.radius.control),
inset: cx.tokens.space.gap.inline,
track: cx.color(colors.surface.panel),
divider: cx.color(colors.line.divider),
}
}
@@ -566,6 +574,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for Gallery<'_, K>
let buttons = self.buttons(level);
let rect = rect.shrink2(Vec2::new(self.inset(cx.style), 0.0));
let (column, rest) = Flow::new(rect, cx.flow.is_rtl()).take_end(if buttons { sizes.button.x } else { 0.0 });
self.column = if buttons { column } else { Rect::NOTHING };
self.laid.clear();
for at in 0..shown {
let cell = rest.span(at as f32 * (sizes.tile.x + sizes.gap), sizes.tile.x);
@@ -702,6 +711,18 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for Gallery<'_, K>
if !self.buttons(level) {
return;
}
if self.framed && self.column.is_positive() {
let draw = ui.draw();
let radius = cx.style.frame.2.round().clamp(0.0, 255.0) as u8;
let track_shape = PaintShape::Rect(self.column, CornerRadius::same(radius));
draw.fill(&track_shape, cx.style.track);
draw.stroke(&track_shape, craft_ui::primitives::StrokeWidth::Thin, cx.style.divider);
let height = self.column.height() / 3.0;
let y1 = self.column.min.y + height;
let y2 = self.column.min.y + 2.0 * height;
draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y1), egui::pos2(self.column.right(), y1));
draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y2), egui::pos2(self.column.right(), y2));
}
ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0));
ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last));
ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone()));
+53
View File
@@ -138,3 +138,56 @@ fn a_wide_captioned_gallery_names_its_tiles_under_wide_pictures() {
assert!(name.min.y >= wide.min.y + square.width() / 2.0, "the name {name:?} is under the picture in {wide:?}");
assert!(!plain.iter().any(|(text, _)| text == "Tile 0"), "a plain tile paints no name: {plain:?}");
}
/// A framed gallery paints a sunken well fill over its bounds, and a panel fill over its stepper button track.
#[trial]
fn a_framed_gallery_paints_sunken_well_and_stepper_track() {
use craft_ui::runtime::env::Env;
use egui::Color32;
fn fills(shapes: &[egui::Shape], out: &mut Vec<(egui::Rect, egui::Color32)>) {
for shape in shapes {
match shape {
egui::Shape::Vec(inner) => fills(inner, out),
egui::Shape::Rect(rect) => out.push((rect.rect, rect.fill)),
_ => {}
}
}
}
let colors_and_rect = Rc::new(Cell::new((Rect::NOTHING, Color32::TRANSPARENT, Color32::TRANSPARENT)));
let held = colors_and_rect.clone();
let mut fixture = Fixture::new(move |ui| {
let [sr, sg, sb, sa] = Env::of(ui).tokens.tokens().color.surface.sunken.0;
let [pr, pg, pb, pa] = Env::of(ui).tokens.tokens().color.surface.panel.0;
let sunken = Color32::from_rgba_unmultiplied(sr, sg, sb, sa);
let panel = Color32::from_rgba_unmultiplied(pr, pg, pb, pa);
let paint = |_: &ContentPainterCx, _: Rect| {};
let items: Vec<GalleryItem<'_, usize>> =
(0..10).map(|at| GalleryItem { key: at, label: Label::from(format!("Tile {at}")), face: GalleryFace::Paint(&paint) }).collect();
let out = Gallery::new("Styles", &items, None).tiles(6, 3).framed().show(ui);
held.set((out.response.rect, sunken, panel));
});
fixture.settle();
let (gallery_rect, sunken, panel) = colors_and_rect.get();
assert!(gallery_rect.is_positive(), "the gallery paints a positive rect");
let mut seen = Vec::new();
fills(&fixture.frame_shapes(), &mut seen);
assert!(
seen.iter()
.any(|(rect, fill)| *fill == sunken && rect.contains_rect(gallery_rect.shrink(1.0)) && gallery_rect.expand(1.0).contains_rect(*rect)),
"a sunken fill covers the gallery {gallery_rect:?}: {seen:?}"
);
let up = fixture.by_label("Previous row").expect("the up button shows");
let down = fixture.by_label("Next row").expect("the down button shows");
let more = fixture.by_label("More").expect("the more button shows");
let column = up.rect.union(down.rect).union(more.rect);
let stepper_track =
seen.iter().find(|(rect, fill)| *fill == panel && rect.contains_rect(column.shrink(1.0)) && gallery_rect.contains_rect(*rect));
assert!(stepper_track.is_some(), "a panel fill covers the stepper track column {column:?}: {seen:?}");
}
+6 -7
View File
@@ -7,13 +7,12 @@
//! out), with a markup column beside each page and Hide White Space. [`PageDisplay`] holds both,
//! and [`LayoutOptions`] carries each app's switches ([`LayoutOptions::ACROBAT`],
//! [`LayoutOptions::WORD`]). The screen spacing ([`PageSpacing`]: gap, margin, side gutter, Hide
//! White Space's pad and seam) is not a constant here: the page view reads it from the `pages.*`
//! size tokens (`PageView::style`), which an app overrides in its `sizes.json` (WordCraft's wider
//! gap and no side gutter).
//! White Space's pad and seam) is not a constant here: the page view derives it from the scope's
//! semantic tokens and `ComponentSet` (`Creative` keeps the tool-rail side gutter; `Productivity`
//! uses a wider gap and matching margin/side without the rail gutter).
//!
//! ```ignore
//! let sizes: Vec<Size> = doc.pages.iter().map(|p| p.size()).collect();
//! let spacing = PageView::style(&tokens).spacing;
//! let scale = fit_scale(&sizes, viewport, view.fit, &options, &spacing, view.current).unwrap_or(view.zoom * SCREEN_POINTS_PER_POINT);
//! let laid = place_pages(&sizes, scale, viewport, &options, &spacing);
//! let shown = if options.continuous { 0..sizes.len() } else { shown_row(sizes.len(), view.current, &options) };
@@ -118,9 +117,9 @@ impl LayoutOptions {
}
/// The spacing of a page layout: screen points, except [`white_space_pad`](Self::white_space_pad),
/// which is in points at 100 % zoom and is multiplied by the zoom. The page view takes it from the `pages.*` size tokens
/// (`craft_pages::ui::PageView::style`); this crate's core has no tokens, so the layout functions
/// take it as a value.
/// which is in points at 100 % zoom and is multiplied by the zoom. The page view derives it from the
/// scope's semantic tokens and `ComponentSet`; this crate's core has no tokens, so the layout
/// functions take it as a value.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PageSpacing {
/// Between pages, and between rows (the page view's gap); unused with
+27 -2
View File
@@ -38,6 +38,7 @@ use craft_ui::contract::{Bind, BodyCx, Held, Props as _, Show as _, ShowContaine
use craft_ui::primitives::EditorPurpose;
use craft_ui::primitives::textures::ThumbSource;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::focus::EditSet;
use craft_ui::runtime::memory::Remember as _;
use craft_ui::style::DataColor;
use egui::{Rect, Ui, Vec2, pos2};
@@ -338,6 +339,7 @@ pub struct PageView<'a> {
describer: Option<&'a dyn AccessDescriber>,
paper: DataColor,
editor: Option<EditorPurpose>,
inactive_edits: EditSet,
snap: Option<PageSnap>,
tool_regions: Vec<PageRegion>,
rulers: bool,
@@ -362,6 +364,7 @@ impl<'a> PageView<'a> {
describer: None,
paper,
editor: None,
inactive_edits: EditSet::NONE,
snap: None,
tool_regions: Vec::new(),
rulers: false,
@@ -404,6 +407,13 @@ impl<'a> PageView<'a> {
self
}
/// Edit commands the view's editor part cannot act on right now, forwarded to [`Canvas::inactive_edits`].
#[must_use]
pub fn inactive_edits(mut self, inactive: EditSet) -> Self {
self.inactive_edits = inactive;
self
}
/// The snapping of the coordinates the pointer sets on the view, with its targets in page points. The view places
/// them on the pages that show this pass, drops those of pages outside the shown row and passes the result to the
/// inner canvas.
@@ -455,7 +465,22 @@ impl<'a> PageView<'a> {
}
fn run(self, ui: &mut Ui, rect: Rect, take_room: bool, mut body: impl FnMut(&mut Ui, &PageBody<'_>)) -> PageViewOutput {
let PageView { label, source, state, options, navigation, bodies, describer, paper, editor, snap, tool_regions, rulers, reach } = self;
let PageView {
label,
source,
state,
options,
navigation,
bodies,
describer,
paper,
editor,
inactive_edits,
snap,
tool_regions,
rulers,
reach,
} = self;
let spacing = PageMetrics::new().show_at(ui, Rect::from_min_size(rect.min, Vec2::ZERO)).spacing;
let count = source.page_count();
@@ -485,7 +510,7 @@ impl<'a> PageView<'a> {
let regions: Vec<ToolRegion> = tool_regions.iter().filter_map(|region| placed_region(region, &geo, &frame)).collect();
let mut canvas = Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true).tool_regions(regions);
if let Some(purpose) = editor {
canvas = canvas.editor(purpose);
canvas = canvas.editor(purpose).inactive_edits(inactive_edits);
}
if let Some(snap) = &snap {
canvas = canvas.snap(placed_snap(snap, &geo, &frame));
+26 -9
View File
@@ -5,6 +5,7 @@ use super::{PageSource, PlacedPage};
use crate::layout::PageSpacing;
use crate::ui::access::{AccessDescriber, describe};
use craft_behavior::{Input, Metrics, PixelSize, Sense};
use craft_theme::ComponentSet;
use craft_ui::canvas::DetailPlan;
use craft_ui::canvas::PixelRect;
use craft_ui::contract::{Access, Common, Component, Cx, DisabledLook, MeasureCx, NoValue, Outcome, PaintUi, Role};
@@ -15,8 +16,12 @@ use craft_ui::runtime::memory::Remember as _;
use craft_ui::style::{ComponentStyle, DataColor, StyleCx};
use egui::{Rect, Response, Vec2, pos2};
/// Productivity inter-page gap as a multiple of `space.gap.section`: 18 pt in Compact (Word's gap) and 24 pt in
/// Comfortable.
const PRODUCTIVITY_GAP_RATIO: f32 = 1.5;
/// The style of the page view's spacing: the gap between pages, the margin, the side column, Hide White Space's pad
/// and its seam, all from the tokens.
/// and its seam, from the tokens and the scope's [`ComponentSet`].
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct PageMetricsStyle {
@@ -74,14 +79,26 @@ impl Component for PageMetrics {
fn style(cx: &StyleCx<'_>, _: PageMetricsStyleKey) -> PageMetricsStyle {
let tokens = cx.tokens;
let pad = tokens.space.pad;
PageMetricsStyle {
metrics: Metrics::new(),
gap: tokens.space.gap.section,
margin: pad.roomy,
side: tokens.size.rail.width,
white_space_pad: tokens.space.gap.inline,
seam: tokens.stroke.thin,
match cx.set() {
ComponentSet::Creative => PageMetricsStyle {
metrics: Metrics::new(),
gap: tokens.space.gap.section,
margin: tokens.space.pad.roomy,
side: tokens.size.rail.width,
white_space_pad: tokens.space.gap.inline,
seam: tokens.stroke.thin,
},
ComponentSet::Productivity => {
let gap = tokens.space.gap.section * PRODUCTIVITY_GAP_RATIO;
PageMetricsStyle {
metrics: Metrics::new(),
gap,
margin: gap,
side: gap,
white_space_pad: tokens.space.gap.stack,
seam: tokens.stroke.thin,
}
}
}
}
+162 -2
View File
@@ -3,18 +3,21 @@
use craft_behavior::geometry::{CropBox, SnapKind, SnapOptions, SnapTarget};
use craft_behavior::kurbo;
use craft_behavior::{Axis, CancelReason, CanvasView};
use craft_pages::layout::{Fit, LayoutOptions, PageDisplay};
use craft_behavior::{Axis, CancelReason, CanvasView, EditCommand};
use craft_pages::layout::{Fit, LayoutOptions, PageDisplay, PagedLayout};
use craft_pages::ui::fixtures::{DemoPages, PAPER};
use craft_pages::ui::{
PagePreview, PageRegion, PageSnap, PageSource, PageView, PageViewState, PageViewWords, PlacedPage, ReadingNav, ReadingState, ReadingView,
};
use craft_theme::ComponentSet;
use craft_ui::canvas::{CanvasTool, CropOverlay, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer};
use craft_ui::contract::{Bind, Role, Show as _};
use craft_ui::primitives::textures::TextureStoreOptions;
use craft_ui::primitives::{Draw, EditorPurpose};
use craft_ui::runtime::commands::{CommandState, EditCommands, resolve};
use craft_ui::runtime::env::Env;
use craft_ui::runtime::focus::EditSet;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Key, Modifiers, pos2, vec2};
use std::cell::{Cell, RefCell};
@@ -955,3 +958,160 @@ fn go_to_a_point_inside_a_page_puts_it_at_the_top() {
assert_eq!(first, Some(5), "the first page in view is the one gone to");
assert!((offset - at).abs() < 0.01, "the view's top {offset} is the point gone to, {at}");
}
/// Lays out three pages under `set` with `start`, returning the layout and the scope's `space.gap.section` token.
fn layout_in_set(set: ComponentSet, options: LayoutOptions, start: PageViewState, bodies: Option<&'static [(f64, f64)]>) -> (PagedLayout, f32) {
let state = Rc::new(RefCell::new(start));
let seen: Rc<RefCell<(PagedLayout, f32)>> = Rc::default();
let (kept, recorded) = (Rc::clone(&state), Rc::clone(&seen));
let pages = DemoPages::new(3);
let mut fixture = Fixture::new(move |ui| {
let section_gap = Env::of(ui).tokens.space.gap.section;
let mut now = kept.borrow().clone();
let mut view = PageView::new("Pages", &pages, &mut now, PAPER).options(options);
if let Some(bodies) = bodies {
view = view.bodies(bodies);
}
let out = view.show(ui, |_, _| ());
*recorded.borrow_mut() = (out.layout, section_gap);
*kept.borrow_mut() = now;
});
fixture.set(set);
fixture.room(vec2(900.0, 600.0));
fixture.settle();
seen.borrow().clone()
}
/// The productivity component set gives pages a wider inter-page gap, no tool-rail side gutter under Fit Width (without
/// overflowing the viewport), and wider Hide White Space padding than the creative set, while leaving `space.gap.section`
/// untouched for other components.
#[trial]
fn the_component_set_picks_the_page_spacing_without_changing_section_gap() {
let fixed = state_with(|s| {
s.fit = Fit::None;
s.zoom = 1.0;
s.display = PageDisplay::Columns;
});
let (creative, creative_section) = layout_in_set(ComponentSet::Creative, LayoutOptions::WORD, fixed.clone(), None);
let (productivity, productivity_section) = layout_in_set(ComponentSet::Productivity, LayoutOptions::WORD, fixed, None);
let creative_gap = creative.rects[1].y0 - creative.rects[0].y1;
let productivity_gap = productivity.rects[1].y0 - productivity.rects[0].y1;
assert_eq!(productivity_section, creative_section, "space.gap.section is unchanged by the component set");
assert!(productivity_gap > creative_gap, "productivity inter-page gap ({productivity_gap}) is wider than creative ({creative_gap})");
assert!(
productivity.rects[0].y0 > creative.rects[0].y0,
"productivity top margin ({}) is wider than creative ({})",
productivity.rects[0].y0,
creative.rects[0].y0
);
let fit_width = state_with(|s| {
s.fit = Fit::Width;
s.display = PageDisplay::Columns;
});
let (creative_fit, _) = layout_in_set(ComponentSet::Creative, LayoutOptions::WORD, fit_width.clone(), None);
let (productivity_fit, _) = layout_in_set(ComponentSet::Productivity, LayoutOptions::WORD, fit_width, None);
assert!(
productivity_fit.rects[0].width() > creative_fit.rects[0].width(),
"productivity Fit Width fills more of the viewport ({}) than creative with its rail gutter ({})",
productivity_fit.rects[0].width(),
creative_fit.rects[0].width()
);
assert!(
productivity_fit.size.width <= 900.0 + 0.5,
"productivity Fit Width stays within the viewport width without horizontal overflow: {}",
productivity_fit.size.width
);
const BODIES: [(f64, f64); 3] = [(72.0, 720.0); 3];
let hidden = state_with(|s| {
s.fit = Fit::None;
s.zoom = 1.0;
s.display = PageDisplay::Single;
s.hide_white_space = true;
});
let (creative_hidden, _) = layout_in_set(ComponentSet::Creative, LayoutOptions::ACROBAT, hidden.clone(), Some(&BODIES));
let (productivity_hidden, _) = layout_in_set(ComponentSet::Productivity, LayoutOptions::ACROBAT, hidden, Some(&BODIES));
assert!(
productivity_hidden.bands[1].0 < creative_hidden.bands[1].0 && productivity_hidden.bands[1].1 > creative_hidden.bands[1].1,
"productivity Hide White Space keeps more pad around the text body: {:?} vs {:?}",
productivity_hidden.bands[1],
creative_hidden.bands[1]
);
}
/// Switching the component set updates the page view's inter-page spacing on the frame of the change and settles.
#[trial]
fn a_component_set_change_updates_the_page_view_spacing() {
let state = Rc::new(RefCell::new(state_with(|s| {
s.fit = Fit::None;
s.zoom = 1.0;
s.display = PageDisplay::Columns;
})));
let gap = Rc::new(Cell::new(0.0_f64));
let (kept, seen) = (Rc::clone(&state), Rc::clone(&gap));
let pages = DemoPages::new(3);
let mut fixture = Fixture::new(move |ui| {
let mut now = kept.borrow().clone();
let out = PageView::new("Pages", &pages, &mut now, PAPER).options(LayoutOptions::WORD).show(ui, |_, _| ());
seen.set(out.layout.rects[1].y0 - out.layout.rects[0].y1);
*kept.borrow_mut() = now;
});
fixture.set(ComponentSet::Creative);
fixture.room(vec2(900.0, 600.0));
fixture.settle();
let creative_gap = gap.get();
fixture.set(ComponentSet::Productivity);
fixture.frame(Vec::new());
let productivity_gap = gap.get();
assert!(
productivity_gap > creative_gap,
"switching to productivity widens the page gap on the frame of the change: {productivity_gap} vs {creative_gap}"
);
fixture.idle(1);
assert_eq!(gap.get(), productivity_gap, "an idle frame after the switch keeps the new gap");
}
/// `PageView::inactive_edits` forwards to its inner canvas editor: Cut resolves disabled while inactive and enabled
/// once active, and Undo/Redo fall through to app command states while inactive.
#[trial]
fn page_view_forwards_inactive_edits_to_its_editor_canvas() {
let state = Rc::new(RefCell::new(PageViewState::default()));
let inactive = Rc::new(Cell::new(EditSet::NONE.with(EditCommand::Cut).with(EditCommand::Undo).with(EditCommand::Redo)));
let (kept_state, kept_inactive) = (Rc::clone(&state), Rc::clone(&inactive));
let pages = DemoPages::new(2);
let mut fixture = Fixture::new(move |ui| {
let mut now = kept_state.borrow().clone();
PageView::new("Pages", &pages, &mut now, PAPER)
.options(LayoutOptions::ACROBAT)
.editor(EditorPurpose::Text)
.inactive_edits(kept_inactive.get())
.show(ui, |_, _| ());
*kept_state.borrow_mut() = now;
});
fixture.command_state(EditCommands::Cut, CommandState::new().enabled(true));
fixture.command_state(EditCommands::Undo, CommandState::new().enabled(false));
fixture.command_state(EditCommands::Redo, CommandState::new().enabled(false));
fixture.room(vec2(900.0, 600.0));
fixture.settle();
let canvas_rect = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas").rect;
fixture.click_at(canvas_rect.center());
fixture.settle();
assert!(fixture.focused().is_some(), "clicking the page view focuses its editor canvas");
assert!(!resolve(fixture.ctx(), EditCommands::Cut).enabled, "inactive Cut resolves disabled on focused PageView");
assert!(!resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo falls through to disabled app state");
assert!(!resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo falls through to disabled app state");
fixture.command_state(EditCommands::Undo, CommandState::new().enabled(true));
fixture.command_state(EditCommands::Redo, CommandState::new().enabled(true));
fixture.settle();
assert!(resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo follows enabled app state");
assert!(resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo follows enabled app state");
inactive.set(EditSet::NONE.with(EditCommand::Undo).with(EditCommand::Redo));
fixture.settle();
assert!(resolve(fixture.ctx(), EditCommands::Cut).enabled, "active Cut resolves enabled on focused PageView");
}
+12 -2
View File
@@ -40,7 +40,7 @@ use craft_ui::contract::{
use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState, PaintShape, StrokeWidth};
use craft_ui::runtime::commands::ClipItem;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::focus::KeyUse;
use craft_ui::runtime::focus::{FocusPolicy, KeyUse};
use craft_ui::runtime::pending::Pending;
use craft_ui::style::{ComponentStyle, StyleColor, StyleCx};
use egui::{Pos2, Rect, Response, Vec2};
@@ -445,6 +445,14 @@ fn char_at(lines: &[HostLine], pos: TextPos) -> usize {
line.chars.start + line.text[..byte].chars().count()
}
/// The I-beam is the editor's over its text and while its own press is held; elsewhere the canvas's tool or the rest
/// of the UI sets the pointer.
fn show_i_beam(cx: &mut Cx<'_, TextEditor<'_>>, phase: &PressPhase, vertical: bool) {
if !matches!(phase, PressPhase::Idle) {
cx.cursor(if vertical { CursorIcon::VerticalText } else { CursorIcon::Text }, CursorPriority::Hover);
}
}
/// The clipboard's text when the pass's input asks to paste and the clipboard has it ready.
fn pasted_text(cx: &mut Cx<'_, TextEditor<'_>>, inputs: &[EditorInput]) -> Option<std::sync::Arc<str>> {
if !inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))) {
@@ -461,6 +469,8 @@ impl Component for TextEditor<'_> {
const INPUT: craft_ui::contract::Input = craft_ui::contract::Input::Editor;
/// Escape always ends the session, so the editor keeps it from its row and from the shortcuts while focused.
const KEYS: KeyUse = KeyUse::CODE.with_claims(&[ESCAPE]);
/// When the session ends, focus goes back to the stop it came from (the canvas), not to the stop before the editor.
const FOCUS_SCOPE: FocusPolicy = FocusPolicy::TAB_LAYER;
type Style = TextEditorStyle;
type Output = TextEditorOutput;
@@ -618,7 +628,7 @@ impl Component for TextEditor<'_> {
if let Some(text) = copied {
cx.clipboard().put(&[ClipItem::Text(text.into())]);
}
cx.cursor(if vertical { CursorIcon::VerticalText } else { CursorIcon::Text }, CursorPriority::Hover);
show_i_beam(cx, &press.phase, vertical);
if done.changed {
cx.propose(selection);
} else if selection != before {
+67
View File
@@ -210,6 +210,25 @@ fn a_secondary_click_on_the_text_reports_a_context_click_and_starts_no_drag() {
assert_eq!(editor.commits.get() + editor.cancels.get(), 0, "the session stays open");
}
/// The I-beam is the editor's only over its text and while its own press is held: elsewhere the pointer is the
/// canvas's or the rest of the UI's.
#[trial]
fn the_i_beam_shows_over_the_text_and_during_its_drag_but_not_elsewhere() {
let mut editor = session("abc def", None);
editor.focus();
let i_beam = Some(craft_behavior::Cursor::System(craft_behavior::CursorIcon::Text));
let cursor = |editor: &Session| craft_ui::runtime::cursor::current(editor.fixture.ctx());
let (on_text, away) = (pos2(40.0, 10.0), pos2(300.0, 300.0));
editor.fixture.frame(vec![pointer::moved(on_text)]).settle();
assert_eq!(cursor(&editor), i_beam, "over the text");
editor.fixture.frame(vec![pointer::moved(away)]).settle();
assert_ne!(cursor(&editor), i_beam, "away from the text, with the session open");
editor.fixture.frame(vec![pointer::moved(on_text)]).frame(vec![pointer::press(on_text)]).frame(vec![pointer::moved(away)]);
assert_eq!(cursor(&editor), i_beam, "a drag that leaves the text keeps it");
editor.fixture.frame(vec![pointer::release(away)]).settle();
assert_ne!(cursor(&editor), i_beam, "after the release");
}
fn preedit(text: &str) -> Event {
Event::Ime(ImeEvent::Preedit { text: text.to_owned(), active_range_chars: None })
}
@@ -346,3 +365,51 @@ fn formatting_keys_follow_the_flow_and_fall_back_to_caret_moves() {
assert!(!plain.host.borrow().styles.is_empty(), "the host was asked for the leading step");
assert_eq!(plain.selection.borrow().caret, before.saturating_sub(LINE), "the step the host did not take moved the caret a line up");
}
/// #15555: a session the app ends (Cmd+Enter, then the editor is not shown) on a canvas with rulers hands the focus back
/// to the canvas it came from, not to the stop before the editor (the rulers' corner, whose arrows move the zero point),
/// and the view stays where it was. Without rulers the canvas is that stop anyway.
#[trial]
fn an_ended_session_returns_the_focus_to_the_canvas_and_the_view_stays() {
const EDITOR: craft_behavior::DocKey = craft_behavior::DocKey::new("trial.type-editor");
use craft_ui::canvas::Rulers;
use craft_ui::contract::Props as _;
use craft_ui::runtime::focus::{FocusTarget, request};
use craft_ui::testing::access::{focused_key, name};
for rulers in [true, false] {
let editing = Rc::new(Cell::new(false));
let view = Rc::new(Cell::new(None::<CanvasView>));
let (shown_editing, shown_view) = (Rc::clone(&editing), Rc::clone(&view));
let mut host = Host { text: "abc".to_owned(), ..Host::default() };
let mut selection = TextSelection::caret_at(3);
let mut zero = Point::ZERO;
let mut fixture = Fixture::new(move |ui| {
let room = ui.available_rect_before_wrap();
let given = shown_view.get().unwrap_or_else(|| CanvasView::new(room, Point::new(100.0, 100.0), 1.0));
let strips = rulers.then(|| Rulers::new("Rulers", Bind::bound(&mut zero)));
let canvas = Canvas::new("Document").view(given).with_rulers(strips).show(ui, |ui, body| {
if shown_editing.get() {
let bounds = Rect::from_min_size(body.rect.min + vec2(40.0, 40.0), vec2(200.0, 20.0));
drop(TextEditor::new("Text", &mut host, Bind::bound(&mut selection)).doc_key(EDITOR).show_at(ui, bounds));
}
});
shown_view.set(Some(canvas.output.view.unwrap_or(given)));
});
fixture.room(vec2(600.0, 400.0)).settle();
let focused = |fixture: &Fixture| name(fixture.tree(), focused_key(fixture.tree())).map(str::to_owned);
// A press on the canvas focuses it, and the session that press starts asks for the editor's focus.
fixture.click_at(pos2(400.0, 300.0)).settle();
assert_eq!(focused(&fixture).as_deref(), Some("Document"), "rulers {rulers}: the press focused the canvas");
editing.set(true);
fixture.settle();
request(fixture.ctx(), FocusTarget::Doc(EDITOR));
fixture.settle();
assert_eq!(focused(&fixture).as_deref(), Some("Text"), "rulers {rulers}: the editor took the focus");
let before = view.get();
editing.set(false);
fixture.settle();
assert_eq!(focused(&fixture).as_deref(), Some("Document"), "rulers {rulers}: the focus went back to the canvas");
assert_eq!(view.get(), before, "rulers {rulers}: the view stays");
}
}
+9 -2
View File
@@ -107,7 +107,7 @@ use crate::contract::{
use crate::primitives::{EditorPurpose, ImeStamp};
use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _};
use crate::runtime::env::Label;
use crate::runtime::focus::KeyUse;
use crate::runtime::focus::{EditSet, KeyUse};
use crate::runtime::lock_keys;
use crate::runtime::measure;
use crate::runtime::motion::{Animate as _, spec};
@@ -217,6 +217,12 @@ pub struct Canvas<'a> {
/// does not apply. The body reports its editor state through [`ToolPass::editor`].
#[prop]
editor: Option<EditorPurpose>,
/// Edit commands the canvas's editor part cannot act on right now (for instance Cut and Copy with nothing
/// selected, or Undo and Redo with no editor-local history). Applied to [`KeyUse::inactive`] while
/// [`editor`](Self::editor) is set: Cut, Copy, Paste and Select All stay the editor's and resolve disabled; Undo
/// and Redo fall through to the app command's state. Ignored without [`editor`](Self::editor).
#[prop]
inactive_edits: EditSet,
/// The editor part's inputs of this pass, taken once in `update`: `tool_pass` is built from a shared `Cx`.
editor_input: Arc<[EditorInput]>,
/// The rulers' units and zero point, published to the body in its [`CanvasSpace`].
@@ -308,6 +314,7 @@ impl<'a> Canvas<'a> {
ruler_output: None,
keys_to_body: false,
editor: None,
inactive_edits: EditSet::NONE,
editor_input: Arc::from([]),
pasteboard: PasteboardColor::Default,
precise_cursors: false,
@@ -825,7 +832,7 @@ impl Component for Canvas<'_> {
/// nudges. It still marks its window as showing a document.
fn keys(&self) -> KeyUse {
match self.editor {
Some(_) => KeyUse::of(Input::Editor).with_chrome_key(true).with_moves(),
Some(_) => KeyUse::of(Input::Editor).with_chrome_key(true).with_moves().with_inactive(self.inactive_edits),
None => Self::KEYS,
}
}
+122 -26
View File
@@ -3,9 +3,13 @@
//! thickness at rest and under the pointer. Document chrome uses inset thumbs, step buttons and a corner.
//! The thumb is the visible fraction of
//! the scrollable extent (the document, plus wherever the view has been scrolled past it); drag it to scroll, or press
//! the track to page by one screenful. With overscroll on, a document smaller than the window can also be scrolled from
//! one edge of the window to the other. With overscroll off the app clamps the view before it draws
//! ([`CanvasScrollbars::clamp`]).
//! the track to page by one screenful. With overscroll on, the extent also takes in the pasteboard around the document,
//! as in the reference application: at either end of a track [`KEPT_IN_VIEW`] points of the document stay in view at
//! the opposite edge, whether the document is larger or smaller than the window. With overscroll off the app clamps the
//! view before it draws ([`CanvasScrollbars::clamp`]).
//!
//! A thumb drag keeps the extent it began with and follows the pointer from the press: the thumb stays under the
//! pointer, also after the pointer went past a track's end and came back.
//!
//! The bars measure the view along the screen axes, so on a rotated view they show the extent of the unrotated
//! document.
@@ -44,6 +48,10 @@ const ARROW_STEP_PIXELS: f64 = 16.0;
const ARROW_HOLD_DELAY: f64 = 0.4;
const ARROW_HOLD_INTERVAL: f64 = 0.06;
/// With overscroll on, how much of the document stays in view, in screen points, when a thumb is at either end of its
/// track: the reference application keeps 100 screen pixels at every zoom, on both axes.
const KEPT_IN_VIEW: f64 = 100.0;
/// The popup of the tip beside a dragged vertical thumb.
const TIP: &str = "tip";
@@ -76,26 +84,30 @@ struct Span {
/// First and last visible coordinate.
v0: f64,
v1: f64,
/// [`KEPT_IN_VIEW`] in document units on this axis.
kept: f64,
}
impl Span {
/// The axis of a view: `size` screen points at `zoom` around `center`.
fn of(len: f64, center: f64, size: f64, zoom: f64) -> Option<Span> {
/// The axis of a view: `size` screen points at `zoom` around `center`; `kept` is [`KEPT_IN_VIEW`] in the same
/// points (the horizontal axis divides both by the pixel aspect).
fn of(len: f64, center: f64, size: f64, zoom: f64, kept: f64) -> Option<Span> {
let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { return None };
let half = size / zoom / 2.0;
let span = Span { len, v0: center - half, v1: center + half };
let span = Span { len, v0: center - half, v1: center + half, kept: kept / zoom };
(span.len.is_finite() && span.len > 0.0 && span.v0.is_finite() && span.v1.is_finite() && span.v1 > span.v0).then_some(span)
}
/// The scrollable extent: the document and the visible span. With `overscroll`, a document shorter than the span
/// may slide edge to edge within it.
/// The scrollable extent: the document and the visible span. With `overscroll` also the pasteboard on both sides,
/// up to where only [`KEPT_IN_VIEW`] of the document (all of a shorter one) is left in view at the opposite edge.
fn content(&self, overscroll: bool) -> Range<f64> {
let (lo, hi) = (self.v0.min(0.0), self.v1.max(self.len));
if !overscroll {
return lo..hi;
}
let visible = self.v1 - self.v0;
lo.min(self.len - visible)..hi.max(visible)
let kept = if self.kept.is_finite() { self.kept.clamp(0.0, self.len) } else { self.len };
let room = (self.v1 - self.v0 - kept).max(0.0);
lo.min(-room)..hi.max(self.len + room)
}
fn scroll(&self, overscroll: bool) -> ScrollSpan {
@@ -142,6 +154,26 @@ impl Bar {
}
}
/// A pressed thumb: the extent and the visible range it was pressed at. Its drag maps the pointer's movement from the
/// press onto that extent, so the track does not grow or shrink under the pointer while the view moves, and the thumb
/// stays under the pointer.
#[derive(Clone, Debug, Default, PartialEq)]
struct HeldThumb {
horizontal: bool,
content: Range<f64>,
visible: Range<f64>,
}
impl HeldThumb {
fn of(axis: Axis, span: &ScrollSpan) -> Self {
HeldThumb { horizontal: axis == Axis::X, content: span.content.clone(), visible: span.visible.clone() }
}
fn on(&self, axis: Axis) -> bool {
self.horizontal == (axis == Axis::X)
}
}
/// The bars of a view over a document, in the order horizontal, vertical.
struct Bars {
horizontal: Option<Bar>,
@@ -198,6 +230,11 @@ fn paint_arrow(draw: &Draw<'_>, rect: Rect, axis: Axis, after: bool, color: Styl
draw.stroke(&path, StrokeWidth::Thin, color);
}
/// The length of a scroll bar's track along `axis`.
fn scroll_track_length(track: Rect, axis: Axis) -> f32 {
if axis == Axis::X { track.width() } else { track.height() }
}
/// How the document's x axis runs on screen: with the view flipped, backwards.
fn along_x(view: &CanvasView, width: f64, c: f64) -> f64 {
if view.flip_x { width - c } else { c }
@@ -208,20 +245,43 @@ fn aspect(view: &CanvasView) -> f64 {
}
impl Bars {
/// The bars inside `rect` (bottom and right edges), `width` thick, for `view` over the document `doc`.
fn of(view: &CanvasView, doc: DocRect, overscroll: bool, horizontal: bool, rect: Rect, style: &ScrollbarsStyle) -> Bars {
/// The bars inside `rect` (bottom and right edges), `width` thick, for `view` over the document `doc`. A `held`
/// thumb's bar keeps the extent the thumb was pressed at.
fn of(
view: &CanvasView,
doc: DocRect,
overscroll: bool,
horizontal: bool,
rect: Rect,
style: &ScrollbarsStyle,
held: Option<&HeldThumb>,
) -> Bars {
let document_chrome = style.document.is_some();
let mut width = style.look.thickness;
if document_chrome {
width = width.min(rect.width().max(0.0)).min(rect.height().max(0.0));
}
let x = Span::of(doc.width(), along_x(view, doc.width(), view.center.x - doc.x0), f64::from(view.rect.width()) / aspect(view), view.zoom)
.filter(|_| horizontal);
let y = Span::of(doc.height(), view.center.y - doc.y0, f64::from(view.rect.height()), view.zoom);
let x = Span::of(
doc.width(),
along_x(view, doc.width(), view.center.x - doc.x0),
f64::from(view.rect.width()) / aspect(view),
view.zoom,
KEPT_IN_VIEW / aspect(view),
)
.filter(|_| horizontal);
let y = Span::of(doc.height(), view.center.y - doc.y0, f64::from(view.rect.height()), view.zoom, KEPT_IN_VIEW);
let right = if y.is_some() { rect.right() - width } else { rect.right() };
let bottom = if x.is_some() { rect.bottom() - width } else { rect.bottom() };
let corner = (document_chrome && x.is_some() && y.is_some()).then(|| Rect::from_min_max(pos2(right, bottom), rect.max));
let bar = |span: Option<Span>, axis, rect| span.map(|span| Bar::new(rect, axis, span.scroll(overscroll), document_chrome));
let bar = |span: Option<Span>, axis, rect| {
span.map(|span| {
let mut scroll = span.scroll(overscroll);
if let Some(held) = held.filter(|held| held.on(axis)) {
scroll.content = held.content.start.min(scroll.visible.start)..held.content.end.max(scroll.visible.end);
}
Bar::new(rect, axis, scroll, document_chrome)
})
};
Bars {
horizontal: bar(x, Axis::X, Rect::from_min_max(pos2(rect.left(), bottom), pos2(right, rect.bottom()))),
vertical: bar(y, Axis::Y, Rect::from_min_max(pos2(right, rect.top()), pos2(rect.right(), bottom))),
@@ -298,13 +358,24 @@ pub struct CanvasScrollbars<'a> {
/// thumb on the reading-start side.
#[prop]
tip: Option<&'a dyn Fn(&CanvasView) -> Label>,
/// The thumb pressed in this pass, as `update` read it from the press slot, for `paint` and `access`.
held: Option<HeldThumb>,
}
impl<'a> CanvasScrollbars<'a> {
/// Scroll bars named `label` that edit `view`, a view over the document `document` (document units).
pub fn new(label: impl Into<Label>, view: Bind<'a, CanvasView>, document: DocRect) -> Self {
CanvasScrollbars { common: Common::new(), view, document, overscroll: false, vertical_only: false, document_chrome: false, tip: None }
.label(label)
CanvasScrollbars {
common: Common::new(),
view,
document,
overscroll: false,
vertical_only: false,
document_chrome: false,
tip: None,
held: None,
}
.label(label)
}
/// Applies overscroll off to `view` over the document `doc`: the view can't leave the document's edges, and a
@@ -353,8 +424,8 @@ impl<'a> CanvasScrollbars<'a> {
changed
}
fn bars(&self, view: &CanvasView, rect: Rect, style: &ScrollbarsStyle) -> Bars {
Bars::of(view, self.document, self.overscroll, !self.vertical_only, rect, style)
fn bars(&self, view: &CanvasView, rect: Rect, style: &ScrollbarsStyle, held: Option<&HeldThumb>) -> Bars {
Bars::of(view, self.document, self.overscroll, !self.vertical_only, rect, style, held)
}
}
@@ -400,7 +471,8 @@ impl Component for CanvasScrollbars<'_> {
/// The bars: `PartsCx::scroll` runs the thumb drag and the page press in the pipeline.
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
let Some(view) = cx.value().copied() else { return };
let bars = self.bars(&view, rect, cx.style);
let held = cx.press_slot::<HeldThumb>();
let bars = self.bars(&view, rect, cx.style, held.as_ref());
for (key, axis, bar) in bars.each() {
cx.scroll(key, bar.track, axis, bar.span.clone());
for (part, rect, _) in bar.arrows(key, axis) {
@@ -424,7 +496,10 @@ impl Component for CanvasScrollbars<'_> {
tip.close(cx);
}
let Some(view) = cx.value().copied() else { return };
let bars = self.bars(&view, cx.rect, cx.style);
let held = cx.press_slot::<HeldThumb>().clone();
let bars = self.bars(&view, cx.rect, cx.style, held.as_ref());
let rtl = cx.flow.is_rtl();
let min_thumb = cx.style.look.min_thumb;
for (key, axis, bar) in bars.each() {
for (part, rect, after) in bar.arrows(key, axis) {
if arrow_pressed(cx, part, rect) {
@@ -441,18 +516,39 @@ impl Component for CanvasScrollbars<'_> {
}
let phase = cx.part(thumb_of(key)).press.phase;
match phase {
// The press keeps the extent the thumb was pressed at for its drag.
PressPhase::Down { .. } => *cx.press_slot::<HeldThumb>() = Some(HeldThumb::of(axis, &bar.span)),
PressPhase::DragStart { .. } => cx.begin(),
PressPhase::Release { click: false, .. } => cx.commit(),
_ => {}
}
let Some(range) = cx.scroll_moved(key) else { continue };
let range = match phase {
// The thumb follows the pointer from the press, over the extent it was pressed at, so it stays under the
// pointer: past a track's end the view waits until the pointer comes back to the thumb.
PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } => {
let Some(held) = held.as_ref().filter(|held| held.on(axis)) else { continue };
let moved_by = pos - start.origin;
let along = match axis {
Axis::X if rtl => -moved_by.x,
Axis::X => moved_by.x,
_ => moved_by.y,
};
let pressed = ScrollSpan::new(held.content.clone(), held.visible.clone());
craft_behavior::scroll::drag(&pressed, scroll_track_length(bar.track, axis), min_thumb, along)
}
_ => {
let Some(range) = cx.scroll_moved(key) else { continue };
range
}
};
let next = moved(&view, self.document, axis, &range);
if matches!(phase, PressPhase::Drag { .. }) {
if phase.is_drag() {
cx.propose(next);
} else if next != view {
cx.set(next);
}
}
self.held = held;
}
/// The tip beside the dragged vertical thumb, on the reading-start side, in a tooltip layer of the bars' own: the
@@ -471,7 +567,7 @@ impl Component for CanvasScrollbars<'_> {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let Some(view) = cx.value().copied() else { return };
let style = cx.style;
let bars = self.bars(&view, cx.rect, style);
let bars = self.bars(&view, cx.rect, style, self.held.as_ref());
let draw = ui.draw();
let rtl = cx.flow.is_rtl();
let fill = |rect, color| draw.fill(&PaintShape::Rect(rect, CornerRadius::ZERO), color);
@@ -498,7 +594,7 @@ impl Component for CanvasScrollbars<'_> {
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let Some(view) = cx.value().copied() else { return };
let words = cx.words::<CanvasWords>();
let bars = self.bars(&view, cx.rect, cx.style);
let bars = self.bars(&view, cx.rect, cx.style, self.held.as_ref());
for (key, axis, bar) in bars.each() {
let name = if axis == Axis::X { &words.scroll_horizontal } else { &words.scroll_vertical };
let room = (bar.span.content.end - bar.span.content.start - (bar.span.visible.end - bar.span.visible.start)).max(0.0);
+71 -2
View File
@@ -2,12 +2,15 @@
//! body through its `ToolPass`.
use craft_behavior::kurbo::{Point, Size};
use craft_behavior::{CanvasView, EditorInput, Proposal, TextPos};
use craft_behavior::{CanvasView, EditCommand, EditorInput, Proposal, TextPos};
use craft_ui::buttons::Button;
use craft_ui::canvas::{Canvas, tool_pass};
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::primitives::{EditorPurpose, EditorState};
use craft_ui::runtime::access::Role;
use craft_ui::runtime::focus;
use craft_ui::runtime::commands::{CommandRef, CommandState, EditCommands, resolve};
use craft_ui::runtime::focus::{self, EditSet};
use craft_ui::runtime::frame;
use craft_ui::testing::focus::egui_focused;
use craft_ui::testing::{Fixture, trial};
use craft_ui::text::TextField;
@@ -144,3 +147,69 @@ fn focus_has_answers_for_a_canvas_whose_editor_part_holds_focus() {
assert!(focus::has(fixture.ctx(), field_id), "a click on the field moves focus there");
assert!(!focus::has(fixture.ctx(), canvas_id), "and the canvas has it no more");
}
/// Guards `Canvas::inactive_edits` with an editor part: inactive Cut stays owned by the editor and resolves disabled
/// (even when the app's Cut is enabled), inactive Undo and Redo fall through to app command states and fire the app
/// command while keeping canvas focus, and a separate text field resolves Cut from its own selection independently.
#[trial]
fn inactive_edits_disable_cut_and_let_undo_and_redo_fall_through_to_app_state() {
let inactive = Rc::new(Cell::new(EditSet::NONE.with(EditCommand::Cut).with(EditCommand::Undo).with(EditCommand::Redo)));
let text = Rc::new(RefCell::new("hello".to_owned()));
let ids: Rc<Cell<Option<(Id, Id, Id)>>> = Rc::default();
let (held_inactive, held_text, shown_ids) = (Rc::clone(&inactive), Rc::clone(&text), Rc::clone(&ids));
let mut fixture = Fixture::new(move |ui| {
let cut = Button::command(EditCommands::Cut).show(ui).id;
let undo = Button::command(EditCommands::Undo).show(ui).id;
let _ = TextField::new("Notes", Bind::bound(&mut *held_text.borrow_mut())).show(ui);
let room = ui.available_rect_before_wrap();
let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0);
let output = canvas(view).inactive_edits(held_inactive.get()).show_at(ui, room, |_, _| {});
shown_ids.set(Some((output.output.response.id, cut, undo)));
});
fixture.command_state(EditCommands::Cut, CommandState::new().enabled(true));
fixture.command_state(EditCommands::Undo, CommandState::new().enabled(false));
fixture.command_state(EditCommands::Redo, CommandState::new().enabled(false));
fixture.room(ROOM);
fixture.settle();
let (canvas_id, cut_id, undo_id) = ids.get().expect("the canvas and buttons showed");
let canvas_rect = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas").rect;
fixture.click_at(canvas_rect.center());
fixture.settle();
assert!(focus::has(fixture.ctx(), canvas_id), "the canvas has focus");
assert!(!resolve(fixture.ctx(), EditCommands::Cut).enabled, "inactive Cut resolves disabled despite app Cut state");
assert!(fixture.tree().is_disabled(cut_id), "the Cut button reflects the inactive editor command");
assert!(!resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo falls through to disabled app state");
assert!(!resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo falls through to disabled app state");
assert!(fixture.tree().is_disabled(undo_id), "the Undo button is disabled while app Undo is disabled");
fixture.command_state(EditCommands::Undo, CommandState::new().enabled(true));
fixture.command_state(EditCommands::Redo, CommandState::new().enabled(true));
fixture.settle();
assert!(resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo follows enabled app state");
assert!(resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo follows enabled app state");
assert!(!fixture.tree().is_disabled(undo_id), "the Undo button enables with app Undo");
frame::take_output(fixture.ctx());
let undo_node = fixture.by_label("Undo").expect("the Undo button shows");
fixture.click(&undo_node);
fixture.settle();
let undo_ref = CommandRef::from(EditCommands::Undo).id;
let fired: Vec<String> = frame::take_output(fixture.ctx()).fired.into_iter().map(|entry| entry.command.id).collect();
assert!(fired.contains(&undo_ref), "clicking Undo while inactive on the editor fires the app command: {fired:?}");
assert!(focus::has(fixture.ctx(), canvas_id), "the Undo button press keeps focus on the canvas");
inactive.set(EditSet::NONE.with(EditCommand::Undo).with(EditCommand::Redo));
fixture.settle();
assert!(resolve(fixture.ctx(), EditCommands::Cut).enabled, "removing Cut from inactive_edits enables Cut");
assert!(!fixture.tree().is_disabled(cut_id), "the Cut button enables once Cut is active on the editor");
let field_rect = fixture.by_role(Role::TEXT_INPUT).into_iter().next().expect("the field").rect;
fixture.click_at(field_rect.center());
fixture.settle();
assert!(!resolve(fixture.ctx(), EditCommands::Cut).enabled, "a focused TextField with no selection disables Cut independently");
fixture.key(Key::A, Modifiers::COMMAND);
fixture.settle();
assert!(resolve(fixture.ctx(), EditCommands::Cut).enabled, "selecting text in the TextField enables Cut independently");
}
@@ -334,3 +334,113 @@ fn a_thumb_drag_follows_every_pointer_move() {
assert_eq!(view.get().center.y, before.y, "chrome {chrome}: a horizontal drag keeps the vertical position");
}
}
/// Document scroll bars over a `document` centred in the window at `zoom`, with the canvas and the bars following
/// `overscroll`.
fn centred_scrollbars(document: Size, zoom: f64, overscroll: bool) -> (Fixture, Rc<Cell<CanvasView>>) {
let view = Rc::new(Cell::new(CanvasView::new(DOCUMENT_WINDOW, Point::new(document.width / 2.0, document.height / 2.0), zoom)));
let observed = Rc::clone(&view);
let mut fixture = Fixture::new(move |ui| {
let mut next = observed.get();
let mut navigation = NavigationOptions::default();
navigation.overscroll = overscroll;
Canvas::new("Document").document(document).view(next).navigation(navigation).show_at(ui, DOCUMENT_WINDOW, |_, body| {
if let Some(space) = canvas_space(&body.env) {
next = space.view;
}
});
let doc = DocRect::from_origin_size(Point::ZERO, document);
let _ =
CanvasScrollbars::new("Scroll bars", Bind::bound(&mut next), doc).overscroll(overscroll).document_chrome().show_at(ui, DOCUMENT_WINDOW);
observed.set(next);
});
fixture.room(vec2(760.0, 560.0)).settle();
(fixture, view)
}
/// Presses the middle of the track `label` (where a centred view's thumb is), drags by `by` and lets go.
fn drag_thumb(fixture: &mut Fixture, label: &str, by: Vec2) {
let track = fixture.by_label(label).expect("the track").rect;
let start = track.center();
fixture.frame(vec![pointer::moved(start)]).frame(vec![pointer::press(start)]);
for step in 1..=20 {
fixture.frame(vec![pointer::moved(start + by * (step as f32 / 20.0))]);
}
fixture.frame(vec![pointer::release(start + by)]).settle();
}
/// The first and last document coordinate the view shows along `axis`.
fn shown_range(view: &CanvasView, axis: Axis) -> (f64, f64) {
let (center, size) = match axis {
Axis::X => (view.center.x, f64::from(view.rect.width())),
_ => (view.center.y, f64::from(view.rect.height())),
};
let half = size / view.zoom / 2.0;
(center - half, center + half)
}
/// With Overscroll on, a thumb at either end of its track leaves 100 screen points of the document in view at the
/// opposite edge, as the reference application does, at any zoom, for documents larger and smaller than the window.
/// With Overscroll off the ends stay the document's own edges.
#[trial]
fn a_thumb_at_either_end_leaves_100_points_of_the_document_in_view_with_overscroll() {
for (document, zoom) in
[(Size::new(4000.0, 3000.0), 1.0), (Size::new(4000.0, 3000.0), 2.0), (Size::new(4000.0, 3000.0), 0.5), (Size::new(300.0, 200.0), 1.0)]
{
for (label, axis, toward_start, toward_end) in [
("Horizontal scroll bar", Axis::X, vec2(-3000.0, 0.0), vec2(3000.0, 0.0)),
("Vertical scroll bar", Axis::Y, vec2(0.0, -3000.0), vec2(0.0, 3000.0)),
] {
let len = if axis == Axis::X { document.width } else { document.height };
let kept = 100.0 / zoom;
let (mut fixture, view) = centred_scrollbars(document, zoom, true);
drag_thumb(&mut fixture, label, toward_start);
let (_, last) = shown_range(&view.get(), axis);
assert!((last - kept).abs() < 1.0, "{document:?} at {zoom}, {axis:?} start: the first {kept} units stay in view, shows up to {last}");
let (mut fixture, view) = centred_scrollbars(document, zoom, true);
drag_thumb(&mut fixture, label, toward_end);
let (first, _) = shown_range(&view.get(), axis);
assert!(
(first - (len - kept)).abs() < 1.0,
"{document:?} at {zoom}, {axis:?} end: the last {kept} units stay in view, shows from {first}"
);
}
}
let large = Size::new(4000.0, 3000.0);
let (mut fixture, view) = centred_scrollbars(large, 1.0, false);
drag_thumb(&mut fixture, "Horizontal scroll bar", vec2(-3000.0, 0.0));
assert!(shown_range(&view.get(), Axis::X).0.abs() < 1.0, "Overscroll off stops at the document's left edge: {:?}", view.get());
let (mut fixture, view) = centred_scrollbars(large, 1.0, false);
drag_thumb(&mut fixture, "Horizontal scroll bar", vec2(3000.0, 0.0));
assert!((shown_range(&view.get(), Axis::X).1 - large.width).abs() < 1.0, "and at its right edge: {:?}", view.get());
}
/// A thumb dragged past the end of its track and back in the same drag moves again once the pointer is back over it,
/// and lands where a drag straight to that point puts it: the thumb stays under the pointer, as in the reference
/// application.
#[trial]
fn a_thumb_dragged_past_the_end_and_back_follows_the_pointer_in_the_same_drag() {
let large = Size::new(4000.0, 3000.0);
let (mut fixture, straight) = centred_scrollbars(large, 1.0, true);
drag_thumb(&mut fixture, "Horizontal scroll bar", vec2(60.0, 0.0));
let straight = straight.get().center.x;
let (mut fixture, view) = centred_scrollbars(large, 1.0, true);
let track = fixture.by_label("Horizontal scroll bar").expect("the track").rect;
let start = track.center();
fixture.frame(vec![pointer::moved(start)]).frame(vec![pointer::press(start)]);
let mut seen = Vec::new();
for step in 1..=30 {
fixture.frame(vec![pointer::moved(start + vec2(40.0 * step as f32, 0.0))]);
seen.push(view.get().center.x);
}
let at_end = view.get().center.x;
let mut back = Vec::new();
for step in (0..30).rev() {
fixture.frame(vec![pointer::moved(start + vec2(40.0 * step as f32 + 60.0, 0.0))]);
back.push(view.get().center.x);
}
fixture.frame(vec![pointer::release(start + vec2(60.0, 0.0))]).settle();
assert!(back.iter().any(|&x| x < at_end - 1.0), "the drag moves back: past the end {seen:?}, back {back:?}");
assert!((view.get().center.x - straight).abs() < 1.0, "back where a straight drag puts it: {} vs {straight}", view.get().center.x);
}
+4
View File
@@ -166,6 +166,9 @@ pub(super) struct BodyHooks<'b> {
/// The container is a row of a vertical flow, not a member of a row's line (`label::in_column`), as its parent
/// flow showed it this run: its own measuring run shows its content in a flow of its own.
in_column: bool,
/// The container is shown in a cell of an `egui::Grid` (`LabelIn::egui_cell`), as its parent flow showed it this
/// run: its label is decided at its own width.
egui_cell: bool,
/// The line just before the container in its flow is a rule (`layout::flow_start`), as its parent flow showed it
/// this run: a rule above its header is not drawn, so two rules never follow each other.
after_rule: bool,
@@ -245,6 +248,7 @@ impl<'b> BodyHooks<'b> {
held: false,
across: false,
in_column: true,
egui_cell: false,
after_rule: false,
follows_end: false,
}
+26 -2
View File
@@ -297,6 +297,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
self.held = self.held(props, &env);
self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(..)));
self.in_column = label::in_column(ui);
self.egui_cell = env.egui_cell;
self.given.1 |= self.given_room(props, &env, at, ui.ctx(), id);
let measured = self.measured_body.unwrap_or(Vec2::ZERO);
let body = if self.presence.visible { Vec2::new(measured.x, measured.y * self.presence.t) } else { Vec2::ZERO };
@@ -329,6 +330,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
// is laid out as given the room, at the footer and header this run measured, so the children that fill share
// it; its record of the content height lets later runs of the pass and kept transcripts lay it out the same.
None if self.capped(&self.props, at.env, at.at) => self.measure_capped(comp, at, cx, plan),
None if self.footed_layer() => self.measure_footed_layer(comp, at, cx, plan),
None => self.measure_run(comp, at, cx, plan.key, None),
};
self.measured_took(took, pad, vertical)
@@ -1288,6 +1290,7 @@ impl BodyHooks<'_> {
plan.regions.body.width()
},
content_row: false,
egui_cell: self.egui_cell,
text: resolved.label_value,
side,
help: props.help.as_ref(),
@@ -1787,10 +1790,10 @@ impl BodyHooks<'_> {
fn measure_room<C: Container>(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>) -> Result<bool, Vec2> {
let props = &self.props;
// A mount outside the flow takes no room in a parent's sizing pass, so its regions run only when it is
// measured itself. A pane as tall as its content takes its height in the flow.
// measured itself. A pane as large as its content takes its extent in the flow.
let flows = match &props.mount {
Mount::Inline => true,
Mount::Pane(pane) => pane.content_height,
Mount::Pane(pane) => pane.content_extent,
_ => false,
};
if !flows && at.ui.is_sizing_pass() {
@@ -1839,6 +1842,7 @@ impl BodyHooks<'_> {
self.room.x = width;
}
self.in_column = label::in_column(at.ui);
self.egui_cell = at.env.egui_cell;
// A body that fills the main axis of the body it sits in is measured and shown at its share of it. The first
// sweep of that body's measuring run only counts it: its contents run in the second sweep, at the share.
let (x, y) = (craft_behavior::Axis::X, craft_behavior::Axis::Y);
@@ -1924,6 +1928,26 @@ impl BodyHooks<'_> {
}
}
/// Whether the container is a layer with a footer: its body is laid out before the footer runs, so a body that
/// fills the layer's room takes the footer's height too, unless the run knows the footer from an earlier one.
fn footed_layer(&self) -> bool {
overlay_of(&self.props).is_some() && self.props.footer.is_some() && self.room.y.is_finite()
}
/// The measuring run of a layer with a footer (photocraft#16326): while what the regions took fits the room it
/// stands; taller (a body that fills, such as a scrolling list, took the room the footer needs), the run is taken
/// back and the body is laid out again beside the footer this run measured, so the layer keeps to its room with
/// the footer as its last row.
fn measure_footed_layer<C: Container>(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>, plan: MeasurePlan) -> Vec2 {
let fits = self.room.y + plan.tolerance;
let (took, kept) = crate::contract::draft(&plan.ctx, || self.measure_run(comp, at, cx, plan.key.clone(), None), |took| took.y <= fits);
if kept {
return took;
}
self.measured_footer = self.footer_size.unwrap_or(Vec2::ZERO);
self.measure_run(comp, at, cx, plan.key, None)
}
/// The extent a measuring run reports from what its regions `took`.
fn measured_took(&mut self, took: Vec2, pad: Vec2, vertical: bool) -> Vec2 {
// A layer hung from an opener or a rect is at least as wide as its overlay asks for, in the measuring run too,
+7 -4
View File
@@ -5,7 +5,7 @@ use super::placement::overlay_of;
use super::regions::{RegionSizes, end_full_height, footer_in_body, footer_in_end};
use super::scroll::scroll_of;
use crate::contract::run::ShowAt;
use crate::contract::{ContainerProps, Mount, PadEdges, ShellPane, Sizing};
use crate::contract::{ContainerProps, Mount, PadEdges, PaneEdge, ShellPane, Sizing};
use crate::runtime::egui::areas;
use crate::runtime::env::Env;
use crate::runtime::layout_memory;
@@ -61,6 +61,7 @@ pub(crate) struct EnvFacts {
offered: Option<f32>,
measure: Option<f32>,
grid: Option<Id>,
egui_cell: bool,
}
impl EnvFacts {
@@ -80,6 +81,7 @@ impl EnvFacts {
offered: env.offered,
measure: env.measure,
grid: env.grid,
egui_cell: env.egui_cell,
}
}
}
@@ -103,7 +105,8 @@ impl<'b> BodyHooks<'b> {
/// from its content until the user sizes it; an inline container follows its props.
pub(super) fn sizing(&self, props: &ContainerProps) -> Sizing {
match &props.mount {
Mount::Pane(pane) if pane.content_height => Sizing::FillWidth,
Mount::Pane(pane) if pane.content_extent && matches!(pane.edge, PaneEdge::Start | PaneEdge::End) => Sizing::FillHeight,
Mount::Pane(pane) if pane.content_extent => Sizing::FillWidth,
Mount::Pane(_) | Mount::Window { .. } => Sizing::Fill,
Mount::Layer(_) | Mount::Viewport { .. } | Mount::FullWindow if self.fixed => Sizing::Fill,
Mount::Layer(_) | Mount::Viewport { .. } => Sizing::Content,
@@ -327,9 +330,9 @@ impl<'b> BodyHooks<'b> {
None => room,
}
}
// A pane as tall as its content runs in the rect its caller laid out.
// A pane as large as its content runs in the rect its caller laid out.
_ => match (&props.mount, at) {
(Mount::Pane(ShellPane { at: Some(rect), content_height: true, .. }), _) => rect.size(),
(Mount::Pane(ShellPane { at: Some(rect), content_extent: true, .. }), _) => rect.size(),
(_, ShowAt::Rect(rect)) => rect.size(),
(_, ShowAt::Flow) => {
let room = crate::layout::flow_room(ui);
+11 -8
View File
@@ -72,8 +72,10 @@ impl Mount {
/// its siblings (so a pane can overlay another) and ignores the extent. Otherwise an edge pane takes
/// [`extent`](Self::extent) along its edge from the room left, or, without an extent, the size it first took, which it
/// keeps in pane memory until the user resizes it. The central pane fills what the edge panes leave. A pane at a rect
/// that is as tall as its content (a content-sized embedded shell's body) takes the rect's width, its content's height
/// from the rect's top, and that room in the flow of its parent.
/// that is as large as its content along its edge (a content-sized embedded shell's body, a slot sized by its content)
/// takes the rect's cross extent, its content's extent from the rect's outer edge, and that room in the flow of its
/// parent: a top or central pane its height from the rect's top, a bottom pane its height from the rect's bottom, a
/// start or end pane its width from that side.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct ShellPane {
@@ -85,14 +87,14 @@ pub struct ShellPane {
pub extent: Option<f32>,
/// The rect the caller laid the pane out in.
pub at: Option<Rect>,
/// The pane at `at` is as tall as its content.
pub(crate) content_height: bool,
/// The pane at `at` is as large as its content along its edge.
pub(crate) content_extent: bool,
}
impl ShellPane {
/// The central pane named `name`.
pub const fn new(name: &'static str) -> Self {
ShellPane { name, edge: PaneEdge::Center, extent: None, at: None, content_height: false }
ShellPane { name, edge: PaneEdge::Center, extent: None, at: None, content_extent: false }
}
/// The pane at `edge`.
@@ -113,11 +115,12 @@ impl ShellPane {
self
}
/// The pane at `rect`, as tall as its content from the rect's top, taking that room in its parent's flow.
/// The pane in `rect`, as large as its content along its edge from the rect's outer edge, taking that room in its
/// parent's flow. `rect` is the room the content may take.
#[doc(hidden)]
pub const fn at_content_height(mut self, rect: Rect) -> Self {
pub const fn at_content_extent(mut self, rect: Rect) -> Self {
self.at = Some(rect);
self.content_height = true;
self.content_extent = true;
self
}
}
@@ -419,12 +419,13 @@ impl Under {
}
/// An env derived for children `PaintUi` builds: the composite's resolved `enabled` and `size`, and only the inside
/// label `under` gives.
/// label `under` gives. The composite places its children itself, so they are in no egui grid's cell.
pub(crate) fn child_env(env: &Env, under: &Under) -> Env {
env.derive_local(|scoped| {
scoped.enabled &= under.enabled;
scoped.size = under.size;
scoped.inside_label = under.inside.clone().map(|inside| inside as crate::runtime::env::Held);
scoped.cell_fills = false;
scoped.egui_cell = false;
})
}
@@ -255,7 +255,14 @@ impl<C: Component> Cx<'_, C> {
/// participate. A control that uses this must sense both clicks and drags.
pub fn swept_toggle(&self, on: Option<bool>) -> Option<bool> {
let group = self.pointer_group?;
crate::runtime::toggle_sweep::value(self, group, on)
let target = crate::runtime::toggle_sweep::ToggleTarget {
id: self.id,
layer: self.response.layer_id,
visible: self.visible,
enabled: self.resolved.enabled && !self.resolved.read_only,
press: self.press().phase,
};
crate::runtime::toggle_sweep::value(&self.ctx, target, group, on)
}
}
+42 -15
View File
@@ -87,7 +87,7 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids:
let gap = label_gap(env);
let indent = after_indent(ctx, env, input, gap);
let mut natural = leaf.measure_in(kids, craft_behavior::Proposal::Ideal);
if input.side.layout == FieldLayout::After {
if input.side.layout == FieldLayout::After && !input.egui_cell {
// The label takes the room the control and the gap leave, and its detail wraps there.
let room = (input.row.width() - indent - input.control_min - gap).max(0.0);
if natural.x > room {
@@ -95,8 +95,13 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids:
}
}
let baseline = leaf.baseline.get();
// An egui grid's cell is decided at what it needs from its left edge in any direction (`LabelIn::egui_cell`); a
// row grows at its end edge.
let grows = if input.egui_cell { Grows::Cell } else { Grows::End };
if input.side.layout == FieldLayout::Line {
let (cell, rest) = flow.take_end(env.control(input.size).number);
let number = env.control(input.size).number;
let flow = if input.egui_cell { widened(flow, natural.x + gap + number, grows) } else { flow };
let (cell, rest) = flow.take_end(number);
let width = natural.x.min((rest.rect().width() - gap).max(0.0));
let drop = (cell.height() - natural.y).max(0.0) / 2.0;
let label = Flow::new(rest.rect(), rtl).align(Vec2::new(width, natural.y), Align::Min, Align::Min).translate(Vec2::new(0.0, drop));
@@ -124,20 +129,19 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids:
let caption = if matches!(input.side.layout, FieldLayout::Above | FieldLayout::Caption(_)) { column } else { 0.0 };
// The room decides; a beside label gets the width it needs even where last frame's content was narrower. A label
// that never sits beside stacks in an unbounded room as well.
let stacks = (input.room < stack_below || stack_below == f32::INFINITY) && !(input.content_row && input.side.layout == FieldLayout::Beside);
// A stacked label has the row's width at most; its name elides there.
let column = if stacks { column.min(input.row.width()) } else { column };
let flow = if stacks || input.row.width() >= stack_below {
flow
} else {
let mut wide = input.row;
if rtl {
wide.min.x = wide.max.x - stack_below;
} else {
wide.max.x = wide.min.x + stack_below;
}
Flow::new(wide, rtl)
let stacks = (input.room < stack_below || stack_below == f32::INFINITY)
&& !((input.content_row || input.egui_cell) && input.side.layout == FieldLayout::Beside);
// A stacked label has the row's width at most, where its name elides; in an egui grid's cell it keeps its own.
let column = if stacks && !input.egui_cell { column.min(input.row.width()) } else { column };
// A beside label that does not stack takes its column, the gap and the control's least, past the row's end where
// the row is narrower. An egui grid's cell is as wide as its label and control need, whatever the layout.
let need = match input.side.layout {
FieldLayout::After if input.egui_cell => indent + input.control_min + gap + natural.x,
_ if input.egui_cell && stacks => column.max(input.control_min),
_ if stacks => 0.0,
_ => stack_below,
};
let flow = widened(flow, need, grows);
if input.side.layout == FieldLayout::After {
let flow = if indent > 0.0 { flow.take_start(indent).1 } else { flow };
@@ -162,6 +166,29 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids:
}
}
/// How a flow takes the width its label and control need (`widened`).
#[derive(Clone, Copy)]
enum Grows {
/// A flow that is too narrow grows at its end edge: the left one under RTL.
End,
/// An egui grid's cell: exactly as wide as they need from its left edge, in either direction, narrowed as well as
/// widened. egui offers a grid's last column the rest of the room, where the control would sit at its far edge
/// under RTL.
Cell,
}
/// `flow` widened to `need` as `grows` says.
fn widened(flow: Flow, need: f32, grows: Grows) -> Flow {
let mut wide = flow.rect();
match grows {
Grows::Cell => wide.max.x = wide.min.x + need,
Grows::End if wide.width() >= need => return flow,
Grows::End if flow.is_rtl() => wide.min.x = wide.max.x - need,
Grows::End => wide.max.x = wide.min.x + need,
}
Flow::new(wide, flow.is_rtl())
}
/// The gap between a label and its control: `space.gap.inline`, `space.gap.item` inside a bar.
pub(crate) fn label_gap(env: &Env) -> f32 {
let gaps = &env.tokens.space.gap;
+22 -5
View File
@@ -32,6 +32,10 @@ pub(crate) struct LabelIn<'a> {
/// The row sits in a column that takes its width from its content: a beside label never stacks for want of room,
/// since the column is as wide as the label, the gap and the control need.
pub content_row: bool,
/// The row is a cell of an `egui::Grid` (`LeafLabel::egui_cell`): the row is as wide as its label and control need,
/// so the label neither wraps nor stacks for want of room, and the row is that wide from its left edge in any
/// direction.
pub egui_cell: bool,
pub text: &'a Label,
pub side: &'a SideLabel,
/// The help line the container's footer shows; it joins the control's description with the label's detail.
@@ -39,6 +43,7 @@ pub(crate) struct LabelIn<'a> {
pub enabled: bool,
pub size: craft_theme::ControlSize,
/// The narrowest the control can be; a row too narrow for the label column, the gap and this stacks the label above.
/// In an egui grid's cell (`egui_cell`), the width the control takes there: a leaf's ideal width.
pub control_min: f32,
/// The control is a leaf child shown in the flow with its label after it, not a field's body.
pub leaf: bool,
@@ -82,6 +87,10 @@ pub(crate) struct LeafLabel<'a> {
pub parent: Option<Id>,
/// The row the label and the child share.
pub row: Rect,
/// The row is a cell of an `egui::Grid` (`Scoped::egui_cell`): egui places it from the cell's left edge in any
/// direction, and gives the column the width it takes from the next frame. `row` then gives only the cell's left
/// edge, top and height.
pub egui_cell: bool,
pub text: &'a Label,
pub side: &'a SideLabel,
/// What the child inherits (`leaf_under`).
@@ -117,7 +126,9 @@ impl LeafPlaced {
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;
// An egui grid's cell is as wide as the row takes, and the control shows at its ideal width there.
let proposal = if at.egui_cell { craft_behavior::Proposal::Ideal } else { craft_behavior::Proposal::Min };
let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), proposal, Some(at.under)).x;
let facts = LeafFacts { control_min, in_column, claims: C::LABELLED_AFTER };
decide_step(ui, env, &leaf_input(env, at, at.row, facts, trailing))
}
@@ -148,6 +159,7 @@ fn leaf_input<'a>(env: &Env, at: &LeafLabel<'a>, row: Rect, facts: LeafFacts, tr
row,
room: row.width(),
content_row: env.content.0,
egui_cell: at.egui_cell,
text: at.text,
side: at.side,
help: None,
@@ -392,20 +404,25 @@ fn flow_leaf_row<C: Show>(
// 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 };
// An `egui::Grid` offers a column with no width from the last frame its least cell width, where the label would
// wrap and keep the column that narrow: in its cell the label is decided at its own width.
let egui_cell = env.egui_cell;
let at = LeafLabel { id, owner, parent: None, row, egui_cell, text: &label, side: &side, under: &under };
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;
// as the grid, so the grid could never set two such cells beside each other (two columns of check boxes). An egui
// grid's cell is too, also inside a scope of its own there.
let content = env.content.0 || ui.layout().is_horizontal() || in_cell || egui_cell;
let control_width = if content { decided.control().width().min(ideal.x) } else { decided.control().width() };
let rtl = env.direction.is_rtl();
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());
// An egui grid's cell takes its extent from its left edge in any direction.
let extent = if !content {
avail.width()
} else if rtl {
} else if rtl && !egui_cell {
avail.max.x - decided_control.min.x.min(decided_label.min.x)
} else {
decided_control.max.x.max(decided_label.max.x) - avail.min.x
+4 -2
View File
@@ -172,8 +172,10 @@ impl Lazy {
open_record(&ctx, audited.is_some());
}
let mut child = alloc::child(ui, UiBuilder::new().max_rect(available).layout(layout).scope_id(id));
// Its extent in the body around it comes from its content's measure, so a change inside reaches that body.
let out = layout_memory::boundary(&ctx, false, || add(&mut child, &mut run));
// Its extent in the body around it comes from its content's measure, so a change inside reaches that body. The
// content runs in the env of `ui`, as the direct children of the body around it: a plain `Lazy` keeps their
// line, cells and shrink step, and a memoized view starts its own room on top of it.
let out = layout_memory::boundary(&ctx, false, || Env::run_in(&mut child, env, |child| add(child, &mut run)));
let rect = child.min_rect();
// The child `Ui` writes its widget rect when it drops: the record holds it as written.
drop(child);
+6
View File
@@ -356,6 +356,12 @@ pub trait Component: Meta + Sized {
/// Whether the component or its parts can take key focus: `false` skips the stop registration of step 7, except
/// for the roving group of a body the shape declares.
const STOPS: bool = true;
/// The focus scope a leaf runs in, as `ContainerProps::focus` gives a container's: the leaf's own stop and its
/// parts lie inside it, and `FocusPolicy::NONE` (the default) opens none. A scope that restores
/// (`FocusPolicy::TAB_LAYER`) makes the stop focus came from its opener, so focus goes back there when the leaf
/// goes away with focus inside (a canvas text editor hands it back to the canvas). Containers and collections take
/// their scope from their props, not from this.
const FOCUS_SCOPE: crate::runtime::focus::FocusPolicy = crate::runtime::focus::FocusPolicy::NONE;
/// Keys the focused component keeps from egui and the shortcut dispatcher.
const KEYS: crate::runtime::focus::KeyUse = crate::runtime::focus::KeyUse::of(Self::INPUT);
/// The keys this instance keeps in its current state. The default is `KEYS`; a component whose key use depends
+15 -4
View File
@@ -143,13 +143,24 @@ pub(super) fn pane_grip_id(id: Id) -> Id {
impl Host for PaneHost {
fn run(&mut self, id: Id, parent: &mut Ui, env: &Env, pass: &mut HostPass<'_>) {
// A pane the caller laid out shows in its rect and leaves the room of its siblings alone; one as tall as its
// content flows from the rect's top and takes its height in the parent's flow.
// A pane the caller laid out shows in its rect and leaves the room of its siblings alone; one as large as its
// content flows from the rect's outer edge and takes its extent in the parent's flow.
if let Some(rect) = self.0.at {
if self.0.content_height {
if self.0.content_extent {
let rtl = env.direction.is_rtl();
let builder = egui::UiBuilder::new().max_rect(rect);
let builder = match self.0.edge {
PaneEdge::Bottom => builder.layout(egui::Layout::bottom_up(egui::Align::Min)),
PaneEdge::Start | PaneEdge::End if (self.0.edge == PaneEdge::Start) == rtl => {
builder.layout(egui::Layout::right_to_left(egui::Align::Min))
}
PaneEdge::Start | PaneEdge::End => builder.layout(egui::Layout::left_to_right(egui::Align::Min)),
_ => builder,
};
let mut ui = crate::runtime::egui::alloc::child(parent, builder);
pass(&mut ui, Some(ShowAt::Flow), None);
// A layout room of its own, as a docked pane's.
let room = env.new_room();
Env::run_in(&mut ui, room.clone(), |ui| pass(ui, Some(ShowAt::Flow), Some(&room)));
crate::runtime::egui::alloc::advance_past(parent, ui.min_rect());
} else {
pass(parent, Some(ShowAt::Rect(rect)), None);
+5 -2
View File
@@ -3,6 +3,7 @@
use crate::layout::flow_region;
use crate::runtime::egui::alloc;
use crate::runtime::env::Env;
use crate::runtime::layout_memory;
use crate::runtime::lazy;
use crate::runtime::memory::sub;
@@ -42,6 +43,8 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> {
let base = sub(ui.scope_id(), ("pages", self.salt));
let region = flow_region(ui);
let layout = *ui.layout();
// Each page runs in the env of `ui`, as the direct children of the body around it.
let env = Env::of(ui);
let hidden = self.pages.iter().filter(|key| *key != self.current).fold(Vec2::ZERO, |largest, key| {
let id = sub(base, hash(key));
let kept = lazy::measured(&ctx, id).map(|(size, reads)| {
@@ -59,7 +62,7 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> {
layout_memory::boundary(&ctx, true, || {
let room = Rect::from_min_size(region.min, Vec2::new(region.width(), f32::INFINITY));
let mut child = alloc::child(ui, UiBuilder::new().max_rect(room).layout(layout).scope_id(id).sizing_pass().invisible());
page(&mut child, key);
Env::run_in(&mut child, env.clone(), |child| page(child, key));
child.min_rect().size()
})
});
@@ -72,7 +75,7 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> {
let id = sub(base, hash(self.current));
let mut child = alloc::child(ui, UiBuilder::new().max_rect(region).layout(layout).scope_id(id));
child.set_min_size(hidden.min(region.size()));
let out = page(&mut child, self.current);
let out = Env::run_in(&mut child, env, |child| page(child, self.current));
let rect = child.min_rect();
drop(child);
// What the place took comes from the hidden pages' measures as well as from the shown page's components.
+4 -2
View File
@@ -163,7 +163,7 @@ impl PaintUi<'_> {
let env = Env::of(self.ui);
let mut child = child;
let under = label::leaf_under(&env, &side, &child, (self.enabled, self.size));
let at = LeafLabel { id, owner: self.id, parent: Some(self.id), row: rect, text: &label, side: &side, under: &under };
let at = LeafLabel { id, owner: self.id, parent: Some(self.id), row: rect, egui_cell: false, text: &label, side: &side, under: &under };
let ctx = self.ui.ctx().clone();
layout_memory::boundary(&ctx, true, || {
let placed = crate::layout::ColumnGroup::field(&mut *self.ui, |ui| label::leaf(ui, &env, &at, &mut child, None));
@@ -183,12 +183,14 @@ impl PaintUi<'_> {
fn child_with<C: Show>(&mut self, id: Id, rect: Rect, child: C, tip: Option<TipFn<'_>>, inside: Option<Arc<InsideLabel>>) -> C::Output {
let scope = sub(self.id, "children");
let parent = &mut *self.ui;
// The kids' `Ui` holds no entry of its own: they inherit the env of the composite's `Ui`.
let outer = Env::of(parent);
let kids = self.kids.get_or_insert_with(|| {
let builder = egui::UiBuilder::new().layout(child::pinned_layout()).scope_id(scope).max_rect(self.rect);
alloc::child(parent, access::with_parent(builder, self.id))
});
let ctx = kids.ctx().clone();
let env = super::cx::child_env(&Env::of(kids), &super::cx::Under { enabled: self.enabled, size: self.size, inside });
let env = super::cx::child_env(&outer, &super::cx::Under { enabled: self.enabled, size: self.size, inside });
// A child shown while the owner's fade runs lies under the owner's veil, so a faded child adds none of its own.
let env = match self.fade {
Some(_) => {
+4
View File
@@ -317,6 +317,10 @@ impl<C: Component> ShapeHooks<C> for LeafHooks {
self.scope
}
fn focus(&self, _: &C) -> Option<crate::runtime::focus::FocusPolicy> {
(C::FOCUS_SCOPE != crate::runtime::focus::FocusPolicy::NONE).then_some(C::FOCUS_SCOPE)
}
fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 {
use craft_behavior::Axis;
let room = crate::layout::leaf_fill_room(ui);
+18 -15
View File
@@ -92,7 +92,10 @@ impl BodyLayout {
BodyLayout::Row { wrap: false, align: RowAlign::Start }
}
/// Children row-major over `columns`: a `'static` slice, or columns built in the pass.
/// Children row-major over `columns`: a `'static` slice, or columns built in the pass. The cells are the body's
/// craft children: an egui container shown in the body is no cell, and egui places it below the cells placed so
/// far. The rows after it are placed over it: show it as the last child, or put it in a craft body (`Row`), which
/// takes a cell.
pub fn grid(columns: impl Into<Cow<'static, [ColumnWidth]>>) -> Self {
BodyLayout::Grid { columns: columns.into(), fit: GridFit::Stack, cells: CellAlign::Center }
}
@@ -521,13 +524,13 @@ pub fn levelled_unit(ui: &mut Ui, key: Id, levels: usize, mut show: impl FnMut(&
});
let width = ui.max_rect().width();
for level in 0..levels.max(1) {
let installed = Env::install_for(ui, no_room.clone());
// Every level shows the same bodies under the same ids: each measures as a probe, so no level reuses a
// record another level left, and none serves the sweep at the levels given, which records its own.
let (_, took) = layout_memory::probing(&ctx, || {
crate::runtime::egui::sizing::run_sized(ui, width, child::column_layout(rtl), |ui| show(ui, level))
crate::runtime::egui::sizing::run_sized(ui, width, child::column_layout(rtl), |ui| {
Env::run_in(ui, no_room.clone(), |ui| show(ui, level))
})
});
Env::restore(&ctx, installed);
if level == 0 {
widest = took;
}
@@ -889,7 +892,7 @@ fn run_sharing<R>(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layo
return inner;
}
if !shares_along(env, axis) {
return child::block(ui, None, layout, body).0;
return child::block(ui, None, layout, |ui| Env::run_in(ui, env.clone(), body)).0;
}
let key = sub(id, "share");
child::block(ui, None, layout, |ui| {
@@ -943,7 +946,7 @@ fn measure_sharing<R>(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::
let ctx = ui.ctx().clone();
let in_child = |ui: &mut Ui, body: &mut dyn FnMut(&mut Ui) -> R| {
let mut child = laid_out_child(ui, layout);
let inner = body(&mut child);
let inner = Env::run_in(&mut child, env.clone(), body);
(inner, child.min_rect())
};
if !shares_along(env, axis) {
@@ -1158,10 +1161,12 @@ impl Spread {
fn run_spread<R>(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Option<f32>) {
let ctx = ui.ctx().clone();
let layout = child::row_layout(rtl, false);
let sweep = |ui: &mut Ui, last: Option<Vec2>, leasts: Vec<f32>, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| {
let env = Env::of(ui);
let sweep = |ui: &mut Ui, env: &Env, last: Option<Vec2>, leasts: Vec<f32>, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| {
let flow = Flow::new(ui.available_rect_before_wrap(), rtl);
pass_state::with::<Cursors, _>(&ctx, |cursors| cursors.0.insert(id, Cursor::Spread(Spread::new(flow, gap, last, leasts, probe))));
let inner = body(ui);
// The children run in the sweep's own `Ui`: the row's env is installed for it, so they are its direct children.
let inner = Env::run_in(ui, env.clone(), body);
let spread = match pass_state::with::<Cursors, _>(&ctx, |cursors| cursors.0.remove(&id)) {
Some(Cursor::Spread(spread)) => Some(spread),
_ => None,
@@ -1174,13 +1179,13 @@ fn run_spread<R>(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(
let count = this_pass(&ctx, false, leasts_id).map_or(0, |count| count.x as usize);
let leasts = (0..count).map(|i| this_pass(&ctx, false, sub(id, ("least", i))).map_or(0.0, |least| least.x)).collect();
let last = this_pass(&ctx, false, id);
let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, last, leasts, false, body)).0;
let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, &env, last, leasts, false, body)).0;
return (inner, natural(&spread));
}
let room = ui.available_rect_before_wrap().size();
let ((inner, spread), rect, short) = crate::contract::keeping_ids(&ctx, || {
let mut first = ui.new_child(egui::UiBuilder::new().layout(layout));
let (inner, spread) = sweep(&mut first, None, Vec::new(), false, body);
let (inner, spread) = sweep(&mut first, &env, None, Vec::new(), false, body);
// Half a point: less than a pixel shows at any scale the box runs.
let short = spread.as_ref().is_some_and(|spread| spread.count >= 2 && room.x.is_finite() && spread.natural > room.x + 0.5);
(((inner, spread), first.min_rect(), short), short)
@@ -1188,21 +1193,19 @@ fn run_spread<R>(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(
let (inner, spread, leasts) = if short {
#[cfg(feature = "testing")]
measure::count_least(&ctx, id);
let probe = Env::of(ui).derive_local(|scoped| {
let probe = env.derive_local(|scoped| {
scoped.unbounded.0 = true;
scoped.least = true;
});
let leasts = crate::contract::keeping_ids(&ctx, || {
let leasts = layout_memory::probing(&ctx, || {
let mut least = ui.new_child(egui::UiBuilder::new().layout(layout));
let installed = Env::install_for(&least, probe.clone());
let (_, spread) = sweep(&mut least, None, Vec::new(), true, body);
Env::restore(&ctx, installed);
let (_, spread) = sweep(&mut least, &probe, None, Vec::new(), true, body);
spread.map_or_else(Vec::new, |spread| spread.widths)
});
(leasts, true)
});
let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, None, leasts.clone(), false, body)).0;
let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, &env, None, leasts.clone(), false, body)).0;
(inner, spread, leasts)
} else {
ui.advance_cursor_after_rect(rect);
+3 -2
View File
@@ -7,6 +7,7 @@ use egui::{Ui, Vec2};
/// Runs `body` in an invisible sizing pass `width` wide and returns the size it took. Nothing is allocated in
/// `ui` and nothing is painted; the closure sees the env of `ui`.
pub fn measure_slot(ui: &mut Ui, width: f32, body: impl FnOnce(&mut Ui)) -> Vec2 {
let rtl = Env::of(ui).direction.is_rtl();
sizing::run_sized(ui, width, child::column_layout(rtl), body).1
let env = Env::of(ui);
let rtl = env.direction.is_rtl();
sizing::run_sized(ui, width, child::column_layout(rtl), |ui| Env::run_in(ui, env, body)).1
}
+19 -1
View File
@@ -495,11 +495,29 @@ impl<'a> Draw<'a> {
self.painter.extend(super::rule::Rule::shapes(look, from, to, self.painter.pixels_per_point()));
}
/// Paints the line `look` from `from` to `to` as dots `gap` points apart (`Rule::dotted`): a grip's dotted line.
/// Paints the line `look` from `from` to `to` as dots `gap` points apart (`Rule::dotted`): a dotted line.
pub fn dotted_rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2, gap: f32) {
self.painter.extend(super::rule::Rule::dotted(look, from, to, gap, self.painter.pixels_per_point()));
}
/// Paints the line `look` from `from` to `to` as ticks `across` points long, `gap` points apart (`Rule::ticks`):
/// a grip's row of marks.
pub fn ticked_rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2, gap: f32, across: f32) {
self.painter.extend(super::rule::Rule::ticks(look, from, to, gap, across, self.painter.pixels_per_point()));
}
/// Paints `count` upright ticks of `look` centred on `centre`, side by side on a level line, `gap` points apart and
/// `across` points tall (`Rule::ticks`): a grip's row of marks, `count` of them at every display scale.
pub fn grip_ticks(&self, look: &crate::style::RuleLook, centre: Pos2, count: u16, gap: f32, across: f32) {
let ppp = self.painter.pixels_per_point().max(f32::EPSILON);
let (side, gap_px) = (look.width.pixels(ppp), (gap * ppp).round().max(1.0));
// The run `Rule::ticks` fits exactly `count` marks into: their sides, the gaps between them and the one free
// pixel it keeps.
let length = f32::from(count) * side + f32::from(count.saturating_sub(1)) * gap_px + 1.0;
let half = egui::vec2(length / ppp / 2.0, 0.0);
self.ticked_rule_with(look, centre - half, centre + half, gap, across);
}
/// Paints a surface of `kind` (tracks, plot wells).
pub fn surface(&self, rect: Rect, kind: SurfaceKind, corners: Corners) {
let style = surface_style(self.env.tokens, kind);
+24 -9
View File
@@ -70,30 +70,45 @@ impl Rule {
}
/// The dotted form of the line from `from` to `to`: square dots as wide as the line, `gap` points apart, the run
/// of whole dots centred between the ends (a grip, a dotted guide or grid line). The gap is whole physical pixels,
/// at least one, and each dot's centre is snapped on both axes by the rule `shapes` snaps across with, so every dot
/// covers whole physical pixels and dots on a level or upright line are evenly spaced. The dots are one mesh.
/// of whole dots centred between the ends (a dotted guide or grid line). The gap is whole physical pixels, at least
/// one, and each dot's centre is snapped on both axes by the rule `shapes` snaps across with, so every dot covers
/// whole physical pixels and dots on a level or upright line are evenly spaced. The dots are one mesh.
pub fn dotted(look: &RuleLook, from: Pos2, to: Pos2, gap: f32, pixels_per_point: f32) -> Vec<Shape> {
let side = look.width.points(pixels_per_point);
Self::ticks(look, from, to, gap, side, pixels_per_point)
}
/// The line from `from` to `to` as a run of ticks: marks as wide as the line along it and `across` points long
/// across it, `gap` points apart, the run of whole marks centred between the ends (a grip's row of upright ticks).
/// With `across` the line's width the marks are the square dots of [`dotted`](Self::dotted). The gap and both
/// sides of a mark are whole physical pixels, at least one, and each mark's centre is snapped on both axes, so every
/// mark covers whole physical pixels. A mark stands across a level line and lies across an upright one; a slanted
/// line takes the level form. The marks are one mesh.
pub fn ticks(look: &RuleLook, from: Pos2, to: Pos2, gap: f32, across: f32, pixels_per_point: f32) -> Vec<Shape> {
let ppp = pixels_per_point.max(f32::EPSILON);
let side = look.width.pixels(ppp);
let long = (across * ppp).round().max(1.0);
let gap = (gap * ppp).round().max(1.0);
let length = (to - from).length() * ppp;
// The run leaves at least a physical pixel of the line free, so snapping, which moves a dot at most half a
// pixel, keeps every dot between the ends.
// The run leaves at least a physical pixel of the line free, so snapping, which moves a mark at most half a
// pixel, keeps every mark between the ends.
let count = ((length - 1.0 + gap) / (side + gap)).floor();
if !count.is_finite() || count < 1.0 {
return Vec::new();
}
let direction = (to - from).normalized();
let level = direction.x.abs() >= direction.y.abs();
// The mark's physical size on the x and y axes.
let (wide, tall) = if level { (side, long) } else { (long, side) };
let first = (length - (count * side + (count - 1.0) * gap)) / 2.0 + side / 2.0;
let dot = Vec2::splat(side / ppp);
let mark = Vec2::new(wide / ppp, tall / ppp);
// One mesh of plain quads: a filled rect two pixels wide or less is tessellated as a line segment, whose ends
// the tessellator rounds inward, and a one-pixel dot drawn that way vanishes.
// the tessellator rounds inward, and a one-pixel mark drawn that way vanishes.
let mut mesh = Mesh::default();
for i in 0..count as usize {
let centre = from + direction * ((first + i as f32 * (side + gap)) / ppp);
let centre = Pos2::new(snap(centre.x, side, ppp), snap(centre.y, side, ppp));
mesh.add_colored_rect(Rect::from_center_size(centre, dot), look.color);
let centre = Pos2::new(snap(centre.x, wide, ppp), snap(centre.y, tall, ppp));
mesh.add_colored_rect(Rect::from_center_size(centre, mark), look.color);
}
vec![Shape::mesh(mesh)]
}
@@ -518,13 +518,13 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
_ => {}
}
}
let env = crate::runtime::env::Env::of(input.ui);
let multiline = input.options.multiline();
let scroll = if multiline { scroll_before(ctx, widget) } else { 0.0 };
let filter = egui_focus::event_filter(input.keys.keep, false);
// A single line sits on the baseline of its control's line, whatever its face: a number field's mono digits on
// the body text's.
let baseline = (!input.options.multiline()).then(|| {
let env = crate::runtime::env::Env::of(input.ui);
let text_env = super::text::TextEnv { tokens: &env.tokens, direction: env.direction, ink: input.ink, fonts: crate::fonts::stack_facts(ctx) };
super::text::line_baseline(ctx, &text_env, input.options.role, input.rect.center().y)
});
@@ -557,7 +557,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
// egui's widget moves the caret to any press, so the selection from before the press is put back.
let secondary = crate::runtime::pointer::frame_raw(ctx).press.is_some_and(|press| press.button == craft_behavior::PointerButton::Secondary);
let kept = selection(ctx, widget).filter(|(caret, anchor)| secondary && caret != anchor);
let shown = text_edit::show(input.ui, edit);
let shown = text_edit::show(input.ui, &env, edit);
crate::runtime::pointer::record_text_widget(ctx, widget, input.id);
if let Some((caret, anchor)) = kept
&& selection(ctx, widget).is_some_and(|(at, _)| (caret.min(anchor)..=caret.max(anchor)).contains(&at))
@@ -644,6 +644,7 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) {
let multiline = run.wrap == crate::primitives::Wrap::Wrap;
let keep = if multiline { KeepKeys::BlockArrows } else { KeepKeys::InlineArrows };
let mut shown = layout.full().to_owned();
let env = crate::runtime::env::Env::of(ui);
// A line longer than its room is cut at the room's edge, as a field's is.
let mut cut = (layout.size().x > rect.width()).then(|| {
let mut cut = crate::runtime::egui::alloc::child(ui, egui::UiBuilder::new().max_rect(rect));
@@ -652,6 +653,7 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) {
});
text_edit::show(
cut.as_mut().unwrap_or(&mut *ui),
&env,
text_edit::Edit {
id: widget,
rect: layout.galley.rect.translate(at.to_vec2()),
+7 -3
View File
@@ -43,10 +43,14 @@ pub(crate) fn column_layout(right_to_left: bool) -> Layout {
stack_layout(right_to_left)
}
/// Runs `body` in a child `Ui`. `disabled` disables the child and everything below it. `direction` gives the
/// child a cloned style carrying that direction and an explicit layout, never the parent's.
pub(crate) fn scope<R>(ui: &mut Ui, disabled: bool, direction: Option<bool>, body: impl FnOnce(&mut Ui) -> R) -> R {
/// Runs `body` in a child `Ui`, with the id salt `id_salt` when given. `disabled` disables the child and everything
/// below it. `direction` gives the child a cloned style carrying that direction and an explicit layout, never the
/// parent's.
pub(crate) fn scope<R>(ui: &mut Ui, id_salt: Option<egui::Id>, disabled: bool, direction: Option<bool>, body: impl FnOnce(&mut Ui) -> R) -> R {
let mut builder = UiBuilder::new();
if let Some(salt) = id_salt {
builder = builder.id_salt(salt);
}
if let Some(right_to_left) = direction {
let mut style = (**ui.style()).clone();
style.right_to_left = right_to_left;
+19 -3
View File
@@ -1,13 +1,29 @@
//! `UiStack` walks for `Env::of`.
use egui::{Id, Ui};
use egui::{Id, Ui, UiKind};
/// The unique id of `ui`'s stack node: the key env entries are installed under.
pub(crate) fn node_id(ui: &Ui) -> Id {
ui.stack().unique_id
}
/// What `nearest` found walking from a `Ui` outwards.
pub(crate) struct Found<T> {
/// The first value found, and whether it was found for the `Ui`'s own node.
pub value: Option<(T, bool)>,
/// The walk passed the `Ui` of an `egui::Grid` (`UiKind::Grid`) before the node the value was found for, or
/// anywhere on the stack when none was found.
pub grid: bool,
}
/// The first value `lookup` finds walking from `ui` outwards, by the stack nodes' unique ids.
pub(crate) fn nearest<T>(ui: &Ui, lookup: impl Fn(Id) -> Option<T>) -> Option<T> {
ui.stack().iter().find_map(|node| lookup(node.unique_id))
pub(crate) fn nearest<T>(ui: &Ui, lookup: impl Fn(Id) -> Option<T>) -> Found<T> {
let mut grid = false;
for (depth, node) in ui.stack().iter().enumerate() {
if let Some(value) = lookup(node.unique_id) {
return Found { value: Some((value, depth == 0)), grid };
}
grid |= node.kind() == Some(UiKind::Grid);
}
Found { value: None, grid }
}
@@ -65,8 +65,8 @@ pub(crate) struct Shown {
pub content: f32,
}
/// Runs the widget at `edit.rect`.
pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown {
/// Runs the widget at `edit.rect`, under `env`, the env of the `Ui` the caller shows the field in.
pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) -> Shown {
let Edit {
id,
rect,
@@ -93,7 +93,6 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown {
scroll,
} = edit;
// The same font and optical size as a label of the same role: one text path.
let env = crate::runtime::env::Env::of(ui);
let tokens = &env.tokens;
// Behind selected text and the selected text itself: the field's roles.
let selection = (tokens.color.accent.soft, tokens.color.text.normal);
@@ -177,7 +176,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown {
super::style::disable_without_fade(ui);
}
// The placeholder is the faint text colour, the disabled one when the field is off.
let text_colors = &crate::runtime::env::Env::of(ui).tokens.color.text;
let text_colors = &tokens.color.text;
super::style::set_hint_color(ui, crate::style::rgba_color(if enabled { text_colors.faint } else { text_colors.disabled }));
super::style::set_text_cursor(ui, caret_visible);
super::style::set_text_selection(ui, crate::style::rgba_color(selection.0), crate::style::rgba_color(selection.1));
+64 -7
View File
@@ -90,6 +90,7 @@ pub(crate) struct Flow {
unbounded: (bool, bool),
cell_fills: bool,
fits: bool,
egui_cell: bool,
}
/// The values of an env.
@@ -216,6 +217,12 @@ pub struct Scoped {
/// The scope is the body of a beside label in an inspector (`LabelScheme::Inspector`): the control shown there
/// fills the width the label leaves. Only that control sees it, as with `inside_label`.
pub(crate) cell_fills: bool,
/// The scope lays out in a cell of an `egui::Grid` that egui code made below the body around it: the grid places
/// each child from its cell's left edge in any direction, and gives the column the width the child takes from the
/// next frame. `Env::of` sets it where the stack between a `Ui` and its entry holds a grid's `Ui`; a scope that
/// passes `Env::of` on (`with_env`, `Lazy`, a memoized view) keeps it, and a body (`start_room`) or a component's
/// children (`child_env`) end it.
pub(crate) egui_cell: bool,
}
/// The values of an env that a scope rarely changes: the resolved tokens, the platform, the language and the app's
@@ -416,7 +423,8 @@ impl Scoped {
/// Ends the layout room of the enclosing body: its flow grid and content column. The axes the body sizes from its
/// content stay (`content`): like `cell_fills` and `least`, they say what a child that fills takes there, its
/// measured size or the room, and the place of a memoized view holds them (`flow`).
/// measured size or the room, and the place of a memoized view holds them (`flow`). `has_room` checks the same set,
/// and `Env::of` ends it for a `Ui` below the one an entry was installed for.
pub(crate) fn start_room(&mut self) {
self.grid = None;
self.grid_top = false;
@@ -432,10 +440,30 @@ impl Scoped {
self.shrink = None;
self.column = None;
self.offered = None;
self.egui_cell = false;
}
/// Whether any of the facts `start_room` ends is set, besides `egui_cell`, which `Env::of` sets.
fn has_room(&self) -> bool {
self.grid.is_some()
|| self.grid_top
|| self.content_column
|| self.given_column
|| self.row_room.is_some()
|| self.row_line.is_some()
|| self.first_line.is_some()
|| self.flow_body.is_some()
|| self.column_row
|| self.fill_body.is_some()
|| self.fill_share.is_some()
|| self.shrink.is_some()
|| self.column.is_some()
|| self.offered.is_some()
}
/// 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
/// content-sized or a given column and whether the view lies in an egui grid's cell, 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
@@ -444,9 +472,9 @@ impl Scoped {
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);
let (content_column, given_column, egui_cell) = (self.content_column, self.given_column, self.egui_cell);
self.start_room();
(self.content_column, self.given_column) = (content_column, given_column);
(self.content_column, self.given_column, self.egui_cell) = (content_column, given_column, egui_cell);
if fits {
self.shrink = Some(Shrink::Fit);
}
@@ -505,6 +533,7 @@ impl Scoped {
unbounded: self.unbounded,
cell_fills: self.cell_fills,
fits: self.view_fits(),
egui_cell: self.egui_cell,
}
}
@@ -656,6 +685,7 @@ impl Env {
item_facts: None,
inside_label: None,
cell_fills: false,
egui_cell: false,
}),
}
}
@@ -663,14 +693,33 @@ impl Env {
/// The env of `ui`: the nearest entry up the `Ui` stack, else the running viewport's root env, so the `Ui`
/// of an egui `Area` or `Window` reads the app's root values. For app panels (layer 8) and caller closures only.
///
/// What a body sets up for the children it places in flow (`Scoped::start_room`: its `Grid` or spread row's cells,
/// its unwrapped row's line and shrink step, its flow start, its content column) is for its direct children, which
/// it shows in the `Ui` it installed its env for. A `Ui` egui code makes below that one (an `egui::Grid`,
/// `ui.horizontal`, `ui.push_id` in a caller's closure) lays out its own children: an entry found for an ancestor
/// of `ui` comes without those facts, so a component there takes no cell, line or shrink step of the body around it.
/// Where that stack holds an `egui::Grid`'s `Ui`, the env says the component lays out in the grid's cell
/// (`Scoped::egui_cell`).
///
/// While apps still use `add_enabled_ui`, it also ANDs `ui.is_enabled()`, outside sizing passes.
pub fn of(ui: &Ui) -> Env {
let ctx = ui.ctx();
let viewport = pass::current_viewport(ctx);
let found = PerViewport::<ViewportEnvs>::with(ctx, viewport, |envs| {
stack::nearest(ui, |node| envs.entries.get(&node).cloned()).or_else(|| envs.root.clone())
// The root env stands for an entry above the whole stack.
let (found, grid) = PerViewport::<ViewportEnvs>::with(ctx, viewport, |envs| {
let stack::Found { value, grid } = stack::nearest(ui, |node| envs.entries.get(&node).cloned());
(value.or_else(|| envs.root.clone().map(|env| (env, false))), grid)
});
let env = found.unwrap_or_else(|| Env::from_root(ctx, &RootEnv::fallback(ctx), None, scale::pixels_per_point(ctx)));
let (env, own) = found.unwrap_or_else(|| (Env::from_root(ctx, &RootEnv::fallback(ctx), None, scale::pixels_per_point(ctx)), false));
let egui_cell = env.egui_cell || grid;
let env = if own || !(env.scoped.has_room() || egui_cell != env.egui_cell) {
env
} else {
env.derive_local(|scoped| {
scoped.start_room();
scoped.egui_cell = egui_cell;
})
};
// egui's `invisible()` also disables the `Ui`, and a sizing `Ui` is invisible, not disabled: in a sizing pass
// the env keeps the enabled state the real run has, so a memoized view keys alike in both.
if style::is_enabled(ui) || ui.is_sizing_pass() { env } else { env.derive_local(|s| s.enabled = false) }
@@ -772,6 +821,14 @@ impl Env {
Installed { viewport, node, previous }
}
/// Runs `body` in `ui` with `env` installed for it, and puts back what the install replaced, also when `body`
/// panics. A body runs its direct children this way in a `Ui` it makes for them.
pub(crate) fn run_in<R>(ui: &mut Ui, env: Env, body: impl FnOnce(&mut Ui) -> R) -> R {
let ctx = ui.ctx().clone();
let _restore = Restore { ctx: &ctx, installed: Some(Env::install_for(ui, env)) };
body(ui)
}
/// Puts back the entry `install_for` replaced.
pub(crate) fn restore(ctx: &Context, installed: Installed) {
PerViewport::<ViewportEnvs>::with(ctx, installed.viewport, |envs| match installed.previous {
+10 -1
View File
@@ -128,6 +128,8 @@ pub struct Overrides {
pub words: Option<WordsOverride>,
/// App values set for the scope.
pub values: AppValues,
/// The child `Ui`'s id salt, as `ui.push_id` gives it: the ids of what it shows derive from it.
pub id_salt: Option<egui::Id>,
}
/// How a scope changes the built-in text: the only override path for words.
@@ -179,15 +181,22 @@ impl Overrides {
/// Runs `body` in a child `Ui` with `set`'s changes applied to the inherited values. A scope that disables
/// disables its child `Ui`; one that changes direction builds the child with an explicit layout and never
/// inherits the parent's.
///
/// The components the child `Ui` shows are children of the body around `ui` as those shown in `ui` itself are, on its
/// line and in its cells. It is the craft form of `ui.scope` and
/// `ui.push_id` (`Overrides::id_salt`) around craft content: what a body sets up for its children in flow does not
/// reach a `Ui` egui code makes below the body's own (`Env::of`). Content laid out along the other axis goes in a
/// craft `Row` or `Stack`, a body of its own.
pub fn with_env<R>(ui: &mut Ui, set: impl FnOnce(&mut Overrides), body: impl FnOnce(&mut Ui) -> R) -> R {
let mut overrides = Overrides::default();
set(&mut overrides);
let id_salt = overrides.id_salt.take();
let outer = Env::of(ui);
let ctx = ui.ctx().clone();
let inner = outer.derive(|scoped| overrides.apply(&ctx, scoped));
let direction = (inner.direction != outer.direction).then(|| inner.direction.is_rtl());
let disabled = !inner.enabled;
child::scope(ui, disabled, direction, |child| {
child::scope(ui, id_salt, disabled, direction, |child| {
let _restore = Restore { ctx: &ctx, installed: Some(Env::install_for(child, inner)) };
body(child)
})
+9 -3
View File
@@ -563,12 +563,17 @@ pub fn takes_letters(keys: &KeyUse) -> bool {
}
/// A registered menu bar takes the keyboard (F10, a lone Alt): focus moves to `target`, a stop of the bar, in this
/// pass, and the stop that held it is remembered for [`give_back_bar`]. Focus already inside the bar leaves the
/// remembered stop as it is.
/// pass, and the stop that held it is remembered for [`give_back_bar`]. With nothing focused, that is the window's
/// document canvas, the key target then: a shortcut pressed on the bar (Space, the canvas's momentary Hand) matches
/// there and gives the keyboard back to it, as Escape does. Focus already inside the bar leaves the remembered stop
/// as it is.
#[doc(hidden)]
pub fn take_for_bar(ctx: &Context, bar: Id, target: FocusTarget) {
let held = focused_stop(ctx).filter(|(id, _)| *id != bar);
let in_bar = held.is_none() && is_focused(ctx, bar);
with(ctx, |state| {
let canvas = || state.stops.iter().chain(&state.last_stops).find(|rec| rec.stop.keys.chrome_key).map(|rec| rec.stop.key());
let held = held.or_else(|| (!in_bar).then(canvas).flatten());
if held.is_some() || state.bar_return.is_none() {
state.bar_return = held.map(|held| (bar, held));
}
@@ -780,7 +785,8 @@ pub(crate) enum FocusOrigin {
/// it counts as an arrival by key, and a text part selects its whole text so typing replaces it.
Open,
/// The focused stop went away and handed focus to its neighbour: neither the keyboard nor a request chose it, so
/// it is no arrival by key (a deleted guide selects no other guide).
/// it is no arrival by key (a deleted guide selects no other guide) and no scroll owner reveals it (a closed canvas
/// text editor does not pan the canvas to the stop before it).
Removal,
}
+5 -2
View File
@@ -168,11 +168,14 @@ impl State {
self.focus_stop_from(rec, FocusOrigin::Request)
}
/// [`focus_stop`](Self::focus_stop) with what moved focus there.
/// [`focus_stop`](Self::focus_stop) with what moved focus there. A stop that inherits the focus from a removed one
/// is not revealed: nothing chose to show it.
fn focus_stop_from(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec<Act> {
let key = rec.stop.key();
let acts = self.enter_stop(rec, origin);
self.revealed = Some(key);
if origin != FocusOrigin::Removal {
self.revealed = Some(key);
}
acts
}
+23 -18
View File
@@ -3,9 +3,8 @@
use std::sync::Arc;
use craft_behavior::{PointerButton, PointerEvent, PressPhase, PressStart};
use egui::{Context, Id, IdSet, LayerId, Pos2, Rect};
use egui::{Context, Id, IdSet, Pos2, Rect};
use crate::contract::{CxCore, Pointer as _};
use crate::runtime::egui::{areas, pass};
use crate::runtime::frame::{PerViewport, Stored};
use crate::runtime::pointer::{self, PassPointer};
@@ -143,50 +142,56 @@ impl Record {
}
}
pub(crate) fn value(cx: &CxCore<'_>, group: Id, on: Option<bool>) -> Option<bool> {
let ctx = &cx.ctx;
pub(crate) struct ToggleTarget {
pub id: Id,
pub layer: areas::Layer,
pub visible: Rect,
pub enabled: bool,
pub press: PressPhase,
}
pub(crate) fn value(ctx: &Context, target: ToggleTarget, group: Id, on: Option<bool>) -> Option<bool> {
let ToggleTarget { id, layer, visible, enabled, press } = target;
let viewport = pass::current_viewport(ctx);
let pass = pointer::pass_of(ctx);
let input = pointer::pass_pointer(ctx);
let cancelled = pointer::cancel_of_pass(ctx).is_some();
let layer = cx.response.layer_id;
let enabled = cx.resolved.enabled && !cx.resolved.read_only;
let eligible = |sweep: &Sweep| enabled && sweep.group == group && sweep.travel.dragging;
let completed = PerViewport::<Record>::with(ctx, viewport, |record| {
record.advance(pass, &input, cancelled);
let finished = record.completed.as_ref().filter(|finished| eligible(&finished.sweep))?;
let sweep = &finished.sweep;
if sweep.owner == cx.id {
if sweep.owner == id {
return Some((sweep.on, None));
}
(!sweep.visited.contains(&cx.id)).then(|| (sweep.on, Some(Arc::clone(&finished.path))))
(!sweep.visited.contains(&id)).then(|| (sweep.on, Some(Arc::clone(&finished.path))))
})
.and_then(|(on, path)| {
if let Some(path) = path {
if !crosses_visible(ctx, layer, cx.visible, &path) {
if !crosses_visible(ctx, layer, visible, &path) {
return None;
}
PerViewport::<Record>::with(ctx, viewport, |record| {
if let Some(finished) = &mut record.completed {
finished.sweep.visited.insert(cx.id);
finished.sweep.visited.insert(id);
}
});
}
Some(on)
});
let ready = PerViewport::<Record>::with(ctx, viewport, |record| {
match cx.press().phase {
match press {
PressPhase::Down { start, .. } if start.button == PointerButton::Primary && enabled => {
record.start(cx.id, group, start, !completed.or(on).unwrap_or(false), &input);
record.start(id, group, start, !completed.or(on).unwrap_or(false), &input);
}
PressPhase::Cancel { .. } if record.sweep.as_ref().is_some_and(|sweep| sweep.owner == cx.id) => record.sweep = None,
PressPhase::Cancel { .. } if record.sweep.as_ref().is_some_and(|sweep| sweep.owner == id) => record.sweep = None,
_ => {}
}
let sweep = record.sweep.as_ref().filter(|sweep| eligible(sweep))?;
if sweep.owner == cx.id {
if sweep.owner == id {
return Some((sweep.on, None, record.replay_first_path));
}
(!record.path.is_empty() && !sweep.visited.contains(&cx.id)).then(|| (sweep.on, Some(Arc::clone(&record.path)), false))
(!record.path.is_empty() && !sweep.visited.contains(&id)).then(|| (sweep.on, Some(Arc::clone(&record.path)), false))
});
let Some(ready) = ready else { return completed };
let (on, path, replay) = ready;
@@ -194,12 +199,12 @@ pub(crate) fn value(cx: &CxCore<'_>, group: Id, on: Option<bool>) -> Option<bool
ctx.request_repaint();
}
if let Some(path) = path {
if !crosses_visible(ctx, layer, cx.visible, &path) {
if !crosses_visible(ctx, layer, visible, &path) {
return completed;
}
PerViewport::<Record>::with(ctx, viewport, |record| {
if let Some(sweep) = &mut record.sweep {
sweep.visited.insert(cx.id);
sweep.visited.insert(id);
}
});
}
@@ -227,7 +232,7 @@ fn clipped((from, to): Segment, rect: Rect) -> Option<Segment> {
(start <= end).then(|| (from + delta * start, from + delta * end))
}
pub(crate) fn crosses_visible(ctx: &Context, layer: LayerId, rect: Rect, path: &[Segment]) -> bool {
pub(crate) fn crosses_visible(ctx: &Context, layer: areas::Layer, rect: Rect, path: &[Segment]) -> bool {
let map = areas::layer_map(ctx, layer);
let rect = map.map_or(rect, |map| Rect::from_min_max(map.to_screen(rect.min), map.to_screen(rect.max)));
path.iter().copied().filter_map(|segment| clipped(segment, rect)).any(|(from, to)| areas::layer_between(ctx, layer, from, to))
@@ -169,6 +169,49 @@ fn a_dotted_rule_is_whole_pixel_dots_at_one_pitch_between_its_ends() {
}
}
#[trial]
fn ticks_stand_across_a_level_rule_and_lie_across_an_upright_one() {
use craft_ui::primitives::Rule;
use craft_ui::style::{RuleLook, RuleWidth};
use egui::{Color32, Rect, Shape};
let whole = |v: f32| (v - v.round()).abs() < EPS;
for ppp in [1.0, 1.25, 1.5, 2.0] {
let look = RuleLook { color: Color32::WHITE, width: RuleWidth::Points(1.0) };
let side = look.width.points(ppp);
let long = (4.0 * ppp).round() / ppp;
for (from, to) in [(pos2(10.3, 20.6), pos2(31.1, 20.6)), (pos2(7.7, 3.2), pos2(7.7, 24.9))] {
let shapes = Rule::ticks(&look, from, to, 1.0, 4.0, ppp);
let [Shape::Mesh(mesh)] = shapes.as_slice() else { panic!("the ticks are one mesh") };
let ticks: Vec<Rect> = mesh.vertices.chunks(4).map(|quad| Rect::from_points(&quad.iter().map(|v| v.pos).collect::<Vec<_>>())).collect();
assert!(ticks.len() > 2, "at {ppp}x: several ticks");
let level = from.y == to.y;
for tick in &ticks {
let px = *tick * ppp;
assert!([px.min.x, px.min.y, px.max.x, px.max.y].into_iter().all(whole), "at {ppp}x: {px:?} is not whole pixels");
let (along, across) = if level { (tick.width(), tick.height()) } else { (tick.height(), tick.width()) };
assert!((along - side).abs() < EPS && (across - long).abs() < EPS, "at {ppp}x: {tick:?} is {side} along, {long} across");
}
let starts: Vec<f32> = ticks.iter().map(|tick| if level { tick.min.x } else { tick.min.y }).collect();
assert!(starts.windows(2).all(|w| w[1] - w[0] > side + EPS), "at {ppp}x: ticks are apart: {starts:?}");
}
}
}
#[trial]
fn a_dotted_rule_is_the_ticks_as_long_as_the_line_is_wide() {
use craft_ui::primitives::Rule;
use craft_ui::style::{RuleLook, RuleWidth};
use egui::Color32;
for ppp in [1.0, 1.5, 2.0] {
let look = RuleLook { color: Color32::WHITE, width: RuleWidth::Points(1.0) };
let (from, to) = (pos2(10.3, 20.6), pos2(41.1, 20.6));
let across = look.width.points(ppp);
assert_eq!(Rule::dotted(&look, from, to, 2.0, ppp), Rule::ticks(&look, from, to, 2.0, across, ppp), "at {ppp}x");
}
}
#[trial]
fn ant_edges_are_whole_device_pixels_at_a_fractional_scale() {
use craft_theme::{Contrast, Mode};
@@ -0,0 +1,48 @@
//! Focus after the focused stop goes away.
use craft_ui::contract::{ContainerProps, Props as _, Scroll, Show as _, ShowContainer as _};
use craft_ui::runtime::focus::{FocusTarget, request};
use craft_ui::testing::layout::{Block, in_region};
use craft_ui::testing::{Frames, trial};
use craft_ui_test_kit::body::Slab;
use craft_ui_test_kit::contract::{Probe, Seen};
use egui::{Pos2, Rect, Ui, Vec2};
use std::cell::{Cell, RefCell};
const ORIGIN: Pos2 = Pos2::new(10.0, 10.0);
const VIEW: Vec2 = Vec2::new(200.0, 100.0);
/// The focused stop goes away and hands the focus to the next stop in its scope, far below a scrolling body's view:
/// the stop takes the focus and the body stays where it is. A neighbour that inherits the focus was not shown by
/// anyone, so nothing reveals it (#15555: the rulers' corner panned the canvas when a closed text editor handed it the
/// focus).
#[trial]
fn a_stop_that_inherits_the_focus_from_a_removed_one_is_not_revealed() {
let (first, next) = (RefCell::new(Seen::default()), RefCell::new(Seen::default()));
let shown = Cell::new(true);
let top = Cell::new(0.0f32);
let mut show = |ui: &mut Ui| {
in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| {
Slab::new(ContainerProps::new().scroll(Scroll::vertical())).id_salt("panel").show(ui, |ui, _| {
top.set(ui.next_widget_position().y);
if shown.get() {
Probe::new(&first).label("First").id_salt("first").show(ui);
}
Block::new(Vec2::new(VIEW.x, VIEW.y * 4.0)).show(ui);
Probe::new(&next).label("Next").id_salt("next").show(ui);
});
});
};
let mut frames = Frames::new();
frames.idle(3, &mut show);
let first_id = first.borrow().id.expect("the first stop ran");
request(&frames.ctx, FocusTarget::Id(first_id));
frames.idle(3, &mut show);
assert_eq!(craft_ui::testing::focus::egui_focused(&frames.ctx), Some(first_id), "the first stop took the focus");
let start = top.get();
shown.set(false);
frames.idle(6, &mut show);
let next_id = next.borrow().id.expect("the next stop ran");
assert_eq!(craft_ui::testing::focus::egui_focused(&frames.ctx), Some(next_id), "the next stop inherits the focus");
assert!((top.get() - start).abs() < 0.5, "the body keeps its offset: content top {} from {start}", top.get());
}
@@ -7,6 +7,7 @@ pub(crate) mod cursor;
pub(crate) mod derived;
pub(crate) mod elapsed;
pub(crate) mod env;
pub(crate) mod focus;
pub(crate) mod frame;
pub(crate) mod latch;
pub(crate) mod memory;
+60 -5
View File
@@ -18,10 +18,10 @@ use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _};
use crate::runtime::env::Label;
use crate::runtime::focus::{self, FocusTarget};
use crate::runtime::memory::sub;
use crate::style::{ComponentStyle, Corners, StyleCx, SurfaceKind};
use crate::style::{ComponentStyle, Corners, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind};
use crate::tabs::{Tab, TabKind, TabStrip, TornOff};
use craft_behavior::{DockSide, IconId, Metrics, PartKey, PressPhase, Sense, keyed};
use craft_theme::{ControlSize, Tokens};
use craft_theme::{ControlSize, Rgba, Tokens};
use egui::{Id, Pos2, Rect, Response, Ui, Vec2};
use std::borrow::Cow;
use std::fmt::Debug;
@@ -33,6 +33,49 @@ use std::hash::Hash;
pub struct GroupGripStyle {
#[style(metrics)]
metrics: Metrics,
/// The marks a grip with [`ticks`](GroupGrip::ticks) shows.
marks: GripMarks,
}
/// How many ticks a grip's row of marks has, at every display scale.
const GRIP_TICKS: u16 = 10;
/// How tall a grip's tick is, in points.
const GRIP_TICK_LENGTH: f32 = 4.0;
/// The share of the panel's lightness a grip's ticks keep: the references' marks are a little darker than the panel
/// they sit on in every interface colour (`#454545` on `#535353`, `#272727` on `#323232`, `#9e9e9e` on `#b8b8b8`).
const GRIP_INK_SHARE: f32 = 0.83;
/// The row of marks a dock grip shows, as the references draw it: ten upright ticks, a thin stroke wide, four points
/// tall and a thin stroke apart, centred on the grip, a little darker than the panel. They keep their ink under the
/// pointer, as the references' do. A toolbar's grip under its column bar and the grip above each icon group of a
/// collapsed column paint the same marks.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct GripMarks {
ink: StyleColor,
/// The width of a tick and the gap between two of them.
side: f32,
/// The height of a tick.
length: f32,
}
impl GripMarks {
/// The marks in the tokens of `cx`.
pub(super) fn style(cx: &StyleCx<'_>) -> Self {
GripMarks { ink: cx.color(grip_ink(cx.tokens.color.surface.panel)), side: cx.tokens.stroke.thin, length: GRIP_TICK_LENGTH }
}
/// Paints the row centred on `centre`.
pub(super) fn paint(&self, ui: &PaintUi<'_>, centre: Pos2) {
let look = RuleLook { color: self.ink.egui(), width: RuleWidth::Points(self.side) };
ui.draw().grip_ticks(&look, centre, GRIP_TICKS, self.side, self.length);
}
}
/// The ink of a grip's ticks on a `panel` surface: the panel's channels at [`GRIP_INK_SHARE`].
fn grip_ink(panel: Rgba) -> Rgba {
let [r, g, b, a] = panel.0;
let darker = |channel: u8| (f32::from(channel) * GRIP_INK_SHARE).round().clamp(0.0, 255.0) as u8;
Rgba([darker(r), darker(g), darker(b), a])
}
/// What a group grip reports: its response, the second press of a double click and whether it started a group
@@ -73,6 +116,9 @@ pub struct GroupGrip<P: Clone + Send + Sync + 'static> {
/// A drag on the grip drags the unit.
#[prop]
movable: bool,
/// The grip shows the dock's row of grip marks in its middle; else it is an unmarked band.
#[prop]
ticks: bool,
double: bool,
started: bool,
}
@@ -80,7 +126,7 @@ pub struct GroupGrip<P: Clone + Send + Sync + 'static> {
impl<P: Clone + Send + Sync + 'static> GroupGrip<P> {
/// The grip of `unit`, whose shown panel is `active`.
pub fn new(unit: DragUnit<P>, active: PanelKey) -> Self {
GroupGrip { common: Common::new(), unit, active, ghost: None, movable: true, double: false, started: false }
GroupGrip { common: Common::new(), unit, active, ghost: None, movable: true, ticks: false, double: false, started: false }
}
}
@@ -92,8 +138,8 @@ impl<P: Clone + Send + Sync + 'static> Component for GroupGrip<P> {
type Style = GroupGripStyle;
type Output = GroupGripOutput;
fn style(_: &StyleCx<'_>, _: GroupGripStyleKey<P>) -> GroupGripStyle {
GroupGripStyle { metrics: Metrics::new() }
fn style(cx: &StyleCx<'_>, _: GroupGripStyleKey<P>) -> GroupGripStyle {
GroupGripStyle { metrics: Metrics::new(), marks: GripMarks::style(cx) }
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
@@ -112,6 +158,12 @@ impl<P: Clone + Send + Sync + 'static> Component for GroupGrip<P> {
}
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
if self.ticks {
cx.style.marks.paint(ui, cx.rect.center());
}
}
fn finish(self, cx: Cx<'_, Self>) -> GroupGripOutput {
GroupGripOutput { response: cx.response.clone(), double_pressed: self.double, drag_started: self.started }
}
@@ -508,6 +560,9 @@ impl<P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> Container for
let (line, gap) = (env.tokens.size.panel_header, env.tokens.space.gap.item);
ui.set_min_height(line);
let surface_pressed = cx.surface_pressed();
// A raw egui layout: the host's items and the tab row sit side by side, and the header column's flow facts are
// not theirs. The tab row takes the rest of the line, so the strip's empty room is its own, and nothing but the
// memoized tab row runs in it, so a settled header replays.
let layout = if rtl { egui::Layout::right_to_left(egui::Align::Min) } else { egui::Layout::left_to_right(egui::Align::Min) };
let mut sent = Vec::new();
let strip = ui
+9 -28
View File
@@ -4,6 +4,7 @@ use super::divider::{self, Divider, Drag};
use super::dock_column::{
BarRecord, CHEVRON, ColumnArrow, ColumnBar, bar_band, bar_slots, column_grip, describe_chevron, paint_chevron, register_edges, show_bar,
};
use super::group::GripMarks;
use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag};
use crate::buttons::IconButton;
use crate::contract::overlay::Anchor;
@@ -16,7 +17,7 @@ use crate::menu::GroupItem;
use crate::primitives::{IconSpec, TextRun};
use crate::runtime::env::Label;
use crate::runtime::focus::KeyUse;
use crate::style::{ComponentStyle, Corners, GlyphRole, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind};
use crate::style::{ComponentStyle, Corners, GlyphRole, StyleColor, StyleCx, SurfaceKind};
use craft_behavior::dock::{Column, DockEdge, Group};
use craft_behavior::overlay::Side;
use craft_behavior::{Axis, CursorIcon, DockSide, Metrics, PartKey, PressPhase, Sense, Value};
@@ -54,12 +55,6 @@ pub struct IconicSizes {
/// The column width, in rail widths, from which the cells show their panels' names: 96 points at the Compact size.
const LABELS_IN_RAIL_WIDTHS: f32 = 2.4;
/// The length of a group's grip line, in icon cell heights: half a cell, 15 points at the Compact size (18 at
/// Comfortable). That holds several dots, so it reads as a handle and not as a dot, and in a rail-wide column (40
/// points at Compact) it leaves more than a quarter of the width free on each side, so it does not read as a rule
/// between the groups.
const GRIP_LINE_IN_CELLS: f32 = 0.5;
impl IconicSizes {
/// The sizes of the style context `cx`.
pub fn style(cx: &StyleCx<'_>) -> Self {
@@ -149,21 +144,15 @@ pub struct IconicColumnStyle {
name_open: StyleColor,
/// The room between an icon and its name.
name_gap: f32,
/// The ink of a group's grip line.
grip: StyleColor,
/// The ink of a group's grip line while the pointer is over it or drags it.
grip_active: StyleColor,
/// The grip line's length across the group.
grip_length: f32,
/// The side of the grip line's dots, and the gap between two of them.
grip_dot: f32,
/// The marks of a group's grip.
grip: GripMarks,
}
/// A column collapsed to icons: the column bar over icon groups, one cell per panel. A panel without an icon shows the
/// first letter of its name in a box. A column widened past `IconicSizes::labels` shows each panel's name beside its
/// icon, cut with an ellipsis to the cell; a click or drag on the name acts as one on the icon. A click or Enter on an icon
/// opens the flyout of its panel beside the column, switches it to that panel or closes it; one flyout is open at a
/// time. A drag of an icon starts a move of its panel, a drag of the grip line on top of a group a move of the group, a
/// time. A drag of an icon starts a move of its panel, a drag of the grip on top of a group a move of the group, a
/// drag of the bar beside its button a move of the column; each starts through the drag session, and a press outside
/// the flyout closes it. Escape and a press
/// outside close the flyout; with `auto_collapse` the focus leaving it does too.
@@ -422,12 +411,8 @@ impl<P: Value + Hash + Debug + 'static> Component for IconicColumn<'_, P> {
name: cx.color(colors.text.normal),
name_open: cx.color(colors.accent.text),
name_gap: cx.tokens.space.gap.item,
// A handle that is found when looked for, as the references' faint grips: hairline dots one dot apart in
// the faint ink, the normal ink under the pointer.
grip: cx.color(colors.text.faint),
grip_active: cx.color(colors.text.normal),
grip_length: cx.tokens.size.rail.button * GRIP_LINE_IN_CELLS,
grip_dot: cx.tokens.stroke.thin,
// The references' grip: a row of upright ticks a little darker than the panel.
grip: GripMarks::style(cx),
}
}
@@ -577,12 +562,8 @@ impl<P: Value + Hash + Debug + 'static> Component for IconicColumn<'_, P> {
ui.face(CELL.at(at as u64), cell);
}
let style = &cx.style;
for (group, strip) in self.laid.as_ref().map_or(&[][..], |plan| &plan.grips[..]) {
let part = cx.part(GRIP.at(*group as u64));
let ink = if part.hovered || part.pressed() { style.grip_active } else { style.grip };
let half = Vec2::new(style.grip_length.min(strip.width()) / 2.0, 0.0);
let look = RuleLook { color: ink.egui(), width: RuleWidth::Points(style.grip_dot) };
ui.draw().dotted_rule_with(&look, strip.center() - half, strip.center() + half, style.grip_dot);
for (_, strip) in self.laid.as_ref().map_or(&[][..], |plan| &plan.grips[..]) {
style.grip.paint(ui, strip.center());
}
// The edge's line lies on the column's inner edge; its handle stays inside the column. A floating window's
// edges are the window's.
@@ -429,3 +429,57 @@ fn icon_groups_take_the_drops_of_an_expanded_columns_groups() {
assert_eq!(found[3], Some(DockSpot::group(3, DockSide::Center)), "a one-icon group keeps its middle for the join");
assert_eq!(found[4], Some(DockSpot::group(3, DockSide::Bottom)), "the foot under the icons stacks below the last group");
}
/// The ticks of a grip strip in `shapes`: the quads of the one mesh that lies inside `strip`, and their colour.
pub(crate) fn grip_ticks(shapes: &[egui::Shape], strip: Rect) -> Option<(Vec<Rect>, egui::Color32)> {
shapes.iter().find_map(|shape| {
let egui::Shape::Mesh(mesh) = shape else { return None };
let quads: Vec<Rect> = mesh.vertices.chunks(4).map(|quad| Rect::from_points(&quad.iter().map(|v| v.pos).collect::<Vec<_>>())).collect();
let inside = !quads.is_empty() && quads.iter().all(|quad| strip.expand(0.01).contains_rect(*quad));
inside.then(|| (quads, mesh.vertices.first().map_or(egui::Color32::TRANSPARENT, |v| v.color)))
})
}
/// Checks the ticks of a grip strip: ten upright marks, one point wide, four tall, one point apart, centred on the
/// strip and darker than the panel `panel`.
pub(crate) fn assert_grip_ticks(ticks: &[Rect], ink: egui::Color32, strip: Rect, panel: craft_theme::Rgba, what: &str) {
assert_eq!(ticks.len(), 10, "{what}: ten ticks: {ticks:?}");
for tick in ticks {
assert!((tick.width() - 1.0).abs() < 0.01 && (tick.height() - 4.0).abs() < 0.01, "{what}: a tick is 1 x 4 points: {tick:?}");
}
assert!(ticks.windows(2).all(|w| (w[1].min.x - w[0].max.x - 1.0).abs() < 0.01), "{what}: one point apart: {ticks:?}");
let run = ticks.iter().fold(Rect::NOTHING, |run, tick| run.union(*tick));
assert!((run.center().x - strip.center().x).abs() <= 0.5, "{what}: centred across the strip: {run:?} in {strip:?}");
assert!((run.center().y - strip.center().y).abs() <= 0.5, "{what}: centred in the strip's height: {run:?} in {strip:?}");
let [r, g, b, _] = panel.0;
assert!(ink.r() < r && ink.g() < g && ink.b() < b && ink.r() >= r / 2, "{what}: the ticks are a little darker than the panel {panel:?}: {ink:?}");
}
/// The grip above each icon group is the references' row of upright ticks, not a line: ten separate marks a little
/// darker than the panel, the same under the pointer.
#[trial]
fn a_groups_grip_is_a_row_of_upright_ticks_darker_than_the_panel() {
let mut fixture =
Fixture::hosted(|ui| {
let mut column = Column::new(vec![Group::new(vec![1, 2], 0), Group::new(vec![3], 0)]);
column.iconic = true;
let place = Rect::from_min_size(Pos2::ZERO, Vec2::new(RAIL, SCREEN.y));
let output = IconicColumn::new("Panels", global("iconic column", "ticks"), &column, Bind::kept(), &named)
.within(screen())
.show_flyouts_at(ui, place, |_, _, _, _| None);
Some(output.into())
});
fixture.room(SCREEN).settle();
let id = fixture.root_id().expect("the column shows");
let panel = StyleCx::with_root(fixture.ctx(), |cx| cx.tokens.color.surface.panel);
for group in [0, 1] {
let strip = fixture.part_rect(id, GRIP.at(group)).expect("each group has its grip");
let shapes = fixture.frame_shapes();
let (ticks, ink) = grip_ticks(&shapes, strip).expect("the grip paints its ticks");
assert_grip_ticks(&ticks, ink, strip, panel, &format!("group {group}"));
fixture.frame(vec![egui::Event::PointerMoved(strip.center())]);
let hovered = fixture.frame_shapes();
let (_, hover_ink) = grip_ticks(&hovered, strip).expect("the grip paints its ticks under the pointer");
assert_eq!(hover_ink, ink, "group {group}: the ticks keep their ink under the pointer");
}
}
+5
View File
@@ -80,6 +80,10 @@ pub struct DockSizes {
pub rail_first: f32,
/// The width each further column of a tool rail adds: a rail button and the tight gap before it.
pub rail_step: f32,
/// The height of a grip strip, the band with the dock's grip marks: above each icon group of a collapsed column,
/// and under the column bar of a tool rail (a group whose panel has a [`DockGrid`](super::DockGrid)) that the host
/// shows itself (the least hit size).
pub grip: f32,
}
impl DockSizes {
@@ -124,6 +128,7 @@ impl DockSizes {
column: size.dock.column,
rail_first: size.rail.button + 2.0 * cx.tokens.space.pad.control,
rail_step: size.rail.button + cx.tokens.space.gap.tight,
grip: size.hit.target,
}
}
@@ -2,8 +2,10 @@
use craft_behavior::{DisplayOrder, ItemSource};
use craft_ui::contract::{Bind, ShowCollection as _, ShowContainer as _};
use craft_ui::contract::{Scroll, Show as _};
use craft_ui::dialog::Dialog;
use craft_ui::layout_components::Row;
use craft_ui::display::Text;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::list::{List, ListRow};
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::testing::{Fixture, trial};
@@ -53,3 +55,28 @@ fn a_dialog_with_a_filling_body_keeps_its_footer_below_the_body_and_inside_the_s
assert!(craft_ui::testing::relations::above(body, button.rect), "{label} is below the body: {:?} under {body:?}", button.rect);
}
}
/// photocraft#16326: a dialog whose body holds a scrolling stack that fills, under a line of other content, keeps to
/// its share of the screen with the footer as its last row: the body leaves the footer its height instead of taking
/// the whole room and pushing the footer past it.
#[trial]
fn a_dialog_with_a_filling_scroll_body_keeps_to_its_room_with_the_footer_last() {
let mut fixture = Fixture::new(move |ui| {
let mut open = true;
Dialog::new("Pick").opened(Bind::bound(&mut open)).buttons([FooterButton::new("OK", DialogRole::Accept)]).show(ui, |ui, _| {
Text::new("Pick a row").show(ui);
Stack::new().scroll(Scroll::vertical()).fill().show(ui, |ui, _| {
for at in 0..ROWS {
Text::new(format!("Row {at}")).show(ui);
}
});
});
});
fixture.room(egui::Vec2::new(1200.0, 700.0)).settle();
let screen = fixture.ctx().content_rect();
let dialog = fixture.by_role(craft_ui::contract::Role::DIALOG).first().expect("the dialog shows").rect;
let ok = fixture.by_label("OK").expect("the footer's OK").rect;
assert!(screen.contains_rect(dialog), "the dialog is inside the screen: {dialog:?} in {screen:?}");
assert!(dialog.height() <= 0.9 * screen.height() + 1.0, "the dialog keeps to its share of the screen: {dialog:?} in {screen:?}");
assert!(dialog.bottom() - ok.bottom() < 20.0, "OK is the dialog's last row: {ok:?} in {dialog:?}");
}
+71 -10
View File
@@ -5,16 +5,17 @@ use super::hide::{self, PruneKey};
use crate::contract::Revision;
use crate::contract::overlay::{PlacementChange, PlacementKind};
use crate::contract::{
Bind, BindMut, BodyCx, Cx, Entry, MemoKey, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, Tracked, WordSetCx as _,
Bind, BindMut, BodyCx, Cx, Entry, MemoKey, MemoProps, MemoView, NoValue, Outbox, Outcome, Pad, Pointer as _, Props as _, Show as _,
ShowContainer as _, Sizing, Tracked, WordSetCx as _,
};
use crate::docking::SplitFramesCx as _;
use crate::docking::stack::{StackSection, StackSections, section_heights};
use crate::docking::{Arrangement, close_requests, cross_window, end_replaced_drags, float_drop, native, open_requests};
use crate::docking::{
ColumnArrow, ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene,
DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels,
IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, SplitArea, Titles, WindowColumn, actions,
column_cells, dock_states, frame, move_actions, with_area_rules,
DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, GroupGrip,
HidePanels, IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, SplitArea, Titles,
WindowColumn, actions, column_cells, dock_states, frame, move_actions, with_area_rules,
};
use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow};
use crate::runtime::commands::{CommandRef, CommandSet as _, CommandState, Commands as _, focus_within};
@@ -915,16 +916,43 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
}
}
/// The grip strip on top of a tool rail the host shows itself: the dock's grip marks over a band that drags the
/// group, which floats at `size`, the group's size. A memoized view ([`rail_grip`]) held to the strip, so a frame
/// whose input is elsewhere replays it, as the column bars and the groups' tab rows replay.
fn rail_grip(&mut self, ui: &mut Ui, anchor: &P, shown: &P, strip: Rect, size: Vec2) {
let scene = self.scene;
let label = Label::from(scene.spec(shown).label.as_str().to_owned());
let mut sent = Vec::new();
ui.scope_builder(UiBuilder::new().max_rect(strip), |ui| {
let props = RailGrip {
unit: DragUnit::Group(anchor.clone()),
active: PanelKey::of(shown),
movable: scene.permissions(shown).movable,
label,
sent: Outbox::new(&mut sent),
};
// Keyed by the rail's group: unique among the rails a dock area shows.
let _ = MemoView::new(("rail grip", PanelKey::of(anchor)), props, rail_grip::<P>).show(ui);
});
// The group's size goes on the drag here, outside the view, whose measuring runs see no size.
if !sent.is_empty() {
drag::amend::<GroupDrag<P>>(ui.ctx(), |drag| drag.source = Some(size));
}
}
/// One group, by the host's `group_view` when it takes the group, else as a `DockGroup` over the host's panels:
/// shown in a rect, or measured at a width the way it would show, returning its height.
fn group(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, members: &[P], active: usize, look: Look, at: GroupAt) -> Option<f32> {
let scene = self.scene;
let anchor = members.first()?;
let active = active.min(members.len() - 1);
// A tool rail (a panel with a grid) that the host shows itself gets the dock's grip strip on top, under its
// column bar, as the references' toolbar: the host's view takes the room under it.
let grip = if members.get(active).is_some_and(|panel| scene.spec(panel).grid.is_some()) { scene.sizes.grip } else { 0.0 };
if let GroupAt::Measure(_) = at
&& let Some(height) = self.panels.group_view(members, active, ui, at, body)
{
return Some(height);
return Some(height + grip);
}
let shown = &members[active];
let words = body.words::<MenuWords>();
@@ -994,12 +1022,13 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
// the group's room, never in the room the area has left. Where the host leaves the group to the dock, the
// group shows in its place. Both run every pass; the host memoizes inside its view, the group inside its
// header and its bodies.
let (strip, view) = if grip > 0.0 { rect.split_top_bottom_at_y(rect.top() + grip.min(rect.height())) } else { (Rect::NOTHING, rect) };
let output = ui
.scope_builder(UiBuilder::new().max_rect(rect), |ui| {
let taken = ui
.scope_builder(UiBuilder::new().max_rect(rect), |ui| {
ui.shrink_clip_rect(rect);
panels.borrow_mut().group_view(members, active, ui, at, body)
.scope_builder(UiBuilder::new().max_rect(view), |ui| {
ui.shrink_clip_rect(view);
panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body)
})
.inner;
match taken {
@@ -1008,8 +1037,13 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
}
})
.inner;
// A host view took the group.
let output = output?;
// A host view took the group: a rail's grip drags the group, as the band of a group's header does.
let Some(output) = output else {
if strip.is_positive() {
self.rail_grip(ui, anchor, shown, strip, rect.size());
}
return None;
};
// The size `panel` floats at out of this group: the group's width, and the height the group measures at with
// `panel` shown in a floating window's room, so content that fills the body takes that room.
let fitted = |ui: &Ui, panel: &P| {
@@ -1534,3 +1568,30 @@ fn window_edit<P: Clone + Eq + Hash>(
fn panel_body<'p, P: Hash>(panels: &RefCell<&mut (dyn DockPanels<P> + 'p)>, panel: &P, ui: &mut Ui, body: &mut BodyCx<'_>) {
panels.borrow_mut().body(panel, ui, body);
}
/// The props of a tool rail's grip strip: the group it drags, its name, and the outbox the drag's start goes to.
#[derive(MemoProps)]
struct RailGrip<'a, P> {
#[memo_props(hash = "a dock's panels are plain values it keys by their hash")]
unit: DragUnit<P>,
active: PanelKey,
movable: bool,
label: Label,
sent: Outbox<'a, ()>,
}
/// A tool rail's grip strip: the dock's grip marks over the view's room, which a drag moves the rail's group by.
fn rail_grip<P: Clone + Hash + Send + Sync + 'static>(props: &mut RailGrip<'_, P>, ui: &mut Ui) {
let strip = ui.max_rect();
let held = GroupGrip::new(props.unit.clone(), props.active)
.ticks(true)
.movable(props.movable)
.ghost(props.label.clone())
.label(props.label.clone())
.show_at(ui, strip);
if held.drag_started {
props.sent.send(());
}
// The grip takes no room in flow; the run covers the strip, so the pointer over it runs it again.
ui.expand_to_include_rect(strip);
}
@@ -114,7 +114,8 @@ pub enum AboutTab {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AboutLayout {
/// The blurb, the version, the community button and the link row centred, the built-with line faint; OK closes.
/// The blurb and the version, then the community button and the link row centred, then the built-with line faint,
/// the blocks set apart by the section gap; OK closes.
#[default]
Centred,
/// From the start edge, one item to a line: the app's name as a heading, the version, the blurb, the community
@@ -304,7 +305,7 @@ impl<'a> AboutDialog<'a> {
}
let before = kept.tab;
*view.borrow_mut() = kept;
Stack::new().header(|ui, _| shown.tabs(ui, &title, &app_titles, &view)).show(ui, |ui, _| {
Stack::new().header(|ui, _| shown.tabs(ui, &title, &app_titles, &view)).fill_width().show(ui, |ui, _| {
let tab = view.borrow().tab;
let app = match tab {
AboutTab::App(at) => app_tabs.as_deref_mut().and_then(|tabs| tabs.get_mut(usize::from(at))),
@@ -398,26 +399,32 @@ impl Shown<'_> {
});
return;
}
Stack::new().show(ui, |ui, _| {
Text::new(info.blurb.clone()).show(ui);
Text::new(words.version.fill(&[("version", info.version.as_str())])).show(ui);
Row::new().align(RowAlign::Center).show(ui, |ui, _| {
if let Some(community) = &info.community
&& clicked(&Button::new(community.label.clone()).variant(Variant::PRIMARY).id_salt("community").show(ui))
{
*link.borrow_mut() = Some(community.url.clone());
}
// Four blocks set apart by the section gap: the blurb and version at the start edge, the community button and
// the link row each centred across the body, the built-with line at the start edge.
Stack::new().gap(Gap::Section).fill_width().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
Text::new(info.blurb.clone()).show(ui);
Text::new(words.version.fill(&[("version", info.version.as_str())])).show(ui);
});
Row::new().align(RowAlign::Center).show(ui, |ui, _| {
for (at, item) in info.links.iter().enumerate() {
if at > 0 {
Text::new("·").shade(Shade::Faint).show(ui);
if let Some(community) = &info.community {
Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| {
if clicked(&Button::new(community.label.clone()).variant(Variant::PRIMARY).id_salt("community").show(ui)) {
*link.borrow_mut() = Some(community.url.clone());
}
if clicked(&Link::new(item.label.clone()).id_salt(("link", at)).show(ui)) {
*link.borrow_mut() = Some(item.url.clone());
});
}
if !info.links.is_empty() {
Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| {
for (at, item) in info.links.iter().enumerate() {
if at > 0 {
Text::new("·").shade(Shade::Faint).show(ui);
}
if clicked(&Link::new(item.label.clone()).id_salt(("link", at)).show(ui)) {
*link.borrow_mut() = Some(item.url.clone());
}
}
}
});
});
}
Text::new(info.built_with.clone()).shade(Shade::Faint).show(ui);
});
}
@@ -1,13 +1,15 @@
//! A group the host takes with `group_view` lays out in the group's rect, not in the room the dock area has left.
//! A group the host takes with `group_view` lays out in the group's rect, not in the room the dock area has left; a
//! tool rail the host takes has the dock's grip strip on top.
use craft_behavior::Axis;
use craft_behavior::dock::{Layout, Node, SplitSize, Workspace};
use craft_behavior::dock::{Column, DockEdge, Group, Layout, Node, SplitSize, Workspace};
use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked};
use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs};
use craft_ui::docking::{DockConfig, DockGrid, DockPanels, DockSizes, DragUnit, GroupAt, GroupDrag, PanelSpec, PanelSpecs};
use craft_ui::patterns::dock::DockArea;
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Ui, Vec2};
use std::cell::Cell;
use craft_ui::runtime::drag;
use craft_ui::testing::{Fixture, last_pass_runs, pointer, trial};
use egui::{Rect, Shape, Ui, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
@@ -59,3 +61,107 @@ fn a_group_view_lays_out_and_clips_to_its_group_rect() {
assert!(rect.contains_rect(room), "the view's room {room:?} lies in its group's rect {rect:?}");
assert!(rect.contains_rect(clip), "the view's clip {clip:?} lies in its group's rect {rect:?}");
}
/// The tool rail of the grip trial: a panel with a rail grid, which the host shows itself.
const RAIL: usize = 7;
/// The height the host's rail measures at.
const RAIL_HEIGHT: f32 = 200.0;
/// The rail is a tool rail; the rest are plain panels.
#[derive(PlainData)]
struct RailSpecs;
impl PanelSpecs<usize> for RailSpecs {
fn spec(&self, panel: &usize) -> PanelSpec {
let spec = PanelSpec::new(format!("Panel {panel}"));
if *panel == RAIL { spec.grid(DockGrid::rail(4)) } else { spec }
}
}
/// The host shows the rail itself and records the rect it was given.
struct RailPanels {
seen: Rc<Cell<Option<Rect>>>,
}
impl DockPanels<usize> for RailPanels {
fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {}
fn group_view(&mut self, panels: &[usize], _: usize, _: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
if !panels.contains(&RAIL) {
return None;
}
match at {
GroupAt::Measure(_) => Some(RAIL_HEIGHT),
GroupAt::Show(rect) => {
self.seen.set(Some(rect));
Some(rect.height())
}
}
}
}
/// A tool rail the host shows itself has the dock's grip under its column bar, as the references' toolbar: a strip of
/// ten upright ticks, a little darker than the panel, above the host's view, which keeps the height it measured at; a
/// drag on the strip moves the rail's group.
#[trial]
fn a_tool_rail_shown_by_its_host_has_a_grip_strip_that_drags_it() {
let seen = Rc::new(Cell::new(None));
let dock = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![RAIL], 0)]).with_steps(1)]);
let root = Node::split(Axis::X, SplitSize::FixedFirst(120.0), dock, Node::tabs(vec![1], 0));
let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())));
let (mut panels, specs) = (RailPanels { seen: seen.clone() }, Tracked::new(RailSpecs));
let columns: Rc<RefCell<Vec<(usize, Rect)>>> = Rc::default();
let placed = Rc::clone(&columns);
let mut fixture = Fixture::new(move |ui| {
let out = DockArea::new("Rail dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui);
*placed.borrow_mut() = out.columns;
});
fixture.room(Vec2::new(800.0, 600.0)).settle();
let sizes = DockSizes::of(fixture.ctx());
let view = seen.get().expect("the host showed the rail");
let column = columns.borrow().iter().find(|(panel, _)| *panel == RAIL).map(|(_, rect)| *rect).expect("the rail's column shows");
let strip = Rect::from_min_max(egui::pos2(view.left(), view.top() - sizes.grip), egui::pos2(view.right(), view.top()));
assert!(sizes.grip > 0.0 && column.top() < strip.top(), "the strip lies under the column bar: {strip:?} in {column:?}");
assert!((view.height() - RAIL_HEIGHT).abs() < 0.5, "the host's view keeps the height it measured at: {view:?}");
// The strip's ticks: one mesh inside it of ten upright marks.
let shapes = fixture.frame_shapes();
let ticks: Vec<Rect> = shapes
.iter()
.find_map(|shape| {
let Shape::Mesh(mesh) = shape else { return None };
let quads: Vec<Rect> = mesh.vertices.chunks(4).map(|quad| Rect::from_points(&quad.iter().map(|v| v.pos).collect::<Vec<_>>())).collect();
(!quads.is_empty() && quads.iter().all(|quad| strip.expand(0.01).contains_rect(*quad))).then_some(quads)
})
.expect("the strip paints its ticks");
assert_eq!(ticks.len(), 10, "ten ticks: {ticks:?}");
assert!(ticks.iter().all(|tick| tick.height() > tick.width()), "the ticks stand upright: {ticks:?}");
let run = ticks.iter().fold(Rect::NOTHING, |run, tick| run.union(*tick));
assert!((run.center().x - strip.center().x).abs() <= 0.5, "the ticks are centred across the rail: {run:?} in {strip:?}");
fixture.drag_hold_at(strip.center(), Vec2::new(200.0, 0.0));
let unit = drag::active::<GroupDrag<usize>>(fixture.ctx()).map(|drag| drag.unit.clone());
assert_eq!(unit, Some(DragUnit::Group(RAIL)), "a drag on the grip moves the rail's group");
fixture.release_at(strip.center() + Vec2::new(200.0, 0.0)).settle();
}
/// The rail's grip strip is a memoized view: a pointer moving elsewhere in the window replays it, as it replays the
/// column bars and the tab rows, and runs no grip (photocraft#16333).
#[trial]
fn a_tool_rails_grip_strip_replays_while_the_pointer_moves_elsewhere() {
let seen = Rc::new(Cell::new(None));
let dock = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![RAIL], 0)]).with_steps(1)]);
let root = Node::split(Axis::X, SplitSize::FixedFirst(120.0), dock, Node::tabs(vec![1], 0));
let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())));
let (mut panels, specs) = (RailPanels { seen: seen.clone() }, Tracked::new(RailSpecs));
let mut fixture = Fixture::new(move |ui| {
let _ = DockArea::new("Rail dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui);
});
fixture.room(Vec2::new(800.0, 600.0)).settle();
let grips =
|fixture: &Fixture| last_pass_runs(fixture.ctx()).into_iter().filter(|(ty, _)| ty.contains("GroupGrip<")).map(|(_, runs)| runs).sum::<u32>();
for step in 1..=3 {
fixture.frame(vec![pointer::moved(egui::pos2(500.0 + step as f32, 300.0))]);
assert_eq!(grips(&fixture), 0, "pointer step {step}: the rail's grip replays its last run");
}
}
@@ -95,6 +95,38 @@ fn the_listed_about_sets_its_blocks_apart() {
assert!(before_caption > within + 1.0, "the built-with line stands apart from the links: {before_caption} against {within}");
}
// The centred layout (the default) sets its blocks apart: the gap from the version to the community button, from the
// button to the link row and from the link row to the built-with line is wider than the one from the blurb to the
// version. The button and the link row stand centred in the dialog, also when the dialog is wider than its lines.
#[trial]
fn the_centred_about_sets_its_blocks_apart_and_centres_the_button_and_links() {
let info = AboutInfo::new("PhotoCraft", "An image editor.", "1.0")
.community(AboutLink::new("Chat", "https://chat.example"))
.links([AboutLink::new("Website", "https://example.org"), AboutLink::new("Source", "https://example.org/source")])
.built_with("MIT");
let mut fixture = Fixture::new(move |ui| {
let _ = AboutDialog::new(&info, &CREDITS).show(ui);
});
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
let [chat, website, source] = ["Chat", "Website", "Source"].map(|name| fixture.by_label(name).expect("every link shows").rect);
let painted = |text: &str| fixture.texts().iter().find(|painted| painted.text == text).map(|painted| painted.rect).expect("the text shows");
let (blurb, version, caption) = (painted("An image editor."), painted("Version 1.0"), painted("MIT"));
let within = version.top() - blurb.bottom();
for (gap, what) in [
(chat.top() - version.bottom(), "the button stands apart from the version"),
(website.top() - chat.bottom(), "the links stand apart from the button"),
(caption.top() - source.bottom(), "the built-with line stands apart from the links"),
] {
assert!(gap > within + 1.0, "{what}: {gap} against {within}");
}
// Centred across the body: the button and the link row share one middle, the dialog's.
let middle = fixture.by_role(Role::DIALOG).first().expect("the dialog shows").rect.center().x;
let links = website.union(source);
assert!((chat.center().x - links.center().x).abs() < 1.0, "the button and the link row share a middle: {chat:?}, {links:?}");
assert!((chat.center().x - middle).abs() < 1.0, "the button is centred: {} against {middle}", chat.center().x);
assert!(blurb.left() < chat.left() - 10.0, "the blurb still starts at the start edge");
}
/// The listed layout is a wide dialog (`LeastWidth::WideDialog`), as WordCraft's About: wider than the centred one
/// with the same text.
#[trial]
@@ -255,3 +287,39 @@ fn names_sort_without_at_and_case_and_undated_contributors_sort_last_both_ways()
sort_by(&mut fixture, "Name");
assert_eq!(rows(&fixture, &["@zed", "Ann", "@alice", "@carol"]), ["@alice", "Ann", "@carol", "@zed"], "a display name sorts among the usernames");
}
/// A crowd of contributors whose grab bag is taller than a small window.
static CROWD: LazyLock<Credits> = LazyLock::new(|| {
let people: Vec<Contributor> = (0..400).map(|at| Contributor::new(format!("contributor-number-{at}")).counts(1, 1)).collect();
Credits::new(people, Vec::new(), 400)
});
/// photocraft#16326: in a small window the Contributors tab, whose grab bag fills the room it is offered, keeps the
/// About dialog inside the window, and back on About the dialog stands centred again, as it opened.
#[trial]
fn about_stays_inside_a_small_window_on_contributors_and_comes_back_to_the_middle() {
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(Vec2::new(1200.0, 700.0));
let id = host.borrow_mut().open(HostedAbout::new(AboutInfo::new("PhotoCraft", "An image editor.", "1.0"), CROWD.clone()));
fixture.settle();
let screen = fixture.ctx().content_rect();
let dialog = |fixture: &Fixture| fixture.by_role(Role::DIALOG).first().expect("the dialog shows").rect;
let opened = dialog(&fixture);
assert!((opened.center().y - screen.center().y).abs() < 1.0, "About opens centred: {opened:?} in {screen:?}");
let ctx = fixture.ctx().clone();
host.borrow_mut().set_json_field(&ctx, id, "tab", json!("contributors")).expect("`tab` takes Contributors");
fixture.settle();
let tall = dialog(&fixture);
assert!(screen.contains_rect(tall), "Contributors keeps the dialog inside the window: {tall:?} in {screen:?}");
let ok = fixture.by_label("OK").expect("the footer's OK").rect;
assert!(tall.bottom() - ok.bottom() < 20.0, "OK is the dialog's last row: {ok:?} in {tall:?}");
assert!(tall.height() <= 0.9 * screen.height() + 1.0, "the dialog keeps to its share of the window: {tall:?} in {screen:?}");
host.borrow_mut().set_json_field(&ctx, id, "tab", json!("about")).expect("`tab` takes About");
fixture.settle();
let back = dialog(&fixture);
assert!((back.center().y - screen.center().y).abs() < 1.0, "back on About the dialog is centred again: {back:?} in {screen:?}");
}
+32 -27
View File
@@ -653,6 +653,15 @@ impl<'a, S> AppShell<'a, S> {
let panels_hidden = kept.reveal.panels_hidden();
let rect_of = |key| regions.slots.iter().find(|(shown, _)| *shown == key).map_or(Rect::ZERO, |(_, rect)| *rect);
// The room a content slot can grow into: from its outer edge to the far edge of what the slots before it
// leave. Its content runs there, so it measures at its own extent, never at the extent it was laid out at.
let window_rect = cx.rect;
let grow_room = |key: SlotKey| {
let Some(at) = claims.iter().position(|claim| claim.key == key) else { return Rect::ZERO };
let mut claimed = claims[..=at].to_vec();
claimed[at].extent = f32::INFINITY;
layout(window_rect, &claimed, rtl).slots.get(at).map_or(Rect::ZERO, |(_, rect)| *rect)
};
// The extents the content slots were laid out at, and what their content took in this pass.
let measured_before = kept.measured.clone();
let mut measured_now: Vec<(SlotKey, f32)> = Vec::new();
@@ -667,7 +676,7 @@ impl<'a, S> AppShell<'a, S> {
}
if let Some((scope, SlotBody(page))) = page.as_mut() {
let pane = ShellPane::new("page");
let pane = if content_room.is_some() { pane.at_content_height(regions.body) } else { pane.at(regions.body) };
let pane = if content_room.is_some() { pane.at_content_extent(regions.body) } else { pane.at(regions.body) };
let mut region = ShellRegion::pane(pane).label(body_label.clone());
region.props = region.props.command_scope(*scope);
let shown = region.show(ui, |ui, bcx| page(ui, bcx, app));
@@ -686,12 +695,17 @@ impl<'a, S> AppShell<'a, S> {
if !*shown || covers(&placed.slot, only) != covering {
continue;
}
let extent = placed.extent(&tokens, &measured_before);
let by_content = placed.sized_by_content();
let along_x = placed.along_x();
let Placed { slot, edge, named, add, .. } = placed;
let at = rect_of(slot.key());
let pane = ShellPane::new(slot.key()).edge(*edge).extent(extent).at(at);
// A slot sized by its content is as large as its content from its outer edge, in the room it
// can grow into; any other slot takes its extent and fills its rect.
let pane = ShellPane::new(placed.slot.key()).edge(placed.edge);
let pane = if by_content {
pane.at_content_extent(grow_room(placed.slot.key()))
} else {
pane.extent(placed.extent(&tokens, &measured_before)).at(rect_of(placed.slot.key()))
};
let Placed { slot, named, add, .. } = placed;
// Every slot is a chrome pane: it paints the surface under its bar or rail and the rule toward
// the body.
let mut region = ShellRegion::chrome(pane).id_salt(("slot", slot.key()));
@@ -709,28 +723,19 @@ impl<'a, S> AppShell<'a, S> {
region.show(ui, |ui, bcx| add(ui, bcx, app));
continue;
}
// The slot's extent along its edge: what its content allocated, plus what the pane keeps
// The slot's extent along its edge is the pane's: its content's, with what the pane keeps
// around its body (its rule). A top or bottom slot's content fills its width and is as tall
// as it is; a rail's is as wide as it is. The content is read from the `Ui` it allocated in,
// never from the stack's response: a response rect is clipped to the pane (`sense_root`), so
// it can never report more than the extent the slot was laid out at.
let took = region
.show(ui, |ui, bcx| {
let room = ui.max_rect();
let inset = (if along_x { at.width() - room.width() } else { at.height() - room.height() }).max(0.0);
let stack = if along_x { Stack::new() } else { Stack::new().fill_width() };
stack
.show(ui, |ui, _| {
add(ui, bcx, app);
let content = ui.min_rect();
if along_x { content.width() } else { content.height() }
})
.inner
.map(|content| content + if inset.is_finite() { inset } else { 0.0 })
})
.inner
.flatten();
if let Some(took) = took.filter(|took| took.is_finite() && *took > 0.0) {
// as it is; a rail's is as wide as it is. Only the slot's own real run records it: a run in a
// sizing pass (the scope's measuring run, which alone runs for a shell out of sight) is not
// what shows.
let shown = region.show(ui, |ui, bcx| {
let stack = if along_x { Stack::new() } else { Stack::new().fill_width() };
stack.show(ui, |ui, _| add(ui, bcx, app));
!ui.is_sizing_pass()
});
let pane = shown.output.response.rect;
let took = if along_x { pane.width() } else { pane.height() };
if shown.inner == Some(true) && took.is_finite() && took > 0.0 {
measured_now.push((key, took));
}
}
@@ -740,7 +745,7 @@ impl<'a, S> AppShell<'a, S> {
// mode's surround (Focus's black). Otherwise the body paints what it shows, and the gaps between its parts
// (the dock's gutters) show the window's background; Immersive's body fills the room with its own canvas.
let pane = ShellPane::new("body");
let pane = if content_room.is_some() { pane.at_content_height(regions.body) } else { pane.at(regions.body) };
let pane = if content_room.is_some() { pane.at_content_extent(regions.body) } else { pane.at(regions.body) };
let mut center = ShellRegion::pane(pane).label(body_label.clone());
let surround = if only && !host_only { Some(SurfaceKind::Scrim) } else { mode.surround() };
if let Some(surface) = surround {
+11 -4
View File
@@ -22,10 +22,17 @@ pub enum SlotSize {
OptionsBarNarrow,
/// `size.rail.width`: the default extent of a start or end slot.
RailWidth,
/// As tall (a top or bottom slot) or as wide (a start or end slot) as its content: the extent the content took the
/// last time the slot showed, and the edge's default until it first shows. The slot stacks its content from its
/// outer edge instead of centring one line in it, so content of more than one line (a ribbon: a tab strip over a
/// group row) gets its own height and the slot's full width. Outside a shell it resolves to `size.bar.options`.
/// As tall (a top or bottom slot) or as wide (a start or end slot) as its content. The window is laid out at the
/// extent the content took the last time the slot showed (the edge's default until it first shows), while the
/// content runs in the room the slot can grow into, from its outer edge to the far edge of what the slots before it
/// leave: it measures at its own extent, and when that differs the shell lays the window out again in the same
/// frame. The slot stacks its content from its outer edge instead of centring one line in it, so content of more
/// than one line (a ribbon: a tab strip over a group row) gets its own height and the slot's full width.
///
/// The slot never takes more than the room the window leaves it: content larger than that, unless it scrolls,
/// is cut at the window's edge. Raw egui content allocates its own extent along the slot's edge; content that takes whatever room it is
/// offered (`ui.available_size()`) takes the whole room the slot can grow into. Outside a shell it resolves to
/// `size.bar.options`.
Content,
}
+12 -3
View File
@@ -6,7 +6,7 @@ use craft_ui::dialog::Dialog;
use craft_ui::layout_components::Stack;
use craft_ui::runtime::env::WindowKey;
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::shell::AppShell;
use craft_ui::shell::{AppShell, Slot, SlotSize};
use craft_ui::testing::contract::clicked;
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Ui};
@@ -87,16 +87,24 @@ fn a_dialog_in_an_embedded_region_is_placed_in_it_and_blocks_only_it() {
}
/// An embedded shell scrolled out of sight with its dialog open shows nothing and does not fail: its region has no
/// room, so neither its body nor its dialog runs in that pass.
/// room, so neither its body, its dialog nor a slot sized by its content runs in that pass.
#[trial]
fn an_embedded_shell_out_of_sight_shows_nothing() {
let mut fixture = Fixture::new(|ui| {
let real = Rc::new(Cell::new(0_u32));
let count = Rc::clone(&real);
let mut fixture = Fixture::new(move |ui| {
Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| {
let _ = Button::new("Top").show(ui);
let view = ui.clip_rect();
let below = Rect::from_min_size(egui::pos2(view.min.x, view.max.y + view.height()), egui::vec2(view.width(), view.height()));
let mut open = true;
AppShell::embedded(WindowKey::new("out-of-sight"))
.top(Slot::new("ribbon").size(SlotSize::Content), |ui, _, _: &mut ()| {
if !ui.is_sizing_pass() {
count.set(count.get() + 1);
}
let _ = Button::new("Slot").show(ui);
})
.body(|ui, _, _| {
let _ = Button::new("Hidden").show(ui);
Dialog::new("Out of sight").opened(Bind::bound(&mut open)).show(ui, |_, _| {});
@@ -108,4 +116,5 @@ fn an_embedded_shell_out_of_sight_shows_nothing() {
assert!(fixture.by_label("Top").is_some(), "the visible part is shown");
assert!(fixture.by_role(Role::DIALOG).is_empty(), "the dialog of a shell out of sight is not shown");
assert!(fixture.by_label("Hidden").is_none(), "the body of a shell out of sight does not run");
assert!(fixture.by_label("Slot").is_none() && real.get() == 0, "the content slot of a shell out of sight does not run");
}
+194 -1
View File
@@ -3,10 +3,11 @@
//! body, and its band keeps the window's ends and moves the window.
use craft_host::target::ShellInfo;
use craft_theme::Size;
use craft_ui::bars::{Bar, BarKind};
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Props as _, Scroll, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Props as _, Scroll, Show as _, ShowContainer as _, Sizing};
use craft_ui::dialog::Dialog;
use craft_ui::display::Text;
use craft_ui::layout_components::{Row, Stack};
@@ -138,6 +139,198 @@ 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:?}");
}
/// The labels of a column of buttons taller than a slot's default extent.
const TALL: [&str; 6] = ["Paste", "Cut", "Copy", "Format Painter", "Clipboard", "Styles"];
/// The rect of the fill-height column a content slot holds and of each of its buttons, from the last run.
type Column = Rc<RefCell<(Rect, Vec<Rect>)>>;
fn column() -> Column {
Rc::new(RefCell::new((Rect::NOTHING, Vec::new())))
}
/// A column of `labels` that fills its height, as a ribbon group does, recording its rects in `seen`.
fn fill_column(ui: &mut Ui, labels: &[&'static str], seen: &Column) {
let mut buttons = Vec::new();
let column = Stack::new()
.sizing(Sizing::FillHeight)
.show(ui, |ui, _| {
for label in labels {
buttons.push(Button::new(*label).show(ui).rect);
}
})
.output
.rect;
*seen.borrow_mut() = (column, buttons);
}
/// A content slot whose content fills its height grows to that content, at the top and at the bottom edge: its
/// content runs in the room the slot can grow into, not in the extent it was first laid out at, so the column takes
/// its buttons' height and the slot takes the column's.
#[trial]
fn a_slot_sized_by_its_content_grows_to_a_child_that_fills_its_height() {
let (top, bottom) = (column(), column());
let regions = Rc::new(RefCell::new(None));
let (top_seen, bottom_seen, out) = (Rc::clone(&top), Rc::clone(&bottom), Rc::clone(&regions));
let mut fixture = Fixture::new(move |ui| {
let shown = AppShell::new(WindowKey::main())
.top(Slot::new("ribbon").size(SlotSize::Content), |ui, _, _: &mut ()| fill_column(ui, &TALL, &top_seen))
.bottom(Slot::new("findBar").size(SlotSize::Content), |ui, _, _: &mut ()| fill_column(ui, &TALL, &bottom_seen))
.body(|_, _, _| {})
.show(ui, &mut ());
*out.borrow_mut() = Some(shown.regions);
});
fixture.room(Vec2::new(600.0, 700.0)).settle();
let regions = regions.borrow().clone().expect("the shell shows");
const SLACK: f32 = 1.0;
for (key, seen) in [("ribbon", &top), ("findBar", &bottom)] {
let slot = regions.slots.iter().find(|(shown, _)| *shown == key).map(|(_, rect)| *rect).expect("the slot shows");
let (column, buttons) = seen.borrow().clone();
assert_eq!(buttons.len(), TALL.len(), "{key}: every button shows");
for button in &buttons {
assert!(column.expand(SLACK).contains_rect(*button), "{key}: the button {button:?} lies in its column {column:?}");
}
assert!(slot.expand(SLACK).contains_rect(column), "{key}: the slot {slot:?} holds its column {column:?}");
}
let (top_slot, bottom_slot) = (regions.slots[0].1, regions.slots[1].1);
assert!(
regions.body.min.y >= top_slot.max.y - SLACK && regions.body.max.y <= bottom_slot.min.y + SLACK,
"the body {:?} lies between the slots",
regions.body
);
assert!((bottom_slot.max.y - 700.0).abs() <= SLACK, "the bottom slot {bottom_slot:?} stands on the window's bottom edge");
}
/// A settled frame runs a content slot's content once, in one pass: its measure is reused while its inputs are
/// unchanged. A frame where the content grows (a roomier density makes every button taller) lays the window out again
/// at most once, shows the new extent in that frame and leaves the next frame settled.
#[trial]
fn a_content_slot_runs_its_content_once_per_settled_frame_and_grows_in_one_frame() {
let runs = Rc::new(Cell::new(0_u32));
let seen = column();
let regions = Rc::new(RefCell::new(None));
let (count, column, out) = (Rc::clone(&runs), Rc::clone(&seen), Rc::clone(&regions));
let mut fixture = Fixture::new(move |ui| {
let shown = AppShell::new(WindowKey::main())
.top(Slot::new("ribbon").size(SlotSize::Content), |ui, _, _: &mut ()| {
count.set(count.get() + 1);
fill_column(ui, &TALL, &column);
})
.body(|_, _, _| {})
.show(ui, &mut ());
*out.borrow_mut() = Some(shown.regions);
});
fixture.room(Vec2::new(600.0, 700.0)).density(Size::Compact).settle();
let before = seen.borrow().0;
runs.set(0);
fixture.frame(Vec::new());
assert_eq!(fixture.passes(), 1, "a settled frame runs one pass");
assert_eq!(runs.get(), 1, "a settled frame runs the slot's content once");
fixture.density(Size::Comfortable).frame(Vec::new());
assert!(fixture.passes() <= 2, "the frame the content grows in lays the window out again at most once: {} passes", fixture.passes());
let slot = regions.borrow().as_ref().and_then(|regions| regions.slots.first().map(|(_, rect)| *rect)).expect("the slot shows");
let grown = seen.borrow().0;
assert!(grown.height() > before.height() + 1.0, "the roomier density makes the column taller: {before:?} to {grown:?}");
assert!(slot.expand(1.0).contains_rect(grown), "in the frame it grows in, the slot {slot:?} holds the grown column {grown:?}");
runs.set(0);
fixture.frame(Vec::new());
assert_eq!(fixture.passes(), 1, "the frame after the grow is settled: one pass");
assert_eq!(runs.get(), 1, "the frame after the grow runs the slot's content once");
}
/// Content rails sit at their own sides in either reading direction, each as wide as the column it holds, and a
/// settled frame runs one pass with each rail's content once: the start rail at the reading start, the end rail at the
/// reading end, the body between them.
#[trial]
fn content_rails_sit_at_their_sides_and_settle_in_one_pass() {
const RAIL: [&str; 3] = ["Move", "Brush", "Eraser"];
for rtl in [false, true] {
let direction = if rtl { craft_i18n::Direction::Rtl } else { craft_i18n::Direction::Ltr };
let (start, end) = (column(), column());
let (start_runs, end_runs) = (Rc::new(Cell::new(0_u32)), Rc::new(Cell::new(0_u32)));
let regions = Rc::new(RefCell::new(None));
let (start_seen, end_seen, start_count, end_count, out) =
(Rc::clone(&start), Rc::clone(&end), Rc::clone(&start_runs), Rc::clone(&end_runs), Rc::clone(&regions));
let mut fixture = Fixture::new(move |ui| {
let shown = AppShell::new(WindowKey::main())
.start(Slot::new("tools").size(SlotSize::Content), |ui, _, _: &mut ()| {
start_count.set(start_count.get() + 1);
fill_column(ui, &RAIL, &start_seen);
})
.end(Slot::new("inspector").size(SlotSize::Content), |ui, _, _: &mut ()| {
end_count.set(end_count.get() + 1);
fill_column(ui, &RAIL, &end_seen);
})
.body(|_, _, _| {})
.show(ui, &mut ());
*out.borrow_mut() = Some(shown.regions);
});
fixture.direction(direction).room(Vec2::new(600.0, 400.0)).settle();
let regions = regions.borrow().clone().expect("the shell shows");
const SLACK: f32 = 1.0;
let rect_of = |key| regions.slots.iter().find(|(shown, _)| *shown == key).map(|(_, rect)| *rect).expect("the rail shows");
let (start_rail, end_rail) = (rect_of("tools"), rect_of("inspector"));
for (key, rail, seen) in [("tools", start_rail, &start), ("inspector", end_rail, &end)] {
let (column, buttons) = seen.borrow().clone();
assert_eq!(buttons.len(), RAIL.len(), "RTL {rtl}, {key}: every button shows");
for button in &buttons {
assert!(column.expand(SLACK).contains_rect(*button), "RTL {rtl}, {key}: the button {button:?} lies in its column {column:?}");
}
assert!(rail.expand(SLACK).contains_rect(column), "RTL {rtl}, {key}: the rail {rail:?} holds its column {column:?}");
}
let body = regions.body;
let (left, right) = if rtl { (end_rail, start_rail) } else { (start_rail, end_rail) };
assert!(left.max.x <= body.min.x + SLACK, "RTL {rtl}: the rail {left:?} lies left of the body {body:?}");
assert!(right.min.x >= body.max.x - SLACK, "RTL {rtl}: the rail {right:?} lies right of the body {body:?}");
start_runs.set(0);
end_runs.set(0);
fixture.frame(Vec::new());
assert_eq!(fixture.passes(), 1, "RTL {rtl}: a settled frame runs one pass");
assert_eq!((start_runs.get(), end_runs.get()), (1, 1), "RTL {rtl}: a settled frame runs each rail's content once");
}
}
/// A content slot holding a list that scrolls along its height is as tall as the list's rows, whether the list sizes
/// from its content or fills its height: the slot offers its content no bound along its edge, so the list shows all
/// of its rows instead of taking the window's height, and the body keeps the rest of the window.
#[trial]
fn a_content_slot_holding_a_scrolling_list_takes_the_list_height() {
for sizing in [Sizing::Content, Sizing::FillHeight, Sizing::Fill] {
let rows = Rc::new(RefCell::new(Vec::new()));
let regions = Rc::new(RefCell::new(None));
let (seen, out) = (Rc::clone(&rows), Rc::clone(&regions));
let mut fixture = Fixture::new(move |ui| {
let shown = AppShell::new(WindowKey::main())
.top(Slot::new("findBar").size(SlotSize::Content), |ui, _, _: &mut ()| {
let mut buttons = Vec::new();
Stack::new().sizing(sizing).scroll(Scroll::vertical()).show(ui, |ui, _| {
for label in ["First", "Second", "Third"] {
buttons.push(Button::new(label).show(ui).rect);
}
});
*seen.borrow_mut() = buttons;
})
.body(|_, _, _| {})
.show(ui, &mut ());
*out.borrow_mut() = Some(shown.regions);
});
fixture.room(Vec2::new(600.0, 700.0)).settle();
let regions = regions.borrow().clone().expect("the shell shows");
let slot = regions.slots.iter().find(|(key, _)| *key == "findBar").map(|(_, rect)| *rect).expect("the slot shows");
let rows = rows.borrow().iter().fold(Rect::NOTHING, |all, row| all.union(*row));
const SLACK: f32 = 1.0;
// The rule toward the body, the stack's padding and rounding.
const AROUND: f32 = 24.0;
assert!(slot.expand(SLACK).contains_rect(rows), "{sizing:?}: the slot {slot:?} holds the list's rows {rows:?}");
assert!(slot.height() <= rows.height() + AROUND, "{sizing:?}: the slot {slot:?} is as tall as the list's rows {rows:?}, not the window");
let body = regions.body;
assert!(
body.min.y >= slot.max.y - SLACK && (body.max.y - 700.0).abs() <= SLACK,
"{sizing:?}: the body {body:?} keeps the window under the slot {slot:?}"
);
}
}
/// 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]
@@ -212,6 +212,11 @@ layout_component!(
);
layout_component!(
/// Children row-major over a column list: a child in flow takes the next cell.
///
/// The cells are the grid's craft children. An egui container shown in the body (`ui.horizontal`, an
/// `egui::Grid`) is no cell: egui places it below the cells placed so far, and its children are not cells. The
/// rows after it are placed over it, since the grid's rows do not count it: show it as the last child, or put it
/// in a craft body (`Row`), which takes a cell.
Grid,
GridStyleKey,
[]
@@ -329,7 +334,6 @@ impl Row {
/// The row's line is at least `points` high, as a child of more than one line that high would make it: the
/// children that fill the line's height take at least it. A row of command groups keeps the height of its
/// rows of controls while its groups are shorter. Ignored by a row that wraps.
// design: allow[props/point-size](the least line of a row is the caller's measured extent (three control rows of a look and a title line), not a chosen size)
pub fn least_height(mut self, points: f32) -> Self {
self.props = self.props.least_height(points);
self
+1 -1
View File
@@ -91,7 +91,7 @@ impl ListRow<'_> {
ToggleFace::Icons { on, off } => {
let shown = match toggle.state {
ToggleState::On | ToggleState::Mixed => Some(on),
ToggleState::Off if toggle.always_visible || cx.part(part).hovered => Some(off),
ToggleState::Off if toggle.shows_off(cx.part(part).hovered) => Some(off),
ToggleState::Off => None,
};
if let Some(id) = shown {
+16
View File
@@ -80,6 +80,9 @@ pub struct ToggleCell {
pub fill: Option<DataColor>,
/// The off icon shows in every row, not only under the pointer. No effect on a check face.
pub always_visible: bool,
/// The off icon never shows, also under the pointer: an off cell stays empty (a hidden layer's eye box). Wins
/// over `always_visible`. No effect on a check face.
pub empty_off: bool,
/// A screen reader announces a check box instead of a toggle button: for a setting the row carries rather than
/// an action on the row.
pub check_box: bool,
@@ -99,6 +102,7 @@ impl ToggleCell {
tooltip: None,
fill: None,
always_visible: false,
empty_off: false,
check_box: false,
row_press: false,
}
@@ -162,10 +166,22 @@ impl ToggleCell {
self
}
/// The off icon never shows, also under the pointer: an off cell stays an empty box.
#[must_use]
pub fn empty_off(mut self) -> Self {
self.empty_off = true;
self
}
/// A press on the row's own area shows on the cell, for a row whose click turns on what the cell shows.
#[must_use]
pub fn row_press(mut self) -> Self {
self.row_press = true;
self
}
/// Whether an off cell draws its off icon, under the pointer when `hovered`.
pub(super) fn shows_off(&self, hovered: bool) -> bool {
!self.empty_off && (self.always_visible || hovered)
}
}
+6 -2
View File
@@ -9,7 +9,8 @@
//!
//! Keys follow spec 9.7: Alt and a letter open the menu with that mnemonic (also while another is open). F10 or a
//! lone Alt closes an open menu; with none open it moves focus to the first title, and the next F10 or lone Alt, an
//! Escape, or running a row returns focus to where it was. A `&` in a title's words row marks its mnemonic; without
//! Escape, a shortcut (Space, a canvas's momentary Hand, among them) or running a row returns focus to where it was.
//! Down and Enter open the focused title's menu; Space opens none. A `&` in a title's words row marks its mnemonic; without
//! one the title takes the first letter no earlier title holds. The mnemonic is underlined while Alt is held.
//!
//! The Help menu can start with a search field over a list of `HelpEntry` commands: typing lists up to `search::MAX_RESULTS`
@@ -428,7 +429,10 @@ impl<'a> MenuBar<'a> {
impl Component for MenuBar<'_> {
const ROLE: Role = Role::MENU_BAR;
const KEYS: crate::runtime::focus::KeyUse = crate::runtime::focus::KeyUse::of(crate::contract::Input::Pointer).with_moves();
// Enter and Down open the focused title's menu; Space does not. Space is a canvas's momentary Hand, so it goes on
// to the app's shortcuts, and a shortcut pressed on the bar gives the keyboard back to where it was.
const KEYS: crate::runtime::focus::KeyUse =
crate::runtime::focus::KeyUse::of(crate::contract::Input::Pointer).with_moves().with_activate(crate::runtime::focus::ActivateKeys::Enter);
type Style = MenuBarStyle;
type Output = MenuBarOutput;
+3 -2
View File
@@ -18,8 +18,9 @@ use crate::buttons::{IconButton, Link};
use crate::choice::Segmented;
use crate::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Entry, Input, MeasureCx, Overlay, OverlayUi, Overlays as _, PaintUi,
PartsCx, Props as _, Remember as _, Role, Show as _, WordSetCx as _, clicked,
PartsCx, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, clicked,
};
use crate::layout_components::Row;
use crate::primitives::{IconSpec, TextKey, TextOptions, TextRun};
use crate::runtime::env::Label;
use crate::text::{Adornment, FieldStyle, place, reserve};
@@ -338,7 +339,7 @@ impl Component for DatePicker<'_> {
view = next;
}
let mut pick = page.picked.map(Some);
ui.horizontal(|ui| {
let _ = Row::new().show(ui, |ui, _| {
let at_precision = today.map(|today| match view.precision {
DatePrecision::Day => today,
DatePrecision::Month => PickedDate::month(today.year, today.month.unwrap_or(1)),
+2 -1
View File
@@ -16,6 +16,7 @@ use crate::contract::{
MeasureCx, Numeric, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupHandle, PopupKind, Props as _, Role, Show as _,
ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _, step_stop, step_stops,
};
use crate::layout_components::Row;
use crate::list::{List, ListRow, ThumbAspect};
use crate::menu::Menu;
use crate::primitives::ContentPainterCx;
@@ -318,7 +319,7 @@ impl<T: Value + 'static> Component for Select<'_, T> {
let list = ui.scope_id().with("options");
let mut query = String::new();
if searchable || header_menu.is_some() {
ui.horizontal(|ui| {
let _ = Row::new().show(ui, |ui, _| {
if searchable {
query = search::show(ui, body, popup, cx, &name, list);
}
@@ -115,6 +115,12 @@ fn select_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
Select::new("Blend mode", data.bind("open", 1u8), &entries).show(ui).into()
}
#[story(Select<'static, u8>, covers = [Open], drive = Drive::Custom(open_listbox))]
fn select_searchable_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let entries = resampling();
Select::new("Resampling", data.bind("searchable_open", 2u8), &entries).searchable().show(ui).into()
}
#[story(Select<'static, u8>, covers = [], disabled_text = "Pick a layer first")]
fn select_with_reason(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let entries = modes();
+329 -4
View File
@@ -1,17 +1,19 @@
//! 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 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.
//! a grid's cell. Components an app shows in an egui container inside a row or grid are laid out by that container:
//! they take neither the row's line nor the grid's cells. In an `egui::Grid`'s cell a labelled control decides its
//! label at its own width.
use craft_behavior::ColumnWidth;
use craft_theme::ControlSize;
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _, Sizing};
use craft_ui::contract::{Bind, FieldLayout, LabelScheme, Props as _, Show as _, ShowContainer as _, Sizing};
use craft_ui::display::Text;
use craft_ui::form::{Field, Help};
use craft_ui::form::{Field, FieldGroup, Help};
use craft_ui::layout_components::{Grid, Row, Stack};
use craft_ui::runtime::env::Label;
use craft_ui::runtime::env::{Label, with_env};
use craft_ui::testing::{Fixture, last_pass_measuring_runs, trial};
use egui::Rect;
use std::cell::Cell;
@@ -165,3 +167,326 @@ fn a_labelled_check_box_sits_with_its_box_on_a_buttons_line_in_a_row_and_a_grid_
assert!((button.center().y - check.center().y).abs() <= ROUNDING, "{at}: the box {check:?} sits on the button's line {button:?}");
}
}
const GRID_ROWS: usize = 3;
type GridBoxes = [(Rect, Rect); GRID_ROWS];
/// Two columns of labelled check boxes in an `egui::Grid`, each box run through `wrap` (`ui.show` or a scope around
/// it) with its index: the box rects of each row.
fn boxes_grid(ui: &mut egui::Ui, wrap: Wrap) -> GridBoxes {
let mut boxes = [(Rect::NOTHING, Rect::NOTHING); GRID_ROWS];
egui::Grid::new("boxes").num_columns(2).spacing([24.0, 6.0]).show(ui, |ui| {
for (row, rect) in boxes.iter_mut().enumerate() {
rect.0 = wrap(ui, 2 * row, Checkbox::new(Bind::given(true)).label(format!("Left {row}")));
rect.1 = wrap(ui, 2 * row + 1, Checkbox::new(Bind::given(false)).label(format!("Right {row}")));
ui.end_row();
}
});
boxes
}
/// How `boxes_grid` shows each check box in its cell.
type Wrap = fn(&mut egui::Ui, usize, Checkbox<'_>) -> Rect;
fn plain(ui: &mut egui::Ui, _: usize, check: Checkbox<'_>) -> Rect {
check.show(ui).response.rect
}
fn read_only(ui: &mut egui::Ui, _: usize, check: Checkbox<'_>) -> Rect {
with_env(ui, |set| set.read_only = Some(true), |ui| check.show(ui).response.rect)
}
fn pushed(ui: &mut egui::Ui, index: usize, check: Checkbox<'_>) -> Rect {
ui.push_id(index, |ui| check.show(ui).response.rect).inner
}
/// The grid of `boxes_grid` in a 300 pt column, inside an unwrapped `Row` or a `Stack`, with a button after it.
fn grid_in(in_row: bool, wrap: Wrap) -> (GridBoxes, Rect) {
let (boxes, after, _) = grid_shown(in_row, wrap);
(boxes, after)
}
/// `grid_in`, with the fixture it ran in.
fn grid_shown(in_row: bool, wrap: Wrap) -> (GridBoxes, Rect, Fixture) {
let seen = Rc::new(Cell::new(([(Rect::NOTHING, Rect::NOTHING); GRID_ROWS], 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(300.0, 600.0));
let out = Rc::clone(&out);
Stack::new().fill().show_at(ui, room, move |ui, _| {
let mut boxes = [(Rect::NOTHING, Rect::NOTHING); GRID_ROWS];
if in_row {
Row::new().fill().show(ui, |ui, _| boxes = boxes_grid(ui, wrap));
} else {
Stack::new().fill().show(ui, |ui, _| boxes = boxes_grid(ui, wrap));
}
let after = Button::new("After").show(ui).rect;
out.set((boxes, after));
});
});
let (boxes, after) = seen.get();
(boxes, after, fixture)
}
fn pitch(boxes: &GridBoxes) -> f32 {
boxes[1].0.top() - boxes[0].0.top()
}
/// Check boxes an app lays out in an `egui::Grid` inside a row (a dialog's custom row of two columns of check boxes)
/// are no children of the row: the grid's rows are as high as the same grid's outside a row, not as high as the row's
/// line, and what follows the row starts under the grid.
#[trial]
fn check_boxes_in_an_egui_grid_in_a_row_keep_their_own_rows() {
let (alone, _) = grid_in(false, plain);
let (boxes, after) = grid_in(true, plain);
assert!((pitch(&boxes) - pitch(&alone)).abs() <= ROUNDING, "the grid rows in a row {boxes:?} are as high as outside one {alone:?}");
assert!(after.top() >= boxes[GRID_ROWS - 1].0.bottom() - ROUNDING, "the button {after:?} is under the grid {boxes:?}");
}
/// The same check boxes, each in a scope of its own in its cell (an env scope, `with_env`, or `ui.push_id`): the scope
/// holds none of the row's facts, so the grid's rows stay as high as the same grid's outside a row, and the boxes are
/// still in the grid's cells: the labels stay on one line and the two columns share each row.
#[trial]
fn check_boxes_in_scopes_in_an_egui_grid_in_a_row_keep_their_own_rows_and_lines() {
for (scope, wrap) in [("with_env", read_only as Wrap), ("push_id", pushed)] {
let (alone, _) = grid_in(false, wrap);
let (boxes, after, fixture) = grid_shown(true, wrap);
assert!((pitch(&boxes) - pitch(&alone)).abs() <= ROUNDING, "{scope}: the grid rows in a row {boxes:?} are as high as outside one {alone:?}");
let line = text(&fixture, "After").height();
for (row, (left, right)) in boxes.iter().enumerate() {
for name in [format!("Left {row}"), format!("Right {row}")] {
let label = text(&fixture, &name);
assert!(label.height() < line * 1.5, "{scope}: the label {name} {label:?} stays on one line");
}
assert!((left.center().y - right.center().y).abs() <= ROUNDING, "{scope}: the two columns share each row: {left:?} {right:?}");
assert!(right.left() >= left.right() - ROUNDING, "{scope}: the right column {right:?} follows the left {left:?}");
}
assert!(after.top() >= boxes[GRID_ROWS - 1].0.bottom() - ROUNDING, "{scope}: the button {after:?} is under the grid {boxes:?}");
}
}
/// Two columns of labelled check boxes in an `egui::Grid` share each row: the first column's labels are decided at
/// their own width, not wrapped in the narrow column egui offers a column it has no width for yet.
#[trial]
fn two_columns_of_labelled_check_boxes_in_an_egui_grid_share_each_row() {
let (boxes, _) = grid_in(false, plain);
for (left, right) in boxes {
assert!((left.center().y - right.center().y).abs() <= ROUNDING, "the two columns share each row: {left:?} {right:?}");
assert!(right.left() >= left.right() - ROUNDING, "the right column {right:?} follows the left {left:?}");
}
}
/// In a form whose labelled rows share a label column, check boxes in an `egui::Grid` in a full-width row (a dialog's
/// custom row) each sit at their cell's start: none takes the form's label-column indent.
#[trial]
fn check_boxes_in_an_egui_grid_in_a_forms_row_sit_at_their_cells_start() {
let seen = Rc::new(Cell::new([(Rect::NOTHING, Rect::NOTHING); GRID_ROWS]));
let out = Rc::clone(&seen);
let _fixture = settled(move |ui| {
let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(400.0, 600.0));
let out = Rc::clone(&out);
Stack::new().fill().show_at(ui, room, move |ui, _| {
FieldGroup::new("Mode").labels(LabelScheme::Form).show(ui, |ui, _| {
Field::new("Name").show(ui, |ui, _| {
Button::new("Pick").show(ui);
});
Row::new().fill().show(ui, |ui, _| out.set(boxes_grid(ui, plain)));
});
});
});
let boxes = seen.get();
for (row, (left, _)) in boxes.iter().enumerate() {
assert!((left.left() - boxes[0].0.left()).abs() <= ROUNDING, "row {row}'s box {left:?} starts where the first {:?} does", boxes[0].0);
}
}
/// A craft `Grid`'s cells are its craft children. A `ui.horizontal` an app shows in one is no cell: egui lays out its
/// check boxes side by side on one line and places it below the cells placed so far, at the grid's start edge, and the
/// next craft child takes the next cell, beside "Name".
#[trial]
fn check_boxes_in_an_egui_container_in_a_grid_take_no_cells() {
let seen = Rc::new(Cell::new([Rect::NOTHING; 5]));
let out = Rc::clone(&seen);
let fixture = settled(move |ui| {
let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(400.0, 400.0));
let out = Rc::clone(&out);
Stack::new().fill().show_at(ui, room, move |ui, _| {
let mut pair = (Rect::NOTHING, Rect::NOTHING);
Grid::new(&[ColumnWidth::Content, ColumnWidth::Content]).show(ui, |ui, _| {
Text::new("Name").show(ui);
Text::new("Size").show(ui);
pair = ui
.horizontal(|ui| {
let one = Checkbox::new(Bind::given(true)).label("One").show(ui).response.rect;
let two = Checkbox::new(Bind::given(true)).label("Two").show(ui).response.rect;
(one, two)
})
.inner;
});
let after = Button::new("After").show(ui).rect;
out.set([pair.0, pair.1, after, Rect::NOTHING, Rect::NOTHING]);
});
});
let [one, two, after, ..] = seen.get();
let (name, size) = (text(&fixture, "Name"), text(&fixture, "Size"));
assert!((one.center().y - two.center().y).abs() <= ROUNDING && two.left() >= one.right() - ROUNDING, "One {one:?}, then Two {two:?} on its line");
assert!(
(size.center().y - name.center().y).abs() <= ROUNDING && size.left() >= name.right() - ROUNDING,
"Size {size:?} takes the cell beside Name {name:?}"
);
assert!(one.top() >= name.bottom() - ROUNDING, "the pair {one:?} lies under Name's row {name:?}");
assert!(one.left() <= name.left() + ROUNDING, "the pair {one:?} starts at the grid's start edge, as Name {name:?} does");
assert!(after.top() >= one.bottom().max(two.bottom()) - ROUNDING, "the grid {after:?} reaches past the pair {one:?} {two:?}");
}
/// A check box in a `ui.horizontal` too narrow for its label wraps the label at the room's end: egui gives the
/// horizontal the room it has, and nothing runs past it.
#[trial]
fn a_check_box_in_a_narrow_horizontal_wraps_its_label_at_the_rooms_end() {
const LONG: &str = "Second option with a long name";
const WIDTH: f32 = 160.0;
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING)));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let out = Rc::clone(&out);
Stack::new().fill().show(ui, move |ui, _| {
let pair = ui.horizontal(|ui| {
let one = Checkbox::new(Bind::given(true)).label("One").show(ui).response.rect;
let two = Checkbox::new(Bind::given(false)).label(LONG).show(ui).response.rect;
(one, two)
});
out.set(pair.inner);
});
});
fixture.room(egui::vec2(WIDTH, 200.0)).settle();
fixture.idle(3);
let (_, two) = seen.get();
let (label, one_line) = (text(&fixture, LONG), text(&fixture, "One"));
assert!(label.right() <= WIDTH + ROUNDING, "the label {label:?} ends inside the room");
assert!(label.height() > one_line.height() * 1.5, "the label {label:?} wraps to a second line beside its box {two:?}");
}
/// One row of two labelled check boxes in an `egui::Grid` shown directly in a `Stack`, or in a `Row` in it (a dialog's
/// custom row), in a 400 pt room under `direction`; `long` lengthens the labels. Records the two boxes and the grid's
/// rect.
fn one_row_grid(in_row: bool, direction: craft_i18n::Direction, long: &Rc<Cell<bool>>) -> (Fixture, Rc<Cell<[Rect; 3]>>) {
let seen = Rc::new(Cell::new([Rect::NOTHING; 3]));
let (out, lengthen) = (Rc::clone(&seen), Rc::clone(long));
let mut fixture = Fixture::new(move |ui| {
let (out, long) = (Rc::clone(&out), lengthen.get());
let grid = move |ui: &mut egui::Ui| {
let mut boxes = [Rect::NOTHING; 3];
boxes[2] = egui::Grid::new("boxes")
.num_columns(2)
.spacing([24.0, 6.0])
.show(ui, |ui| {
for (column, rect) in boxes.iter_mut().take(2).enumerate() {
*rect = Checkbox::new(Bind::given(true)).label(column_name(column, long)).show(ui).response.rect;
}
ui.end_row();
})
.response
.rect;
out.set(boxes);
};
Stack::new().fill().show(ui, move |ui, _| {
if in_row {
Row::new().fill().show(ui, |ui, _| grid(ui));
} else {
grid(ui);
}
});
});
fixture.direction(direction).room(egui::vec2(400.0, 200.0)).settle();
(fixture, seen)
}
fn column_name(column: usize, long: bool) -> String {
if long { format!("Column {column} with a longer name") } else { format!("C{column}") }
}
/// What the cells of `one_row_grid` show: each column's box and label.
fn cells(fixture: &Fixture, boxes: [Rect; 3]) -> [Rect; 2] {
[0, 1].map(|column| boxes[column].union(text(fixture, &column_name(column, true))))
}
/// Under right-to-left, labelled check boxes in an `egui::Grid` shown directly in a right-to-left body, or in a row
/// there, stay in their cells: egui lays a grid out from its left edge in any direction, so the grid's rect is finite,
/// on the frame the labels lengthen the first column's box and label stay right of the grid's left edge, once settled
/// the second column stays clear of the first, and the cells take as much width as under left-to-right: the last
/// column is as wide as its box and label, not the rest of the room.
#[trial]
fn check_boxes_in_an_egui_grid_stay_in_their_cells_under_rtl() {
for in_row in [false, true] {
let ltr = {
let long = Rc::new(Cell::new(true));
let (mut fixture, seen) = one_row_grid(in_row, craft_i18n::Direction::Ltr, &long);
fixture.settle();
cells(&fixture, seen.get())
};
let long = Rc::new(Cell::new(false));
let (mut fixture, seen) = one_row_grid(in_row, craft_i18n::Direction::Rtl, &long);
let grid = seen.get()[2];
assert!(grid.is_finite(), "in a row {in_row}: the grid's rect {grid:?} is finite");
long.set(true);
fixture.frame(vec![]);
for (part, rect) in [("box", seen.get()[0]), ("label", text(&fixture, &column_name(0, true)))] {
assert!(
rect.left() >= grid.left() - ROUNDING,
"in a row {in_row}: the first column's {part} {rect:?} stays right of the grid's left edge {grid:?}"
);
}
fixture.settle();
let [first, second] = cells(&fixture, seen.get());
assert!(second.left() >= first.right() - ROUNDING, "in a row {in_row}: the second column {second:?} is clear of the first {first:?}");
let (width, ltr_width) = (first.union(second).width(), ltr[0].union(ltr[1]).width());
assert!((width - ltr_width).abs() <= ROUNDING, "in a row {in_row}: the cells take {width} under RTL, as under LTR ({ltr_width})");
}
}
/// A labelled container in an `egui::Grid`'s first column decides its label at its own width: the label stays on one
/// line, and the two columns share the row.
#[trial]
fn a_labelled_row_in_an_egui_grid_keeps_its_label_on_one_line() {
const LONG: &str = "Spacing between the rows";
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(400.0, 300.0));
let out = Rc::clone(&out);
Stack::new().fill().show_at(ui, room, move |ui, _| {
egui::Grid::new("rows").num_columns(2).show(ui, |ui| {
let mut first = Rect::NOTHING;
Field::new(LONG).show(ui, |ui, _| first = Button::new("Go").show(ui).rect);
let second = Button::new("Next").show(ui).rect;
ui.end_row();
out.set((first, second));
});
});
});
let (first, second) = seen.get();
let (label, go) = (text(&fixture, LONG), text(&fixture, "Go"));
assert!(label.height() < go.height() * 1.5, "the label {label:?} stays on one line");
assert!((first.center().y - second.center().y).abs() <= ROUNDING, "the two columns share the row: {first:?} {second:?}");
}
/// A small labelled check box in a plain `Lazy` in a row beside a button sits with its box on the button's line: a
/// `Lazy` runs its content as the row's direct children.
#[trial]
fn a_labelled_check_box_in_a_lazy_in_a_row_sits_on_the_rows_line() {
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING)));
let out = Rc::clone(&seen);
let _fixture = settled(move |ui| {
let out = Rc::clone(&out);
Row::new().show(ui, |ui, _| {
let button = Button::new("Go").show(ui).rect;
let mut check = Rect::NOTHING;
craft_ui::contract::Lazy::new("check", 0.0).show(ui, |ui| {
check = Checkbox::new(Bind::given(true)).label("Snap").size(ControlSize::Sm).show(ui).response.rect;
});
out.set((button, check));
});
});
let (button, check) = seen.get();
assert!((button.center().y - check.center().y).abs() <= ROUNDING, "the box {check:?} sits on the button's line {button:?}");
}
+121
View File
@@ -375,3 +375,124 @@ fn holding_alt_runs_the_memoized_view_of_a_menu_bar() {
fixture.hold(Modifiers::NONE);
assert!(frame(&mut fixture) > 0, "Alt coming up runs the view, which drops the underlines");
}
/// What a window's own Space does: the canvas's momentary Hand, say.
#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui::contract::CommandSet)]
#[command(prefix = "trialHand", scope = "trial.hand")]
#[non_exhaustive]
pub enum HandCommand {
#[command(label = "Hand", default = "Space")]
Hand,
}
/// Space on the menu bar that F10 or a lone Alt focused opens no menu: the press goes on to the window's own Space
/// command (a canvas's Hand), as in the reference application, where Space is always the Hand, and the shortcut gives
/// the keyboard back to the stop the bar took it from. Enter and Down still open the focused title's menu.
#[trial]
fn space_on_the_focused_bar_opens_no_menu_and_reaches_the_window() {
use craft_ui::buttons::Button;
use craft_ui::contract::ShowContainer as _;
use craft_ui::layout_components::Stack;
use craft_ui::runtime::commands::Commands as _;
use craft_ui::runtime::focus::{FocusTarget, request};
use std::cell::Cell;
use std::rc::Rc;
let (hands, clicks, button) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0)), Rc::new(Cell::new(None)));
let (seen_hands, seen_clicks, seen_button) = (Rc::clone(&hands), Rc::clone(&clicks), Rc::clone(&button));
let mut fixture = Fixture::new(move |ui| {
let titles = vec![MenuTitle::new("&File", |ui| {
MenuItem::new("&New").show(ui);
})];
MenuBar::new("Main menu", titles).show(ui);
Stack::new().command_scope(<HandCommand as craft_ui::contract::CommandSet>::SCOPE).show(ui, |ui, cx| {
while cx.take_command::<HandCommand>().is_some() {
seen_hands.set(seen_hands.get() + 1);
}
let shown = Button::new("Layer").show(ui);
if shown.clicked() {
seen_clicks.set(seen_clicks.get() + 1);
}
seen_button.set(Some(shown.response.id));
});
});
fixture.os(Os::Linux);
fixture.settle();
let layer = button.get().expect("the button ran");
for (enter, alt) in [(None, false), (None, true), (Some(Key::Enter), false), (Some(Key::ArrowDown), false)] {
request(fixture.ctx(), FocusTarget::Id(layer));
fixture.settle();
let before = (hands.get(), clicks.get());
if alt {
fixture.hold(Modifiers::ALT).settle();
fixture.hold(Modifiers::NONE).settle();
} else {
fixture.key(Key::F10, Modifiers::NONE);
fixture.settle();
}
assert!(fixture.focused_stop().is_some_and(|(id, _)| id != layer), "the bar takes the keyboard (alt {alt})");
if let Some(key) = enter {
fixture.key(key, Modifiers::NONE);
fixture.settle();
assert!(fixture.by_label("New").is_some(), "{key:?} opens the focused title's menu");
assert_eq!((hands.get(), clicks.get()), before, "{key:?} reaches neither the window nor the button");
fixture.key(Key::Escape, Modifiers::NONE);
fixture.key(Key::Escape, Modifiers::NONE);
fixture.settle();
continue;
}
fixture.key(Key::Space, Modifiers::NONE);
fixture.settle();
assert!(fixture.by_label("New").is_none(), "Space opens no menu (alt {alt})");
assert_eq!(fixture.focused_stop().map(|(id, _)| id), Some(layer), "Space takes the keyboard off the bar, back to the button (alt {alt})");
assert_eq!(hands.get(), before.0 + 1, "the press reaches the window's Space command (alt {alt})");
assert_eq!(clicks.get(), before.1, "and activates nothing else (alt {alt})");
}
}
/// With nothing focused the window's document canvas is the key target: a bar that F10 or a lone Alt focused then
/// gives the keyboard back to the canvas, so Space, the canvas's Hand, matches there and leaves the bar in one press.
#[trial]
fn space_on_a_bar_focused_from_nothing_goes_to_the_document_canvas() {
use craft_ui::contract::ShowContainer as _;
use craft_ui::layout_components::Stack;
use craft_ui::runtime::commands::Commands as _;
use craft_ui::runtime::focus::{KeyUse, host_canvas};
use std::cell::Cell;
use std::rc::Rc;
let canvas = egui::Id::unique("document canvas");
let hands = Rc::new(Cell::new(0));
let seen_hands = Rc::clone(&hands);
let mut fixture = Fixture::new(move |ui| {
let titles = vec![MenuTitle::new("&File", |ui| {
MenuItem::new("&New").show(ui);
})];
MenuBar::new("Main menu", titles).show(ui);
Stack::new().command_scope(<HandCommand as craft_ui::contract::CommandSet>::SCOPE).show(ui, |ui, cx| {
while cx.take_command::<HandCommand>().is_some() {
seen_hands.set(seen_hands.get() + 1);
}
let rect = ui.available_rect_before_wrap();
ui.interact(rect, canvas, egui::Sense::click());
host_canvas(ui.ctx(), canvas, KeyUse::CANVAS);
});
});
fixture.os(Os::Linux);
fixture.settle();
for alt in [false, true] {
assert!(fixture.focused_stop().is_none_or(|(id, _)| id == canvas), "nothing but the canvas holds the keyboard (alt {alt})");
if alt {
fixture.hold(Modifiers::ALT).settle();
fixture.hold(Modifiers::NONE).settle();
} else {
fixture.key(Key::F10, Modifiers::NONE);
fixture.settle();
}
assert!(fixture.focused_stop().is_some_and(|(id, _)| id != canvas), "the bar takes the keyboard (alt {alt})");
let before = hands.get();
fixture.key(Key::Space, Modifiers::NONE);
fixture.settle();
assert!(fixture.by_label("New").is_none(), "Space opens no menu (alt {alt})");
assert_eq!(hands.get(), before + 1, "Space reaches the canvas's command (alt {alt})");
assert_eq!(fixture.focused_stop().map(|(id, _)| id), Some(canvas), "and the keyboard goes to the canvas (alt {alt})");
}
}
@@ -1,9 +1 @@
config_version = 1
[[exception]]
name = "divider-length-content-extent"
kind = "marker"
rule = "props/point-size"
path = "crates/ui-widgets/src/display/divider.rs"
reason = "The length is the measured extent of the owner's content (a group as tall as its content and title), not a chosen size."
count = 1
+5 -1
View File
@@ -1837,6 +1837,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `const OVERLAYS: bool`. Whether the component hosts popups: `false` skips the overlay bookkeeping of steps 9, 10, 12, 15 and 16.
- `const PARTS: bool`. Whether the component declares parts, a text part or an editor part: `false` skips the parts step (the parts
- `const STOPS: bool`. Whether the component or its parts can take key focus: `false` skips the stop registration of step 7, except
- `const FOCUS_SCOPE: crate::runtime::focus::FocusPolicy`. The focus scope a leaf runs in, as `ContainerProps::focus` gives a container's: the leaf's own stop and its
- `const KEYS: crate::runtime::focus::KeyUse`. Keys the focused component keeps from egui and the shortcut dispatcher.
- `fn keys(&self) -> crate::runtime::focus::KeyUse`. The keys this instance keeps in its current state. The default is `KEYS`; a component whose key use depends
- `const SHOWS_LABEL: bool`. Whether the component paints its label as visible text. `false` for a face that shows only an icon or a
@@ -2910,7 +2911,9 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`.
- `pub fn scroll_bar(&self, look: &crate::style::ScrollBarLook, track: Rect, axis: craft_behavior::Axis, rtl: bool, span: &craft_behavior::ScrollSpan, state: &crate::style::StateSet,)`. Paints the scroll bar in `track` along `axis` for `span`, in the bar's `state` (`ScrollBar::shapes`;
- `pub fn rule_width(&self, kind: RuleKind) -> f32`. The width in points of the line `rule` paints for `kind`.
- `pub fn rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2)`. Paints the line `look` from `from` to `to`, snapped to physical pixels as `rule` is: a rule in a component's own
- `pub fn dotted_rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2, gap: f32)`. Paints the line `look` from `from` to `to` as dots `gap` points apart (`Rule::dotted`): a grip's dotted line.
- `pub fn dotted_rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2, gap: f32)`. Paints the line `look` from `from` to `to` as dots `gap` points apart (`Rule::dotted`): a dotted line.
- `pub fn ticked_rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2, gap: f32, across: f32)`. Paints the line `look` from `from` to `to` as ticks `across` points long, `gap` points apart (`Rule::ticks`):
- `pub fn grip_ticks(&self, look: &crate::style::RuleLook, centre: Pos2, count: u16, gap: f32, across: f32)`. Paints `count` upright ticks of `look` centred on `centre`, side by side on a level line, `gap` points apart and
- `pub fn surface(&self, rect: Rect, kind: SurfaceKind, corners: Corners)`. Paints a surface of `kind` (tracks, plot wells).
- `pub fn surface_styled(&self, rect: Rect, style: &SurfaceStyle)`. Paints a surface of an already resolved `style` (a kind's look with one field changed, as a knob's round radius).
- `pub fn surface_look(&self, rect: Rect, look: &crate::style::SurfaceLook, state: &crate::style::StateSet)`. Paints `look` over `rect` in `state`, as the paint step paints a component's surface: a part's own surface (an
@@ -3050,6 +3053,7 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`.
- `craft_ui::primitives::Rule`: `pub struct Rule`. The rule painter.
- `pub fn shapes(look: &RuleLook, from: Pos2, to: Pos2, pixels_per_point: f32) -> Vec<Shape>`. The line from `from` to `to`, snapped across its direction: a line whose physical width is odd sits on a
- `pub fn dotted(look: &RuleLook, from: Pos2, to: Pos2, gap: f32, pixels_per_point: f32) -> Vec<Shape>`. The dotted form of the line from `from` to `to`: square dots as wide as the line, `gap` points apart, the run
- `pub fn ticks(look: &RuleLook, from: Pos2, to: Pos2, gap: f32, across: f32, pixels_per_point: f32) -> Vec<Shape>`. The line from `from` to `to` as a run of ticks: marks as wide as the line along it and `across` points long
- `pub fn edge(look: &RuleLook, rect: Rect, side: RectSide, pixels_per_point: f32) -> Vec<Shape>`. The line along the `side` edge of `rect`, on the physical pixels just inside it: a row's bottom rule or a
- `craft_ui::primitives::RuleKind`: `pub enum RuleKind { Divider, Edge, Grid, DropMark }`. Which rule a look is for.
- `craft_ui::primitives::RulerFace`: `pub enum RulerFace { Edge, Centred }`. How a ruler lays out its marks and numbers. A ruler takes a face from its `face` prop, else from the scope's