Compare commits

..
7 changed files with 60 additions and 110 deletions
+1 -2
View File
@@ -16,8 +16,7 @@ mod objects;
pub(crate) use header_footer::saved_copy;
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers};
pub use items::{
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in, format_date_parts,
format_date_parts_in,
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_in, format_date_parts, format_date_parts_in,
};
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
use links::{bookmark, delete_bookmark, link, link_targets};
+1 -1
View File
@@ -26,7 +26,7 @@ pub(crate) mod symbol;
pub use columns::DropCapForm;
pub use date_time::DateTimeForm;
#[cfg(test)]
pub(crate) use date_time::date_time_previews_at;
pub(crate) use date_time::date_time_preview_matches;
pub use field::{DATE_FORMATS, FIELD_CATEGORIES, FIELDS, FieldForm, FieldKind, NUMBER_FORMATS, STYLEREF_SWITCHES, field_kind};
pub(crate) use symbol::SymbolDialog;
pub use symbol::{RECENT_SYMBOLS, RecentSymbol, SPECIAL, SUBSETS, SymbolForm, remember_symbol, subset_of};
@@ -35,16 +35,14 @@ const PT_DATE_FORMATS: &[&str] = &[
"HH:mm:ss",
];
/// What the Date and Time preview list shows at the instant `unix`: document values, not
/// interface strings. The i18n audit recognizes these instead of treating month names, dates and
/// times as labels.
/// The date preview list consists of document values (not interface strings).
/// The i18n audit recognizes these dynamic values instead of treating month names as UI labels.
#[cfg(test)]
pub(crate) fn date_time_previews_at(unix: u64) -> impl Iterator<Item = String> {
let offset = wordcraft_engine::cmd::local_offset_secs(unix);
PT_DATE_FORMATS
.iter()
.chain(DATE_FORMATS.iter())
.flat_map(move |picture| ["pt-BR", "en-US"].map(|lang| wordcraft_engine::cmd::insert::format_date_at_in(picture, Some(lang), unix, offset)))
pub(crate) fn date_time_preview_matches(value: &str) -> bool {
PT_DATE_FORMATS.iter().chain(DATE_FORMATS.iter()).any(|picture| {
wordcraft_engine::cmd::insert::format_date_in(picture, Some("pt-BR")) == value
|| wordcraft_engine::cmd::insert::format_date_in(picture, Some("en-US")) == value
})
}
/// State of the Word-like Insert > Date & Time dialog.
+20 -12
View File
@@ -14,12 +14,14 @@ use craft::behavior::IconId;
use craft::theme::Variant;
use craft::ui::buttons::Button;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked};
use craft::ui::contract::{Bind, Pad, Props as _, Show as _, ShowContainer as _, clicked};
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft::ui::display::{Badge, Icon, Shade, Text};
use craft::ui::layout_components::Row as Line;
use craft::ui::layout::RowAlign;
use craft::ui::layout_components::{Row as Line, Stack};
use craft::ui::primitives::IconSpec;
use craft::ui::sections::{DialogRole, FooterButton, GroupBox};
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::style::{SurfaceKind, TypeRole};
use egui::Ui;
use serde::Serialize;
@@ -272,15 +274,21 @@ impl StackDialog for FontBox {
.shade(Shade::Faint)
.show(ui);
for (at, g) in groups(fonts).into_iter().enumerate() {
// The names are the document's own words, not interface text.
GroupBox::new(g.fonts.join(", "), None).id_salt(("download", at)).show(ui, |ui, _| {
let shown_as =
crate::i18n::fmt(tl!("Shown as {fonts} · {publisher}"), &[("fonts", &g.shown_as.join(", ")), ("publisher", g.publisher)]);
Text::new(shown_as).shade(Shade::Faint).show(ui);
if g.restricted {
Text::new(tl!("Its licence limits who may use it: read the terms first.")).shade(Shade::Faint).show(ui);
}
Line::new().show(ui, |ui, _| {
// One row per download, as before the craft port: the names, what they are shown as and the licence
// note stacked at the start edge, the button at the end. The names are the document's own words.
Stack::new().surface(SurfaceKind::Frame).pad(Pad::Regular).fill_width().id_salt(("download_group", at)).show(ui, |ui, _| {
Line::new().fill_width().align(RowAlign::SpaceBetween).id_salt(("download", at)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
Text::new(g.fonts.join(", ")).role(TypeRole::BodyStrong).show(ui);
let shown_as = crate::i18n::fmt(
tl!("Shown as {fonts} · {publisher}"),
&[("fonts", &g.shown_as.join(", ")), ("publisher", g.publisher)],
);
Text::new(shown_as).shade(Shade::Faint).show(ui);
if g.restricted {
Text::new(tl!("Its licence limits who may use it: read the terms first.")).shade(Shade::Faint).show(ui);
}
});
if clicked(&Button::new(tl!("Download")).variant(Variant::PRIMARY).id_salt(("download_button", at)).show(ui)) {
asks.push(Ask::Download(g.url.to_string()));
}
+30
View File
@@ -233,3 +233,33 @@ fn only_so_many_documents_are_remembered() {
assert_eq!(a.font_notice_seen.len(), REMEMBERED);
assert_eq!(a.font_notice_seen.last(), Some(&(REMEMBERED as u64 + 49)));
}
/// Each missing font's names, substitute and Download button sit in one compact row, not one under another, and a
/// narrow window keeps them inside the box.
#[test]
fn each_download_is_one_row() {
let row = |font: &str, shown: &str, url: &str| Row {
font: font.into(),
shown_as: vec![shown.into()],
download: font.into(),
publisher: "Microsoft".into(),
url: url.into(),
restricted: false,
};
for width in [1440.0, 520.0] {
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
let fonts = vec![row("Aptos", "Carlito", "https://a"), row("Cascadia Code", "Liberation Mono", "https://c")];
open_with(&mut a, None, FontBox::new(fonts, false), DialogHooks { prepare: None, settle });
let h = harness_sized(a, egui::vec2(width, 900.0));
let buttons: Vec<_> = h.query_all_by_role_and_label(egui::accesskit::Role::Button, "Download").collect();
assert_eq!(buttons.len(), 2);
for (button, shown) in buttons.iter().zip(["Shown as Carlito · Microsoft", "Shown as Liberation Mono · Microsoft"]) {
let shown = h.get_by_label(shown).rect();
let button = button.rect();
// The button is beside the text block, level with it, not under it.
assert!(button.min.x >= shown.max.x, "{width}: {button:?} {shown:?}");
assert!(button.center().y < shown.max.y, "{width}: button under the text: {button:?} {shown:?}");
assert!(button.max.x <= width, "{width}: clipped {button:?}");
}
}
}
+1 -67
View File
@@ -28,14 +28,7 @@ fn unmarked(text: &str) -> String {
out
}
/// When the audit began: the Date and Time preview drawn at any moment since is clock data, not
/// interface text, whatever second the audit compares it in (#7463).
static CLOCK_START: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
thread_local! {
// Every date/time the preview list could show since `CLOCK_START`, up to the second last
// looked at: (next second to add, strings).
static CLOCK_TEXTS: std::cell::RefCell<(u64, std::collections::HashSet<String>)> = std::cell::RefCell::new(Default::default());
// Input time, advanced every frame so tooltips and animations move on.
static TIME: Cell<f64> = const { Cell::new(0.0) };
// Process-wide names (font families, the custom dictionary) seen at any point of the run:
@@ -43,19 +36,6 @@ thread_local! {
static GLOBAL_NAMES: std::cell::RefCell<std::collections::HashSet<String>> = std::cell::RefCell::new(Default::default());
}
/// Whether `text` is something the Date and Time preview list showed at any second since the audit began.
fn clock_text(text: &str) -> bool {
let start = *CLOCK_START.get_or_init(wordcraft_engine::cmd::now_unix);
let now = wordcraft_engine::cmd::now_unix();
CLOCK_TEXTS.with_borrow_mut(|(next, set)| {
for unix in (*next).max(start)..=now {
set.extend(crate::dialogs_insert::date_time_previews_at(unix));
}
*next = now + 1;
set.contains(text)
})
}
/// Remember the process-wide names drawn this frame could have come from.
fn note_global_names() {
GLOBAL_NAMES.with_borrow_mut(|seen| {
@@ -144,16 +124,11 @@ fn pseudo_app(ctx: &egui::Context) -> WordApp {
}
fn fresh_app(ctx: &egui::Context) -> WordApp {
CLOCK_START.get_or_init(wordcraft_engine::cmd::now_unix);
ctx.all_styles_mut(|s| s.interaction.tooltip_delay = 0.0);
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_engine::sample::sample_document()), Default::default());
// Read Aloud holds each sentence instead of starting the system's speech engine: no sound on
// machines that have one, and no worker thread failing at its own pace on machines that don't.
app.session.read_aloud.backend = wordcraft_engine::speech::Backend::Hold;
// Help › Check for Updates answers "up to date" instead of asking GitHub, whose rate limit
// would otherwise put the updater's error text on screen.
#[cfg(not(target_arch = "wasm32"))]
app.stub_update_check();
// Fonts install over the first frames.
for _ in 0..2 {
frame(ctx, &mut app);
@@ -161,11 +136,6 @@ fn fresh_app(ctx: &egui::Context) -> WordApp {
app
}
/// A link: one `http(s)://` word.
fn is_url(text: &str) -> bool {
(text.starts_with("https://") || text.starts_with("http://")) && !text.contains(char::is_whitespace)
}
/// Words (two or more ASCII letters in a row) drawn outside translation marks.
fn english_words(text: &str) -> bool {
let plain = unmarked(text);
@@ -314,8 +284,7 @@ impl<'a> Exempt<'a> {
|| matches!(plain, "WordCraft" | "WordCraft User" | "Discord" | "https://" | "auto" | "I. II. III." | "i. ii. iii." | "I, II, III, …" | "i, ii, iii, …")
|| plain == "CONFIDENTIAL" // the watermark dialog's text: document content, kept as typed
|| plain == "Figure 1" // the caption dialog's sample: the label goes into the document as is
|| clock_text(plain) // the Date and Time preview: formatted from the clock
|| is_url(plain) // a link is data, not wording
|| crate::dialogs_insert::date_time_preview_matches(plain)
}
}
@@ -331,41 +300,6 @@ fn math_placeholders_are_exact_math_input_only() {
assert!(!set.contains("Translate"), "ordinary interface wording is not exempt");
}
/// Runtime data is exempt (links, the clock's dates and times), wording is not (#7463), and
/// Check for Updates never reaches the network.
#[test]
fn runtime_data_is_exempt_and_wording_is_not() {
let ctx = crate::test_harness::context();
let mut app = fresh_app(&ctx);
let none = std::collections::HashSet::new();
let exempt = Exempt::new(&app, &none);
let now = wordcraft_engine::cmd::now_unix();
let offset = wordcraft_engine::cmd::local_offset_secs(now);
for picture in ["M/d/yyyy h:mm:ss am/pm", "h:mm:ss am/pm", "dddd, MMMM d, yyyy"] {
let drawn = wordcraft_engine::cmd::insert::format_date_at_in(picture, None, now, offset);
assert!(exempt.allows(&app, &drawn), "{drawn:?} is the clock");
}
assert!(exempt.allows(&app, "https://github.com/storytold/wordcraft/releases"));
assert!(!exempt.allows(&app, "Download the newest release"), "an unwrapped sentence is reported");
assert!(!exempt.allows(&app, "See https://example.com now"), "a sentence with a link is not a link");
assert!(!exempt.allows(&app, "11/22/1999 5:28:50 PM"), "a time before the audit began is not the preview");
// A stubbed check finds no update and puts no updater error on screen.
app.run("help.checkForUpdates", json!({})).expect("Check for Updates runs");
let calls = app.updates_rt.stub_calls.clone();
// The check runs on a worker thread: draw at least 30 frames, then until it has run (a loaded
// runner can be slow to start the thread, so the cap is wall-clock time, not a frame count).
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
for n in 0.. {
let drawn = frame(&ctx, &mut app);
assert!(drawn.iter().all(|t| !t.contains("request limit")), "{drawn:?}");
if n >= 30 && (calls.load(std::sync::atomic::Ordering::SeqCst) > 0 || std::time::Instant::now() > deadline) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(2));
}
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1, "the check went through the stub, not GitHub");
}
/// Fails on interface text drawn without going through the catalog, listed per UI state, and
/// prints the missing-translation report (`report_catalog_gaps`). `cargo xtask i18n-report` runs it
/// with `--nocapture`; `cargo xtask test` and `ci` run it that way instead of in the main test run.
-19
View File
@@ -16,9 +16,6 @@ pub(crate) struct Runtime {
/// The desktop app turns the check at start on; tests and the web build leave it off.
#[cfg(not(target_arch = "wasm32"))]
startup_check: bool,
/// How many times the test stub answered a check (see `stub_update_check`).
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) stub_calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
}
impl Default for Runtime {
@@ -28,8 +25,6 @@ impl Default for Runtime {
updater: Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).with_translator(translate),
#[cfg(not(target_arch = "wasm32"))]
startup_check: false,
#[cfg(all(test, not(target_arch = "wasm32")))]
stub_calls: Default::default(),
}
}
}
@@ -58,20 +53,6 @@ impl WordApp {
rt.updater = Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).with_translator(translate).with_source(refused_check());
}
/// Answers every update check with "up to date" instead of asking GitHub, so a test's result
/// doesn't depend on the network or its rate limit (#7463).
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) fn stub_update_check(&mut self) {
let rt = &mut self.updates_rt;
rt.startup_check = false;
let calls = rt.stub_calls.clone();
rt.updater =
Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).with_translator(translate).with_source(std::sync::Arc::new(move || {
calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(None)
}));
}
/// Starts the helper of an update that is ready, so that it installs once the process has
/// ended. Call it once the exit is certain, before a path that ends the process without
/// dropping the app. Later calls do nothing.