Files
deckcraft/crates/ui-egui/src/tests.rs
T
Dylan M. TaylorandClaude Opus 5.5 8974f3b9df Quick access Alt+digit: while editing text, the framework composes the top-row Alt code into the text
craft-libs main composes top-row Alt codes (alt_code, upstream's suite-wide rule since the sync); the slot still does not run while text is edited, which the test keeps guarding, and only the edited text changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 14:44:45 +00:00

1824 lines
89 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
use craft::host::{Picked, ScriptedFiles};
use craft::platform::clipboard::Written;
use craft::ui::runtime::commands::{ClipItem, ClipboardHandle};
use craft::ui::runtime::env::WindowKey;
use craft::ui::runtime::windows::WindowHost;
use deckcraft_engine::Mods;
use egui_kittest::kittest::Queryable;
use std::sync::Arc;
fn notices(ctx: &egui::Context) -> Vec<craft::ui::runtime::toast::Card> {
craft::ui::runtime::toast::cards(ctx, &WindowKey::main())
}
fn files_harness(session: Session, files: Arc<ScriptedFiles>) -> egui_kittest::Harness<'static, SlideApp> {
crate::test_harness::harness_with(session, Services::default(), egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)), move |p| {
p.host = p.host.clone().with_files(files)
})
}
fn control_harness(
session: Session,
) -> (egui_kittest::Harness<'static, SlideApp>, std::sync::mpsc::Sender<craft::automation::control::ControlRequest>) {
let (tx, rx) = std::sync::mpsc::channel();
let h =
crate::test_harness::harness_with(session, Services::default(), egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)), |p| {
p.control = Some(craft::automation::control::ControlChannel::new(rx))
});
(h, tx)
}
fn shape_rot(app: &SlideApp) -> f64 {
let d = app.session.active().unwrap();
let id = d.selection.shapes[0];
d.shape(id).unwrap().xfrm.unwrap().rot
}
/// A two-finger twist is egui's Rotate event. Over the canvas it turns the selection;
/// letting go is one undo step. Off the canvas it does nothing.
#[test]
fn a_trackpad_twist_rotates_the_shape_under_the_canvas() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
let id = harness.state_mut().session.execute("shape.insert", &json!({"preset": "rect", "rect": [80.0, 80.0, 100.0, 60.0]})).unwrap();
let id = id.get("id").and_then(|v| v.as_u64()).unwrap();
harness.state_mut().session.execute("edit.select", &json!({"ids": [id]})).unwrap();
harness.run_steps(1);
harness.ctx.on_end_pass(
"twist replay",
Arc::new(|ctx| {
if ctx.current_pass_index() == 0 {
ctx.request_discard("exercise input-only-first-pass");
}
}),
);
let canvas = harness.state().canvas_rect().expect("canvas");
let outside = egui::pos2(1.0, 1.0);
assert!(!canvas.contains(outside), "the ribbon corner is not the canvas: {canvas:?}");
harness.input_mut().events.push(egui::Event::PointerMoved(outside));
harness.input_mut().events.push(egui::Event::Rotate(20.0_f32.to_radians()));
harness.run_steps(1);
assert!((shape_rot(harness.state()) - 0.0).abs() < 0.01, "off the canvas, still {}", shape_rot(harness.state()));
harness.input_mut().events.push(egui::Event::PointerMoved(canvas.center()));
harness.input_mut().events.push(egui::Event::Rotate(20.0_f32.to_radians()));
harness.run_steps(1);
harness.input_mut().events.push(egui::Event::PointerMoved(canvas.center()));
harness.input_mut().events.push(egui::Event::Rotate(10.0_f32.to_radians()));
harness.run_steps(1);
assert!((shape_rot(harness.state()) - 30.0).abs() < 0.05, "twist landed on {}", shape_rot(harness.state()));
harness.event(egui::Event::PointerMoved(canvas.center() + egui::vec2(1.0, 0.0)));
harness.run_steps(1);
assert!(harness.state().session.active().unwrap().interaction.is_none());
harness.state_mut().session.execute("edit.undo", &json!({})).unwrap();
assert!((shape_rot(harness.state()) - 0.0).abs() < 0.01, "one undo, got {}", shape_rot(harness.state()));
}
/// The browser "PNG images (all slides)" export yields one image per slide, not just the selected one (#64).
#[test]
fn web_export_all_slides_gives_one_file_per_slide() {
let mut doc = deckcraft_model::Presentation::default();
if let Some(first) = doc.slides.first().cloned() {
doc.slides.push(first.clone());
doc.slides.push(first);
}
assert_eq!(doc.slides.len(), 3);
let all = web_image_files(&doc, 1, true, "Deck", "png", false);
let names: Vec<&str> = all.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["Deck1.png", "Deck2.png", "Deck3.png"]);
let one = web_image_files(&doc, 1, false, "Deck", "png", false);
assert_eq!(one.len(), 1);
assert_eq!(one[0].0, "Deck.png");
}
/// The files a browser host downloaded: each Save the app asked for whose bytes arrived. A browser save is
/// a download, not a `Files::write`, so `ScriptedFiles::written` does not list it.
fn downloaded(files: &ScriptedFiles) -> Vec<std::path::PathBuf> {
files
.requests()
.into_iter()
.filter(|request| request.kind == craft::host::PickKind::Save)
.filter_map(|request| {
let name = std::path::PathBuf::from(request.file_name?);
Some(request.directory.map_or_else(|| name.clone(), |dir| dir.join(&name)))
})
.filter(|path| files.file(path).is_some())
.collect()
}
/// A PNG may omit the background; JPEG remains opaque.
#[test]
fn web_png_export_can_leave_the_background_transparent() {
let files = Arc::new(ScriptedFiles::new().in_browser().saving_suggested());
let mut h = files_harness(Session::with_new(), files.clone());
let mut alpha = Vec::new();
for (format, extra) in [("png", json!({})), ("png", json!({"transparentBackground": true})), ("jpeg", json!({"transparentBackground": true}))] {
let before = downloaded(&files).len();
assert!(h.state_mut().export_as(format, extra));
h.run_steps(2);
let written = downloaded(&files);
assert!(written.len() > before);
let bytes = files.file(written.last().unwrap()).unwrap();
alpha.push(deckcraft_render::decode_image(&bytes).unwrap().get_pixel(2, 2).0[3]);
}
assert!(alpha[1] < alpha[0], "transparent PNG omits the background: {alpha:?}");
assert_eq!(alpha[2], alpha[0], "JPEG remains opaque");
}
/// A listed save format must produce a file through the browser file service.
#[test]
fn every_listed_save_type_exports() {
let files = Arc::new(ScriptedFiles::new().in_browser().saving_suggested());
let mut h = files_harness(Session::with_new(), files.clone());
h.state_mut().session.execute("slide.new", &json!({})).unwrap();
for (id, _, _) in crate::backstage::SAVE_TYPES {
let before = downloaded(&files).len();
assert!(h.state_mut().export_as(id, json!({})), "{id} exports");
h.run_steps(2);
let written = downloaded(&files);
assert!(written.len() > before, "{id} produces a file");
for path in &written[before..] {
assert!(!files.file(path).unwrap().is_empty(), "{id}: {path:?}");
}
}
let title = h.state().session.active().unwrap().title();
let names = downloaded(&files);
for name in [format!("{title}1.jpg"), format!("{title}2.jpg"), format!("{title}1.png"), format!("{title}2.png")] {
assert!(names.iter().any(|p| p.file_name().is_some_and(|n| n == name.as_str())), "{name}: {names:?}");
}
}
fn title_text(app: &SlideApp) -> String {
let d = app.session.active().unwrap();
let sh = &d.doc.slides[0].shapes[0];
sh.text.as_ref().map(|t| t.paragraphs.iter().map(|p| p.text()).collect::<Vec<_>>().join("\n")).unwrap_or_default()
}
#[test]
fn quick_access_toolbar_adds_removes_resets_and_persists() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
let ids = |app: &SlideApp| app.ui.qat.iter().map(|q| q.id.clone()).collect::<Vec<_>>();
assert_eq!(ids(harness.state()), ["app.home", "file.save", "app.exportDialog", "edit.undo", "edit.redo", "show.fromStart"]);
let app = harness.state_mut();
app.run("app.qat", json!({"add": "insert.table", "label": "Table", "icon": "table"})).unwrap();
app.run("app.qat", json!({"add": "insert.table"})).unwrap();
app.run("app.qat", json!({"add": "view.pane", "params": {"pane": "selection"}, "label": "Selection Pane"})).unwrap();
assert!(app.run("app.qat", json!({"add": "no.such"})).is_err());
app.run("app.qat", json!({"remove": "edit.redo"})).unwrap();
assert_eq!(ids(app), ["app.home", "file.save", "app.exportDialog", "edit.undo", "show.fromStart", "insert.table", "view.pane"]);
assert_eq!(app.ui.qat[5].label, "Table");
// Saved with the rest of the UI state and read back.
let back: UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap();
assert_eq!(back.qat, app.ui.qat);
harness.run_steps(2);
let app = harness.state_mut();
app.run("app.qat", json!({"remove": "view.pane", "params": {"pane": "selection"}})).unwrap();
assert_eq!(app.ui.qat.len(), 6);
app.run("app.qat", json!({"reset": true})).unwrap();
assert_eq!(ids(app), ["app.home", "file.save", "app.exportDialog", "edit.undo", "edit.redo", "show.fromStart"]);
// An older settings file without the toolbar gets the defaults.
let old: UiState = serde_json::from_value(json!({"tab": "Home"})).unwrap();
assert_eq!(old.qat.len(), 6);
}
/// One Escape closes Insert ▸ Icons with a query typed in its search field, as production's library did.
#[test]
fn one_escape_closes_the_icons_library_over_a_typed_query() {
use egui::accesskit::Role;
let mut h = crate::test_harness::harness_with(
Session::with_new(),
Services::default(),
egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)),
|_| {},
);
h.state_mut().ui.tab = "Insert".into();
h.run_steps(3);
h.get_by_role_and_label(Role::Button, "Icons").click();
h.run_steps(3);
let library = |h: &egui_kittest::Harness<'_, SlideApp>| h.query_all_by_role_and_label(Role::Dialog, "Icons").next().is_some();
assert!(library(&h), "the library opened");
h.get_by_role_and_label(Role::TextInput, "Search icons").click();
h.run_steps(2);
h.get_by_role_and_label(Role::TextInput, "Search icons").type_text("arrow");
h.run_steps(2);
h.key_press(egui::Key::Escape);
h.run_steps(4);
assert!(!library(&h), "one Escape closed the library");
}
#[test]
fn opening_a_file_with_missing_fonts_shows_a_toast_once() {
use egui_kittest::kittest::Queryable;
let mut p = deckcraft_model::Presentation::default();
let slide = std::sync::Arc::make_mut(&mut p.slides[0]);
let mut body = deckcraft_model::text::TextBody::from_text("Hello");
body.paragraphs[0].runs[0].props.font = Some("Qqq Nonexistent Sans".into());
slide.shapes[0].text = Some(body);
let data = deckcraft_engine::cmd::base64_encode(&deckcraft_engine::cmd::file::save_bytes(&p, "pptx").unwrap());
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
assert!(notices(&harness.ctx).is_empty(), "a new presentation has nothing to say");
harness.state_mut().session.execute("file.openBytes", &json!({"name": "a.pptx", "data": data})).unwrap();
harness.run_steps(2);
assert_eq!(notices(&harness.ctx).len(), 1, "one notice for the opened document");
assert!(harness.query_by_label_contains("Qqq Nonexistent Sans").is_some());
// Closed, it stays closed for that document.
harness.get_by_label("Dismiss").click();
harness.run_steps(2);
assert!(notices(&harness.ctx).is_empty());
harness.run_steps(2);
assert!(notices(&harness.ctx).is_empty());
}
/// #115: Change Picture replaced nothing — it inserted a second picture.
#[test]
fn change_picture_replaces_the_selected_picture() {
let svg =
|c: &str| format!("<svg xmlns='http://www.w3.org/2000/svg' width='4' height='4'><rect width='4' height='4' fill='{c}'/></svg>").into_bytes();
let media = |app: &SlideApp| {
let d = app.session.active().unwrap();
let pics: Vec<_> = d.doc.slides[0]
.shapes
.iter()
.filter_map(|s| if let deckcraft_model::ShapeKind::Picture { fill } = &s.kind { Some(fill.media) } else { None })
.collect();
assert_eq!(pics.len(), 1, "one picture, replaced in place");
pics[0]
};
let insert = |app: &mut SlideApp| {
let id = app.session.execute("insert.picture", &json!({"name": "a.svg", "data": deckcraft_engine::cmd::base64_encode(&svg("red"))})).unwrap()
["id"]
.clone();
app.session.execute("edit.select", &json!({"ids": [id]})).unwrap();
media(app)
};
for browser in [false, true] {
let files = Arc::new(if browser {
ScriptedFiles::held().in_browser()
} else {
ScriptedFiles::answering([Picked::Paths(vec!["b.svg".into()])]).hosted().with_file("b.svg", svg("blue"))
});
let mut h = files_harness(Session::with_new(), files.clone());
let before = insert(h.state_mut());
h.state_mut().run("app.changePictureDialog", json!({})).unwrap();
if browser {
h.run_steps(2);
assert_eq!(media(h.state()), before, "a held pick changes nothing");
assert!(files.answer(Picked::Contents(vec![("b.svg".into(), svg("blue"))])).is_some());
}
h.run_steps(3);
assert_ne!(media(h.state()), before);
}
}
/// The title bar's Home button shows on while Home (the File view) is open over a presentation, and off once it is
/// left.
#[test]
fn the_title_bars_home_button_is_on_while_home_is_open() {
use egui::accesskit::Toggled;
use egui_kittest::kittest::{NodeT, Queryable};
let mut h = crate::test_harness::harness(Session::with_new(), Services::default());
h.run_steps(2);
// The title bar's item, not the File view's Home page in its side menu.
let in_title_bar = |node: &egui_kittest::Node<'_>| node.accesskit_node().bounding_box().is_some_and(|bounds| bounds.y1 <= 44.0);
let home_on = |h: &egui_kittest::Harness<'_, SlideApp>| {
let homes: Vec<_> = h.query_all_by(|node| node.label().is_some_and(|label| label.starts_with("Home"))).filter(in_title_bar).collect();
assert!(!homes.is_empty(), "the title bar has a Home item");
homes.iter().any(|node| node.accesskit_node().toggled() == Some(Toggled::True))
};
assert!(!home_on(&h), "Home is off over the slides");
h.state_mut().run("app.home", json!({})).unwrap();
h.run_steps(2);
assert!(h.state().backstage_open());
assert!(home_on(&h), "Home is on while the File view is open");
}
/// #17: Home created a new blank presentation instead of going to the start screen.
#[test]
fn home_shows_the_start_screen_over_the_open_presentation() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
// The app keeps requesting repaints, so step frames instead of run().
harness.run_steps(2);
let title = harness.state().session.active().unwrap().doc.slides[0].shapes[0].id.0;
harness.state_mut().session.execute("text.edit", &json!({"id": title})).unwrap();
harness.state_mut().run("app.home", json!({})).unwrap();
harness.run_steps(2);
assert!(harness.state().backstage_open());
assert_eq!(harness.state().session.documents().len(), 1, "Home doesn't create a presentation");
// Typing on the start screen doesn't reach the presentation behind it; Escape goes back.
harness.event(egui::Event::Text("a".into()));
harness.key_press(egui::Key::Backspace);
harness.run_steps(2);
assert_eq!(title_text(harness.state()), "");
assert!(!harness.state().session.active().unwrap().is_dirty());
harness.key_press(egui::Key::Escape);
harness.run_steps(2);
assert!(!harness.state().backstage_open());
// Home again toggles; picking a theme on the start screen (a new presentation) leaves it.
harness.state_mut().run("app.home", json!({})).unwrap();
harness.run_steps(2);
assert!(harness.state().backstage_open());
harness.state_mut().run("app.home", json!({})).unwrap();
assert!(!harness.state().backstage_open());
harness.state_mut().run("app.home", json!({"on": true})).unwrap();
harness.state_mut().run("file.new", json!({})).unwrap();
harness.run_steps(2);
assert!(!harness.state().backstage_open(), "a new presentation leaves Home");
assert_eq!(harness.state().session.documents().len(), 2);
}
/// #268: Ctrl+Backspace, Ctrl+Delete, Ctrl+arrows and Ctrl+Shift+arrows in text, through real
/// egui key events (Windows keys).
#[test]
fn ctrl_word_keys_edit_text() {
use egui::{Key, Modifiers};
let mut session = Session::with_new();
session.mac_keys = false;
session.prefs.autocorrect = false;
let mut harness = crate::test_harness::harness(session, Services::default());
harness.run_steps(2);
let title = harness.state().session.active().unwrap().doc.slides[0].shapes[0].id.0;
harness.state_mut().session.execute("text.edit", &json!({"id": title})).unwrap();
harness.event(egui::Event::Text("Hello, world. Foo bar".into()));
harness.run_steps(1);
assert_eq!(title_text(harness.state()), "Hello, world. Foo bar");
let caret = |h: &egui_kittest::Harness<'_, SlideApp>| h.state().session.active().unwrap().selection.text.clone().unwrap();
let ctrl = Modifiers::COMMAND;
let ctrl_shift = Modifiers::COMMAND | Modifiers::SHIFT;
// Ctrl+Left stops at every word and punctuation run, as in PowerPoint.
let mut stops = vec![];
for _ in 0..6 {
harness.key_press_modifiers(ctrl, Key::ArrowLeft);
harness.run_steps(1);
stops.push(caret(&harness).caret.1);
}
assert_eq!(stops, vec![19, 15, 12, 7, 5, 0]);
harness.key_press_modifiers(ctrl, Key::ArrowRight);
harness.run_steps(1);
assert_eq!(caret(&harness).caret, (0, 5));
// Ctrl+Shift+Right selects to the next stops.
harness.key_press_modifiers(ctrl_shift, Key::ArrowRight);
harness.key_press_modifiers(ctrl_shift, Key::ArrowRight);
harness.run_steps(1);
let t = caret(&harness);
assert_eq!((t.anchor, t.caret), ((0, 5), (0, 12)));
// Ctrl+Delete deletes the next word from the selection's start; Ctrl+Backspace the one
// before the caret.
harness.key_press_modifiers(ctrl, Key::Delete);
harness.run_steps(1);
assert_eq!(title_text(harness.state()), "Helloworld. Foo bar");
harness.key_press(Key::End);
harness.key_press_modifiers(ctrl, Key::Backspace);
harness.run_steps(1);
assert_eq!(title_text(harness.state()), "Helloworld. Foo ");
// Ctrl+Up/Down go by paragraph, Ctrl+Home/End to the text's ends.
harness.key_press(Key::Enter);
harness.event(egui::Event::Text("Next".into()));
harness.key_press_modifiers(ctrl, Key::ArrowUp);
harness.run_steps(1);
assert_eq!(caret(&harness).caret, (1, 0));
harness.key_press_modifiers(ctrl, Key::ArrowUp);
harness.run_steps(1);
assert_eq!(caret(&harness).caret, (0, 0));
harness.key_press_modifiers(ctrl, Key::ArrowDown);
harness.run_steps(1);
assert_eq!(caret(&harness).caret, (1, 0));
harness.key_press_modifiers(ctrl_shift, Key::Home);
harness.run_steps(1);
let t = caret(&harness);
assert_eq!((t.anchor, t.caret), ((1, 0), (0, 0)));
// Ctrl+Shift+> (egui reports the Period key) grows the selected text's font.
let size = |h: &mut egui_kittest::Harness<'_, SlideApp>| h.state_mut().session.execute("format.state", &json!({})).unwrap()["size"].as_f64();
let before = size(&mut harness);
harness.key_press_modifiers(ctrl_shift, Key::Period);
harness.run_steps(1);
let after = size(&mut harness).unwrap();
assert!(after > before.unwrap_or(0.0), "{before:?} → {after}");
harness.key_press_modifiers(ctrl, Key::OpenBracket);
harness.run_steps(1);
assert!(size(&mut harness).unwrap_or(f64::MAX) < after, "Ctrl+[ shrinks");
}
/// A browser's Copy Image puts the picture on the clipboard with text that only names it: the
/// address (and the alt text), and an `<img>` fragment as HTML. Ctrl+V pastes the picture, as
/// PowerPoint does, instead of a text box with the link. Without a picture the link pastes as text.
#[test]
fn ctrl_v_pastes_the_picture_a_browser_copied_not_its_link() {
let url = "https://github.com/storytold/deckcraft/raw/main/assets/app-icon/hicolor/256x256/apps/ai.storyteller.deckcraft.png";
let caption = format!("{url}\nDeckCraft icon: a presentation screen with a bar chart on an orange tile");
for (text, html, with_picture, pictures_after) in [
(caption.clone(), Some(format!("<img src=\"{url}\" alt=\"DeckCraft icon\">")), true, 1),
(url.to_string(), None, true, 1),
// Firefox's text/x-moz-url is UTF-16; read as UTF-8 it carries NULs.
(url.chars().flat_map(|c| [c, '\0']).collect(), None, true, 1),
(url.to_string(), None, false, 0),
("See https://example.com for the photos".to_string(), None, true, 0),
] {
let session = Session::with_new();
let png = {
let d = session.active().unwrap();
deckcraft_engine::cmd::file::render_png(&d.doc, 0, 0.1, false).0
};
let mut harness = crate::test_harness::harness(session, Services::default());
let mut offer = vec![ClipItem::Text(text.clone().into())];
if let Some(html) = html {
offer.push(ClipItem::Html(html.into()));
}
if with_picture {
let image = deckcraft_render::decode_image(&png).unwrap();
offer.push(ClipItem::Image(Arc::new(egui::ColorImage::from_rgba_unmultiplied(
[image.width() as usize, image.height() as usize],
image.as_raw(),
))));
}
assert_eq!(ClipboardHandle::of(&harness.ctx).offer(&offer).unwrap(), Written::Written);
harness.run_steps(2);
let shapes_before = harness.state().session.active().unwrap().doc.slides[0].shapes.len();
harness.event(egui::Event::Paste(text.clone()));
harness.run_steps(2);
let d = harness.state().session.active().unwrap();
let shapes = &d.doc.slides[0].shapes;
let pictures = shapes.iter().filter(|s| matches!(s.kind, deckcraft_model::ShapeKind::Picture { .. })).count();
assert_eq!(pictures, pictures_after, "{text:?}");
assert_eq!(shapes.len(), shapes_before + 1, "one shape, picture or text, for {text:?}");
if pictures_after == 0 {
let pasted = shapes.last().and_then(|s| s.text.as_ref()).map(deckcraft_model::TextBody::text);
assert_eq!(pasted.as_deref(), Some(text.as_str()), "the text survives");
}
}
}
/// An image-only clipboard is pasted by the window's Paste chord without a text Paste event.
#[test]
fn ctrl_v_pastes_an_image_when_no_paste_event_arrives() {
let mut h = crate::test_harness::harness(Session::with_new(), Services::default());
h.run_steps(2);
let pictures = |app: &SlideApp| {
app.session.active().unwrap().doc.slides[0].shapes.iter().filter(|s| matches!(s.kind, deckcraft_model::ShapeKind::Picture { .. })).count()
};
let before = pictures(h.state());
let image = ClipItem::Image(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::RED)));
assert_eq!(ClipboardHandle::of(&h.ctx).offer(&[image]).unwrap(), Written::Written);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::V);
h.run_steps(2);
assert_eq!(pictures(h.state()), before + 1);
h.run_steps(2);
assert_eq!(pictures(h.state()), before + 1, "an idle frame does not paste again");
}
/// #78: after Tab in a text box, typing and deleting no longer reached the text.
#[test]
fn typing_goes_on_after_tab_in_a_text_box() {
let mut session = Session::with_new();
session.prefs.autocorrect = false;
let mut harness = crate::test_harness::harness(session, Services::default());
harness.run_steps(2);
let title = harness.state().session.active().unwrap().doc.slides[0].shapes[0].id.0;
harness.state_mut().session.execute("text.edit", &json!({"id": title})).unwrap();
harness.event(egui::Event::Text("ab".into()));
harness.run_steps(2);
harness.key_press(egui::Key::Tab);
harness.run_steps(2);
harness.event(egui::Event::Text("c".into()));
harness.run_steps(2);
assert_eq!(title_text(harness.state()), "ab\tc");
harness.key_press(egui::Key::Backspace);
harness.run_steps(2);
assert_eq!(title_text(harness.state()), "ab\t");
assert!(harness.state().session.active().unwrap().selection.text.is_some(), "still editing");
// Tab at the start of a paragraph indents it, and typing goes on there too (#93).
harness.key_press(egui::Key::Enter);
harness.run_steps(2);
harness.key_press(egui::Key::Tab);
harness.run_steps(2);
harness.event(egui::Event::Text("d".into()));
harness.run_steps(2);
assert_eq!(title_text(harness.state()), "ab\t\nd");
let level =
|h: &egui_kittest::Harness<SlideApp>| h.state().session.active().unwrap().doc.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[1].level;
assert_eq!(level(&harness), 1);
}
/// #93: Tab in an edited list indented the item but handed the keyboard to egui's focus
/// cycle: the stray focus (e.g. on the window's drag handle) swallowed every later key, so the
/// list could neither be typed into nor continued with Enter.
#[test]
fn tab_in_an_edited_list_keeps_the_keyboard() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
let title = harness.state().session.active().unwrap().doc.slides[0].shapes[0].id.0;
harness.state_mut().session.execute("text.edit", &json!({"id": title})).unwrap();
harness.event(egui::Event::Text("one".into()));
harness.run_steps(2);
harness.key_press(egui::Key::Enter);
harness.run_steps(2);
harness.key_press(egui::Key::Tab); // Increase List Level
harness.run_steps(2);
harness.event(egui::Event::Text("sub".into()));
harness.run_steps(2);
harness.key_press(egui::Key::Enter); // continues the list
harness.run_steps(2);
harness.event(egui::Event::Text("two".into()));
harness.run_steps(2);
assert_eq!(title_text(harness.state()), "one\nsub\ntwo", "typing after Tab must reach the text");
let body = harness.state().session.active().unwrap().doc.slides[0].shapes[0].text.clone().unwrap();
let levels: Vec<u8> = body.paragraphs.iter().map(|p| p.level).collect();
assert_eq!(levels, vec![0, 1, 1], "Tab indents one level; Enter keeps the level");
}
/// View › New Window is a second window on the open presentation. Its slide is its own;
/// the editor's selection stays where it was. Closing the window leaves the document open.
#[test]
fn new_window_shows_the_same_document_on_its_own_slide() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
let ctx = harness.ctx.clone();
let app = harness.state_mut();
app.session.execute("slide.new", &json!({})).unwrap();
app.session.execute("slide.go", &json!({"index": 1})).unwrap();
let err = {
let mut empty = crate::test_harness::harness(Session::new(), Services::default());
empty.state_mut().run("view.newWindow", json!({})).unwrap_err()
};
assert!(err.contains("presentation"), "{err}");
let name = app.session.active().unwrap().title();
let opened = app.run("view.newWindow", json!({})).unwrap();
assert_eq!(opened["open"], true);
assert_eq!(opened["window"], 2);
assert_eq!(opened["slide"], 1);
assert_eq!(opened["title"], format!("{name}:2"));
assert_eq!(app.session.active().unwrap().selection.slide, 1);
let moved = app.run("view.newWindow", json!({"delta": -1})).unwrap();
assert_eq!(moved["slide"], 0);
assert_eq!(app.doc_window.as_ref().unwrap().slide, 0);
assert_eq!(app.session.active().unwrap().selection.slide, 1, "the editor stays on its slide");
let again = app.run("view.newWindow", json!({})).unwrap();
assert_eq!(again["window"], 2);
assert_eq!(again["slide"], 0, "opening again keeps the window's slide");
app.session.execute("file.close", &json!({})).unwrap();
let _ = ctx.run_ui(egui::RawInput::default(), |ui| doc_window::show(app, ui));
assert!(app.doc_window.is_none(), "closing the presentation closes the extra window");
assert!(app.session.active().is_none());
}
#[test]
fn grid_options_sets_spacing_and_display_or_opens_the_dialog() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
let ctx = harness.ctx.clone();
let app = harness.state_mut();
assert!((app.session.prefs.grid_spacing - 6.0).abs() < 1e-9);
let v = app.run("view.gridOptions", json!({"spacing": 72.0, "snap": false, "smartGuides": false, "gridlines": true, "guides": true})).unwrap();
assert_eq!(v["spacing"], 72.0);
assert_eq!(v["snap"], false);
assert_eq!(v["smartGuides"], false);
assert_eq!(v["gridlines"], true);
assert_eq!(v["guides"], true);
assert!(!crate::dialogs::modal_open(&ctx));
assert!(app.ui.gridlines && app.ui.guides);
assert!(!app.session.prefs.snap_to_grid && !app.ui.smart_guides);
app.run("view.gridOptions", json!({"snap": true})).unwrap();
assert!(app.session.prefs.snap_to_grid);
assert!((app.session.prefs.grid_spacing - 72.0).abs() < 1e-9);
assert!(!crate::dialogs::modal_open(&ctx));
for bad in [json!({"spacing": 0}), json!({"spacing": 289}), json!({"spacing": "72"}), json!({"spacing": null}), json!({"snap": 1})] {
assert!(app.run("view.gridOptions", bad).is_err(), "rejected a bad grid option");
}
assert!((app.session.prefs.grid_spacing - 72.0).abs() < 1e-9);
assert!(app.session.prefs.snap_to_grid);
app.run("view.gridOptions", json!({})).unwrap();
assert!((app.session.prefs.grid_spacing - 72.0).abs() < 1e-9);
harness.run_steps(1);
assert!(crate::dialogs::open_keys(&ctx).iter().any(|key| key == "gridOptions"));
}
/// Preferences (#752): Cancel, Esc and the window's close button put back what the dialog
/// changed while it was open; OK keeps it.
#[test]
fn preferences_cancel_restores_the_settings_done_keeps_them() {
use egui_kittest::kittest::Queryable;
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
let before = harness.state().session.prefs.clone();
let dark_before = harness.state().ui.brightness;
let change = |harness: &mut egui_kittest::Harness<'static, SlideApp>| {
harness.state_mut().run("app.preferences", json!({})).unwrap();
harness.run_steps(2);
for label in ["Dark appearance", "Show smart guides", "Snap objects to grid"] {
harness
.query_all_by_role_and_label(egui::accesskit::Role::CheckBox, label)
.next()
.unwrap_or_else(|| panic!("no {label} checkbox"))
.click_accesskit();
harness.run_steps(2);
}
assert_ne!(harness.state().ui.brightness, dark_before, "the dialog previews the appearance");
assert_ne!(harness.state().session.prefs.smart_guides, before.smart_guides);
};
let unchanged = |harness: &egui_kittest::Harness<'static, SlideApp>, how: &str| {
let s = harness.state();
assert!(!crate::dialogs::modal_open(&harness.ctx), "{how} closes Preferences");
assert_eq!(s.ui.brightness, dark_before, "{how} restores the appearance");
assert_eq!(s.session.prefs.smart_guides, before.smart_guides, "{how} restores smart guides");
assert_eq!(s.session.prefs.snap_to_grid, before.snap_to_grid, "{how} restores snap to grid");
};
change(&mut harness);
harness
.query_all_by_role_and_label(egui::accesskit::Role::Button, "Cancel")
.next()
.unwrap_or_else(|| panic!("no Cancel button"))
.click_accesskit();
harness.run_steps(2);
unchanged(&harness, "Cancel");
change(&mut harness);
harness.key_press(egui::Key::Escape);
harness.run_steps(2);
unchanged(&harness, "Esc");
change(&mut harness);
harness.query_all_by_role_and_label(egui::accesskit::Role::Button, "OK").next().unwrap_or_else(|| panic!("no OK button")).click_accesskit();
harness.run_steps(2);
let s = harness.state();
assert!(!crate::dialogs::modal_open(&harness.ctx), "Done closes Preferences");
assert_ne!(s.ui.brightness, dark_before, "Done keeps the appearance");
assert_ne!(s.session.prefs.smart_guides, before.smart_guides, "Done keeps smart guides");
assert_ne!(s.session.prefs.snap_to_grid, before.snap_to_grid, "Done keeps snap to grid");
}
fn canvas_harness() -> egui_kittest::Harness<'static, SlideApp> {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
let app = harness.state_mut();
// Zoomed out, the canvas shows plenty of pasteboard around the slide.
app.ui.zoom = Some(0.4);
app.session.prefs.snap_to_grid = false;
app.session.prefs.smart_guides = false;
harness
}
fn selected(app: &SlideApp) -> Vec<u64> {
app.session.active().unwrap().selection.shapes.iter().map(|i| i.0 as u64).collect()
}
fn shape_x(app: &SlideApp, id: u64) -> f64 {
let st = app.session.active().unwrap();
st.shape(deckcraft_model::ShapeId(id as u32)).and_then(|s| s.xfrm).unwrap().x
}
/// #270: PowerPoint's Normal view draws objects off the slide on the area around it, where
/// they can be selected and moved.
#[test]
fn off_slide_objects_show_on_the_pasteboard_and_can_be_selected_and_moved() {
let _gpu = crate::gpu_lock::gpu_lock();
let mut harness = canvas_harness();
let off = harness.state_mut().session.execute("shape.insert", &json!({"preset": "rect", "rect": [1000.0, 100.0, 120.0, 80.0]})).unwrap()["id"]
.as_u64()
.unwrap();
harness.state_mut().session.execute("edit.select", &json!({"ids": []})).unwrap();
harness.run_steps(3);
let app = harness.state();
let (slide, region, k) = (app.slide_rect().unwrap(), app.picture.region.unwrap(), app.canvas_scale());
// The texture reaches past the slide's right edge to the shape's, and no further left/up.
assert!(region.max.x >= slide.min.x + 1120.0 * k - 1.0, "{region:?} {slide:?}");
assert!((region.min.x - slide.min.x).abs() < 1.0 && (region.min.y - slide.min.y).abs() < 1.0, "{region:?} {slide:?}");
let centre = slide.min + egui::vec2(1060.0 * k, 140.0 * k);
assert!(app.canvas_rect().unwrap().contains(centre));
// Drawn at full strength on the pasteboard (when a GPU renderer is available here).
if let Ok(img) = harness.render() {
let px = |p: egui::Pos2| img.get_pixel(p.x as u32, p.y as u32).0;
let shape = px(centre);
let board = px(slide.min + egui::vec2(1060.0 * k, 400.0 * k));
let doc = &harness.state().session.active().unwrap().doc;
let accent = doc.masters[0].theme.colors.get(deckcraft_color::SchemeSlot::Accent1);
let close = |a: u8, b: u8| (a as i32 - b as i32).abs() <= 4;
assert!(close(shape[0], accent.r) && close(shape[1], accent.g) && close(shape[2], accent.b), "{shape:?} vs {accent:?}");
assert_ne!(shape, board);
}
// Click selects it.
harness.hover_at(centre);
harness.run_steps(1);
harness.drag_at(centre);
harness.run_steps(1);
harness.drop_at(centre);
harness.run_steps(2);
assert_eq!(selected(harness.state()), vec![off]);
// Drag moves it, further off the slide.
let to = centre + egui::vec2(40.0, 0.0);
harness.hover_at(centre);
harness.run_steps(1);
harness.drag_at(centre);
harness.run_steps(1);
for i in 1..=4 {
harness.hover_at(centre + egui::vec2(10.0 * i as f32, 0.0));
harness.run_steps(1);
}
harness.drop_at(to);
harness.run_steps(2);
let x = shape_x(harness.state(), off);
assert!((x - (1000.0 + 40.0 / k as f64)).abs() < 1.5, "{x}");
// The pasteboard followed it.
let (slide, region) = (harness.state().slide_rect().unwrap(), harness.state().picture.region.unwrap());
assert!(region.max.x >= slide.min.x + (x as f32 + 120.0) * k - 1.0, "{region:?}");
// Idle frames don't render the canvas again.
let n = harness.state().picture.canvas_renders;
harness.run_steps(3);
assert_eq!(harness.state().picture.canvas_renders, n);
}
/// A slide with nothing off it renders just the slide, as before.
#[test]
fn the_canvas_renders_only_the_slide_when_nothing_is_off_it() {
let mut harness = canvas_harness();
harness.run_steps(3);
let app = harness.state();
let (slide, region) = (app.slide_rect().unwrap(), app.picture.region.unwrap());
assert!((region.min - slide.min).length() < 0.5 && (region.max - slide.max).length() < 1.0, "{region:?} {slide:?}");
let n = app.picture.canvas_renders;
harness.run_steps(3);
assert_eq!(harness.state().picture.canvas_renders, n, "an unchanged slide isn't rendered again");
}
/// #431: the ribbon's Copy and Cut, the slide's context menu, the menus and the control
/// channel all run the commands; they put the text on the system clipboard, as Ctrl+C and
/// Ctrl+X do.
#[test]
fn copy_and_cut_commands_reach_the_system_clipboard() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
let clipboard = ClipboardHandle::of(&harness.ctx);
let copied = |_: &egui_kittest::Harness<'_, SlideApp>| clipboard.read_text().unwrap();
let title = harness.state().session.active().unwrap().doc.slides[0].shapes[0].id.0;
harness.state_mut().session.execute("text.edit", &json!({"id": title})).unwrap();
harness.state_mut().session.type_text("Aurora").unwrap();
harness.state_mut().session.key("Escape", Mods::default()).unwrap();
harness.run_steps(1);
assert_eq!(copied(&harness), None);
harness.get_by_role_and_label(egui::accesskit::Role::Button, "Copy").click();
harness.run_steps(1);
assert_eq!(copied(&harness).as_deref(), Some("Aurora"), "Copy puts the text on the clipboard");
assert_eq!(clipboard.offer(&[ClipItem::Text("clipboard sentinel".into())]).unwrap(), Written::Written);
harness.run_steps(1);
assert_eq!(copied(&harness).as_deref(), Some("clipboard sentinel"), "copy is published once");
harness.get_by_role_and_label(egui::accesskit::Role::Button, "Cut").click();
harness.run_steps(1);
assert_eq!(copied(&harness).as_deref(), Some("Aurora"), "Cut does too");
assert!(harness.state().session.active().unwrap().doc.slides[0].shapes.iter().all(|s| s.id.0 != title), "and removes the shape");
}
/// #182: Ctrl+C then Ctrl+V did nothing for objects without text (a rectangle), because
/// egui-winit drops Ctrl+V when the system clipboard is empty; the context menu worked.
#[test]
fn copy_then_paste_shortcut_duplicates_an_object_without_text() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
harness.state_mut().session.execute("shape.insert", &json!({"preset": "rect", "rect": [10, 10, 50, 50]})).unwrap();
let count = |h: &egui_kittest::Harness<'_, SlideApp>| h.state().session.doc().unwrap().current_slide().unwrap().shapes.len();
let before = count(&harness);
harness.event(egui::Event::Copy);
harness.run_steps(2);
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::V);
harness.run_steps(2);
assert_eq!(count(&harness), before + 1, "the shortcut pastes a copy of the rectangle");
let d = harness.state().session.active().unwrap();
let pasted = d.doc.slides[0].shapes.last().unwrap();
assert!(pasted.text.as_ref().is_none_or(|t| t.text().is_empty()), "a copy of the rectangle, not a text box");
}
/// #188: Ctrl/Cmd+A with the slide thumbnail pane focused selects every slide; with the
/// canvas focused it still selects shapes.
#[test]
fn select_all_follows_the_focused_pane() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
for _ in 0..2 {
harness.state_mut().run("slide.new", json!({})).unwrap();
}
harness.state_mut().run("slide.go", json!({"index": 0})).unwrap();
harness.run_steps(3);
let click = |h: &mut egui_kittest::Harness<'_, SlideApp>, pos: egui::Pos2| {
h.event(egui::Event::PointerMoved(pos));
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
}
h.run_steps(2);
};
// Press in the thumbnail pane, then Cmd+A.
let w = harness.state().ui.thumbs_width;
click(&mut harness, egui::pos2(w / 2.0, 300.0));
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
harness.run_steps(2);
let st = harness.state().session.active().unwrap();
assert_eq!(st.selection.slides.len(), 3, "every slide is selected");
// A press on the canvas moves focus away: Cmd+A selects shapes again.
click(&mut harness, egui::pos2(700.0, 400.0));
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
harness.run_steps(2);
let st = harness.state().session.active().unwrap();
assert!(!st.selection.shapes.is_empty(), "canvas select all picks the shapes");
}
fn harness() -> egui_kittest::Harness<'static, SlideApp> {
crate::test_harness::harness(Session::new(), Services::default())
}
/// #172: a recent file that no longer exists is marked on File › Home, and clicking it draws
/// the open error right there (the status bar is hidden while the backstage is open, so the
/// message used to vanish).
#[test]
fn missing_recent_is_marked_and_its_error_shows() {
let mut harness = harness();
let missing = "/deckcraft-tests/172/missing.deckcraft";
harness.state_mut().ui.recent = vec![missing.to_string()];
harness.run_steps(2);
// The row is labelled with the file's name. Clicking it raises the open error, and the
// drawn message is a second node that mentions the name (the OS text after it varies).
harness.get_all_by_label_contains("missing.deckcraft").next().expect("the recent entry").click();
harness.run_steps(2);
// The file is read in the background (#350): wait for that read to finish.
for _ in 0..500 {
if harness.state().opening.is_none() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run_steps(1);
}
harness.run_steps(2);
assert!(!notices(&harness.ctx).is_empty(), "the open error was raised");
assert!(harness.get_all_by_label_contains("missing.deckcraft").count() >= 2, "the open error is drawn on the page, next to the entry");
}
/// The existence probe tells present files from missing ones and never touches remote paths.
#[test]
fn recent_exists_tells_missing_from_present() {
let path = std::path::PathBuf::from("/deckcraft-tests/172/present.deckcraft");
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new().with_file(&path, Vec::new()));
let mut harness = crate::test_harness::harness_with(
Session::new(),
Services::default(),
egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)),
|platform| platform.host = platform.host.with_files(files),
);
let app = harness.state_mut();
assert!(app.recent_exists(&path.to_string_lossy()), "the file exists");
assert!(!app.recent_exists("/deckcraft-tests/172/missing.deckcraft"));
assert!(app.recent_exists("\\\\server/share/deck.deckcraft"), "UNC paths are never probed");
}
/// #339: clicking a language in Review > Language did nothing, and OK didn't mark the text.
#[test]
fn the_language_dialog_marks_the_selected_text() {
use egui_kittest::kittest::Queryable;
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
let title = harness.state().session.active().unwrap().doc.slides[0].shapes[0].id.0;
harness.state_mut().session.execute("text.edit", &json!({"id": title})).unwrap();
harness.state_mut().session.execute("text.insert", &json!({"text": "Bonjour"})).unwrap();
harness.state_mut().session.execute("text.selectAll", &json!({})).unwrap();
harness.state_mut().run("app.dialog", json!({"id": "language"})).unwrap();
// The anchored window settles over its first frames; click once it stays put.
harness.run_steps(4);
// Installed dictionaries append a marker to the language's accessible label.
harness.get_by_label_contains("Français (France)").click();
harness.run_steps(2);
harness.get_by_label("OK").click();
harness.run_steps(2);
assert!(!crate::dialogs::modal_open(&harness.ctx));
let d = harness.state().session.active().unwrap();
let body = d.doc.slides[0].shapes[0].text.as_ref().unwrap();
assert_eq!(body.paragraphs[0].runs[0].props.lang.as_deref(), Some("fr-FR"));
}
/// With nothing selected, Review > Language applies to the whole presentation without
/// choosing it, and Selected text can't be picked.
#[test]
fn the_language_dialog_marks_the_whole_presentation_with_nothing_selected() {
use egui_kittest::kittest::{NodeT, Queryable};
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
let s = &mut harness.state_mut().session;
let title = s.active().unwrap().doc.slides[0].shapes[0].id.0;
s.execute("text.edit", &json!({"id": title})).unwrap();
s.execute("text.insert", &json!({"text": "Hola"})).unwrap();
s.execute("slide.new", &json!({"title": "Adiós"})).unwrap();
s.execute("edit.select", &json!({"ids": []})).unwrap();
assert!(s.active().unwrap().selection.text.is_none() && s.active().unwrap().selection.shapes.is_empty());
harness.state_mut().run("app.dialog", json!({"id": "language"})).unwrap();
harness.run_steps(4);
assert!(harness.get_by_label("Selected text").accesskit_node().is_disabled());
harness.get_by_label("Español (España)").click();
harness.run_steps(2);
harness.get_by_label("OK").click();
harness.run_steps(2);
assert!(!crate::dialogs::modal_open(&harness.ctx));
let d = harness.state().session.active().unwrap();
for sl in &d.doc.slides {
let body = sl.shapes[0].text.as_ref().unwrap();
assert_eq!(body.paragraphs[0].runs[0].props.lang.as_deref(), Some("es-ES"));
}
}
/// Speaker notes keep their formatting when edited in the notes pane: typing into a bold
/// heading, Enter in a bulleted point, then saving as .pptx and reopening.
#[test]
fn editing_notes_in_the_pane_keeps_their_formatting() {
use deckcraft_model::text::{Bullet, ParaProps, Paragraph, Run, RunProps, TextBody};
let point = |runs: Vec<Run>| Paragraph {
level: 1,
props: ParaProps {
margin_left: Some(22.5),
indent: Some(-22.5),
bullet: Some(Bullet::Char { char: "§".into() }),
bullet_font: Some("Wingdings".into()),
..Default::default()
},
runs,
..Default::default()
};
let bold = RunProps { bold: Some(true), ..Default::default() };
let notes = TextBody {
paragraphs: vec![
Paragraph { runs: vec![Run::with("Metodický prehľad", bold.clone())], ..Default::default() },
Paragraph::new("Žiaci pracujú vo dvojiciach."),
point(vec![Run::with("Cieľ: ", bold.clone()), Run::new("vysvetliť cyklus")]),
point(vec![Run::new("Reflexia")]),
Paragraph::new("Pomôcky: počítač"),
],
..Default::default()
};
let mut session = Session::with_new();
session.execute("slide.notes", &json!({"index": 0, "body": notes})).unwrap();
let mut harness = crate::test_harness::harness(session, Services::default());
harness.run_steps(2);
// Five paragraphs run past the pane's visible height, so the click goes on the first line, not the node's centre.
let first_line = harness.get_by_role_and_label(egui::accesskit::Role::MultilineTextInput, "Notes").rect().left_top() + egui::vec2(40.0, 8.0);
harness.hover_at(first_line);
harness.drag_at(first_line);
harness.drop_at(first_line);
harness.run_steps(1);
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Home);
harness.key_press(egui::Key::End);
harness.event(egui::Event::Text(" hodiny".into()));
harness.run_steps(1);
harness.key_press(egui::Key::ArrowDown);
harness.key_press(egui::Key::ArrowDown);
harness.key_press(egui::Key::End);
harness.key_press(egui::Key::Enter);
harness.event(egui::Event::Text("Nový bod".into()));
harness.run_steps(1);
let canvas = harness.state().canvas_rect().unwrap().center();
harness.hover_at(canvas);
harness.drag_at(canvas);
harness.drop_at(canvas);
harness.run_steps(2);
let check = |n: &TextBody| {
assert_eq!(n.text(), "Metodický prehľad hodiny\nŽiaci pracujú vo dvojiciach.\nCieľ: vysvetliť cyklus\nNový bod\nReflexia\nPomôcky: počítač");
assert_eq!(n.paragraphs[0].runs.len(), 1, "{n:?}");
assert_eq!(n.paragraphs[0].runs[0].props.bold, Some(true));
assert_eq!(n.paragraphs[1].props, ParaProps::default());
assert_eq!(n.paragraphs[2].runs[0].props.bold, Some(true), "the bold label");
assert_eq!(n.paragraphs[2].runs[1].props.bold, None);
for i in [2, 3, 4] {
assert_eq!((n.paragraphs[i].level, &n.paragraphs[i].props), (1, &notes.paragraphs[2].props), "point {i}");
}
assert_eq!((n.paragraphs[5].level, &n.paragraphs[5].props), (0, &ParaProps::default()));
};
check(&harness.state().session.active().unwrap().doc.slides[0].notes);
// Saved as .pptx and reopened.
let s = &mut harness.state_mut().session;
let data = s.execute("file.saveBytes", &json!({"format": "pptx"})).unwrap()["data"].clone();
s.execute("file.openBytes", &json!({"name": "notes.pptx", "data": data})).unwrap();
check(&s.active().unwrap().doc.slides[0].notes);
}
fn step_app(services: Services) -> egui_kittest::Harness<'static, SlideApp> {
let mut h = crate::test_harness::harness(Session::with_new(), services);
h.run_steps(2);
h
}
/// #1855: text pasted into the focused speaker-notes field lands at its caret. While a stock
/// field has the focus, `SlideApp::keyboard` leaves the batch to it and nothing in the app drops
/// `Paste`, whether it arrives alone or inside the ⌘V batch egui-winit sends (V down, Paste, V up).
#[test]
fn paste_reaches_the_focused_notes_field() {
let mut h = step_app(Services::default());
h.get_by_role_and_label(egui::accesskit::Role::MultilineTextInput, "Notes").click();
h.run_steps(2);
h.event(egui::Event::Text("ab".into()));
h.run_steps(2);
h.event(egui::Event::Paste("PASTED".into()));
h.run_steps(2);
assert_eq!(crate::panels::notes::to_notes(&h.state().session.active().unwrap().doc.slides[0].notes).plain(), "abPASTED", "a bare Paste event");
let v = |pressed| egui::Event::Key { key: egui::Key::V, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::COMMAND };
h.input_mut().events.extend([v(true), egui::Event::Paste("TWO".into()), v(false)]);
h.run_steps(2);
assert_eq!(h.state().session.active().unwrap().doc.slides[0].notes_text(), "abPASTEDTWO", "the ⌘V batch");
}
/// Copy of a bold selection offers HTML; paste of Pages-like HTML keeps the bold.
#[test]
fn copy_offers_html_and_paste_keeps_bold() {
let mut h = step_app(Services::default());
let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0;
h.state_mut().session.execute("text.edit", &json!({"id": title})).unwrap();
h.event(egui::Event::Text("Hi".into()));
h.run_steps(1);
h.state_mut().session.execute("text.selectAll", &json!({})).unwrap();
h.state_mut().session.execute("format.bold", &json!({"on": true})).unwrap();
h.event(egui::Event::Copy);
h.run_steps(1);
let clipboard = ClipboardHandle::of(&h.ctx);
let html = String::from_utf8(clipboard.read(&["text/html"]).unwrap().expect("HTML offered").data).unwrap();
let plain = clipboard.read_text().unwrap().expect("plain text offered");
assert!(html.contains("<b>"), "{html}");
assert_eq!(plain, "Hi");
let mut h = step_app(Services::default());
let offer = [ClipItem::Html(html.into()), ClipItem::Text(plain.clone().into())];
assert_eq!(ClipboardHandle::of(&h.ctx).offer(&offer).unwrap(), Written::Written);
h.event(egui::Event::Paste(plain));
h.run_steps(1);
let st = h.state().session.active().unwrap();
let body = st
.current_slide()
.unwrap()
.shapes
.iter()
.find(|sh| sh.text.as_ref().is_some_and(|t| t.text() == "Hi"))
.and_then(|sh| sh.text.clone())
.expect("pasted text");
assert_eq!(body.paragraphs[0].runs[0].props.bold, Some(true), "{body:?}");
}
fn redder(px: [u8; 4]) -> i32 {
px[0] as i32 - px[1].max(px[2]) as i32
}
/// A fade entrance is hidden at the start of the preview clock and opaque once it has played.
#[test]
fn preview_hides_an_entrance_until_it_plays() {
let mut session = Session::with_new();
let text = session.execute("shape.insert", &json!({"preset": "rect", "rect": [40.0, 40.0, 220.0, 80.0]})).unwrap()["id"].as_u64().unwrap();
session.execute("text.set", &json!({"id": text, "text": "Alpha\nBeta"})).unwrap();
session.execute("animation.set", &json!({"effect": "fade", "duration": 1000})).unwrap();
session.execute("animation.options", &json!({"textBuild": "byParagraph"})).unwrap();
let doc = session.active().unwrap().doc.clone();
let tl = deckcraft_anim::ShowState::timeline(&doc, 0);
let shape = deckcraft_model::ShapeId(text as u32);
let para = |time: f64, i: usize| preview::shape_state_at(&tl, shape, time).paras.into_iter().find(|(p, _)| *p == i).map(|(_, s)| s).unwrap();
assert!(!para(0.0, 0).visible && !para(0.0, 1).visible, "entrances have not started");
let mid = para(0.25, 0);
assert!(mid.visible && mid.opacity > 0.05 && mid.opacity < 0.95, "{mid:?}");
assert!(!para(0.25, 1).visible, "the next paragraph waits for its step");
session.execute("animation.clear", &json!({})).unwrap();
let id = session.execute("shape.insert", &json!({"preset": "rect", "rect": [400.0, 300.0, 120.0, 80.0]})).unwrap()["id"].as_u64().unwrap();
session.execute("shape.fill", &json!({"id": id, "color": "#CC2200"})).unwrap();
session.execute("animation.set", &json!({"effect": "fade", "duration": 1000})).unwrap();
let doc = session.active().unwrap().doc.clone();
let tl = deckcraft_anim::ShowState::timeline(&doc, 0);
let (w, h) = (doc.slide_size.width.round().max(1.0) as u32, doc.slide_size.height.round().max(1.0) as u32);
let paint = |time: Option<f64>| {
let f = |sid: deckcraft_model::ShapeId| preview::shape_state_at(&tl, sid, time.unwrap_or(0.0));
let state: Option<&dyn Fn(deckcraft_model::ShapeId) -> deckcraft_render::ShapeState> = if time.is_some() { Some(&f) } else { None };
let opts = deckcraft_render::RenderOpts { scale: 1.0, size: Some((w, h)), state, ..Default::default() };
deckcraft_render::render_slide(&doc, 0, &opts).pixel(460, 340)
};
let rest = paint(None);
let start = paint(Some(0.0));
let end = paint(Some(tl.total_duration() + 0.05));
assert!(redder(rest) > 40, "the shape is filled at rest {rest:?}");
assert!(redder(start) < redder(rest) / 2, "hidden at the first preview frame {start:?} vs {rest:?}");
assert!(redder(end) > 40, "visible again once the sequence has played {end:?}");
}
#[test]
fn animation_preview_plays_on_the_canvas_then_stops() {
let mut harness = crate::test_harness::harness_with(
Session::with_new(),
Services::default(),
egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(0.05),
|_| {},
);
harness.run_steps(2);
let none = harness.state_mut().run("animation.preview", json!({})).unwrap();
assert_eq!(none["playing"], false);
assert!(harness.state().status.as_ref().is_some_and(|s| s.0.contains("no animations")));
assert!(harness.state().show.is_none());
let id = harness.state_mut().session.execute("shape.insert", &json!({"preset": "rect", "rect": [200.0, 280.0, 180.0, 80.0]})).unwrap()["id"]
.as_u64()
.unwrap();
harness.state_mut().session.execute("animation.set", &json!({"effect": "fade", "duration": 400})).unwrap();
let started = harness.state_mut().run("animation.preview", json!({})).unwrap();
assert_eq!(started["playing"], true);
assert!(harness.state().show.is_none(), "preview stays on the editor canvas");
harness.run_steps(1);
let elapsed = harness.state().anim_preview.as_ref().map(|p| p.elapsed).unwrap();
assert!(elapsed < 0.02, "the clock latches on the first frame, got {elapsed}");
let renders = harness.state().picture.canvas_renders;
harness.run_steps(6);
let elapsed = harness.state().anim_preview.as_ref().map(|p| p.elapsed).unwrap();
assert!((0.2..0.5).contains(&elapsed), "{elapsed}");
assert!(harness.state().picture.canvas_renders > renders, "each preview frame redraws the slide");
assert!(harness.state().show.is_none());
harness.key_press(egui::Key::Escape);
harness.run_steps(1);
assert!(harness.state().anim_preview.is_none(), "Escape stops the preview");
harness.state_mut().run("animation.preview", json!({})).unwrap();
harness.run_steps(1);
assert!(harness.state().anim_preview.is_some());
harness.state_mut().run("animation.preview", json!({"on": false})).unwrap();
assert!(harness.state().anim_preview.is_none());
harness.state_mut().run("animation.preview", json!({})).unwrap();
harness.run_steps(1);
let centre = harness.state().slide_rect().unwrap().center();
harness.hover_at(centre);
harness.run_steps(1);
harness.drag_at(centre);
harness.run_steps(2);
assert!(harness.state().anim_preview.is_none(), "a click on the slide stops the preview");
harness.state_mut().run("animation.preview", json!({})).unwrap();
harness.run_steps(1);
harness.state_mut().session.execute("slide.new", &json!({})).unwrap();
harness.run_steps(1);
assert!(harness.state().anim_preview.is_none(), "leaving the slide stops the preview");
harness.state_mut().session.execute("slide.previous", &json!({})).unwrap();
harness.state_mut().session.execute("edit.select", &json!({"ids": [id]})).unwrap();
harness.state_mut().run("animation.preview", json!({})).unwrap();
harness.run_steps(1);
assert!(harness.state().anim_preview.is_some());
// 400 ms effect plus the hold.
harness.run_steps(30);
assert!(harness.state().anim_preview.is_none(), "the preview ends after the sequence");
assert!(harness.state().show.is_none());
}
fn flick_harness() -> egui_kittest::Harness<'static, SlideApp> {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
// Fitted: the slide is smaller than the window, so a flick turns the page instead of panning.
harness.state_mut().ui.zoom = Some(0.4);
harness
}
fn slide_at(app: &SlideApp) -> usize {
app.session.active().unwrap().selection.slide
}
/// One frame of a trackpad flick: four short samples, each under egui's cutoff for smoothing a
/// mouse notch. The harness runs one frame per queued event, so they have to share a frame or
/// none of them reaches the page threshold.
fn flick(harness: &mut egui_kittest::Harness<'static, SlideApp>, delta: egui::Vec2) {
let centre = harness.state().canvas_rect().unwrap_or(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))).center();
let input = harness.input_mut();
input.events.push(egui::Event::PointerMoved(centre));
let step = delta / 4.0;
for _ in 0..4 {
input.events.push(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: step,
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Trackpad,
modifiers: egui::Modifiers::NONE,
});
}
harness.run_steps(1);
}
/// Test helper: place the pointer over the canvas centre, inject wheel notches, and step once.
fn mouse_wheel(harness: &mut egui_kittest::Harness<'static, SlideApp>, notches: &[f32]) {
let centre = harness.state().canvas_rect().unwrap().center();
let input = harness.input_mut();
input.events.push(egui::Event::PointerMoved(centre));
for &y in notches {
input.events.push(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Line,
delta: egui::vec2(0.0, y),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Wheel,
modifiers: egui::Modifiers::NONE,
});
}
harness.run_steps(1);
}
/// Wheel input over a zoomed canvas pans it, while the same input outside the canvas must not
/// navigate slides.
#[test]
fn mouse_wheel_over_a_zoomed_canvas_pans_and_outside_the_canvas_does_not_navigate() {
let mut h = flick_harness();
h.state_mut().run("slide.new", json!({})).unwrap();
h.state_mut().run("slide.go", json!({"index": 0})).unwrap();
h.state_mut().ui.zoom = Some(3.0);
h.run_steps(2);
let before = h.state().slide_rect().unwrap();
mouse_wheel(&mut h, &[-3.0]);
h.run_steps(30);
assert_eq!(slide_at(h.state()), 0);
assert!(h.state().slide_rect().unwrap().min.y < before.min.y, "the enlarged canvas scrolls");
h.state_mut().ui.zoom = Some(0.4);
h.run_steps(2);
h.input_mut().events.push(egui::Event::PointerMoved(egui::pos2(-10.0, -10.0)));
h.input_mut().events.push(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Line,
delta: egui::vec2(0.0, -3.0),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Wheel,
modifiers: egui::Modifiers::NONE,
});
h.run_steps(30);
assert_eq!(slide_at(h.state()), 0, "wheel input outside the canvas is ignored");
}
/// An indexed show request refuses non-indices and slides beyond the deck.
#[test]
fn show_start_refuses_a_from_that_is_not_a_slide() {
let mut s = Session::with_new();
s.execute("slide.new", &json!({})).unwrap();
s.execute("slide.new", &json!({})).unwrap();
s.execute("slide.hide", &json!({"index": 1, "hidden": true})).unwrap();
let (mut h, tx) = control_harness(s);
let ctx = h.ctx.clone();
for from in [json!(-1), json!(1.5), json!("1"), json!("current"), json!(3), json!(u64::MAX)] {
assert!(h.state_mut().run("show.start", json!({"from": from})).is_err(), "{from}");
let (req, reply) = craft::automation::control::ControlRequest::new("show.start", json!({"from": from}));
tx.send(req).unwrap();
h.state_mut().raw_input_hook(&ctx, &mut egui::RawInput::default());
let answer = reply.recv_timeout(std::time::Duration::from_secs(1)).unwrap();
assert_eq!(answer["ok"], false, "{from}: {answer}");
assert!(h.state().show.is_none());
}
h.state_mut().run("show.start", json!({"from": 1})).unwrap();
assert_eq!(h.state().show.as_ref().map(|s| (s.state.slide, s.state.ended)), Some((1, false)));
h.state_mut().show = None;
h.state_mut().run("slide.go", json!({"index": 1})).unwrap();
h.state_mut().run("show.fromCurrent", json!({})).unwrap();
assert_eq!(h.state().show.as_ref().map(|s| (s.state.slide, s.state.ended)), Some((1, false)));
h.state_mut().show = None;
let (req, reply) = craft::automation::control::ControlRequest::new("show.start", json!({"from": 2, "reading": true}));
tx.send(req).unwrap();
h.state_mut().raw_input_hook(&ctx, &mut egui::RawInput::default());
let answer = reply.recv_timeout(std::time::Duration::from_secs(1)).unwrap();
assert_eq!(answer["ok"], true, "{answer}");
assert_eq!(h.state().show.as_ref().map(|s| (s.state.slide, s.reading)), Some((2, true)));
}
/// The pen is drawing. A flick must not turn the page out from under the stroke.
#[test]
fn the_pen_ignores_a_swipe_during_the_show() {
let mut harness = flick_harness();
harness.state_mut().session.execute("slide.new", &json!({})).unwrap();
harness.state_mut().start_show(0, true);
harness.run_steps(2);
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::P);
harness.run_steps(1);
flick(&mut harness, egui::vec2(-24.0, 0.0));
assert_eq!(harness.state().show.as_ref().map(|s| s.state.slide), Some(0));
}
/// Preferences › Interface size (#767): dragging the slider leaves the interface size alone
/// until the pointer lets go, so the slider doesn't grow under the pointer mid-drag.
#[test]
fn interface_size_applies_when_the_slider_is_let_go() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
harness.state_mut().run("app.preferences", json!({})).unwrap();
harness.run_steps(4);
let before = harness.state().ui.ui_scale;
let rect = harness.query_all_by_role_and_label(egui::accesskit::Role::Slider, "Interface size").next().expect("the Interface size slider").rect();
let (from, to) = (rect.left_center() + egui::vec2(4.0, 0.0), rect.right_center() - egui::vec2(4.0, 0.0));
harness.hover_at(from);
harness.run_steps(1);
harness.drag_at(from);
harness.run_steps(1);
for k in 1..=8 {
harness.hover_at(from.lerp(to, k as f32 / 8.0));
harness.run_steps(1);
}
assert_eq!(harness.state().ui.ui_scale, before, "nothing rescales while the slider is held");
harness.drop_at(to);
harness.run_steps(2);
let after = harness.state().ui.ui_scale;
assert!(after > before + 0.3, "letting go applies the size dragged to: {before} -> {after}");
assert!(crate::dialogs::modal_open(&harness.ctx), "Preferences stays open");
}
/// The Format Shape fill page exposes one named Transparency slider.
#[test]
fn preferences_and_format_pane_name_every_input() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(3);
harness.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [100, 100, 200, 100]})).unwrap();
harness.state_mut().ui.pane = Some("format".into());
harness.state_mut().ui.format_tab = "fill".into();
harness.run_steps(3);
harness.check_accessibility();
let sliders: Vec<_> = harness.query_all_by_role_and_label(egui::accesskit::Role::Slider, "Transparency").collect();
assert_eq!(sliders.len(), 1, "one fill Transparency slider");
assert!(sliders[0].rect().width() > 40.0, "the slider keeps room next to its one visible label: {:?}", sliders[0].rect());
}
/// A hidden logic iteration answers requests without a UI pass.
#[test]
fn logic_drains_control_without_a_ui_pass() {
let (mut h, tx) = control_harness(Session::with_new());
let ctx = h.ctx.clone();
let (req, reply) = craft::automation::control::ControlRequest::new("engine.execute", json!({"command": "slide.new", "params": {}}));
let before = h.state().session.active().unwrap().doc.slides.len();
tx.send(req).unwrap();
let mut raw = egui::RawInput::default();
raw.viewports.entry(egui::ViewportId::ROOT).or_default().minimized = Some(true);
// As eframe's logic-only iteration does: the input hook, then logic, with no UI pass.
h.state_mut().raw_input_hook(&ctx, &mut raw);
let _ = ctx.run_logic(&raw, |ctx| h.state_mut().logic(ctx));
let answer = reply.recv_timeout(std::time::Duration::from_secs(1)).unwrap();
assert_eq!(answer["ok"], true, "{answer}");
assert_eq!(h.state().session.active().unwrap().doc.slides.len(), before + 1);
}
/// A queued document request waits until the old target has consumed its injected click.
#[test]
fn synthetic_click_is_consumed_on_its_old_target_before_logic_changes_the_document() {
let mut destination = Session::with_new();
let size = destination.active().unwrap().doc.slide_size;
destination.execute("shape.insert", &json!({"preset": "rect", "rect": [0, 0, size.width, size.height]})).unwrap();
let data = destination.execute("file.saveBytes", &json!({})).unwrap()["data"].clone();
let (mut h, tx) = control_harness(Session::with_new());
h.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [100, 100, 200, 100]})).unwrap();
h.run_steps(2);
let old = h.state().session.active().unwrap().uid;
let slide = h.state().slide_rect().unwrap();
let point = slide.min + slide.size() * 0.8;
let ctx = h.ctx.clone();
let host = WindowHost::of(&ctx);
host.inject_click(egui::ViewportId::ROOT, point, craft::behavior::PointerButton::Primary, 1, craft::keymap::Mods::default(), false);
h.state_mut().note_injected(&ctx);
let (req, reply) = craft::automation::control::ControlRequest::new(
"engine.execute",
json!({"command": "file.openBytes", "params": {"name": "destination.deckcraft", "data": data}}),
);
tx.send(req).unwrap();
for _ in 0..8 {
if host.injected_idle() {
break;
}
h.run_steps(1);
assert_eq!(h.state().session.active().unwrap().uid, old, "the click's pass stays on its captured document");
}
let old_doc = h.state().session.documents().iter().find(|d| d.uid == old).unwrap();
assert!(old_doc.selection.shapes.is_empty(), "the old document consumed the bare-canvas click");
h.run_steps(2);
let answer = reply.recv_timeout(std::time::Duration::from_secs(1)).unwrap();
assert_eq!(answer["ok"], true, "{answer}");
let active = h.state().session.active().unwrap();
assert_ne!(active.uid, old);
assert!(!active.doc.slides[0].shapes.is_empty());
assert!(active.selection.shapes.is_empty(), "the click did not leak to the opened document");
}
/// Every target-changing app state withdraws a click captured for the earlier state.
#[test]
fn input_target_changes_retract_a_queued_click() {
let ribbon_arrow = |h: &egui_kittest::Harness<'_, SlideApp>| h.get_by_label("Scroll ribbon right").rect().center();
for case in [
"show",
"show step",
"show reading",
"show grid",
"show ended",
"show instance",
"opening",
"reopening",
"palette",
"palette query",
"palette selected",
"dialog",
"ribbon tab",
"collapse",
"scroll",
"document",
"document return",
] {
let mut h = crate::test_harness::harness_with(
Session::with_new(),
Services::default(),
egui_kittest::Harness::builder().with_size(egui::vec2(if case == "scroll" { 600.0 } else { 1440.0 }, 900.0)),
|_| {},
);
h.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [100, 100, 200, 100]})).unwrap();
h.run_steps(3);
let ctx = h.ctx.clone();
let original_tab = h.state().ui.tab.clone();
let original_active = h.state().session.active_index().unwrap();
if case.starts_with("show ") {
h.state_mut().start_show(0, true);
}
if case.starts_with("palette ") {
h.state_mut().run("app.palette", json!({})).unwrap();
h.run_steps(2);
}
if case == "reopening" {
h.state_mut().open_path_in_background("/tmp/quarterly.pptx");
}
let target = h.state().input_target(&ctx);
let slide = h.state().slide_rect().unwrap();
let point = slide.min + slide.size() * 0.8;
// The window holds real input until the injected batch has run, so the arrow's press goes ahead of the click.
// The pointer rests on the arrow until the row has moved: a click whose first step ran is delivered whole.
if case == "scroll" {
let arrow = ribbon_arrow(&h);
let host = WindowHost::of(&ctx);
host.inject_click(egui::ViewportId::ROOT, arrow, craft::behavior::PointerButton::Primary, 1, craft::keymap::Mods::default(), false);
host.inject_move(egui::ViewportId::ROOT, arrow, craft::keymap::Mods::default(), 0.25);
}
WindowHost::of(&ctx).inject_click(
egui::ViewportId::ROOT,
point,
craft::behavior::PointerButton::Primary,
1,
craft::keymap::Mods::default(),
false,
);
h.state_mut().note_injected(&ctx);
match case {
"show" | "show instance" => h.state_mut().start_show(0, true),
"show step" => h.state_mut().show.as_mut().unwrap().state.step += 1,
"show reading" => h.state_mut().show.as_mut().unwrap().reading = false,
"show grid" => h.state_mut().show.as_mut().unwrap().grid = true,
"show ended" => h.state_mut().show.as_mut().unwrap().ended = true,
"opening" => h.state_mut().open_path_in_background("/tmp/quarterly.pptx"),
"reopening" => {
h.state_mut().cancel_opening();
h.state_mut().open_path_in_background("/tmp/quarterly.pptx");
}
"palette" => {
h.state_mut().run("app.palette", json!({})).unwrap();
}
"palette query" => h.state_mut().palette_state.query.push_str("open"),
"palette selected" => h.state_mut().palette_state.selected = Some(1),
"dialog" => h.state_mut().open_dialog("preferences", json!({})),
"ribbon tab" => h.state_mut().ui.tab = "Insert".into(),
"collapse" => h.state_mut().ui.ribbon_collapsed = true,
"scroll" => {
let before = crate::ribbon::scroll_position(h.state(), &ctx);
// The arrow's injected move, press and release each take a pass of their own.
for _ in 0..6 {
h.run_steps(1);
if crate::ribbon::scroll_position(h.state(), &ctx) != before {
break;
}
}
assert_ne!(crate::ribbon::scroll_position(h.state(), &ctx), before, "the real ribbon arrow scrolls its row");
}
"document" | "document return" => {
h.state_mut().run("file.new", json!({})).unwrap();
if case == "document return" {
h.state_mut().session.set_active(original_active);
}
}
_ => {}
}
if case == "dialog" {
h.run_steps(1);
}
assert_ne!(h.state().input_target(&ctx), target, "{case}");
let mut raw = egui::RawInput::default();
h.state_mut().raw_input_hook(&ctx, &mut raw);
h.state_mut().show = None;
h.state_mut().cancel_opening();
h.state_mut().palette_open = false;
h.state_mut().palette_state = Default::default();
if crate::dialogs::modal_open(&ctx) {
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.close", &json!({})).unwrap().unwrap();
}
h.state_mut().ui.tab = original_tab;
h.state_mut().ui.ribbon_collapsed = false;
h.state_mut().session.set_active(original_active);
h.run_steps(8);
assert!(!h.state().session.active().unwrap().selection.shapes.is_empty(), "{case}: the withdrawn bare-canvas click must not clear selection");
}
}
/// egui 0.37 carries a clipboard image as `Event::PasteImage`; it inserts once, without
/// asking the host clipboard service for the same image again.
#[test]
fn paste_image_event_inserts_one_picture() {
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
harness.run_steps(2);
let before = harness.state().session.active().unwrap().doc.slides[0].shapes.len();
let image = egui::ColorImage::filled([2, 2], egui::Color32::from_rgb(1, 2, 3));
harness.event(egui::Event::PasteImage(std::sync::Arc::new(image)));
harness.run_steps(2);
let after = harness.state().session.active().unwrap().doc.slides[0].shapes.len();
assert_eq!(after, before + 1, "one image is inserted");
}
/// A minimized/occluded show keeps playing from logic alone: the clock advances on wall
/// time, an After transition advances the slide without a draw, and a visible pass resumes
/// from the show state instead of inventing a paused-show policy.
#[test]
fn hidden_viewport_advances_show_and_presenter_clocks_from_logic() {
/// Nested helper in the hidden-show test: build root `RawInput` with the given time and
/// visibility flags.
fn raw_at(time: f64, minimized: bool, occluded: bool) -> egui::RawInput {
let mut raw = egui::RawInput { time: Some(time), ..Default::default() };
raw.viewports.insert(
egui::ViewportId::ROOT,
egui::ViewportInfo { minimized: Some(minimized), occluded: Some(occluded), native_pixels_per_point: Some(1.0), ..Default::default() },
);
raw
}
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
let ctx = harness.ctx.clone();
let app = harness.state_mut();
app.session.execute("slide.new", &json!({})).unwrap();
app.session.execute("slide.new", &json!({})).unwrap();
app.session.execute("transition.timing", &json!({"index": 0, "after": 1000})).unwrap();
app.session.execute("transition.timing", &json!({"index": 1, "after": null})).unwrap();
app.start_show(0, false);
// A real visible UI pass starts the show and its clocks. There is no renderer here, so
// each frame's texture uploads are cleared explicitly (egui 0.37 panics on drop).
ctx.run_ui(raw_at(10.0, false, false), |ui| {
app.logic(ui.ctx());
app.ui(ui);
})
.drop_without_applying_deltas();
let start = app.show.as_ref().expect("show started").clock_snapshot();
assert_eq!(start.step_start, 10.0);
assert_eq!(start.show_start, 10.0);
// Hidden logic starts at the last visible egui time, then advances on the monotonic
// instant. Two seconds later the slide's After: 1 s transition has advanced the show.
let t0 = web_time::Instant::now();
app.show.as_mut().expect("show started").observe_visible_frame(10.0, t0);
let _ = ctx.run_logic(&raw_at(12.0, true, false), |ctx| app.tick_hidden_show(ctx, t0));
let _ = ctx.run_logic(&raw_at(12.0, true, false), |ctx| app.tick_hidden_show(ctx, t0 + std::time::Duration::from_secs(2)));
let hidden = app.show.as_ref().expect("hidden show");
assert_eq!(hidden.state.slide, 1, "the After transition advances without a draw");
assert!((hidden.clock_snapshot().slide_start - 12.0).abs() < 1e-9);
assert!((hidden.presenter_elapsed(12.0) - 2.0).abs() < 1e-9, "presenter time keeps running");
// A later hidden tick does not replay the transition or stack time.
let _ = ctx.run_logic(&raw_at(12.0, true, false), |ctx| app.tick_hidden_show(ctx, t0 + std::time::Duration::from_secs(3)));
assert_eq!(app.show.as_ref().unwrap().state.slide, 1);
assert!((app.show.as_ref().unwrap().clock_snapshot().slide_start - 12.0).abs() < 1e-9);
// A visible pass re-anchors to egui's real time and keeps the state it reached hidden.
ctx.run_ui(raw_at(20.0, false, false), |ui| {
app.logic(ui.ctx());
app.ui(ui);
})
.drop_without_applying_deltas();
let resumed = app.show.as_ref().expect("show resumed");
assert_eq!(resumed.state.slide, 1);
assert!((resumed.presenter_elapsed(20.0) - 10.0).abs() < 1e-9);
assert!((resumed.clock_snapshot().slide_start - 12.0).abs() < 1e-9);
}
/// A visible window can receive an overdue logic-only pass before the next paint. That pass
/// still carries the previous full frame's `InputState::time`; treating it as a visible frame
/// re-anchors the hidden clock to the later monotonic instant and loses elapsed show time.
/// Re-anchoring belongs to `show::ui`, which only runs on a real visible pass.
#[test]
fn overdue_visible_logic_does_not_reanchor_a_later_hidden_show() {
/// Nested helper in the overdue-logic test: build root `RawInput` with the given time and
/// visibility flags.
fn raw_at(time: f64, minimized: bool, occluded: bool) -> egui::RawInput {
let mut raw = egui::RawInput { time: Some(time), ..Default::default() };
raw.viewports.insert(
egui::ViewportId::ROOT,
egui::ViewportInfo { minimized: Some(minimized), occluded: Some(occluded), native_pixels_per_point: Some(1.0), ..Default::default() },
);
raw
}
let mut harness = crate::test_harness::harness(Session::with_new(), Services::default());
let ctx = harness.ctx.clone();
let app = harness.state_mut();
app.session.execute("slide.new", &json!({})).unwrap();
app.session.execute("slide.new", &json!({})).unwrap();
app.session.execute("transition.timing", &json!({"index": 0, "after": 2500})).unwrap();
app.session.execute("transition.timing", &json!({"index": 1, "after": null})).unwrap();
app.start_show(0, false);
// The full visible pass is the only pass that anchors the show: egui time 10.
ctx.run_ui(raw_at(10.0, false, false), |ui| {
app.logic(ui.ctx());
app.ui(ui);
})
.drop_without_applying_deltas();
let visible_anchor = web_time::Instant::now();
// An overdue visible logic-only pass does not refresh InputState::time. It must not move
// the hidden anchor from the full visible frame to this later instant.
let _ = ctx.run_logic(&raw_at(12.0, false, false), |ctx| app.tick_hidden_show(ctx, visible_anchor + std::time::Duration::from_secs(2)));
assert_eq!(ctx.input(|i| i.time), 10.0, "run_logic retains the last full pass's egui time");
assert_eq!(app.show.as_ref().unwrap().state.slide, 0);
// Three seconds after the full visible frame is past the slide's 2.5 s After delay. If the
// logic-only pass had re-anchored at +2 s, this hidden tick would still be only +1 s and
// the slide would not advance.
let _ = ctx.run_logic(&raw_at(12.0, true, false), |ctx| app.tick_hidden_show(ctx, visible_anchor + std::time::Duration::from_secs(3)));
assert_eq!(app.show.as_ref().unwrap().state.slide, 1, "time from the full visible frame is preserved through the logic-only pass");
}
/// #1431: a comment card's reply row was wider than the pane, so the Comments pane grew every
/// frame until it stuck at its widest and dragging its edge did nothing.
#[test]
fn comments_pane_keeps_its_width_and_resizes() {
let mut h = crate::test_harness::harness(Session::with_new(), Services::default());
h.run_steps(3);
h.state_mut().run("comment.add", json!({"text": "Check the figures on this slide"})).unwrap();
h.state_mut().run("comment.add", json!({"text": "Resolved one"})).unwrap();
h.state_mut().run("comment.resolve", json!({"index": 1, "resolved": true})).unwrap();
h.state_mut().run("view.pane", json!({"pane": "comments"})).unwrap();
h.run_steps(3);
let width = h.state().ui.pane_width;
h.run_steps(30);
assert_eq!(h.state().ui.pane_width, width, "settled comments do not grow the pane");
// Drag the pane's left edge: right narrows it, left widens it.
let drag = |h: &mut egui_kittest::Harness<'_, SlideApp>, dx: f32| {
let start = egui::pos2(h.ctx.content_rect().right() - h.state().ui.pane_width, h.ctx.content_rect().center().y);
let end = start + egui::vec2(dx, 0.0);
h.event(egui::Event::PointerMoved(start));
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
for i in 1..=6 {
h.event(egui::Event::PointerMoved(start + (end - start) * (i as f32 / 6.0)));
h.run_steps(1);
}
h.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.run_steps(10);
h.state().ui.pane_width
};
assert_eq!(drag(&mut h, 0.0), width, "a click with no drag leaves the width alone");
let narrow = drag(&mut h, 50.0);
assert!(narrow < width, "dragging right narrows the pane: {width} -> {narrow}");
h.run_steps(30);
assert_eq!(h.state().ui.pane_width, narrow, "the narrowed width persists");
let wide = drag(&mut h, -150.0);
assert!(wide > narrow, "dragging left widens the pane: {narrow} -> {wide}");
h.run_steps(30);
assert_eq!(h.state().ui.pane_width, wide, "the widened width persists");
let travel = h.ctx.content_rect().width() * 2.0;
let widest = drag(&mut h, -travel);
assert!(widest >= wide);
assert_eq!(drag(&mut h, -travel), widest, "further outward dragging reaches a stable limit");
h.run_steps(30);
assert_eq!(h.state().ui.pane_width, widest, "the upper limit persists");
let narrowest = drag(&mut h, travel);
assert!(narrowest <= narrow);
assert_eq!(drag(&mut h, travel), narrowest, "further inward dragging reaches a stable limit");
h.run_steps(30);
assert_eq!(h.state().ui.pane_width, narrowest, "the lower limit persists");
}
/// The debug window must survive its first frames both without and with a document.
#[test]
fn the_whole_window_runs_a_few_frames() {
let mut h = crate::test_harness::harness_with(
Session::new(),
Services::default(),
egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)),
|_| {},
);
h.run_steps(3);
assert!(h.state().session.active().is_none());
deckcraft_engine::sample::open_sample(&mut h.state_mut().session).unwrap();
h.state_mut().ui.view = ViewMode::Normal;
h.run_steps(3);
assert!(h.state().canvas_rect().is_some());
assert!(h.state().picture.region.is_some());
}
/// Quick-access digits respect text editing, Backstage, key policy and slot availability.
#[test]
fn alt_digit_runs_a_quick_access_slot_unless_text_is_edited() {
use egui::Key;
for (mac, editing, backstage, key, runs) in [
(false, false, false, Key::Num1, true),
(false, true, false, Key::Num1, false),
(true, false, false, Key::Num1, false),
(false, false, true, Key::Num1, false),
(false, false, false, Key::Num9, false),
(false, false, false, Key::Num4, false),
] {
let mut h = crate::test_harness::harness(Session::with_new(), Services::default());
h.state_mut().session.mac_keys = mac;
if editing {
let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0;
h.state_mut().run("text.edit", json!({"id": title})).unwrap();
}
if backstage {
h.state_mut().run("app.home", json!({"on": true})).unwrap();
}
h.run_steps(2);
if key == Key::Num4 {
assert!(h.state().session.active().unwrap().history.undo.is_empty());
}
let before = h.state().backstage_open();
let document = serde_json::to_value(&h.state().session.active().unwrap().doc).unwrap();
h.key_press_modifiers(egui::Modifiers::ALT, key);
h.run_steps(2);
assert_eq!(
h.state().backstage_open(),
if runs { !before } else { before },
"mac={mac}, editing={editing}, backstage={backstage}, key={key:?}"
);
let after = serde_json::to_value(&h.state().session.active().unwrap().doc).unwrap();
if editing {
// The framework composes a top-row Alt code into the text being edited (craft-libs alt_code, the suite's
// rule since the sync); what this guards is that the slot does not run, and only the edited text changes.
let title = |doc: &serde_json::Value| doc["slides"][0]["shapes"][0].clone();
let mut rest = after.clone();
rest["slides"][0]["shapes"][0] = title(&document);
assert_eq!(rest, document, "only the edited text changes: mac={mac}, key={key:?}");
} else {
assert_eq!(after, document, "mac={mac}, editing={editing}, backstage={backstage}, key={key:?}");
}
}
}
/// Shipped scripts must have real ink in the font stack installed at app startup.
#[test]
fn interface_text_in_every_shipped_script_has_ink() {
let mut h = crate::test_harness::harness(Session::new(), Services::default());
h.run_steps(2);
h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic);
let tokens = craft::ui::runtime::env::Env::of_root(&h.ctx).tokens.clone();
for (script, text) in [
("Hangul", "한글"),
("Simplified Chinese", "简体中文演示文稿"),
("Hebrew", "עבריתשלום"),
("kana", "ひらがなカタカナ"),
("punctuation", "·•…–—'\"!|.,:;"),
] {
for role in [craft::theme::TypeRole::Body, craft::theme::TypeRole::Caption] {
let font = egui::FontId::proportional(tokens.typography.get(role).size);
let covered = h.ctx.fonts_mut(|fonts| text.chars().all(|c| fonts.has_glyph(&font, c)));
let available = text
.chars()
.all(|c| c.is_ascii() || deckcraft_fonts::FontDb::global().fallback_for_filtered(c, u32::MAX, |face| !face.is_color()).is_some());
if !available {
assert!(option_env!("CRAFT_FONTS_REQUIRED").is_none(), "required font input lacks {script}");
eprintln!("optional font input absent: {script} ink at {role:?} was not qualified");
continue;
}
assert!(covered, "the installed stack lacks {script} at {role:?}");
h.ctx.fonts_mut(|fonts| {
let galley = fonts.layout_no_wrap(text.into(), font, egui::Color32::WHITE);
let glyphs: Vec<_> = galley.rows.iter().flat_map(|r| &r.glyphs).collect();
assert!(!glyphs.is_empty(), "{script}: no glyphs");
for glyph in glyphs {
assert!(glyph.uv_rect.size.x > 0.0 && glyph.uv_rect.size.y > 0.0, "{script}: {:?} has no ink at {role:?}", glyph.chr);
}
});
}
}
h.run_steps(1);
}