pdf-chrome-w4: net change of 1 commits

- pdf-chrome-w4: written from its sheet
This commit is contained in:
Dylan M. Taylor committed 2026-11-18 03:54:14 -05:00
1 parent 4cc8033a29
commit c61ce09591
6 files changed
+209 -50

No files matched your search

+46 -14
View File
@@ -3,8 +3,8 @@
//! The window's shell shows its queue through `ToastHost`, at the end-bottom corner of its body, and tells it which
//! cards the pointer or focus holds; an embedded shell shows its own queue inside its own body. A card's timer runs only
//! while nothing holds it, and starts over with its whole timeout when the hold ends. Each new toast is announced once,
//! when it is first shown. At most `MAX_CARDS` cards are queued per window; a toast's end (an action taken, a
//! dismissal, the timer, a drop by the cap) is read once with `end`.
//! when it is first shown. At most `MAX_CARDS` cards are queued per window unless progress cards fill it; a toast's end
//! (an action taken, a dismissal, the timer, a drop by the cap) is read once with `end`.
use crate::runtime::access::{self, Politeness};
use crate::runtime::egui::{pass, repaint};
@@ -17,7 +17,9 @@ use egui::{Context, ViewportId};
pub const TIMEOUT: f32 = 6.0;
/// Most cards queued at once per window. Posting past it keeps the new card and drops the oldest earlier card that
/// would leave by itself (no action, a timeout), else the oldest earlier card; `end` reports the drop as `Dropped`.
/// would leave by itself (no action, a timeout), else the oldest earlier card without progress; `end` reports the drop
/// as `Dropped`. A progress card is never dropped: when only progress cards are earlier, the new card is queued past
/// the cap.
pub const MAX_CARDS: usize = 3;
/// Ended toasts whose end nobody has read yet; the oldest report goes first.
@@ -84,7 +86,7 @@ impl Toast {
title: None,
lines: Vec::new(),
actions: Vec::new(),
progress: Default::default(),
progress: None,
}
}
@@ -124,17 +126,42 @@ impl Toast {
self
}
/// Sets the fraction done, clamped to `0..=1`.
pub fn progress(self, fraction: f32) -> Self {
let _ = fraction;
todo!("CH-C14")
/// Sets the fraction done, clamped to `0..=1`; the card then has no timer.
pub fn progress(mut self, fraction: f32) -> Self {
self.progress = Some(clamp_fraction(fraction));
self.timeout = None;
self
}
}
/// Sets the fraction done of the toast `id` and, when given, its message.
/// `fraction` clamped to `0..=1`, and 0 when it is not a number.
fn clamp_fraction(fraction: f32) -> f32 {
if fraction.is_nan() { 0.0 } else { fraction.clamp(0.0, 1.0) }
}
/// Sets the fraction done of the toast `id` and, when given, its message, in whichever viewport holds it; the card
/// keeps no timer from then on. A toast that is gone is left alone, and a measuring run changes nothing.
pub fn set_progress(ctx: &Context, id: ToastId, fraction: f32, message: Option<Label>) {
let _ = (ctx, id, fraction, message);
todo!("CH-C14")
if !crate::runtime::measure::effect(ctx, "toast::set_progress") {
return;
}
let fraction = clamp_fraction(fraction);
for viewport in pass::live_viewports(ctx) {
let found = PerViewport::<Queue>::with(ctx, viewport, |queue| {
let Some(live) = queue.live().find(|live| live.card.id == id) else { return false };
let toast = &mut live.card.toast;
toast.progress = Some(fraction);
toast.timeout = None;
if let Some(message) = message.clone() {
toast.message = message;
}
live.remaining = None;
true
});
if found {
repaint::request_of(ctx, viewport);
}
}
}
/// A posted toast's handle.
@@ -233,9 +260,14 @@ pub fn post_to(ctx: &Context, viewport: ViewportId, window: &WindowKey, toast: T
let live = queue.window(window);
live.push(Live { card: Card { id, toast }, shown: false, remaining, held: false, fresh: false });
while live.len() > MAX_CARDS {
// The new card is last and never the one dropped; a kept card has no timer, so it counts as sticky.
let earlier = live.len() - 1;
let at = live.iter().take(earlier).position(Live::leaves_by_itself).unwrap_or(0);
// The new card is last and never the one dropped; a kept card has no timer, so it counts as sticky. A
// progress card stands for a running job and is never dropped.
let earlier = &live[..live.len() - 1];
let at = earlier
.iter()
.position(Live::leaves_by_itself)
.or_else(|| earlier.iter().position(|live| live.card.toast.progress.is_none()));
let Some(at) = at else { break };
dropped.push(live.remove(at).card.id);
}
for dropped in dropped {
+43
View File
@@ -153,6 +153,49 @@ fn the_cap_drops_a_card_that_would_leave_by_itself_and_reports_it() {
assert!(ends.borrow().contains(&NoticeEnd::Dropped(notice)), "the center reports its notice dropped: {:?}", ends.borrow());
}
/// Past the cap a progress card stays: with only sticky cards beside it the oldest sticky card goes, and with only
/// progress cards earlier the new card is queued past the cap. `set_progress` moves the live card's fraction and
/// message, and its Cancel action ends it as an action.
#[trial]
fn the_cap_never_drops_a_progress_card() {
use craft_ui::runtime::toast::{ToastAction, ToastEnd};
let window = WindowKey::new("toast-progress-shell");
let shell = window.clone();
let mut fixture = Fixture::new(move |ui| {
AppShell::embedded(shell.clone()).body(|_, _, _| {}).show(ui, &mut ());
});
fixture.room(egui::Vec2::new(800.0, 600.0));
fixture.settle();
let ctx = fixture.ctx().clone();
let ids = |ctx: &egui::Context, window: &WindowKey| toast::cards(ctx, window).iter().map(|card| card.id).collect::<Vec<_>>();
let job = toast::post(&ctx, &window, Toast::new("Page 1 of 4").title("Exporting").progress(0.25).action(ToastAction::new("Cancel")));
let first = toast::post(&ctx, &window, Toast::new("The disk is full.").timeout(None));
let second = toast::post(&ctx, &window, Toast::new("The font is missing.").timeout(None));
let newest = toast::post(&ctx, &window, Toast::new("The profile is missing.").timeout(None));
fixture.settle();
assert_eq!(ids(&ctx, &window), vec![job, second, newest], "the oldest sticky card made room; the progress card stays");
assert_eq!(toast::end(&ctx, first), Some(ToastEnd::Dropped), "the oldest plain card was dropped");
assert_eq!(toast::end(&ctx, job), None, "the progress card has not ended");
let jobs = WindowKey::new("toast-progress-only");
let posted: Vec<_> = (0..=toast::MAX_CARDS).map(|n| toast::post(&ctx, &jobs, Toast::new(format!("Job {n}")).progress(0.0))).collect();
assert_eq!(ids(&ctx, &jobs), posted, "with only progress cards none is dropped, past the cap");
toast::set_progress(&ctx, job, 0.5, Some("Page 2 of 4".into()));
fixture.settle();
let card = toast::cards(&ctx, &window).into_iter().find(|card| card.id == job).expect("the progress card is queued");
assert_eq!(card.toast.progress, Some(0.5), "the fraction moved");
assert_eq!(card.toast.message, Toast::new("Page 2 of 4").message, "the message moved");
assert!(fixture.texts().iter().any(|painted| painted.text == "Page 2 of 4"), "the card shows the new message");
let cancel = fixture.texts().iter().find(|painted| painted.text == "Cancel").map(|painted| painted.rect.center()).expect("Cancel shows");
fixture.click_at(cancel);
fixture.settle();
assert!(!ids(&ctx, &window).contains(&job), "Cancel ended the card");
assert_eq!(toast::end(&ctx, job), Some(ToastEnd::Action(0)), "it ended by its first action");
}
/// A card the pointer rests on for longer than its timeout, with no pass running meanwhile, gets its whole timeout
/// again when the pointer leaves: the pass that sees the pointer go, run twice in its frame, counts none of the hover
/// against it. It expires one full timeout after the leave.
+45 -18
View File
@@ -101,9 +101,34 @@ impl Outcome for NoticeCenterOutput {
}
}
/// The notices the center posted that have not ended, with their dismiss keys.
/// A notice the center posted and has not heard the end of.
#[derive(Clone)]
struct Tracked {
id: ToastId,
/// The notice's dismiss key: its card then ends with a "Don't Show Again" action.
key: Option<String>,
/// The notice has its own action, the card's first.
action: bool,
}
impl Tracked {
/// What the app hears of the card's `end`. The card's actions are the notice's own action, if any, then "Don't
/// Show Again", if it has a dismiss key.
fn end(&self, end: ToastEnd) -> NoticeEnd {
let id = self.id;
match (end, &self.key) {
(ToastEnd::Action(0), _) if self.action => NoticeEnd::Action(id),
(ToastEnd::Action(_), Some(key)) => NoticeEnd::Silenced { id, key: key.clone() },
(ToastEnd::Action(_) | ToastEnd::Dismissed, _) => NoticeEnd::Closed(id),
(ToastEnd::Expired, _) => NoticeEnd::Expired(id),
(ToastEnd::Dropped, _) => NoticeEnd::Dropped(id),
}
}
}
/// The notices the center posted that have not ended.
#[derive(Clone, Default)]
struct Posted(Vec<(ToastId, Option<String>)>);
struct Posted(Vec<Tracked>);
fn posted_slot() -> egui::Id {
unique("craft_ui.notice_center")
@@ -112,9 +137,9 @@ fn posted_slot() -> egui::Id {
/// The app's way to post notices to a window. It holds only the window and its timeout: the queue, the timers, the
/// hover pause and the announcement are the toast service's. So is the cap of `toast::MAX_CARDS` cards: a new notice
/// always shows, and makes room by dropping the oldest earlier card that would leave by itself (no action, a timeout),
/// else the oldest; `show` reports a dropped notice as `NoticeEnd::Dropped`. A body posts to its shell's window
/// (`BodyCx::shell`). A notice with a dismiss key shows a "Don't Show Again" action; `show` reports how posted notices
/// ended.
/// else the oldest without progress; a progress notice is never dropped. `show` reports a dropped notice as
/// `NoticeEnd::Dropped`. A body posts to its shell's window (`BodyCx::shell`). A notice's own action comes first on its
/// card and a dismiss key's "Don't Show Again" last; `show` reports how posted notices ended.
#[derive(Clone, Debug, PartialEq, crate::contract::Pattern, crate::contract::Props)]
pub struct NoticeCenter {
/// The window whose toasts show the notices.
@@ -138,7 +163,8 @@ impl NoticeCenter {
}
/// Posts `notice` to the center's window in the running viewport; `None` when its dismiss key is in `silenced`, and
/// in a measuring run, which posts nothing and tracks nothing (the real run posts it).
/// in a measuring run, which posts nothing and tracks nothing (the real run posts it). A notice with progress has no
/// timer.
pub fn post(&self, ctx: &Context, notice: &PostedNotice, silenced: &[String]) -> Option<ToastId> {
if notice.dismiss_key.as_ref().is_some_and(|key| silenced.contains(key)) {
return None;
@@ -148,14 +174,21 @@ impl NoticeCenter {
}
let politeness = if notice.tone == Tone::Bad { Politeness::Assertive } else { Politeness::Polite };
let timeout = if notice.sticky { None } else { self.timeout };
let mut card = Toast::new(Label::Empty).title(notice.title.clone()).lines(notice.lines.clone());
let message = notice.message.clone().map_or(Label::Empty, Label::from);
let mut card = Toast::new(message).title(notice.title.clone()).lines(notice.lines.clone());
card = card.tone(notice.tone).timeout(timeout).politeness(politeness);
if let Some(fraction) = notice.progress {
card = card.progress(fraction);
}
if let Some(action) = &notice.action {
card = card.action(ToastAction::new(action.clone()));
}
if notice.dismiss_key.is_some() {
card = card.action(ToastAction::new(dont_show_again()));
}
let id = toast::post(ctx, &self.window, card);
with_session(ctx, posted_slot(), |posted: &mut Posted| {
posted.0.push((id, notice.dismiss_key.clone()));
posted.0.push(Tracked { id, key: notice.dismiss_key.clone(), action: notice.action.is_some() });
if posted.0.len() > TRACKED {
posted.0.remove(0);
}
@@ -171,8 +204,7 @@ impl NoticeCenter {
/// Sets how far the job of notice `id` has got, `fraction` between 0 and 1, and its message; the center keeps
/// tracking the id.
pub fn set_progress(&self, ctx: &Context, id: ToastId, fraction: f32, message: Option<Label>) {
let _ = (ctx, id, fraction, message);
todo!("CH-C16")
toast::set_progress(ctx, id, fraction, message);
}
/// Removes a notice the app no longer needs (the job it reported on was cancelled).
@@ -185,14 +217,9 @@ impl NoticeCenter {
let ctx = ui.ctx().clone();
let mut ends = Vec::new();
with_session(&ctx, posted_slot(), |posted: &mut Posted| {
posted.0.retain(|(id, key)| {
let Some(end) = toast::end(&ctx, *id) else { return true };
ends.push(match (end, key) {
(ToastEnd::Action(_), Some(key)) => NoticeEnd::Silenced { id: *id, key: key.clone() },
(ToastEnd::Action(_) | ToastEnd::Dismissed, _) => NoticeEnd::Closed(*id),
(ToastEnd::Expired, _) => NoticeEnd::Expired(*id),
(ToastEnd::Dropped, _) => NoticeEnd::Dropped(*id),
});
posted.0.retain(|tracked| {
let Some(end) = toast::end(&ctx, tracked.id) else { return true };
ends.push(tracked.end(end));
false
});
});
+19 -15
View File
@@ -205,7 +205,8 @@ pub struct Notice<'a> {
announce: Option<Politeness>,
actions: Vec<NoticeAction>,
lines: Vec<Label>,
/// The host's leaves under the actions of a centred notice, and their sizes in this pass.
/// The host's leaves: under the actions of a centred notice, between the bullet lines and the actions of an inline
/// or card notice; and their sizes in this pass.
content: Vec<Box<dyn for<'r> Hosted<Notice<'r>> + 'a>>,
content_sizes: Vec<Vec2>,
placed: Option<Placed>,
@@ -304,22 +305,18 @@ impl<'a> Notice<'a> {
self
}
/// Hosts `component` under the actions of a centred notice, after the leaves added before it; its output goes to
/// `output` in the pass it is shown. Other layouts show no hosted leaves.
/// Hosts `component` after the leaves added before it: under the actions of a centred notice, and in an inline or
/// card notice under the message and its bullet lines, before the actions, across the whole width. Its output goes
/// to `output` in the pass it is shown.
#[must_use]
pub fn content<C: Show + 'a>(mut self, component: C, output: impl FnOnce(C::Output) + 'a) -> Self {
self.content.push(Box::new(Hosting::new(component, output)));
self
}
/// Measures the hosted leaves for this pass; only a centred notice shows them.
/// Measures the hosted leaves for this pass.
fn measure_content(&mut self, cx: &MeasureCx<'_, Self>) {
let centred = !self.row();
self.content_sizes = if centred {
self.content.iter_mut().enumerate().map(|(at, item)| item.measure(cx, (CONTENT, at), Proposal::Ideal)).collect()
} else {
Vec::new()
};
self.content_sizes = self.content.iter_mut().enumerate().map(|(at, item)| item.measure(cx, (CONTENT, at), Proposal::Ideal)).collect();
}
fn texts<'t>(&self, env: &EnvView<'_>, words: &NoticeWords, format: &Format, message: &'t str) -> Texts<'t> {
@@ -420,18 +417,20 @@ impl<'a> Notice<'a> {
let more = texts.more.as_deref().map(|more| cx.layout_at(&self.run(more, cx.style.more.role), width).size());
let stack = cx.style.stack;
let actions_width = actions.iter().map(|size| size.x).sum::<f32>() + gap * actions.len().saturating_sub(1) as f32;
// In a row layout the lines and the actions run from the content's start edge, under the icon.
let below_width = if row { actions_width } else { 0.0 };
let content_width = self.content_sizes.iter().map(|size| size.x).fold(0.0, f32::max);
// In a row layout the lines, the hosted leaves and the actions run from the content's start edge, under the icon.
let below_width = if row { actions_width.max(content_width) } else { 0.0 };
let lines_width = line_sizes.iter().map(|size| size.x + bullet).fold(more.map_or(below_width, |size| size.x.max(below_width)), f32::max);
let lines_height = line_sizes.iter().chain(more.iter()).map(|size| stack + size.y).sum::<f32>();
let leaves_height = self.content_sizes.iter().map(|size| stack + size.y).sum::<f32>();
let stacked = !row && column.is_finite() && actions_width > column;
let actions_height = if stacked {
actions.iter().map(|size| size.y).sum::<f32>() + gap * actions.len().saturating_sub(1) as f32
} else {
actions.iter().map(|size| size.y).fold(0.0, f32::max)
};
let content_width = self.content_sizes.iter().map(|size| size.x).fold(0.0, f32::max);
let text_width = title.map_or(0.0, |size| size.x).max(message.x).max(actions_width - below_width).max(content_width);
let column_width = if row { 0.0 } else { actions_width.max(content_width) };
let text_width = title.map_or(0.0, |size| size.x).max(message.x).max(column_width);
// The head line: the icon, the first line of the text and the dismiss button share its centre line.
let first_role = match (&texts.title, texts.message.is_empty()) {
(Some(_), _) => Some(title_role),
@@ -443,7 +442,7 @@ impl<'a> Notice<'a> {
let text_offset = (line - first) / 2.0;
// Lines and actions start under the head line.
let head = (text_offset + title.map_or(0.0, |size| size.y) + message.y).max(line);
let with_actions = head + lines_height + if actions.is_empty() { 0.0 } else { stack.max(gap) + actions_height };
let with_actions = head + lines_height + leaves_height + if actions.is_empty() { 0.0 } else { stack.max(gap) + actions_height };
let (needs, height) = if row {
((icon_width + text_width + dismiss_width).max(lines_width), with_actions)
} else {
@@ -623,6 +622,11 @@ impl Component for Notice<'_> {
placed.more = Some(Rect::from_min_size(Pos2::new(rect.left(), y), Vec2::new(rect.width(), height)));
y += height;
}
for size in &self.content_sizes {
y += stack;
placed.content.push(Rect::from_min_size(Pos2::new(rect.left(), y), Vec2::new(rect.width(), size.y)));
y += size.y;
}
y += stack.max(gap);
let mut line = Flow::new(Rect::from_min_size(Pos2::new(rect.left(), y), Vec2::new(rect.width(), (rect.bottom() - y).max(0.0))), rtl);
for size in &plan.actions {
+43 -1
View File
@@ -4,7 +4,8 @@ use super::{
Notice, NoticeAction, NoticeCenter, NoticeIcon, NoticeLayout, PostedNotice, SaveResult, SettingsLoad, SettingsNoticeState, SettingsNotices,
ToastStack,
};
use crate::contract::{Politeness, Show as _};
use crate::buttons::Button;
use crate::contract::{Politeness, Show as _, clicked};
use crate::display::{Shade, Text};
use crate::primitives::IconSpec;
use crate::runtime::env::{Label, WindowKey};
@@ -111,6 +112,27 @@ fn notice_center(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
NoticeCenter::new().window(window).show(ui).into()
}
/// A notice with a title, a message, its own action and Don't Show Again in the bottom corner of the story's stage. It
/// stays until closed, and comes back once closed.
#[story(NoticeCenter, covers = [], drive = Drive::Never)]
fn notice_center_with_message(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let ctx = ui.ctx().clone();
let window = WindowKey::new("notice-center-message-story");
if toast::cards(&ctx, &window).is_empty() {
let center = NoticeCenter::new().window(window.clone());
let notice = PostedNotice::new("Form submitted")
.message("The server accepted all 12 fields.")
.action("Show Response")
.tone(Tone::Good)
.dismiss_key("form-submitted".to_owned())
.sticky();
let _ = center.post(&ctx, &notice, &[]);
}
let area = stage(ui);
ToastStack::show(ui, &window, area);
NoticeCenter::new().window(window).show(ui).into()
}
/// A neutral toast, a warning with ten lines and an error in the bottom corner of the story's stage.
#[story(ToastStack, covers = [], drive = Drive::Never)]
fn toast_stack(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
@@ -127,3 +149,23 @@ fn toast_stack(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
ToastStack::show(ui, &window, area);
Text::new("Toasts").show(ui).into()
}
/// A plain toast in the bottom corner of the story's stage; the button posts a progress card with Cancel under it,
/// and Cancel ends that card.
#[story(ToastStack, covers = [], drive = Drive::Never)]
fn toast_stack_progress(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let ctx = ui.ctx().clone();
let window = WindowKey::new("toast-stack-progress-story");
let cards = toast::cards(&ctx, &window);
if cards.is_empty() {
toast::post(&ctx, &window, toast::Toast::new(Label::Empty).title("Pasted from the clipboard").timeout(None));
}
let running = cards.iter().any(|card| card.toast.progress.is_some());
if clicked(&Button::new("Export").show(ui)) && !running {
let job = toast::Toast::new("Page 3 of 8").title("Exporting poster.pdf").progress(0.375).action(toast::ToastAction::new("Cancel"));
toast::post(&ctx, &window, job);
}
let area = stage(ui);
ToastStack::show(ui, &window, area);
Text::new("Toasts").show(ui).into()
}
+13 -2
View File
@@ -2,12 +2,15 @@
use crate::contract::toast::{CardOutcome, ToastHost};
use crate::contract::{Props as _, Show as _};
use crate::display::{Progress, Shade, Text};
use crate::notices::{Notice, NoticeAction, NoticeLayout};
use crate::runtime::env::WindowKey;
use crate::runtime::env::{Env, WindowKey};
use crate::runtime::toast::ToastEnd;
use crate::style::TypeRole;
use egui::{Rect, Ui};
/// The cards of a window's toast queue. Whoever owns the window root calls `show` once per pass.
/// The cards of a window's toast queue. Whoever owns the window root calls `show` once per pass. A card with progress
/// shows a progress bar named by its title (else its message) and the percentage under its text, before its actions.
#[derive(Clone, Copy, Debug, Default, crate::contract::Pattern)]
pub struct ToastStack;
@@ -21,6 +24,14 @@ impl ToastStack {
if let Some(title) = &toast.title {
notice = notice.title(title.clone());
}
if let Some(fraction) = toast.progress {
// The bar and the percentage read as `StatusProgress` shows a task's progress.
let name = toast.title.clone().unwrap_or_else(|| toast.message.clone());
let percent = Env::of(ui).format().percent(f64::from(Progress::clamped(fraction)), 0);
notice = notice
.content(Progress::new(fraction).label(name), |_| {})
.content(Text::new(percent).role(TypeRole::Mono).shade(Shade::Muted), |_| {});
}
for action in &toast.actions {
notice = notice.action(NoticeAction::new(action.label.clone()));
}