Rulers: an edge and a centred face, picked by the component set

`RulerFace { Edge, Centred }` sits beside `TickEdge`, and
`RulerFace::of(set)` maps the creative set to Edge and the office set to
Centred. The shared tick painter takes the face. Centred draws a bar
inset in the strip by `space.gap.tight`, centres the marks on it, and
puts a number in place of each whole-unit mark. No mark runs under a
number (`RulerFace::beside_numbers`), so a whole-unit tick shows only
where its number is dropped.

TextRuler, VerticalRuler and canvas Rulers take an optional `face` prop
in their style key. Unset, the style resolves it from the scope's set.
PageRulers passes its face to both of its rulers, and the timeline ruler
keeps the edge face.

Under Centred:
- the strip is on the chrome surface and the bar carries the margin
  shade and the text column on the well;
- numbers show only over the text area and are dropped where a marker
  stands;
- canvas Rulers shade their margin bands as the text ruler does.

Edge is the look the rulers had before. Each ruler gets an edge and a
centred story.
This commit is contained in:
aiongg
2026-11-20 18:23:17 +00:00
parent d395d4f831
commit 3f9adf355d
12 changed files with 567 additions and 113 deletions
+1
View File
@@ -58,6 +58,7 @@ const CLOSED: &[&str] = &[
"ReorderMove", // built or matched in craft-ui-patterns
"RowState", // built or matched in craft-ui-widgets
"RuleLook", // built or matched in craft-ui-canvas
"RulerFace", // matched by every ruler (craft-text, craft-pages, craft-ui-canvas): a new face must be drawn by each
"ShellRegions", // built or matched in craft-ui-shell
"SizeLimits", // built or matched in craft-ui-panels
"StoryOutput", // built or matched in craft-ui-widgets
+75 -23
View File
@@ -17,7 +17,7 @@ use craft_ui::contract::{
Access, Bind, Common, Component, Cx, Focus as _, IdSource, Input, MeasureCx, Name, NoValue, Numeric, Outcome, PaintUi, PartsCx, Pointer as _,
Props as _, Remember as _, Role, Show as _, Styled as _, WordSetCx as _,
};
use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun, Tick, TickEdge, TickRank};
use craft_ui::primitives::{PaintShape, RulerFace, StrokeWidth, TextRun, Tick, TickEdge, TickRank};
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeyUse};
use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, TextLook, TypeRole};
@@ -80,6 +80,10 @@ pub struct VerticalRulerStyle {
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// The face: the prop's, else the component set's.
face: RulerFace,
/// The strip round the centred face's bar.
strip: StyleColor,
/// The text range.
fill: StyleColor,
/// The margins above and below it.
@@ -113,6 +117,9 @@ struct Held(Option<(usize, f32)>);
/// shaded as margin and the text range filled, and a drag of a grip is one gesture.
///
/// - Ticks and numbers count from the page's top in the unit, through the canvas rulers' tick rule.
/// - The face ([`RulerFace`]) is the prop's, else the component set's: the edge face hangs the ticks from the strip's
/// inner edge with each number below its whole-unit tick; the centred face (Word's) draws a bar inset in the strip
/// with the ticks centred on it and the numbers in place of the whole-unit ticks, over the text range only.
/// - A grip drag reports a [`RowDrag`]: Begin, Update per move, Commit on release, Cancel on Escape. It snaps to the
/// ruler's step; Alt reports in `mods` that the drag is free of the snap and the position is not snapped.
/// - The grips are one Tab stop: Page Down and Page Up pick the next or previous grip, the arrows nudge the focused one
@@ -133,13 +140,17 @@ pub struct VerticalRuler<'a> {
/// The table row bottoms, points from the page's top, each a grip.
#[prop]
rows: &'a [f32],
/// The face; unset, the scope's component set picks it ([`RulerFace::of`]).
#[style_key]
#[prop]
face: Option<RulerFace>,
report: Option<RowDrag>,
}
impl<'a> VerticalRuler<'a> {
/// The ruler named `label` along `page`.
pub fn new(label: impl Into<Label>, page: &'a PlacedPage) -> Self {
VerticalRuler { common: Common::new(), page, text: None, unit: DocUnit::points(), rows: &[], report: None }.label(label)
VerticalRuler { common: Common::new(), page, text: None, unit: DocUnit::points(), rows: &[], face: None, report: None }.label(label)
}
/// Screen points per page point.
@@ -170,12 +181,14 @@ impl Component for VerticalRuler<'_> {
type Style = VerticalRulerStyle;
type Output = VerticalRulerOutput;
fn style(cx: &StyleCx<'_>, _: VerticalRulerStyleKey) -> VerticalRulerStyle {
fn style(cx: &StyleCx<'_>, key: VerticalRulerStyleKey) -> VerticalRulerStyle {
let tokens = cx.tokens;
let colors = &tokens.color;
VerticalRulerStyle {
metrics: Metrics::new(),
focus: cx.focus_look(),
face: key.face.unwrap_or(RulerFace::of(cx.set())),
strip: cx.color(colors.surface.chrome),
// As `TextRuler`'s: the text range is the light well, the margins are shaded as the desk round the page.
fill: cx.color(colors.surface.sunken),
margin: cx.color(colors.surface.canvas),
@@ -307,38 +320,61 @@ impl Component for VerticalRuler<'_> {
let text = ruler_text(self.unit, &numbers);
let per_doc = text.units.per_doc;
let shape = |rect: Rect| PaintShape::Rect(rect, CornerRadius::ZERO);
let draw = ui.draw();
draw.fill(&shape(rect), style.margin);
let face = style.face;
let bar = ui.content_painter(cx).ruler_bar(rect, TickEdge::Right, face);
let page = Rect::from_x_y_ranges(rect.x_range(), self.y(0.0)..=self.y(self.page_height())).intersect(rect);
if let Some(range) = self.text {
let band = Rect::from_x_y_ranges(rect.x_range(), self.y(range.min)..=self.y(range.max)).intersect(page);
if band.is_positive() {
draw.fill(&shape(band), style.fill);
let draw = ui.draw();
// The edge face shades the whole strip; the centred face shades the page's span of its bar on the strip's own
// surface.
match face {
RulerFace::Edge => draw.fill(&shape(rect), style.margin),
RulerFace::Centred => {
draw.fill(&shape(rect), style.strip);
draw.fill(&shape(Rect::from_x_y_ranges(bar.x_range(), page.y_range())), style.margin);
}
}
let text_band = self.text.map(|range| Rect::from_x_y_ranges(bar.x_range(), self.y(range.min)..=self.y(range.max)).intersect(page));
if let Some(band) = text_band.filter(|band| band.is_positive()) {
draw.fill(&shape(band), style.fill);
}
let grips: Vec<Rect> = self.rows.iter().map(|row| self.grip_rect(rect, style, *row)).collect();
let (lo, hi) = (((page.min.y - self.y(0.0)) / scale).max(0.0), ((page.max.y - self.y(0.0)) / scale).max(0.0));
let ticks: Vec<RulerTick> =
Rulers::ticks(&text.units, TickRule::of_unit(self.unit.kind), f64::from(scale), (f64::from(lo) * per_doc)..=(f64::from(hi) * per_doc));
let marks: Vec<Tick> = ticks
.iter()
.map(|tick| self.y((tick.value / per_doc) as f32))
.zip(ticks.iter())
.filter(|(y, _)| (page.min.y..=page.max.y).contains(y))
.map(|(y, tick)| Tick::new(y - rect.min.y, tick.rank))
.collect();
ui.content_painter(cx).ticks(rect, TickEdge::Right, &marks);
let draw = ui.draw();
let color: StyleColor = cx.resolve(&style.label.color);
// The centred face numbers the text range only, as a word processor's vertical ruler does.
let numbered_span = match face {
RulerFace::Edge => page,
RulerFace::Centred => text_band.unwrap_or(page),
};
let mut runs = Vec::new();
for tick in ticks.iter().filter(|tick| matches!(tick.rank, TickRank::Major)) {
let y = self.y((tick.value / per_doc) as f32);
let run = TextRun::new(text.tick_label(&numbers, tick.value, tick.step)).role(style.label.role).color(color);
let size = draw.layout(&run, f32::INFINITY).size();
let boxed = Rect::from_min_size(pos2(rect.min.x, y + style.pad), vec2(rect.width(), size.y));
if page.contains_rect(boxed) && size.x <= rect.width() && !grips.iter().any(|grip| grip.intersects(boxed)) {
draw.text(boxed, &run);
let boxed = match face {
RulerFace::Edge => Rect::from_min_size(pos2(rect.min.x, y + style.pad), vec2(rect.width(), size.y)),
RulerFace::Centred => RulerFace::centred_number(bar, TickEdge::Right, y, size),
};
let span = Rect::from_x_y_ranges(rect.x_range(), numbered_span.y_range());
if span.contains_rect(boxed) && size.x <= bar.width() && !grips.iter().any(|grip| grip.intersects(boxed)) {
runs.push((boxed, run));
}
}
let marks: Vec<Tick> = ticks
.iter()
.map(|tick| (self.y((tick.value / per_doc) as f32), tick))
.filter(|(y, _)| (page.min.y..=page.max.y).contains(y))
.map(|(y, tick)| Tick::new(y - bar.min.y, tick.rank))
.collect();
let boxes: Vec<Rect> = runs.iter().map(|(boxed, _)| *boxed).collect();
let marks = face.beside_numbers(TickEdge::Right, bar.min.y, marks, &boxes, style.pad);
ui.content_painter(cx).ticks(bar, TickEdge::Right, face, &marks);
let draw = ui.draw();
for (boxed, run) in &runs {
draw.text(*boxed, run);
}
for grip in &grips {
draw.fill(&shape(*grip), style.margin);
draw.stroke(&shape(*grip), StrokeWidth::Thin, style.marker);
@@ -374,7 +410,8 @@ pub struct PageRulersOutput {
/// their edges win. It shows no guides, no zero point and no units menu; `Rulers` is unchanged.
///
/// The text ruler counts from the text column's start edge and is cut to the page's width; the vertical ruler counts
/// from the page's top and shades the margins. The strips are as thick as the canvas rulers' strips.
/// from the page's top and shades the margins. The strips are as thick as the canvas rulers' strips. Both rulers take
/// the face given here, else the scope's component set's.
#[must_use = "show the rulers with `show_at`"]
#[derive(craft_ui::contract::Pattern)]
pub struct PageRulers<'a> {
@@ -393,6 +430,7 @@ pub struct PageRulers<'a> {
mirrored_even: bool,
id: IdSource,
gaps_draggable: bool,
face: Option<RulerFace>,
}
impl<'a> PageRulers<'a> {
@@ -414,9 +452,16 @@ impl<'a> PageRulers<'a> {
mirrored_even: false,
id: IdSource::Auto,
gaps_draggable: true,
face: None,
}
}
/// The face of both rulers ([`TextRuler::face`], [`VerticalRuler::face`]); unset, the scope's component set picks it.
pub fn face(mut self, face: RulerFace) -> Self {
self.face = Some(face);
self
}
/// Salts the text ruler's id with `salt` (the caret paragraph's key): a new salt is a new ruler, so a drag open on
/// the ruler of another paragraph ends with no commit.
pub fn id_salt(mut self, salt: impl AsIdSalt) -> Self {
@@ -503,6 +548,7 @@ impl<'a> PageRulers<'a> {
mirrored_even,
id,
gaps_draggable,
face,
} = self;
let (words, interface_rtl) = {
let env = Env::of(ui);
@@ -536,11 +582,17 @@ impl<'a> PageRulers<'a> {
if let Some(kind) = kind {
horizontal = horizontal.kind(kind);
}
if let Some(face) = face {
horizontal = horizontal.face(face);
}
let ruler_out = horizontal.show_at(ui, top_strip);
let vertical_label = Label::from(words.vertical.fill(&[("name", label.as_str())]));
let vertical =
VerticalRuler::new(vertical_label, page).text(Rangef::new(top as f32, bottom as f32)).unit(unit).rows(rows).show_at(ui, left_strip);
let mut vertical = VerticalRuler::new(vertical_label, page).text(Rangef::new(top as f32, bottom as f32)).unit(unit).rows(rows);
if let Some(face) = face {
vertical = vertical.face(face);
}
let vertical = vertical.show_at(ui, left_strip);
let margins_label = Label::from(words.margins.fill(&[("name", label.as_str())]));
let margins =
+39 -7
View File
@@ -10,6 +10,7 @@ use crate::ui::view::{PageView, PageViewState};
use craft_text::ui::DocUnit;
use craft_text::ui::ruler::{RulerValues, TabAlign};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::primitives::RulerFace;
use craft_ui::runtime::env::UnitKind;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::{Rangef, Rect, Ui, pos2, vec2};
@@ -37,8 +38,8 @@ fn inches() -> DocUnit {
DocUnit::new(UnitKind::Inches, 96.0)
}
/// The vertical ruler along a demo page, with `rows` and the text range when `text` is set.
fn vertical(ui: &mut Ui, rows: &[f32], text: Option<Rangef>) -> StoryOutput {
/// The vertical ruler along a demo page, with `rows`, the text range when `text` is set and `face` when set.
fn vertical(ui: &mut Ui, rows: &[f32], text: Option<Rangef>, face: Option<RulerFace>) -> StoryOutput {
let full = craft_ui::testing::stage(ui);
let page = demo_placed(1, pos2(full.min.x + STRIP, full.min.y + PAGE_TOP)).remove(0);
let strip = Rect::from_min_size(full.min, vec2(STRIP, full.height()));
@@ -46,21 +47,37 @@ fn vertical(ui: &mut Ui, rows: &[f32], text: Option<Rangef>) -> StoryOutput {
if let Some(range) = text {
ruler = ruler.text(range);
}
if let Some(face) = face {
ruler = ruler.face(face);
}
ruler.show_at(ui, strip).into()
}
#[story(VerticalRuler<'static>, covers = [Default], drive = Drive::Never)]
fn with_row_grips(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
vertical(ui, &ROWS, None)
vertical(ui, &ROWS, None, None)
}
#[story(VerticalRuler<'static>, covers = [], drive = Drive::Never)]
fn text_range_shaded(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
vertical(ui, &[], Some(Rangef::new(TEXT.0, TEXT.1)))
vertical(ui, &[], Some(Rangef::new(TEXT.0, TEXT.1)), None)
}
/// The edge face: ticks grow from the strip's inner edge, each number below its whole-unit tick.
#[story(VerticalRuler<'static>, covers = [], drive = Drive::Never)]
fn vertical_edge_face(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
vertical(ui, &ROWS, Some(Rangef::new(TEXT.0, TEXT.1)), Some(RulerFace::Edge))
}
/// The centred face (the office set's): a bar inset in the strip, ticks centred on it, numbers in place of the
/// whole-unit ticks over the text range only.
#[story(VerticalRuler<'static>, covers = [], drive = Drive::Never)]
fn vertical_centred_face(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
vertical(ui, &ROWS, Some(Rangef::new(TEXT.0, TEXT.1)), Some(RulerFace::Centred))
}
/// The rulers around one demo page, the margin edges and the paragraph's values kept in the story's data.
fn single_page(ui: &mut Ui, data: &mut StoryData, right_to_left: Option<bool>) -> StoryOutput {
fn single_page(ui: &mut Ui, data: &mut StoryData, right_to_left: Option<bool>, face: Option<RulerFace>) -> StoryOutput {
let full = craft_ui::testing::stage(ui);
let page = demo_placed(1, pos2(full.min.x + PAGE_LEFT, full.min.y + PAGE_TOP)).remove(0);
let state = data.value("rulers", (PageEdges::new(Margins::uniform(72.0)), RulerValues::default()));
@@ -74,6 +91,9 @@ fn single_page(ui: &mut Ui, data: &mut StoryData, right_to_left: Option<bool>) -
if right_to_left.is_some() {
rulers = rulers.right_to_left(right_to_left);
}
if let Some(face) = face {
rulers = rulers.face(face);
}
rulers.show_at(ui, full).margins.into()
}
@@ -92,10 +112,22 @@ fn multi_page_view_with_rulers_on_page_2(ui: &mut Ui, data: &mut StoryData) -> S
#[story(PageRulers<'static>, covers = [], drive = Drive::Never)]
fn table_and_two_columns(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
single_page(ui, data, None)
single_page(ui, data, None, None)
}
/// Both rulers in the edge face.
#[story(PageRulers<'static>, covers = [], drive = Drive::Never)]
fn page_edge_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
single_page(ui, data, None, Some(RulerFace::Edge))
}
/// Both rulers in the centred face (the office set's).
#[story(PageRulers<'static>, covers = [], drive = Drive::Never)]
fn page_centred_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
single_page(ui, data, None, Some(RulerFace::Centred))
}
#[story(PageRulers<'static>, covers = [], drive = Drive::Never)]
fn right_to_left(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
single_page(ui, data, Some(true))
single_page(ui, data, Some(true), None)
}
+16 -2
View File
@@ -20,6 +20,7 @@ use craft_ui::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Input, MeasureCx, Name, Numeric, Outcome, PaintUi, PartsCx, Props as _,
Role, WordSetCx as _,
};
use craft_ui::primitives::RulerFace;
use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeyUse};
use craft_ui::style::{ComponentStyle, Flags, FocusLook, Stateful, StyleColor, StyleCx, TextLook, TypeRole};
use egui::{Rect, Response, Vec2};
@@ -282,6 +283,10 @@ pub struct TextRulerStyle {
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// The face: the prop's, else the component set's.
face: RulerFace,
/// The strip round the centred face's bar.
strip: StyleColor,
/// The column.
fill: StyleColor,
/// The margins beside the column.
@@ -326,7 +331,9 @@ pub struct TextRulerStyle {
///
/// - Ticks and numbers in the unit through the canvas rulers' tick rule (inches follow Word's sixteenths), from the
/// column's start edge; numbers keep clear of the markers. The column takes the ruler's fill, the margins the
/// margin shade.
/// margin shade. The face ([`RulerFace`]) is the prop's, else the component set's: the edge face hangs the ticks
/// from the strip's bottom with each number beside its whole-unit tick; the centred face (Word's) draws a bar inset
/// in the strip with the ticks centred on it and the numbers in place of the whole-unit ticks.
/// - Indent markers (Word's): the first-line triangle down at the top, the hanging triangle up and the left box under
/// it at the bottom, the right triangle at the right. Dragging the box moves first-line and left together; Alt drags
/// freely (no snap).
@@ -388,6 +395,10 @@ pub struct TextRuler<'a> {
/// The stop shown picked.
#[prop(name = "picked_stop")]
selected: Option<usize>,
/// The face; unset, the scope's component set picks it ([`RulerFace::of`]).
#[style_key]
#[prop]
face: Option<RulerFace>,
report: Report,
}
@@ -408,6 +419,7 @@ impl<'a> TextRuler<'a> {
scale: None,
right_to_left: None,
selected: None,
face: None,
report: Report::default(),
}
.label(label)
@@ -478,12 +490,14 @@ impl Component for TextRuler<'_> {
type Style = TextRulerStyle;
type Output = TextRulerOutput;
fn style(cx: &StyleCx<'_>, _: TextRulerStyleKey) -> TextRulerStyle {
fn style(cx: &StyleCx<'_>, key: TextRulerStyleKey) -> TextRulerStyle {
let tokens = cx.tokens;
let colors = &tokens.color;
TextRulerStyle {
metrics: Metrics::new(),
focus: cx.focus_look(),
face: key.face.unwrap_or(RulerFace::of(cx.set())),
strip: cx.color(colors.surface.chrome),
// The column is the light well the text goes in; the margins are shaded as the desk round the page, so the
// column reads lighter than the margins in both modes.
fill: cx.color(colors.surface.sunken),
+43 -26
View File
@@ -6,7 +6,7 @@ use super::run::{Held, ruler_text};
use super::{TextRuler, TextRulerStyle};
use craft_ui::canvas::{RulerTick, Rulers, TickRule};
use craft_ui::contract::{Cx, Edit as _, PaintUi, Remember as _, Styled as _};
use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun, Tick, TickEdge, TickRank};
use craft_ui::primitives::{PaintShape, RulerFace, StrokeWidth, TextRun, Tick, TickEdge, TickRank};
use craft_ui::style::StyleColor;
use egui::{CornerRadius, Pos2, Rect, pos2, vec2};
@@ -17,15 +17,21 @@ impl TextRuler<'_> {
let (g, shapes) = (layout.g, layout.shapes);
let values = cx.value().cloned().unwrap_or_default();
let held = cx.recall::<Held>();
let draw = ui.draw();
let rect = |rect: Rect| PaintShape::Rect(rect, CornerRadius::ZERO);
let path = |a: Pos2, b: Pos2| PaintShape::Path(vec![a, b]);
let visible = g.visible();
draw.fill(&rect(visible), style.margin);
draw.fill(&rect(g.column().intersect(visible)), style.fill);
let bar = ui.content_painter(cx).ruler_bar(g.strip, TickEdge::Bottom, style.face);
// The edge face shades the whole strip; the centred face shades its bar on the strip's own surface.
let across = |part: Rect| Rect::from_x_y_ranges(part.x_range(), bar.y_range());
let draw = ui.draw();
if style.face == RulerFace::Centred {
draw.fill(&rect(g.strip), style.strip);
}
draw.fill(&rect(across(visible)), style.margin);
draw.fill(&rect(across(g.column().intersect(visible))), style.fill);
for (start, end) in self.gaps {
let (a, b) = (g.x(*start), g.x(*end));
let gap = Rect::from_x_y_ranges(a.min(b)..=a.max(b), g.strip.y_range()).intersect(visible);
let gap = Rect::from_x_y_ranges(a.min(b)..=a.max(b), bar.y_range()).intersect(visible);
if gap.is_positive() {
draw.fill(&rect(gap), style.margin);
}
@@ -114,34 +120,45 @@ impl TextRuler<'_> {
let (lo, hi) = g.shown_span();
let ticks: Vec<RulerTick> =
Rulers::ticks(&text.units, TickRule::of_unit(self.unit.kind), f64::from(g.scale), (f64::from(lo) * per_doc)..=(f64::from(hi) * per_doc));
let bar = ui.content_painter(cx).ruler_bar(g.strip, TickEdge::Bottom, style.face);
let draw = ui.draw();
let color: StyleColor = cx.resolve(&style.label.color);
// Numbers count from the column's start edge, so none stand in the margins.
let in_column = |at: f32| (0.0..=g.width).contains(&at);
let mut runs = Vec::new();
for tick in ticks.iter().filter(|tick| matches!(tick.rank, TickRank::Major)) {
if !in_column((tick.value / per_doc) as f32) {
continue;
}
let x = g.x((tick.value / per_doc) as f32);
let label = text.tick_label(&numbers, tick.value, tick.step);
let run = TextRun::new(label).role(style.label.role).color(color);
let size = draw.layout(&run, f32::INFINITY).size();
let boxed = match style.face {
RulerFace::Edge => {
let start = if g.right_to_left { x - style.pad - size.x } else { x + style.pad };
Rect::from_min_size(pos2(start, g.strip.top()), vec2(size.x, g.strip.height()))
}
RulerFace::Centred => RulerFace::centred_number(bar, TickEdge::Bottom, x, size),
};
if g.visible().contains_rect(boxed) && !keep_clear.iter().any(|clear| clear.intersects(boxed)) {
runs.push((boxed, run));
}
}
// The tick rule adds a labelled step beyond each end; a ruler cut to its extent (a page's) shows none past it.
let covered = g.visible().x_range();
let marks: Vec<Tick> = ticks
.iter()
.map(|tick| g.x((tick.value / per_doc) as f32))
.zip(&ticks)
.map(|tick| (g.x((tick.value / per_doc) as f32), tick))
.filter(|(x, _)| covered.contains(*x))
.map(|(x, tick)| Tick::new(x - g.strip.min.x, tick.rank))
.map(|(x, tick)| Tick::new(x - bar.min.x, tick.rank))
.collect();
ui.content_painter(cx).ticks(g.strip, TickEdge::Bottom, &marks);
let boxes: Vec<Rect> = runs.iter().map(|(boxed, _)| *boxed).collect();
let marks = style.face.beside_numbers(TickEdge::Bottom, bar.min.x, marks, &boxes, style.pad);
ui.content_painter(cx).ticks(bar, TickEdge::Bottom, style.face, &marks);
let draw = ui.draw();
let color: StyleColor = cx.resolve(&style.label.color);
// Numbers count from the column's start edge, so none stand in the margins.
let in_column = |tick: &&RulerTick| {
let at = (tick.value / per_doc) as f32;
(0.0..=g.width).contains(&at)
};
for tick in ticks.iter().filter(|tick| matches!(tick.rank, TickRank::Major)).filter(in_column) {
let x = g.x((tick.value / per_doc) as f32);
let label = text.tick_label(&numbers, tick.value, tick.step);
let run = TextRun::new(label).role(style.label.role).color(color);
let width = draw.layout(&run, f32::INFINITY).size().x;
let size = vec2(width, g.strip.height());
let at = if g.right_to_left { pos2(x - style.pad - width, g.strip.top()) } else { pos2(x + style.pad, g.strip.top()) };
let boxed = Rect::from_min_size(at, size);
if g.visible().contains_rect(boxed) && !keep_clear.iter().any(|clear| clear.intersects(boxed)) {
draw.text(boxed, &run);
}
for (boxed, run) in &runs {
draw.text(*boxed, run);
}
}
}
+26 -3
View File
@@ -7,6 +7,7 @@ use crate::ui::length::DocUnit;
use craft_behavior::Mixed;
use craft_ui::canvas::Rulers;
use craft_ui::contract::{Bind, Show as _, Validity};
use craft_ui::primitives::RulerFace;
use craft_ui::runtime::env::{Message, UnitKind};
use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story};
use egui::Ui;
@@ -85,8 +86,8 @@ const TWO_GAPS: [(f32, f32); 2] = [(144.0, 162.0), (306.0, 324.0)];
/// Three gaps in the text width, between four columns.
const THREE_GAPS: [(f32, f32); 3] = [(108.0, 126.0), (225.0, 243.0), (342.0, 360.0)];
#[story(TextRuler<'static>, covers = [], drive = Drive::Never)]
fn page_wide(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
/// Word's ruler over a page, its zero at the left margin, in `face` (unset: the component set's).
fn over_a_page(ui: &mut Ui, data: &mut StoryData, face: Option<RulerFace>) -> StoryOutput {
let values = data.value("values", word());
let stage = craft_ui::testing::stage(ui);
let (strip, _) = Rulers::strips(ui, stage);
@@ -96,7 +97,29 @@ fn page_wide(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
} else {
(strip.min.x + PAGE_MARGIN, egui::Rangef::new(strip.min.x, strip.min.x + PAGE))
};
TextRuler::new("Ruler", Bind::bound(&mut *values), COLUMN).unit(inches()).origin(origin).extent(extent).scale(1.0).show_at(ui, strip).into()
let mut ruler = TextRuler::new("Ruler", Bind::bound(&mut *values), COLUMN).unit(inches()).origin(origin).extent(extent).scale(1.0);
if let Some(face) = face {
ruler = ruler.face(face);
}
ruler.show_at(ui, strip).into()
}
#[story(TextRuler<'static>, covers = [], drive = Drive::Never)]
fn page_wide(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
over_a_page(ui, data, None)
}
/// The edge face: ticks rise from the strip's bottom, each number beside its whole-unit tick.
#[story(TextRuler<'static>, covers = [], drive = Drive::Never)]
fn edge_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
over_a_page(ui, data, Some(RulerFace::Edge))
}
/// The centred face (the office set's): a bar inset in the strip, ticks centred on it, numbers in place of the
/// whole-unit ticks over the column only.
#[story(TextRuler<'static>, covers = [], drive = Drive::Never)]
fn centred_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
over_a_page(ui, data, Some(RulerFace::Centred))
}
#[story(TextRuler<'static>, covers = [], drive = Drive::Never)]
+130
View File
@@ -4,11 +4,15 @@
use craft_behavior::GesturePhase;
use craft_text::ui::DocUnit;
use craft_text::ui::ruler::{GapDrag, GapEdge, RulerValues, TabAlign, TabLeader, TabStop, TextRuler};
use craft_theme::ComponentSet;
use craft_ui::buttons::Button;
use craft_ui::canvas::Rulers;
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::layout_components::Stack;
use craft_ui::popover::Popover;
use craft_ui::primitives::RulerFace;
use craft_ui::runtime::env::UnitKind;
use craft_ui::runtime::env::with_env;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Key, Modifiers, Vec2};
use std::cell::RefCell;
@@ -314,3 +318,129 @@ fn a_tab_stop_gesture_is_primary_only_cancellable_and_a_drag_off_the_ruler_clear
fixture.drag_at(at, Vec2::new(0.0, 80.0));
assert!(values.borrow().stops.is_empty(), "a release well away from the strip clears the stop");
}
/// What one frame of a page-wide ruler painted: its strip, its tick marks and its numbers.
struct Painted {
strip: egui::Rect,
ticks: Vec<egui::Rect>,
numbers: Vec<egui::Rect>,
}
/// The tick marks among `shapes`: thin upright lines inside `strip`.
fn tick_marks(shapes: &[egui::Shape], strip: egui::Rect) -> Vec<egui::Rect> {
shapes
.iter()
.map(egui::Shape::visual_bounding_rect)
.filter(|rect| rect.is_finite() && rect.width() <= 2.0 && rect.height() > 0.0)
.filter(|rect| strip.expand(0.5).contains_rect(*rect))
.collect()
}
/// A page-wide ruler in inches, shown with `face` when given, in a fixture whose root takes `set`; `popup` shows it in
/// an open popover inside a scope that sets the office set.
fn page_ruler(set: ComponentSet, face: Option<RulerFace>, popup: bool) -> (Fixture, Rc<RefCell<Option<egui::Rect>>>) {
let values = Rc::new(RefCell::new(RulerValues::default()));
let strip_at: Rc<RefCell<Option<egui::Rect>>> = Rc::new(RefCell::new(None));
let seen = strip_at.clone();
let mut fixture = Fixture::new(move |ui| {
let ruler = |ui: &mut egui::Ui| {
let stage = craft_ui::testing::stage(ui);
let (strip, _) = Rulers::strips(ui, stage);
*seen.borrow_mut() = Some(strip);
let mut values = values.borrow_mut();
let mut ruler = TextRuler::new("Ruler", Bind::bound(&mut *values), 432.0)
.unit(DocUnit::new(UnitKind::Inches, 96.0))
.origin(strip.min.x + 72.0)
.extent(egui::Rangef::new(strip.min.x, strip.min.x + 576.0))
.scale(1.0);
if let Some(face) = face {
ruler = ruler.face(face);
}
ruler.show_at(ui, strip);
};
if popup {
with_env(
ui,
|env| {
env.values.set(ComponentSet::Office);
},
|ui| {
Popover::new("Card", Bind::given(true)).show(ui, |ui, _| ruler(ui));
},
);
} else {
ruler(ui);
}
});
fixture.set(set);
fixture.settle();
(fixture, strip_at)
}
/// The latest paint of `fixture`.
fn painted(fixture: &mut Fixture, strip_at: &Rc<RefCell<Option<egui::Rect>>>) -> Painted {
let shapes = fixture.frame_shapes();
let strip = strip_at.borrow().expect("the ruler showed");
Painted { strip, ticks: tick_marks(&shapes, strip), numbers: numbers(fixture) }
}
/// Whether the ruler paints the centred face: every tick is centred on the strip's middle line and clear of its edges,
/// and every number is centred on that line with no tick under it.
fn centred(p: &Painted) -> bool {
let middle = p.strip.center().y;
!p.ticks.is_empty()
&& !p.numbers.is_empty()
&& p.ticks.iter().all(|tick| (tick.center().y - middle).abs() < 1.0 && tick.max.y < p.strip.max.y - 1.0)
&& p.numbers.iter().all(|number| (number.center().y - middle).abs() < 1.0)
&& p.numbers.iter().all(|number| !p.ticks.iter().any(|tick| number.x_range().contains(tick.center().x)))
}
/// Whether the ruler paints the edge face: every tick rises from the strip's bottom edge.
fn edge(p: &Painted) -> bool {
!p.ticks.is_empty() && p.ticks.iter().all(|tick| (tick.max.y - p.strip.max.y).abs() < 1.0)
}
/// With no face given, the component set picks it: the office set's ruler centres its marks on a bar and puts numbers
/// in place of the whole-unit ticks, the creative set's hangs them from the strip's bottom edge.
#[trial]
fn the_component_set_picks_the_ruler_face() {
let (mut fixture, strip) = page_ruler(ComponentSet::Office, None, false);
let office = painted(&mut fixture, &strip);
assert!(centred(&office), "the office set paints the centred face: ticks {:?}, numbers {:?}", office.ticks, office.numbers);
let (mut fixture, strip) = page_ruler(ComponentSet::Creative, None, false);
let creative = painted(&mut fixture, &strip);
assert!(edge(&creative), "the creative set paints the edge face: ticks {:?}", creative.ticks);
}
/// A face given on the ruler wins over the component set.
#[trial]
fn a_given_face_wins_over_the_component_set() {
let (mut fixture, strip) = page_ruler(ComponentSet::Office, Some(RulerFace::Edge), false);
let given_edge = painted(&mut fixture, &strip);
assert!(edge(&given_edge), "the edge face under the office set: ticks {:?}", given_edge.ticks);
let (mut fixture, strip) = page_ruler(ComponentSet::Creative, Some(RulerFace::Centred), false);
let given_centred = painted(&mut fixture, &strip);
assert!(centred(&given_centred), "the centred face under the creative set: ticks {:?}", given_centred.ticks);
}
/// A scope's component set reaches a popup opened inside it, though the root's set is another.
#[trial]
fn a_scopes_component_set_reaches_a_popup_opened_inside_it() {
let (mut fixture, strip) = page_ruler(ComponentSet::Creative, None, true);
let in_popup = painted(&mut fixture, &strip);
assert!(centred(&in_popup), "the popup's ruler takes the scope's office set: ticks {:?}", in_popup.ticks);
}
/// A set change restyles the ruler in the frame it arrives in, in one pass, and the frame after asks for nothing more.
#[trial]
fn a_component_set_change_restyles_the_ruler_in_one_pass_and_then_rests() {
let (mut fixture, strip) = page_ruler(ComponentSet::Creative, None, false);
assert!(edge(&painted(&mut fixture, &strip)));
fixture.set(ComponentSet::Office);
let changed = painted(&mut fixture, &strip);
assert!(centred(&changed), "the frame of the change paints the office face");
assert_eq!(fixture.passes(), 1, "the change takes one pass");
fixture.idle(1);
assert_eq!(fixture.passes(), 1);
assert!(!fixture.repaint_requested(), "an idle frame after the change asks for no repaint");
}
+2 -2
View File
@@ -11,7 +11,7 @@ use craft_ui::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Numeric, Outcome, PaintUi, PartsCx,
Pointer as _, Props, Role, Styled as _, WordSetCx as _,
};
use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun, Tick as TickMark, TickEdge, TickRank};
use craft_ui::primitives::{PaintShape, RulerFace, StrokeWidth, TextRun, Tick as TickMark, TickEdge, TickRank};
use craft_ui::runtime::env::Label;
use craft_ui::runtime::focus::{ActivateKeys, KeyUse};
use craft_ui::style::{ComponentStyle, FocusLook, Stateful, StyleColor, StyleCx, TextLook, TypeRole, UiTokens};
@@ -613,7 +613,7 @@ impl Component for TimelineRuler<'_> {
let ticks = ruler_ticks(&axis, rect.width(), ruler_ladder(rate.timecode_base(), style.line));
let marks: Vec<TickMark> = ticks.iter().map(|tick| TickMark::new(axis.x_of(tick.at, left) - left, tick.rank)).collect();
ui.content_painter(cx).ticks(body, TickEdge::Bottom, &marks);
ui.content_painter(cx).ticks(body, TickEdge::Bottom, RulerFace::Edge, &marks);
let color = cx.resolve(&style.label.color);
for (tick, text) in ticks.iter().filter_map(|tick| tick.label.as_ref().map(|text| (tick, text))) {
let layout = draw.layout(&TextRun::new(text.as_str()).role(style.label.role).color(color), f32::INFINITY);
+96 -34
View File
@@ -16,7 +16,7 @@ use crate::contract::{
PaintUi, PartsCx, Pointer as _, Props as _, Role, Styled as _, WordSetCx as _,
};
use crate::menu::Menu;
use crate::primitives::{PaintShape, RectSide, StrokeWidth, TextRun, Tick, TickEdge, TickRank};
use crate::primitives::{PaintShape, RectSide, RulerFace, StrokeWidth, TextRun, Tick, TickEdge, TickRank};
use crate::runtime::env::{Label, UnitKind};
use crate::runtime::focus::KeyUse;
use crate::runtime::memory::Remember as _;
@@ -137,8 +137,14 @@ pub struct RulersStyle {
pad: f32,
/// How far a vertical label's next character sits below the one before: the label role's size.
pitch: f32,
/// The face: the prop's, else the component set's.
face: RulerFace,
/// The strips and the corner.
fill: StyleColor,
margin: StyleColor,
/// The well: the edge face's margin bands, the centred face's bar.
well: StyleColor,
/// The centred face's margin bands, shaded as the desk round the page.
shade: StyleColor,
label: TextLook,
marker: StyleColor,
}
@@ -212,6 +218,10 @@ pub struct Rulers<'a> {
/// no menu.
#[prop]
units: Option<&'a [UnitKind]>,
/// The face; unset, the scope's component set picks it ([`RulerFace::of`]).
#[style_key]
#[prop]
face: Option<RulerFace>,
/// The canvas's space and snap in this pass, which the canvas hands to the rulers it shows.
space: Option<CanvasSpace>,
snap: Option<Snap>,
@@ -231,6 +241,7 @@ impl<'a> Rulers<'a> {
interactive: true,
margins: RulerMargins::default(),
units: None,
face: None,
space: None,
snap: None,
guide: None,
@@ -357,15 +368,17 @@ impl Component for Rulers<'_> {
type Style = RulersStyle;
type Output = RulersOutput;
fn style(cx: &StyleCx<'_>, _: RulersStyleKey) -> RulersStyle {
fn style(cx: &StyleCx<'_>, key: RulersStyleKey) -> RulersStyle {
let c = &cx.tokens.color;
RulersStyle {
metrics: Metrics::new(),
thickness: thickness(cx.tokens),
pad: cx.tokens.space.gap.tight,
pitch: cx.tokens.typography.get(LABEL_ROLE).size,
face: key.face.unwrap_or(RulerFace::of(cx.set())),
fill: cx.color(c.surface.chrome),
margin: cx.color(c.surface.sunken),
well: cx.color(c.surface.sunken),
shade: cx.color(c.surface.canvas),
label: TextLook::new(LABEL_ROLE, Stateful::new(cx.color(c.text.muted))),
marker: cx.color(c.text.normal),
}
@@ -520,11 +533,39 @@ impl Component for Rulers<'_> {
draw.fill(&rect(corner), style.fill);
return;
};
let face = style.face;
let level = space.view.level(zero);
let rulers = space.rulers();
let text_of = |part: RulerPart| if part == RulerPart::Vertical { rulers.y } else { rulers.x };
for (part, strip, spans) in [(RulerPart::Horizontal, top, &self.margins.horizontal), (RulerPart::Vertical, left, &self.margins.vertical)] {
let vertical = part == RulerPart::Vertical;
// The divider is painted inside each strip's inner edge; the ticks keep clear of it so they keep their full
// length, and the centred face's bar is inset in what is left.
let band = draw.rule_width(RuleKind::Divider);
let tick_strip = |part: RulerPart, strip: Rect| {
if part == RulerPart::Vertical {
Rect::from_min_max(strip.min, Pos2::new(strip.right() - band, strip.bottom()))
} else {
Rect::from_min_max(strip.min, Pos2::new(strip.right(), strip.bottom() - band))
}
};
let painter = ui.content_painter(cx);
let parts = [(RulerPart::Horizontal, top, TickEdge::Bottom), (RulerPart::Vertical, left, TickEdge::Right)];
let bars = parts.map(|(part, strip, edge)| painter.ruler_bar(tick_strip(part, strip), edge, face));
if face == RulerFace::Centred {
for bar in &bars {
draw.fill(&rect(*bar), style.well);
}
}
// The edge face shades the margin bands across the strip in the well colour; the centred face shades them on
// its bar, as the text ruler shades its margins.
let mut margin_bands: [Vec<Rect>; 2] = [Vec::new(), Vec::new()];
for (((part, strip, _), spans), (bar, bands)) in
parts.iter().zip([&self.margins.horizontal, &self.margins.vertical]).zip(bars.iter().zip(margin_bands.iter_mut()))
{
let vertical = *part == RulerPart::Vertical;
let across = match face {
RulerFace::Edge => *strip,
RulerFace::Centred => *bar,
};
for span in spans {
let at = |along: f64| {
let p = if vertical { Point::new(zero.x, along) } else { Point::new(along, zero.y) };
@@ -533,59 +574,80 @@ impl Component for Rulers<'_> {
};
let (a, b) = (at(span.start), at(span.end));
let (lo, hi) = (a.min(b), a.max(b));
let band = if vertical {
Rect::from_min_max(Pos2::new(strip.left(), lo), Pos2::new(strip.right(), hi))
let shaded = if vertical {
Rect::from_min_max(Pos2::new(across.left(), lo), Pos2::new(across.right(), hi))
} else {
Rect::from_min_max(Pos2::new(lo, strip.top()), Pos2::new(hi, strip.bottom()))
Rect::from_min_max(Pos2::new(lo, across.top()), Pos2::new(hi, across.bottom()))
};
let band = band.intersect(strip);
if band.is_positive() {
draw.fill(&rect(band), style.margin);
let shaded = shaded.intersect(across);
if shaded.is_positive() {
draw.fill(&rect(shaded), if face == RulerFace::Centred { style.shade } else { style.well });
bands.push(shaded);
}
}
}
let painter = ui.content_painter(cx);
let numbers = cx.env.units();
let label = &style.label;
let color = cx.resolve(&label.color);
// A label is painted where the strip shows it: it overlaps the strip and stays inside the rulers' rect, so a
// label that hangs off an end of the strip is left out.
// label that hangs off an end of the strip is left out. The centred face numbers no margin band.
let shows = |strip: Rect, text: Rect| text.intersects(strip) && cx.rect.contains_rect(text);
for (part, strip, edge) in [(RulerPart::Horizontal, top, TickEdge::Bottom), (RulerPart::Vertical, left, TickEdge::Right)] {
for (((part, strip, edge), bar), bands) in parts.into_iter().zip(bars).zip(&margin_bands) {
let vertical = part == RulerPart::Vertical;
let ticks = Self::axis_ticks(&text_of(part), &level, strip, part, zero);
let marks: Vec<Tick> =
ticks.iter().map(|(tick, at)| Tick::new(*at - if vertical { strip.top() } else { strip.left() }, tick.rank)).collect();
// The divider is painted inside the strip's inner edge; the ticks hang from its inner side so they keep their full length.
let band = draw.rule_width(RuleKind::Divider);
let tick_strip = if vertical {
Rect::from_min_max(strip.min, Pos2::new(strip.right() - band, strip.bottom()))
} else {
Rect::from_min_max(strip.min, Pos2::new(strip.right(), strip.bottom() - band))
};
painter.ticks(tick_strip, edge, &marks);
let mut galleys = Vec::new();
for (tick, at) in ticks.iter().filter(|(tick, _)| tick.rank == TickRank::Major) {
let text = text_of(part).tick_label(&numbers, tick.value, tick.step);
if vertical {
// One character per line, centred in the strip: a narrow "1" lines up with a "0".
let mut y = at + style.pad;
for ch in text.chars() {
let layout = draw.layout(&TextRun::new(ch.to_string()).role(label.role).color(color), f32::INFINITY);
let at = Pos2::new(strip.center().x - layout.size().x / 2.0, y);
let layouts: Vec<_> =
text.chars().map(|ch| draw.layout(&TextRun::new(ch.to_string()).role(label.role).color(color), f32::INFINITY)).collect();
let mut y = match face {
RulerFace::Edge => at + style.pad,
RulerFace::Centred => at - style.pitch * layouts.len() as f32 / 2.0,
};
let middle = match face {
RulerFace::Edge => strip.center().x,
RulerFace::Centred => bar.center().x,
};
let placed: Vec<_> = layouts
.into_iter()
.map(|layout| {
let at = Pos2::new(middle - layout.size().x / 2.0, y);
y += style.pitch;
(at, layout)
})
.collect();
let column = placed.iter().fold(Rect::NOTHING, |all, (at, layout)| all.union(Rect::from_min_size(*at, layout.size())));
if face == RulerFace::Centred && (!shows(strip, column) || bands.iter().any(|band| band.intersects(column))) {
continue;
}
for (at, layout) in placed {
if shows(strip, Rect::from_min_size(at, layout.size())) {
draw.galley(at, &layout);
galleys.push((at, layout));
}
y += style.pitch;
}
} else {
let layout = draw.layout(&TextRun::new(text).role(label.role).color(color), f32::INFINITY);
let at = Pos2::new(at + style.pad, strip.top() + style.pad);
if shows(strip, Rect::from_min_size(at, layout.size())) {
draw.galley(at, &layout);
let boxed = match face {
RulerFace::Edge => Rect::from_min_size(Pos2::new(at + style.pad, strip.top() + style.pad), layout.size()),
RulerFace::Centred => RulerFace::centred_number(bar, edge, *at, layout.size()),
};
let clear = face == RulerFace::Edge || !bands.iter().any(|band| band.intersects(boxed));
if shows(strip, boxed) && clear {
galleys.push((boxed.min, layout));
}
}
}
let origin = if vertical { bar.top() } else { bar.left() };
let marks: Vec<Tick> = ticks.iter().map(|(tick, at)| Tick::new(*at - origin, tick.rank)).collect();
let boxes: Vec<Rect> = galleys.iter().map(|(at, layout)| Rect::from_min_size(*at, layout.size())).collect();
let marks = face.beside_numbers(edge, origin, marks, &boxes, style.pad);
painter.ticks(bar, edge, face, &marks);
for (at, layout) in &galleys {
draw.galley(*at, layout);
}
}
if let Some(at) = crate::runtime::pointer::frame(&cx.core.ctx).pos.filter(|at| cx.rect.contains(*at)) {
+33 -2
View File
@@ -1,9 +1,10 @@
//! Stories of the rulers.
use super::{CORNER, Rulers};
use super::{CORNER, RulerMargins, Rulers};
use crate::canvas::testing::canvas_story::{StoryDocument, on_ruled_canvas};
use crate::canvas::{Canvas, RulerText};
use crate::canvas::{Canvas, RasterSource as _, RulerText};
use crate::contract::{Bind, Validity};
use crate::primitives::RulerFace;
use crate::runtime::env::{Message, UnitKind};
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use crate::testing::{pointer, stage};
@@ -17,6 +18,9 @@ const DRAG_THRESHOLDS: f32 = 12.0;
/// The least x the invalid story accepts for the zero point.
const LEAST_X: f64 = 0.0;
/// The margin the face stories shade on each side of the document, pixels.
const MARGIN: f64 = 48.0;
/// The units the menu story offers.
const UNITS: [UnitKind; 2] = [UnitKind::Pixels, UnitKind::Points];
@@ -115,3 +119,30 @@ fn zero_point_left_of_the_document(ui: &mut Ui, data: &mut StoryData) -> StoryOu
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", Bind::bound(&mut *zero).check(inside)));
on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD))
}
/// The rulers in `face` with the document's margins shaded.
fn in_face(ui: &mut Ui, data: &mut StoryData, face: RulerFace) -> StoryOutput {
let settings = settings(data);
let zero = data.value("zero", Point::ZERO);
let room = stage(ui);
let size = StoryDocument::STANDARD.size();
let (width, height) = (f64::from(size.width), f64::from(size.height));
let margins = RulerMargins::new([0.0..MARGIN, width - MARGIN..width], [0.0..MARGIN, height - MARGIN..height]);
let rulers = Rulers::new("Rulers", Bind::bound(&mut *zero)).margins(margins).face(face);
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, rulers);
on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD))
}
/// The edge face: ticks rise from each strip's inner edge, each label beside its major tick, the margins in the well
/// colour.
#[story(Rulers<'static>, covers = [], drive = Drive::Never)]
fn edge_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
in_face(ui, data, RulerFace::Edge)
}
/// The centred face (the office set's): a bar inset in each strip, ticks centred on it, labels in place of the major
/// ticks and none over the shaded margins.
#[story(Rulers<'static>, covers = [], drive = Drive::Never)]
fn centred_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
in_face(ui, data, RulerFace::Centred)
}
+104 -12
View File
@@ -30,6 +30,79 @@ pub enum TickEdge {
Right,
}
impl TickEdge {
/// Whether positions run along x (a top or bottom edge).
pub const fn horizontal(self) -> bool {
matches!(self, TickEdge::Bottom | TickEdge::Top)
}
}
/// How a ruler lays out its marks and numbers. A ruler takes a face from its `face` prop, else from the scope's
/// component set ([`RulerFace::of`]); the face changes the arrangement only, every value still comes from the same
/// tokens.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum RulerFace {
/// Marks rise from the strip's inner edge, a major one across the strip's depth, and each number sits beside its
/// major mark.
#[default]
Edge,
/// A bar inset in the strip by `BAR_INSET` carries the marks centred on it, and a number stands in place of
/// each major mark; a major mark shows only where its number is dropped.
Centred,
}
impl RulerFace {
/// The face the component set `set` shows: the creative set the edge face, the office set the centred one.
pub const fn of(set: craft_theme::ComponentSet) -> Self {
match set {
craft_theme::ComponentSet::Creative => RulerFace::Edge,
craft_theme::ComponentSet::Office => RulerFace::Centred,
}
}
/// Where the marks of a strip along `edge` sit: the whole strip for the edge face, the strip inset across its
/// depth by `BAR_INSET` on each side for the centred face.
pub fn bar(self, strip: Rect, edge: TickEdge) -> Rect {
match self {
RulerFace::Edge => strip,
RulerFace::Centred => {
if edge.horizontal() {
strip.shrink2(Vec2::new(0.0, BAR_INSET))
} else {
strip.shrink2(Vec2::new(BAR_INSET, 0.0))
}
}
}
}
/// The marks of `marks` this face shows beside the numbers in `numbers` (screen boxes): the edge face shows every
/// mark, the centred face leaves out each one whose position lies inside a number widened by `pad` along `edge`'s
/// axis, so a number stands in place of its own mark and no mark runs through one. `origin` is the screen position
/// the marks' `at` counts from.
pub fn beside_numbers(self, edge: TickEdge, origin: f32, marks: Vec<Tick>, numbers: &[Rect], pad: f32) -> Vec<Tick> {
match self {
RulerFace::Edge => marks,
RulerFace::Centred => marks
.into_iter()
.filter(|mark| {
let at = origin + mark.at;
!numbers.iter().any(|number| {
let along = if edge.horizontal() { number.x_range() } else { number.y_range() };
(along.min - pad..=along.max + pad).contains(&at)
})
})
.collect(),
}
}
/// The box a centred number of `size` takes for the mark at `at` (a screen position along `edge`'s axis): centred
/// on the mark and on the bar.
pub fn centred_number(bar: Rect, edge: TickEdge, at: f32, size: Vec2) -> Rect {
let centre = if edge.horizontal() { pos2(at, bar.center().y) } else { pos2(bar.center().x, at) };
Rect::from_center_size(centre, size)
}
}
/// How long a tick is: the rank it has among its neighbours.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
@@ -38,7 +111,7 @@ pub enum TickRank {
Minor,
/// Halfway between two major ticks, `TICK_MID` long.
Mid,
/// The longest, across the ruler's depth.
/// The longest: across the depth of the rect the marks are painted in.
Major,
}
@@ -48,6 +121,9 @@ const TICK_MINOR: f32 = 3.0;
/// The length of the tick halfway between two major ticks, in points, in every density.
const TICK_MID: f32 = 6.0;
/// How far the centred face's bar sits inside the ruler strip on each side across its depth.
const BAR_INSET: f32 = 2.0;
/// One tick: where it sits along its edge and how long it is.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
@@ -624,9 +700,10 @@ pub fn grid_lines_with(look: &GridLook, grid: &GridLines, ink: &GridInk, pixels_
shapes
}
/// The tick marks of `ticks` on one edge of `rect` that `clip` shows, `stroke.thin` lines of `text.faint`: minor ones
/// `TICK_MINOR` long, mid ones `TICK_MID`, major ones across the whole depth of `rect`, beside their labels.
pub fn ticks(tokens: &UiTokens, rect: Rect, edge: TickEdge, ticks: &[Tick], clip: Rect, pixels_per_point: f32) -> Vec<Shape> {
/// The tick marks of `ticks` along `edge` of `rect` that `clip` shows, `stroke.thin` lines of `text.faint`: minor ones
/// `TICK_MINOR` long, mid ones `TICK_MID`, major ones across the whole depth of `rect`. The edge
/// face hangs them from `edge`; the centred face centres them on `rect`'s middle line (`rect` is then the face's bar).
pub fn ticks(tokens: &UiTokens, rect: Rect, edge: TickEdge, face: RulerFace, ticks: &[Tick], clip: Rect, pixels_per_point: f32) -> Vec<Shape> {
let look = RuleLook { color: rgba_color(tokens.color.text.faint), width: RuleWidth::Points(tokens.stroke.thin) };
let depth = match edge {
TickEdge::Bottom | TickEdge::Top => rect.height(),
@@ -640,11 +717,21 @@ pub fn ticks(tokens: &UiTokens, rect: Rect, edge: TickEdge, ticks: &[Tick], clip
TickRank::Mid => TICK_MID,
TickRank::Major => depth,
};
let (from, to) = match edge {
TickEdge::Bottom => (pos2(rect.left() + tick.at, rect.bottom()), pos2(rect.left() + tick.at, rect.bottom() - length)),
TickEdge::Top => (pos2(rect.left() + tick.at, rect.top()), pos2(rect.left() + tick.at, rect.top() + length)),
TickEdge::Left => (pos2(rect.left(), rect.top() + tick.at), pos2(rect.left() + length, rect.top() + tick.at)),
TickEdge::Right => (pos2(rect.right(), rect.top() + tick.at), pos2(rect.right() - length, rect.top() + tick.at)),
let (from, to) = match (face, edge) {
(RulerFace::Edge, TickEdge::Bottom) => {
(pos2(rect.left() + tick.at, rect.bottom()), pos2(rect.left() + tick.at, rect.bottom() - length))
}
(RulerFace::Edge, TickEdge::Top) => (pos2(rect.left() + tick.at, rect.top()), pos2(rect.left() + tick.at, rect.top() + length)),
(RulerFace::Edge, TickEdge::Left) => (pos2(rect.left(), rect.top() + tick.at), pos2(rect.left() + length, rect.top() + tick.at)),
(RulerFace::Edge, TickEdge::Right) => (pos2(rect.right(), rect.top() + tick.at), pos2(rect.right() - length, rect.top() + tick.at)),
(RulerFace::Centred, TickEdge::Bottom | TickEdge::Top) => {
let (x, y) = (rect.left() + tick.at, rect.center().y);
(pos2(x, y - length / 2.0), pos2(x, y + length / 2.0))
}
(RulerFace::Centred, TickEdge::Left | TickEdge::Right) => {
let (x, y) = (rect.center().x, rect.top() + tick.at);
(pos2(x - length / 2.0, y), pos2(x + length / 2.0, y))
}
};
clip.intersects(Rect::from_two_pos(from, to)).then(|| Rule::shapes(&look, from, to, pixels_per_point))
})
@@ -928,9 +1015,14 @@ impl ContentPainterCx<'_> {
super::draw::data_checker(&self.painter, self.tokens, self.data, checker, rect, radius);
}
/// Paints tick marks on one edge of `rect`.
pub fn ticks(&self, rect: Rect, edge: TickEdge, marks: &[Tick]) {
self.painter.extend(ticks(self.tokens, rect, edge, marks, self.painter.clip_rect(), self.ppp()));
/// Where the marks of a ruler strip along `edge` sit in `face`; see [`RulerFace::bar`].
pub fn ruler_bar(&self, strip: Rect, edge: TickEdge, face: RulerFace) -> Rect {
face.bar(strip, edge)
}
/// Paints tick marks along `edge` of `rect` in `face`; see [`ticks`].
pub fn ticks(&self, rect: Rect, edge: TickEdge, face: RulerFace, marks: &[Tick]) {
self.painter.extend(ticks(self.tokens, rect, edge, face, marks, self.painter.clip_rect(), self.ppp()));
}
/// Paints a halo-and-line outline of `shape`.
+2 -2
View File
@@ -40,8 +40,8 @@ pub(crate) use icon::SvgIcon;
pub use icon::{Glyph, IconMark, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names};
pub use ime_surface::ImeSurface;
pub use kit::{
Checker, CheckerArea, GridAxis, GridCrowding, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, Tick, TickEdge, TickRank, dashed, drop_mark,
ellipse, fill_polygon, grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks,
Checker, CheckerArea, GridAxis, GridCrowding, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, RulerFace, Tick, TickEdge, TickRank, dashed,
drop_mark, ellipse, fill_polygon, grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks,
};
pub use marker::{Marker, MarkerSize};
pub use paint_slot::PaintSlot;