Merge remote-tracking branch 'upstream/next' into next-lint-picker

# Conflicts:
#	crates/automation/src/client_tests.rs
#	crates/ui-panels/src/docking/dock_column.rs
This commit is contained in:
aiongg
2026-11-24 18:17:38 +00:00
41 changed files with 1178 additions and 117 deletions
+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 -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();
+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
}
+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,
@@ -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);
@@ -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;
@@ -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)))
}
+1
View File
@@ -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;
+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),
@@ -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) {
@@ -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)]
+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) {
+29 -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 {
+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()
@@ -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]
@@ -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).
+128 -2
View File
@@ -3,7 +3,8 @@
//! 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, Sense};
use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind};
@@ -19,7 +20,7 @@ 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};
@@ -867,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]
@@ -1310,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());
}
}
@@ -542,6 +542,32 @@ fn an_owner_change_mid_composition_interrupts_it_and_drops_its_late_input() {
);
}
/// An editor that stops being shown while it composes is interrupted in the pass it vanished in. egui keeps its focus
/// until the end of that pass, so waiting for the owner change at the next begin interrupted it a frame late. Guards
/// against the interrupt depending on a second pass of the frame.
#[trial]
fn an_editor_that_vanishes_while_composing_is_interrupted_in_that_pass() {
let log = RefCell::new(Vec::new());
let shown = Cell::new(true);
let mut ui = |ui: &mut egui::Ui| {
if shown.get() {
Probe::new(&log, true).label("Source").id_salt("code").show_at(ui, AT);
}
};
let mut frames = Frames::new();
click(&mut frames, AT.center(), &mut ui);
frames.frame(vec![preedit("k")], &mut ui);
assert!(matches!(log.take().as_slice(), [EditorInput::Preedit { .. }]), "the editor composes");
shown.set(false);
let passes = frames.frame(Vec::new(), &mut ui);
let seen = frames.ime().cloned();
assert!(seen.as_ref().is_some_and(|ime| ime.interrupt && ime.reset.is_some()), "the pass the editor vanished in interrupts it: {seen:?}");
assert_eq!(passes, 1, "the interrupt needs no second pass");
frames.frame(Vec::new(), &mut ui);
assert!(frames.ime().is_none(), "with the editor gone, no one owns the IME: {:?}", frames.ime());
}
/// An editor losing focus while it composes asks the system once to discard the marked text: later frames and a retired
/// request asked again add no discard.
#[trial]
+19 -3
View File
@@ -6,10 +6,10 @@
//! user did; the dock decides what a drop changes.
use super::divider::{self, Divider, Drag};
use super::{CardInset, DockSizes, DockSpot, DockTargets, DockWords, DragUnit, PanelKey, PanelSpec, Splitter};
use super::{CardInset, DividerKind, DockSizes, DockSpot, DockTargets, DockWords, DragUnit, PanelKey, PanelSpec, Splitter};
use crate::contract::{
Access, BodyCx, Common, Component, Container, ContainerProps, Cx, NoValue, Outcome, Pad, PaintUi, PartsCx, Props as _, Role, ShowContainer as _,
Sizing, WordSetCx as _,
Access, BodyCx, Common, Component, Container, ContainerProps, Cx, NoValue, Outcome, Pad, PaintUi, PartsCx, Pointer as _, Props as _, Role,
ShowContainer as _, Sizing, WordSetCx as _,
};
use crate::menu::GroupItem;
use crate::runtime::env::Label;
@@ -139,6 +139,9 @@ pub struct DockColumnOutput<P> {
pub resized: Vec<(P, f32)>,
/// The width the user gave the column on its inner edge this pass.
pub width: Option<f32>,
/// The dividers drawn this pass: between each two open groups and on the inner edge, each with the rect of its
/// handle and the id of the handle's accessibility node.
pub dividers: Vec<(DividerKind<P>, Rect, Id)>,
}
impl<P> Outcome for DockColumnOutput<P> {
@@ -563,7 +566,20 @@ impl<P: Value + Debug + Hash + 'static> Component for DockColumn<'_, P> {
}
fn finish(self, cx: Cx<'_, Self>) -> DockColumnOutput<P> {
let node = |part| crate::runtime::access::sub_node_id(cx.core.id, part);
let mut dividers = Vec::new();
for pair in self.laid.as_ref().map_or(&[][..], |plan| &plan.open[..]).windows(2) {
let part = DIVIDER.at(pair[0] as u64);
if let (Some(shown), Some(anchor)) = (cx.part_if_declared(part), self.anchor(pair[0])) {
dividers.push((DividerKind::Groups(anchor.clone()), shown.rect, node(part)));
}
}
let edge = EDGE.at(0);
if let (Some(shown), Some(first)) = (cx.part_if_declared(edge), self.anchor(0)) {
dividers.push((DividerKind::ColumnEdge(first.clone()), shown.rect, node(edge)));
}
DockColumnOutput {
dividers,
response: cx.response.clone(),
placed: cx.rect,
iconic: self.collapse.then_some(true),
+12 -1
View File
@@ -23,7 +23,7 @@ use crate::primitives::IconSpec;
use crate::runtime::drag::OsFile;
use crate::runtime::env::{Env, Label};
use crate::runtime::overlay::CloseReason;
use crate::runtime::windows::WindowSpec;
use crate::runtime::windows::{ResizeEdge, WindowSpec};
use crate::sections::{HeaderAction, HeaderStrength, MenuRows, TitleRow};
use crate::style::{ComponentStyle, StyleCx, SurfaceKind, UiTokens};
use craft_behavior::dock::DockEdge;
@@ -194,6 +194,11 @@ pub struct FloatingGroupOutput {
pub collapsed_width: Option<f32>,
/// The files dropped on the group's window that no target there took.
pub files: Vec<OsFile>,
/// The band the group is moved by this pass, with the id of its accessibility node; `None` when it has none.
pub grip: Option<(Rect, Id)>,
/// The grips the group is resized by this pass, each with the edge or corner it moves and the id of its
/// accessibility node; none while it does not resize (minimized).
pub resize: Vec<(ResizeEdge, Rect, Id)>,
}
impl Outcome for FloatingGroupOutput {
@@ -321,6 +326,10 @@ impl<'a> FloatingGroup<'a> {
.pad(Pad::None)
.sizing(Sizing::Content)
.header(HeaderRegion::new().band(DragBand::Move).rule(true));
let props = match <DockWords as craft_i18n::WordSet>::word("floatingGroup.resize") {
Some(word) => props.resize_name(Label::from(word)),
None => props,
};
FloatingGroup {
common: Common::new(),
props,
@@ -553,6 +562,8 @@ impl Component for FloatingGroup<'_> {
iconic,
collapsed_width: self.collapsed_width,
files: self.files,
grip: cx.move_band(),
resize: cx.resize_grips(),
};
native::raise(&cx.core.ctx, &output);
native::fade(&cx.core.ctx, &output);
+42 -8
View File
@@ -18,7 +18,7 @@ use crate::menu::{GroupItem, Menu, PanelMenu, PanelRow};
use crate::primitives::PaintShape;
use crate::runtime::commands::{self, CommandSet as _, CommandState, Commands as _};
use crate::runtime::env::Label;
use crate::runtime::focus::{self, FocusTarget};
use crate::runtime::focus::{self, FocusRequest, FocusTarget};
use crate::runtime::memory::sub;
use crate::sections::FooterBar;
use crate::style::{ComponentStyle, Corners, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind, TypeRole};
@@ -292,6 +292,11 @@ pub struct DockGroupOutput {
/// The host may add the size
/// the dragged unit floats at with `drag::amend` in this pass.
pub drag_started: bool,
/// The tabs the strip shows this pass, each with its rect and the id of its accessibility node; none for a
/// [`titled`](DockGroup::titled) group.
pub tabs: Vec<(PanelKey, Rect, Id)>,
/// The band the group is dragged by this pass, with the id of its accessibility node.
pub grip: Option<(Rect, Id)>,
}
impl Outcome for DockGroupOutput {
@@ -324,6 +329,7 @@ struct Reported {
drag_started: bool,
/// A drag started on the strip's empty room, which `finish` starts as a drag of the group.
empty_drag: bool,
tabs: Vec<(PanelKey, Rect, Id)>,
}
/// A group of panels: a header of tab strip and panel menu button, dragged by its empty part, over the active panel's
@@ -363,6 +369,8 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> {
/// single titled panel does: the panels are shown from a rail, not by tabs.
#[prop(flag)]
titled: bool,
/// The tab row takes key focus in this pass: [`take_focus`](DockGroup::take_focus).
take_focus: bool,
/// The dock whose drop registry the group's spots go to.
#[prop]
dock: Option<Id>,
@@ -416,6 +424,7 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup<
wheel_selects_tabs: false,
tab_look: PanelTabLook::Plain,
titled: false,
take_focus: false,
dock: None,
zones: ZoneRule::Fraction,
in_window: false,
@@ -440,6 +449,14 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup<
self
}
/// The group takes key focus in this pass, as a click on its tabs gives it: its tab row's stop takes it while the
/// row runs, so the keys of the next pass route through the group; a titled header, which has no tab row, focuses
/// its drag band. A request of the pass.
#[must_use]
pub fn take_focus(self) -> Self {
DockGroup { take_focus: true, ..self }
}
/// Whether the panel menu button shows: it is asked for and the group has a menu.
fn shows_menu_button(&self) -> bool {
self.panel_menu_shown && self.menu.is_some()
@@ -559,6 +576,10 @@ impl<P: Clone + PartialEq + Debug + Hash + Send + Sync + 'static> Component for
popup.open(cx);
}
}
// A titled header has no tab row: its drag band is the group's stop.
if self.take_focus && self.titled && cx.part_if_declared(GRIP).is_some() {
focus::request(&cx.core.ctx, FocusTarget::Part(cx.core.id, GRIP.into()));
}
if let Some(grip) = cx.part_if_declared(GRIP).map(|grip| grip.press) {
self.reported.toggle_minimized |= grip.double_pressed();
if self.movable && matches!(grip.phase, PressPhase::DragStart { .. }) {
@@ -592,8 +613,9 @@ impl<P: Clone + PartialEq + Debug + Hash + Send + Sync + 'static> Component for
if let Some(request) = &self.reported.menu {
cx.core.memory.shown::<MenuAsked>(sub(cx.core.id, MENU_ASKED)).0 = Some(request.at);
}
let Reported { picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started, .. } = self.reported;
DockGroupOutput { response: cx.response.clone(), picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started }
let grip = cx.part_if_declared(GRIP).map(|grip| (grip.rect, crate::runtime::access::sub_node_id(cx.core.id, GRIP.into())));
let Reported { picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started, tabs, .. } = self.reported;
DockGroupOutput { response: cx.response.clone(), picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started, tabs, grip }
}
}
@@ -683,6 +705,7 @@ impl<P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> Container for
closable: self.closable,
wheel_selects: self.wheel_selects_tabs,
look: self.tab_look,
take_focus: self.take_focus,
dock: self.dock,
sent: Outbox::new(&mut sent),
};
@@ -693,8 +716,11 @@ impl<P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> Container for
.inner;
self.extra = extra;
// A press on the group's empty body focuses its panel, as in Photoshop.
if surface_pressed && let Some(strip) = strip {
focus::request(ui.ctx(), FocusTarget::Id(strip));
if surface_pressed && let Some((strip, _)) = &strip {
focus::request(ui.ctx(), FocusTarget::Id(*strip));
}
if let Some((strip, tabs)) = &strip {
self.reported.tabs = tabs.iter().map(|(key, rect)| (*key, *rect, crate::contract::item_node(*strip, key))).collect();
}
let size = self.size;
let reported = &mut self.reported;
@@ -758,6 +784,9 @@ struct TabRow<'a, P> {
closable: bool,
wheel_selects: bool,
look: PanelTabLook,
/// The strip takes key focus in this pass (`DockGroup::take_focus`): in the key, so the row runs and the strip
/// takes it while it runs.
take_focus: bool,
dock: Option<Id>,
sent: Outbox<'a, TabEvent>,
}
@@ -773,8 +802,9 @@ fn tab_marks(ctx: &egui::Context, panels: &[PanelTitle]) -> Vec<(PanelKey, Optio
.collect()
}
/// A group's tab strip with its tab insertion spots. Returns the strip's id.
fn tab_row<P: Clone + PartialEq + Debug + Hash + Send + Sync + 'static>(row: &mut TabRow<'_, P>, ui: &mut Ui) -> Id {
/// A group's tab strip with its tab insertion spots. Returns the strip's id and the rect of each tab it shows, which a
/// replay returns again, moved with the row.
fn tab_row<P: Clone + PartialEq + Debug + Hash + Send + Sync + 'static>(row: &mut TabRow<'_, P>, ui: &mut Ui) -> (Id, Vec<(PanelKey, Rect)>) {
let env = crate::runtime::env::Env::of(ui);
let name = Label::from(env.words::<DockWords>().panels.as_str().to_owned());
let rtl = env.direction.is_rtl();
@@ -797,6 +827,10 @@ fn tab_row<P: Clone + PartialEq + Debug + Hash + Send + Sync + 'static>(row: &mu
if row.wheel_selects {
strip = strip.wheel_selects();
}
// The strip takes the focus while it runs, so it runs focused and the keys of the next pass route through it.
if row.take_focus {
strip = strip.request_focus(FocusRequest::Take);
}
let marks = &row.marks;
let strip = strip.show_items(ui, &source, &mut |key, _| {
let panel = panels.iter().find(|panel| &panel.key == key);
@@ -843,7 +877,7 @@ fn tab_row<P: Clone + PartialEq + Debug + Hash + Send + Sync + 'static>(row: &mu
if strip.empty_double {
row.sent.send(TabEvent::EmptyDouble);
}
strip.response.response.id
(strip.response.response.id, strip.tab_rects)
}
/// Registers the tab insertion spots of a group: the half of each shown tab nearer the start edge inserts before
+34 -4
View File
@@ -15,6 +15,7 @@ pub(crate) mod floating;
mod panels;
mod placed;
pub(crate) mod root;
mod sources;
mod spec;
pub(crate) mod splitter;
pub mod stack;
@@ -43,6 +44,7 @@ pub use panels::{DockPanels, PanelSpecs, SpecSource, request_actions};
pub use panels::{close_requests, open_requests};
pub use placed::{Placing, placed_rect, with_area_rules};
pub use root::{DockRoot, DockRootOutput, DockRootStyle};
pub use sources::{DividerKind, DockSource, SourceKind};
pub use spec::{DockGrid, DockHeights, PanelSpec};
pub use splitter::{Splitter, SplitterStyle};
pub use targets::{CardInset, DockSizes, DockSpot, DockTargets, GroupDrag, ZoneRule};
@@ -67,7 +69,7 @@ pub use window_menu::{WindowMenuRows, WindowMenuRowsOutput};
use crate::contract::{
Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, Edit as _, EditResponse, Focus as _, Outcome, Pad, PaintUi,
PartsCx, Props as _, Role, Sizing, WordSetCx as _,
PartsCx, Pointer as _, Props as _, Role, Sizing, WordSetCx as _,
};
use crate::runtime::commands::CommandRef;
use crate::runtime::env::Label;
@@ -104,6 +106,17 @@ impl PanelKey {
}
}
/// A key names a panel: it has no place, so a replay at another place keeps it.
impl crate::runtime::Shift for PanelKey {
fn shifted(&self, _: &egui::RecordShift) -> Self {
*self
}
fn snapped(&self, _: &Self, _: f32) -> Self {
*self
}
}
/// A panel as its group's strip shows it.
#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)]
#[non_exhaustive]
@@ -214,6 +227,9 @@ pub struct SplitAreaStyle {
pub struct SplitAreaOutput<P> {
/// The resize edits of the layout and the area's response.
pub edit: EditResponse<Layout<P>>,
/// The dividers drawn this pass: each split's path from the root (`false` for the first child), the rect of its
/// handle and the id of the handle's accessibility node.
pub dividers: Vec<(Vec<bool>, Rect, egui::Id)>,
}
/// The first body's share of a pair's room when its layout holds none: an even split.
@@ -259,13 +275,15 @@ pub struct SplitArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> {
/// preview", "Resize timeline".
#[prop(into)]
divider_label: Option<Label>,
/// The paths of the splits whose handles `parts` declared this pass, by handle index.
declared: Vec<Vec<bool>>,
}
impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> SplitArea<'a, P> {
/// A split area named `label` over `layout`, sized by `rules`. A mixed layout shows no handles.
pub fn new(label: impl Into<Label>, layout: Bind<'a, Layout<P>>, rules: FrameRules<'a, P>) -> Self {
let props = ContainerProps::new().arena(true).sizing(Sizing::Fill).pad(Pad::None);
SplitArea { common: Common::new(), props, layout, rules, divider_label: None }.label(label)
SplitArea { common: Common::new(), props, layout, rules, divider_label: None, declared: Vec::new() }.label(label)
}
/// A two-body area: `bodies.0` first along `axis` and `bodies.1` after it, with one divider between them. The first
@@ -383,10 +401,12 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Component for SplitAr
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
let Some(layout) = cx.value() else { return };
let (sizes, rtl) = (cx.style.sizes, cx.flow.is_rtl());
for (at, handle) in handles(layout, rect, &sizes, &self.rules, rtl).iter().enumerate() {
let handles = handles(layout, rect, &sizes, &self.rules, rtl);
for (at, handle) in handles.iter().enumerate() {
let divider = divider_of(layout, handle, rect, &sizes, &self.rules, rtl, false);
divider::declare(cx, rect, HANDLE, at as u64, &divider);
}
self.declared = handles.into_iter().map(|handle| handle.path).collect();
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
@@ -455,7 +475,17 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Component for SplitAr
}
fn finish(self, cx: Cx<'_, Self>) -> SplitAreaOutput<P> {
SplitAreaOutput { edit: cx.edit_response() }
let dividers = self
.declared
.into_iter()
.enumerate()
.filter_map(|(at, path)| {
let part = HANDLE.at(at as u64);
let rect = cx.part_if_declared(part)?.rect;
Some((path, rect, crate::runtime::access::sub_node_id(cx.core.id, part)))
})
.collect();
SplitAreaOutput { edit: cx.edit_response(), dividers }
}
}
+56
View File
@@ -0,0 +1,56 @@
//! The places a dock area drew in a pass where a press starts a dock gesture: tabs, group bars, a floating window's
//! grip and resize grips, and the dividers. A host names them for its own automation (an element id per source) and
//! reads which one holds key focus by the source's node id.
use crate::runtime::windows::ResizeEdge;
use egui::{Id, Rect, ViewportId};
/// A place in a dock area where a press starts a dock gesture, as the area drew it this pass.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct DockSource<P> {
/// What the gesture acts on.
pub kind: SourceKind<P>,
/// Where it was drawn: in the area's layer space, or in the OS window's own for a floating window in one.
pub rect: Rect,
/// The OS window it is in: `ViewportId::ROOT` unless it is in a floating window's own OS window.
pub viewport: ViewportId,
/// The id of its accessibility node, which [`focused_node`](crate::runtime::access::focused_node) reports while
/// it holds key focus.
pub id: Id,
}
impl<P> DockSource<P> {
/// `kind` drawn at `rect` in the app window, with the node `id`.
pub fn new(kind: SourceKind<P>, rect: Rect, id: Id) -> Self {
DockSource { kind, rect, viewport: ViewportId::ROOT, id }
}
}
/// What a [`DockSource`] acts on.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum SourceKind<P> {
/// The tab of a panel: a click shows it, a drag moves it.
Tab(P),
/// The bar a group is dragged by, named by the group's first panel.
GroupBar(P),
/// The band a floating window is moved by, named by the window's first panel.
WindowGrip(P),
/// A grip a floating window is resized by, named by the window's first panel, with the edge or corner it moves.
WindowResize(P, ResizeEdge),
/// A divider a drag resizes the panes beside.
Divider(DividerKind<P>),
}
/// Which divider a [`SourceKind::Divider`] is.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum DividerKind<P> {
/// The divider of the docked tree's split at this path from the root (`false` for the first child).
Split(Vec<bool>),
/// The divider under a group of a column, between it and the next open group, named by the group's first panel.
Groups(P),
/// The inner edge of a docked column, named by the column's first panel.
ColumnEdge(P),
}
+62
View File
@@ -160,6 +160,26 @@ fn a_grip_window_keeps_no_band_for_a_title_rule() {
assert!(ruled - grip >= 0.5, "the grip window's body ({grip}) starts above the ruled window's ({ruled})");
}
// A floating window's resize grips are named, so assistive technology and automation address them: each edge and
// corner the window declares is one node.
#[trial]
fn a_floating_window_names_each_resize_grip() {
use craft_ui::contract::Role;
use craft_ui::docking::FloatingGroup;
let mut fixture = Fixture::new(move |ui| {
let group = FloatingGroup::new("Quick tools", Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(120.0, 200.0)));
let _ = group.show_group(ui, |ui, _| {
Button::new("Select").show(ui);
});
});
fixture.settle();
let grips = fixture.by_role(Role::SPLITTER);
assert!(grips.len() >= 4, "a resizable window declares a grip on each edge");
for grip in &grips {
assert_eq!(craft_ui::testing::access::name(fixture.tree(), grip.node), Some("Resize panel window"), "every grip is named");
}
}
// A toolbar's marked grip is a handle (photocraft#16467): the grab cursor over it and grabbing while it is held, as
// the grips of a collapsed column show. An unmarked band and a grip that does not move keep the plain arrow.
#[trial]
@@ -206,3 +226,45 @@ fn a_tab_mark_change_repaints_the_tab_row() {
let cleared = width(&mut fixture);
assert!((cleared - plain).abs() < 0.5, "the tab loses its dot again: {plain} then {cleared}");
}
// A click on an app's own egui widget in a group's body (a raw text field) is the widget's, not a press on the
// group's empty body: the group reads no surface press, so its stop does not take the focus, and the field keeps
// egui's focus and takes typing. A press on the body's empty room still focuses the group's panel.
#[trial]
fn a_click_on_an_app_field_in_the_body_keeps_its_focus() {
use std::cell::RefCell;
let text = Rc::new(RefCell::new(String::new()));
let field = Rc::new(Cell::new(None::<(egui::Id, Rect)>));
let surface = Rc::new(Cell::new(false));
let (typed, shown, pressed) = (Rc::clone(&text), Rc::clone(&field), Rc::clone(&surface));
let panels = vec![PanelTitle::new(PanelKey::new(1), "Color")];
let mut fixture = Fixture::new(move |ui| {
let group = DockGroup::new(1usize, Titles::from_content(panels.clone()), panels[0].key);
let (typed, shown, pressed) = (Rc::clone(&typed), Rc::clone(&shown), Rc::clone(&pressed));
group.show_at(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(300.0, 240.0)), move |ui, cx| {
pressed.set(pressed.get() || cx.surface_pressed());
let response = egui::TextEdit::singleline(&mut *typed.borrow_mut()).desired_width(120.0).show(ui).response;
shown.set(Some((response.id, response.rect)));
});
});
fixture.settle();
let Some((field_id, field_rect)) = field.get() else { panic!("the body shows the app's field") };
let empty = Pos2::new(field_rect.center().x, field_rect.bottom() + 80.0);
// Typing a character at a time with a click before each. The clicks are a second apart, so egui sees no double
// click (which would select the word).
for (clicks, typed) in ["a", "1"].into_iter().enumerate() {
fixture.advance(1.0).click_at(field_rect.center()).settle();
assert!(!surface.get(), "click {clicks} on the field is no press on the group's empty body");
assert_eq!(fixture.focused(), Some(field_id), "click {clicks} leaves egui's focus on the app's field");
fixture.type_text(typed).settle();
}
let on_field = fixture.focused_stop();
assert!(text.borrow().contains("a1"), "the field takes the typing after each click: {:?}", text.borrow());
fixture.click_at(empty).settle();
let group_stop = fixture.focused_stop();
assert!(surface.get(), "a press on the empty body is the group's surface press");
assert!(group_stop.is_some() && fixture.focused() != Some(field_id), "a press on the empty body focuses the group's panel");
assert_ne!(on_field, group_stop, "the clicks on the field left the group's stop unfocused");
}
+100 -18
View File
@@ -13,10 +13,10 @@ use crate::docking::stack::{StackSection, StackSections, section_heights};
use crate::docking::tree::FrameRules;
use crate::docking::{Arrangement, CardInset, close_requests, cross_window, end_replaced_drags, float_drop, native, open_requests};
use crate::docking::{
ColumnArrow, ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene,
DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, GroupGrip,
HidePanels, IconicColumn, IconicMode, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, SplitArea,
Titles, WindowColumn, actions, dock_states, fit_widths, frame, move_actions,
ColumnArrow, ColumnBar, DividerKind, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels,
DockRoot, DockScene, DockSizes, DockSource, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt,
GroupDrag, GroupGrip, HidePanels, IconicColumn, IconicMode, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing,
SourceKind, SpecSource, SplitArea, Titles, WindowColumn, actions, dock_states, fit_widths, frame, move_actions,
};
use crate::layout_components::Stack;
use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow};
@@ -68,7 +68,8 @@ pub struct DockAreaOutput<P> {
pub events: Vec<DockEvent<P>>,
/// The shown panel of the group that holds key focus: focus is on the group or on a control inside it.
pub focused: Option<P>,
/// The panel whose tab the user clicked or picked this pass.
/// The panel whose tab the user clicked or picked this pass; a pick of the host's `DockArea::focus` is not the
/// user's and shows only in `actions`.
pub picked: Option<P>,
/// Why nothing was drawn, when the workspace is invalid.
pub error: Option<InvalidGeometry>,
@@ -85,6 +86,11 @@ pub struct DockAreaOutput<P> {
pub windows: Vec<(P, ViewportId)>,
/// The files dropped on the area's windows this pass, for the host to open.
pub window_files: Vec<drag::OsFile>,
/// Every place the area drew this pass where a press starts a dock gesture: each tab, each group's drag bar, each
/// floating window's grip and resize grips, and each divider, with its rect, its OS window and the id of its
/// accessibility node. Nothing the area did not draw reports: a hidden panel, the groups of a column collapsed to
/// icons, a minimized window's resize grips.
pub sources: Vec<DockSource<P>>,
/// The area's response.
pub response: Response,
}
@@ -107,6 +113,7 @@ impl<P> Outcome for DockAreaOutput<P> {
/// actions the workspace took, divider sizes and window moves included. A given workspace is not written.
/// - Requests: while the pass runs, a body changes the workspace through
/// [`request_actions`](crate::docking::request_actions); the output returns those actions unapplied in `requested`.
/// The host moves key focus to a panel's group with [`focus`](DockArea::focus).
/// - Hiding: [`hide`](DockArea::hide), the shell's panel visibility and [`maximized`](DockArea::maximized) prune
/// what shows; a pruned panel keeps its place for restore.
/// - Drops: the area is the drop target of tab and group drags. Ctrl or Cmd held at the release floats the drop, and
@@ -151,6 +158,13 @@ pub struct DockArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> {
/// nothing.
#[prop(quantity = "panel and grab point")]
continue_move: Option<(P, Vec2)>,
/// Moves key focus to the group that shows the panel and picks its tab, as a click on the tab does: the group's
/// stop takes focus in this pass, and the pick is one of the pass's `actions`. A request of the pass: a host that
/// focuses a panel itself (it opened something in it) sets it for one pass. A panel the area does not show in this
/// pass (hidden, pruned by a maximize, in a closed flyout, or in a group the host's `group_view` draws) takes
/// neither; `DockAreaOutput::focused` tells the host where focus is.
#[prop]
focus: Option<P>,
/// Adds the host's fixed trailing controls to the docked rail containing `panel`. The panel identifies the
/// column as it moves between dock sides. The host draws the controls through [`DockPanels::rail_footer`]; its
/// icons scroll above them when the rail is short. Has no effect in flyout mode or on floating columns.
@@ -183,6 +197,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
locked: false,
flyout: None,
continue_move: None,
focus: None,
rail_footer: None,
top_inset: 0.0,
}
@@ -290,6 +305,8 @@ struct Report<P> {
windows: Vec<(P, ViewportId)>,
/// The files dropped on the floating windows that no target there took.
files: Vec<drag::OsFile>,
/// The gesture sources the parts drew, in the order they showed.
sources: Vec<DockSource<P>>,
}
/// The inputs of the workspace's derived values: the workspace, the panels' specs and the lock.
@@ -316,6 +333,8 @@ struct Scene<'s, P> {
auto_collapse: bool,
/// The panel whose window takes over the held press, with its grab point (`DockArea::continue_move`).
continue_move: Option<(&'s P, Vec2)>,
/// The panel whose group takes key focus in this pass (`DockArea::focus`).
focus: Option<&'s P>,
rtl: bool,
/// The docked places floating panels left, for Dock Panel.
floated: &'s [(P, Location<P>)],
@@ -413,6 +432,7 @@ struct Passed<P> {
columns: Vec<(P, Rect)>,
windows: Vec<(P, ViewportId)>,
files: Vec<drag::OsFile>,
sources: Vec<DockSource<P>>,
}
/// How a group is shown: minimized, whether it is an accordion section (with its open state), and whether it is in
@@ -491,6 +511,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
locked,
mut flyout,
continue_move,
focus,
rail_footer,
top_inset,
} = self;
@@ -550,6 +571,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
maximized: maximized.as_ref(),
auto_collapse,
continue_move: continue_move.as_ref().map(|(panel, grab)| (panel, *grab)),
focus: focus.as_ref(),
sizes,
rtl,
rail_footer: rail_footer.as_ref(),
@@ -569,7 +591,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
passed = Some(result);
});
let requested = close_requests::<P>(&ctx);
let Passed { geometry, actions, events, focused, picked, edit, space, columns, windows, files } = passed.unwrap_or_else(|| Passed {
let Passed { geometry, actions, events, focused, picked, edit, space, columns, windows, files, sources } = passed.unwrap_or_else(|| Passed {
geometry: Vec::new(),
actions: Vec::new(),
events: Vec::new(),
@@ -580,6 +602,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
columns: Vec::new(),
windows: Vec::new(),
files: Vec::new(),
sources: Vec::new(),
});
if shown.output.dropped.is_some() {
cross_window::accept_cross_window(&ctx);
@@ -597,6 +620,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
columns,
windows,
window_files: files,
sources,
response: shown.output.response,
}
}
@@ -655,6 +679,7 @@ struct Input<'i, P> {
maximized: Option<&'i P>,
auto_collapse: bool,
continue_move: Option<(&'i P, Vec2)>,
focus: Option<&'i P>,
sizes: DockSizes,
rtl: bool,
rail_footer: Option<&'i P>,
@@ -689,8 +714,24 @@ fn show_area<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
panels: &mut dyn DockPanels<P>,
mut flyout: Option<&mut Bind<'_, Option<P>>>,
) -> Passed<P> {
let Input { id, ctx, current, config, specs, keys, hide, model, maximized, auto_collapse, continue_move, sizes, rtl, rail_footer, top_inset } =
*input;
let Input {
id,
ctx,
current,
config,
specs,
keys,
hide,
model,
maximized,
auto_collapse,
continue_move,
focus,
sizes,
rtl,
rail_footer,
top_inset,
} = *input;
let shell = body.shell();
let mut memory = body.memory::<AreaMemory<P>>().clone();
let protected = |panel: &P| rights.get(panel).is_some_and(|rights| rights.is_protected());
@@ -712,6 +753,7 @@ fn show_area<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
bounds,
auto_collapse,
continue_move,
focus,
rtl,
floated: current.floated(),
rail_footer,
@@ -729,6 +771,7 @@ fn show_area<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
placed: Vec::new(),
windows: Vec::new(),
files: Vec::new(),
sources: Vec::new(),
},
dock: id,
};
@@ -760,6 +803,9 @@ fn show_area<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
pass.dock(ui, split, DockPlan { edge, columns, rect, flow, open: open.clone() });
}
});
let splits =
area.output.dividers.iter().map(|(path, rect, node)| DockSource::new(SourceKind::Divider(DividerKind::Split(path.clone())), *rect, *node));
pass.report.sources.extend(splits);
let mut edit = area.output.edit.events.map(|edited| {
let mut layout = current.layout().clone();
view.write_back(&edited, &mut layout);
@@ -830,6 +876,7 @@ fn show_area<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
columns: report.placed,
windows: report.windows,
files: report.files,
sources: report.sources,
}
}
@@ -1017,12 +1064,12 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
/// The grip strip on top of a tool rail the host shows itself: the dock's grip marks over a band that drags the
/// group, which floats at `size`, the group's size. A memoized view ([`rail_grip`]) held to the strip, so a frame
/// whose input is elsewhere replays it, as the column bars and the groups' tab rows replay.
fn rail_grip(&mut self, ui: &mut Ui, anchor: &P, shown: &P, strip: Rect, size: Vec2) {
/// whose input is elsewhere replays it, as the column bars and the groups' tab rows replay. Returns the grip's id.
fn rail_grip(&mut self, ui: &mut Ui, anchor: &P, shown: &P, strip: Rect, size: Vec2) -> Option<Id> {
let scene = self.scene;
let label = Label::from(scene.spec(shown).label.as_str().to_owned());
let mut sent = Vec::new();
ui.scope_builder(UiBuilder::new().max_rect(strip), |ui| {
let grip = ui.scope_builder(UiBuilder::new().max_rect(strip), |ui| {
let props = RailGrip {
unit: DragUnit::Group(anchor.clone()),
active: PanelKey::of(shown),
@@ -1031,7 +1078,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
sent: Outbox::new(&mut sent),
};
// Keyed by the rail's group: unique among the rails a dock area shows.
let _ = MemoView::new(("rail grip", PanelKey::of(anchor)), props, rail_grip::<P>).show(ui);
MemoView::new(("rail grip", PanelKey::of(anchor)), props, rail_grip::<P>).show(ui)
});
// The group's size goes on the drag here, outside the view, whose measuring runs see no size; so does the
// press, which a floating rail's window keeps under the pointer when it is dropped on empty room.
@@ -1041,6 +1088,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
drag.press = Some(press);
});
}
grip.inner
}
/// One group, by the host's `group_view` when it takes the group, else as a `DockGroup` over the host's panels:
@@ -1058,6 +1106,8 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
return Some(height + grip);
}
let shown = &members[active];
// The host's focus request, when it names a panel of this group.
let focus = scene.focus.filter(|panel| members.contains(panel));
let words = body.words::<MenuWords>();
let ctx = ui.ctx().clone();
let panels = RefCell::new(&mut *self.panels);
@@ -1148,17 +1198,29 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
let taken = in_room(ui, view, |ui| panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body));
match taken {
Some(_) => None,
None => Some(make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output),
None => {
let group = make(active, look.minimized);
let group = if focus.is_some() { group.take_focus() } else { group };
Some(group.show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output)
}
}
})
.inner;
// A host view took the group: a rail's grip drags the group, as the band of a group's header does.
let Some(output) = output else {
if strip.is_positive() {
self.rail_grip(ui, anchor, shown, strip, rect.size());
if strip.is_positive()
&& let Some(node) = self.rail_grip(ui, anchor, shown, strip, rect.size())
{
self.report.sources.push(DockSource::new(SourceKind::GroupBar(anchor.clone()), strip, node));
}
return None;
};
let tabs =
output.tabs.iter().filter_map(|(key, rect, node)| Some(DockSource::new(SourceKind::Tab(scene.panel(*key)?.clone()), *rect, *node)));
self.report.sources.extend(tabs);
if let Some((rect, node)) = output.grip {
self.report.sources.push(DockSource::new(SourceKind::GroupBar(anchor.clone()), rect, node));
}
// The size `panel` floats at out of this group: the group's width, and the height the group measures at with
// `panel` shown in a floating window's room, so content that fills the body takes that room.
let fitted = |ui: &Ui, panel: &P| {
@@ -1188,10 +1250,14 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
let torn = torn.map(|(panel, pointer)| {
float_drop(&DragUnit::Panel(panel.clone()), scene.space, pointer, Some(fitted(ui, panel)), None, scene.rtl).action
});
let picked = output.picked.and_then(|key| scene.panel(key));
let clicked = output.picked.and_then(|key| scene.panel(key));
if let Some(panel) = clicked {
self.report.picked = Some(panel.clone());
}
// The host's focus request picks its panel's tab as a click does; the user's click of the pass wins.
let picked = clicked.or(focus.filter(|panel| *panel != shown));
if let Some(panel) = picked {
self.report.actions.push(Action::activate(panel.clone()));
self.report.picked = Some(panel.clone());
}
// A tab picked in this pass is the group's shown panel from now on, though this pass drew the one before.
if focus_within(ui.ctx(), output.response.id) {
@@ -1418,6 +1484,8 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
let output = shown.show_groups_at(ui, cell, |group, rect, ui, body| {
self.group_of(ui, body, group, GroupAt::Show(rect), in_window);
});
let dividers = output.dividers.into_iter().map(|(divider, rect, node)| DockSource::new(SourceKind::Divider(divider), rect, node));
self.report.sources.extend(dividers);
let width = output.width.map(|width| width - inset);
ColumnWork { iconic: output.iconic, picked: output.picked, resized: output.resized, width, flyout: None }
};
@@ -1599,6 +1667,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
});
}
let area_dock = std::mem::replace(&mut self.dock, dock);
let drawn = self.report.sources.len();
let shown = group.show_group(ui, |ui, body| {
for (command, state) in states.iter().cloned() {
body.publish(command, state);
@@ -1614,6 +1683,17 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
});
self.dock = area_dock;
let output = shown.output;
// The window's grips, then everything it drew, in the OS window it shows in, if it has one.
let grips = output.grip.map(|(rect, node)| DockSource::new(SourceKind::WindowGrip(anchor.clone()), rect, node));
let resize =
output.resize.iter().map(|(edge, rect, node)| DockSource::new(SourceKind::WindowResize(anchor.clone(), *edge), *rect, *node));
let inside = self.report.sources.split_off(drawn);
self.report.sources.extend(grips.into_iter().chain(resize).chain(inside));
if let Some(viewport) = opening.spec.as_ref().and_then(|_| WindowHost::of(&ctx).viewport_of(output.response.id)) {
for source in &mut self.report.sources[drawn..] {
source.viewport = viewport;
}
}
self.report.files.extend(output.files);
if let Some(dropped) = dropped.into_inner() {
cross_window::accept_cross_window(&ctx);
@@ -1774,7 +1854,8 @@ struct RailGrip<'a, P> {
}
/// A tool rail's grip strip: the dock's grip marks over the view's room, which a drag moves the rail's group by.
fn rail_grip<P: Clone + Hash + Send + Sync + 'static>(props: &mut RailGrip<'_, P>, ui: &mut Ui) {
/// Returns the grip's id.
fn rail_grip<P: Clone + Hash + Send + Sync + 'static>(props: &mut RailGrip<'_, P>, ui: &mut Ui) -> Id {
let strip = ui.max_rect();
let held = GroupGrip::new(props.unit.clone(), props.active)
.ticks(true)
@@ -1787,4 +1868,5 @@ fn rail_grip<P: Clone + Hash + Send + Sync + 'static>(props: &mut RailGrip<'_, P
}
// The grip takes no room in flow; the run covers the strip, so the pointer over it runs it again.
ui.expand_to_include_rect(strip);
held.response.id
}
@@ -0,0 +1,97 @@
//! The host's focus request: `DockArea::focus` moves key focus to the group that shows a panel, as a click on its tab
//! does.
use super::Numbered;
use craft_behavior::dock::{Action, Layout, Node, SplitSize, Workspace};
use craft_behavior::{Axis, PartKey};
use craft_ui::contract::{Bind, BodyCx, Tracked};
use craft_ui::docking::{DockConfig, DockPanels};
use craft_ui::patterns::dock::DockArea;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Ui, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
struct Panels;
impl DockPanels<usize> for Panels {
fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {}
}
/// What one pass of the area reported.
#[derive(Debug)]
struct Seen {
focused: Option<usize>,
picked: Option<usize>,
actions: Vec<Action<usize>>,
}
/// The fixture, the host's focus request for the next pass, and each pass's report.
type TwoGroups = (Fixture, Rc<Cell<Option<usize>>>, Rc<RefCell<Vec<Seen>>>);
/// A dock of group A (panel 0) beside group B (panels 1 and 2, 1 shown) with `config`; the host's focus request for the
/// next pass goes in the cell, and each pass's report is pushed to the list.
fn two_groups(config: DockConfig) -> TwoGroups {
let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), Node::tabs(vec![1, 2], 0));
let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())));
let request = Rc::new(Cell::new(None));
let seen = Rc::new(RefCell::new(Vec::new()));
let (asked, reported, specs) = (Rc::clone(&request), Rc::clone(&seen), Tracked::new(Numbered));
let mut fixture = Fixture::new(move |ui| {
let mut panels = Panels;
let mut area = DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut panels, config.clone());
if let Some(panel) = asked.take() {
area = area.focus(panel);
}
let output = area.show(ui);
reported.borrow_mut().push(Seen { focused: output.focused, picked: output.picked, actions: output.actions });
});
fixture.room(Vec2::new(1200.0, 600.0)).settle();
(fixture, request, seen)
}
/// With the user's focus on group A's tabs, the host's request for panel 2 of group B moves key focus to B's stop (the
/// one a click on B's tabs focuses) and picks 2's tab; a key there reaches B. Guards against a request that picked the
/// tab but left key focus, and so the keys, on the tabs the user clicked last.
#[trial]
fn the_hosts_focus_request_moves_key_focus_to_the_panels_group_and_picks_its_tab() {
let (mut fixture, request, seen) = two_groups(DockConfig::default());
let tab = |fixture: &Fixture, name: &str| fixture.by_label(name).expect("a group's tab");
let b_tab = tab(&fixture, "Panel 1");
fixture.click(&b_tab).idle(1);
let b_stop = fixture.focused_stop().expect("a click on B's tab focuses B's stop");
let a_tab = tab(&fixture, "Panel 0");
fixture.click(&a_tab).idle(1);
assert_ne!(fixture.focused_stop(), Some(b_stop), "a click on A's tab moves focus to A's stop");
assert_eq!(seen.borrow().last().and_then(|seen| seen.focused), Some(0), "A holds the focus");
seen.borrow_mut().clear();
request.set(Some(2));
fixture.idle(2);
assert_eq!(fixture.focused_stop(), Some(b_stop), "the request moves key focus to B's stop");
{
let seen = seen.borrow();
assert!(seen.iter().any(|pass| pass.actions.contains(&Action::activate(2))), "the request picks 2's tab: {seen:?}");
assert!(seen.iter().all(|pass| pass.picked.is_none()), "the host's pick is not the user's: {seen:?}");
assert_eq!(seen.last().and_then(|pass| pass.focused), Some(2), "B holds the focus, with 2 shown: {seen:?}");
}
seen.borrow_mut().clear();
fixture.key(Key::ArrowLeft, Modifiers::NONE).idle(1);
fixture.key(Key::Space, Modifiers::NONE).idle(1);
let picked = seen.borrow().iter().find_map(|pass| pass.picked);
assert!(matches!(picked, Some(1 | 2)), "the keys reach B's tabs, not A's: {picked:?}");
}
/// A titled header has no tab row: the request moves key focus to its drag band, the group's stop, and the group
/// holds the focus. Guards against a request that a titled group dropped.
#[trial]
fn the_hosts_focus_request_focuses_a_titled_groups_drag_band() {
let (mut fixture, request, seen) = two_groups(DockConfig::default().titled_headers(true));
request.set(Some(2));
fixture.idle(2);
let part = fixture.focused_stop().and_then(|(_, part)| part).map(|part| part.key);
assert_eq!(part, Some(PartKey::new("grip")), "the drag band holds key focus");
assert_eq!(seen.borrow().last().and_then(|pass| pass.focused), Some(2), "B holds the focus, with 2 shown");
}
@@ -6,6 +6,7 @@ use craft_ui::testing::style::{tokens, with_cx};
pub(crate) mod render;
pub(crate) mod focus;
pub(crate) mod panel_menu;
pub(crate) mod runs;
@@ -19,6 +20,7 @@ pub(crate) mod floating;
pub(crate) mod floating_area;
pub(crate) mod floating_rail;
pub(crate) mod hidden;
pub(crate) mod sources;
pub(crate) mod columns;
pub(crate) mod dock_back;
@@ -0,0 +1,147 @@
//! The gesture sources a dock area reports (`DockAreaOutput::sources`): one per tab, group bar, window grip and divider
//! it drew, named by what it acts on, and none for what it did not draw.
use super::Numbered;
use craft_behavior::Axis;
use craft_behavior::dock::{Column, DockEdge, Floating, Group, Layout, Node, SplitSize, Workspace};
use craft_ui::contract::{Bind, BodyCx, Tracked};
use craft_ui::docking::{DividerKind, DockConfig, DockPanels, DockSource, HidePanels, PanelKey, SourceKind};
use craft_ui::patterns::dock::DockArea;
use craft_ui::runtime::env::{BodyMode, ShellCx, ShellEntry, WindowKey};
use craft_ui::testing::{Fixture, trial};
use egui::{Pos2, Rect, Ui, Vec2};
use std::cell::RefCell;
use std::collections::{BTreeSet, HashSet};
use std::rc::Rc;
use std::sync::Arc;
/// The start dock's column: a group of two tabs over a group of one.
const UPPER: usize = 1;
const UPPER_TWO: usize = 2;
const LOWER: usize = 3;
/// The middle split: a group of two tabs beside a group of one.
const LEFT: usize = 4;
const LEFT_TWO: usize = 5;
const RIGHT: usize = 6;
/// The end dock's column, collapsed to icons.
const ICONIC: usize = 7;
/// The floating window's panel.
const FLOATING: usize = 8;
struct Bodies;
impl DockPanels<usize> for Bodies {
fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {}
}
/// A start dock whose column holds two groups, a split of two tab groups, an end dock whose column is collapsed to
/// icons, and one floating window.
fn layout() -> Layout<usize> {
let start = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![UPPER, UPPER_TWO], 0), Group::new(vec![LOWER], 0)])]);
let mut collapsed = Column::new(vec![Group::new(vec![ICONIC], 0)]);
collapsed.iconic = true;
let end = Node::dock(DockEdge::End, vec![collapsed]);
let middle = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![LEFT, LEFT_TWO], 0), Node::tabs(vec![RIGHT], 0));
let root = Node::split(Axis::X, SplitSize::Ratio(0.25), start, Node::split(Axis::X, SplitSize::Ratio(0.85), middle, end));
let window = Floating::single(FLOATING as u64, vec![FLOATING], 0, Rect::from_min_size(Pos2::new(420.0, 200.0), Vec2::new(220.0, 180.0)));
Layout::new(Some(root), vec![window])
}
const ROOM: Vec2 = Vec2::new(1000.0, 640.0);
/// A fixture showing the layout under `shell`, keeping only `keep` when it names panels; what the area reported in
/// its last pass goes into the returned cell.
fn fixture(shell: Option<ShellCx>, keep: Option<BTreeSet<usize>>) -> (Fixture, Rc<RefCell<Vec<DockSource<usize>>>>) {
let reported: Rc<RefCell<Vec<DockSource<usize>>>> = Rc::default();
let seen = Rc::clone(&reported);
let mut fixture = Fixture::new(move |ui| {
let mut workspace = Arc::new(Workspace::new(layout()));
let specs = Tracked::new(Numbered);
let kept = Tracked::new(keep.iter().flatten().map(PanelKey::of).collect::<BTreeSet<_>>());
let mut bodies = Bodies;
let mut area = DockArea::new("Sources", Bind::bound(&mut workspace), &specs, &mut bodies, DockConfig::default());
if keep.is_some() {
area = area.hide(HidePanels::Except(&kept));
}
*seen.borrow_mut() = area.show(ui).sources;
});
fixture.room(ROOM);
if let Some(shell) = shell {
fixture.root_value(ShellEntry(Some(shell)));
}
fixture.settle();
(fixture, reported)
}
/// The panel a source names, for a tab, a group bar or a window's grips.
fn named(source: &DockSource<usize>) -> Option<usize> {
match &source.kind {
SourceKind::Tab(panel) | SourceKind::GroupBar(panel) | SourceKind::WindowGrip(panel) | SourceKind::WindowResize(panel, _) => Some(*panel),
SourceKind::Divider(DividerKind::Groups(panel) | DividerKind::ColumnEdge(panel)) => Some(*panel),
_ => None,
}
}
/// The panels named by the sources `pick` takes, in order, with repeats.
fn panels(sources: &[DockSource<usize>], pick: impl Fn(&SourceKind<usize>) -> Option<usize>) -> Vec<usize> {
let mut picked: Vec<usize> = sources.iter().filter_map(|source| pick(&source.kind)).collect();
picked.sort_unstable();
picked
}
#[trial]
fn a_dock_area_reports_one_source_per_tab_bar_grip_and_divider_it_drew_and_the_same_after_an_idle_pass() {
let (mut fixture, reported) = fixture(None, None);
let sources = reported.borrow().clone();
let tabs = panels(&sources, |kind| if let SourceKind::Tab(panel) = kind { Some(*panel) } else { None });
assert_eq!(tabs, vec![UPPER, UPPER_TWO, LOWER, LEFT, LEFT_TWO, RIGHT, FLOATING], "one tab per panel shown in a tab strip: {sources:#?}");
let bars = panels(&sources, |kind| if let SourceKind::GroupBar(panel) = kind { Some(*panel) } else { None });
assert_eq!(bars, vec![UPPER, LOWER, LEFT, RIGHT, FLOATING], "one drag bar per shown group, named by its first panel");
let grips = panels(&sources, |kind| if let SourceKind::WindowGrip(panel) = kind { Some(*panel) } else { None });
assert_eq!(grips, vec![FLOATING], "the floating window's grip, named by its panel");
let edges: Vec<_> =
sources.iter().filter_map(|source| if let SourceKind::WindowResize(FLOATING, edge) = source.kind { Some(edge) } else { None }).collect();
assert!(!edges.is_empty(), "the floating window reports its resize grips");
let distinct = edges.iter().enumerate().all(|(at, edge)| !edges[..at].contains(edge));
assert!(distinct, "each resize grip names its own edge: {edges:?}");
let divider = |kind: DividerKind<usize>| sources.iter().filter(|source| source.kind == SourceKind::Divider(kind.clone())).count();
assert_eq!(divider(DividerKind::Split(vec![true, false])), 1, "the divider of the middle split, by its path");
assert_eq!(divider(DividerKind::Groups(UPPER)), 1, "the divider under the column's upper group");
assert_eq!(divider(DividerKind::ColumnEdge(UPPER)), 1, "the inner edge of the start dock's column");
assert!(sources.iter().all(|source| named(source) != Some(ICONIC)), "a column collapsed to icons reports no tab, bar or divider");
let room = Rect::from_min_size(Pos2::ZERO, ROOM);
for source in &sources {
assert!(source.rect.is_positive() && room.contains_rect(source.rect), "every source lies in the window: {source:?}");
}
let window = sources.iter().find(|source| source.kind == SourceKind::WindowGrip(FLOATING)).map(|source| source.rect);
let tab = sources.iter().find(|source| source.kind == SourceKind::Tab(FLOATING)).map(|source| source.rect);
assert!(window.zip(tab).is_some_and(|(grip, tab)| grip.bottom() <= tab.top() + 0.5), "the window's grip lies above its tab");
let ids: HashSet<_> = sources.iter().map(|source| source.id).collect();
assert_eq!(ids.len(), sources.len(), "every source has its own node id");
fixture.idle(3);
assert_eq!(*reported.borrow(), sources, "an idle pass, which replays the settled parts, reports the same sources");
let left_two = sources.iter().find(|source| source.kind == SourceKind::Tab(LEFT_TWO)).cloned().expect("the tab of the second panel");
fixture.click_at(left_two.rect.center()).settle();
assert_eq!(
craft_ui::runtime::access::focused_node(fixture.ctx()),
Some(left_two.id),
"the clicked tab holds focus under the id its source reports"
);
}
#[trial]
fn a_panel_the_shell_hides_reports_no_source() {
let room = Rect::from_min_size(Pos2::ZERO, ROOM);
let hiding = ShellCx::detached(WindowKey::main(), BodyMode::Normal, room).with_panels_hidden(true);
let keep = BTreeSet::from([UPPER, UPPER_TWO, LOWER, LEFT, LEFT_TWO, ICONIC]);
let (_fixture, reported) = fixture(Some(hiding), Some(keep));
let sources = reported.borrow();
assert!(sources.iter().any(|source| source.kind == SourceKind::Tab(LEFT)), "a kept panel still reports its tab");
for hidden in [RIGHT, FLOATING] {
assert!(sources.iter().all(|source| named(source) != Some(hidden)), "the hidden panel {hidden} reports no tab, bar or grip: {sources:#?}");
}
}
+14 -3
View File
@@ -5,7 +5,7 @@
use craft_host::target::ShellInfo;
use craft_ui::runtime::InstallSpec;
use craft_ui::runtime::env::RootEnv;
use craft_ui::runtime::frame::{FrameInput, set_input};
use craft_ui::runtime::frame::{FrameInput, WindowInput, set_input};
use craft_ui::testing::Frames;
use craft_ui::testing::access::{AccessTree, tree_of};
use craft_ui::testing::windows::FakeSystem;
@@ -281,6 +281,7 @@ pub struct Windows {
pub ctx: Context,
root_info: RefCell<ViewportInfo>,
root: RefCell<RootEnv>,
window_input: Cell<WindowInput>,
}
impl Default for Windows {
@@ -309,7 +310,12 @@ impl Windows {
COMMANDS.with(|kept| kept.borrow_mut().clear());
BUILDERS.with(|kept| kept.borrow_mut().clear());
NOW.with(|now| now.set(0.0));
Windows { ctx, root_info: RefCell::new(ViewportInfo::default()), root: RefCell::new(RootEnv::default()) }
Windows {
ctx,
root_info: RefCell::new(ViewportInfo::default()),
root: RefCell::new(RootEnv::default()),
window_input: Cell::new(WindowInput::Live),
}
}
/// The window facts child passes report from now on.
@@ -323,6 +329,11 @@ impl Windows {
with_facts(viewport, |info| info.clone())
}
/// The window-input policy every following frame's input gives, as a host's `FrameInput::window_input` does.
pub fn window_input(&self, policy: WindowInput) {
self.window_input.set(policy);
}
/// The window facts the root viewport reports from now on.
pub fn root_info(&self, info: ViewportInfo) {
*self.root_info.borrow_mut() = info;
@@ -360,7 +371,7 @@ impl Windows {
CHILD_FILES.with(|files| *files.borrow_mut() = child_files);
TREES.with(|kept| kept.borrow_mut().clear());
SHAPES.with(|kept| kept.borrow_mut().clear());
set_input(&self.ctx, FrameInput::new(self.root.borrow().clone()));
set_input(&self.ctx, FrameInput::new(self.root.borrow().clone()).window_input(self.window_input.get()));
let mut input = RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, ROOT_SIZE)),
events: root,
+40 -10
View File
@@ -21,7 +21,8 @@ use crate::buttons::IconButton;
use crate::contract::{
Access, Animate as _, Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps,
ContextMenuRequest, Cx, DropKind, DropMark, Entry, ListDrag, Meta, Name, NoValue, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Pointer as _, PopupKind, Props as _, Role, RowState, SelectMode, ShowContainer as _, ShowShape, Sizing, WindowDropTarget, WordSetCx as _, spec,
Pointer as _, PopupKind, Props as _, Remember as _, Role, RowState, SelectMode, ShowContainer as _, ShowShape, Sizing, WindowDropTarget,
WordSetCx as _, spec,
};
use crate::list::{DropTest, RowTest};
use crate::menu::Menu;
@@ -186,6 +187,19 @@ enum Lane {
Ghost(usize),
}
/// The wheel scroll a strip has taken but not yet turned into a step, and the tab the strip left shown.
#[derive(Clone)]
struct WheelCarry<K> {
owed: f32,
left: Option<K>,
}
impl<K> Default for WheelCarry<K> {
fn default() -> Self {
Self { owed: 0.0, left: None }
}
}
/// What the fit reads besides the tabs' widths: the shown tab, the kind's rule, the tabs kept ahead of the others and
/// the end items.
#[derive(Clone, Debug)]
@@ -629,24 +643,40 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri
}
/// With `wheel_selects`, the wheel's whole notches step the shown tab through the tabs in the source's order:
/// down to later tabs, up to earlier ones.
/// down to later tabs, up to earlier ones. The scroll short of a notch is kept for the next pass, so a trackpad's
/// small deltas add up; it is dropped when the scroll reverses, when the strip stops at an end, and when the
/// shown tab is not the one the last step left.
fn wheel_step(&mut self, cx: &mut Cx<'_, Self>) {
if !self.wheel_selects {
return;
}
let Some(wheel) = cx.take_wheel().filter(|wheel| !wheel.mods.cmd && !wheel.mods.ctrl) else { return };
let notch = self.items.wheel_notch(cx.style.line).points(cx.rect.height());
let steps = if notch > 0.0 { (wheel.scroll.y / notch).trunc() } else { 0.0 };
if steps == 0.0 || !steps.is_finite() {
if !notch.is_finite() || notch <= 0.0 || !wheel.scroll.y.is_finite() {
return;
}
let texts = self.texts.borrow();
let Some(at) = self.shown.as_ref().and_then(|shown| texts.iter().position(|(key, _)| key == shown)) else { return };
let last = texts.len().saturating_sub(1) as i64;
let to = (at as i64 - steps as i64).clamp(0, last) as usize;
if to != at {
self.wheeled = Some(texts[to].0.clone());
let mut carry = cx.memory::<WheelCarry<K>>().clone();
if carry.left != self.shown || carry.owed * wheel.scroll.y < 0.0 {
carry.owed = 0.0;
}
carry.owed += wheel.scroll.y;
let steps = (carry.owed / notch).trunc();
carry.owed -= steps * notch;
let texts = self.texts.borrow();
let at = self.shown.as_ref().and_then(|shown| texts.iter().position(|(key, _)| key == shown));
if let Some(at) = at
&& steps != 0.0
{
let last = texts.len().saturating_sub(1) as i64;
let to = (at as i64 - steps as i64).clamp(0, last) as usize;
if to == at {
carry.owed = 0.0;
} else {
self.wheeled = Some(texts[to].0.clone());
}
}
carry.left = self.wheeled.clone().or_else(|| self.shown.clone());
*cx.memory::<WheelCarry<K>>() = carry;
}
fn report(&self) -> Report {
+16
View File
@@ -270,6 +270,22 @@ fn the_wheel_steps_the_shown_tab_only_where_the_strip_asks_for_it() {
}
}
/// A notch of wheel scroll that arrives in four quarter-notch passes shows one tab step, as a whole notch in one pass
/// does: a trackpad's small deltas add up instead of being dropped.
#[trial]
fn small_wheel_deltas_add_up_to_one_tab_step() {
use craft_ui::testing::pointer;
for parts in [4_u32, 1] {
let (mut fixture, shown) = wheel_rig(true);
let over = fixture.by_label("Two").expect("the tab's node").center();
fixture.frame(vec![pointer::moved(over)]).idle(1);
for _ in 0..parts {
fixture.frame(vec![pointer::wheel_lines(-1.0 / parts as f32)]).idle(2);
}
assert_eq!(shown.get(), 1, "a notch in {parts} passes shows exactly the next tab");
}
}
/// A double click on the empty room after the last document tab asks for a new document; a double click on a tab
/// activates it and asks for none.
#[trial]
+1 -1
View File
@@ -141,7 +141,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. `
| When | eframe method | Call |
| --- | --- | --- |
| Once, when the app is created | with the `CreationContext` | `embed::install(ctx, InstallSpec, &UiFonts)`: the runtime, then the app's fonts. Returns the font `Stack`. |
| Each frame | `raw_input_hook` | `embed::before_input(ctx, \|output\| { ...; input })`: the closure receives the `FrameOutput` of the frame before (fired commands, announcements, chrome toggles) and returns the `FrameInput` for this frame (`RootEnv`, command states, the `Host`). |
| Each frame | `raw_input_hook` | `embed::before_input(ctx, \|output\| { ...; input })`: the closure receives the `FrameOutput` of the frame before (fired commands, announcements, chrome toggles) and returns the `FrameInput` for this frame (`RootEnv`, command states, the `Host`). eframe runs the hook for the main window only: an app that drops the window system's input there (an agent-driven session) sets `FrameInput::window_input(WindowInput::Dropped)` too, and the runtime drops it in every other OS window it hosts, before injected input joins. macOS Control+Click is the runtime's in every window; the app does not map it. |
| Each frame | `logic`, after the app's own logic | `embed::logic(ctx, \|\| decision)`: the root window's close path. The closure runs only when the root window was asked to close, and returns `CloseDecision::Close` or `Hold`. |
| Each pass | `ui`, before the app's UI | `embed::before_ui(ctx, frame)`: hands the runtime the root's native window (eframe's `Frame`, or any `raw_window_handle::HasWindowHandle`) on Windows, where the runtime answers the window's hit test (resize edges, the title bar's move area, snap layouts on the maximize button), and fits the root window to its monitor once. Native only; it needs no eframe feature of the facade. |
| Each pass | `ui`, where the app draws its own document canvas | Optional: `ui::runtime::focus::host_canvas(ctx, id, KeyUse::CANVAS)` declares it as the window's canvas (Tab row below). |