Merge origin/next

This commit is contained in:
skylartaylor committed 2026-11-24 21:38:34 +01:00
commit e7d564b62d
140 files changed
+3001 -488

No files matched your search

+10 -2
View File
@@ -22,6 +22,12 @@ pub struct ActionsFile {
/// Sets that hold no action.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sets: Vec<String>,
/// Every set name in display order, empty sets included. Written only when loading `actions`
/// and `sets` would not give this order (the actions' sets in order of first appearance, then
/// the empty sets), so files in that natural order, PhotoCraft's included, save unchanged.
/// Files without it load in the natural order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub set_order: Vec<String>,
/// The folder occurrences a PhotoCraft file carried; empty for every other file.
#[serde(skip)]
pub(super) occurrences: FileOccurrences,
@@ -55,6 +61,8 @@ struct RawFile {
#[serde(default)]
sets: Vec<String>,
#[serde(default)]
set_order: Vec<String>,
#[serde(default)]
set_rows: Vec<String>,
}
@@ -71,7 +79,7 @@ impl From<RawFile> for ActionsFile {
let (actions, occurrences): (Vec<Action>, Vec<ActionOccurrence>) = raw.actions.into_iter().map(|raw| (raw.action, raw.occurrence)).unzip();
let empty = raw.set_rows.is_empty() && occurrences.iter().all(|occurrence| *occurrence == ActionOccurrence::default());
let occurrences = if empty { FileOccurrences::default() } else { FileOccurrences { set_rows: raw.set_rows, actions: occurrences } };
ActionsFile { version: raw.version, actions, sets: raw.sets, occurrences }
ActionsFile { version: raw.version, actions, sets: raw.sets, set_order: raw.set_order, occurrences }
}
}
@@ -117,7 +125,7 @@ impl ActionsFile {
/// A file of version [`VERSION`](Self::VERSION) with `actions` and the empty `sets`.
pub fn new(actions: Vec<Action>, sets: Vec<String>) -> Self {
ActionsFile { version: Self::VERSION, actions, sets, occurrences: FileOccurrences::default() }
ActionsFile { version: Self::VERSION, actions, sets, set_order: Vec::new(), occurrences: FileOccurrences::default() }
}
/// Reads a file's JSON text.
+17 -3
View File
@@ -576,12 +576,13 @@ impl ActionList {
/// actions sharing a name, the file's shortcut owner keeps the name. The stored ids come back
/// in [`MergedFile::ids`].
pub fn merge_file(&mut self, file: ActionsFile, replace: bool, mut calls: impl FnMut(&mut ActionStep, &[(String, String)])) -> MergedFile {
let ActionsFile { mut actions, sets, occurrences, .. } = file;
let ActionsFile { mut actions, sets, set_order, occurrences, .. } = file;
if replace {
let named: BTreeSet<&str> = actions
.iter()
.filter_map(|action| action.set.as_deref())
.chain(sets.iter().map(String::as_str))
.chain(set_order.iter().map(String::as_str))
.chain(occurrences.set_rows.iter().map(String::as_str))
.collect();
self.actions.retain(|action| !action.set.as_deref().is_some_and(|set| named.contains(set)));
@@ -596,6 +597,9 @@ impl ActionList {
for (&i, name) in order.iter().zip(claimed) {
given[i] = name;
}
for set in &set_order {
self.record_set(set);
}
let mut merged = MergedFile::default();
let ids = file_ids(&occurrences.actions);
for (index, (mut action, name)) in actions.into_iter().zip(given).enumerate() {
@@ -757,10 +761,20 @@ impl ActionList {
self.touch();
}
/// The list as a file (version [`ActionsFile::VERSION`]; the empty sets in `sets`).
/// The list as a file (version [`ActionsFile::VERSION`]; the empty sets in `sets`, the set order in `set_order` when it is not the natural one).
pub fn to_file(&self) -> ActionsFile {
let empty = self.sets().into_iter().filter(|set| !self.actions.iter().any(|action| action.set.as_deref() == Some(*set)));
ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect())
let mut file = ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect());
let mut natural: Vec<&str> = Vec::new();
for set in self.actions.iter().filter_map(|action| action.set.as_deref()).chain(file.sets.iter().map(String::as_str)) {
if !natural.contains(&set) {
natural.push(set);
}
}
if natural != self.sets() {
file.set_order = self.sets().into_iter().map(str::to_owned).collect();
}
file
}
/// Puts `set` at the end of the set order when the order lacks it.
+16
View File
@@ -80,6 +80,22 @@ fn action_list_file_round_trip_keeps_pc_json() {
assert_eq!(back.sets, ["Empty"]);
assert_eq!(ActionList::from_file(back).sets(), ["S", "Empty"]);
}
// An empty set made before filled ones keeps its place through a save; a file of the older layout
// (empty sets in `sets`, no `set_order`) loads with its filled sets first.
#[trial]
fn set_order_survives_the_file() {
let mut list = ActionList::new();
list.new_set("A").unwrap();
list.new_set("B").unwrap();
list.new_set("C").unwrap();
list.push(Action { set: Some("B".into()), ..action("X", &[]) }).unwrap();
list.push(Action { set: Some("C".into()), ..action("Y", &[]) }).unwrap();
let back = ActionList::from_file(ActionsFile::from_json(&list.to_file().to_json().unwrap()).unwrap());
assert_eq!(back.sets(), ["A", "B", "C"]);
let old = r#"{"version":1,"actions":[{"name":"X","steps":[],"set":"F"}],"sets":["E"]}"#;
assert_eq!(ActionList::from_file(ActionsFile::from_json(old).unwrap()).sets(), ["F", "E"]);
}
// A file that repeats a name keeps a later action's own name: `Foo, Foo, Foo 2` renames the repeat
// (`Foo 3`), never the real `Foo 2`; a merge does the same against the names already in the list.
#[trial]
+4 -1
View File
@@ -88,7 +88,10 @@ fn an_unasked_line_makes_the_connection_unusable_before_sending() {
reader.read_line(&mut line).unwrap();
writeln!(out, "{}", json!({"id": 1, "ok": true})).unwrap();
wait.recv().unwrap();
writeln!(out, "{}", json!({"id": null, "ok": false, "error": "idle connection closed"})).unwrap();
// One write: `writeln!` on a bare stream sends the line and its newline apart, and the client closes on
// the first bytes, so the newline met a reset (BrokenPipe) now and then.
let unasked = format!("{}\n", json!({"id": null, "ok": false, "error": "idle connection closed"}));
out.write_all(unasked.as_bytes()).unwrap();
out.flush().unwrap();
// The client's close shows as an end of input or, with the unread line, a reset.
line.clear();
+9 -2
View File
@@ -208,13 +208,15 @@ pub enum PaintedCursor {
end: bool,
},
/// A pointer with the tool's icon below and right of it: a crosshair (Perspective Crop), or an arrow with its tip
/// on the hotspot (Paint Bucket, Ruler).
/// on the hotspot (Paint Bucket, Ruler, the lassos).
#[non_exhaustive]
PointerTool {
/// The pointer the icon rides beside.
pointer: PointerGlyph,
/// The icon.
icon: IconId,
/// A mark at the icon's lower right.
badge: Option<CursorBadge>,
},
/// No cursor at all.
Hidden,
@@ -294,7 +296,12 @@ impl PaintedCursor {
/// `pointer` with the tool's icon below and right of it.
pub const fn pointer_tool(pointer: PointerGlyph, icon: IconId) -> Self {
PaintedCursor::PointerTool { pointer, icon }
PaintedCursor::PointerTool { pointer, icon, badge: None }
}
/// `pointer` with the tool's icon below and right of it, and `badge` at the icon's lower right.
pub const fn pointer_tool_badged(pointer: PointerGlyph, icon: IconId, badge: Option<CursorBadge>) -> Self {
PaintedCursor::PointerTool { pointer, icon, badge }
}
/// A system cursor with a mark.
+5 -4
View File
@@ -4,15 +4,16 @@
use emath::{Rect, vec2};
/// One Window › Arrange entry. The n-up entries split the document area into that many
/// cells and put one document group in each, and Tile one cell per document; the rest act on
/// windows and views. Saved under the command names (`"twoUpVertical"`, `"tile"`).
/// cells and put one document group in each, and Tile All and Tile one cell per document; the
/// rest act on windows and views. Saved under the command names (`"twoUpVertical"`, `"tile"`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum Arrangement {
/// Tiles every document window across the document area, side by side.
/// One cell per document across the document area, side by side, floating windows docked
/// first.
TileAllVertically,
/// Tiles every document window across the document area, stacked.
/// One cell per document across the document area, stacked, floating windows docked first.
TileAllHorizontally,
/// Two cells, side by side.
TwoUpVertical,
+1 -1
View File
@@ -33,7 +33,7 @@ pub struct DocumentWindows<D> {
/// The floating groups, each with its window rect.
#[serde(with = "floating_serde")]
pub floating: Vec<(DocumentGroup<D>, Rect)>,
/// The n-up or Tile arrangement the document area shows: set by Window › Arrange, cleared by
/// The n-up, Tile All or Tile arrangement the document area shows: set by Window › Arrange, cleared by
/// Consolidate and by floating a document.
#[serde(default)]
pub arrangement: Option<Arrangement>,
+8 -3
View File
@@ -212,6 +212,8 @@ enum Target {
knot: KnotRef,
side: HandleSide,
from: Point,
/// The handle's anchor at the press: ⇧ turns the handle about it.
anchor: Point,
},
/// A curved segment, grabbed at `t` where it passes `from`.
Bend {
@@ -635,7 +637,8 @@ impl<'a> BezierOverlay<'a> {
let knot_at = |path: u64, knot: KnotRef| Self::path(paths, path).and_then(|p| p.knot(knot));
match (self.tool, hit) {
(_, BezierHit::Handle { path, knot, side }) if self.tool != BezierTool::Curvature => {
Target::Handle { path, knot, side, from: knot_at(path, knot).map_or(Point::ZERO, |k| k.handle(side)) }
let at = knot_at(path, knot);
Target::Handle { path, knot, side, from: at.map_or(Point::ZERO, |k| k.handle(side)), anchor: at.map_or(Point::ZERO, |k| k.anchor) }
}
(BezierTool::Curvature, BezierHit::Anchor { path, knot }) => {
self.report.select = Some(self.selecting(path, vec![knot], None));
@@ -728,8 +731,10 @@ impl<'a> BezierOverlay<'a> {
Target::Anchors { path, anchors, from } => {
PathEdit::MoveAnchors { path: *path, anchors: anchors.clone(), by: snapped(*from + locked(delta)) - *from }
}
&Target::Handle { path, knot, side, from } => {
PathEdit::MoveHandle { path, knot, side, to: snapped(from + delta), alone: tool == BezierTool::Convert || mods.alt }
&Target::Handle { path, knot, side, from, anchor } => {
// ⇧ turns the handle to the nearest 45° about its anchor, as the Pen's pull does.
let to = if mods.shift { handle_45(anchor, from + delta) } else { snapped(from + delta) };
PathEdit::MoveHandle { path, knot, side, to, alone: tool == BezierTool::Convert || mods.alt }
}
&Target::Bend { path, segment, t, from } => PathEdit::BendSegment { path, segment, t, by: snapped(from + delta) - from },
&Target::Convert { path, knot } => PathEdit::Convert { path, knot, out: Some(snapped(view.to_doc(pointer))) },
@@ -160,6 +160,7 @@ impl<'a, W: TransformWarp> TransformOverlay<'a, W> {
.reference_point(session.reference_point())
.reach(self.reach)
.rotate_zone(self.rotate_zone)
.own_context_menu(self.reach == TransformReach::Box)
.id_source(self.id);
if let Some(mods) = self.mods {
tbox = tbox.mods(mods);
+18 -12
View File
@@ -509,6 +509,10 @@ pub struct TransformBox<'a> {
/// and an open drag's Escape still cancels the drag.
#[prop]
session_commit: bool,
/// The caller hangs a context menu of its own on the box (`Menu::context` over its response): every part takes the
/// right click, so it does not reach the tool under the box.
#[prop]
own_context_menu: bool,
/// Whether this pass holds a drag of the reference point, so the hidden point is drawn while it moves.
pivot_held: bool,
/// Whether this pass holds a drag that began, so a live line's box shows as it scales.
@@ -538,6 +542,7 @@ impl<'a> TransformBox<'a> {
reach: TransformReach::Box,
color: None,
session_commit: true,
own_context_menu: false,
pivot_held: false,
dragging: false,
report: Report::default(),
@@ -1098,11 +1103,11 @@ fn paint_frame(draw: &Draw<'_>, style: &TransformBoxStyle, line: StrokeColor, co
/// The move reach outside the box whose corners are `quad` on the screen: every point within `points` of its border,
/// as a strip along each side and a round sector outside each corner (PhotoCraft's type move reach measures the
/// distance to the nearest side, pc-prod-e76 type_transform.rs:156-196).
fn declare_ring(cx: &mut PartsCx<'_, TransformBox<'_>>, quad: &[Pos2; 4], points: f32) {
fn declare_ring(cx: &mut PartsCx<'_, TransformBox<'_>>, quad: &[Pos2; 4], points: f32, context: Sense) {
let outward = outward_normals(quad);
let mut declare = |part: usize, shape: Vec<Pos2>| {
cx.part(MOVE_RING.at(part as u64), HitShape::Polygon(shape))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside) | context)
.priority(HitPriority::new(HitLevel::Body, RING_SUB))
.pointer_only(MOVE_BY_KEY);
};
@@ -1250,9 +1255,10 @@ impl Component for TransformBox<'_> {
let style = cx.style;
let screen = on_screen(&space.view, &state);
let quad: [Pos2; 4] = screen.quad.map(pos);
let context = if self.own_context_menu { Sense::CONTEXT_CLICK } else { Sense::empty() };
if self.move_only().is_some() {
if let Some(points) = self.ring_reach() {
declare_ring(cx, &quad, points);
declare_ring(cx, &quad, points, context);
}
return;
}
@@ -1279,13 +1285,13 @@ impl Component for TransformBox<'_> {
)
}
};
cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part)).priority(priority).focus_shape(focus).focusable();
cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part) | context).priority(priority).focus_shape(focus).focusable();
any = true;
}
if let Some(line) = self.line {
for (end, at) in line.free_ends() {
cx.part(LINE_END.at(end.index()), HitShape::circle(space.view.to_screen(at), style.handle_reach))
.sense(Sense::DRAG | Sense::CLICK)
.sense(Sense::DRAG | Sense::CLICK | context)
.priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB))
.pointer_only(LINE_END_BY_KEY);
}
@@ -1299,7 +1305,7 @@ impl Component for TransformBox<'_> {
let band =
if self.rules.edge_band > 0.0 { edge_band(&quad, side, self.rules.edge_band) } else { side_band(&quad, side, style.side_band) };
cx.part(EDGE.at(u64::from(k)), band)
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k)))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k)) | context)
.priority(HitPriority::new(HitLevel::Handle, EDGE_SUB))
.pointer_only(EDGE_BY_KEY);
}
@@ -1309,7 +1315,7 @@ impl Component for TransformBox<'_> {
for (end, side) in [(0u64, corner), (1, (corner + 3) % 4)] {
let Some(reach) = corner_reach(&quad, side, corner, style.side_band) else { continue };
cx.part(CORNER_REACH.at(2 * u64::from(k) + end), reach)
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Corner(k)))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Corner(k)) | context)
.priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB))
.pointer_only(CORNER_BY_KEY);
}
@@ -1317,7 +1323,7 @@ impl Component for TransformBox<'_> {
if self.declares_centre() {
let centre = quad.iter().fold(Vec2::ZERO, |sum, corner| sum + corner.to_vec2()) / 4.0;
cx.part(CENTRE.at(0), HitShape::circle(centre.to_pos2(), style.hit))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside) | context)
.priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB))
.pointer_only(MOVE_BY_KEY);
}
@@ -1328,7 +1334,7 @@ impl Component for TransformBox<'_> {
RotateZone::Outside | RotateZone::Border { .. } if self.rules.allows(BoxPart::Outside) => {
for (corner, region) in outside_regions(&quad, rect).into_iter().enumerate() {
cx.part(OUTSIDE.at(corner as u64), HitShape::Polygon(region))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context)
.priority(HitPriority::new(HitLevel::Background, 0))
.pointer_only(ROTATE_BY_KEY);
}
@@ -1336,7 +1342,7 @@ impl Component for TransformBox<'_> {
RotateZone::Band if self.rules.allows(BoxPart::Outside) => {
for (corner, ring) in band_rings(&screen, style).into_iter().enumerate() {
cx.part(OUTSIDE.at(corner as u64), HitShape::Polygon(ring))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context)
.priority(HitPriority::new(HitLevel::Body, 0))
.pointer_only(ROTATE_BY_KEY);
}
@@ -1347,7 +1353,7 @@ impl Component for TransformBox<'_> {
if self.has_knob() {
let (knob, _) = knob_at(&quad, rect, style);
cx.part(KNOB.at(0), HitShape::circle(knob, style.handle_reach))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context)
.priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB))
.pointer_only(ROTATE_BY_KEY);
}
@@ -1355,7 +1361,7 @@ impl Component for TransformBox<'_> {
RotateZone::Handle if self.rules.allows(BoxPart::Outside) => {
let (_, knob) = rotate_handle(&quad, style.rotate_stem);
cx.part(ROTATE_HANDLE.at(0), HitShape::circle(knob, style.handle_reach))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context)
.priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB))
.pointer_only(ROTATE_BY_KEY);
}
+27
View File
@@ -739,6 +739,33 @@ fn shift_keeps_an_anchor_drag_on_the_axis_or_the_diagonal() {
}
}
// ⇧ during a handle drag turns the handle to the nearest 45° about its anchor, also when pressed mid-drag: about 20°
// lands on the axis, about 40° on the diagonal, and photocraft#15760's measured (-78, +140) on (-78, +78); without ⇧
// the handle follows the pointer.
#[trial]
fn shift_locks_a_handle_drag_to_the_nearest_45_degrees() {
let anchor = p(260.0, 60.0);
let cases =
[(p(360.0, 96.0), p(360.0, 60.0)), (p(340.0, 127.0), p(327.0, 127.0)), (anchor + Vec2::new(-78.0, 140.0), anchor + Vec2::new(-78.0, 78.0))];
for (shift, (target, locked)) in cases.iter().flat_map(|c| [(true, *c), (false, *c)]) {
let mut h = two_paths();
h.update(|st| st.selection = sel(1, &[(0, 2)]));
let handle = h.screen(p(290.0, 100.0));
let to = h.screen(target);
h.press_at(handle);
h.move_to(handle + (to - handle) * 0.5);
if shift {
h.fixture.hold(egui::Modifiers::SHIFT);
}
h.move_to(to);
let Some(PathEdit::MoveHandle { to: got, .. }) = h.last_change() else { panic!("a handle move: {:?}", h.last_change()) };
h.release_at(to);
h.fixture.hold(egui::Modifiers::NONE);
let want = if shift { locked } else { target };
assert!(got.distance(want) < 1e-3, "shift {shift}: {target:?} gives {got:?}, wants {want:?}");
}
}
// Delete Anchor with only some subpaths' anchors shown (#12769): a click on a hidden anchor deletes nothing and
// edits nothing, selects that anchor and shows only its subpath; the next click on it deletes it.
#[trial]
+14 -4
View File
@@ -1070,20 +1070,28 @@ fn a_jittery_double_click_inside_applies_with_no_move_committed() {
assert_eq!(h.host.borrow().applied, 1, "the double click applies");
}
/// A secondary click on the session's box opens the mode menu (its rows are on the page); with the menu closed again, a
/// secondary click away from the box opens none.
/// A secondary click on the session's box opens the mode menu (its rows are on the page) and is the box's alone: the
/// tool host under it asks for no menu of its own. With the menu closed again, a secondary click away from the box
/// opens none.
#[trial]
fn a_secondary_click_on_the_box_opens_the_mode_menu() {
use craft_draw::ui::transform::TransformTool;
use craft_ui::canvas::{ToolHost, tool_pass};
let session = TransformSession::<()>::new(RECT);
let settings = TransformSettings::default();
let view = Rc::new(RefCell::new(CanvasView::new(egui::Rect::NOTHING, Point::ZERO, 1.0)));
let shown_view = Rc::clone(&view);
let host_asked = Rc::new(Cell::new(false));
let (shown_view, asked) = (Rc::clone(&view), Rc::clone(&host_asked));
let mut fixture = Fixture::new(move |ui| {
let room = ui.available_rect_before_wrap();
let at = CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0);
*shown_view.borrow_mut() = at;
Canvas::new("Document").view(at).show(ui, |ui, body| {
TransformOverlay::new("Free Transform", &session, &settings).show_at(ui, body.rect);
let shown = TransformOverlay::new("Free Transform", &session, &settings).show_at(ui, body.rect);
if let Some(pass) = tool_pass(&body.env) {
let mut tool = TransformTool::new(&session, shown.snapped.clone());
asked.set(asked.get() || ToolHost::new().run(ui, &pass, &mut tool).context.is_some());
}
});
});
fixture.settle();
@@ -1098,8 +1106,10 @@ fn a_secondary_click_on_the_box_opens_the_mode_menu() {
right_click(&mut fixture, screen(Point::new(1000.0, 1000.0)));
assert!(fixture.by_label("Distort").is_none(), "a secondary click away from the box opens no mode menu");
host_asked.set(false);
right_click(&mut fixture, screen(Point::new(200.0, 150.0)));
assert!(fixture.by_label("Distort").is_some(), "a secondary click on the box opens the mode menu");
assert!(!host_asked.get(), "the tool host under the box asks for no menu");
}
/// A drag from inside snaps the moved box's edges, not the pointer: the right edge lands on the guide at 310 while the
+78 -49
View File
@@ -19,7 +19,7 @@ use craft_host::Section;
use craft_theme::variant::Tone;
use craft_ui::buttons::{ControlPlace, IconButton};
use craft_ui::contract::{
Access, Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, step_stop,
};
use craft_ui::controls::disclosure::{DisclosureGlyph, DropdownArrow};
@@ -59,8 +59,6 @@ craft_ui::words! {
/// The name of the preview banner, with `{family}` for the family it shows.
preview_of: template "fontPicker.previewOf" = "Font preview: {family}";
no_match: "fontPicker.noMatch" = "No fonts match";
/// The family field's label when the selection has several families.
mixed: "fontPicker.mixed" = "Mixed";
/// The name of a row's star, with `{row}` for the row's label.
favorite: template "fontPicker.favorite" = "Favorite {row}";
list: "fontPicker.list" = "Fonts";
@@ -732,6 +730,18 @@ pub struct FontPicker<'a> {
host_picked: Option<String>,
}
/// How many times a closed [`FontPicker`] built its stop list on `ctx`, for regression trials.
#[cfg(feature = "screen-testing")]
#[derive(Clone, Copy, Default)]
struct StopBuilds(u64);
/// How many times a closed [`FontPicker`] built its stop list on `ctx`.
#[doc(hidden)]
#[cfg(feature = "screen-testing")]
pub fn stop_builds(ctx: &egui::Context) -> u64 {
ctx.data(|data| data.get_temp::<StopBuilds>(egui::Id::unique("font_picker_stop_builds")).unwrap_or_default().0)
}
impl<'a> FontPicker<'a> {
/// A picker named `label` over the family `family` of `catalog`.
pub fn new(label: impl Into<Label>, family: Bind<'a, String>, catalog: &'a Arc<Catalog>) -> Self {
@@ -808,6 +818,10 @@ impl<'a> FontPicker<'a> {
/// What the closed field's arrows and wheel step through: the host face and action rows in group order, then the
/// families in the list's narrowed order. A notice takes no step.
fn stops(&self, cx: &Cx<'_, Self>, settings: Option<&FontPickerSettings>, filters: &FontFilters) -> Vec<Stop> {
#[cfg(feature = "screen-testing")]
cx.response.ctx.data_mut(|data| {
data.get_temp_mut_or_default::<StopBuilds>(egui::Id::unique("font_picker_stop_builds")).0 += 1;
});
let folder = cx.env.folder();
let host = rank::host_rows(self.host, "", &folder)
.into_iter()
@@ -934,10 +948,8 @@ impl Component for FontPicker<'_> {
}
let mut options = TextOptions::new();
options.select_on_focus = true;
// A selection of several families shows an empty field, as the reference applications do.
options.mixed = cx.value().is_none();
if options.mixed {
options.placeholder = Some(cx.words::<FontPickerWords>().mixed.clone());
}
if !self.catalog.is_ready() {
// The first scan runs on a background thread; the field asks again until it ends.
self.catalog.scan_in_background();
@@ -954,12 +966,6 @@ impl Component for FontPicker<'_> {
Some(self.family.reborrow())
}
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
if cx.value().is_none() && cx.text(&text_key()).is_none_or(|text| text.draft.as_deref().is_none_or(str::is_empty)) {
access.value(cx.words::<FontPickerWords>().mixed.as_str());
}
}
/// A changed draft filters the list: it opens on the matches, and closes when the draft ended (committed,
/// cancelled or replaced by a pick). A preview that the list closed on without a pick is cancelled. While the
/// list is closed, the arrows and the wheel step through the host rows and the families.
@@ -995,52 +1001,75 @@ impl Component for FontPicker<'_> {
let typing = cx.memory::<Typing>();
typing.expanded.clear();
typing.rested.clear();
// Collect stepping input before building the sorted stop list: idle frames carry neither arrow moves nor
// wheel ticks, so skipping `stops` avoids collating every installed family on every repaint.
let mut moves: Vec<bool> = Vec::new();
while let Some((step, mods)) = cx.intents().take_move() {
match step {
NavMove::Down if !mods.fine => moves.push(true),
NavMove::Up if !mods.fine => moves.push(false),
_ => {}
}
}
let wheel = cx.take_wheel();
let wheel_along = wheel.as_ref().and_then(|wheel| {
if wheel.phase == WheelPhase::End {
None
} else if let StepResult::Set(along) =
wheel_step(&ValueSteps::new(0.0, -f64::MAX, f64::MAX, 1.0, 1.0).fine(1.0), ValueAxes::Both, wheel, cx.env.direction().is_rtl())
&& along != 0.0
{
Some((wheel.phase, along))
} else {
None
}
});
let wheel_ended = wheel.is_some_and(|wheel| wheel.phase == WheelPhase::End);
if moves.is_empty() && wheel_along.is_none() {
if wheel_ended {
cx.wheel_run(WheelPhase::End, None);
}
return;
}
let settings = read(&mut self.settings, cx);
let filters = read(&mut self.filters, cx).unwrap_or_default();
let all = self.stops(cx, settings.as_ref(), &filters);
let stops: Vec<usize> = (0..all.len()).collect();
let here = match self.current_host.as_deref() {
Some(key) => all.iter().position(|stop| matches!(stop, Stop::Host(host) if host == key)),
None => cx.value().and_then(|current| all.iter().position(|stop| matches!(stop, Stop::Family(family) if family == current))),
};
let mut to = here;
while let Some((step, mods)) = cx.intents().take_move() {
match step {
NavMove::Down if !mods.fine => to = step_stop(&stops, to, true),
NavMove::Up if !mods.fine => to = step_stop(&stops, to, false),
_ => {}
if !moves.is_empty() {
let here = match self.current_host.as_deref() {
Some(key) => all.iter().position(|stop| matches!(stop, Stop::Host(host) if host == key)),
None => cx.value().and_then(|current| all.iter().position(|stop| matches!(stop, Stop::Family(family) if family == current))),
};
let mut to = here;
for forward in moves {
to = step_stop(&stops, to, forward);
}
}
if to != here {
match to.and_then(|at| all.get(at)) {
Some(Stop::Host(key)) => self.host_picked = Some(key.clone()),
Some(Stop::Family(family)) => {
self.picked = Some(family.clone());
cx.set(family.clone());
if to != here {
match to.and_then(|at| all.get(at)) {
Some(Stop::Host(key)) => self.host_picked = Some(key.clone()),
Some(Stop::Family(family)) => {
self.picked = Some(family.clone());
cx.set(family.clone());
}
None => {}
}
None => {}
}
}
// The wheel steps one stop a line down for a step forward, as one run the wheel's end commits.
if let Some(wheel) = cx.take_wheel() {
if wheel.phase == WheelPhase::End {
cx.wheel_run(wheel.phase, None);
} else if let StepResult::Set(along) =
wheel_step(&ValueSteps::new(0.0, -f64::MAX, f64::MAX, 1.0, 1.0).fine(1.0), ValueAxes::Both, &wheel, cx.env.direction().is_rtl())
&& along != 0.0
{
let mut stop = match self.current_host.as_deref() {
Some(key) => all.iter().position(|stop| matches!(stop, Stop::Host(host) if host == key)),
None => cx.value().and_then(|current| all.iter().position(|stop| matches!(stop, Stop::Family(family) if family == current))),
};
for _ in 0..along.abs().round() as usize {
stop = step_stop(&stops, stop, along < 0.0);
}
match stop.and_then(|at| all.get(at)) {
Some(Stop::Host(key)) => self.host_picked = Some(key.clone()),
Some(Stop::Family(family)) => cx.wheel_run(wheel.phase, Some(family.clone())),
None => {}
}
if wheel_ended {
cx.wheel_run(WheelPhase::End, None);
} else if let Some((phase, along)) = wheel_along {
let mut stop = match self.current_host.as_deref() {
Some(key) => all.iter().position(|stop| matches!(stop, Stop::Host(host) if host == key)),
None => cx.value().and_then(|current| all.iter().position(|stop| matches!(stop, Stop::Family(family) if family == current))),
};
for _ in 0..along.abs().round() as usize {
stop = step_stop(&stops, stop, along < 0.0);
}
match stop.and_then(|at| all.get(at)) {
Some(Stop::Host(key)) => self.host_picked = Some(key.clone()),
Some(Stop::Family(family)) => cx.wheel_run(phase, Some(family.clone())),
None => {}
}
}
}
+43 -3
View File
@@ -122,8 +122,10 @@ fn present(fx: &Fixture, text: &str) -> bool {
fx.by_label(text).is_some() || fx.texts().iter().any(|painted| painted.text == text)
}
/// A selection of several families leaves the family field empty, on screen and to assistive technology, as the
/// reference applications do: no family name and no word stands in for it.
#[trial]
fn mixed_family_is_named_until_a_font_is_chosen() {
fn a_mixed_family_shows_an_empty_field() {
let catalog = catalog_of(&[INTER_REGULAR]);
let mut family = craft_behavior::Mixed::<String>::Mixed;
let mut fx = Fixture::new(move |ui| {
@@ -132,8 +134,14 @@ fn mixed_family_is_named_until_a_font_is_chosen() {
fx.in_room(Room::Window);
fx.settle();
let field = fx.by_role(craft_ui::runtime::access::Role::COMBO_BOX).into_iter().next().expect("the family field");
let label = fx.tree().value_of(field.node).filter(|value| !value.is_empty()).expect("the mixed family has an accessible label");
assert!(present(&fx, label), "the accessible mixed label is also visible");
assert!(fx.tree().value_of(field.node).is_none_or(str::is_empty), "the mixed family has no accessible value");
let words: Vec<String> = fx
.texts()
.iter()
.filter(|painted| field.rect.contains_rect(painted.rect) && painted.text.chars().any(char::is_alphabetic))
.map(|painted| painted.text.clone())
.collect();
assert!(words.is_empty(), "the field paints no text: {words:?}");
}
#[trial]
@@ -1046,3 +1054,35 @@ fn the_list_loads_its_sample_faces_off_the_pass_and_once() {
fx.frame(vec![]);
assert_eq!(jobs.waiting(), 0, "the list opened again loads no face");
}
#[trial]
fn the_closed_field_skips_building_stops_while_idle_and_steps_on_input() {
let all = listed(&three_faces(), &FontFilters::default(), &[]);
assert_eq!(all.len(), 3);
let (mut fx, seen) = rig(three_faces(), vec![]);
seen.borrow_mut().family = all[0].clone();
fx.frame(vec![]);
let before = craft_font_manager::picker::stop_builds(fx.ctx());
for _ in 0..5 {
fx.frame(vec![]);
}
assert_eq!(craft_font_manager::picker::stop_builds(fx.ctx()), before, "idle closed frames do not rebuild stops");
aim_at_field(&mut fx);
assert_eq!(craft_font_manager::picker::stop_builds(fx.ctx()), before, "focusing and hovering without stepping do not rebuild stops");
fx.key(Key::ArrowDown, Modifiers::NONE);
assert_eq!(seen.borrow().family, all[1], "ArrowDown steps to the next family");
let after_key = craft_font_manager::picker::stop_builds(fx.ctx());
assert_eq!(after_key, before + 1, "one ArrowDown builds stops once");
fx.frame(vec![wheel_lines(-1.0)]);
assert_eq!(seen.borrow().family, all[2], "wheel down steps to the following family");
let after_wheel = craft_font_manager::picker::stop_builds(fx.ctx());
assert_eq!(after_wheel, after_key + 1, "one wheel tick builds stops once");
fx.advance(GESTURE_GAP * 2.0).idle(3);
assert_eq!(seen.borrow().picks.last().map(|(f, _)| f.as_str()), Some(all[2].as_str()), "wheel end commits the stepped family");
assert_eq!(craft_font_manager::picker::stop_builds(fx.ctx()), after_wheel, "wheel end and idle frames do not rebuild stops");
}
+5 -7
View File
@@ -1,19 +1,16 @@
//! [`LassoTool`]: the freehand Lasso with Alt-latched straight segments, and the pieces the Polygonal Lasso shares.
use craft_behavior::geometry::{ConstrainStyle, DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft, SelectionOperation};
use craft_behavior::{CancelReason, Cursor, PaintedCursor, PointerButton};
use craft_behavior::{CancelReason, Cursor, PaintedCursor, PointerButton, PointerGlyph};
use craft_keymap::{Key, Mods};
use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft_ui::primitives::{Draw, PaintShape, StrokeWidth, ToolIcon};
use egui::{Pos2, Vec2};
use egui::Pos2;
use kurbo::Rect;
use super::drag::{InsideDrag, PressRule, cursor_over, drag_kind, moved_selection_snap};
use super::{DragKind, Place, Report, SelectEvent, SelectPhase, SelectToolPass, SelectWords, SelectionProbe, SelectionShape};
/// Where a lasso cursor's icon touches the document: the icon's own origin.
const ICON_HOTSPOT: Vec2 = Vec2::ZERO;
/// The reach of an outline's closing presses in this pass: a press within the slop of the first vertex or of the last
/// closes.
pub(super) fn reach(cx: &ToolContext<'_>) -> DraftReach {
@@ -54,7 +51,8 @@ pub(super) struct LassoCursor<'a> {
pub(super) rule: PressRule,
}
/// The lasso icon with the operation's badge: the latched one while an outline is open, else the live modifiers';
/// The arrow with its tip on the point the outline starts from, the lasso icon below and right of it and the
/// operation's badge beside the icon: the latched one while an outline is open, else the live modifiers';
/// Cmd is the Move tool's, so it shows none. Over the selection, the cursors of [`cursor_over`].
pub(super) fn cursor(shown: &LassoCursor<'_>, probe: &dyn SelectionProbe, cx: &ToolContext<'_>) -> Cursor {
let LassoCursor { icon, draft, operation, bar, inside, rule } = shown;
@@ -71,7 +69,7 @@ pub(super) fn cursor(shown: &LassoCursor<'_>, probe: &dyn SelectionProbe, cx: &T
} else {
SelectionOperation::resolve(*bar, cx.mods, probe.has_selection()).badge()
};
PaintedCursor::tool(icon.icon(), ICON_HOTSPOT, badge).into()
PaintedCursor::pointer_tool_badged(PointerGlyph::Arrow, icon.icon(), badge).into()
}
/// The outline as marching ants and, between straight segments, the rubber band: the one painter of an
+4 -7
View File
@@ -1,7 +1,7 @@
//! [`MagneticLassoTool`]: an outline that snaps to the edges the app's [`EdgeTracer`] finds.
use craft_behavior::geometry::SelectionOperation;
use craft_behavior::{CancelReason, Cursor, PaintedCursor};
use craft_behavior::{CancelReason, Cursor, PaintedCursor, PointerGlyph};
use craft_keymap::{Key, Mods};
use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft_ui::primitives::{Draw, PaintShape, StrokeWidth, ToolIcon};
@@ -12,9 +12,6 @@ use serde::{Deserialize, Serialize};
use super::lasso::{DraftKey, draft_command, outline_access};
use super::{Place, Report, SelectEvent, SelectPhase, SelectToolPass, SelectionProbe, SelectionShape};
/// Where the magnetic lasso cursor's icon touches the document: the icon's own origin.
const ICON_HOTSPOT: Vec2 = Vec2::ZERO;
/// The detection settings of one edge query.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
@@ -478,8 +475,8 @@ impl<T: EdgeTracer> CanvasTool for SelectToolPass<'_, MagneticLassoTool<T>> {
if self.tool.outline.as_ref().is_some_and(|o| !o.down) { ToolClaims::NONE.keyboard().deletes() } else { ToolClaims::NONE }
}
/// The width circle under the canvas's precise cursor (`width * zoom`, at least the slop); otherwise the lasso
/// icon with the operation's badge.
/// The width circle under the canvas's precise cursor (`width * zoom`, at least the slop); otherwise the arrow on
/// the pointer with the lasso icon beside it and the operation's badge.
fn cursor(&self, cx: &ToolContext<'_>) -> Cursor {
let tool = &*self.tool;
if cx.precise()
@@ -494,7 +491,7 @@ impl<T: EdgeTracer> CanvasTool for SelectToolPass<'_, MagneticLassoTool<T>> {
None if cx.mods.cmd => None,
None => SelectionOperation::resolve(tool.bar, cx.mods, self.probe.has_selection()).badge(),
};
PaintedCursor::tool(ToolIcon::MagneticLasso.icon(), ICON_HOTSPOT, badge).into()
PaintedCursor::pointer_tool_badged(PointerGlyph::Arrow, ToolIcon::MagneticLasso.icon(), badge).into()
}
/// The first click starts an outline; later ones close near the first point, add a straight segment with Alt (and
+21 -1
View File
@@ -19,7 +19,7 @@ use craft_imaging::ui::wide_angle::PreviewDone;
use craft_imaging::ui::{ChannelColor, HistogramSet, ScopeChannel};
use craft_ui::InstallSpec;
use craft_ui::canvas::{PixelRect, RasterSource};
use craft_ui::dialog::{DialogHost, DialogResult, FullWindowWorkspace as _, HostedWorkspace};
use craft_ui::dialog::{DialogHost, DialogResult, FullWindowWorkspace as _, HostedWorkspace, OWN_WINDOW_MIN_SIZE};
use craft_ui::primitives::Revision;
use craft_ui::runtime::access::Role;
use craft_ui::runtime::pending::Job;
@@ -251,6 +251,26 @@ fn raw_develop_window_keeps_its_size_when_the_saved_screen_is_gone() {
assert!((0.0..=880.0).contains(&pos.x) && (0.0..=320.0).contains(&pos.y), "restored position is in reach: {pos:?}");
}
/// photocraft#16595: while the window shrank each frame, the placement store saved its size, 1 pt wide at 100 %
/// scaling. Restored, the window opens no smaller than a full-window dialog's own window may be, and the OS keeps it
/// there.
#[trial]
fn raw_develop_window_saved_while_shrinking_opens_at_its_minimum() {
let store = Arc::new(Mutex::new(Store::in_memory()));
store.lock().unwrap().set("craft_imaging.raw_develop.window", &Placement::new([1.0, 500.0], 1.0));
let system = Arc::new(FakeSystem::new());
system.set_monitors(vec![Monitor::new(MonitorKey::new("Attached", [1920, 1080]), [0, 0], [1920, 1080], 1.0)]);
let windows = Windows::with(InstallSpec::new(ShellInfo::default(), system).placement(store));
let mut host = DialogHost::new();
host.open(HostedWorkspace::new(RawDevelopWorkspace::new(open(RawTarget::OpenRaw)), Source::new()));
let output = windows.frame(vec![], vec![], |ui| {
host.run(ui);
});
let (_, builder) = output.builders.iter().find(|(id, _)| *id != ViewportId::ROOT).expect("Raw Develop opens a child window");
assert_eq!(builder.inner_size, Some(Vec2::new(OWN_WINDOW_MIN_SIZE.x, 500.0)), "the saved width is raised to the minimum");
assert_eq!(builder.min_inner_size, Some(OWN_WINDOW_MIN_SIZE), "the OS keeps the window at least that big");
}
#[trial]
fn raw_develop_switches_raws_and_finishes_with_each_footer_button() {
let host = Rc::new(RefCell::new(DialogHost::new()));
+42
View File
@@ -951,6 +951,48 @@ fn the_magnetic_lasso_shows_the_width_circle_under_the_precise_cursor() {
}
}
/// The cursor `rig` shows over the middle of its canvas with `mods` held.
fn lasso_cursor<T: Reports + 'static>(rig: &mut Rig<T>, mods: Modifiers) -> Option<craft_behavior::Cursor>
where
for<'a> SelectToolPass<'a, T>: CanvasTool,
{
let ctx = rig.fixture().ctx().clone();
let over = rig.canvas().center();
rig.fixture().frame(vec![pointer::moved(over)]);
hold(rig, mods);
rig.fixture().frame(Vec::new());
craft_ui::runtime::cursor::current(&ctx)
}
// The lassos show an arrow with its tip where the outline starts and the tool's icon below right of it, as the reference
// application does; the operation's badge rides at the icon's lower right. With the icon alone on the pointer, its
// empty top-left corner was the hotspot, so the outline began beside the icon (photocraft#16671).
#[trial]
fn the_lassos_point_an_arrow_at_where_the_outline_starts() {
use craft_behavior::{Cursor, CursorBadge, PaintedCursor, PointerGlyph};
use craft_ui::primitives::ToolIcon;
fn check(cursor: Option<Cursor>, icon: ToolIcon, badge: Option<CursorBadge>, what: &str) {
match cursor {
Some(Cursor::Painted(PaintedCursor::PointerTool { pointer, icon: shown, badge: b, .. })) => {
assert_eq!(pointer, PointerGlyph::Arrow, "{what}: an arrow");
assert_eq!(shown, icon.icon(), "{what}: the tool's icon");
assert_eq!(b, badge, "{what}: the badge");
}
other => panic!("{what}: an arrow with the tool's icon, got {other:?}"),
}
}
let selected = Rect::new(20.0, 20.0, 60.0, 60.0);
let shift = Modifiers::SHIFT;
let mut lasso = rig("Lasso", LassoTool::new(), Fake::selected(selected));
check(lasso_cursor(&mut lasso, Modifiers::NONE), ToolIcon::Lasso, None, "Lasso");
check(lasso_cursor(&mut lasso, shift), ToolIcon::Lasso, Some(CursorBadge::Add), "Lasso with Shift");
let mut polygon = rig("Polygonal Lasso", PolygonLassoTool::new(), Fake::selected(selected));
check(lasso_cursor(&mut polygon, Modifiers::NONE), ToolIcon::PolygonalLasso, None, "Polygonal Lasso");
check(lasso_cursor(&mut polygon, Modifiers::ALT), ToolIcon::PolygonalLasso, Some(CursorBadge::Subtract), "Polygonal Lasso with Alt");
let (mut magnetic, _) = magnetic();
check(lasso_cursor(&mut magnetic, Modifiers::NONE), ToolIcon::MagneticLasso, None, "Magnetic Lasso");
}
#[trial]
fn width_steps_by_one_and_shift_jumps_to_the_limits() {
let mut settings = MagneticSettings::default();
@@ -27,6 +27,18 @@ fn cf_html_offsets_delimit_the_fragment_bytes() {
assert_eq!(end_html, data.len() - 1);
}
/// Ported from WordCraft (#7317). When multiple RTF targets are offered, text/rtf is preferred over application/rtf and text/richtext.
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn rtf_target_prefers_text_rtf() {
use super::unix::rtf_target;
let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(rtf_target(&names(&["TARGETS", "text/richtext", "application/rtf", "text/rtf"])), Some("text/rtf"));
assert_eq!(rtf_target(&names(&["text/richtext", "UTF8_STRING"])), Some("text/richtext"));
assert_eq!(rtf_target(&names(&["text/html", "text/rtf;charset=x"])), None);
assert_eq!(rtf_target(&[]), None);
}
// Copied files reach the system clipboard as a file list holding the same paths, spaces and
// non-ASCII names included; a URI that names no local file is never written as one, and a list
// with no file in it leaves the write to the next flavour.
+23 -5
View File
@@ -975,14 +975,22 @@ impl<'a> CharacterControls<'a> {
let columns = if ui.available_width() < pair_width { &TWO_COLUMNS[..1] } else { &TWO_COLUMNS };
let shown = Stack::new().label(self.label).show(ui, |ui, _| {
#[cfg(feature = "font-picker")]
let family = family_field_keyed(ui, &words, values, families, Some(keys::FAMILY), None, picker.as_mut());
let family = family_field_keyed(ui, &words, values, families, Some(keys::FAMILY), None, Some(Sizing::FillWidth), picker.as_mut());
#[cfg(not(feature = "font-picker"))]
let family = family_field_keyed(ui, &words, values, families, Some(keys::FAMILY), None);
let family = family_field_keyed(ui, &words, values, families, Some(keys::FAMILY), None, Some(Sizing::FillWidth));
preview_family = family.preview;
rested_family = family.rested;
picker_id = family.picker;
edits.extend(family.edits);
edits.extend(select_row(ui, &words.style, hidden_side(), mixed(values.style.clone()), &style_entries, CharacterChange::Style));
edits.extend(select_row(
ui,
&words.style,
hidden_side(),
mixed(values.style.clone()),
&style_entries,
Some(Sizing::FillWidth),
CharacterChange::Style,
));
#[cfg(feature = "font-picker")]
if let Some(axes) = axes {
let held = values.axes.clone().unwrap_or_default();
@@ -1061,6 +1069,7 @@ impl<'a> CharacterControls<'a> {
hidden_side(),
mixed(values.font_height),
&entries,
Some(Sizing::FillWidth),
CharacterChange::FontHeight,
));
}
@@ -1070,7 +1079,7 @@ impl<'a> CharacterControls<'a> {
let event = lengths.kerning(
ui,
words.kerning.clone(),
mark(GlyphLabel::icon(IconId::new("text_cursor")), Some(words.kerning_hint.clone()), FieldLayout::Beside),
mark(GlyphLabel::icon(IconId::new("text_cursor")), Some(words.kerning_hint.clone()), FieldLayout::Inside),
kerning_shown,
&kerning_presets,
Some(keys::KERNING),
@@ -1122,6 +1131,7 @@ impl<'a> CharacterControls<'a> {
hidden_side(),
mixed(values.anti_alias),
&entries,
Some(Sizing::FillWidth),
CharacterChange::AntiAlias,
));
}
@@ -1211,7 +1221,15 @@ impl<'a> CharacterControls<'a> {
}
if let Some(entries) = &language_entries {
edits.extend(select_row(ui, &words.language, hidden_side(), mixed(values.language.clone()), entries, CharacterChange::Language));
edits.extend(select_row(
ui,
&words.language,
hidden_side(),
mixed(values.language.clone()),
entries,
Some(Sizing::FillWidth),
CharacterChange::Language,
));
}
});
CharacterControlsOutput { response: shown.output, edits, preview_family, rested_family, requests, picker: picker_id }
+2 -2
View File
@@ -338,9 +338,9 @@ impl<'a> FormatText<'a> {
let panel = Stack::new().label(self.label).show(ui, |ui, _| {
// The font, across the panel.
#[cfg(feature = "font-picker")]
let family = family_field(ui, &cw, character, families, reason(FormatControl::Font), picker.as_mut());
let family = family_field(ui, &cw, character, families, reason(FormatControl::Font), Some(Sizing::FillWidth), picker.as_mut());
#[cfg(not(feature = "font-picker"))]
let family = family_field(ui, &cw, character, families, reason(FormatControl::Font));
let family = family_field(ui, &cw, character, families, reason(FormatControl::Font), Some(Sizing::FillWidth));
edits.extend(character_edits(family.edits));
if let Some(key) = family.host_picked {
edits.push(picked_event(FormatTextChange::HostFont(key), cw.family.as_str()));
+29 -12
View File
@@ -106,7 +106,7 @@ impl Lengths<'_> {
field.inner.unwrap_or_default()
}
/// The kerning field: a number or the name of a presets row (Metrics, Optical).
/// The kerning field: a number or the name of a presets row (Metrics, Optical). The field fills its grid cell.
pub(super) fn kerning(
&self,
ui: &mut Ui,
@@ -118,7 +118,11 @@ impl Lengths<'_> {
) -> EditEvents<NamedOr<KerningName>> {
let units = self.units;
let shown = Field::new(label.clone()).side(side).show(ui, |ui, _| {
let field = NumberField::named(label.clone(), Bind::given(mixed(value))).range(TRACKING_RANGE).presets(presets).scrub_by_label();
let field = NumberField::named(label.clone(), Bind::given(mixed(value)))
.range(TRACKING_RANGE)
.presets(presets)
.scrub_by_label()
.sizing(Sizing::FillWidth);
let field = field.codec(NumberCodec::new(units.reader(None), 0));
match key {
Some(key) => field.doc_key(key),
@@ -131,7 +135,7 @@ impl Lengths<'_> {
shown.inner.unwrap_or_default()
}
/// A field over a number that is not a length: its event and the preset row picked.
/// A field over a number that is not a length: its event and the preset row picked. The field fills its grid cell.
pub(crate) fn plain(&self, ui: &mut Ui, spec: PlainRow<'_>) -> (EditEvents<Option<f64>>, Option<NumberPick>) {
self.plain_keyed(ui, spec, None)
}
@@ -141,7 +145,8 @@ impl Lengths<'_> {
let PlainRow { label, side, value, range, percent, presets, disabled } = spec;
let units = self.units;
let shown = Field::new(label.clone()).side(side).show(ui, |ui, _| {
let field = NumberField::new(label.clone(), Bind::given(value)).range(range.clone()).presets(presets).scrub_by_label();
let field =
NumberField::new(label.clone(), Bind::given(value)).range(range.clone()).presets(presets).scrub_by_label().sizing(Sizing::FillWidth);
let field = if percent {
field.unit_kind(UnitKind::Percent).step(UnitKind::Percent.step())
} else {
@@ -275,21 +280,30 @@ pub(crate) fn string_entries(pairs: impl Iterator<Item = (String, String)>) -> V
pairs.map(|(value, text)| Entry::new(value, text)).collect()
}
/// A row with a select over `entries`; its pick as a change.
/// A row with a select over `entries`, sized by `sizing` (`None` keeps the select's own width); its pick as a change.
pub(crate) fn select_row<V: Value + 'static, C>(
ui: &mut Ui,
label: &Label,
side: SideLabel,
value: Mixed<V>,
entries: &[Entry<V>],
sizing: Option<Sizing>,
change: impl Fn(V) -> C,
) -> EditEvents<C> {
let shown = Field::new(label.clone())
.side(side)
.show(ui, |ui, _| Select::new(label.clone(), Bind::given(value.clone()), entries).placeholder("—").show(ui).events);
.show(ui, |ui, _| sized(Select::new(label.clone(), Bind::given(value.clone()), entries).placeholder("—"), sizing).show(ui).events);
shown.inner.unwrap_or_default().map(&change)
}
/// `component` sized by `sizing`; `None` keeps its own sizing.
fn sized<P: Props>(component: P, sizing: Option<Sizing>) -> P {
match sizing {
Some(sizing) => component.sizing(sizing),
None => component,
}
}
/// One toggle button of a row: its name, icon, state (`None` while the selection mixes) and the change it makes.
pub(crate) struct Toggle<C> {
pub(crate) name: Label,
@@ -347,27 +361,29 @@ pub(crate) struct FamilyField {
}
/// The family field of the character controls, the style options and the type bar: the font picker in a
/// hidden-label field when a `picker` source is given, else a select over `families`. A `disabled` reason disables the
/// field and shows in its tooltip.
/// hidden-label field when a `picker` source is given, else a select over `families`, sized by `sizing` (`None` keeps
/// the control's own width). A `disabled` reason disables the field and shows in its tooltip.
pub(crate) fn family_field(
ui: &mut Ui,
words: &CharacterWords,
values: &CharacterValues,
families: &[String],
disabled: Option<&Label>,
sizing: Option<Sizing>,
#[cfg(feature = "font-picker")] picker: Option<&mut FontPickerSource<'_>>,
) -> FamilyField {
#[cfg(feature = "font-picker")]
{
family_field_keyed(ui, words, values, families, None, disabled, picker)
family_field_keyed(ui, words, values, families, None, disabled, sizing, picker)
}
#[cfg(not(feature = "font-picker"))]
{
family_field_keyed(ui, words, values, families, None, disabled)
family_field_keyed(ui, words, values, families, None, disabled, sizing)
}
}
/// As [`family_field`], the picker carrying the document `key` a host focuses it by (the plain select has none).
#[allow(clippy::too_many_arguments)]
pub(crate) fn family_field_keyed(
ui: &mut Ui,
words: &CharacterWords,
@@ -376,6 +392,7 @@ pub(crate) fn family_field_keyed(
#[cfg(feature = "font-picker")] key: Option<DocKey>,
#[cfg(not(feature = "font-picker"))] _key: Option<DocKey>,
disabled: Option<&Label>,
sizing: Option<Sizing>,
#[cfg(feature = "font-picker")] picker: Option<&mut FontPickerSource<'_>>,
) -> FamilyField {
let value = mixed(values.family.clone());
@@ -403,7 +420,7 @@ pub(crate) fn family_field_keyed(
if let Some(key) = key {
field = field.doc_key(key);
}
disabled_for(field, &words.family, disabled).show(ui)
disabled_for(sized(field, sizing), &words.family, disabled).show(ui)
});
let Some(out) = shown.inner else { return FamilyField::default() };
let id = craft_ui::contract::Outcome::response(&out).id;
@@ -422,7 +439,7 @@ pub(crate) fn family_field_keyed(
let entries = string_entries(families.iter().map(|name| (name.clone(), name.clone())));
let shown = Field::new(words.family.clone()).side(hidden_side()).show(ui, |ui, _| {
let select = Select::new(words.family.clone(), Bind::given(value.clone()), &entries).placeholder("—");
disabled_for(select, &words.family, disabled).show(ui).events
disabled_for(sized(select, sizing), &words.family, disabled).show(ui).events
});
let edits = shown.inner.unwrap_or_default().map(CharacterChange::Family).into_iter().collect();
FamilyField { edits, ..FamilyField::default() }
@@ -308,9 +308,9 @@ impl<'a> TextStyleOptions<'a> {
let found = match attribute {
StyleAttribute::Font => include_row(ui, &words.include, attribute, on, |ui| {
#[cfg(feature = "font-picker")]
let family = family_field(ui, &cw, c, families, None, picker.as_mut());
let family = family_field(ui, &cw, c, families, None, Some(Sizing::FillWidth), picker.as_mut());
#[cfg(not(feature = "font-picker"))]
let family = family_field(ui, &cw, c, families, None);
let family = family_field(ui, &cw, c, families, None, Some(Sizing::FillWidth));
let mut found = character(family.edits);
found.extend(character(select_row(
ui,
@@ -318,6 +318,7 @@ impl<'a> TextStyleOptions<'a> {
hidden_side(),
mixed(c.style.clone()),
&style_entries,
Some(Sizing::FillWidth),
CharacterChange::Style,
)));
found
@@ -390,7 +391,7 @@ impl<'a> TextStyleOptions<'a> {
let align_of = |key: String| {
ParagraphChange::Align(ALIGNS.iter().find(|(_, k)| *k == key).map_or_else(TextAlign::default, |(align, _)| *align))
};
paragraph_changes(select_row(ui, &pw.alignment, hidden_side(), mixed(key), &align_entries, align_of))
paragraph_changes(select_row(ui, &pw.alignment, hidden_side(), mixed(key), &align_entries, Some(Sizing::FillWidth), align_of))
}),
StyleAttribute::FirstLineIndent => include_row(ui, &words.include, attribute, on, |ui| {
let row = LengthRow {
+3 -3
View File
@@ -178,14 +178,14 @@ impl<'a> TypeBar<'a> {
.extend(toggle.events.map(|on| TypeBarChange::Orientation(if on { TextOrientation::Vertical } else { TextOrientation::Horizontal })));
#[cfg(feature = "font-picker")]
let family = family_field(ui, &character_words, character, families, None, picker.as_mut());
let family = family_field(ui, &character_words, character, families, None, None, picker.as_mut());
#[cfg(not(feature = "font-picker"))]
let family = family_field(ui, &character_words, character, families, None);
let family = family_field(ui, &character_words, character, families, None, None);
preview_family = family.preview;
rested_family = family.rested;
edits.extend(family.edits.into_iter().map(|event| event.map(TypeBarChange::Character)));
let style = select_row(ui, &bar_words.style, hidden_side(), mixed(character.style.clone()), &style_entries, CharacterChange::Style);
let style = select_row(ui, &bar_words.style, hidden_side(), mixed(character.style.clone()), &style_entries, None, CharacterChange::Style);
edits.extend(style.into_iter().map(|event| event.map(TypeBarChange::Character)));
// The size glyph the Character panel's size row shows.
+65 -1
View File
@@ -1,6 +1,7 @@
use craft_text::ui::character::{CharacterControls, CharacterRows, CharacterValues, Kerning, Leading};
use craft_theme::TextSize;
use craft_ui::testing::{Fixture, trial};
use egui::vec2;
use egui::{Rect, vec2};
#[trial]
fn character_fields_are_readable_when_the_panel_is_narrowed() {
@@ -44,3 +45,66 @@ fn the_properties_rows_leave_out_baseline_shift_and_the_style_toggles() {
}
}
}
/// Edges closer than this are the same edge.
const EDGE: f32 = 0.5;
#[trial]
fn character_fields_line_up_in_their_columns_at_every_width_and_text_size() {
let families = vec!["Inter".to_owned()];
let styles = vec!["Regular".to_owned()];
let mut fixture = Fixture::new(move |ui| {
let values = CharacterValues {
family: Some("Inter".to_owned()),
style: Some("Regular".to_owned()),
size: Some(12.0),
leading: Some(Leading::Auto),
kerning: Some(Kerning::Metrics),
..CharacterValues::default()
};
CharacterControls::new("Character", &values, &families, &styles).show(ui);
});
let left = ["Font size", "Kerning", "Vertical scale", "Baseline shift"];
let right = ["Leading", "Tracking", "Horizontal scale"];
let across = ["Font family", "Style"];
for text_size in [TextSize::Small, TextSize::Large] {
fixture.text_size(text_size);
for width in [222.0, 300.0, 340.0, 402.0, 520.0] {
fixture.room(vec2(width, 900.0)).settle();
let at = format!("at {width} pt, {text_size:?} text");
let rect = |label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("{label} is shown {at}")).rect;
let same = |a: f32, b: f32| (a - b).abs() <= EDGE;
let size = rect("Font size");
let leading = rect("Leading");
let lined_up = |labels: &[&str], column: Rect| {
for label in labels {
let field = rect(label);
assert!(
same(field.left(), column.left()) && same(field.right(), column.right()),
"{label} {field:?} spans its column {column:?} {at}"
);
}
};
let full = Rect::from_x_y_ranges(size.left()..=leading.right(), size.y_range());
if size.bottom() <= leading.top() {
// One column: every field spans it.
lined_up(&left, size);
lined_up(&right, size);
lined_up(&across, size);
assert!(same(rect("Text color").right(), size.right()), "the colour well ends at the column's end {at}");
} else {
assert!(size.right() <= leading.left(), "the columns do not overlap {at}");
lined_up(&left, size);
lined_up(&right, leading);
lined_up(&across, full);
assert!(same(rect("Text color").right(), leading.right()), "the colour well ends at the right column's end {at}");
}
assert!(full.right() <= size.left() + width + EDGE, "no field runs past the panel {at}");
for value in ["12", "Metrics"] {
let text = fixture.texts().iter().find(|run| run.text == value).unwrap_or_else(|| panic!("{value} is painted {at}")).clone();
assert!(!text.elided && text.clip.expand(EDGE).contains_rect(text.rect), "{value} fits inside its field {at}: {text:?}");
}
}
}
}
+2 -2
View File
@@ -6,7 +6,7 @@
use std::fmt::Write as _;
use crate::{
BarSizes, ColorToken, ControlSizes, DialogSizes, DockColumnSizes, Easing, Edge, Elevation, ElevationTokens, FloatSizes, FontSlot, Gaps, GripMark,
BarSizes, ColorToken, ControlSizes, DialogSizes, DockColumnSizes, Easing, Edge, Elevation, ElevationTokens, FloatSizes, FontSlot, Gaps,
GripShape, HandleSizes, HitSizes, IconSizes, Insets, KnobShape, LengthSizes, Motion, MotionTokens, Pads, PaneSizes, PlotSizes, RadiusSet,
RailSizes, RampSizes, Rgba, RowSizes, ShapeTokens, SizeTokens, SpaceTokens, StrokeTokens, ThumbSamples, ThumbSizes, Tokens, TypeStyle,
TypeTokens, WellShape, WindowSizes,
@@ -76,7 +76,7 @@ fn shape_lines(out: &mut Lines, shape: &ShapeTokens) {
out.line("shape.knob", if *knob == KnobShape::Round { "round" } else { "tab" });
out.line("shape.wells", if *wells == WellShape::Square { "square" } else { "round" });
let GripShape { mark, count, length, width, gap } = grip;
out.line("shape.grip.mark", if *mark == GripMark::Ticks { "ticks" } else { "dots" });
out.line("shape.grip.mark", mark.name());
out.line("shape.grip.count", count.to_string());
for (k, v) in [("length", length), ("width", width), ("gap", gap)] {
out.line(&format!("shape.grip.{k}"), len(*v));
+1 -1
View File
@@ -42,7 +42,7 @@ const KNOB: &str = "\"round\" or \"tab\"";
/// What `shape.wells` takes.
const WELLS: &str = "\"square\" or \"round\"";
/// What `shape.grip.mark` takes.
const GRIP_MARK: &str = "\"ticks\" or \"dots\"";
const GRIP_MARK: &str = "\"ticks\", \"dots\" or \"bar\"";
/// What the numbers of `shape.grip` take.
const GRIP_NUMBER: &str = "a number";
/// What `icon_pack` takes.
+2 -1
View File
@@ -318,6 +318,7 @@ impl Parser {
None | Some(Value::Null) => Some(None),
Some(Value::String(s)) if s == "ticks" => Some(Some(GripMark::Ticks)),
Some(Value::String(s)) if s == "dots" => Some(Some(GripMark::Dots)),
Some(Value::String(s)) if s == "bar" => Some(Some(GripMark::Bar)),
Some(_) => {
p.fail(ErrorKind::BadValue { expected: GRIP_MARK });
None
@@ -340,7 +341,7 @@ impl Parser {
})
};
let count = number(self, "count", 1.0, 32.0, true);
let length = number(self, "length", 0.5, 16.0, false);
let length = number(self, "length", 0.5, 32.0, false);
let width = number(self, "width", 0.5, 8.0, false);
let gap = number(self, "gap", 0.5, 16.0, false);
Some(GripSeed { mark: mark?, count: count?.map(|c| c as u16), length: length?, width: width?, gap: gap? })
+2 -2
View File
@@ -5,7 +5,7 @@ use serde_json::{Map, Number, Value};
use super::{FormatErrors, SCHEMA, SCHEMA_VERSION, ThemeFile};
use crate::scale::Radius;
use crate::theme::{AppOverrides, ContrastIntent, EdgeSeed, GripSeed, ModePins, ModeSeeds, Pins, ShapeSeed, ThemeDef, Variants};
use crate::tokens::{GripMark, KnobShape, WellShape};
use crate::tokens::{KnobShape, WellShape};
/// Top-level keys in the order a file lists them; other keys follow, sorted.
const TOP_ORDER: [&str; 14] = [
@@ -173,7 +173,7 @@ fn update_shape(shape: &mut Map<String, Value>, s: &ShapeSeed) {
fn grip(out: &mut Map<String, Value>, g: &GripSeed) {
match g.mark {
Some(mark) => {
out.insert("mark".to_owned(), Value::String(if mark == GripMark::Ticks { "ticks" } else { "dots" }.to_owned()));
out.insert("mark".to_owned(), Value::String(mark.name().to_owned()));
}
None => {
out.remove("mark");
+17 -3
View File
@@ -80,19 +80,33 @@ pub enum GripMark {
Ticks,
/// Square dots, [`GripShape::width`] on a side.
Dots,
/// One level bar, [`GripShape::length`] long and [`GripShape::width`] thick: a tick turned on its side. The count
/// and the gap do not apply.
Bar,
}
impl GripMark {
/// The mark's name in a theme file and a token dump.
pub fn name(self) -> &'static str {
match self {
GripMark::Ticks => "ticks",
GripMark::Dots => "dots",
GripMark::Bar => "bar",
}
}
}
/// The row of marks a dock grip shows (the grip above an icon group, under a tool rail's column bar, at a floating
/// panel's edge): what the marks are, how many, how large and how far apart, in points.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GripShape {
/// Ticks or dots.
/// Ticks, dots or a bar.
pub mark: GripMark,
/// How many marks the row has, at every display scale.
pub count: u16,
/// How tall a tick is; dots ignore it.
/// How tall a tick is, or how long the bar is; dots ignore it.
pub length: f32,
/// How wide a tick is, or a dot's side.
/// How wide a tick is, a dot's side, or how thick the bar is.
pub width: f32,
/// The space between two marks.
pub gap: f32,
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 3
space.gap.inline = 6
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 2
space.gap.inline = 4
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 3
space.gap.inline = 6
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 2
space.gap.inline = 4
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 3
space.gap.inline = 6
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 2
space.gap.inline = 4
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 3
space.gap.inline = 6
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 2
space.gap.inline = 4
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 3
space.gap.inline = 6
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 2
space.gap.inline = 4
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 3
space.gap.inline = 6
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 2
space.gap.inline = 4
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 3
space.gap.inline = 6
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 2
space.gap.inline = 4
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 3
space.gap.inline = 6
@@ -119,10 +119,10 @@ shape.radius.pill = 999
shape.edge = flat
shape.knob = round
shape.wells = square
shape.grip.mark = ticks
shape.grip.mark = bar
shape.grip.count = 11
shape.grip.length = 5
shape.grip.width = 1
shape.grip.length = 18
shape.grip.width = 3
shape.grip.gap = 1
space.gap.tight = 2
space.gap.inline = 4
@@ -16,7 +16,13 @@
"warn": "#f0a330"
}
},
"shape": null,
"shape": {
"grip": {
"mark": "bar",
"length": 18,
"width": 3
}
},
"light": {
"accent.solid": "#d9472f",
"caption.close_hover": "#c42b1c",
+7 -1
View File
@@ -16,7 +16,13 @@
"warn": "#f0a330"
}
},
"shape": null,
"shape": {
"grip": {
"mark": "bar",
"length": 18,
"width": 3
}
},
"light": {
"accent.solid": "#d9472f",
"caption.close_hover": "#c42b1c",
+10 -4
View File
@@ -16,7 +16,7 @@ use crate::runtime::windows::WindowSpec;
use crate::sections::FooterButton;
use crate::style::{ComponentStyle, StyleCx, SurfaceKind};
use craft_behavior::{Metrics, Sense};
use egui::Ui;
use egui::{Ui, Vec2, vec2};
pub use hosted::{FullWindowWorkspace, HostedWorkspace, WorkspaceCx, WorkspacePass};
@@ -26,6 +26,11 @@ pub(crate) mod stories;
#[cfg(feature = "suite")]
pub(crate) mod trials;
/// The least a full-window dialog's own window may be, in points: the OS window's minimum, and the floor a restored
/// placement is fitted to. A placement saved while photocraft#16595 shrank the window could be 1 pt wide; without
/// a floor it opened that small and nothing grew it again.
pub const OWN_WINDOW_MIN_SIZE: Vec2 = vec2(640.0, 480.0);
/// The style of a full-window dialog: the surface comes from the container.
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
#[non_exhaustive]
@@ -121,13 +126,14 @@ impl<'a> FullWindowDialog<'a> {
.label(title)
}
/// Shows the dialog in its own OS window described by `spec`, resizable, opening at the saved placement; where
/// viewports are unavailable it fills the main window. The dialog's focus policy moves into the fallback overlay.
/// Shows the dialog in its own OS window described by `spec`, resizable down to [`OWN_WINDOW_MIN_SIZE`], opening at
/// the saved placement; where viewports are unavailable it fills the main window. The dialog's focus policy moves
/// into the fallback overlay.
#[must_use]
pub fn own_window(mut self, spec: WindowSpec) -> Self {
// A viewport mount takes its scope from the fallback overlay and holds `props.focus` at none.
let focus = std::mem::replace(self.focus_mut(), FocusPolicy::NONE);
self.props.mount = Mount::viewport_with(Overlay::full_window(focus), spec);
self.props.mount = Mount::viewport_with(Overlay::full_window(focus).min_size(OWN_WINDOW_MIN_SIZE), spec);
self
}
+6 -2
View File
@@ -402,7 +402,7 @@ impl Component for Rulers<'_> {
for (part, strip) in [(RulerPart::Horizontal, top), (RulerPart::Vertical, left)] {
let declared = cx.part(part.part(), strip).priority(handle).pointer_only("the New Guide... command places a guide by number");
if self.interactive {
let declared = declared.sense(Sense::DRAG | Sense::CLICK);
let declared = declared.sense(Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK);
if let Some(space) = space {
declared.cursor(resize_cursor(&space.view, motion_across(part.guide_along())));
}
@@ -410,7 +410,11 @@ impl Component for Rulers<'_> {
}
let declared = cx.part(CORNER, corner).priority(handle);
if self.interactive {
let sense = if self.origin_locked { Sense::CLICK | Sense::CONTEXT_CLICK } else { Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS };
let sense = if self.origin_locked {
Sense::CLICK | Sense::CONTEXT_CLICK
} else {
Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK | Sense::TAKE_FOCUS
};
let declared = declared.sense(sense);
if self.origin_locked {
declared.pointer_only("the zero point is locked");
@@ -499,7 +499,7 @@ impl Component for Guides<'_> {
let Some([a, b]) = place::segment(&space.view, guide.along, guide.position, guide.span, rect) else { continue };
let part = cx
.part(guide.key.part(GUIDE), HitShape::segment(a, b))
.sense(Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS)
.sense(Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK | Sense::TAKE_FOCUS)
.priority(HitPriority::new(HitLevel::Edge, 0))
.cursor(resize_cursor(&space.view, motion_across(guide.along)))
.focusable();
@@ -74,8 +74,9 @@ impl TaskBarPlace {
/// or the bar grows; a press with no drag changes nothing. A moved bar whose offset place would cover the `keep_clear` point shows at its unmoved place and keeps
/// its offset. Pinned, it stays where it shows.
/// - Area: the bar shows inside `area` (the canvas rect): a move stays inside it, and a stored place outside it comes
/// back inside, its left and top edges winning where the bar does not fit. Its members continue on a new line when
/// the area is too narrow for them.
/// back inside, its left and top edges winning where the bar does not fit. An anchor that leaves no room on either
/// side (a crop frame larger than the view) has the bar over it, on its side's edge of the area, with all its
/// members. Its members continue on a new line when the area is too narrow for them.
/// - Menu: Hide bar reports `hide`; Reset bar position clears the place, so the bar follows its anchor again; Pin bar
/// position keeps it where it shows and, picked again, lets it follow its anchor from where it shows.
/// - `place` is the caller's value (`Bind::bound`): the bar reads it before it shows and writes the pass's change
@@ -464,7 +465,7 @@ impl Hung {
/// Where a bar of `size` hangs inside `area` before any offset: the place the overlay host computes for the
/// anchored layer, taken from the one placement rule.
fn unmoved(&self, size: Vec2, area: Rect, rtl: bool) -> Rect {
let request = PlaceRequest::new(self.rect, size, area).side(self.side).align(self.align).rtl(rtl).flips_across(true);
let request = PlaceRequest::new(self.rect, size, area).side(self.side).align(self.align).rtl(rtl).flips_across(true).covers_anchor(true);
craft_behavior::overlay::place(&request).rect
}
}
@@ -494,7 +495,7 @@ fn selection_overlay(hang: Option<&Hung>, area: Rect, dismiss: TaskBarDismiss) -
};
let overlay = Overlay::floating().modeless().body_scroll(false).dismiss(Dismiss::new().outside(outside));
match hang {
Some(hang) => overlay.bounds(area).place(Place::anchored(Anchor::Rect(hang.rect), hang.side, hang.align)),
Some(hang) => overlay.bounds(area).place(Place::anchored(Anchor::Rect(hang.rect), hang.side, hang.align).covering_anchor()),
None => overlay,
}
}
@@ -509,7 +510,9 @@ fn layer_overlay(held: &TaskBarPlace, hang: Option<&Hung>, area: Rect, movable:
if let Some(at) = held.placed_in(area).filter(|_| movable) {
return overlay.placed_at(at);
}
let mut hung = Place::anchored(Anchor::Rect(hang.rect), hang.side, hang.align).flipping_across();
// An anchor that fills the area (a crop frame larger than the view) leaves no room on either side: the bar keeps
// its members and slides over the anchor, inside the area, instead of showing an empty surface.
let mut hung = Place::anchored(Anchor::Rect(hang.rect), hang.side, hang.align).flipping_across().covering_anchor();
if movable {
hung = hung.offset(held.offset_in().unwrap_or(Vec2::ZERO));
}
+3 -1
View File
@@ -31,7 +31,9 @@ pub mod canvas_controls;
/// Dialog shells and prompts, with the full-window dialog family that shows a canvas.
pub mod dialog {
pub use crate::canvas::full_window::{FullWindowDialog, FullWindowDialogStyle, FullWindowWorkspace, HostedWorkspace, WorkspaceCx, WorkspacePass};
pub use crate::canvas::full_window::{
FullWindowDialog, FullWindowDialogStyle, FullWindowWorkspace, HostedWorkspace, OWN_WINDOW_MIN_SIZE, WorkspaceCx, WorkspacePass,
};
pub use crate::canvas::full_window_parts::{
FullWindowCanvas, FullWindowCanvasOutput, FullWindowSide, FullWindowSideOutput, FullWindowSideStyle, FullWindowStatus,
FullWindowStatusOutput, FullWindowTitle, FullWindowTitleOutput, FullWindowView, FullWindowZoomBar, FullWindowZoomBarOutput, RasterOverlay,
@@ -265,3 +265,43 @@ fn a_corner_drag_the_host_cancelled_lands_nothing_at_its_release() {
fixture.settle();
assert_eq!(*zero.borrow(), host, "the release after the host's change leaves the zero point where the host put it");
}
/// A right-click on a ruler strip or on the corner is the rulers': they report the part, for their units menu, and
/// the tool host under them asks for no menu of its own.
#[trial]
fn a_right_click_on_a_ruler_is_the_rulers_not_the_tools() {
use craft_ui::canvas::{RulerPart, ToolHost, tool_pass};
let zero = Rc::new(RefCell::new(Point::ZERO));
let asked: Rc<RefCell<(Option<RulerPart>, bool)>> = Rc::new(RefCell::new((None, false)));
let (shown_zero, seen) = (Rc::clone(&zero), Rc::clone(&asked));
let room = Rc::new(Cell::new(Rect::NOTHING));
let shown_room = Rc::clone(&room);
let tool = RefCell::new(Overpaint);
let mut fixture = Fixture::new(move |ui| {
let at = ui.available_rect_before_wrap();
shown_room.set(at);
let view = CanvasView::new(at, Point::new(f64::from(at.center().x), f64::from(at.center().y)), 1.0);
let mut zero = shown_zero.borrow_mut();
let mut host_asked = false;
let canvas = Canvas::new("Document").view(view).with_rulers(Some(Rulers::new("Rulers", Bind::bound(&mut *zero)))).show(ui, |ui, body| {
if let Some(pass) = tool_pass(&body.env) {
host_asked = ToolHost::new().run(ui, &pass, &mut *tool.borrow_mut()).context.is_some();
}
});
let mut seen = seen.borrow_mut();
seen.0 = seen.0.or(canvas.output.rulers.as_ref().and_then(|rulers| rulers.context));
seen.1 |= host_asked;
});
fixture.room(Vec2::new(500.0, 400.0)).settle();
let mut right_click = |at: Pos2| {
*asked.borrow_mut() = (None, false);
fixture.frame(vec![craft_ui::testing::pointer::moved(at)]);
fixture.frame(vec![craft_ui::testing::pointer::secondary(at, true)]);
fixture.frame(vec![craft_ui::testing::pointer::secondary(at, false)]);
fixture.settle();
*asked.borrow()
};
let canvas = room.get();
assert_eq!(right_click(egui::pos2(canvas.center().x, canvas.min.y + 4.0)), (Some(RulerPart::Horizontal), false), "the top strip");
assert_eq!(right_click(canvas.min + Vec2::splat(4.0)), (Some(RulerPart::Corner), false), "the corner, its zero point unlocked");
}
@@ -6,7 +6,7 @@ use craft_behavior::{Axis, CancelReason, CanvasView};
use craft_ui::canvas::{CanvasTool, Guide, GuideKey, Snap, ToolAction, ToolContext, ToolPath, ToolPointer};
use craft_ui::canvas_controls::Guides;
use craft_ui::canvas_controls::reading::{GuideReading, running};
use craft_ui::contract::{Bind, BodyCx, Show as _};
use craft_ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowContainer as _};
use craft_ui::primitives::Draw;
use craft_ui::testing::{ToolFixture, pointer, tool_fixture, trial};
use egui::{Id, Key, Modifiers, Pos2, Rect, Vec2, pos2, vec2};
@@ -284,3 +284,39 @@ fn a_deleted_guide_hands_focus_on_without_selecting_the_next_guide() {
assert!(at(&guides, Axis::Y, 200.0).is_none(), "Delete removes it: {:?}", guides.borrow());
assert_eq!(*selected.borrow(), None, "and selects no other guide");
}
// A right-click on an unlocked guide is the guide's: the guides report its menu request and the tool host under them
// reports none. Off the guide the right-click reaches the host, which asks for its own menu.
#[trial]
fn a_right_click_on_a_guide_asks_for_the_guide_menu_not_the_tools() {
use craft_ui::canvas::{Canvas, ToolHost, tool_pass};
use craft_ui::testing::Fixture;
use craft_ui::testing::tool_fixture::DOCUMENT;
let guides: Shared<Vec<Guide>> = Rc::new(RefCell::new(vec![guide(1, Axis::Y, 200.0)]));
let asked: Shared<(Option<GuideKey>, bool)> = Rc::new(RefCell::new((None, false)));
let (shown, seen) = (Rc::clone(&guides), Rc::clone(&asked));
let tool = RefCell::new(Recorder::default());
let mut fixture = Fixture::new(move |ui| {
let room = ui.available_rect_before_wrap();
let canvas = Canvas::new("Document").id(tool_fixture::canvas_id("Document")).document(DOCUMENT).view(view_at(1.0)(room));
let _ = canvas.show(ui, |ui, body| {
let out = Guides::new("Guides", canvas_of(body), Bind::bound(&mut *shown.borrow_mut())).interactive(true).show_at(ui, body.rect);
let mut seen = seen.borrow_mut();
seen.0 = seen.0.or(out.context.map(|(key, _)| key));
if let Some(pass) = tool_pass(&body.env) {
seen.1 |= ToolHost::new().run(ui, &pass, &mut *tool.borrow_mut()).context.is_some();
}
});
});
fixture.settle();
let mut right_click = |at: Pos2| {
*asked.borrow_mut() = (None, false);
fixture.frame(vec![pointer::moved(at)]);
fixture.frame(vec![pointer::secondary(at, true)]);
fixture.frame(vec![pointer::secondary(at, false)]);
fixture.settle();
*asked.borrow()
};
assert_eq!(right_click(pos2(200.0, 300.0)), (Some(GuideKey::new(1)), false), "on the guide: its menu, not the tool's");
assert_eq!(right_click(pos2(400.0, 300.0)), (None, true), "off the guide: the tool's menu");
}
@@ -55,6 +55,12 @@ fn low_frame() -> Vec<Point> {
[(120.0, 290.0), (520.0, 290.0), (520.0, 390.0), (120.0, 390.0)].into_iter().map(|(x, y)| Point::new(x, y)).collect()
}
/// A frame far larger than the story canvas, as a crop frame on a document zoomed past the view: it leaves no room for
/// a bar above or below it.
fn filling_frame() -> Vec<Point> {
[(-2000.0, -2000.0), (3000.0, -2000.0), (3000.0, 3000.0), (-2000.0, 3000.0)].into_iter().map(|(x, y)| Point::new(x, y)).collect()
}
/// A canvas that shows the bar for the scene's anchor and place, with the More menu before a Done button: a movable
/// bar, or a `fixed` one, which takes no place.
fn fixture(scene: &Rc<RefCell<Scene>>, fixed: bool) -> Fixture {
@@ -424,6 +430,36 @@ fn a_fixed_task_bar_ignores_a_drag_shows_no_more_menu_and_opens_above_with_no_ro
);
}
/// An anchor that fills the canvas leaves no room on either side: the task bar and a fixed bar still show all their
/// members, over the anchor at the area's bottom edge, instead of an empty surface at its top (photocraft#16657).
#[trial]
fn a_bar_whose_anchor_fills_the_area_keeps_its_members_at_the_bottom_edge() {
for fixed in [false, true] {
let scene = Rc::new(RefCell::new(Scene {
anchor: filling_frame(),
place: TaskBarPlace::default(),
bounds: Rect::NOTHING,
area: Rect::NOTHING,
rect: Rect::NOTHING,
}));
let mut fixture = fixture(&scene, fixed);
fixture.settle();
let shown = seen(&scene);
assert!(shown.bounds.contains_rect(shown.area), "fixed {fixed}: the anchor {:?} covers the canvas {:?}", shown.bounds, shown.area);
let done = fixture.by_label("Done").unwrap_or_else(|| panic!("fixed {fixed}: the bar shows its members"));
assert!(done.rect.is_positive(), "fixed {fixed}: Done has a size: {:?}", done.rect);
assert!(shown.rect.contains_rect(done.rect.shrink(SLACK)), "fixed {fixed}: Done {:?} lies in the bar {:?}", done.rect, shown.rect);
assert!(inside_area(&shown), "fixed {fixed}: inside the canvas {:?}: {:?}", shown.area, shown.rect);
assert!(
(shown.area.bottom() - shown.rect.bottom()).abs() < SLACK,
"fixed {fixed}: on the canvas's bottom edge {:?}: {:?}",
shown.area,
shown.rect
);
assert_eq!(fixture.by_label("More options").is_some(), !fixed, "fixed {fixed}: only the task bar has its More menu");
}
}
/// The grip is one of the bar's members: it sits on the members' line, centred with them, inside the bar's padding,
/// and a drag on it still moves the bar.
#[trial]
@@ -40,9 +40,9 @@ impl BodyCx<'_> {
}
/// Whether the primary press of this pass went down on the container's own surface, for a root that senses
/// `Sense::SURFACE`: inside its rect, on its layer, where none of its children or parts takes the press. The
/// container decides what it means (a dock group focuses its panel, as Photoshop does); it is no click and moves
/// no focus by itself.
/// `Sense::SURFACE`: inside its rect, on its layer, where none of its children or parts and no app's own egui widget
/// in its body takes the press. The container decides what it means (a dock group focuses its panel, as Photoshop
/// does); it is no click and moves no focus by itself.
pub fn surface_pressed(&self) -> bool {
self.memory.recall::<SurfacePress>(sub(self.id, "surface_press")).pressed
}
@@ -76,8 +76,8 @@ impl BodyCx<'_> {
impl BodyHooks<'_> {
/// Records for the container's hooks whether this pass's primary press went down on its own surface
/// (`BodyCx::surface_pressed`): no shape of last pass under the press takes it, nor a component's text widget
/// egui gives it to (a focused field's), and the press lies in the
/// container's rect on its layer; and whether that press is the second of a double click
/// egui gives it to (a focused field's), nor an app's own egui widget (a raw text field or canvas in the body), and
/// the press lies in the container's rect on its layer; and whether that press is the second of a double click
/// (`BodyCx::surface_double_pressed`), read from the same press's click count; and whether this pass's primary
/// release ends a press that went down there (`BodyCx::surface_clicked`). The press origin waits in the press slot
/// until the release; Escape and a blur clear it, and so does any pass with no button held.
@@ -95,6 +95,7 @@ impl BodyHooks<'_> {
inside(press.origin)
&& pointer::press_winner(&ctx, press.origin, pass.press_targets).is_none()
&& !pointer::text_takes_press(&ctx, pass.press_targets)
&& !pass.press_targets.click.is_some_and(|widget| pointer::foreign_target(&ctx, widget))
})
} else {
None
@@ -273,6 +273,31 @@ fn edge_of(dx: i8, dy: i8) -> ResizeEdge {
}
}
/// The move band and the resize grips the body step declared for a container this pass, for a host that names them
/// (an automation interface that drives a window by its grips). Each comes with the id of its accessibility node, the
/// id [`focused_node`](crate::runtime::access::focused_node) reports while it holds focus.
impl<C: Container> Cx<'_, C> {
/// The band the container is moved by, `None` when it has none this pass (no header, not movable).
pub fn move_band(&self) -> Option<(Rect, Id)> {
let band = self.core.results.get(&(MOVE_BAND, None))?;
Some((band.rect, crate::runtime::access::sub_node_id(self.core.id, MOVE_BAND.into())))
}
/// The edge and corner grips the container is resized by, each with the edge or corner it moves; none when it does
/// not resize this pass (minimized, maximized, or a window the platform resizes from its own frame).
pub fn resize_grips(&self) -> Vec<(ResizeEdge, Rect, Id)> {
GRIPS
.into_iter()
.enumerate()
.filter_map(|(index, (dx, dy, _))| {
let part = GRIP.at(index as u64);
let grip = self.core.results.get(&(GRIP, Some(index as u64)))?;
Some((edge_of(dx, dy), grip.rect, crate::runtime::access::sub_node_id(self.core.id, part)))
})
.collect()
}
}
/// The arrow chords, with and without Shift, a window mode holds, with the direction each moves.
const MODE_ARROWS: [(Key, [i8; 2]); 4] = [(Key::Left, [-1, 0]), (Key::Right, [1, 0]), (Key::Up, [0, -1]), (Key::Down, [0, 1])];
@@ -814,6 +839,7 @@ impl BodyHooks<'_> {
let top = top_band(props, &ctx, pcx.id, pcx.tokens);
let pinned = overlay_of(props).map_or(Pinned::NONE, |overlay| Pinned::of(overlay, &ctx, pcx.id, pcx.env.direction().is_rtl()));
let caller_sizes = overlay_of(props).is_some_and(|overlay| overlay.resize.by_caller);
let grip_name = props.resize_name.as_ref().map(|name| pcx.env.resolve(name).as_str().to_owned());
for (index, (dx, dy, cursor)) in GRIPS.into_iter().enumerate() {
if held != Some(index) && !grip_stands(edges, pinned, dx, dy) {
continue;
@@ -837,6 +863,10 @@ impl BodyHooks<'_> {
.pointer_only(reason)
.exact_hit()
.over();
let part = match &grip_name {
Some(name) => part.node(crate::runtime::access::Role::SPLITTER, name.as_str()),
None => part,
};
// The grips of a window its caller sizes are the app's (`window_resize`), never the platform's.
if let Some(hit) = exclusive(WindowHit::Resize(edge_of(dx, dy))).filter(|_| !caller_sizes) {
part.exclusive(hit);
@@ -13,7 +13,7 @@ pub use events::{
};
pub use props::{
ActivateOn, CollectionProps, DeleteTarget, DragPayload, HoverLead, ItemKeys, LeadOnOpen, LeadSource, ReorderRule, RowHeight, RowPressed,
RowState, SelectMode, SpaceAction,
RowPreview, RowState, SelectMode, SpaceAction,
};
pub(crate) use response::Gestures;
pub(crate) use response::ItemsOut;
@@ -37,6 +37,23 @@ pub enum DeleteTarget {
FocusOrHover,
}
/// What a row drag shows while it runs. The text is the count word for the dragged items
/// (`CollectionProps::drag_count`), else the number of items for several and the item's text for one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum RowPreview {
/// The text in a badge by the pointer.
#[default]
Badge,
/// The text inside the region a drop would take, where the target marks one ([`DragPreview::Named`]); nothing
/// by the pointer.
///
/// [`DragPreview::Named`]: crate::runtime::drag::DragPreview::Named
Named,
/// No preview: the dragged row shows alone.
None,
}
/// How the user may reorder items.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
@@ -246,11 +263,11 @@ pub struct CollectionProps {
/// Map a row drag to the payloads that other drop targets take (8.4), one per type. A map starts row drags by
/// itself, with or without a reorder rule.
pub drag_payloads: Vec<DragPayload>,
/// The count word the drag badge shows for the dragged items, one item included ("1 page", "3 pages"); `None`
/// shows the number of items for several and the item's text for one.
/// The count word a row drag's preview shows for the dragged items, one item included ("1 page", "3 pages");
/// `None` shows the number of items for several and the item's text for one.
pub drag_count: Option<Counted>,
/// Whether a row drag shows its badge by the pointer. Off, the drag carries no preview.
pub drag_badge: bool,
/// What a row drag shows while it runs.
pub drag_preview: RowPreview,
/// The collection takes the full height of its rows and owns no scroll, so it can sit inside a scrolling page:
/// every row is built, the wheel and the keys that move past an end act on the page's scroll owner, and moving
/// the lead scrolls the page to keep the row in view. For short collections only; a long one keeps its own
@@ -369,7 +386,7 @@ impl CollectionProps {
delete_target: DeleteTarget::Focus,
drag_payloads: Vec::new(),
drag_count: None,
drag_badge: true,
drag_preview: RowPreview::Badge,
natural_height: false,
min_rows: 0,
max_rows: None,
@@ -424,14 +441,14 @@ impl CollectionProps {
self
}
/// Whether a row drag shows its badge by the pointer (on by default).
/// What a row drag shows while it runs (a badge by the pointer by default).
#[must_use]
pub const fn drag_badge(mut self, on: bool) -> Self {
self.drag_badge = on;
pub const fn drag_preview(mut self, preview: RowPreview) -> Self {
self.drag_preview = preview;
self
}
/// The drag badge reads `count` for the number of dragged items.
/// A row drag's preview reads `count` for the number of dragged items.
#[must_use]
pub const fn drag_count(mut self, count: Counted) -> Self {
self.drag_count = Some(count);
@@ -812,6 +812,8 @@ pub struct ContainerProps {
/// The help line the footer shows under the control column of a label-scoped container; its text joins the
/// control's description.
pub help: Option<Label>,
/// The accessible name of each resize grip of a window or layer mount; its grips report no node without one.
pub resize_name: Option<Label>,
/// The container's place in its set, reported on its node.
pub position: Option<SetPosition>,
/// The focus scope of an `Inline`, `Pane` or `FullWindow` mount.
@@ -937,6 +939,7 @@ impl ContainerProps {
footer: None,
end: None,
help: None,
resize_name: None,
position: None,
focus: FocusPolicy::NONE,
collapse: None,
@@ -1056,6 +1059,12 @@ impl ContainerProps {
self
}
/// The accessible name of every resize grip of the container's window or layer.
pub fn resize_name(mut self, name: impl Into<Label>) -> Self {
self.resize_name = Some(name.into());
self
}
/// The container's place in its set (`n of m`), reported on its node.
pub const fn position(mut self, position: SetPosition) -> Self {
self.position = Some(position);
@@ -89,6 +89,8 @@ pub(crate) struct PartExtras {
pub toggles: Option<crate::contract::overlay::ToggleDecl>,
/// A header part at the end edge: its stop registers after the header's children.
pub after_header: bool,
/// The part reports an access node of this role and name though no face is painted for it.
pub node: Option<(crate::runtime::access::Role, String)>,
}
impl PartBuilder<'_> {
@@ -245,6 +247,12 @@ impl PartBuilder<'_> {
self
}
/// The part reports an access node of `role`, named `name`, for a part the component paints no face for.
pub fn node(self, role: crate::runtime::access::Role, name: impl Into<String>) -> Self {
self.declared.node = Some((role, name.into()));
self
}
/// A part with no focus stop names its keyboard path: the intent or command that does the same.
pub fn pointer_only(self, reason: &'static str) -> Self {
self.declared.pointer_only = Some(reason);
+1
View File
@@ -85,6 +85,7 @@ mod keys;
mod lead;
mod measure;
mod members;
pub use members::item_node;
mod output;
mod press;
mod rename;
+11 -6
View File
@@ -10,7 +10,7 @@
use super::marquee::MarqueeDrag;
use super::{ItemsHooks, Placement};
use crate::contract::collection::{
CollectionEvent, CollectionProps, ColumnKind, ContextMenuRequest, DropAt, DropPayload, DropPlace, ListDrag, PendingDrop, ReorderMove,
CollectionEvent, CollectionProps, ColumnKind, ContextMenuRequest, DropAt, DropPayload, DropPlace, ListDrag, PendingDrop, ReorderMove, RowPreview,
ToggleColumn, ToggleEdit,
};
use crate::contract::reorder;
@@ -25,6 +25,7 @@ use craft_behavior::{
};
use egui::{Pos2, Rect, Vec2};
use std::any::Any;
use std::borrow::Cow;
/// Maps a point to layout coordinates once for every collection type.
fn logical_point(layout: &dyn ItemLayout, rect: Rect, rtl: bool, at: Pos2) -> Pos2 {
@@ -591,11 +592,15 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
let key = self.source.key(at);
let keys = self.keys_at(&self.acted_on(at));
let count = keys.len() as u64;
let preview = match props.drag_count.filter(|_| props.drag_badge) {
Some(word) => DragPreview::Badge(Label::from(cx.env.counted(word, count))),
None if !props.drag_badge => DragPreview::None,
None if count > 1 => DragPreview::Badge(Label::from(count.to_string())),
None => self.source.text(at).map_or(DragPreview::None, |text| DragPreview::Badge(Label::from(text.into_owned()))),
let text = || match props.drag_count {
Some(word) => Some(cx.env.counted(word, count)),
None if count > 1 => Some(count.to_string()),
None => self.source.text(at).map(Cow::into_owned),
};
let preview = match props.drag_preview {
RowPreview::Badge => text().map_or(DragPreview::None, |text| DragPreview::Badge(Label::from(text))),
RowPreview::Named => text().map_or(DragPreview::None, |text| DragPreview::Named(Label::from(text))),
_ => DragPreview::None,
};
let drag = ListDrag::new(id, keys, key.clone());
let also: Vec<_> = props.drag_payloads.iter().filter_map(|map| map.of(&drag)).collect();
@@ -608,7 +608,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
}
let leaf = leaf_height.map_or(row, |height| Rect::from_min_size(row.min, Vec2::new(row.width(), height)));
// A member has no node of its own: it reports as a sub-node of the collection's.
let row_node = if C::MEMBERS { super::members::lead_node(id, &key) } else { item_id };
let row_node = if C::MEMBERS { super::members::item_node(id, &key) } else { item_id };
shown_rows.push(ShownRow::new(key.clone(), row_node, leaf, shown_cells.clone()).with_hover(state.hovered));
let Some((mut row_ui, installed)) = row_ui else {
debug_assert!(tip.is_none() && detail.is_none(), "a member of a collection's run takes no rich tooltip and no detail body");
@@ -693,7 +693,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
access::set_focus(&ctx, crate::runtime::access::sub_node_id(id, section_part(&key)));
} else {
if C::MEMBERS {
access::set_focus(&ctx, super::members::lead_node(id, &key));
access::set_focus(&ctx, super::members::item_node(id, &key));
} else {
let item_id = sub(id, ("key", key_hash(&key)));
let cell = (sheet && self.selection.lead_column().is_some()).then_some(self.lead.column);
@@ -100,7 +100,9 @@ pub(super) fn item_id<K: std::hash::Hash>(id: Id, key: &K) -> Id {
crate::runtime::memory::sub(id, ("key", key_hash(key)))
}
/// The access node a members collection's lead item stands for: the sub-node of its item part.
pub(super) fn lead_node<K: std::hash::Hash>(id: Id, key: &K) -> Id {
/// The access node of the item `key` of the members collection `id` (a tab strip, a swatch table): the sub-node of its
/// item part, which [`focused_node`](crate::runtime::access::focused_node) reports while the item is the lead of the
/// focused collection.
pub fn item_node<K: std::hash::Hash>(id: Id, key: &K) -> Id {
access::sub_node_id(id, ITEM_NODE.at(key_hash(key)))
}
+2 -1
View File
@@ -14,6 +14,7 @@ pub use leaf::colon_of;
pub(crate) use place::{control_after, label_gap};
pub(crate) use props::inside;
pub use props::{
CaptionColumn, CellWidth, FieldLayout, GlyphColon, GlyphLabel, InsideLabel, LabelKind, LabelPress, LabelScheme, LinkLabelInk, Scrub, SideLabel,
CaptionColumn, CaptionInk, CellWidth, FieldLayout, GlyphColon, GlyphLabel, InsideLabel, LabelKind, LabelPress, LabelScheme, LinkLabelInk, Scrub,
SideLabel,
};
pub(crate) use step::{LabelIn, LeafLabel, Trailing, flow_leaf, in_column, leaf, leaf_under, report_after_reach, run, show_leaf_in_flow};
@@ -1,6 +1,6 @@
//! The side label as a leaf component: its node, press state, reset dot and colon.
use super::props::{FieldLayout, Glyph, GlyphColon, LabelKind, LabelScheme, LinkLabelInk};
use super::props::{CaptionInk, FieldLayout, Glyph, GlyphColon, LabelKind, LabelScheme, LinkLabelInk};
use super::step::LabelIn;
use crate::contract::InBar;
use crate::contract::{Component, Props};
@@ -30,8 +30,8 @@ pub(super) struct LabelStyle {
gap: f32,
/// The detail: `text.muted`, `text.disabled` with a disabled control.
detail: Stateful<StyleColor>,
/// The name: `TypeRole::Label` in `text.muted`; after a check box or a radio, `TypeRole::Body` in `text.normal`.
/// `text.disabled` with a disabled control.
/// The name: `TypeRole::Label` in the [`CaptionInk`]; after a check box or a radio, `TypeRole::Body` in
/// `text.normal`. `text.disabled` with a disabled control.
#[style(text)]
name: TextLook,
/// The glyph and icon: their own ink (`None`), `text.disabled` with a disabled control.
@@ -173,7 +173,8 @@ impl Component for LabelLeaf {
// A caption reads as secondary; a check box's or a radio's text after it is the control's own.
name: {
let text = &cx.tokens.color.text;
let (role, ink) = if key.after { (TypeRole::Body, text.normal) } else { (TypeRole::Label, text.muted) };
let caption = if cx.env::<CaptionInk>() == CaptionInk::Normal { text.normal } else { text.muted };
let (role, ink) = if key.after { (TypeRole::Body, text.normal) } else { (TypeRole::Label, caption) };
let neutral = cx.env::<LinkLabelInk>() == LinkLabelInk::Neutral;
if key.link && !neutral {
// A link label keeps its role, so it takes the room of the caption it is, in the link's ink.
@@ -136,6 +136,21 @@ pub enum LinkLabelInk {
Neutral,
}
/// The ink of a side label's name, other than a link's ([`LinkLabelInk`]) and the text after a check box or a radio,
/// which reads at full ink. An app sets it once at its root (`RootEnv::values`); the default is the muted ink of a
/// caption that reads as secondary.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::runtime::env::EnvValue, crate::contract::MemoProps)]
#[env(style)]
#[non_exhaustive]
pub enum CaptionInk {
/// `text.muted`.
#[default]
Muted,
/// `text.normal`, the ink of the values beside it: VectorCraft's field labels ("X:", "Angle:", "Opacity"), as
/// production drew them.
Normal,
}
/// Whether the beside captions of a [`LabelScheme::Inline`] form share one column. Off (the default), each caption is
/// as wide as its own text and its control follows it at once. On, the captions keep to the row start in one column as
/// wide as the widest, so the controls after them line up (production's Rotate Pages dialog: Direction:, Pages: and
+88 -28
View File
@@ -11,6 +11,7 @@ use crate::runtime::lazy::{self, Call, Decision, Key, Place};
use crate::runtime::measure::{MemoRun, count_memo_run};
use crate::runtime::memory::sub;
use crate::runtime::replay;
use craft_behavior::Axis;
use egui::{Pos2, Rect, Ui, UiBuilder, Vec2};
use std::hash::Hash;
@@ -67,33 +68,48 @@ impl Lazy {
}
}
/// The id of the child in `ui`: under its scroll area, or under `ui`'s scope outside every scroll area.
pub(super) fn id(&self, ui: &Ui) -> egui::Id {
match Env::of(ui).view().lazy_view() {
Some(view) => sub(view.owner, ("lazy", self.key)),
None => sub(ui.scope_id(), ("lazy", self.key)),
}
}
/// The one runner of a `Lazy` child and a memoized view (`MemoView`), named `name` in the count trials: runs `add`,
/// replays the kept run of a memoized view keyed `key`, or takes the extent of a child out of view.
pub(super) fn run_keyed<R>(self, ui: &mut Ui, name: &'static str, key: Key, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Shown<R> {
let ctx = ui.ctx().clone();
let env = Env::of(ui);
let view = env.view().lazy_view();
let id = match view {
Some(view) => sub(view.owner, ("lazy", self.key)),
None => sub(ui.scope_id(), ("lazy", self.key)),
};
let id = self.id(ui);
let rtl = ui.layout().prefer_right_to_left();
let memo = matches!(key, Key::Memo(_));
// A memoized view is one unit of the shrinking row around it. A row that narrows it gives it at most the width
// its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not
// narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a
// new content runs it once and the discard pass its new size asks for replays that run.
let shrink = env.shrink.filter(|_| memo);
let cap = match shrink {
Some(Shrink::Apply(row)) => crate::layout::shrink_cap(&ctx, row, id).filter(|cap| cap.narrowed),
_ => None,
};
let available = cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width));
let available = if memo { on_row_line(ui, id, available) } else { available };
let sizing = ui.is_sizing_pass();
// The child is not part of its body's transcript: in a real run it counts there by its extent, whether it
// runs or not, so what scrolls into reach does not change the body's content.
let real = !sizing && !crate::runtime::measure::active(&ctx);
// A memoized view whose content filled the axis the body around it shares is one of the children that fill
// that body: a real run shows it in its share, as the body gives a child that fills it directly.
let share = env
.shares()
.filter(|axis| memo && real && lazy::fills(&ctx, id, sizing) == Some(*axis))
.and_then(|axis| crate::layout::fill_share(ui, axis).map(|share| (axis, share)));
// A memoized view is one unit of the shrinking row around it. A row that narrows it gives it at most the width
// its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not
// narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a
// new content runs it once and the discard pass its new size asks for replays that run. A view that fills the
// row takes no part in its shrink step, as a body that fills it does not.
let shrink = env.shrink.filter(|_| memo);
let cap = match shrink {
Some(Shrink::Apply(row)) if share.is_none() => crate::layout::shrink_cap(&ctx, row, id).filter(|cap| cap.narrowed),
_ => None,
};
let available = match share {
Some((axis, share)) => share_of(flow_region(ui), rtl, axis, share),
None => cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width)),
};
let available = if memo { on_row_line(ui, id, available) } else { available };
let owner = view.map(|view| view.owner);
// A run around this one that is replayed later keeps the child's entry.
replay::journal(&ctx, || (owner, id), |ctx, &(owner, id)| lazy::keep(ctx, owner, id));
@@ -147,7 +163,8 @@ impl Lazy {
{
// A real replay is where the run's content went, moved with the room.
let rect = if real { ran_at } else { Rect::from_min_size(at_start(available, rtl, size), size) };
let took = place_view(ui, rect);
let fills = if memo && !real { lazy::fills(&ctx, id, sizing) } else { None };
let took = place_unit(ui, (shrink, fills), id, rect, rtl);
let kept = if real {
layout_memory::backstop(&ctx, id, size);
let kept = lazy::replay_settled(&ctx, id, &shift);
@@ -160,7 +177,6 @@ impl Lazy {
// the extent this call takes, never from rects in it.
lazy::kept_output(&ctx, id)
};
report_unit(&ctx, shrink, id, rect.size());
#[cfg(feature = "testing")]
count_memo_run(&ctx, name, id, MemoRun::Replayed, real);
return Shown::Replayed(kept, shift);
@@ -177,6 +193,9 @@ impl Lazy {
if run.recording {
open_record(&ctx, audited.is_some());
}
if memo {
crate::layout::open_view_fill(&ctx, id);
}
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. The
// content runs in the env of `ui`, as the direct children of the body around it: a plain `Lazy` keeps their
@@ -185,6 +204,7 @@ impl Lazy {
let rect = child.min_rect();
// The child `Ui` writes its widget rect when it drops: the record holds it as written.
drop(child);
let fills = if memo { crate::layout::take_view_fill(&ctx, id) } else { None };
let record = run.recording.then(|| replay::close(&ctx, place.layer));
if let Some(shift) = audited {
return place_audit_run(ui, Audited { name, id, view, rect, record: record.as_ref(), shift }, out, &run);
@@ -199,15 +219,14 @@ impl Lazy {
layout_memory::backstop(&ctx, id, rect.size());
}
if memo {
place_view(ui, rect);
report_unit(&ctx, shrink, id, rect.size());
place_unit(ui, (shrink, fills.filter(|_| !real)), id, rect, rtl);
} else {
crate::layout::close_flow_start_in(ui);
alloc::advance_past(ui, rect);
}
if view.is_some() || memo {
let registered = real.then(|| record.as_ref().map_or_else(|| focus::transcript(&ctx, mark), |record| record.focus.clone()));
lazy::shown(&ctx, owner, id, sizing, lazy::Measured { size: rect.size(), key, room: available, flow: place.flow }, registered);
lazy::shown(&ctx, owner, id, sizing, lazy::Measured { size: rect.size(), key, room: available, flow: place.flow, fills }, registered);
}
if let Some(view) = view
&& real
@@ -296,17 +315,58 @@ fn at_most(region: Rect, rtl: bool, width: f32) -> Rect {
Rect::from_min_size(at_start(region, rtl, size), size)
}
/// Reports the extent `size` of the memoized view `id` to the shrinking row around it: what it takes, in the row's
/// counting sweep, and its least, in the sweep that asks the row's body units for theirs. Like a body unit, it narrows
/// from what it takes in no room down to what it takes with every leaf at its least.
fn report_unit(ctx: &egui::Context, shrink: Option<Shrink>, id: egui::Id, size: Vec2) {
match shrink {
Some(Shrink::Count(row)) => crate::layout::report_shrink(ctx, row, id, size.x, size.x, None, (false, None)),
Some(Shrink::Least(row)) => crate::layout::report_least(ctx, row, id, size.x),
_ => {}
/// `region` cut to `share` at most along `axis`, from its start edge: the room of a memoized view that fills the body
/// around it.
fn share_of(region: Rect, rtl: bool, axis: Axis, share: f32) -> Rect {
match axis {
Axis::X => at_most(region, rtl, share),
_ => Rect::from_min_size(region.min, Vec2::new(region.width(), share.min(region.height()))),
}
}
/// Places the extent `rect` of the memoized view `id` in flow in `ui` (`place_view`) as one unit of the body around it,
/// and returns the rect it took. `fills` is the axis the body shares which the view's content filled in a measuring
/// run: the view is then one of the children that fill the body, as a child shown there directly is. It takes its
/// share along the axis once the body knows it; in the first sweep of the body's measuring run it is counted and takes
/// nothing there (`counting_fills`), outside the least measure, where it takes what its content took. In a shrinking
/// row it is a unit that does not narrow below what it takes, as a body that fills the row is.
///
/// Any other view reports its extent to the shrinking row around it: what it takes, in the row's counting sweep, and
/// its least, in the sweep that asks the row's body units for theirs. Like a body unit, it narrows from what it takes
/// in no room down to what it takes with every leaf at its least.
fn place_unit(ui: &mut Ui, (shrink, fills): (Option<Shrink>, Option<Axis>), id: egui::Id, rect: Rect, rtl: bool) -> Rect {
let ctx = ui.ctx().clone();
let env = Env::of(ui);
let Some(axis) = fills.filter(|axis| env.shares() == Some(*axis)) else {
let took = place_view(ui, rect);
match shrink {
Some(Shrink::Count(row)) => crate::layout::report_shrink(&ctx, row, id, rect.width(), rect.width(), None, (false, None)),
Some(Shrink::Least(row)) => crate::layout::report_least(&ctx, row, id, rect.width()),
_ => {}
}
return took;
};
let content = rect.size();
let along = match crate::layout::fill_share(ui, axis) {
Some(share) => Some(share),
None if crate::layout::counting_fills(ui, axis) && !env.least => {
crate::layout::count_fill_view(ui);
Some(0.0)
}
None => None,
};
let size = match (axis, along) {
(Axis::X, Some(along)) => Vec2::new(along, content.y),
(_, Some(along)) => Vec2::new(content.x, along),
(_, None) => content,
};
let took = place_view(ui, Rect::from_min_size(at_start(rect, rtl, size), size));
if let (Axis::X, Some(Shrink::Count(row))) = (axis, shrink) {
crate::layout::report_shrink(&ctx, row, id, size.x, size.x, Some((size.x, size.x)), (false, None));
}
took
}
/// Places a memoized view's extent `rect` in flow in `ui`, as its run and its replay both do, and returns `rect`: in the
/// `Grid` or spread `Row` body that encloses `ui` directly the view takes the next cell at its extent, as its content
/// starts a layout room of its own and takes none; elsewhere the flow moves past `rect`.
+18 -9
View File
@@ -3,7 +3,7 @@
use super::lazy::{Lazy, Shown};
use super::memo::{MemoKey, MemoProps};
use crate::runtime::env::{Env, Scoped, Shrink};
use crate::runtime::env::{Env, Shrink};
use crate::runtime::shift::Shift;
use egui::Ui;
use std::fmt;
@@ -48,9 +48,9 @@ use std::sync::Arc;
/// Its other inputs are the framework's, and each reaches the key or the settled test:
/// - its place: the room it is given, the clip, the layer, the layout, the scale, the scope's style inputs (tokens,
/// theme, density, direction, language, window active) and the flow of the body around it (whether that body is a
/// content-sized or a given column, the axes it sizes from its content, a least measure, the axes a scroll leaves
/// unbounded, a beside label's cell, whether its leaves fit the room), compared for every view and for each kind of
/// run on its own;
/// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that
/// fill it, a least measure, the axes a scroll leaves unbounded, a beside label's cell, whether its leaves fit the
/// room), compared for every view and for each kind of run on its own;
/// - what the scope around it hands down beyond those (enabled, read-only, size, ink, the command chain, motion, every
/// app value, and the rest of `Scoped::scope_key`), in the key;
/// - the framework inputs it reads outside its props (`runtime::inputs`: the modifiers, the pointer, the keys held, the
@@ -64,8 +64,15 @@ use std::sync::Arc;
/// around it the view is one unit, sized by its content's measure. In a shrinking `Row` it is a unit the row narrows
/// as it narrows a body unit: from what its content takes in no room down to what it takes with every leaf at its
/// least. When the row narrows it, the width the row gives it is the room of its place; otherwise it shows as in no
/// room, in the row's flow region. Its content sizes from its content along x, and its leaves fit the view's room, as
/// they fit the room of a `Stack` the view is shown in.
/// room, in the row's flow region. Its leaves fit the view's room, as they fit the room of a `Stack` the view is shown
/// in.
///
/// In a `Stack` or `Row` body that shares its height or width among the children that fill it, a view whose content
/// fills that axis (a direct child of the content given it to fill, as a fill-width bar in a shell slot) is one of
/// those children, as that child shown without the view would be: the body counts it, and gives it its share as the
/// room of its place, so a new share runs it. Which axis its content filled is kept with its measure. In a shrinking
/// `Row` that does not share its width, its content sizes from its content along x: a child that fills there takes its
/// measured width.
///
/// What `show` returns holds layout facts only (a size, a rect, which part took the room). A replay returns the kept
/// value again, moved with the record when the room moved (`Shift`), so an event returned through it would arrive once
@@ -120,12 +127,14 @@ impl<P: MemoProps, R: Clone + PartialEq + Shift + Send + Sync + 'static> MemoVie
let counting = matches!(Env::of(ui).shrink, Some(Shrink::Count(_)));
let unbounded = counting.then(|| Env::install_for(ui, Env::of(ui).derive_local(|scoped| scoped.unbounded.0 = true)));
let env = Env::of(ui);
let id = lazy.id(ui);
let key = Self::key(&ctx, &env, &props, show);
let shown = lazy.run_keyed(ui, std::any::type_name::<P>(), crate::runtime::lazy::Key::Memo(key), |ui, run| {
// The content is a layout room of its own: the flow of the body around it does not reach in. It keeps how
// that body sizes from its content and whether its leaves fit their room (`Scoped::start_view_room`), so
// the view takes what its content used there, as the same content shown without the view would.
let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room));
// that body sizes from its content, whether its leaves fit their room and which axis it shares among the
// children that fill it (`Scoped::start_view_room`), so the view takes what its content used there, as the
// same content shown without the view would.
let installed = Env::install_for(ui, env.derive_local(|scoped| scoped.start_view_room(id)));
let out = show(&mut props, ui);
Env::restore(&ctx, installed);
run.output = Some(Arc::new(out.clone()));
+4 -3
View File
@@ -61,7 +61,7 @@ pub use collection::{
ActivateOn, CollectionEvent, CollectionProps, CollectionResponse, ColumnAlign, ColumnEvent, ColumnKind, ColumnLayout, ColumnRemove,
ColumnRequest, ColumnSort, ColumnSpec, ContextMenuRequest, DeleteTarget, DragPayload, DropAt, DropKind, DropPayload, DropPlace, EdgePress,
HeaderMenuRequest, HoverLead, ItemKeys, LeadOnOpen, LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowHeight,
RowPressed, RowState, SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit,
RowPressed, RowPreview, RowState, SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit,
};
#[doc(hidden)]
pub use container::InBar;
@@ -85,6 +85,7 @@ pub use footer_slot::FooterSlot;
pub use group::{GroupHandle, GroupKind, GroupState};
pub use held::Held;
pub use hosted::{Hosted, HostedKey, Hosting};
pub use items::item_node;
pub use items::lead_position;
#[doc(hidden)]
pub use items::put_toggle_names;
@@ -93,8 +94,8 @@ pub use items::{measure_item, show_item, show_item_in_flow};
#[doc(hidden)]
pub use label::colon_of;
pub use label::{
CaptionColumn, CellWidth, FieldLabelRole, FieldLayout, GlyphColon, GlyphLabel, InsideLabel, LabelKind, LabelPress, LabelScheme, LinkLabelInk,
Scrub, SideLabel,
CaptionColumn, CaptionInk, CellWidth, FieldLabelRole, FieldLayout, GlyphColon, GlyphLabel, InsideLabel, LabelKind, LabelPress, LabelScheme,
LinkLabelInk, Scrub, SideLabel,
};
pub use lazy::Lazy;
#[doc(hidden)]
+8 -9
View File
@@ -365,25 +365,24 @@ impl Host for ViewportHost {
let spec = self.spec.clone().unwrap_or_else(by_rank);
let placed = self.overlay.placed;
let full_window = self.overlay.is_full_window();
// A full-window container fills its window, so the window's own layout memory holds the size the user gave
// it; before it has one the window opens at the opener's content size, large enough for a workspace.
let measured = || {
let remembered = layout_memory::read(&ctx, id);
if full_window { remembered.or_else(|| Some(ctx.content_rect().size())) } else { remembered }
};
// A full-window container fills its window and has no content size: its window opens at the opener's content
// size, large enough for a workspace. What its body took is no size for the window: side panels, header and
// footer are no part of it, and a window sent it shrank by them each pass (photocraft#16595).
let measured = || if full_window { Some(ctx.content_rect().size()) } else { layout_memory::read(&ctx, id) };
let open = ViewportOpen {
id,
title: title.as_str(),
// A placed rect is the caller's size for the window, within the window's limits, which the OS would clamp it
// to; then a resizable fallback's default size, as the layer takes it; the measured size is for a window
// sized by content: what its body took in the window, recorded once the window reported its place
// (`steps::record_body_size`).
// (`steps::record_body_size`), or a full-window container's opening size.
size: placed
.map(|rect| self.overlay.size_limits.clamp(rect.size()))
.or(self.overlay.size.filter(|_| self.overlay.fit == overlay::OverlayFit::Resizable))
.or_else(measured),
// A resizable window takes its default or content size to open; from then on its size is the user's.
follows_size: placed.is_some() || self.overlay.fit != overlay::OverlayFit::Resizable,
// A resizable window takes its default or content size to open; from then on its size is the user's, as a
// full-window container's is.
follows_size: placed.is_some() || (!full_window && self.overlay.fit != overlay::OverlayFit::Resizable),
save: self.save.as_deref(),
spec: &spec,
limits: (Some(self.overlay.size_limits.min), self.overlay.size_limits.max),
@@ -4,9 +4,10 @@ use super::host::{Layer, LayerMemory};
use super::props::Outside;
use crate::contract::{Component, Cx};
use crate::runtime::commands::FireSource;
use crate::runtime::egui::pass;
use crate::runtime::focus::{self, FocusPolicy, Initial};
use crate::runtime::overlay::{self, CloseReason, Rank};
use crate::runtime::{frame, keys, pointer};
use crate::runtime::{frame, keys, pointer, sampler};
use craft_behavior::CancelRule;
use craft_keymap::Mods;
use egui::{Context, Rect};
@@ -94,13 +95,15 @@ pub(super) fn popup_dismissal(
(here || away || crate::runtime::windows::pressed_elsewhere(ctx, popup, appears)).then_some(CloseReason::Outside)
}
/// Whether a primary press landed outside the layer, its anchor and the layers opened from inside it.
/// Whether a primary press landed outside the layer, its anchor and the layers opened from inside it. A press the
/// canvas the layer keeps open took (a colour sampled under the Color Picker) is the canvas's, not one beside the layer.
fn press_outside(ctx: &Context, layer: &Layer<'_>, rect: Rect, anchor: Rect) -> bool {
let Some(press) = pointer::primary_press(ctx) else {
return false;
};
let inside_family = overlay::family(ctx, layer.id).iter().filter_map(|id| overlay::entry(ctx, *id)).any(|entry| entry.rect.contains(press));
!rect.contains(press) && !anchor.contains(press) && !inside_family
let sampled = || sampler::through(ctx, pass::current_viewport(ctx), layer.id).is_some() && sampler::admitted_press(ctx, press);
!rect.contains(press) && !anchor.contains(press) && !inside_family && !sampled()
}
/// Whether the focused stop sits in no scope that belongs to a shown layer.
@@ -80,6 +80,10 @@ pub enum Place {
offset: egui::Vec2,
/// A rect the layer keeps clear of, in the layer's own space.
clear: Option<egui::Rect>,
/// Below or above the anchor, a layer that fits on neither side keeps its size and slides over the anchor,
/// inside its bounds, instead of being cut to the room left beside it: a task bar under a crop frame that
/// fills the canvas.
covers: bool,
},
/// Free-standing.
Float(FloatPlace),
@@ -88,13 +92,15 @@ pub enum Place {
impl Place {
/// An anchored place.
pub const fn anchored(anchor: Anchor, side: Side, align: Align) -> Self {
Place::Anchored { anchor, side, align, flips_across: false, offset: egui::Vec2::ZERO, clear: None }
Place::Anchored { anchor, side, align, flips_across: false, offset: egui::Vec2::ZERO, clear: None, covers: false }
}
/// The place, beside its anchor, lining up with the anchor's other end when that fits and the aligned end does not.
pub const fn flipping_across(self) -> Self {
match self {
Place::Anchored { anchor, side, align, offset, clear, .. } => Place::Anchored { anchor, side, align, flips_across: true, offset, clear },
Place::Anchored { anchor, side, align, offset, clear, covers, .. } => {
Place::Anchored { anchor, side, align, flips_across: true, offset, clear, covers }
}
float => float,
}
}
@@ -107,6 +113,15 @@ impl Place {
self
}
/// The place, below or above its anchor, sliding over the anchor when it fits on neither side; no change off
/// `Anchored`.
pub fn covering_anchor(mut self) -> Self {
if let Place::Anchored { covers, .. } = &mut self {
*covers = true;
}
self
}
/// The place keeping clear of `rect`; no change off `Anchored`.
pub fn clear_of(mut self, rect: egui::Rect) -> Self {
if let Place::Anchored { clear, .. } = &mut self {
@@ -54,8 +54,12 @@ pub(super) fn opened_overlay(ctx: &Context, overlay: &Overlay, stored: Option<Op
/// Whether a layer of `overlay` may cover its anchor when it fits on neither side of it: a menu's layer (its key class
/// is [`OwnerClass::Menu`]) hung at the pointer, at a point, or at the rect a context request named. No other overlay
/// covers its anchor: a tooltip or a popover at the pointer stays off it. `stored` is the opening the layer decided.
/// covers its anchor: a tooltip or a popover at the pointer stays off it, unless its place asks for it
/// ([`Place::covering_anchor`]). `stored` is the opening the layer decided.
pub(super) fn layer_covers_anchor(ctx: &Context, overlay: &Overlay, stored: Option<Opening>) -> bool {
if matches!(overlay.place, Place::Anchored { covers: true, .. }) {
return true;
}
if overlay.keys != OwnerClass::Menu {
return false;
}
@@ -11,7 +11,7 @@ use crate::runtime::env::{Label, Message};
use crate::runtime::focus::{self};
use crate::runtime::{inspect, keys, pass_state};
use crate::style::Flags;
use craft_behavior::Sense;
use craft_behavior::{PartRef, Sense};
use egui::Id;
/// What step 16 reads that the pass computed before: the part declarations, the sense and the container facts.
@@ -276,6 +276,16 @@ pub(crate) fn report_parts(core: &CxCore<'_>, decls: &Decls, nodes: &[SubNode],
for face in faces.iter().filter(|face| !seen.contains(&face.part)) {
report_sub(core, decls, &SubNode::new(face.part, face.role), Some(face), parent);
}
for (decl, extras) in decls {
let part = PartRef { key: decl.key, index: decl.index };
let Some((role, name)) = &extras.node else { continue };
if seen.contains(&part) || faces.iter().any(|face| face.part == part) {
continue;
}
let mut node = SubNode::new(part, *role);
node.name = access::Name::Text(name.clone());
report_sub(core, decls, &node, None, parent);
}
}
fn report_sub(core: &CxCore<'_>, decls: &Decls, node: &SubNode, face: Option<&FaceRecord>, parent: Id) {
+13 -4
View File
@@ -2,7 +2,8 @@
//!
//! A tooltip shows after one delay while the pointer rests on the component, or on keyboard focus after the same
//! delay, and at once while a neighbour's tooltip was hiding a moment ago. A press, a menu that owns keys and a
//! running drag hide it.
//! running drag hide it. A press on the component keeps its tooltip hidden until the pointer leaves it, so what the
//! press opens (a popover under a swatch) is not covered.
//!
//! A component with no tooltip shows its own label as the tooltip when its type declares `Component::SHOWS_LABEL`
//! false (or an instance does, through `Component::shows_label`): no text paints that name, inside a field or not. A
@@ -42,6 +43,8 @@ struct TipState {
shown: bool,
/// The part the tooltip belongs to; `None` for the component's own.
subject: Option<PartRef>,
/// A press on the subject hid the tooltip; it stays hidden until neither the pointer nor the keyboard is on it.
dismissed: bool,
}
/// When the last tooltip of the context hid.
@@ -279,7 +282,8 @@ struct TipCall<'a> {
text: &'a dyn Fn() -> Option<String>,
rich: Option<TipFn<'a>>,
spec: Option<&'a TooltipSpec>,
/// The tooltip shows at the pointer whatever its spec's `at` says.
/// The tooltip shows at the pointer whatever its spec's `at` says. Such a tip has no subject a press could
/// dismiss it from: it hides only while the press lasts.
at_pointer: bool,
/// The pointer rests on the subject or the keyboard is on it.
wants_input: bool,
@@ -313,7 +317,12 @@ fn show_tip(call: TipCall<'_>) {
}
let when_now = spec.is_some_and(|spec| spec.when == TooltipWhen::Now);
let screen = areas::layer_to_screen(ctx, rect_layer) * rect;
let suppressed = pressed || overlay_blocks(ctx, screen.center()) || pointer::press_captured(ctx) || drag::running(ctx);
if !wants_input {
state.dismissed = false;
} else if pressed && !at_pointer {
state.dismissed = true;
}
let suppressed = pressed || state.dismissed || overlay_blocks(ctx, screen.center()) || pointer::press_captured(ctx) || drag::running(ctx);
if wants {
state.since.get_or_insert(now);
} else {
@@ -334,7 +343,7 @@ fn show_tip(call: TipCall<'_>) {
state.shown = show;
let tip_id = sub(id, "tip");
let presence = motion::layer_presence(ctx, tip_id, owner, env.motion, show, overlay_motion());
if state.shown || state.since.is_some() || presence.visible {
if state.shown || state.since.is_some() || state.dismissed || presence.visible {
store::put(ctx, state_id, state);
}
if !presence.visible {
+33 -1
View File
@@ -141,6 +141,11 @@ pub(crate) struct Cursors(IdMap<Cursor>);
#[derive(Default)]
pub(crate) struct FillCounts(IdMap<u32>);
/// The memoized views running this pass whose content holds a direct child that fills the axis the body around the
/// view shares (`Scoped::fill_view`), by view id, with that axis.
#[derive(Default)]
pub(crate) struct ViewFills(IdMap<Axis>);
/// What makes a child of a content-sized `Stack` column a held child: it measures at its own width while the column
/// settles its width from the others, and the column's second sweep gives it the settled width.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -423,6 +428,9 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32
if !given {
return measured;
}
if let Some((view, along)) = env.fill_view.filter(|(_, along)| *along == axis) {
pass_state::with::<ViewFills, _>(ui.ctx(), |fills| fills.0.insert(view, along));
}
// In a body that shares the axis and scrolls along it, a share never cuts the child's content: what is past the
// view scrolls.
if env.fill_body.is_some_and(|(_, along)| along == axis) && view_room(ui, axis).is_some() {
@@ -452,12 +460,36 @@ fn main_fill(ui: &Ui, id: Id, axis: Axis) -> MainFill {
return MainFill::Share(share, layout_memory::fill_least(ui.ctx(), id, axis));
}
if measure::active(ui.ctx()) {
pass_state::with::<FillCounts, _>(ui.ctx(), |counts| *counts.0.entry(body).or_insert(0) += 1);
count_fill(ui.ctx(), body);
return MainFill::Measuring;
}
MainFill::Room(layout_memory::fill_least(ui.ctx(), id, axis))
}
/// Counts one child that fills the main axis of the sharing body `body`, in the first sweep of its measuring run.
fn count_fill(ctx: &egui::Context, body: Id) {
pass_state::with::<FillCounts, _>(ctx, |counts| *counts.0.entry(body).or_insert(0) += 1);
}
/// Counts the memoized view whose content fills the main axis of `ui`'s sharing body as one child that fills it, in the
/// first sweep of the body's measuring run (`counting_fills`), as a child shown there directly is counted.
pub(crate) fn count_fill_view(ui: &Ui) {
if let Some((body, _)) = Env::of(ui).fill_body {
count_fill(ui.ctx(), body);
}
}
/// Opens the record of whether the content of the memoized view `view` fills the axis its body shares, before its run.
pub(crate) fn open_view_fill(ctx: &egui::Context, view: Id) {
pass_state::with::<ViewFills, _>(ctx, |fills| fills.0.remove(&view));
}
/// The axis the content of the memoized view `view` filled in the run that just ended, as `fill_size` noted it; closes
/// the record.
pub(crate) fn take_view_fill(ctx: &egui::Context, view: Id) -> Option<Axis> {
pass_state::with::<ViewFills, _>(ctx, |fills| fills.0.remove(&view))
}
/// The share a child of `ui`'s body that fills along `axis` takes there, once its body knows it: the room the child
/// is measured and shown in along that axis, in the measuring run's second sweep and in the real run alike.
pub(crate) fn fill_share(ui: &Ui, axis: Axis) -> Option<f32> {
+4 -4
View File
@@ -24,8 +24,8 @@ pub use body::place_in_flow;
#[cfg(feature = "testing")]
pub(crate) use body::run_body;
pub(crate) use body::{
BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share,
fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, members_line,
open_first_lines, place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y,
shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, view_room,
BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start_in, count_fill_view, counting_fills,
fill_share, fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room,
members_line, open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room,
run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, take_view_fill, view_room,
};
@@ -69,11 +69,11 @@ pub(crate) fn pointer_art(env: &Env, cursor: &PaintedCursor, closed: bool, marks
PaintedCursor::Locator => locator(&pen),
PaintedCursor::Arrow { hollow, toward, .. } => arrow(&pen, *hollow, *toward),
PaintedCursor::PathText { start, end, .. } => path_text(&pen, *start, *end),
PaintedCursor::PointerTool { pointer, icon, .. } => {
PaintedCursor::PointerTool { pointer, icon, badge, .. } => {
// The arrow's icon sits under its body, so it takes the larger size to show past the arrow.
let side = if *pointer == PointerGlyph::Arrow { env.tokens.size.icon.md } else { env.tokens.size.icon.sm };
let icon = SvgIcon::of(&env.tokens, env.direction, side, icon, Mirror::Auto);
pointer_tool(&pen, *pointer, icon, side, edge, ink);
pointer_tool(&pen, *pointer, icon, *badge, side, edge, ink);
}
// `Hidden` has no marks.
_ => {}
@@ -451,14 +451,27 @@ pub(crate) fn path_text(pen: &Pen, start: bool, end: bool) {
/// `pointer` with the tool's `icon` of `side` points below and right of it: a crosshair with arms of `side` points in a
/// line of `width` in `color`, as the plain crosshair pointer, beside the icon; or the solid arrow, as the plain arrow
/// pointer, over the icon's top-left corner. An icon the catalog lacks leaves only the pointer.
pub(crate) fn pointer_tool(pen: &Pen, pointer: PointerGlyph, icon: Option<SvgIcon>, side: f32, width: f32, color: Color32) {
/// pointer, over the icon's top-left corner; `badge` at the icon's lower right. An icon the catalog lacks leaves only the
/// pointer and the badge.
pub(crate) fn pointer_tool(
pen: &Pen,
pointer: PointerGlyph,
icon: Option<SvgIcon>,
badge: Option<CursorBadge>,
side: f32,
width: f32,
color: Color32,
) {
let corner = match pointer {
PointerGlyph::Arrow => ARROW_ICON,
_ => CROSSHAIR_ICON,
};
let rect = Rect::from_min_size(v(corner).to_pos2(), Vec2::splat(side));
if let Some(icon) = icon {
icon_on_halo(pen, Rect::from_min_size(v(corner).to_pos2(), Vec2::splat(side)), icon);
icon_on_halo(pen, rect, icon);
}
if let Some(badge) = badge {
self::badge(pen, rect.right_bottom().to_vec2(), badge);
}
match pointer {
PointerGlyph::Arrow => arrow(pen, false, None),
+1
View File
@@ -19,6 +19,7 @@ use egui::Id;
use std::ops::RangeInclusive;
pub use crate::runtime::egui::access::bounds;
pub use crate::runtime::egui::access::focused_node;
#[doc(hidden)]
pub use emit::SubDecl;
#[doc(hidden)]
+20 -8
View File
@@ -959,14 +959,26 @@ pub(crate) struct Ghost {
pub mark: Option<(DropMark, Arc<UiTokens>)>,
}
/// The running session's ghost data.
/// The running session's ghost data for the running viewport. The mark paints in the window whose target registered
/// it, and also in the window the session moves, mapped to the same desktop place: that window lies over the mark,
/// which would otherwise show only through it.
pub(crate) fn ghost(ctx: &Context) -> Option<Ghost> {
let viewport = pass::current_viewport(ctx);
board(ctx, |board| {
board.session.as_ref().map(|session| Ghost {
preview: session.preview.clone(),
env: session.env.clone(),
mark: session.mark.as_ref().filter(|shown| shown.viewport == viewport).map(|shown| (shown.mark, shown.tokens.clone())),
})
})
let (preview, env, mark, moves_this) = board(ctx, |board| {
board
.session
.as_ref()
.map(|session| (session.preview.clone(), session.env.clone(), session.mark.clone(), session.moving.viewport == Some(viewport)))
})?;
let mark = mark.and_then(|shown| {
let offset = if shown.viewport == viewport {
Vec2::ZERO
} else if moves_this {
WindowHost::of(ctx).offset_between(shown.viewport, viewport)?
} else {
return None;
};
Some((shown.mark.mapped(|point| point + offset), shown.tokens))
});
Some(Ghost { preview, env, mark })
}
+31 -6
View File
@@ -177,10 +177,26 @@ pub(crate) fn set_modal(ctx: &Context, id: Id) {
/// holds focus replays while nothing reaches it.
pub(crate) fn set_focus(ctx: &Context, id: Id) {
crate::runtime::replay::journal(ctx, || id, |ctx, &id| set_focus(ctx, id));
with_emitted(ctx, |emitted| emitted.focus_set = true);
with_emitted(ctx, |emitted| emitted.focus = Some(id));
ctx.set_accesskit_focus(id);
}
/// The node of the last finished pass of `viewport` that holds key focus.
#[derive(Clone, Copy)]
struct FocusedNode(Id);
fn focused_node_key(viewport: ViewportId) -> Id {
memory::unique(("craft access focused node", viewport))
}
/// The node that held key focus at the end of the running viewport's last finished pass, the one reported to
/// assistive technology: a focused part's node ([`sub_node_id`](crate::runtime::access::sub_node_id)), the shown item
/// of a list that holds focus, else the focused component's own; `None` when nothing holds focus.
pub fn focused_node(ctx: &Context) -> Option<Id> {
let viewport = pass::current_viewport(ctx);
ctx.data(|data| data.get_temp::<FocusedNode>(focused_node_key(viewport))).map(|node| node.0)
}
/// The runtime's nodes of a pass in the order it emitted them: the first time each node was reported as a child or
/// created, and the ids of the nodes written. egui lists a node's children in the order their nodes were first
/// created, which is not always the order the component emitted them in.
@@ -190,8 +206,8 @@ struct Emitted {
written: IdSet,
/// Text widgets whose node folds into their owner's node, each with its owner.
folded: IdMap<Id>,
/// Whether the runtime reported a focused node this pass.
focus_set: bool,
/// The focused node the runtime reported this pass.
focus: Option<Id>,
/// Components that offer a context menu this pass (a `Trigger::Context` opener on them).
context: IdSet,
}
@@ -288,11 +304,20 @@ pub(crate) fn order_children(ctx: &Context) {
reported.emitted.remove(&viewport)
})
.unwrap_or_default();
if !emitted.focus_set
&& let Some(owner) = ctx.memory(|memory| memory.focused()).and_then(|widget| emitted.folded.get(&widget))
let widget = ctx.memory(|memory| memory.focused());
let folded = widget.and_then(|widget| emitted.folded.get(&widget).copied());
if emitted.focus.is_none()
&& let Some(owner) = folded
{
ctx.set_accesskit_focus(*owner);
ctx.set_accesskit_focus(owner);
}
let focused = widget.map(|widget| emitted.focus.or(folded).unwrap_or(widget));
ctx.data_mut(|data| match focused {
Some(node) => {
data.insert_temp(focused_node_key(viewport), FocusedNode(node));
}
None => data.remove::<FocusedNode>(focused_node_key(viewport)),
});
hide_behind_modal(ctx, viewport, &emitted.written);
for parent in emitted.written {
ctx.accesskit_node_builder(parent, |node| {
@@ -3,6 +3,7 @@
//! A family crate hands the filter what it learned outside the window (a key equivalent the platform's menu
//! took) and the filter puts it into the viewport's input in the hook, ahead of the stages that read keys, so it
//! reaches the application as the key press the user made. No family crate touches `RawInput` or `egui::Event`.
//! The host's window-input policy (`FrameInput::window_input`) is applied here too, first.
use std::collections::HashMap;
@@ -12,6 +13,7 @@ use egui::{Context, Event, ViewportId};
use super::injected::{egui_modifiers, key_press, key_release};
use super::memory::Service;
use super::repaint;
use crate::runtime::frame::WindowInput;
use crate::runtime::windows::KeyEquivalent;
#[derive(Default)]
@@ -35,8 +37,10 @@ fn repeat_running_pass(ctx: &Context, viewport: ViewportId, reason: &'static str
}
}
/// The input hook's filter step: adds the queued key equivalents of `input.viewport_id` to `input.events`.
/// The input hook's filter step: drops a hosted window's input under [`WindowInput::Dropped`], then adds the queued
/// key equivalents of `input.viewport_id` to `input.events`.
pub(crate) fn input_hook(ctx: &Context, input: &mut egui::RawInput) {
drop_window_input(ctx, input);
dismiss_input(ctx, input);
let queued = Service::<Pending>::run(ctx, |pending| pending.by_viewport.remove(&input.viewport_id));
let Some(queued) = queued else { return };
@@ -51,6 +55,18 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut egui::RawInput) {
}
}
/// The policy step: under [`WindowInput::Dropped`] a hosted window's input keeps none of the window system's events or
/// files. It runs before the injected step joins the input, so injected input still reaches the window. The root's
/// input is the host's own, in eframe's `raw_input_hook`, where the host may already have added its own events.
fn drop_window_input(ctx: &Context, input: &mut egui::RawInput) {
if input.viewport_id == ViewportId::ROOT || crate::runtime::frame::window_input(ctx) != WindowInput::Dropped {
return;
}
input.events.clear();
input.hovered_files.clear();
input.dropped_files.clear();
}
/// Puts the press of `chord` ahead of its key-up when that is already in the input, else last; `tap` adds the
/// release right after it.
fn insert_press(input: &mut egui::RawInput, chord: Chord, platform: craft_keymap::Platform, tap: bool) {
+20 -2
View File
@@ -1,6 +1,8 @@
//! The theme styles' `right_to_left`.
//! The theme styles' `right_to_left` and font coverage transfer function.
use egui::{Context, Ui};
use craft_theme::Mode;
use egui::epaint::FontColorTransferFunction;
use egui::{Context, Theme, Ui};
/// Turns off egui's own caret blink in `ui`, and hides the caret stroke unless `visible`: the runtime blinks it.
pub(crate) fn set_text_cursor(ui: &mut Ui, visible: bool) {
@@ -63,3 +65,19 @@ pub(crate) fn set_theme_direction(ctx: &Context, root: &mut Ui, right_to_left: b
pub(crate) fn set_item_spacing(ui: &mut Ui, gap: egui::Vec2) {
ui.spacing_mut().item_spacing = gap;
}
/// Matches egui's font coverage transfer function to `mode` across both egui theme styles, so dark-on-light text
/// never renders with the dark-mode curve (or vice versa) when the app's mode differs from the OS's.
pub(crate) fn set_text_color_transfer(ctx: &Context, mode: Mode) {
let transfer = match mode {
Mode::Light => FontColorTransferFunction::LIGHT_MODE_DEFAULT,
Mode::Dark => FontColorTransferFunction::DARK_MODE_DEFAULT,
};
let matches = ctx.style_of(Theme::Dark).visuals.text_options.color_transfer_function == transfer
&& ctx.style_of(Theme::Light).visuals.text_options.color_transfer_function == transfer;
if !matches {
ctx.all_styles_mut(|style| {
style.visuals.text_options.color_transfer_function = transfer;
});
}
}
+37 -6
View File
@@ -78,7 +78,8 @@ pub(crate) struct FooterSlotOf {
}
/// The flow facts of the body around a memoized view that its content is laid out by: whether that body is a
/// content-sized or a given column, the axes it sizes from its content, whether the view runs in a least measure, the
/// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that fill
/// it, whether the view runs in a least measure, the
/// axes a scrolling body leaves unbounded, whether it fills a beside label's cell and whether its leaves fit the view's
/// room (`Scoped::view_fits`). A measuring run of a container or a row lays the view out under other facts than its
/// real run, so they are a fact of the view's place, which each kind of run compares on its own (`lazy::Place`,
@@ -88,6 +89,7 @@ pub(crate) struct Flow {
content_column: bool,
given_column: bool,
content: (bool, bool),
shares: Option<craft_behavior::Axis>,
least: bool,
unbounded: (bool, bool),
cell_fills: bool,
@@ -187,6 +189,10 @@ pub struct Scoped {
/// extents of the other children and the gaps, over the number of children that fill. `None` while the body is
/// measured, and without a measuring run of this pass.
pub(crate) fill_share: Option<f32>,
/// The memoized view whose content the scope's direct children run in, with the axis the body around that view
/// shares (its `fill_body`'s): a child given that axis to fill tells the view (`layout::fill_size`), which then is
/// a child that fills that body (`contract::lazy`).
pub(crate) fill_view: Option<(Id, craft_behavior::Axis)>,
/// The shrink step of the unwrapped `Row` or `Stack` body that encloses the scope, as its direct children in flow
/// take part in it.
pub(crate) shrink: Option<Shrink>,
@@ -419,8 +425,15 @@ impl Scoped {
/// Starts a layer from its opener's scope: the inherited group stays, the layer-local fields start fresh, and the
/// layer is no line of a bar it was opened from. A layer's content measures and runs in this.
///
/// The layer is outside its opener's flow: an inside label and a filling cell belong to the beside label's own
/// control, and the opener's least measure is not the layer's. A tooltip of a control in an inspector cell keeps
/// its text width, not the layer's cap.
pub(crate) fn start_layer(&mut self) {
self.start_room();
self.inside_label = None;
self.cell_fills = false;
self.least = false;
self.bracket = None;
self.measure = None;
self.arena = None;
@@ -457,6 +470,7 @@ impl Scoped {
self.column_row = false;
self.fill_body = None;
self.fill_share = None;
self.fill_view = None;
self.shrink = None;
self.column = None;
self.offered = None;
@@ -476,6 +490,7 @@ impl Scoped {
|| self.column_row
|| self.fill_body.is_some()
|| self.fill_share.is_some()
|| self.fill_view.is_some()
|| self.shrink.is_some()
|| self.column.is_some()
|| self.offered.is_some()
@@ -486,12 +501,17 @@ impl Scoped {
/// content axes. The view's content then measures and
/// fills as it would shown without the view: a child that fills takes its measured size where the body sizes from
/// content, never the open room. Where a leaf shown here would fit its room (`view_fits`), the leaves of the view's
/// content fit the room the view is given (`Shrink::Fit`). A view that is a unit of a shrinking `Row` sizes from its
/// content along x, as the row counted it: a child that fills there takes its measured width, not the row's flow
/// region a view the row does not narrow is shown in.
pub(crate) fn start_view_room(&mut self) {
/// content fit the room the view is given (`Shrink::Fit`).
///
/// In a body that shares an axis among the children that fill it (`fill_body`), a direct child of the content
/// given that axis to fill tells the view `view` (`fill_view`): the view is then one of the children that fill the
/// body, given its share as its room, as the child shown without the view would be. A view that is a unit of a
/// shrinking `Row` that does not share its width sizes from its content along x, as the row counted it: a child
/// that fills there takes its measured width, not the row's flow region a view the row does not narrow is shown in.
pub(crate) fn start_view_room(&mut self, view: Id) {
let fits = self.view_fits();
let row_unit = matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_)));
let shares = self.shares();
let (content_column, given_column, egui_cell) = (self.content_column, self.given_column, self.egui_cell);
// The view stands on the line of the row around it only to fill it, as a levelled unit does: a fill-width row in
// it (a bar in a shell slot) takes the line's height and centres on it, as shown without the view; its children
@@ -500,14 +520,23 @@ impl Scoped {
self.start_room();
(self.content_column, self.given_column, self.egui_cell) = (content_column, given_column, egui_cell);
self.row_line = line;
self.fill_view = shares.map(|axis| (view, axis));
if fits {
self.shrink = Some(Shrink::Fit);
}
if row_unit {
if row_unit && shares != Some(craft_behavior::Axis::X) {
self.content.0 = true;
}
}
/// The axis the enclosing body shares among its direct children that fill it (`fill_body`).
pub(crate) const fn shares(&self) -> Option<craft_behavior::Axis> {
match self.fill_body {
Some((_, axis)) => Some(axis),
None => None,
}
}
/// Whether a memoized view shown in flow here fits its content to its room, as a leaf here would: in a `Stack` body
/// and a wrapping `Row`, whose leaves show at most its room (a whole line), and as one of the units a shrinking
/// `Row` narrows. In a `Grid` cell or a `Ui` with no body around it a leaf keeps its measured width, and so does the
@@ -561,6 +590,7 @@ impl Scoped {
content_column: self.content_column,
given_column: self.given_column,
content: self.content,
shares: self.shares(),
least: self.least,
unbounded: self.unbounded,
cell_fills: self.cell_fills,
@@ -710,6 +740,7 @@ impl Env {
footer_slot: None,
fill_body: None,
fill_share: None,
fill_view: None,
shrink: None,
column: None,
least: false,
+15
View File
@@ -179,6 +179,21 @@ impl RootEnv {
self.resolved_for(super::system_appearance(ctx).appearance)
}
/// The mode the root's theme actually shows on `ctx`: the resolved mode clamped to the theme's supported
/// variants (for example, `Mode::Light` for a light-only theme even when dark mode is requested).
pub(crate) fn effective_mode(&self, ctx: &Context) -> Mode {
let wanted = self.resolved(ctx).mode;
if let Some(def) = &self.theme_def {
return def.variants.mode_for(wanted);
}
let themes = craft_theme::builtins();
let theme = [self.theme.as_str(), craft_theme::SUITE_DEFAULT]
.into_iter()
.find_map(|id| themes.iter().find(|theme| theme.id.as_str() == id))
.unwrap_or(&themes[0]);
theme.variants.mode_for(wanted)
}
/// What the choices resolve to when the OS reports `system`.
pub fn resolved_for(&self, system: SystemAppearance) -> ResolvedRoot {
let mode = match self.mode {
+43 -1
View File
@@ -32,12 +32,35 @@ pub struct FrameInput {
pub host: Option<Arc<Host>>,
/// The modifiers the app's own tablet or latched-key reader holds down beyond the window's input.
pub latched: Mods,
/// Whether the window system's input reaches the OS windows the runtime hosts.
pub window_input: WindowInput,
}
/// Whether the window system's input reaches the OS windows the runtime hosts beside the root (a panel floated into
/// its own window). eframe gives the host only the root's raw input (`App::raw_input_hook`), so the host applies its
/// policy to the root there and gives it here for the rest.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum WindowInput {
/// The window system's input reaches every hosted window.
#[default]
Live,
/// An agent-driven session: a hosted window's events, hovered files and dropped files are dropped before any
/// stage reads them, so only the runtime's injected input reaches it. Its window facts (size, focus, close
/// requests) stay.
Dropped,
}
impl FrameInput {
/// A frame with `root` and no host.
pub fn new(root: RootEnv) -> Self {
FrameInput { root, commands: CommandInput::new(), host: None, latched: Mods::NONE }
FrameInput { root, commands: CommandInput::new(), host: None, latched: Mods::NONE, window_input: WindowInput::Live }
}
/// Sets whether the window system's input reaches the hosted windows.
pub fn window_input(mut self, window_input: WindowInput) -> Self {
self.window_input = window_input;
self
}
/// Sets the command input.
@@ -416,6 +439,11 @@ pub(crate) fn root_input(ctx: &Context) -> (WheelSpeed, AltCodePages) {
pass_state::with::<FrameState, _>(ctx, |state| state.input.as_ref().map(|input| (input.root.wheel, input.root.alt_codes))).unwrap_or_default()
}
/// The frame's window-input policy; `Live` before the app sets any input.
pub(crate) fn window_input(ctx: &Context) -> WindowInput {
pass_state::with::<FrameState, _>(ctx, |state| state.input.as_ref().map(|input| input.window_input)).unwrap_or_default()
}
/// How far a press may move and still be a click, in points: the app's hit tolerances (`HitSizes::slop`). egui's own
/// click options stay the app's.
pub(crate) fn slop(ctx: &Context) -> f32 {
@@ -664,6 +692,15 @@ pub(crate) fn held_for(ctx: &Context, viewport: ViewportId, frame: u64) -> Vec<e
PerViewport::<ViewportRecord>::with(ctx, viewport, |record| record.held.delivered_in(frame))
}
/// The mode the current frame's root theme resolves to on `ctx`.
fn effective_mode(ctx: &Context) -> Mode {
let root = pass_state::with::<FrameState, _>(ctx, |state| state.input.as_ref().map(|input| input.root.clone()));
match root {
Some(root) => root.effective_mode(ctx),
None => RootEnv::fallback(ctx).effective_mode(ctx),
}
}
/// The input hook: egui runs it before it pushes the viewport, so every step reads only `RawInput` and
/// records keyed by `input.viewport_id`.
pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) {
@@ -675,6 +712,11 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) {
raw_input::prepare(ctx, input);
// H0b: the OS colour scheme egui's integration reports reaches the system reader.
crate::runtime::env::system::input_hook(ctx, &input.events);
// H0d: match egui's font coverage transfer function to the pass's resolved theme mode before egui runs
// `Fonts::begin_pass`, so dark-on-light and light-on-dark text use the right curve even when the app's mode
// differs from the OS's.
let mode = effective_mode(ctx);
style::set_text_color_transfer(ctx, mode);
// From H0 to H3 the events go with the input time each arrived at (`Arrived`): held events keep theirs, and the key
// stage gives each shortcut its own. egui's events are what these stages leave.
let mut events = Arrived::take(input);
+29 -13
View File
@@ -159,6 +159,23 @@ impl Engine {
self.observed.map(|(target, _)| target).filter(|target| target.owner == owner)
}
/// Hands the IME to `owner`. The old owner, if it was composing, keeps its preedit for its adapter and is
/// interrupted. The tracker starts the new owner's context when the end hook observes it.
fn set_owner(&mut self, owner: Option<Id>) {
if self.owner == owner {
return;
}
if self.composing
&& let Some(old) = self.owner
{
self.leaving = Some((old, std::mem::take(&mut self.preedit)));
self.interrupt(old);
}
self.composing = false;
self.edits.clear();
self.owner = owner;
}
/// Ends the composition of `owner` here and has the end hook interrupt the OS composition; its late events are
/// dropped until the reset completes.
fn interrupt(&mut self, owner: Id) {
@@ -203,18 +220,7 @@ pub(crate) fn take_discard(ctx: &Context, viewport: ViewportId) -> bool {
/// The begin hook, after pending focus moves are applied: resolves the owner and turns the queue into edits.
pub(crate) fn begin(ctx: &Context, owner: Option<Id>) {
current(ctx, |engine| {
if engine.owner != owner {
if engine.composing
&& let Some(old) = engine.owner
{
engine.leaving = Some((old, std::mem::take(&mut engine.preedit)));
engine.interrupt(old);
}
engine.composing = false;
engine.edits.clear();
// The tracker starts the new owner's context when the end hook observes it.
engine.owner = owner;
}
engine.set_owner(owner);
for (raw, place) in std::mem::take(&mut engine.queue) {
match raw {
// A completion of an earlier request is stale: the latest request still fences.
@@ -404,9 +410,19 @@ pub(crate) fn end_pass(ctx: &Context) {
let viewport = pass::current_viewport(ctx);
let (frame_nr, pass_nr) = (ctx.cumulative_frame_nr_for(viewport), ctx.cumulative_pass_nr_for(viewport));
let (owner, interrupt, caret, update, published) = with(ctx, viewport, |engine| {
if !std::mem::take(&mut engine.ran) {
let ran = std::mem::take(&mut engine.ran);
if !ran {
engine.edits.clear();
}
// An owner that neither took its edits nor noted its caret was not shown this pass (a replay notes the caret
// again). egui keeps its focus until after this hook, so it loses the IME here: the interrupt goes out in the
// pass it vanished, not at the next begin.
if let Some(owner) = engine.owner
&& !ran
&& engine.caret.is_none_or(|(id, ..)| id != owner)
{
engine.set_owner(None);
}
// The fence has no request the integration can answer: the owner's output asks again.
if engine.stale
&& engine.reset.is_none()
@@ -1244,6 +1244,7 @@ pub(crate) mod guard {
("layout::column_group::Open", "column groups: frames the run opens and closes; reports go through contribute"),
("access::scope::Stack", "label and merge scopes: opened and closed by the run; control minimums go through contribute"),
("layout::body::FillCounts", "fill counts: opened and closed by the body's own measuring sweep"),
("layout::body::ViewFills", "view fills: opened and closed by the memoized view's own run"),
("layout::body::HeldWidths", "held children: opened by the column's own first sweep and closed after its last"),
("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"),
("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"),
+12 -3
View File
@@ -160,14 +160,16 @@ struct Entry {
}
/// What a run that showed a child measured: the extent it took, the key of the content it showed, the room it was
/// offered (`Rect::NOTHING` for a collection row, whose extent its collection reports) and the flow of the body around
/// it (the default for a collection row).
/// offered (`Rect::NOTHING` for a collection row, whose extent its collection reports), the flow of the body around
/// it (the default for a collection row) and the axis that body shares which a memoized view's content filled, which
/// makes the view one of the children that fill the body (`layout::fill_size`).
#[derive(Clone, Copy, Debug)]
pub(crate) struct Measured {
pub(crate) size: Vec2,
pub(crate) key: Key,
pub(crate) room: Rect,
pub(crate) flow: Flow,
pub(crate) fills: Option<craft_behavior::Axis>,
}
/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity, flow and environment,
@@ -457,6 +459,13 @@ pub(crate) fn shown(ctx: &Context, owner: Option<Id>, id: Id, sizing: bool, meas
});
}
/// The axis the content of the memoized view `id` filled in its last run of this kind (`sizing`), else of the other
/// kind: the run of this pass once one ran, else the kept one. `None` before any run showed it.
pub(crate) fn fills(ctx: &Context, id: Id, sizing: bool) -> Option<craft_behavior::Axis> {
let (own, other) = (usize::from(!sizing), usize::from(sizing));
with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.sizes[own].or(entry.sizes[other])).and_then(|measured| measured.fills))
}
/// The extent the child `id` took in the last measuring or real run that showed it (this pass's measuring run once it
/// ran), at whatever room it had; `None` before any run showed it.
pub(crate) fn last_extent(ctx: &Context, id: Id) -> Option<Vec2> {
@@ -740,7 +749,7 @@ pub(crate) fn note_edit(ctx: &Context, key: BindKey) {
pub(crate) fn remember(ctx: &Context, owner: Id, id: Id, size: Vec2) {
write(ctx, id, |store, pass_nr, frame| {
let entry = store.touch(Some(owner), id, frame);
entry.sizes[1] = Some(Measured { size, key: Key::None, room: Rect::NOTHING, flow: Flow::default() });
entry.sizes[1] = Some(Measured { size, key: Key::None, room: Rect::NOTHING, flow: Flow::default(), fills: None });
entry.measured_in = Some(pass_nr);
});
}
+29 -22
View File
@@ -292,7 +292,12 @@ pub(crate) struct TopModal {
pub(crate) struct Persist {
raised: IdMap<u64>,
counter: u64,
modal: bool,
/// The viewport's place in the app's modal stack: the root frame its top live modal layer over the whole window
/// first showed in, as of its last finished pass, or `None` without one. A modal viewport blocks the viewports whose
/// top modal opened in an earlier frame and those with none (`modal_viewport`). Modals that open in the same frame
/// form one level and block none of each other: the screen picker opens a capture window over each monitor in one
/// pass, and each must take its click. When the top modal closes, the one under it keeps its own first frame.
modal: Option<u64>,
/// The layers of the last pass, bottom to top, as `end_pass` handed them to egui.
stack: Vec<Id>,
/// A press the modal drop removed, for the window host to raise the modal's window.
@@ -861,6 +866,7 @@ pub(crate) fn end_pass(ctx: &Context) {
let (current, last_ids, raise) =
with_pass(ctx, |pass| (pass.current.clone(), pass.last.iter().map(|entry| entry.id).collect::<Vec<_>>(), pass.raise.clone()));
let pressed = pointer::frame_raw(ctx).press.map(|press| press.origin);
let now = pass::root_frame_nr(ctx);
let order = with_persist(ctx, viewport, |persist| {
let stamp = |id: Id, persist: &mut Persist| {
persist.counter += 1;
@@ -910,9 +916,9 @@ pub(crate) fn end_pass(ctx: &Context) {
persist.stack.push(member.id);
}
}
persist.modal = current.iter().any(|entry| entry.blocks_window() && !entry.exiting);
persist.top_modal =
current.iter().rev().find(|entry| entry.blocks_window() && !entry.exiting).map(|entry| TopModal { id: entry.id, cover: entry.cover });
let top = current.iter().rev().find(|entry| entry.blocks_window() && !entry.exiting);
persist.modal = top.map(|entry| persist.appeared.get(&entry.id).map_or(now, |(frame, _)| *frame));
persist.top_modal = top.map(|entry| TopModal { id: entry.id, cover: entry.cover });
persist.popup_over_modal = current.iter().filter(|entry| entry.rank == Rank::Popup && !entry.exiting).any(|popup| {
let mut at = popup.parent;
while let Some(parent) = at.and_then(|id| current.iter().find(|entry| entry.id == id)) {
@@ -936,7 +942,6 @@ pub(crate) fn end_pass(ctx: &Context) {
});
areas::set_layer_order(ctx, &order);
// An owner takes a close in the frame after the request at the latest; one nobody took is for a layer that is not shown.
let now = pass::root_frame_nr(ctx);
pass_state::with::<Closes, _>(ctx, |closes| closes.0.retain(|(.., queued, carried)| *carried || queued + 1 >= now));
let top_modal = current.iter().rev().find(|entry| entry.blocks_window() && !entry.exiting);
if let Some(entry) = top_modal.filter(|entry| !entry.window) {
@@ -944,19 +949,15 @@ pub(crate) fn end_pass(ctx: &Context) {
}
let any = {
let here = top_modal.is_some();
here || modal_in_other_viewports(ctx, viewport)
here || modal_elsewhere(ctx, viewport)
};
commands::set_modal_open(ctx, any, viewport, top_modal.map(|entry| entry.id));
}
fn modal_in_other_viewports(ctx: &Context, running: ViewportId) -> bool {
modal_viewport(ctx, running).is_some()
}
/// Whether a modal layer is open in a viewport other than `viewport`: the global open-modal fact the input hook
/// reads (H3).
/// Whether a modal layer in another viewport blocks `viewport` (`modal_viewport`): the app-modal fact the input hook
/// (H3), key ownership and the command state read.
pub(crate) fn modal_elsewhere(ctx: &Context, viewport: ViewportId) -> bool {
modal_in_other_viewports(ctx, viewport)
modal_viewport(ctx, viewport).is_some()
}
/// Records that the input hook dropped a press for `viewport` because a modal is open elsewhere.
@@ -1002,7 +1003,7 @@ pub(crate) fn key_layer(ctx: &Context, scopes: &[Id], below: Option<Id>) -> Laye
(_, None, None) => true,
_ => false,
});
if above || modal_in_other_viewports(ctx, viewport) {
if above || modal_elsewhere(ctx, viewport) {
return LayerKeys::Blocked;
}
inside.map_or(LayerKeys::Window, |entry| LayerKeys::Class(entry.keys))
@@ -1023,22 +1024,28 @@ pub(crate) fn beneath(ctx: &Context, layer: Id) -> (bool, Option<Id>) {
.max_by_key(|(shown, _)| *shown)
.map(|(_, id)| id)
});
(root.is_some() || modal_in_other_viewports(ctx, viewport), root)
(root.is_some() || modal_elsewhere(ctx, viewport), root)
}
/// The live viewports with a modal layer open as of their last finished pass.
fn modal_viewports(ctx: &Context) -> impl Iterator<Item = ViewportId> + '_ {
pass::live_viewports(ctx).into_iter().filter(|viewport| with_persist(ctx, *viewport, |persist| persist.modal))
/// The live viewports with a modal layer open as of their last finished pass, each with its place in the modal stack
/// (`Persist::modal`).
fn modal_viewports(ctx: &Context) -> impl Iterator<Item = (ViewportId, u64)> + '_ {
pass::live_viewports(ctx).into_iter().filter_map(|viewport| with_persist(ctx, viewport, |persist| persist.modal).map(|opened| (viewport, opened)))
}
/// A viewport other than `viewport` that has a modal layer open: the window a blocked press raises.
/// The viewport whose modal layer blocks `viewport`: of the other viewports whose top modal opened in a later frame
/// than `viewport`'s own (any, when it has none), the one that opened last, the window a blocked press raises.
pub(crate) fn modal_viewport(ctx: &Context, viewport: ViewportId) -> Option<ViewportId> {
modal_viewports(ctx).find(|other| *other != viewport)
let own = with_persist(ctx, viewport, |persist| persist.modal);
modal_viewports(ctx)
.filter(|(other, opened)| *other != viewport && own.is_none_or(|own| *opened > own))
.max_by_key(|(_, opened)| *opened)
.map(|(other, _)| other)
}
/// A viewport that has a modal layer open: the window that blocks the app's other windows.
/// The viewport at the top of the modal stack: the window that blocks the app's other windows.
pub(crate) fn app_modal_viewport(ctx: &Context) -> Option<ViewportId> {
modal_viewports(ctx).next()
modal_viewports(ctx).max_by_key(|(_, opened)| *opened).map(|(viewport, _)| viewport)
}
/// Whether a layer of key class `class` that is not fading out was shown last frame and the screen point `at` lies in
@@ -95,6 +95,7 @@ pass_state! {
bar_rules: crate::contract::BarRules,
surface_frames: crate::primitives::SurfaceFrames,
fill_counts: crate::layout::body::FillCounts,
view_fills: crate::layout::body::ViewFills,
held_widths: crate::layout::body::HeldWidths,
first_lines: crate::layout::body::FirstLines,
row_lines: crate::layout::body::RowLines,
+12 -1
View File
@@ -477,9 +477,20 @@ impl WindowHost {
/// The desktop pointer in the coordinates of `viewport`, when it lies inside that window.
pub fn pointer_in(&self, viewport: ViewportId) -> Option<Pos2> {
let desktop = self.desktop_pointer()?;
let inner = PerViewport::<Record>::with(&self.ctx, viewport, |record| record.facts.and_then(|facts| facts.inner))?;
let inner = self.inner_on_desktop(viewport)?;
inner.contains(desktop).then(|| Pos2::ZERO + (desktop - inner.min))
}
/// What a point of `from`'s window adds to land at the same desktop place in `to`'s window, by the inner rects
/// the windows last reported, as [`Self::pointer_in`] maps the desktop pointer.
pub(crate) fn offset_between(&self, from: ViewportId, to: ViewportId) -> Option<Vec2> {
Some(self.inner_on_desktop(from)?.min - self.inner_on_desktop(to)?.min)
}
/// The inner rect of `viewport`'s window on the desktop, as the window last reported it.
fn inner_on_desktop(&self, viewport: ViewportId) -> Option<Rect> {
PerViewport::<Record>::with(&self.ctx, viewport, |record| record.facts.and_then(|facts| facts.inner))
}
}
/// The frame of `viewport`'s window as its chrome and the caption buttons it was opened with tell it, for a window
@@ -509,6 +509,54 @@ fn a_host_canvas_reads_the_clipboard_of_its_edit_set_with_nothing_focused() {
assert!(!clipboard_with_canvas(KeyUse::CANVAS, chord).1.is_empty(), "a canvas without the command: the chord fires the app's Paste");
}
/// Which of the arrow keys, Home and End reached egui's input, one press each, in a window whose host declares a canvas;
/// with `focus_field` the host's text field has the focus; and whether Left moved the field's caret.
fn navigation_keys_with_canvas(focus_field: bool) -> (Vec<Key>, bool) {
const KEYS: [Key; 6] = [Key::ArrowLeft, Key::ArrowRight, Key::ArrowUp, Key::ArrowDown, Key::Home, Key::End];
let canvas = named_id("host canvas");
let reached = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&reached);
let (host, mut base) = host_window();
host.borrow_mut().text = "abc".to_owned();
let mut show = move |ui: &mut Ui| {
seen.borrow_mut().extend(KEYS.into_iter().filter(|key| key_reached(ui.ctx(), *key)));
base(ui);
widget(ui, canvas);
host_canvas(ui.ctx(), canvas, KeyUse::CANVAS);
};
let mut frames = Frames::new();
frames.frame(Vec::new(), &mut show);
if focus_field {
fixture::host_focus(&frames.ctx, field());
frames.frame(Vec::new(), &mut show);
frames.frame(vec![key_press(Key::End, Modifiers::NONE), key_release(Key::End, Modifiers::NONE)], &mut show);
}
reached.borrow_mut().clear();
let caret = |frames: &Frames| {
egui::TextEdit::load_state(&frames.ctx, field()).and_then(|state| state.cursor.char_range()).map(|range| range.primary.index)
};
let at_end = caret(&frames);
let mut moved = false;
for key in KEYS {
press_key(&mut frames, &mut show, key);
if key == Key::ArrowLeft {
moved = caret(&frames) != at_end;
}
}
let mut reached = reached.take();
reached.dedup();
(reached, moved)
}
#[trial]
fn a_host_canvas_leaves_navigation_keys_in_egui_for_the_app_s_widget() {
const KEYS: [Key; 6] = [Key::ArrowLeft, Key::ArrowRight, Key::ArrowUp, Key::ArrowDown, Key::Home, Key::End];
let (reached, caret) = navigation_keys_with_canvas(true);
assert_eq!(reached, KEYS, "a focused app field reads the arrows, Home and End from egui");
assert!(caret, "the field's caret moved left from the end");
assert_eq!(navigation_keys_with_canvas(false).0, KEYS, "with nothing focused, the host canvas's own keys stay in egui");
}
/// A clipboard with a picture and no text sends a paste with no text: it fires the app's Paste as the chord does, and
/// `textless_paste` reads it in that pass only.
#[trial]
@@ -58,3 +58,89 @@ fn a_memoized_row_unit_replays_after_the_rows_counting_call() {
let calls = of_view(last_frame_memo_runs(&frames.ctx));
assert!(calls.iter().all(|run| *run == MemoRun::Replayed), "the next frame replays the view in every call: {calls:?}");
}
thread_local! {
/// The rect the fill panel of a `Filled` view took in its last run.
static FILLED: RefCell<Seen> = RefCell::default();
}
/// A view whose content is one panel that fills the main axis of the body around it (`axis`: 0 the width, 1 the height).
#[derive(MemoProps)]
struct Filled {
axis: u8,
}
fn filled(props: &mut Filled, ui: &mut Ui) {
fill_panel(ui, props.axis);
}
/// The panel that fills `axis`, holding one probe.
fn fill_panel(ui: &mut Ui, axis: u8) {
let sizing = if axis == 0 { Sizing::FillWidth } else { Sizing::FillHeight };
FILLED.with(|seen| {
Panel::new().seen(seen).sizing(sizing).id_salt("fill").show(ui, |ui, _| {
let inner = RefCell::new(Seen::default());
Probe::new(&inner).id_salt("inner").show(ui);
});
});
}
/// The rects of the fill panel and the probes before and after it in a body along `axis` (0 a row, 1 a stack) given its
/// room, the panel shown through a memoized view when `memo`, after the frames settle; and how the view took part in
/// the calls of one more frame.
fn shared_body(axis: u8, memo: bool) -> ([Rect; 3], Vec<MemoRun>) {
let (before, after) = (RefCell::new(Seen::default()), RefCell::new(Seen::default()));
let mut frames = Frames::new();
let (layout, room) = if axis == 0 { (BodyLayout::row(), Vec2::new(400.0, 40.0)) } else { (BodyLayout::stack(), Vec2::new(200.0, 300.0)) };
let frame = |frames: &mut Frames| {
frames.frame(vec![], |ui| {
in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), room), |ui| {
Panel::new().layout(layout.clone()).sizing(Sizing::Fill).id_salt("body").show(ui, |ui, _| {
Probe::new(&before).id_salt("before").show(ui);
if memo {
let _ = MemoView::new("view", Filled { axis }, filled).show(ui);
} else {
fill_panel(ui, axis);
}
Probe::new(&after).id_salt("after").show(ui);
});
});
});
};
for _ in 0..30 {
frame(&mut frames);
}
frame(&mut frames);
let runs = last_frame_memo_runs(&frames.ctx).into_iter().filter(|(name, _, _)| name.contains("Filled")).map(|(_, _, run)| run).collect();
([before.borrow().rect, FILLED.with(|seen| seen.borrow().rect), after.borrow().rect], runs)
}
/// A memoized view whose content fills the width of the row around it is one of the children that fill the row, as the
/// content shown without the view is: it takes the row's free width and the probe after it keeps its place at the row's
/// end. With nothing changed every call of a frame replays the view.
#[trial]
fn a_memoized_view_whose_content_fills_the_row_takes_its_free_width() {
let (direct, _) = shared_body(0, false);
let (memo, runs) = shared_body(0, true);
let [before, fill, after] = memo;
assert!(fill.left() >= before.right() && after.left() >= fill.right(), "the view lies between the probes: {memo:?}");
for (shown, alone) in memo.iter().zip(direct) {
assert!(shown.min.distance(alone.min) < 0.5 && shown.max.distance(alone.max) < 0.5, "as without the view: {memo:?} and {direct:?}");
}
assert!(!runs.is_empty() && runs.iter().all(|run| *run == MemoRun::Replayed), "an idle frame replays the view in every call: {runs:?}");
}
/// A memoized view whose content fills the height of the stack around it takes its share of the stack's height, as the
/// content shown without the view does: the probe after it stays inside the stack. With nothing changed every call of a
/// frame replays the view.
#[trial]
fn a_memoized_view_whose_content_fills_the_stack_takes_its_share_of_the_height() {
let (direct, _) = shared_body(1, false);
let (memo, runs) = shared_body(1, true);
let [before, fill, after] = memo;
assert!(fill.top() >= before.bottom() && after.top() >= fill.bottom(), "the view lies between the probes: {memo:?}");
for (shown, alone) in memo.iter().zip(direct) {
assert!(shown.min.distance(alone.min) < 0.5 && shown.max.distance(alone.max) < 0.5, "as without the view: {memo:?} and {direct:?}");
}
assert!(!runs.is_empty() && runs.iter().all(|run| *run == MemoRun::Replayed), "an idle frame replays the view in every call: {runs:?}");
}
@@ -209,6 +209,41 @@ fn a_tool_icon_rides_below_right_of_its_pointer() {
}
}
/// An arrow with a tool icon keeps ink on its hotspot (the arrow's tip), and a badge lands below right of the icon: the
/// marks reach no farther left or up than without it, and farther right (photocraft#16671).
#[trial]
fn a_badged_tool_pointer_keeps_its_tip_on_the_hotspot_and_the_badge_below_right() {
fn reach(image: &CustomCursorImage) -> [i32; 4] {
let (side, [hx, hy]) = (i32::from(image.size[0]), image.hotspot.map(i32::from));
let mut reach = [0; 4];
for (i, px) in image.rgba.chunks(4).enumerate() {
if px[3] > 0 {
let (dx, dy) = (i as i32 % side - hx, i as i32 / side - hy);
reach = [reach[0].max(-dx), reach[1].max(-dy), reach[2].max(dx), reach[3].max(dy)];
}
}
reach
}
for scale in [1.0, 1.25, 2.0] {
let mut frames = frames(linux(), scale);
let plain = painted(&mut frames, PaintedCursor::pointer_tool(PointerGlyph::Arrow, IconId::new("lasso"))).image.unwrap();
let [hx, hy] = plain.hotspot.map(i32::from);
assert!(pixel(&plain, hx, hy)[3] > 0, "{scale}: the arrow's tip is on the hotspot");
for badge in [CursorBadge::Add, CursorBadge::Subtract, CursorBadge::Intersect] {
let badged = PaintedCursor::pointer_tool_badged(PointerGlyph::Arrow, IconId::new("lasso"), Some(badge));
let image = painted(&mut frames, badged).image.unwrap();
let [hx, hy] = image.hotspot.map(i32::from);
assert!(pixel(&image, hx, hy)[3] > 0, "{scale} {badge:?}: the arrow's tip is on the hotspot");
let (with, without) = (reach(&image), reach(&plain));
assert_eq!(with[..2], without[..2], "{scale} {badge:?}: nothing reaches farther left or up");
// A minus lies on the icon's bottom edge, so only the plus and the cross reach lower.
assert!(with[2] > without[2] && with[3] >= without[3], "{scale} {badge:?}: the badge lies at the icon's lower right");
}
let none = PaintedCursor::pointer_tool_badged(PointerGlyph::Arrow, IconId::new("lasso"), None);
assert_eq!(reach(&painted(&mut frames, none).image.unwrap()), reach(&plain), "{scale}: no badge is the plain pointer");
}
}
/// An unchanged pointer hands the window the same image, so the integration uploads it to the OS once; a new size or
/// scale makes a new one; a frame whose winner is a system cursor, or that asks for nothing, clears it (egui keeps an
/// image until it is replaced).
+235 -6
View File
@@ -3,21 +3,24 @@
//! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows, a
//! palette's level under a modal and its visibility while the main window is minimized, injected keys across a focus
//! loss, non-finite injected points, a repeated injected press, the window that has the keys, a wheel with no known
//! pointer, the placement of a minimized window, the root frame decided again, a held close, and `act`.
//! pointer, the placement of a minimized window, the root frame decided again, a held close, `act`, and a hosted
//! window's Control-click and window-input policy.
use craft_behavior::{Cursor, CursorIcon, PointerButton};
use craft_behavior::{Cursor, CursorIcon, PointerButton, Sense};
use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind};
use craft_keymap::{Key, Mods};
use craft_ui::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, Show as _, ShowContainer as _};
use craft_ui::runtime::InstallSpec;
use craft_ui::runtime::focus::FocusPolicy;
use craft_ui::runtime::windows::{WindowHost, WindowSpec};
use craft_ui::runtime::overlay::CloseReason;
use craft_ui::runtime::windows::{WindowHost, WindowLevel, WindowSpec};
use craft_ui::style::StyleCx;
use craft_ui::testing::pointer::{moved, press, wheel};
use craft_ui::testing::input::key_press;
use craft_ui::testing::pointer::{moved, press, release, wheel};
use craft_ui::testing::windows::{FakeSystem, NoWindows};
use craft_ui::testing::{Fixture, trial};
use craft_ui_test_kit::contract::{PlainStyle, Probe, Seen};
use craft_ui_test_kit::windows::{Out, Windows};
use craft_ui_test_kit::windows::{FilesOver, Out, Windows};
use craft_window::policy::{Decision, Desktop, DesktopKind, Frame, MacInset, Runtime, TitleBarPref};
use craft_window::restore::Store;
use egui::{Event, Pos2, Rect, Response, UserAttentionType, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
@@ -359,7 +362,7 @@ fn a_window_an_app_modal_in_another_window_blocks_takes_no_wheel() {
#[trial]
fn wheel_over_a_modal_never_reaches_a_view_under_it_during_a_drag() {
use craft_behavior::{Sense, WheelTaker};
use craft_behavior::WheelTaker;
use craft_ui::testing::wheel::{register, take};
let windows = Windows::new();
let view = egui::Id::unique("dragging view");
@@ -466,6 +469,107 @@ fn a_blocking_modal_is_raised_when_the_main_window_gains_focus() {
assert!(raised(&frame()), "the main window gained focus: the dialog's window is raised");
}
/// A modal window that opens over a modal in another window comes first in the app's modal stack: the screen picker's
/// capture windows, one per monitor and all opened in one frame, take the click and the Escape that end the pick and
/// block none of each other, while the window of the Color Picker under them stays blocked until they close.
#[trial]
fn modal_windows_opened_over_a_modal_in_another_window_take_input_and_block_it() {
let windows = Windows::new();
let screen = Rect::from_min_size(Pos2::ZERO, Vec2::new(400.0, 300.0));
windows.child_info(ViewportInfo { inner_rect: Some(screen), focused: Some(true), ..ViewportInfo::default() });
let titles = ["monitor 1", "monitor 2"];
let seen = [RefCell::new(Seen::default()), RefCell::new(Seen::default())];
let closed = RefCell::new(Vec::new());
// The capture windows shown, in show order. The trial's renderer hands the child events to the first child pass of
// the frame, so the order picks the window a click goes to.
let frame = |shown: &[usize], root: Vec<Event>, child: Vec<Event>| {
windows.frame(root, child, |ui| {
let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal()));
Modal { common: Common::new(), props }.id_salt("color picker").show(ui, |_, _| {});
for &at in shown {
Capture::new(titles[at], screen, &closed).show(ui, |ui, _| {
Probe::new(&seen[at]).size(Vec2::splat(120.0)).sense(Sense::CLICK).show(ui);
});
}
})
};
let (both, flipped) = ([0, 1], [1, 0]);
let blocked = Some(Cursor::System(CursorIcon::NotAllowed));
for _ in 0..3 {
frame(&[], vec![], vec![]);
}
let mut out = frame(&both, vec![], vec![]);
for _ in 0..3 {
out = frame(&both, vec![], vec![]);
}
let captures = titles.map(|title| builder_titled(&out, title).0);
let at = Pos2::new(50.0, 50.0);
for order in [both, flipped] {
frame(&order, vec![], vec![moved(at)]);
frame(&order, vec![], vec![press(at)]);
frame(&order, vec![], vec![release(at)]);
frame(&order, vec![], vec![]);
}
let clicks: Vec<u32> = seen.iter().map(|seen| seen.borrow().activations).collect();
assert_eq!(clicks, [1, 1], "a click reaches each capture window");
assert_eq!(craft_ui::runtime::cursor::current(&windows.ctx), blocked, "the Color Picker's window is blocked");
let mut sent = frame(&both, vec![moved(at), press(at)], vec![]).commands;
sent.extend(frame(&both, vec![release(at)], vec![]).commands);
assert!(
sent.iter().any(|(id, command)| captures.contains(id) && *command == ViewportCommand::Focus),
"a press in the Color Picker's window raises a capture window: {sent:?}"
);
frame(&both, vec![], vec![key_press(egui::Key::Escape, egui::Modifiers::NONE)]);
frame(&both, vec![], vec![]);
assert_eq!(*closed.borrow(), [CloseReason::Escape], "Escape closes the capture window, which ends the pick");
for _ in 0..3 {
frame(&[], vec![], vec![]);
}
assert_ne!(craft_ui::runtime::cursor::current(&windows.ctx), blocked, "the pick ended: the Color Picker's window takes input again");
}
/// A modal container in an OS window of its own over `over`, as the screen picker's capture windows mount, that adds
/// how it closed to `closed`.
#[derive(craft_ui::contract::Component)]
#[component(container)]
struct Capture<'a> {
#[common]
common: Common,
#[container]
props: ContainerProps,
closed: &'a RefCell<Vec<CloseReason>>,
}
impl<'a> Capture<'a> {
fn new(title: &'static str, over: Rect, closed: &'a RefCell<Vec<CloseReason>>) -> Self {
let mount = Mount::viewport_with(Overlay::modal().placed(over), WindowSpec::dialog().level(WindowLevel::AlwaysOnTop).taskbar(false));
Capture { common: Common::new(), props: ContainerProps::new().mount(mount), closed }.label(title).id_salt(title)
}
}
impl Component for Capture<'_> {
const ROLE: Role = Role::GROUP;
type Style = PlainStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: CaptureStyleKey) -> PlainStyle {
PlainStyle::min(Vec2::new(120.0, 60.0))
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
impl Container for Capture<'_> {
fn closed(&mut self, why: CloseReason) {
self.closed.borrow_mut().push(why);
}
}
/// A container mounted in an OS viewport that opens as `spec`, with a body the trial gives it.
#[derive(craft_ui::contract::Component)]
#[component(container)]
@@ -764,6 +868,45 @@ fn a_content_sized_window_takes_its_content_size_once_it_reported_its_place() {
);
}
/// photocraft#16595: a full-window container in a window of its own keeps the size the window has. Its body takes
/// less than the window (side panels, header and footer are no part of it), and the window was sent that size each
/// frame, so it shrank until it was a pixel wide.
#[trial]
fn a_full_window_viewport_keeps_its_window_size() {
const GIVEN: Vec2 = Vec2::new(1000.0, 700.0);
let windows = Windows::new();
let frame = || {
windows.frame(vec![], vec![], |ui| {
Palette::full_window("Workspace").show(ui, |ui, _| {
ui.allocate_exact_size(Vec2::new(300.0, 200.0), egui::Sense::hover());
});
})
};
let (dialog, _) = builder_titled(&frame(), "Workspace");
let report = |size: Vec2| {
let rect = Rect::from_min_size(Pos2::new(100.0, 100.0), size);
windows.child_info(ViewportInfo {
inner_rect: Some(rect),
outer_rect: Some(rect),
native_pixels_per_point: Some(1.0),
..ViewportInfo::default()
});
};
let sizes_sent = || -> Vec<Vec2> {
(0..6)
.flat_map(|_| frame().commands)
.filter_map(|(id, command)| match command {
ViewportCommand::InnerSize(size) if id == dialog => Some(size),
_ => None,
})
.collect()
};
report(GIVEN);
assert_eq!(sizes_sent(), Vec::<Vec2>::new(), "the workspace's window keeps the size it has");
report(Vec2::new(1200.0, 820.0));
assert_eq!(sizes_sent(), Vec::<Vec2>::new(), "a size the user gives the window is kept too");
}
/// Placing a minimized window below its smallest inner size restores it and lowers that size to the placed one, so the
/// window takes the place it is given.
#[trial]
@@ -1207,3 +1350,89 @@ fn a_title_with_nul_reaches_the_window_without_it() {
assert_eq!(send("Notes.docx"), ["Notes.docx"], "a changed title is sent");
assert_eq!(send("\0Report\0\0 draft.docx\0"), ["Report draft.docx"], "a title changed back is sent again, every NUL dropped");
}
/// What the hosted child window's passes saw: its last pass's pointer, events and OS files, and the clicks since the
/// last reset.
#[derive(Clone, Copy, Debug, Default)]
struct ChildSeen {
pointer: bool,
events: usize,
files: usize,
primary: bool,
secondary: bool,
}
/// One frame of a root window that hosts the child window as an OS window with a 200-point click area at its origin:
/// `root` events go to the root, `events` and `dropped` files to the child. Returns whether the root knows the pointer.
fn hosted_frame(windows: &Windows, root: Vec<Event>, events: Vec<Event>, dropped: Vec<String>, seen: &Cell<ChildSeen>) -> bool {
let root_pointer = Cell::new(false);
windows.frame_with_files(root, events, FilesOver::Child, Vec::new(), dropped, |ui| {
root_pointer.set(ui.ctx().input(|input| input.pointer.latest_pos().is_some()));
ui.ctx().show_viewport_immediate(child(), ViewportBuilder::default(), |cui, _| {
let area = cui.allocate_rect(Rect::from_min_size(Pos2::ZERO, Vec2::splat(200.0)), egui::Sense::click());
let (pointer, events, files) = cui.ctx().input(|input| {
(input.pointer.latest_pos().is_some(), input.events.len(), input.raw.hovered_files.len() + input.raw.dropped_files.len())
});
let was = seen.get();
seen.set(ChildSeen {
pointer,
events,
files,
primary: was.primary || area.clicked(),
secondary: was.secondary || area.secondary_clicked(),
});
});
});
root_pointer.get()
}
/// A panel floated into its own OS window gets a macOS Control+Click as a secondary click, as the main window does:
/// the Control-click mapping runs on every hosted window's input, which eframe's `raw_input_hook` never sees.
#[trial]
fn a_control_click_in_a_hosted_window_is_a_secondary_click_on_macos() {
let shell = ShellInfo::default().os(Os::Mac).caps(Caps::native(Os::Mac));
let windows = Windows::with(InstallSpec::new(shell, Arc::new(FakeSystem::new())));
let seen = Cell::new(ChildSeen::default());
let at = Pos2::new(50.0, 50.0);
let control = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::CTRL };
hosted_frame(&windows, vec![], vec![], vec![], &seen);
hosted_frame(&windows, vec![], vec![moved(at)], vec![], &seen);
hosted_frame(&windows, vec![], vec![control(true)], vec![], &seen);
hosted_frame(&windows, vec![], vec![control(false)], vec![], &seen);
hosted_frame(&windows, vec![], vec![], vec![], &seen);
assert!(seen.get().secondary && !seen.get().primary, "the Control+Click is a secondary click there: {:?}", seen.get());
}
/// `WindowInput::Dropped` (an agent-driven session): a hosted window's own events and OS files reach none of its
/// passes, while the root's input stays the host's and injected input still reaches the hosted window. Under `Live`
/// the same input reaches it.
#[trial]
fn dropped_window_input_leaves_a_hosted_window_only_injected_input() {
use craft_ui::runtime::frame::WindowInput;
let at = Pos2::new(50.0, 50.0);
for policy in [WindowInput::Live, WindowInput::Dropped] {
let windows = Windows::new();
windows.window_input(policy);
let seen = Cell::new(ChildSeen::default());
hosted_frame(&windows, vec![], vec![], vec![], &seen);
let root_pointer = hosted_frame(&windows, vec![moved(at)], vec![moved(at)], vec!["clip.mov".to_owned()], &seen);
assert!(root_pointer, "{policy:?}: the root's input is the host's");
let after_move = seen.get();
hosted_frame(&windows, vec![], vec![press(at)], vec![], &seen);
hosted_frame(&windows, vec![], vec![release(at)], vec![], &seen);
hosted_frame(&windows, vec![], vec![], vec![], &seen);
let live = policy == WindowInput::Live;
assert_eq!(after_move.pointer, live, "{policy:?}: the window's pointer move {after_move:?}");
assert_eq!(after_move.events > 0, live, "{policy:?}: the window's events {after_move:?}");
assert_eq!(after_move.files > 0, live, "{policy:?}: the files dropped on the window {after_move:?}");
assert_eq!(seen.get().primary, live, "{policy:?}: the window's own click {:?}", seen.get());
seen.set(ChildSeen::default());
let host = WindowHost::of(&windows.ctx);
host.inject_click(child(), Pos2::new(60.0, 60.0), PointerButton::Primary, 1, Mods::NONE, false);
for _ in 0..8 {
hosted_frame(&windows, vec![], vec![], vec![], &seen);
}
assert!(seen.get().primary, "{policy:?}: the injected click reaches the window: {:?}", seen.get());
}
}
@@ -96,3 +96,48 @@ fn a_reported_text_scale_reaches_the_systems_text_scale_and_raises_the_generatio
report_os_text_scale(&frames.ctx, None);
assert_eq!(system_text_scale(&frames.ctx), None);
}
/// egui's font coverage transfer function follows the pass's resolved theme mode before `Fonts::begin_pass`, so
/// dark-on-light text never renders with the dark-mode curve (or vice versa) when the app's mode differs from the
/// OS's, and single-mode themes keep their own variant's curve.
#[trial]
fn egui_font_transfer_function_follows_the_resolved_theme_mode() {
use craft_theme::ThemeId;
use egui::epaint::FontColorTransferFunction;
let mut frames = Frames::new();
let mut transfer = None;
// Light app on a dark OS must use the light-mode transfer function on the same pass.
frames.root(RootEnv::new().mode(ModeChoice::Light));
frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Dark)], |ui| {
transfer = Some(ui.visuals().text_options.color_transfer_function);
});
assert_eq!(transfer, Some(FontColorTransferFunction::LIGHT_MODE_DEFAULT));
// Dark app on a light OS must use the dark-mode transfer function on the same pass.
frames.root(RootEnv::new().mode(ModeChoice::Dark));
frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Light)], |ui| {
transfer = Some(ui.visuals().text_options.color_transfer_function);
});
assert_eq!(transfer, Some(FontColorTransferFunction::DARK_MODE_DEFAULT));
// System mode tracks OS theme changes immediately.
frames.root(RootEnv::new().mode(ModeChoice::System));
frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Dark)], |ui| {
transfer = Some(ui.visuals().text_options.color_transfer_function);
});
assert_eq!(transfer, Some(FontColorTransferFunction::DARK_MODE_DEFAULT));
frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Light)], |ui| {
transfer = Some(ui.visuals().text_options.color_transfer_function);
});
assert_eq!(transfer, Some(FontColorTransferFunction::LIGHT_MODE_DEFAULT));
// A light-only theme keeps the light-mode transfer function even when dark mode is requested.
let classic = ThemeId::parse("craft.classic").expect("classic theme id");
frames.root(RootEnv::new().theme(classic).mode(ModeChoice::Dark));
frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Dark)], |ui| {
transfer = Some(ui.visuals().text_options.color_transfer_function);
});
assert_eq!(transfer, Some(FontColorTransferFunction::LIGHT_MODE_DEFAULT));
}
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff. Show more