Merge review-2449-a fixes (CodeRabbit review of #2449: closing, dialogs, files, web presenter)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Dylan M. Taylor
2026-11-30 17:05:49 +00:00
co-authored by Claude Opus 5.5
15 changed files with 335 additions and 34 deletions
+9 -1
View File
@@ -10,7 +10,7 @@ use craft::ui::runtime::frame::FrameInput;
use craft::ui::shell::{AppShell, embed};
use craft::web_host::link::{LinkLimits, LinkState, WindowLink};
use craft::web_host::popup::{PopupOpener, PopupPeer};
use deckcraft_ui_egui::presenter::{Preview, Snapshot, SnapshotDelta, merge};
use deckcraft_ui_egui::presenter::{Command, Preview, Snapshot, SnapshotDelta, merge};
// PLAN: assumed pub const SHOW_SCOPE: craft::ui::runtime::commands::CommandScope in presenter_view (show-w7)
use deckcraft_ui_egui::presenter_view::{NextPic, PresenterModel, PreviewPic, SHOW_SCOPE, presenter_body};
use deckcraft_ui_egui::show::{Blank, GridSource};
@@ -46,6 +46,8 @@ enum Picture {
pub struct PopupApp {
peer: PopupPeer,
snapshot: Option<Snapshot>,
/// The number of the last delta received.
seq: Option<u64>,
textures: TextureStore<Picture>,
current_revision: u64,
next_revision: u64,
@@ -65,6 +67,7 @@ impl PopupApp {
Ok(Self {
peer,
snapshot: None,
seq: None,
textures: TextureStore::in_context(ctx, "deckcraft.popup", TextureStoreOptions::frames()),
current_revision: 0,
next_revision: 0,
@@ -76,6 +79,11 @@ impl PopupApp {
// take drains only this pass's arrivals; a second pass sees no replay of earlier deltas.
for payload in self.peer.take() {
let Some(delta) = SnapshotDelta::from_payload(&payload) else { continue };
if self.seq.is_some_and(|seq| delta.seq != seq.wrapping_add(1)) {
// A full inbox dropped a delta, which may have carried an image: ask for every image again.
let _ = self.peer.post(&Command::Resync.to_payload());
}
self.seq = Some(delta.seq);
if delta.current_changed {
self.current_revision = self.current_revision.wrapping_add(1);
self.textures.forget(ctx, &Picture::Current);
+6 -3
View File
@@ -1393,11 +1393,10 @@ impl OutlinePen for FlipPen {
#[cfg(test)]
mod font_dir_tests {
use std::path::Path;
use super::*;
fn assert_fixture_discovered_after_rescan(env: FontEnv, directory: &Path) {
#[cfg(unix)]
fn assert_fixture_discovered_after_rescan(env: FontEnv, directory: &std::path::Path) {
let catalog = Arc::new(Catalog::new(env.clone()).with_font_service(false));
catalog.set_confined_dirs(vec![env.root]);
let db = FontDb::with_catalog(catalog.clone(), CatalogScope::Isolated);
@@ -1519,7 +1518,9 @@ mod font_dir_tests {
assert_eq!(cache.elements, before);
}
// The catalogue keeps only host-absolute XDG entries, and `/nix/…` is absolute only on a Unix host.
#[test]
#[cfg(unix)]
fn xdg_data_dirs_contribute_their_fonts_folders() {
let root = std::env::temp_dir().join(format!("deckcraft-fonts-xdg-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
@@ -1541,7 +1542,9 @@ mod font_dir_tests {
let _ = std::fs::remove_dir_all(root);
}
// A `<dir>` of `/…` is absolute only on a Unix host; elsewhere it joins the configuration's folder.
#[test]
#[cfg(unix)]
fn fontconfig_dir_entries_are_read() {
let conf = r#"<?xml version="1.0"?>
<fontconfig>
+8 -2
View File
@@ -1,4 +1,5 @@
use super::catalog::{START_SCREEN, edit_command_of, is_ui_command};
use super::files::SaveOutcome;
#[cfg(not(target_arch = "wasm32"))]
use super::updates_ui;
use super::{SlideApp, Value, ViewMode, backstage, doc_window, json, media, qat};
@@ -32,14 +33,19 @@ impl SlideApp {
} else if id == "file.save" && self.host.files().saves_to_page() && params.get("path").is_none() {
match self.session.active() {
Some(d) => {
let uid = d.uid;
let name = d
.path
.as_deref()
.and_then(|path| std::path::Path::new(path).file_name())
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| format!("{}.deckcraft", d.title()));
self.save();
Ok(json!({"path": name}))
match self.save_document(uid) {
SaveOutcome::Saved | SaveOutcome::Downloaded => Ok(json!({"path": name})),
SaveOutcome::Pending => Ok(json!({"path": name, "pending": true})),
SaveOutcome::Cancelled => Err("The save was cancelled".into()),
SaveOutcome::Failed(reason) => Err(reason),
}
}
None => Err("no presentation is open".into()),
}
+1
View File
@@ -400,6 +400,7 @@ fn host_save_as_under_the_same_name_returns_to_the_slide() {
h.state().backstage.as_ref().is_some_and(|view| Arc::ptr_eq(&view.instance, &replacement)),
"an old success cannot close a new File view"
);
assert!(h.state().session.active().unwrap().path.is_some(), "the old save still completed");
}
#[test]
+150 -13
View File
@@ -1,8 +1,11 @@
//! Coordinates document save questions with the root window's close decision.
use std::sync::Arc;
use craft::quit::{CloseAnswer, CloseGuard, CloseScope, GuardStep};
use craft::ui::dialog::{DialogHost, DialogId, StackDialog, UnsavedChangesDialog};
use craft::ui::runtime::windows::{WindowAction, WindowHost};
use deckcraft_model::Presentation;
use egui::{Context, ViewportId};
use serde_json::json;
@@ -54,6 +57,7 @@ pub(crate) fn pump(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost) {
step = match step {
GuardStep::Save(uid) => {
closing.pending_uid = Some(uid);
closing.pending_snapshot = live_snapshot(app, uid);
app.dialogs.closing = Some(closing);
let outcome = app.save_document(uid);
app.save_settled(uid, outcome);
@@ -64,14 +68,13 @@ pub(crate) fn pump(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost) {
next
}
GuardStep::Discard(uid) => {
let result = if closing.scope == CloseScope::Close {
close_document(app, uid)
} else if app.session.recovery_dir.is_some() {
app.session.execute("file.recovery.discard", &json!({"uid": uid})).map(|_| ()).map_err(|error| error.to_string())
} else {
Ok(())
};
if let Err(reason) = result {
if closing.scope != CloseScope::Close {
// Recovery stays until the Quit commits: a later Cancel keeps this presentation open.
if let Some(doc) = live_snapshot(app, uid) {
closing.answered.push(Answered { uid, doc, discard: true });
}
closing.guard.discarded()
} else if let Err(reason) = close_document(app, uid) {
app.set_status(reason);
closing.guard.save_failed()
} else {
@@ -100,6 +103,27 @@ pub(crate) fn pump(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost) {
if closing.scope != CloseScope::Quit {
return;
}
// A presentation changed while the questions were open (a script, another window) gets its own
// question; one still in the state it was answered for is not asked again.
let unanswered: Vec<u64> = app
.session
.documents()
.iter()
.filter(|doc| doc.is_dirty() && !closing.answered.iter().any(|a| a.uid == doc.uid && Arc::ptr_eq(&a.doc, &doc.doc)))
.map(|doc| doc.uid)
.collect();
if !unanswered.is_empty() {
closing.guard = CloseGuard::new(CloseScope::Quit, unanswered);
step = closing.guard.current().copied().map_or(GuardStep::Finished, GuardStep::Ask);
continue;
}
if app.session.recovery_dir.is_some() {
for uid in closing.answered.iter().filter(|a| a.discard).map(|a| a.uid) {
if let Err(error) = app.session.execute("file.recovery.discard", &json!({"uid": uid})) {
app.set_status(error.to_string());
}
}
}
// Retain permission after issuing Close, without issuing it again next pass.
closing.asked = true;
app.dialogs.closing = Some(closing);
@@ -117,8 +141,20 @@ pub(crate) struct Closing {
scope: CloseScope,
asked: bool,
pending_uid: Option<u64>,
/// The document state the pending save serialized: its outcome covers that state, not a later edit.
pending_snapshot: Option<Arc<Presentation>>,
completion: Option<(u64, SaveOutcome)>,
reason: Option<String>,
/// Quit's settled answers, each for the document state it was given for.
answered: Vec<Answered>,
}
/// A Quit answer that lets a document close while it stays in the answered state.
struct Answered {
uid: u64,
doc: Arc<Presentation>,
/// Don't Save: its recovery files go when the Quit commits.
discard: bool,
}
impl SlideApp {
@@ -129,8 +165,16 @@ impl SlideApp {
return;
}
self.show = None;
self.dialogs.closing =
Some(Closing { guard: CloseGuard::new(scope, uids), scope, asked: false, pending_uid: None, completion: None, reason: None });
self.dialogs.closing = Some(Closing {
guard: CloseGuard::new(scope, uids),
scope,
asked: false,
pending_uid: None,
pending_snapshot: None,
completion: None,
reason: None,
answered: Vec::new(),
});
}
/// Whether clean documents or a completed, uncancelled Quit guard allow the window to close.
@@ -156,11 +200,12 @@ impl Closing {
fn completion_step(app: &mut SlideApp, closing: &mut Closing) -> Option<GuardStep<u64>> {
let (uid, outcome) = closing.completion.take()?;
closing.pending_uid = None;
let snapshot = closing.pending_snapshot.take();
Some(match outcome {
SaveOutcome::Saved | SaveOutcome::Downloaded => {
let doc = app.session.documents().iter().find(|doc| doc.uid == uid);
if matches!(outcome, SaveOutcome::Saved) && doc.is_some_and(|doc| doc.is_dirty()) {
// Saved refers to the serialized snapshot; a later edit still needs an answer.
let live = live_snapshot(app, uid);
if live.as_ref().is_some_and(|live| snapshot.as_ref().is_none_or(|snapshot| !Arc::ptr_eq(live, snapshot))) {
// The file or download holds the serialized snapshot; a later edit still needs an answer.
closing.guard.retry_after_failure()
} else if closing.scope == CloseScope::Close {
match close_document(app, uid) {
@@ -171,6 +216,9 @@ fn completion_step(app: &mut SlideApp, closing: &mut Closing) -> Option<GuardSte
}
}
} else {
if let Some(doc) = live {
closing.answered.push(Answered { uid, doc, discard: false });
}
closing.guard.saved()
}
}
@@ -183,6 +231,11 @@ fn completion_step(app: &mut SlideApp, closing: &mut Closing) -> Option<GuardSte
})
}
/// The document's current state, absent once it is closed.
fn live_snapshot(app: &SlideApp, uid: u64) -> Option<Arc<Presentation>> {
app.session.documents().iter().find(|doc| doc.uid == uid).map(|doc| doc.doc.clone())
}
fn close_document(app: &mut SlideApp, uid: u64) -> Result<(), String> {
let Some(index) = app.session.documents().iter().position(|doc| doc.uid == uid) else { return Ok(()) };
let previous = app.session.active().map(|doc| doc.uid);
@@ -263,6 +316,90 @@ mod tests {
assert_eq!(h.state_mut().close_decision(), CloseDecision::Close);
}
fn two_unsaved() -> (Session, Vec<u64>) {
let mut session = Session::new();
for title in ["First", "Second"] {
session.execute("file.new", &json!({})).unwrap();
session.execute("file.properties", &json!({"title": title})).unwrap();
}
let uids = session.documents().iter().map(|doc| doc.uid).collect();
(session, uids)
}
/// The bug this prevents: Don't Save for the first presentation deleted its recovery files at once, so a Cancel
/// for the second left it open with nothing to recover after a crash.
#[test]
fn a_cancelled_quit_keeps_the_recovery_of_a_presentation_answered_dont_save() {
let (mut session, uids) = two_unsaved();
let dir = std::env::temp_dir().join(format!("deckcraft-closing-recovery-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
session.recovery_dir = Some(dir.clone());
deckcraft_engine::recovery::save(&session, &dir).unwrap();
let recoverable = || deckcraft_engine::recovery::list(&dir).into_iter().map(|(uid, _)| uid).collect::<Vec<_>>();
let mut h = harness(session, Services::default());
h.state_mut().start_closing(CloseScope::Quit, uids.clone());
h.run_steps(4);
answer(&h, Some(CloseAnswer::DontSave));
h.run_steps(4);
answer(&h, None);
h.run_steps(4);
assert!(recoverable().contains(&uids[0]), "the Quit was cancelled, so the presentation stays recoverable");
h.state_mut().start_closing(CloseScope::Quit, uids.clone());
h.run_steps(4);
answer(&h, Some(CloseAnswer::DontSave));
h.run_steps(4);
answer(&h, Some(CloseAnswer::DontSave));
h.run_steps(4);
assert!(h.state().quit_allowed());
assert!(!uids.iter().any(|uid| recoverable().contains(uid)), "a Quit that goes through discards what was not saved");
let _ = std::fs::remove_dir_all(&dir);
}
/// The bug this prevents: a presentation changed by a script while Quit's question about another one was open
/// closed with its changes, never asked about.
#[test]
fn a_presentation_changed_during_quit_is_asked_about() {
let (mut session, uids) = two_unsaved();
let second = session.documents()[1].doc.clone();
deckcraft_engine::cmd::file::mark_saved_snapshot(&mut session, uids[1], second, None).unwrap();
session.set_active(1);
let mut h = harness(session, Services::default());
h.state_mut().start_closing(CloseScope::Quit, vec![uids[0]]);
h.run_steps(4);
h.state_mut().session.execute("file.properties", &json!({"title": "Changed"})).unwrap();
answer(&h, Some(CloseAnswer::DontSave));
h.run_steps(4);
assert!(!h.state().quit_allowed(), "the changed presentation has not been answered for");
assert_eq!(h.state().dialogs.closing.as_ref().unwrap().guard.current(), Some(&uids[1]));
answer(&h, Some(CloseAnswer::DontSave));
h.run_steps(4);
assert!(h.state().quit_allowed(), "the first answer still holds for the unchanged presentation");
}
/// The bug this prevents: Save in the Close question on the web closed the presentation when its download
/// finished, losing an edit made while the download was pending.
#[test]
fn a_download_does_not_close_a_presentation_edited_after_it_started() {
let files = Arc::new(craft::host::ScriptedFiles::held().in_browser());
let installed = files.clone();
let mut h = crate::test_harness::harness_with(Session::with_new(), Services::default(), egui_kittest::Harness::builder(), move |platform| {
platform.host = platform.host.with_files(installed)
});
h.state_mut().session.execute("slide.new", &json!({})).unwrap();
let uid = h.state().session.active().unwrap().uid;
h.state_mut().start_closing(CloseScope::Close, vec![uid]);
h.run_steps(4);
answer(&h, Some(CloseAnswer::Save));
h.run_steps(4);
let ticket = h.state().pending_files.last().expect("the download waits").ticket;
h.state_mut().session.execute("slide.new", &json!({})).unwrap();
files.answer_to(ticket, craft::host::Picked::Downloaded("Presentation.deckcraft".into()));
h.run_steps(4);
assert!(h.state().session.documents().iter().any(|doc| doc.uid == uid), "the later edit keeps the presentation open");
assert!(crate::dialogs::top_dialog(&h.ctx).is_some(), "the later edit is asked about");
}
/// The `close` dialog key asks about the active presentation alone, and only when it has unsaved changes.
#[test]
fn the_close_key_asks_about_the_active_unsaved_presentation() {
@@ -94,6 +94,16 @@ fn a_field_left_as_shown_keeps_each_text_box_s_own_value() {
assert_eq!(columns_of_each(&h), before);
}
/// The bug this prevents: opening Columns with the earlier dialog's `spacing` in inches applied that number in points.
#[test]
fn an_opening_spacing_is_in_inches() {
let mut h = harness();
dialog_method(&mut h, "ui.dialog.open", json!({"id": "columns", "fields": {"spacing": 0.5}}));
h.run_steps(2);
confirm(&mut h);
assert_eq!(columns_of(&h).1, Some(0.5 * 72.0));
}
fn field(h: &Harness<'_, SlideApp>, key: &str) -> Option<Value> {
super::inspect(&h.ctx).as_array()?.iter().find(|dialog| dialog["key"] == "columns")?.get("fields")?.get(key).cloned()
}
@@ -69,6 +69,19 @@ fn paragraph_button_aligns_text_in_one_undo() {
assert_eq!(h.state().session.active().unwrap().history.undo.len(), undo);
}
/// The bug this prevents: opening Paragraph with the fields the earlier dialog took (`before` in inches, `align:
/// right`) was refused or set the indent in points.
#[test]
fn opening_fields_as_the_earlier_dialog_took_them_apply() {
let mut h = harness();
dialog(&mut h, "ui.dialog.open", json!({"id": "paragraph", "fields": {"before": "0.5", "align": "right"}}));
dialog(&mut h, "ui.dialog.confirm", json!({"dialog": "top"}));
assert!(super::open_keys(&h.ctx).is_empty(), "status {:?}", h.state().status);
assert_eq!(align_of(&h).as_deref(), Some(deckcraft_model::text::Align::Right.xml()));
let st = h.state().session.active().unwrap();
assert_eq!(st.selected_shapes()[0].text.as_ref().unwrap().paragraphs[0].props.margin_left, Some(0.5 * 72.0));
}
/// Paragraph-dialog tab settings apply the chosen stop and return to the paragraph controls.
#[test]
fn tabs_from_paragraph_applies_a_stop_and_returns() {
+8 -3
View File
@@ -114,6 +114,7 @@ pub(crate) fn open(app: &SlideApp, ctx: &egui::Context, params: &Value) -> Hoste
let album = params.get("album").and_then(album_json_id).and_then(|id| i64::try_from(id).ok()).unwrap_or(0);
fields.set("album", album);
let editing = params.get("items").is_some();
fields.set("editing", editing);
HostedParamDialog::new(ctx, "photoAlbum", fields, move |fields| {
let list = Param::custom("items", "Pictures in album", |ui, fields, context| {
Stack::new()
@@ -263,6 +264,7 @@ pub(crate) fn open(app: &SlideApp, ctx: &egui::Context, params: &Value) -> Hoste
Param::new("grayscale", "ALL pictures black and white", ParamKind::bool(false)),
choice("theme", "Album theme", "DeckCraft", &ALBUM_THEMES.iter().map(|name| (*name, *name)).collect::<Vec<_>>()),
Param::new("album", "Album", ParamKind::int(None, None, 0)).shown(false),
Param::new("editing", "Editing an album", ParamKind::bool(false)).shown(false),
Param::new("themeWas", "Opening theme", ParamKind::text("")).shown(false),
];
ParamDialog::new("photoAlbum", "Photo Album", rows)
@@ -371,9 +373,12 @@ pub(crate) fn finish(app: &mut SlideApp, result: &ParamResult, _host: &mut Dialo
if Some(theme) != fields.text("themeWas") {
payload["theme"] = json!(theme);
}
let album = fields.int("album").filter(|id| *id > 0);
if let Some(album) = album {
if !fields.bool("editing").unwrap_or(false) {
return app.run("insert.photoAlbum", payload).map(|_| ());
}
// An album from before albums had ids has none: the engine finds the selected run of album slides.
if let Some(album) = fields.int("album").filter(|id| *id > 0) {
payload["album"] = json!(album);
}
app.run(if album.is_some() { "insert.photoAlbumEdit" } else { "insert.photoAlbum" }, payload).map(|_| ())
app.run("insert.photoAlbumEdit", payload).map(|_| ())
}
@@ -151,6 +151,38 @@ fn update_reflows_the_open_album() {
assert_eq!(slides(&h), expanded, "the last undo restores the original album");
}
/// The bug this prevents: Update on an album made before albums had ids (a run of slides named Photo Album) inserted a
/// second album and left the first in place.
#[test]
fn update_reflows_an_album_without_an_id() {
let data = deckcraft_engine::cmd::base64_encode(&png());
let pictures = json!([{"name": "hill.png", "data": data}, {"name": "lake.png", "data": data}]);
let mut h = harness_with(
Session::with_new(),
Services::default(),
Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_step_dt(1.0 / 60.0),
|_| {},
);
h.state_mut().run("insert.photoAlbum", json!({"pictures": pictures, "layout": "1"})).expect("create");
h.state_mut()
.session
.edit(|doc, _| {
for slide in &mut doc.slides {
std::sync::Arc::make_mut(slide).raw_ext = None;
}
Ok(())
})
.unwrap();
let expanded = slides(&h);
h.state_mut().run("insert.photoAlbumEdit", json!({})).expect("edit");
h.run_steps(3);
control(&mut h, "ui.dialog.set", json!({"dialog": "top", "field": "layout", "value": "2"}));
control(&mut h, "ui.dialog.confirm", json!({"dialog": "top"}));
h.run_steps(4);
assert!(super::open_keys(&h.ctx).is_empty(), "status {:?}", h.state().status);
assert!(slides(&h) < expanded, "the album reflowed in place");
}
#[test]
fn a_pick_left_open_by_a_closed_album_does_not_reach_the_next_album() {
for queued_before_cancel in [false, true] {
+42 -1
View File
@@ -7,7 +7,7 @@
use serde_json::{Value, json};
/// The opener parameters of dialog `id`, with the fields that choose how it opens taken out of `fields`: the tab
/// Bullets and Action Settings open on.
/// Bullets and Action Settings open on. The opening fields the earlier dialogs took become the hosted dialogs' own.
pub(super) fn opener(id: &str, params: &Value, fields: &mut Vec<(String, Value)>) -> Value {
let mut params = if params.is_object() { params.clone() } else { json!({}) };
if matches!(id, "bullets" | "action")
@@ -15,9 +15,50 @@ pub(super) fn opener(id: &str, params: &Value, fields: &mut Vec<(String, Value)>
{
params["tab"] = fields.remove(at).1;
}
for (field, value) in fields.iter_mut() {
let (name, translated) = opening_field(id, field, value.take());
*field = name;
*value = translated;
}
params
}
/// An opening field as the earlier dialogs named it, in the hosted dialog's name and unit: Columns' `spacing` and
/// Paragraph's `before`, `after` and `by` in inches, Paragraph's `align`, `special`, `spaceBefore` and `spaceAfter`.
/// A value that cannot be read goes as it is, for the dialog to refuse.
fn opening_field(id: &str, field: &str, value: Value) -> (String, Value) {
let inches = |value: Value| number(&value).map_or(value, |inches| json!(inches * 72.0));
let named = |value: Value, names: &[(&str, &str)]| match names.iter().find(|(old, _)| value.as_str() == Some(*old)) {
Some((_, name)) => json!(name),
None => value,
};
let (name, value) = match (id, field) {
("columns", "spacing") => (field, inches(value)),
("paragraph", "before") => ("before_text", inches(value)),
("paragraph", "after") => ("after_text", inches(value)),
("paragraph", "by") => (field, inches(value)),
("paragraph", "spaceBefore") => ("space_before", value),
("paragraph", "spaceAfter") => ("space_after", value),
("paragraph", "align") => (
field,
named(
value,
&[
("left", "Left"),
("center", "Center"),
("right", "Right"),
("justify", "Justify"),
("justLow", "JustifyLow"),
("distributed", "Distributed"),
],
),
),
("paragraph", "special") => (field, named(value, &[("none", "None"), ("first", "FirstLine"), ("hanging", "Hanging")])),
_ => (field, value),
};
(name.to_owned(), value)
}
/// `fields` as dialog `key` takes them, read against its current fields `current`; `tab` is the Action Settings tab
/// a `kind` applies to.
pub(super) fn typed(key: &str, current: &Value, tab: &str, fields: Vec<(String, Value)>) -> Result<Vec<(String, Value)>, String> {
+12
View File
@@ -173,6 +173,18 @@ fn palette_save_goes_to_the_page() {
assert!(!app.session.active().unwrap().is_dirty());
}
/// The bug this prevents: `file.save` by id reported the file's name as saved when the page refused it, so an
/// automation client could not tell the presentation still had unsaved changes.
#[test]
fn palette_save_the_page_refuses_is_an_error() {
let (mut h, _) = host_app(true);
let app = h.state_mut();
app.open_from_host(Some("deck.pptx"), &pptx(1));
edit(app);
assert!(app.run("file.save", json!({})).is_err());
assert!(app.session.active().unwrap().is_dirty());
}
/// A file the page sent without a name, or with a name that isn't a presentation's, has no file
/// of its own: Save is a new `.deckcraft`, never an overwrite of an invented `Presentation.pptx`.
#[test]
+21 -3
View File
@@ -74,8 +74,19 @@ pub struct DeltaCache {
next: Option<Preview>,
slides: Option<Vec<Preview>>,
acknowledged: bool,
sent: u64,
}
impl DeltaCache {
/// The sequence number the next successful send carries.
pub fn seq(&self) -> u64 {
self.sent
}
/// The window missed a delta, and with it maybe an image: the next send carries every image again.
pub fn resend(&mut self) {
self.acknowledged = false;
}
/// Sends changed images, acknowledging them only after the transport succeeds.
pub fn send<E>(&mut self, mut snapshot: Snapshot, refresh: bool, send: impl FnOnce(Snapshot, bool, bool) -> Result<(), E>) -> Result<(), E> {
if refresh {
@@ -103,6 +114,7 @@ impl DeltaCache {
self.next = next;
self.slides = slides;
self.acknowledged = true;
self.sent = self.sent.wrapping_add(1);
Ok(())
}
}
@@ -126,6 +138,8 @@ pub enum Command {
/// Zero-based slide index.
slide: usize,
},
/// The window missed a snapshot (its inbox was full): the audience sends every image again.
Resync,
}
impl Command {
/// Reads an action, refusing malformed messages and nonfinite zoom coordinates.
@@ -153,6 +167,10 @@ pub struct SnapshotDelta {
pub current_changed: bool,
/// Whether to replace the next preview, including replacement with no image.
pub next_changed: bool,
/// The send's number ([`DeltaCache::seq`]); a number that does not follow the last one received means a delta
/// was lost.
#[serde(default)]
pub seq: u64,
}
impl SnapshotDelta {
@@ -170,7 +188,7 @@ impl SnapshotDelta {
/// Keeps omitted images and grid thumbnails from the previous accepted snapshot.
pub fn merge(previous: Option<&Snapshot>, delta: SnapshotDelta) -> Snapshot {
let SnapshotDelta { mut snapshot, current_changed, next_changed } = delta;
let SnapshotDelta { mut snapshot, current_changed, next_changed, .. } = delta;
if let Some(previous) = previous {
if !current_changed {
snapshot.current = previous.current.clone();
@@ -463,7 +481,7 @@ mod tests {
incoming.next = None;
incoming.elapsed += 1.0;
let decode = |snapshot: Snapshot, current_changed, next_changed| {
let delta = SnapshotDelta { snapshot, current_changed, next_changed };
let delta = SnapshotDelta { snapshot, current_changed, next_changed, seq: 0 };
SnapshotDelta::from_payload(&delta.to_payload()).unwrap()
};
let kept = merge(Some(&previous), decode(incoming.clone(), false, false));
@@ -518,7 +536,7 @@ mod tests {
] {
assert_eq!(Command::from_payload(&command.to_payload()), Some(command));
}
let envelope = SnapshotDelta { snapshot: snapshot(), current_changed: true, next_changed: false };
let envelope = SnapshotDelta { snapshot: snapshot(), current_changed: true, next_changed: false, seq: 0 };
let wire = envelope.to_payload();
let decoded = SnapshotDelta::from_payload(&wire).unwrap();
assert_eq!(decoded.snapshot.current, envelope.snapshot.current);
+3 -1
View File
@@ -193,6 +193,7 @@ fn apply_command(show: &mut Show, doc: &Arc<Presentation>, now: f64, command: Co
let action = show.state.goto(doc, slide);
return show.apply(action, doc, now);
}
Command::Resync => show.remote_images.resend(),
_ => {}
}
true
@@ -254,8 +255,9 @@ fn remote_pass(
slides: show.presenter_grid.then(|| show.remote_grid.clone()),
};
let refresh = link.take_ready();
let seq = show.remote_images.seq();
if let Err(error) = show.remote_images.send(snapshot, refresh, |snapshot, current_changed, next_changed| {
link.post(&SnapshotDelta { snapshot, current_changed, next_changed }.to_payload())
link.post(&SnapshotDelta { snapshot, current_changed, next_changed, seq }.to_payload())
}) {
message = Some(link_message(ui, error));
}
+19 -6
View File
@@ -1163,6 +1163,16 @@ fn input_state_tracks_the_modes_that_move_show_click_targets() {
assert_ne!(show.input_state(), base, "a blank screen has no slide click targets");
}
/// Steps the app, at most two seconds of frames, until `done`.
fn step_until(h: &mut egui_kittest::Harness<'static, SlideApp>, done: impl Fn() -> bool) {
for _ in 0..120 {
h.step();
if done() {
break;
}
}
}
#[test]
fn remote_presenter_uses_the_audience_state_and_closes_with_the_show() {
use crate::presenter::{Command, Snapshot, SnapshotDelta, merge};
@@ -1250,13 +1260,16 @@ fn remote_presenter_uses_the_audience_state_and_closes_with_the_show() {
let posted = bridge.borrow().posts.len();
// Every accepted ready handshake is emitted by WindowLink, including a popup reload.
bridge.borrow_mut().ready = true;
for _ in 0..120 {
h.step();
if bridge.borrow().posts.len() > posted {
break;
}
}
step_until(&mut h, || bridge.borrow().posts.len() > posted);
assert_eq!(bridge.borrow().posts.get(posted), Some(&(false, true, true, true, true)), "the first post after reload resends both previews");
// A popup whose full inbox dropped a delta asks again; the images it may have lost come back.
let posted = bridge.borrow().posts.len();
step_until(&mut h, || bridge.borrow().posts.len() > posted);
assert_eq!(bridge.borrow().posts.last(), Some(&(false, false, false, false, false)), "unchanged previews are left out");
let posted = bridge.borrow().posts.len();
bridge.borrow_mut().commands.push(Command::Resync);
step_until(&mut h, || bridge.borrow().posts.len() > posted);
assert_eq!(bridge.borrow().posts.get(posted), Some(&(false, true, true, true, true)), "a resync resends both previews");
// #1866: All slides opens in the web Presenter View, as on desktop; the audience keeps its slide.
let posted = bridge.borrow().posts.len();
bridge.borrow_mut().commands.push(run(ShowCommands::Grid));
+1 -1
View File
@@ -46,7 +46,7 @@ Coordinates are slide points (1/72 inch; a 16:9 slide is 960 × 540) unless note
| `ui.wheel` / `ui.drop` / `ui.capsLock` | Library synthetic-input parameters | Wheel input, file drops and Caps Lock state through the window host |
| `ui.set` | `{tab?, view?, pane?, notes?, zoom?, dark?, recent?, palette?: {query, selected?}, backstage?: {page?, query?, exportTask?, fileType?, printLayout?, printRange?}, paneWidth?, thumbsWidth?, notesHeight?, caretBlink?, presenterView?, handoutPerPage?, …}` | Set UI state and return the full state. Pane sizes are finite numbers in points, clamped to the supported ranges. `caretBlink: false` requests a solid editor caret; true inherits the motion policy. `recent` is a list of paths. Palette selection is a displayed-result ordinal, excluding headings and dividers; it is normalized by the palette. File-page keyboard focus uses `ui.focus` on the entry label |
| `ui.notify` | `{text, kind?: toast\|status}` | Post a notice; the default kind is `toast` |
| `ui.dialog.open` | `{id, params?, fields?}` | Open a dialog through its registered implementation; `fields` pre-fills its fields, and `tab` among them picks the tab Bullets and Action Settings open on |
| `ui.dialog.open` | `{id, params?, fields?}` | Open a dialog through its registered implementation; `fields` pre-fills its fields, and `tab` among them picks the tab Bullets and Action Settings open on. Columns `spacing` and Paragraph `before`, `after` and `by` are in inches; Paragraph also takes `align` (`left`, `center`, `right`, `justify`, `justLow`, `distributed`), `special` (`none`, `first`, `hanging`), `spaceBefore` and `spaceAfter` |
| `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel` / `ui.dialog.close` | Dialog selector and fields for `set` | Edit or answer the real hosted dialog; closing follows its cancel path. A value may be text: a number field takes its digits, a check box `1`/`0` or `true`/`false`. Some dialogs also take these names: Find `text` (Find what), Hyperlink `mode: slide` (a place in this document), Action Settings `kind` (`none`, `program`, `playMedia` or a hyperlink target such as `url`), Paragraph `lineKind` (`multiple` or `exactly`) and `lineValue`, Tabs `stops` as `position:align\|…` (inches; `l`, `ctr`, `r`, `dec`), Reuse Slides `off{index}: 1` (untick a slide). A value outside a field's range is refused at `set` |
| `ui.screenshot` | `{path?, region?: [x0,y0,x1,y1], window?: docWindow\|presenter}` | Capture a PNG of the named window or the main window. A region is in window points. Without a path, return `{base64, mime, width, height, pixels_per_point}`; with a path, return `{path, width, height, pixels_per_point}`. Unknown or closed windows are refused |
| `ui.render` | `{path?, slide?, scale?}` | Render a slide headlessly |