Compare commits

..
Author SHA1 Message Date
autocraft-bot[bot] aac21c8baf Merge main (4680b9a2) into the pull request
I resolved the one conflict, in crates/ui-egui/src/widgets/tests.rs, by 

I resolved the one conflict, in crates/ui-egui/src/widgets/tests.rs, by keeping the pull request's `scroll_fonts_until(&mut h, 20.0, ...)` call before the heading assertions in the `restores_recents` branch. The default branch's side of the conflict was empty, and the surrounding merged code already requires both section headings. No conflict markers remain in that file, and `cargo fmt --all --check` passes.

The test was not verified. A first run of `cargo test --offline -p wordcraft-ui-egui --lib the_typed_list` timed out while the build pod was starting. A second run was still unfinished after about 46 minutes, across runner restarts, so I stopped it. Its output was piped through `tail`, so I don't know how far it got. I did not run clippy.

One thing to check: the merged code before my resolution appears to require the headings without scrolling. With the pull request's call kept, the test scrolls up to find a missing heading before failing, so it would not catch headings that are merely out of view on the clearing frame.
2026-12-04 21:51:24 +00:00
batistalucasv bd5a4e8039 test(widgets): always require section headings on font_box clearing frames (#8774) 2026-12-03 23:46:01 -03:00
10 changed files with 60 additions and 404 deletions
-91
View File
@@ -4005,97 +4005,6 @@ fn header_and_footer_link_annotations_are_tagged_on_every_page() {
assert_eq!(top_roles, vec!["Div", "P", "Div", "Div", "P", "Div"], "header link before body, footer link after body");
}
/// Neighbouring table cells carrying the same link URL keep separate Link elements, MCIDs, and
/// OBJRs inside their own TD cells (both in RTL tables and when a right-aligned first cell puts
/// the two runs within one em of each other).
#[test]
fn table_cell_links_with_same_target_stay_in_their_own_cells() {
use hayro_syntax::object::{Array, Dict, Name, Object};
use wordcraft_doc::props::{Align, TableProps};
use wordcraft_doc::{Cell, Row, Table};
let link_props = CharProps { link: Some("https://example.com".into()), ..Default::default() };
let make_cell = |text: &str, align: Option<Align>| {
let mut p = Paragraph::with_text(text, link_props.clone());
p.props.align = align;
Cell { blocks: vec![para_block(p)], ..Cell::empty() }
};
for (name, bidi_visual, first_align) in [("rtl", true, None), ("ltr-right-aligned", false, Some(Align::Right))] {
let row = Row { cells: vec![make_cell("First", first_align), make_cell("Second", None)], ..Default::default() };
let table = Table {
props: TableProps { bidi_visual, cell_margins: Some([0.0, 5.4, 0.0, 5.4]), ..Default::default() },
grid: vec![120.0, 120.0],
rows: vec![row],
..Default::default()
};
let mut d = Document::new();
d.body = vec![Arc::new(Block::Table(table))];
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
let annots = pdf.pages()[0].raw().get::<Array>(b"Annots").expect("page Annots");
let annot_ids: Vec<String> = annots.iter::<Dict>().map(|a| format!("{:?}", a.obj_id().expect("indirect annot"))).collect();
assert_eq!(annot_ids.len(), 2, "{name}: expected two link annotations, got {annot_ids:?}");
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
let struct_tree = root.get::<Dict>(b"StructTreeRoot").expect("StructTreeRoot");
fn children<'a>(dict: &Dict<'a>) -> Vec<Object<'a>> {
match dict.get::<Object>(b"K") {
Some(Object::Array(a)) => a.iter::<Object>().collect(),
Some(other) => vec![other],
None => Vec::new(),
}
}
fn collect_links(d: &Dict, out: &mut Vec<(bool, Option<String>)>) {
if d.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"Link") {
let mut has_mcid = false;
let mut objr = None;
for item in children(d) {
match item {
Object::Number(_) => has_mcid = true,
Object::Dict(o) if o.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") => {
objr = o.get::<Dict>(b"Obj").and_then(|obj| obj.obj_id()).map(|id| format!("{id:?}"));
}
_ => {}
}
}
out.push((has_mcid, objr));
}
for item in children(d) {
if let Object::Dict(c) = item {
collect_links(&c, out);
}
}
}
fn collect_tds(dict: &Dict, out: &mut Vec<Vec<(bool, Option<String>)>>) {
if dict.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"TD") {
let mut cell_links = Vec::new();
collect_links(dict, &mut cell_links);
out.push(cell_links);
return;
}
for item in children(dict) {
if let Object::Dict(c) = item {
collect_tds(&c, out);
}
}
}
let mut tds = Vec::new();
collect_tds(&struct_tree, &mut tds);
assert_eq!(tds.len(), 2, "{name}: expected 2 TD cells, got {tds:?}");
assert_eq!(tds[0].len(), 1, "{name}: first TD should hold 1 Link: {tds:?}");
assert_eq!(tds[1].len(), 1, "{name}: second TD should hold 1 Link: {tds:?}");
assert!(tds[0][0].0 && tds[1][0].0, "{name}: both cell Links must hold an MCID: {tds:?}");
let objr0 = tds[0][0].1.as_deref().expect("first TD Link OBJR");
let objr1 = tds[1][0].1.as_deref().expect("second TD Link OBJR");
assert_ne!(objr0, objr1, "{name}: cells must reference distinct OBJR annotations: {tds:?}");
assert!(annot_ids.iter().any(|id| id == objr0) && annot_ids.iter().any(|id| id == objr1), "{name}: OBJRs must match page Annots");
}
}
/// A paragraph's continuation must follow the footer and header between its pages.
#[test]
fn spanning_paragraph_links_follow_page_reading_order() {
+2 -5
View File
@@ -181,7 +181,7 @@ pub enum Target {
/// What the pick is remembered as.
remember: Remember,
},
/// Run nothing: the pick is only reported in [`ColorPick::picked`].
/// Run nothing: the pick is only reported in [`ColorPick::picked`] (a gradient stop's colour).
Pick,
}
@@ -258,10 +258,7 @@ fn cell_shading(table: &wordcraft_doc::Table, cells: impl IntoIterator<Item = (u
/// differs across the selection, or cannot be read (a picture's icon colour is not stored).
fn current_of(app: &mut WordApp, target: &Target) -> Option<Rgb> {
use wordcraft_doc::InlineObject;
let Target::Run { cmd, params, at, .. } = target else { return None };
if let Some(c) = params.pointer(at).and_then(Value::as_str).and_then(parse) {
return Some(c);
}
let Target::Run { cmd, .. } = target else { return None };
let s = &app.session;
let shapes = |o: &InlineObject| matches!(o, InlineObject::Shape { .. }) || o.is_canvas();
let objects = || wordcraft_engine::cmd::objects::target_objects(s, shapes).into_iter().map(|(_, o)| o);
+11 -76
View File
@@ -13,7 +13,7 @@ use craft::theme::Srgba;
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::choice::{Checkbox, Radio, RadioGroup};
use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _, ShowContainer as _, Trigger, clicked};
use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _, ShowContainer as _, Trigger};
use craft::ui::form::{Field, SliderField};
use craft::ui::layout_components::Stack;
use craft::ui::menu::Menu;
@@ -509,9 +509,7 @@ fn solid(app: &mut WordApp, ui: &mut Ui, theme: &[Rgb], color: Rgb, transparency
let mut hex = color.hex();
let label: Label = tl!("Color").into();
let picked = color_field(ui, &label, &mut hex, &ColorFieldEmpty::NoColor, &palette);
if picked.more_colors {
colors::open_for(app, &Target::cmd("shape.fill"), Some(color), craft::color_ui::ui::ColorPickerTab::Standard);
} else if picked.changed
if picked.changed
&& let Some(n) = Rgb::parse(&hex)
{
let _ = app.run("shape.fill", json!({"color": n.hex()}));
@@ -679,22 +677,17 @@ fn gradient(app: &mut WordApp, ui: &mut Ui, g: &Gradient) {
// PLAN: the framework has no public kept-value write; the open flag goes through the saved value
let was: bool = saved_value(&ctx, &key);
let mut open = was || editor.color_requested.is_some();
let stop_at = editor.color_requested.as_ref().map(|c| c.index).or(match editor.selected {
Some(StopRef::Color(at)) => Some(at),
_ => None,
});
let stop_target = match stop_at.filter(|&at| at < g.stops.len()) {
Some(at) => Target::at("shape.fill", shape_fill::params(Some(&Fill::Gradient(Arc::new(g.clone())))), &format!("/gradient/stops/{at}/color")),
None => Target::Pick,
};
let mut close_popover = false;
let mut chosen = None;
Popover::new(tl!("Stop color"), Bind::bound(&mut open)).opened_by(editor.response()).show(ui, |ui, _| {
let pick = colors::palette(ui, app, stop_target.clone());
if pick.picked.is_some() || clicked(&pick.response) {
close_popover = true;
}
// PLAN: assumed colors::palette(ui, app, Target::Pick) -> ColorPick (ribbon-w11, rb.A4)
chosen = colors::palette(ui, app, Target::Pick).picked;
});
if close_popover {
if let (Some(color), Some(StopRef::Color(at))) = (chosen, editor.selected) {
let mut stops = stops_of(g);
if let Some(stop) = stops.color.get_mut(at) {
stop.color = srgba(color, stop.color.a);
apply(app, Some(&with_stops(g, &stops)));
}
open = false;
}
if open != was {
@@ -1073,64 +1066,6 @@ mod tests {
assert_eq!(stroke(h.state()), Some(wordcraft_doc::Rgb(255, 0, 0)));
}
/// Selecting More Colors… in the Solid fill color picker applies the custom color via `shape.fill`
/// while preserving transparency.
#[test]
fn format_shape_pane_solid_more_colors_applies_fill() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
a.run("shape.fill", json!({"color": "112233", "transparency": 35})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
h.query_all_by_role_and_label(egui::accesskit::Role::Button, "Color #112233").last().expect("solid fill color field").click();
h.run_steps(3);
h.get_by_label("More Colors…").click();
h.run_steps(3);
let dialog = h.state_mut().dialog_host.get_mut::<craft::color_ui::ui::ColorPickerDialog>().expect("Colors dialog opened");
assert_eq!(dialog.opening().map(|p| super::rgb_of(p.color)), Some(wordcraft_doc::Rgb(0x11, 0x22, 0x33)));
dialog.set_color(craft::color_ui::ui::PickedColor::rgb(craft::theme::Srgba::rgb(0.0, 1.0, 0.0)));
let ctx = h.ctx.clone();
assert!(h.state_mut().dialog_host.confirm::<craft::color_ui::ui::ColorPickerDialog>(&ctx));
crate::dialogs::host::settle(h.state_mut(), &ctx);
assert_eq!(fill(h.state()), Some(Fill::Solid { color: wordcraft_doc::Rgb(0, 255, 0), transparency: 35.0 }));
}
/// Selecting More Colors… from a gradient stop's color popover applies the custom color to that
/// stop while keeping the other stops and gradient settings intact.
#[test]
fn format_shape_pane_gradient_stop_more_colors_applies_stop_color() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
a.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
let stops = json!([{"pos": 0, "color": "FFFFFF", "transparency": 20}, {"pos": 100, "color": "156082", "transparency": 50}]);
a.run("shape.fill", json!({"gradient": {"stops": stops, "angle": 90}})).unwrap();
a.run("view.formatShapePane", json!({"value": true})).unwrap();
let mut h = harness(a);
h.run_steps(4);
h.get_by_label("Color stop 2 of 2").click();
h.run_steps(3);
h.key_press(egui::Key::Enter);
h.run_steps(3);
h.get_by_label("More Colors…").click();
h.run_steps(3);
let dialog = h.state_mut().dialog_host.get_mut::<craft::color_ui::ui::ColorPickerDialog>().expect("Colors dialog opened");
assert_eq!(dialog.opening().map(|p| super::rgb_of(p.color)), Some(wordcraft_doc::Rgb(0x15, 0x60, 0x82)));
dialog.set_color(craft::color_ui::ui::PickedColor::rgb(craft::theme::Srgba::rgb(1.0, 0.0, 0.0)));
let ctx = h.ctx.clone();
assert!(h.state_mut().dialog_host.confirm::<craft::color_ui::ui::ColorPickerDialog>(&ctx));
crate::dialogs::host::settle(h.state_mut(), &ctx);
let Some(Fill::Gradient(g)) = fill(h.state()) else { panic!("expected gradient fill, got {:?}", fill(h.state())) };
assert_eq!(g.stops.len(), 2);
assert_eq!(g.stops[0].color, wordcraft_doc::Rgb(0xFF, 0xFF, 0xFF));
assert_eq!(g.stops[1].color, wordcraft_doc::Rgb(255, 0, 0));
assert_eq!(g.stops[1].transparency, 50.0);
}
fn png_data() -> String {
let img = image::RgbaImage::from_fn(20, 10, |x, y| {
if x > 2 && x < 17 && y > 2 && y < 7 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([255, 255, 255, 255]) }
-103
View File
@@ -1652,109 +1652,6 @@ mod tests {
assert!(backend.network.load(Ordering::Relaxed), "the person's click in the picker is the consent");
}
/// The bounds of the first node whose label starts with `label`.
fn bounds_of(tree: &egui::accesskit::TreeUpdate, label: &str) -> Option<egui::accesskit::Rect> {
tree.nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.starts_with(label))).and_then(|(_, n)| n.bounds())
}
/// In the Add a language picker, the reason an agent's Install was refused shows in that row with its license,
/// whatever the license's length (Dutch's is one short line, Catalan's wraps).
#[test]
fn a_refused_install_says_why_in_its_own_row() {
let _g = BACKEND_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let _reset = ResetBackend;
let (mut a, ctx, backend) = options_app("language", false);
// The fetch the click starts runs on a thread and reports its end here.
let (done, ended) = std::sync::mpsc::channel();
packs::set_background(Some(std::sync::Arc::new(move || {
let _ = done.send(());
})));
let add = spot(&settled(&mut a, &ctx), "Add a language").expect("the button");
user_click(&mut a, &ctx, add);
assert!(a.dialog_host.is_open::<super::AddLanguage>(), "the picker opens");
while packs::fetching() {
ended.recv().expect("the fetch reports its end");
}
backend.network.store(false, Ordering::Relaxed);
for (row, locale) in [("Dutch", "nl"), ("Catalan", "ca")] {
let tree = settled(&mut a, &ctx);
let shown = bounds_of(&tree, row).unwrap_or_else(|| panic!("{row} is listed: {:?}", labels(&tree)));
let install = tree
.nodes
.iter()
.filter(|(_, n)| n.label().is_some_and(|l| l.starts_with("Install")))
.filter_map(|(_, n)| n.bounds())
.find(|b| (b.y0 + b.y1) / 2.0 > shown.y0 && (b.y0 + b.y1) / 2.0 < shown.y1)
.unwrap_or_else(|| panic!("{row} offers Install"));
as_agent(&mut a, &ctx, "ui.click", json!({"x": (install.x0 + install.x1) / 2.0, "y": (install.y0 + install.y1) / 2.0}));
assert!(a.packs_rt.errors.get(locale).is_some_and(|e| e.contains("Only you")), "{row}: {:?}", a.packs_rt.errors);
let tree = settled(&mut a, &ctx);
let shown = bounds_of(&tree, row).expect("the row stays listed");
// The row's bounds stop at the list's visible edge, and the reason may run past it, so the reason starts
// inside the row. It is at least as wide as the row's Install, so it has room to be read.
let reason = tree.nodes.iter().find(|(_, n)| {
n.label().is_some_and(|l| l.contains("Only you"))
&& n.bounds()
.is_some_and(|b| b.width() >= install.width() && b.x0 >= shown.x0 && b.x1 <= shown.x1 && b.y0 >= shown.y0 && b.y0 < shown.y1)
});
let why: Vec<_> = tree.nodes.iter().filter(|(_, n)| n.label().is_some_and(|l| l.contains("Only you"))).map(|(_, n)| n.bounds()).collect();
let reason =
reason.map(|(id, _)| *id).unwrap_or_else(|| panic!("{row}'s row ({shown:?}) says why, as wide as Install ({install:?}): {why:?}"));
// Scrolled into view, the whole reason fits inside the list's visible area: the list's bounds cut to the
// picker's, below the Search field and above the Close footer (the list's own bounds run on past the
// picker when it scrolls, and the picker's bounds take in its footer).
let visible = |tree: &egui::accesskit::TreeUpdate| {
let find = |role: egui::accesskit::Role, label: &str| {
tree.nodes.iter().find(|(_, n)| n.role() == role && n.label() == Some(label)).and_then(|(_, n)| n.bounds())
};
let list = find(egui::accesskit::Role::List, "Languages").expect("the list");
let picker = find(egui::accesskit::Role::Dialog, "Add a language").expect("the picker");
let in_picker = |label: &str| {
tree.nodes
.iter()
.filter(|(_, n)| n.label() == Some(label))
.filter_map(|(_, n)| n.bounds())
.filter(|b| b.x0 >= picker.x0 && b.x1 <= picker.x1 && b.y0 >= picker.y0 && b.y1 <= picker.y1)
.collect::<Vec<_>>()
};
let search = *in_picker("Search").first().expect("the picker's Search field");
// The picker has two Close buttons: one in its title bar, above the Search field, and the footer's below
// it. Which comes first in the tree depends on the node ids, so take the footer's by position.
let close = in_picker("Close")
.into_iter()
.filter(|b| b.y0 >= search.y1)
.min_by(|a, b| a.y0.total_cmp(&b.y0))
.expect("the picker's Close button");
(list.y0.max(picker.y0).max(search.y1), list.y1.min(picker.y1).min(close.y0), list)
};
let mut tree = tree;
let mut seen = None;
for _ in 0..20 {
let (top, bottom, list) = visible(&tree);
let b = tree.nodes.iter().find(|(id, _)| *id == reason).and_then(|(_, n)| n.bounds()).expect("the reason stays shown");
seen = Some((b, top, bottom));
if b.y0 >= top && b.y1 <= bottom {
break;
}
let delta = if b.y1 > bottom { bottom - b.y1 } else { top - b.y0 };
let center = egui::pos2(((list.x0 + list.x1) / 2.0) as f32, ((top + bottom) / 2.0) as f32);
let wheel = egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, delta as f32),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Unknown,
modifiers: Default::default(),
};
frame(&mut a, &ctx, vec![egui::Event::PointerMoved(center), wheel]);
tree = settled(&mut a, &ctx);
}
assert!(
seen.is_some_and(|(b, top, bottom)| b.y0 >= top && b.y1 <= bottom),
"{row}'s reason fits inside the list's visible area (reason, top, bottom): {seen:?}"
);
}
}
/// Set as default sets only the saved default proofing language (`review.language.preferred`); the
/// document, its undo history, the redo stack and the modified flag are untouched.
#[test]
-2
View File
@@ -187,7 +187,6 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
let mut family = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
let picked = crate::widgets::font_box::font_box(ui, app, tl!("Font").to_string(), &mut family);
crate::ribbon::common::painted_ibeam_over(ui, &picked.edit.response);
follow_list(app, preview, &picked.preview, |f| Some(("format.font".to_string(), json!({"name": f}))));
if let Some(f) = &picked.picked {
let _ = app.run("format.font", json!({"name": f}));
@@ -201,7 +200,6 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
let mut text = size.clone();
// `text` is rebuilt from the selection on every pass: the box keeps what is typed until Enter.
let combo = ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut text).policy(EditPolicy::OnCommit), &sizes).show(ui);
crate::ribbon::common::painted_ibeam_over(ui, &combo.edit.response);
follow_list(app, preview, &combo.preview, |v| {
v.trim().parse::<f64>().ok().map(|x| ("format.size".to_string(), json!({"size": x})))
});
+1 -14
View File
@@ -1,7 +1,5 @@
use std::ops::RangeInclusive;
use craft::behavior::cursor::{Cursor, CursorPriority, PaintedCursor};
use craft::host::target::{Os, Runtime};
use craft::keymap::CommandRef;
use craft::menu::ribbon::{RibbonGroup, RibbonRow};
use craft::ui::buttons::{Arrangement, Button};
@@ -13,7 +11,7 @@ use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::ThumbAspect;
use craft::ui::menu::{Menu, MenuItem, MenuOutput};
use craft::ui::primitives::{FacePaint, IconSpec};
use craft::ui::runtime::env::{Env, Label};
use craft::ui::runtime::env::Label;
use craft::ui::text::NumberField;
use serde_json::Value;
@@ -70,17 +68,6 @@ pub(crate) fn labelled<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R {
)
}
/// On Windows the system I-beam is the legacy white XOR cursor over the GPU surface; the page
/// replaces it with the framework's painted beam. Do the same over a ribbon or mini-toolbar text
/// field on hover.
pub(crate) fn painted_ibeam_over(ui: &Ui, response: &egui::Response) {
let env = Env::of(ui);
let shell = env.view().shell();
if shell.os == Os::Windows && shell.runtime == Runtime::Native && response.hovered() {
craft::ui::runtime::cursor::request(ui.ctx(), Cursor::Painted(PaintedCursor::IBeam), CursorPriority::Hover);
}
}
/// Two rows of small controls spread over the ribbon's body, `row(ui, 0)` above `row(ui, 1)`, with as much room above
/// the first, between them and under the second, so a two-row group fills the height of the three rows beside it and
/// leaves no empty band over its title.
+1 -3
View File
@@ -14,7 +14,7 @@ use craft::ui::primitives::{HAlign, TextRun};
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
use wordcraft_doc::props::Align;
use super::common::{icon_only, menu_button, painted_ibeam_over, two_rows};
use super::common::{icon_only, menu_button, two_rows};
use super::underline::underline_menu;
use egui::vec2;
use serde_json::Value;
@@ -200,7 +200,6 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
if at == 0 {
let mut family = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
let out = crate::widgets::font_box(ui, app, tl!("Font").to_string(), &mut family);
painted_ibeam_over(ui, &out.edit.response);
if let Some(f) = out.picked {
let _ = app.run("format.font", json!({"name": f}));
}
@@ -208,7 +207,6 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut size), font_size_entries())
.tooltip(tl!("Font Size").to_string())
.show(ui);
painted_ibeam_over(ui, &out.edit.response);
if let Some(v) = out.edit.events.committed()
&& let Ok(x) = v.trim().parse::<f64>()
{
-30
View File
@@ -2458,36 +2458,6 @@ fn clicks_on_ribbon_and_status_bar_chrome_keep_typing_in_the_document() {
assert_eq!(body_text(h.state()), before, "typing went into the font size box, not the page");
}
/// #7757: Windows draws its system text I-beam in white over the app's surface, so the ribbon's font
/// fields looked cursorless there. Like the page, the font size box must ask for craft's painted
/// I-beam on a native Windows shell; other shells keep the system text cursor.
#[test]
fn the_ribbon_font_size_box_shows_a_painted_ibeam_on_windows() {
use craft::host::target::{Os, Runtime};
use egui::accesskit::Role;
let mut h = harness(app());
h.run_steps(4);
let size =
h.get_all_by_role(Role::TextInput).find(|n| n.value().is_some_and(|v| v.trim().parse::<f64>().is_ok())).expect("the font size box").rect();
h.hover_at(size.center());
h.step();
h.step();
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
let shell = env.view().shell();
if shell.os == Os::Windows && shell.runtime == Runtime::Native {
assert!(h.output().platform_output.cursor_image.is_some(), "the font size box asks for the painted I-beam on Windows native");
assert_eq!(
craft::ui::runtime::cursor::current(&h.ctx),
Some(craft::behavior::cursor::Cursor::Painted(craft::behavior::cursor::PaintedCursor::IBeam)),
"the font size box asks for the painted I-beam"
);
} else {
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Text, "other shells keep the text cursor");
}
}
/// #1538: inserting WordArt leaves its text selected, so Delete erased only the text and the
/// empty box stayed. Escape now selects the box itself, Delete removes it, and a second Escape
/// is back to a caret in the body.
+42 -77
View File
@@ -3,10 +3,8 @@ use std::sync::Arc;
use craft::font_manager::Catalog;
use craft::font_manager::craft_font_catalog::{FontEnv, Os};
use craft::font_manager::missing::MissingFontsWords;
use craft::host::{Host, PickKind, ScriptedFiles};
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Props as _, Show as _, tooltip};
use craft::ui::contract::{Props as _, Show as _};
use egui::accesskit::Role;
use egui::{Key, vec2};
use egui_kittest::kittest::{By, NodeT, Queryable};
@@ -227,49 +225,24 @@ fn drawn_buttons_fade_in_on_hover_and_darken_while_pressed() {
assert_eq!(fill_after, None, "Save button must clear hover fill after unhovering");
}
/// #7317 / #8447 / #8778: WordCraft's `font_box` warns with `MissingAdvice::AddFont` for an
/// uninstalled family, updates the popup list on the same frame as each keystroke, shows the
/// Recently Used Fonts section again when cleared, places `Add Font…` last, and picking `Add Font…`
/// runs `font.add` without changing the family.
/// #7317 / #8447: typing in WordCraft's `font_box` updates the popup list on the same frame as
/// the keystroke, shows the Recently Used Fonts section (and WordCraft's `Add Font…` action row)
/// again when cleared, and narrows immediately on subsequent typing.
#[test]
fn the_typed_list_shows_on_the_frame_of_the_keystroke() {
const RECENT: &str = "Source Serif 4";
const MISSING: &str = "Wordcraft Missing Face";
let files = Arc::new(ScriptedFiles::held());
let host = Host::builder(crate::APP).files(files.clone()).build();
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample")), Services::default()).with_host(Arc::new(host));
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample")), Services::default());
app.ui.language = "en".into();
app.font_catalog = Some(fixed_catalog());
app.ui.font_picker.recent = vec![RECENT.to_string()];
let substitute = app.font_box_warning(MISSING).expect("missing family produces a substitute warning");
let words = MissingFontsWords::default();
let expected_note = format!("{} {}", words.shown_as.fill(&[("family", MISSING), ("face", &substitute)]), words.add_font.as_str());
let mut family = String::new();
let mut h = crate::test_harness::builder().with_size(vec2(400.0, 900.0)).build_ui_state(
|ui, (app, family): &mut (WordApp, String)| {
let _ = super::font_box(ui, app, "Font", family);
},
(app, MISSING.to_string()),
);
let mut h = crate::test_harness::builder().with_size(vec2(400.0, 900.0)).build_ui(move |ui| {
let _ = super::font_box(ui, &mut app, "Font", &mut family);
});
h.run_steps(2);
// Resting on the warning mark shows the missing-font note together with MissingAdvice::AddFont.
let input_rect = h.get(By::new().role(Role::TextInput)).rect();
let chevron_rect = h.get_by_role_and_label(Role::Button, "Fonts").rect();
let warning_pos = egui::pos2((input_rect.max.x + chevron_rect.min.x) * 0.5, chevron_rect.center().y);
assert!(
h.query_by_label_contains(words.add_font.as_str()).is_none(),
"missing-font advice should wait until the pointer rests on the warning mark"
);
h.event(egui::Event::PointerMoved(warning_pos));
let delay_frames = (tooltip::DELAY / 0.25).ceil() as usize + 3;
h.run_steps(delay_frames);
assert!(
h.query_by_label(expected_note.as_str()).is_some(),
"expected missing-font note with MissingAdvice::AddFont when hovering the warning mark; substitute={substitute:?}"
);
h.get(By::new().role(Role::TextInput)).click();
h.run_steps(2);
@@ -279,7 +252,7 @@ fn the_typed_list_shows_on_the_frame_of_the_keystroke() {
egui::Event::Key { key: Key::Backspace, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE },
]
};
let send = |h: &mut egui_kittest::Harness<'static, (WordApp, String)>, events: Vec<egui::Event>| {
let send = |h: &mut egui_kittest::Harness<'static, ()>, events: Vec<egui::Event>| {
for ev in events {
h.event(ev);
}
@@ -310,6 +283,31 @@ fn the_typed_list_shows_on_the_frame_of_the_keystroke() {
}
}
fn scroll_fonts_until(
h: &mut egui_kittest::Harness<'static, ()>,
delta_y: f32,
mut ready: impl FnMut(&egui_kittest::Harness<'static, ()>) -> bool,
) {
if ready(h) {
return;
}
let list_center = h.get_by_role_and_label(Role::ListBox, "Fonts").rect().center();
h.event(egui::Event::PointerMoved(list_center));
for _ in 0..20 {
if ready(h) {
break;
}
h.event(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Page,
delta: vec2(0.0, delta_y),
phase: egui::TouchPhase::Move,
modifiers: egui::Modifiers::NONE,
source: egui::MouseWheelSource::Unknown,
});
h.step();
}
}
for (n, (events, expected, excluded, restores_recents)) in frames.into_iter().enumerate() {
send(&mut h, events);
let mut texts = Vec::new();
@@ -323,6 +321,7 @@ fn the_typed_list_shows_on_the_frame_of_the_keystroke() {
assert!(texts.iter().all(|t| t != label), "keystroke {n}: expected {label:?} to be filtered out on the frame, got texts: {texts:?}");
}
if restores_recents {
scroll_fonts_until(&mut h, 20.0, |h| h.query_by_label("Recently Used Fonts").is_some() && h.query_by_label("All Fonts").is_some());
let recent_y = h.get_by_label("Recently Used Fonts").rect().min.y;
let all_y = h.get_by_label("All Fonts").rect().min.y;
assert!(
@@ -335,47 +334,13 @@ fn the_typed_list_shows_on_the_frame_of_the_keystroke() {
}
}
// Clearing `"int"` restores the full list with WordCraft's `Add Font…` action row last.
// Clearing `"int"` restores the full list with WordCraft's `Add Font…` action row at the end.
for _ in 0..3 {
send(&mut h, erase());
}
let list_center = h.get_by_role_and_label(Role::ListBox, "Fonts").rect().center();
h.event(egui::Event::PointerMoved(list_center));
let scroll_down = |h: &mut egui_kittest::Harness<'static, (WordApp, String)>| {
h.event(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Page,
delta: vec2(0.0, -20.0),
phase: egui::TouchPhase::Move,
modifiers: egui::Modifiers::NONE,
source: egui::MouseWheelSource::Unknown,
});
h.step();
};
let visible_rows = |h: &egui_kittest::Harness<'static, (WordApp, String)>| -> Vec<(String, f32)> {
let mut rows: Vec<(String, f32)> =
h.query_all_by_role(Role::TreeItem).filter_map(|n| Some((n.accesskit_node().label()?, n.rect().min.y))).collect();
rows.sort_by(|a, b| a.1.total_cmp(&b.1));
rows
};
for _ in 0..50 {
if h.query_by_role_and_label(Role::TreeItem, "Add Font…").is_some() {
break;
}
scroll_down(&mut h);
}
assert!(h.query_by_role_and_label(Role::TreeItem, "Add Font…").is_some(), "expected WordCraft's Add Font… action row in font_box's cleared list");
scroll_down(&mut h);
let rows = visible_rows(&h);
assert!(rows.len() >= 2, "expected font families above Add Font… in the list, got {rows:?}");
assert_eq!(rows.last().map(|(label, _)| label.as_str()), Some("Add Font…"), "expected Add Font… to be the last row, got {rows:?}");
// Picking Add Font… runs `font.add` without changing `family`.
assert!(files.requests().is_empty(), "no file picker request before picking Add Font…");
h.get_by_role_and_label(Role::TreeItem, "Add Font…").click();
h.run_steps(2);
let requests = files.requests();
assert_eq!(requests.len(), 1, "picking Add Font… should run font.add");
assert_eq!(requests[0].purpose, "font");
assert_eq!(requests[0].kind, PickKind::OpenMany);
assert_eq!(h.state().1, MISSING, "picking Add Font… should leave the family unchanged");
scroll_fonts_until(&mut h, -20.0, |h| h.query_by_role_and_label(Role::TreeItem, "Add Font…").is_some());
assert!(
h.query_by_role_and_label(Role::TreeItem, "Add Font…").is_some(),
"expected WordCraft's Add Font… action row at the end of font_box's cleared list"
);
}
File diff suppressed because one or more lines are too long