Merge branch 'pdf-port/sync' into pdf-port/sync-post

This commit is contained in:
Dylan M. Taylor
2026-11-23 09:22:42 -05:00
20 changed files with 486 additions and 20 deletions
+10 -3
View File
@@ -1200,10 +1200,17 @@ fn run_pass(
Label::from(words.page_of.fill(&[("page", label.as_str()), ("count", total.as_str())]))
};
let bars = if count > 0 { bars.tip(&tip) } else { bars };
let bars = bars.show_at(ui, cx.rect);
let bar_drag = bars.view.value().is_some();
// Full screen's edge-to-edge view (`PageView::fill_screen`) has no scroll bars: nothing is drawn and nothing takes a press
// along the window's edges.
let bar_moved = if build.fill_screen {
drop(bars);
None
} else {
bars.show_at(ui, cx.rect).view.value().cloned()
};
let bar_drag = bar_moved.is_some();
scrolled |= bar_drag;
let bar_want = bars.view.value().map(|moved| drawn_frame.offset_of(moved.center, vw, vh));
let bar_want = bar_moved.map(|moved| drawn_frame.offset_of(moved.center, vw, vh));
let bar_shapes = slot.take_after(&ctx);
// The part in view waits while the view zooms or moves.
+20
View File
@@ -2683,3 +2683,23 @@ fn full_screen_two_page_view_fits_the_spread_it_shows() {
let centre = offset.0 + width / 2.0;
assert!((spread.center().x - centre).abs() < 1.0, "the spread is centred across: {} against {centre}", spread.center().x);
}
/// Full screen's edge-to-edge view (`fill_screen`) has no scroll bars, so a press along the window's edges reaches the
/// pages; by default the bars show.
#[trial]
fn full_screen_shows_no_scroll_bars() {
let bars = |fill: bool| {
let state = Rc::new(RefCell::new(state_with(|s| s.fit = Fit::Width)));
let pages = DemoPages::new(3);
let mut fixture = Fixture::new(move |ui| {
let mut now = state.borrow().clone();
let _ = PageView::new("Pages", &pages, &mut now, PAPER).options(LayoutOptions::ACROBAT).fill_screen(fill).show(ui, |_, _| ());
*state.borrow_mut() = now;
});
fixture.room(vec2(900.0, 600.0));
fixture.settle();
fixture.by_label("Vertical scroll bar").is_some()
};
assert!(bars(false), "the view shows its scroll bars by default");
assert!(!bars(true), "full screen shows none");
}
+13 -2
View File
@@ -246,12 +246,13 @@ pub struct CommentComposer<'a> {
hint: Option<Label>,
kind: ComposerDraft,
close: ComposerClose,
fixed_rows: bool,
}
impl<'a> CommentComposer<'a> {
/// A composer at `anchor` (screen points; `None` hides it) that edits `draft`.
pub fn new(anchor: Option<Pos2>, draft: &'a mut String) -> Self {
CommentComposer { anchor, draft, header: None, hint: None, kind: ComposerDraft::New, close: ComposerClose::OnOutsidePress }
CommentComposer { anchor, draft, header: None, hint: None, kind: ComposerDraft::New, close: ComposerClose::OnOutsidePress, fixed_rows: false }
}
/// A header of `title` and the `author` above the field; the card is named `title`.
@@ -260,6 +261,15 @@ impl<'a> CommentComposer<'a> {
self
}
/// The field keeps its three rows and scrolls longer text inside them (`TextField::max_lines`), so the card keeps
/// one size. Off (the default), the field grows with its text, which the card's measure, taken before the text
/// wraps, does not see: near the bottom of the window the card is placed shorter than it lays out and clips its
/// buttons.
pub fn fixed_rows(mut self) -> Self {
self.fixed_rows = true;
self
}
/// What the field asks for, in place of "Add a comment": its name and its placeholder ("Text to insert" for an
/// insertion).
pub fn hint(mut self, hint: impl Into<Label>) -> Self {
@@ -330,7 +340,7 @@ pub struct CommentComposerOutput {
impl CommentComposer<'_> {
/// Shows the composer and reports whether the user posted or closed it.
pub fn show(self, ui: &mut Ui) -> CommentComposerOutput {
let CommentComposer { anchor, draft, header, hint, kind, close } = self;
let CommentComposer { anchor, draft, header, hint, kind, close, fixed_rows } = self;
let mut output = CommentComposerOutput::default();
let Some(anchor) = anchor else { return output };
let words = Env::of(ui).words::<ThreadWords>();
@@ -355,6 +365,7 @@ impl CommentComposer<'_> {
}
let hint = hint.clone().unwrap_or_else(|| words.add_comment.clone());
let field = TextField::new(hint.clone(), Bind::bound(&mut *draft)).lines(COMPOSER_ROWS).placeholder(hint).submits().default_stop();
let field = if fixed_rows { field.max_lines(COMPOSER_ROWS) } else { field };
// An edit opens with the caret after the comment's text, so typing adds to it; a new comment's empty
// field has nothing to replace either way.
let field = if kind == ComposerDraft::New { field } else { field.keep_caret_on_open() }.show(ui);
+22
View File
@@ -340,3 +340,25 @@ fn an_edit_composer_opens_with_the_caret_after_the_text() {
assert_eq!(draft.borrow().as_str(), want, "{kind:?}");
}
}
/// `CommentComposer::fixed_rows`: a card near the bottom of the window keeps its Post button inside it when its text
/// runs past the field's three rows, and Post posts.
#[trial]
fn a_composer_with_fixed_rows_keeps_post_inside_its_card_near_the_bottom() {
let posted = Rc::new(RefCell::new(None));
let seen = Rc::clone(&posted);
let mut draft = String::new();
let mut fixture = Fixture::new(move |ui| {
let out = CommentComposer::new(Some(pos2(120.0, 470.0)), &mut draft).header("Text box", "Ada").fixed_rows().show(ui);
if let Some(text) = out.posted {
*seen.borrow_mut() = Some(text);
}
});
fixture.room(vec2(800.0, 600.0)).settle();
fixture.type_text(&"word ".repeat(20)).settle();
let card = fixture.by_role(craft_ui::contract::Role::DIALOG).first().expect("the card").rect;
let post = fixture.by_label("Post").expect("the Post button");
assert!(card.contains_rect(post.rect), "Post {:?} lies inside the card {card:?}", post.rect);
fixture.click(&post).settle();
assert!(posted.borrow().as_deref().is_some_and(|text| text.starts_with("word word")), "Post posted: {:?}", posted.borrow());
}
+42 -1
View File
@@ -117,7 +117,7 @@ use craft_behavior::geometry::crop::normalized_angle;
use craft_behavior::kurbo::{Point, Rect as DocRect, Size};
use craft_behavior::{
CanvasTransform, CanvasView, CursorIcon, CursorPriority, EditEvent, EditorInput, HitLevel, HitPriority, HitShape, Input, Intent, Metrics, Mixed,
PartKey, PointerButton, PressPhase, PressState, Sense, Wheel, WheelNotch, WheelUnit,
PartKey, PointerButton, PressPhase, PressState, Sense, Wheel, WheelNotch, WheelSource, WheelUnit,
};
use egui::{Context, Pos2, Rect, Response, Vec2};
use navigate::MiddleAutoscroll;
@@ -460,6 +460,8 @@ impl<'a> Canvas<'a> {
let (press, on_region) = self.pressed(cx);
// A press, a zoom, a key move and a view command end the touchpad glide and the eased wheel's owed motion.
let mut halt = matches!(press.phase, PressPhase::Down { .. });
// A press, a key move and a view command also drop the eased wheel zoom's owed part; its own zoom does not.
let mut stop_zoom_ease = halt;
let mut jumped = false;
let mut line_pan = Vec2::ZERO;
// The screen point a wheel or pinch zoom of this pass kept still, before the clamp below can move the centre.
@@ -473,6 +475,10 @@ impl<'a> Canvas<'a> {
zoom_anchor = read.zoom_anchor.or(zoom_anchor);
halt |= read.zoomed;
}
let paid = pay_wheel_zoom(&ctx, &mut motion, &mut view, size, pixels_per_point, now);
jumped |= paid.jumped;
zoom_anchor = paid.zoom_anchor.or(zoom_anchor);
halt |= paid.zoomed;
// Every pass feeds the ease, the line pan or nothing, so owed motion keeps paying; the service takes the time
// from its own clock, so a later pass of the same frame pays nothing.
if self.navigation.eased_wheel && !halt {
@@ -535,6 +541,7 @@ impl<'a> Canvas<'a> {
}
moves.extend(cx.take_scroll_moves());
halt |= !moves.is_empty();
stop_zoom_ease |= !moves.is_empty();
for (step, mods) in moves {
if to_body {
keys.page = Some((step, mods));
@@ -559,6 +566,7 @@ impl<'a> Canvas<'a> {
}
view = next;
halt = true;
stop_zoom_ease = true;
match motion {
CommandMotion::Ease if self.navigation.animated_zoom => {
// A zoom that keeps the centre eases about it; one that moves the centre (Fit on Screen) eases
@@ -578,6 +586,7 @@ impl<'a> Canvas<'a> {
motion.glide.stop();
cx.stop_wheel_ease();
}
motion.wheel_zoom.stop_if(stop_zoom_ease);
// A view that moves during a wheel gesture marks it moved, so a body that turns pages at the edge does not turn
// one after a pan or a go-to.
if target != at_start {
@@ -611,6 +620,13 @@ impl<'a> Canvas<'a> {
match action {
// The eased wheel hands a line's pan to the wheel service, which pays it out over the passes after.
WheelAction::Pan(delta) if self.navigation.eased_wheel && wheel.unit == WheelUnit::Line => read.line_pan = delta,
// The eased wheel zoom owes a notch's zoom, which `settle` pays over this pass and the ones after.
WheelAction::Zoom(factor) if self.navigation.eased_wheel_zoom && eases_zoom(wheel) => {
let at = wheel.at.unwrap_or_else(|| view.rect.center());
let frame_dt = f64::from(cx.core.ctx.input(|input| input.stable_dt));
motion.wheel_zoom.feed(factor, at, now, frame_dt);
read.zoomed = true;
}
action => {
read.zoomed = !matches!(action, WheelAction::Pan(_));
// The pointer the wheel came at: the canvas's own widget is not hovered where an app widget in
@@ -1094,6 +1110,31 @@ fn clamped(mut view: CanvasView, document: Option<Size>, navigation: &Navigation
view
}
/// Pays this pass's part of what the eased wheel zoom's notches owe (`NavigationOptions::eased_wheel_zoom`) on `view`,
/// and asks for the next pass while more is owed: whether it zoomed, whether the view moved and the point the zoom kept
/// still.
fn pay_wheel_zoom(ctx: &Context, motion: &mut ViewMotion, view: &mut CanvasView, size: Size, pixels_per_point: f32, now: f64) -> WheelRead {
let paid = motion.wheel_zoom.step(now).map(|(factor, at)| {
let action = WheelAction::Zoom(factor);
let (anchor, zoom) = (WheelNavigation::zoom_anchor(view, action, at, size), view.zoom);
let jumped = WheelNavigation::apply(view, action, at, size, pixels_per_point);
WheelRead { jumped, zoom_anchor: anchor.filter(|_| view.zoom != zoom), zoomed: true, ..WheelRead::default() }
});
if motion.wheel_zoom.owes() {
frame::request_repaint(ctx);
}
paid.unwrap_or_default()
}
/// Whether the eased wheel zoom takes `wheel`'s zoom: a wheel notch under the zoom modifier (Cmd or Ctrl), whose
/// deltas the wheel service turns into the share's zoom and never into scroll. A pinch (no modifier), a trackpad's
/// steps and a step under 8 points of egui's wheel zoom speed (which egui leaves unsmoothed too) zoom at once.
fn eases_zoom(wheel: &Wheel) -> bool {
/// The log of the factor of 8 points at egui's default wheel zoom speed (1/200 a point).
const SMALLEST: f32 = 8.0 / 200.0;
(wheel.mods.cmd || wheel.mods.ctrl) && wheel.source != WheelSource::Trackpad && wheel.zoom.ln().abs() >= SMALLEST
}
/// What a pass's wheel did to the view ([`Canvas::read_wheel`]).
#[derive(Default)]
struct WheelRead {
@@ -38,6 +38,9 @@ pub struct NavigationOptions {
pub key_line: f32,
/// A wheel pan eases to its target through the wheel service instead of jumping. Off.
pub eased_wheel: bool,
/// A wheel zoom (a zoom-modifier wheel notch, not a pinch or a trackpad's small steps) eases to its factor over the
/// passes after the notch, as egui eases a wheel, instead of zooming at once. Off.
pub eased_wheel_zoom: bool,
/// A touchpad's scroll glides on after the fingers lift. Off.
pub touchpad_glide: bool,
/// What the middle button does over the canvas background. `Pan`.
@@ -100,6 +103,7 @@ impl Default for NavigationOptions {
wheel_line: 16.0,
key_line: PageKey::SMALL_STEP,
eased_wheel: false,
eased_wheel_zoom: false,
touchpad_glide: false,
middle_button: craft_behavior::MiddleButton::default(),
invert_middle: false,
@@ -136,6 +136,73 @@ pub(crate) struct ViewMotion {
pub(crate) autoscroll: super::navigate::MiddleAutoscroll,
/// The frame of the autoscroll's last pass: an autoscroll whose canvas missed a frame (another tab showed) ends.
pub(crate) scrolled_in: Option<u64>,
/// The wheel zoom still owed under `NavigationOptions::eased_wheel_zoom`.
pub(crate) wheel_zoom: WheelZoomEase,
}
/// A wheel zoom paid out over the passes after its notch (`NavigationOptions::eased_wheel_zoom`), as egui eases the
/// wheel: each pass pays the part of what is owed that reaches 90% in a tenth of a second, by the pass clock, so a
/// later pass of the same frame pays nothing, and the last sliver is paid whole.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct WheelZoomEase {
/// The zoom still owed, as the natural log of its factor.
owed: f64,
/// The screen point the zoom keeps still: the pointer of the latest notch.
anchor: Pos2,
/// The pass clock of the last payment.
paid_at: f64,
}
impl WheelZoomEase {
/// The owed zoom paid whole: one point of egui's default wheel zoom speed.
const SLIVER: f64 = 0.005;
/// The longest time one payment counts, in seconds, as egui caps its wheel's frame time.
const LONGEST_STEP: f64 = 0.1;
/// Adds a notch's `factor` about `anchor` at the pass clock `now`. An ease that owed nothing starts one frame
/// (`frame_dt` seconds) back, so the notch's own pass pays its first part, as egui's wheel does.
pub(crate) fn feed(&mut self, factor: f64, anchor: Pos2, now: f64, frame_dt: f64) {
let log = factor.ln();
if !log.is_finite() || log == 0.0 {
return;
}
if self.owed == 0.0 {
let back = if frame_dt.is_finite() { frame_dt.clamp(0.0, Self::LONGEST_STEP) } else { 0.0 };
self.paid_at = now - back;
}
self.owed += log;
if !self.owed.is_finite() {
self.owed = 0.0;
}
self.anchor = anchor;
}
/// This pass's payment at the clock `now`: the factor to zoom by and the point it keeps still, if any.
pub(crate) fn step(&mut self, now: f64) -> Option<(f64, Pos2)> {
if self.owed == 0.0 {
return None;
}
let dt = if (now - self.paid_at).is_finite() { (now - self.paid_at).clamp(0.0, Self::LONGEST_STEP) } else { 0.0 };
self.paid_at = now;
let pay = if self.owed.abs() < Self::SLIVER { self.owed } else { self.owed * (1.0 - 0.1_f64.powf(dt / Self::LONGEST_STEP)) };
if pay == 0.0 || !pay.is_finite() {
return None;
}
self.owed -= pay;
Some((pay.exp(), self.anchor))
}
/// Whether zoom is still owed.
pub(crate) fn owes(&self) -> bool {
self.owed != 0.0
}
/// Drops what is owed when `stop`.
pub(crate) fn stop_if(&mut self, stop: bool) {
if stop {
self.owed = 0.0;
}
}
}
impl ViewMotion {
@@ -620,6 +620,79 @@ fn an_eased_wheel_pays_the_same_distance_at_any_frame_rate_keeps_paying_after_th
assert_eq!(view.get().center, paged, "a key move ends the owed motion");
}
/// A canvas over a large document whose app reruns the pass of a frame while the flag is set, with `eased_wheel_zoom`
/// as `eased`: the fixture, the view it shows and the flag.
fn zoom_rig(eased: bool) -> EasedRig {
let mut options = NavigationOptions::default();
options.eased_wheel_zoom = eased;
let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)));
let rerun = Rc::new(Cell::new(false));
let (shown, again) = (Rc::clone(&view), Rc::clone(&rerun));
let mut fixture = Fixture::new(move |ui| {
let mut given = shown.get();
given.rect = ui.available_rect_before_wrap();
let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |_, _| {});
shown.set(canvas.output.view.unwrap_or(given));
if again.replace(false) && frame::discardable(ui.ctx()) {
frame::discard_pass(ui.ctx(), "the trial's second pass");
}
});
fixture.settle();
(fixture, view, rerun)
}
/// A zoom-modifier wheel notch of 60 points.
fn zoom_notch() -> egui::Event {
egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: Vec2::new(0.0, 60.0),
phase: egui::TouchPhase::Move,
modifiers: Modifiers::COMMAND,
source: egui::MouseWheelSource::Wheel,
}
}
/// The zoom after each of the notch's frame and the `frames` frames after it, each run as two passes when `twice`.
fn zooms_after_notch(eased: bool, frames: usize, twice: bool) -> Vec<f64> {
let (mut fixture, view, rerun) = zoom_rig(eased);
fixture.frame(vec![pointer::moved(view.get().rect.center())]);
let mut zooms = Vec::new();
eased_frame(&mut fixture, &rerun, twice, vec![zoom_notch()]);
zooms.push(view.get().zoom);
for _ in 0..frames {
eased_frame(&mut fixture, &rerun, twice, vec![]);
zooms.push(view.get().zoom);
}
zooms
}
#[trial]
fn an_eased_wheel_zoom_spreads_a_notch_over_the_frames_after_it_and_lands_where_the_plain_one_jumps() {
let plain = zooms_after_notch(false, 3, false);
assert!(plain[0] > 1.0, "the notch zooms in: {plain:?}");
assert!(plain.windows(2).all(|pair| pair[0] == pair[1]), "upstream's default zooms at once: {plain:?}");
let eased = zooms_after_notch(true, 60, false);
let (first, last) = (eased[0], eased[eased.len() - 1]);
assert!(first > 1.0 && first < plain[0], "the notch's frame pays part of it: {first} of {}", plain[0]);
assert!(eased[2] > eased[1], "a frame after the notch still zooms: {eased:?}");
assert!((last / plain[0] - 1.0).abs() < 1e-3, "the ease lands on the plain zoom: {last} and {}", plain[0]);
let rerun = zooms_after_notch(true, 60, true);
assert!((rerun[1] - eased[1]).abs() < 1e-9, "a frame's second pass pays nothing more: {} and {}", rerun[1], eased[1]);
// A key move drops what is still owed.
let (mut fixture, view, _) = zoom_rig(true);
let canvas = fixture.by_role(Role::CANVAS)[0];
fixture.click(&canvas);
fixture.frame(vec![pointer::moved(view.get().rect.center())]);
fixture.frame(vec![zoom_notch()]);
fixture.key(Key::PageDown, Modifiers::NONE);
let paged = view.get().zoom;
fixture.idle(5);
assert_eq!(view.get().zoom, paged, "a key move ends the owed zoom");
}
#[trial]
fn a_held_alt_key_is_in_the_wheels_modifiers_when_the_wheel_events_miss_it() {
// Windows can report a held Alt in its key events and not in the wheel's modifier state.
@@ -59,7 +59,12 @@ pub(crate) fn edit_intents<C: Component>(comp: &mut C, cx: &mut Cx<'_, C>) {
&& focus::escape_closes_dialog(&cx.core.ctx);
let escapes = !cx.core.escape_to_list && !crate::runtime::keys::focus_in_modal_dialog(&cx.core.ctx);
let reason = if dialog_escape {
cx.cancel(CancelReason::Escape);
// A dialog that keeps typing on Escape (`FocusPolicy::escape_keeps_typing`) commits it instead.
if focus::escape_keeps_typing(&cx.core.ctx) {
cx.commit();
} else {
cx.cancel(CancelReason::Escape);
}
None
} else if escapes && cx.core.intents.take(Intent::Cancel) {
Some(CancelReason::Escape)
@@ -480,8 +480,9 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
&& input.intents.untaken(&Intent::Cancel)
&& crate::runtime::focus::escape_closes_dialog(ctx);
if dialog_escape {
// The draft ends as for Escape (its typing is dropped), and the Escape stays for the dialog.
state.end = Some(End::Escape);
// The draft ends as for Escape (its typing is dropped), and the Escape stays for the dialog. A dialog that keeps
// typing on Escape (`FocusPolicy::escape_keeps_typing`) commits the draft as leaving the field does.
state.end = Some(if crate::runtime::focus::escape_keeps_typing(ctx) { End::Blur } else { End::Escape });
}
let draft_takes = state.draft.is_some() && !dialog_escape && !(focused_before && keys::focus_in_modal_dialog(ctx));
let takes_escape =
@@ -151,6 +151,8 @@ pub(crate) struct Board {
out: Vec<Fired>,
/// The latest point-bearing clipboard request in each viewport.
pending_pastes: HashMap<ViewportId, Fired>,
/// The app's `CommandInput::paste_reads_clipboard`.
paste_reads_clipboard: bool,
/// App-scope commands a key pressed while only their own state disabled them, for the next `FrameOutput`.
declined: Vec<Fired>,
/// The commands instances took since the last `FrameOutput`, in order.
@@ -1082,6 +1084,7 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) {
}
board.gate = input.gate.clone();
board.app = input.catalog.clone();
board.paste_reads_clipboard = input.paste_reads_clipboard;
let stale = board.keymap.as_ref().is_none_or(|cache| {
cache.platform != platform
|| cache.generation != generation
@@ -1637,6 +1640,21 @@ fn queue(ctx: &Context, fired: Fired) {
{
return;
}
// An app that reads the clipboard through the board (`CommandInput::paste_reads_clipboard`) gets a Paste fired at
// it from a menu, a button or the palette with the clipboard's content: the platform is asked in this pass, and
// the paste it delivers fires the command (`deliver_requested_paste`).
let reads_clipboard = fired.phase != FirePhase::Release
&& fired.target.is_none()
&& fired.pasted.is_none()
&& fired.source != FireSource::Key
&& with(ctx, |board| board.paste_reads_clipboard && board.registry.edit_of(&fired.command.id) == Some(EditCommand::Paste));
if reads_clipboard {
with(ctx, |board| {
board.pending_pastes.insert(pass::current_viewport(ctx), fired);
});
crate::runtime::egui::clipboard::request_paste(ctx);
return;
}
with(ctx, |board| if fired.target.is_some() { board.queue.push(fired) } else { board.out.push(fired) });
// A scoped entry is taken next pass, so the root viewport runs one.
repaint::request_of(ctx, ViewportId::ROOT);
@@ -457,6 +457,7 @@ pub struct CommandInput {
pub(crate) overrides: Option<Arc<Overrides>>,
pub(crate) gate: Option<CommandGate>,
pub(crate) catalog: Option<AppCatalog>,
pub(crate) paste_reads_clipboard: bool,
}
impl CommandInput {
@@ -494,6 +495,16 @@ impl CommandInput {
self.gate = Some(gate);
self
}
/// Whether the library's Paste ([`EditCommands::Paste`]), fired at the app by a menu row, a toolbar button or the
/// palette, first asks the platform for the clipboard in the pass that fires it and reaches the app with the
/// clipboard's content, as ⌘V does. Off (the default), it reaches the app at once with no content and the app
/// reads its clipboard itself.
#[must_use]
pub fn paste_reads_clipboard(mut self, on: bool) -> Self {
self.paste_reads_clipboard = on;
self
}
}
/// The chain of container instances that receive scoped commands, innermost last. A private inherited field of
+21 -9
View File
@@ -1059,24 +1059,36 @@ pub fn focus_in_scope(ctx: &Context, scope: Id) -> Option<bool> {
/// Only a modal dialog counts: a modeless window's edits belong to the app, so its field reverts its own draft first
/// and the next Escape closes the window.
pub(crate) fn escape_closes_dialog(ctx: &Context) -> bool {
let Some(rec) = focused_rec(ctx) else {
return false;
};
let dialog = with(ctx, |state| {
escaping_dialog(ctx).is_some()
}
/// Whether the dialog that [`escape_closes_dialog`] finds keeps the focused field's typing on Escape
/// (`FocusPolicy::escape_keeps_typing`): the field then commits its draft instead of cancelling it.
pub(crate) fn escape_keeps_typing(ctx: &Context) -> bool {
escaping_dialog(ctx).is_some_and(|policy| policy.escape_keeps_typing)
}
/// The policy of the modal dialog on top whose Escape closes it and which holds the focused stop
/// ([`escape_closes_dialog`]).
fn escaping_dialog(ctx: &Context) -> Option<FocusPolicy> {
let rec = focused_rec(ctx)?;
let (id, policy) = with(ctx, |state| {
let mut at = rec.scope;
while let Some(id) = at {
let scope = state.scopes.get(&id).or_else(|| state.last_scopes.get(&id))?;
match scope.policy.kind {
craft_behavior::ScopeKind::Group | craft_behavior::ScopeKind::Pane => at = scope.parent,
craft_behavior::ScopeKind::Dialog => return (scope.policy.cancel == craft_behavior::CancelRule::Close).then_some(id),
craft_behavior::ScopeKind::Dialog => {
return (scope.policy.cancel == craft_behavior::CancelRule::Close).then_some((id, scope.policy));
}
_ => return None,
}
}
None
});
dialog.is_some_and(|id| {
crate::runtime::overlay::top(ctx) == Some(id) && crate::runtime::overlay::entry(ctx, id).is_some_and(|entry| entry.rank.is_modal())
})
})?;
let modal_on_top =
crate::runtime::overlay::top(ctx) == Some(id) && crate::runtime::overlay::entry(ctx, id).is_some_and(|entry| entry.rank.is_modal());
modal_on_top.then_some(policy)
}
/// Whether the focus is in the focus scope of the layer `layer`, or, for an `Initial::KeepAnchor` scope, on the stop
@@ -69,6 +69,10 @@ pub struct FocusPolicy {
/// In a `KeepAnchor` layer, the collection the opener hands its list keys to (Up, Down, Page keys, Home and End,
/// Enter and Tab as the layer's rules say). Without one the opener keeps its keys.
pub list: Option<Id>,
/// In a dialog whose Escape closes it, the Escape keeps the typing in the focused field: the field commits its
/// draft as on leaving it, and the dialog then closes. Off (the default), one Escape cancels the typing with the
/// dialog. A window that applies its rows as they change (a live Preferences window) keeps what was typed.
pub escape_keeps_typing: bool,
}
impl FocusPolicy {
@@ -83,6 +87,7 @@ impl FocusPolicy {
pages: false,
list_enter: true,
list: None,
escape_keeps_typing: false,
};
/// A pane: an F6 stop.
pub const PANE: FocusPolicy = FocusPolicy { kind: ScopeKind::Pane, ..FocusPolicy::NONE };
@@ -97,6 +102,7 @@ impl FocusPolicy {
pages: false,
list_enter: true,
list: None,
escape_keeps_typing: false,
};
/// A popup: focus moves in, Escape closes and focus returns to the opener.
pub const POPUP: FocusPolicy = FocusPolicy {
@@ -109,6 +115,7 @@ impl FocusPolicy {
pages: false,
list_enter: true,
list: None,
escape_keeps_typing: false,
};
/// A menu: like a popup.
pub const MENU: FocusPolicy = FocusPolicy { kind: ScopeKind::Menu, ..FocusPolicy::POPUP };
@@ -152,6 +159,12 @@ impl FocusPolicy {
self
}
/// Whether Escape in this dialog keeps the focused field's typing ([`FocusPolicy::escape_keeps_typing`]).
pub const fn escape_keeps_typing(mut self, on: bool) -> Self {
self.escape_keeps_typing = on;
self
}
/// Whether Ctrl+Tab cycles pages.
pub const fn pages(mut self, on: bool) -> Self {
self.pages = on;
+11
View File
@@ -222,6 +222,17 @@ impl<'a> Dialog<'a> {
})
}
/// Whether Escape keeps the typing in the focused field: the field commits its draft and the dialog closes. Off
/// (the default), one Escape cancels the typing with the dialog. For a dialog that applies its fields as they
/// change, where the dialog's Escape takes nothing back (`FocusPolicy::escape_keeps_typing`).
#[must_use]
pub fn escape_keeps_typing(self, on: bool) -> Self {
self.overlay(|overlay| {
let focus = overlay.focus.escape_keeps_typing(on);
overlay.focus(focus)
})
}
/// Where the dialog first opens, as a screen position of its `corner`; the middle of the window without it. A saved
/// placement comes first.
#[must_use]
@@ -104,6 +104,10 @@ pub struct PreferencesWindow<'a> {
/// Lays the page out as `layout` says ([`PreferencesPage::layout`]); the default is [`PreferencesLayout::Paged`].
#[prop]
layout: PreferencesLayout,
/// Escape keeps the typing in the focused field ([`Dialog::escape_keeps_typing`]): in [`PreferencesMode::Live`]
/// the typed value stays applied when Escape closes the window. Off by default: Escape cancels the typing.
#[prop(flag)]
escape_keeps_typing: bool,
}
/// What the body, the footer and the buttons' guard share during one pass: the host, the window's state as the pass
@@ -158,12 +162,20 @@ impl<H: PreferencesDraft + ?Sized> Session<'_, '_, H> {
impl<'a> PreferencesWindow<'a> {
/// A window over the host's `state`.
pub fn new(state: Bind<'a, PreferencesState>) -> Self {
PreferencesWindow { state, title: None, embedded: false, remember: None, mode: PreferencesMode::Staged, layout: PreferencesLayout::Paged }
PreferencesWindow {
state,
title: None,
embedded: false,
remember: None,
mode: PreferencesMode::Staged,
layout: PreferencesLayout::Paged,
escape_keeps_typing: false,
}
}
/// Shows the window for this pass over `host`. The output's `closed` tells the host to stop showing it.
pub fn show<H: PreferencesDraft + ?Sized>(self, ui: &mut Ui, host: &mut H) -> PreferencesOutput {
let PreferencesWindow { state, title, embedded, remember, mode, layout } = self;
let PreferencesWindow { state, title, embedded, remember, mode, layout, escape_keeps_typing } = self;
let env = Env::of(ui);
let words = env.words::<PreferencesWords>();
let common = env.words::<CommonWords>();
@@ -201,6 +213,7 @@ impl<'a> PreferencesWindow<'a> {
.resizable(true)
.overlay(|overlay| overlay.size(size).min_size(least))
.close_on_enter(can_ok)
.escape_keeps_typing(escape_keeps_typing)
.on_pick(|button, cx| {
if button.role() == DialogRole::Other && !nested {
session.borrow_mut().apply(cx);
@@ -125,3 +125,85 @@ fn corrected_custom_row_applies_after_an_error() {
fixture.click(&correct).settle();
assert_eq!(model.borrow().saved, 2, "a correction applies without closing the window");
}
#[derive(Default)]
struct TextModel {
draft: String,
saved: String,
}
impl PreferencesModel for TextModel {
fn pages(&self) -> Vec<PageSpec<'_>> {
vec![PageSpec::new("general", "General", vec![RowSpec::new("author", "Author", RowKind::Text(&self.draft))])]
}
fn set(&mut self, _: &str, value: PrefValue) {
if let PrefValue::Text(value) = value {
self.draft = value;
}
}
fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool {
false
}
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
false
}
fn reset_page(&mut self, _: &str) {}
}
impl PreferencesDraft for TextModel {
fn differs(&self) -> bool {
self.draft != self.saved
}
fn apply(&mut self) -> Result<(), String> {
self.saved = self.draft.clone();
Ok(())
}
fn cancel(&mut self) {
self.draft = self.saved.clone();
}
}
/// Types into a live window's text row, presses Escape and answers whether the window closed and what it kept.
fn escape_after_typing(keeps: bool) -> (bool, String) {
let model = Rc::new(RefCell::new(TextModel::default()));
let shown = model.clone();
let closed = Rc::new(RefCell::new(false));
let seen = closed.clone();
let mut state = PreferencesState::default();
let mut fixture = Fixture::new(move |ui| {
if *seen.borrow() {
return;
}
let mut window = PreferencesWindow::new(Bind::bound(&mut state)).mode(PreferencesMode::Live).embedded();
if keeps {
window = window.escape_keeps_typing();
}
if window.show(ui, &mut *shown.borrow_mut()).closed.is_some() {
*seen.borrow_mut() = true;
}
});
fixture.settle();
let field = fixture.by_label("Author").expect("the text row");
fixture.click(&field).settle();
fixture.type_text("Ada").settle();
fixture.key(egui::Key::Escape, egui::Modifiers::NONE).settle();
let saved = model.borrow().saved.clone();
(*closed.borrow(), saved)
}
/// Upstream's default: one Escape closes a live window and cancels the field's typing with it.
#[trial]
fn escape_cancels_a_live_windows_typing_by_default() {
let (closed, saved) = escape_after_typing(false);
assert!(closed, "Escape closes the window");
assert_eq!(saved, "", "the typing goes with the Escape");
}
/// `escape_keeps_typing`: Escape closes the window and the field's typing stays applied, as a live window whose rows
/// apply as they change keeps what was typed (PdfCraft's Preferences).
#[trial]
fn escape_keeps_a_live_windows_typing_when_asked() {
let (closed, saved) = escape_after_typing(true);
assert!(closed, "Escape closes the window");
assert_eq!(saved, "Ada", "the typing stays applied");
}
+3
View File
@@ -438,6 +438,9 @@ impl<C: Codec + Clone + 'static> Component for TextField<'_, C> {
&& let Some(empty) = self.empty.clone()
{
cx.set(empty);
// The text part showed the old text earlier in this pass: the pass runs again, so the field shows and reports
// the empty text in the pass that took the click, not one pass later.
crate::runtime::frame::discard_pass(&cx.core.ctx, "a search field's clear part emptied it");
}
}
@@ -271,3 +271,33 @@ fn a_context_menu_near_the_top_stays_inside_the_window() {
let window = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(400.0, 300.0));
assert!(menu.min.y >= window.min.y - 0.5 && menu.max.y <= window.max.y + 0.5, "the menu lies inside the window: {menu:?}");
}
/// Edit ▸ Paste fired at the app reaches it at once with no content by default; an app that reads the clipboard
/// through the board (`CommandInput::paste_reads_clipboard`) gets it with the clipboard's text once the platform
/// answers, as ⌘V's paste does.
#[trial]
fn a_menu_paste_reads_the_clipboard_when_the_app_asks() {
for reads in [false, true] {
let mut fixture = Fixture::new(|ui| {
Button::new("Target").show(ui);
});
fixture.commands(commands::CommandInput::new().paste_reads_clipboard(reads)).settle();
let _ = take_output(fixture.ctx());
commands::fire(fixture.ctx(), EditCommands::Paste, FireSource::Menu);
fixture.settle();
let now = take_output(fixture.ctx()).fired;
if !reads {
assert!(now.iter().any(|fired| fired.command.id == EditCommands::Paste.id() && fired.pasted.is_none()), "at once: {now:?}");
continue;
}
assert!(now.is_empty(), "the paste waits for the platform's clipboard: {now:?}");
fixture.frame(vec![egui::Event::Paste("clipboard text".to_owned())]).settle();
let later = take_output(fixture.ctx()).fired;
assert!(
later.iter().any(|fired| fired.command.id == EditCommands::Paste.id()
&& fired.source == FireSource::Menu
&& fired.pasted.as_ref().and_then(|content| content.text.as_deref()) == Some("clipboard text")),
"the paste arrives with the clipboard's text: {later:?}"
);
}
}
@@ -275,3 +275,25 @@ fn a_bound_caret_moves_the_caret_and_follows_it() {
fixture.idle(2);
assert_eq!(caret.get(), 4, "the user's caret move past the two-byte \"é\" writes its byte offset back");
}
/// The clear part empties the field in the pass that takes its click: the field's node reads empty after that one pass,
/// as an agent's click reply comes with it (the control channel answers with the pass that ran the input).
#[trial]
fn the_clear_part_empties_the_field_in_the_pass_of_its_click() {
use craft_ui::testing::focus::AccessActionKind;
let id = Rc::new(Cell::new(Id::NULL));
let field = id.clone();
// The app's own text, as a search panel's query is.
let text = Rc::new(RefCell::new(String::from("abc")));
let held = text.clone();
let mut fixture = Fixture::new(move |ui| {
let mut query = held.borrow_mut();
field.set(TextField::search("Search", Bind::bound(&mut *query)).show(ui).response.id);
});
fixture.settle();
assert_eq!(fixture.tree().value(id.get()), Some("abc"));
let clear = fixture.part(id.get(), CLEAR).expect("a search field with text shows the clear part");
fixture.access(AccessActionKind::Click, &clear);
assert_eq!(text.borrow().as_str(), "", "the click emptied the text");
assert_eq!(fixture.tree().value(id.get()), Some(""), "the field reads empty in the pass of the click");
}