Merge pull request #2934 from davidmann4/fix/photocraft-16332-grip-ticks

Docking: grips are the reference's upright ticks; a grip under a tool rail's column bar (photocraft#16332, photocraft#16333)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-22 01:37:10 +01:00
commit 4fc1e38945
10 files changed
+341 -59

No files matched your search

+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)]
}
@@ -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};
+57 -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 }
}
+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,
}
}
+36 -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, NoValue, 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,35 @@ 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.
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 held = GroupGrip::new(DragUnit::Group(anchor.clone()), PanelKey::of(shown))
.ticks(true)
.movable(scene.permissions(shown).movable)
.ghost(label.clone())
.label(label)
.show_at(ui, strip);
if held.drag_started {
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 +1014,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 +1029,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| {
@@ -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::runtime::drag;
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Ui, Vec2};
use std::cell::Cell;
use egui::{Rect, Shape, Ui, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
@@ -59,3 +61,86 @@ 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();
}
+4 -1
View File
@@ -2910,7 +2910,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 +3052,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