diff --git a/crates/text/src/find/matches.rs b/crates/text/src/find/matches.rs index f797dccac..d7b5b6ca6 100644 --- a/crates/text/src/find/matches.rs +++ b/crates/text/src/find/matches.rs @@ -51,6 +51,7 @@ impl FindMatches { } /// The page the search started from, so a refined query restarts from it. + #[must_use] pub fn from(&self) -> Option { self.from } diff --git a/crates/text/src/ui/find/bar.rs b/crates/text/src/ui/find/bar.rs index 6d6297ce4..3aea09930 100644 --- a/crates/text/src/ui/find/bar.rs +++ b/crates/text/src/ui/find/bar.rs @@ -1,10 +1,10 @@ //! The find bar: Acrobat's Cmd+F bar over a document. use craft_behavior::IconId; -use craft_ui::buttons::IconButton; +use craft_ui::buttons::{Button, IconButton}; use craft_ui::contract::{Bind, BodyCx, Commands as _, Entry, Outcome as _, Props as _, Show as _, ShowContainer as _, Trigger, clicked}; use craft_ui::display::Text; -use craft_ui::layout_components::Row; +use craft_ui::layout_components::{Row, Stack}; use craft_ui::menu::Menu; use craft_ui::runtime::access::PopupKind; use craft_ui::runtime::env::{Env, Units}; @@ -54,10 +54,16 @@ impl craft_ui::contract::Outcome for FindBarOutput { } /// Whether the bar has just been asked for, kept by the app beside its query ([`open`](Self::open) when Cmd+F opens -/// it, and again when it is asked for with the bar open). The bar clears it once the query field holds focus. +/// it, and again when it is asked for with the bar open). The bar clears it once the asked-for field holds focus, and +/// that field selects its text, so typing replaces it, whether it still held the keyboard or had lost it. A request +/// made while the field is composing text is dropped, so the composition's commit does not replace the query. In a +/// frame that runs twice, the pass where the field holds focus asks for the select and clears the flag; the select +/// applies at the start of the next pass, which asks nothing more. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct FindBarState { opened: bool, + /// The replace row was asked for with the bar: it opens, and its field takes the focus while the query has text. + replace: bool, } impl FindBarState { @@ -72,13 +78,22 @@ impl FindBarState { } /// Whether the bar was asked for and not yet shown, clearing it, for a caller that shows no [`FindBar`]. + #[must_use] pub fn taken(&mut self) -> bool { - todo!("CV-C17") + self.replace = false; + std::mem::take(&mut self.opened) } /// The bar is being opened with its replace row, and focus goes to the Replace field when the query is not empty. pub fn open_replace(&mut self) { - todo!("CV-C17") + self.opened = true; + self.replace = true; + } + + /// The asked-for field holds focus: the request is done. + fn served(&mut self) { + self.opened = false; + self.replace = false; } } @@ -98,6 +113,9 @@ enum BarOption { /// - Previous and Next are `IconButton`s bound to the [`FindStep`] commands, so their tooltips show the chords; the /// options button opens a `Menu` of the options (check rows) and shows pressed while an option is on; changing an /// option searches again. +/// - With [`replace`](Self::replace), a toggle before the options button shows a second row: the Replace with field +/// (Enter presses Replace), Replace (while a match is current) and Replace All (while the query has text). Either +/// reports a [`FindRequest`] in [`FindBarOutput::request`]. #[derive(craft_ui::contract::Pattern)] pub struct FindBar<'a> { query: &'a mut String, @@ -137,71 +155,115 @@ impl<'a> FindBar<'a> { /// Paints the bar and returns what the user asked for. pub fn show(self, ui: &mut Ui) -> FindBarOutput { - let FindBar { query, options, matches, progress, state, replace } = self; - let _ = replace; // P3(pdf-canvas-w7): CV-C17 + let FindBar { query, options, matches, progress, mut state, replace } = self; + let (mut with, mut open) = match replace { + Some((with, open)) => (Some(with), Some(open)), + None => (None, None), + }; let env = Env::of(ui); let (words, units) = (env.words::(), env.units()); - let mut state = state; let opened = state.as_deref().is_some_and(|state| state.opened); + let replace_asked = opened && open.is_some() && state.as_deref().is_some_and(|state| state.replace); + if replace_asked && let Some(open) = open.as_deref_mut() { + *open = true; + } + // The focus request goes to the Replace field when there is a query to replace, else to the query field. + let to_with = replace_asked && !query.is_empty(); + let to_query = opened && !to_with; let mut out = FindBarOutput { search: false, stepped: false, closed: false, request: None, response: ui.response() }; let mut step: Option = None; - let row = Row::new().show(ui, |ui, cx: &mut BodyCx<'_>| { + let bar = Stack::new().show(ui, |ui, cx: &mut BodyCx<'_>| { while let Some((command, _)) = cx.take_command::() { step = Some(command == FindStep::Previous); } - let edit = TextField::search(words.find_text.clone(), Bind::given(query.clone())).placeholder(words.find_text.clone()).show(ui); - if opened { - focus::request(ui.ctx(), FocusTarget::Id(edit.response.id)); - // Asking again each run until the field holds focus keeps the request across the measuring run. - if edit.response.has_focus() - && let Some(state) = state.as_deref_mut() - { - state.opened = false; + Row::new().show(ui, |ui, _| { + let edit = TextField::search(words.find_text.clone(), Bind::given(query.clone())) + .placeholder(words.find_text.clone()) + .select_all(to_query) + .show(ui); + if to_query { + focus::request(ui.ctx(), FocusTarget::Id(edit.response.id)); + // Asking again each run until the field holds focus keeps the request across the measuring run. + if edit.response.has_focus() + && let Some(state) = state.as_deref_mut() + { + state.served(); + } } + if let Some(value) = edit.events.value() { + query.clone_from(value); + out.search = true; + } + if edit.submitted { + step = Some(edit.submit_mods.shift); + } + let text = count_text(&words, &units, query.trim().is_empty(), matches, progress); + if !text.is_empty() { + Text::new(text).show(ui); + } + if clicked(&IconButton::command(IconId::new("chevron_up"), FindStep::Previous).show(ui)) { + step = Some(true); + } + if clicked(&IconButton::command(IconId::new("chevron_down"), FindStep::Next).show(ui)) { + step = Some(false); + } + if let Some(open) = open.as_deref_mut() + && clicked(&IconButton::new(IconId::new("swap_horizontal")).label(words.show_replace.clone()).selected(*open).show(ui)) + { + *open = !*open; + } + let active = options.match_case || options.whole_word; + let button = + IconButton::new(IconId::new("settings")).label(words.options.clone()).popup(PopupKind::Menu).selected(active).show(ui); + let entries = [ + Entry::new(BarOption::WholeWords, words.whole_words_only.clone()).checked(options.whole_word), + Entry::new(BarOption::MatchCase, words.case_sensitive.clone()).checked(options.match_case), + ]; + match Menu::new(words.options.clone()).opened_by(&button, Trigger::Press).pick(ui, &entries).picked { + Some(BarOption::WholeWords) => { + options.whole_word = !options.whole_word; + out.search = true; + } + Some(BarOption::MatchCase) => { + options.match_case = !options.match_case; + out.search = true; + } + None => {} + } + if clicked(&IconButton::new(IconId::new("close")).label(words.close.clone()).show(ui)) { + out.closed = true; + } + }); + if let (Some(with), Some(true)) = (with.as_deref_mut(), open.as_deref().copied()) { + Row::new().show(ui, |ui, _| { + let edit = TextField::new(words.replace_with.clone(), Bind::given(with.clone())).submits().select_all(to_with).show(ui); + if to_with { + focus::request(ui.ctx(), FocusTarget::Id(edit.response.id)); + if edit.response.has_focus() + && let Some(state) = state.as_deref_mut() + { + state.served(); + } + } + if let Some(value) = edit.events.value() { + with.clone_from(value); + } + let current = matches.current().is_some(); + let pressed = clicked(&Button::new(words.replace.clone()).enabled(current).show(ui)); + if pressed || (edit.submitted && current) { + out.request = Some(FindRequest::replace(query.clone(), with.clone(), *options)); + } + if clicked(&Button::new(words.replace_all.clone()).enabled(!query.is_empty()).show(ui)) { + out.request = Some(FindRequest::replace_all(query.clone(), with.clone(), *options)); + } + }); } - if let Some(value) = edit.events.value() { - query.clone_from(value); - out.search = true; - } - if edit.submitted { - step = Some(edit.submit_mods.shift); - } - // The field takes the Esc that clears it; an Esc it passes on closes the bar. + // The query field takes the Esc that clears it; an Esc a field passes on closes the bar. if cx.take_cancel() { out.closed = true; } - let text = count_text(&words, &units, query.trim().is_empty(), matches, progress); - if !text.is_empty() { - Text::new(text).show(ui); - } - if clicked(&IconButton::command(IconId::new("chevron_up"), FindStep::Previous).show(ui)) { - step = Some(true); - } - if clicked(&IconButton::command(IconId::new("chevron_down"), FindStep::Next).show(ui)) { - step = Some(false); - } - let active = options.match_case || options.whole_word; - let button = IconButton::new(IconId::new("settings")).label(words.options.clone()).popup(PopupKind::Menu).selected(active).show(ui); - let entries = [ - Entry::new(BarOption::WholeWords, words.whole_words_only.clone()).checked(options.whole_word), - Entry::new(BarOption::MatchCase, words.case_sensitive.clone()).checked(options.match_case), - ]; - match Menu::new(words.options.clone()).opened_by(&button, Trigger::Press).pick(ui, &entries).picked { - Some(BarOption::WholeWords) => { - options.whole_word = !options.whole_word; - out.search = true; - } - Some(BarOption::MatchCase) => { - options.match_case = !options.match_case; - out.search = true; - } - None => {} - } - if clicked(&IconButton::new(IconId::new("close")).label(words.close.clone()).show(ui)) { - out.closed = true; - } }); - out.response = row.output.response().clone(); + out.response = bar.output.response().clone(); if let Some(back) = step { out.stepped = matches.step(back).is_some(); } diff --git a/crates/text/src/ui/find/stories.rs b/crates/text/src/ui/find/stories.rs index d1504acd5..83e998af6 100644 --- a/crates/text/src/ui/find/stories.rs +++ b/crates/text/src/ui/find/stories.rs @@ -23,6 +23,26 @@ fn with_matches(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { FindBar::new(&mut query, &mut options, &mut found).show(ui).response.into() } +/// The bar with its replace row open; the readout shows the last Replace or Replace All. +#[story(FindBar<'static>, covers = [], drive = Drive::Never)] +fn with_replace(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let mut query = data.value("query", "craft".to_owned()).clone(); + let mut with = data.value("with", "Craft".to_owned()).clone(); + let mut open = *data.value("open", true); + let mut options = FindOptions::default(); + let mut found = matches("craft makes craft apps with craft", &query); + let out = FindBar::new(&mut query, &mut options, &mut found).replace(&mut with, &mut open).show(ui); + *data.value("query", String::new()) = query; + *data.value("with", String::new()) = with; + *data.value("open", true) = open; + let last = data.note("last", None::); + if let Some(request) = out.request { + *last = Some(format!("{request:?}")); + } + let readout = last.as_ref().map_or_else(|| "No event yet".to_owned(), |event| format!("Last event: {event}")); + StoryOutput::from(out.response).readout(readout) +} + #[story(FindBar<'static>, covers = [], drive = Drive::Never)] fn searching(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut query = data.value("query", "craft".to_owned()).clone(); diff --git a/crates/text/tests/it/find_bar.rs b/crates/text/tests/it/find_bar.rs new file mode 100644 index 000000000..b7119acaf --- /dev/null +++ b/crates/text/tests/it/find_bar.rs @@ -0,0 +1,86 @@ +//! The find bar over a test-held query: asking for the bar again selects its query, so typing replaces it. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +use craft_text::find::{FindMatches, FindOptions}; +use craft_text::ui::find::{FindBar, FindBarState}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Event, ImeEvent, Key, Modifiers}; + +struct Bar { + fixture: Fixture, + query: Rc>, + state: Rc>, + /// The next frame runs a second pass. + discard: Rc>, +} + +impl Bar { + fn new() -> Self { + let query = Rc::new(RefCell::new(String::new())); + let state = Rc::new(RefCell::new(FindBarState::default())); + let discard = Rc::new(Cell::new(false)); + let (shown_query, shown_state, shown_discard) = (Rc::clone(&query), Rc::clone(&state), Rc::clone(&discard)); + let mut options = FindOptions::default(); + let mut matches = FindMatches::new(0); + let fixture = Fixture::new(move |ui| { + if shown_discard.take() { + ui.ctx().request_discard("the trial reruns the pass"); + } + FindBar::new(&mut shown_query.borrow_mut(), &mut options, &mut matches).state(&mut shown_state.borrow_mut()).show(ui); + }); + Bar { fixture, query, state, discard } + } + + /// Cmd+F: the app asks for the bar. + fn ask(&mut self) { + self.ask_in(false); + } + + /// Cmd+F, in a frame that runs a second pass when `rerun`. + fn ask_in(&mut self, rerun: bool) { + self.discard.set(rerun); + self.state.borrow_mut().open(); + self.fixture.frame(Vec::new()).settle(); + assert!(!self.state.borrow().is_opening(), "the query field took the focus request"); + } + + fn query(&self) -> String { + self.query.borrow().clone() + } +} + +#[trial] +fn asking_for_the_bar_again_selects_its_query_unless_a_composition_runs() { + let mut bar = Bar::new(); + bar.ask(); + bar.fixture.type_text("cat").settle(); + assert_eq!(bar.query(), "cat"); + + bar.ask(); + bar.fixture.type_text("dog").settle(); + assert_eq!(bar.query(), "dog", "with the field holding the keyboard, typing replaces the selected query"); + + // The first pass serves the request; the rerun pass asks nothing and keeps the selection it applies. + bar.ask_in(true); + bar.fixture.type_text("owl").settle(); + assert_eq!(bar.query(), "owl", "a frame that runs twice still selects the query once"); + + let field = bar.fixture.focused(); + bar.fixture.key(Key::Tab, Modifiers::NONE).settle(); + assert_ne!(bar.fixture.focused(), field, "the field lost the keyboard to the next stop"); + bar.ask(); + bar.fixture.type_text("cat").settle(); + assert_eq!(bar.query(), "cat", "the focus-gain caret does not undo the select"); + + bar.fixture.frame(vec![Event::Ime(ImeEvent::Preedit { text: "ka".to_owned(), active_range_chars: Some(0..2) })]).settle(); + // Selecting the query here would make the commit replace all of it. + bar.ask(); + bar.fixture.frame(vec![Event::Ime(ImeEvent::Commit("か".to_owned()))]).settle(); + assert_eq!(bar.query(), "catか", "a request during a composition is dropped"); + + bar.ask(); + bar.fixture.type_text("dog").settle(); + assert_eq!(bar.query(), "dog", "after the commit the next request selects the query again"); +} diff --git a/crates/text/tests/it/find_matches.rs b/crates/text/tests/it/find_matches.rs new file mode 100644 index 000000000..c2e20c2f2 --- /dev/null +++ b/crates/text/tests/it/find_matches.rs @@ -0,0 +1,48 @@ +//! `FindMatches` as pages report their text: following the start page, and the user's choice ending it. + +use std::ops::Range; + +use craft_text::find::FindMatches; + +/// Ranges from `(start, end)` pairs. +fn ranges(pairs: &[(usize, usize)]) -> Vec> { + pairs.iter().map(|&(start, end)| start..end).collect() +} + +/// The current match's page and range. +fn current(found: &FindMatches) -> Option<(usize, Range)> { + found.current_match().map(|found| (found.page, found.range.clone())) +} + +#[test] +fn following_takes_the_first_match_from_the_start_page_whatever_order_pages_arrive_in() { + let mut found = FindMatches::new(1); + assert!(found.set_page(2, ranges(&[(0, 6)])), "the only known match is shown while the start page is pending"); + assert_eq!(current(&found), Some((2, 0..6))); + assert!(found.set_page(1, ranges(&[(4, 10)])), "the start page's match takes over once its text arrives"); + assert_eq!(current(&found), Some((1, 4..10))); + assert!(!found.set_page(0, ranges(&[(2, 8)])), "a match before the start page does not move the view"); + assert_eq!(current(&found), Some((1, 4..10))); + assert!(!found.set_page(3, Vec::new()), "a page whose text failed changes nothing"); + assert_eq!(current(&found), Some((1, 4..10))); + assert_eq!((found.len(), found.from()), (3, Some(1)), "every page's matches are listed and following goes on"); +} + +#[test] +fn a_step_or_pick_ends_following_and_later_pages_keep_the_users_match() { + let mut stepped = FindMatches::new(0); + stepped.set_page(1, ranges(&[(0, 3), (5, 8)])); + assert_eq!(stepped.step(false).map(|found| (found.page, found.range.clone())), Some((1, 5..8))); + assert_eq!(stepped.from(), None, "a step ends following"); + assert!(!stepped.set_page(0, ranges(&[(1, 4)])), "a later page does not move the view"); + assert_eq!(current(&stepped), Some((1, 5..8)), "the stepped-to match stays current"); + + let mut picked = FindMatches::new(0); + picked.set_page(2, ranges(&[(0, 3)])); + picked.set_page(1, ranges(&[(0, 3)])); + assert_eq!(current(&picked), Some((1, 0..3))); + picked.pick(1); + assert_eq!(picked.from(), None, "a pick ends following"); + assert!(!picked.set_page(0, ranges(&[(0, 3)])), "a later page does not move the view"); + assert_eq!(current(&picked), Some((2, 0..3)), "the picked match stays current"); +} diff --git a/crates/text/tests/it/main.rs b/crates/text/tests/it/main.rs index 7145e43f1..fc03ad849 100644 --- a/crates/text/tests/it/main.rs +++ b/crates/text/tests/it/main.rs @@ -3,6 +3,9 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod editor; +mod find_bar; +mod find_matches; + mod notes; mod path_text; diff --git a/crates/ui-contract/src/primitives/content.rs b/crates/ui-contract/src/primitives/content.rs index cd13babcf..f1781b6b7 100644 --- a/crates/ui-contract/src/primitives/content.rs +++ b/crates/ui-contract/src/primitives/content.rs @@ -3,16 +3,18 @@ use super::draw::{Draw, DrawEnv, StrokeWidth}; use super::record::PaintRecord; use super::text::{HAlign, TextLayout, aligned_rows}; +use crate::contract::WordSetCx; use crate::fonts::{FontRef, SEMIBOLD, stack_facts}; use crate::runtime::egui::text_layout; -use crate::runtime::env::Env; +use crate::runtime::env::{Env, Label}; use crate::style::{DataColor, Ink, StyleCx, UiTokens, ink_color}; -use craft_i18n::Direction; +use craft_i18n::{Direction, Format, WordSet}; use egui::epaint::text::{FontId, TextDirection}; use egui::text::{LayoutJob, TextFormat}; use egui::{Color32, Context, FontFamily, Painter, Stroke}; use std::borrow::Cow; use std::cell::RefCell; +use std::sync::Arc; /// The weight of a regular run. const REGULAR: u16 = 400; @@ -98,6 +100,21 @@ impl<'a> ContentPainterCx<'a> { } } +impl WordSetCx for ContentPainterCx<'_> { + /// A content painter has no label of its own: the empty label. + fn label(&self) -> Label { + Label::default() + } + + fn words(&self) -> Arc { + self.env.words() + } + + fn format(&self) -> &Format { + self.env.format() + } +} + /// Document text: runs with their own font, size and colour. On `TextRun` these fields would let any component /// bypass tokens for UI text, so only `ContentPainterCx::layout` takes them. #[derive(Clone, Copy, Debug)] diff --git a/crates/ui-contract/src/primitives/textures/loader.rs b/crates/ui-contract/src/primitives/textures/loader.rs index 84f03fe62..35571a0e5 100644 --- a/crates/ui-contract/src/primitives/textures/loader.rs +++ b/crates/ui-contract/src/primitives/textures/loader.rs @@ -122,6 +122,8 @@ struct Asked { priority: Priority, /// The last frame a painter asked for the key. frame: u64, + /// The pass time the job was queued, for `TextureLoader::waited`. + queued: f64, } type Finished = (K, Revision, LoadResult); @@ -178,10 +180,11 @@ impl Clone for TextureLoader { } impl TextureLoader { - /// Seconds `key` has waited for its picture, `None` when it is not waiting. + /// Seconds `key` has waited for its picture since its job was queued, by the pass clock; `None` when no job of + /// the key is queued or running. pub fn waited(&self, ctx: &Context, key: &K) -> Option { - let _ = (ctx, key); - todo!("CV-C16") + let now = pass::now(ctx); + self.with(ctx, |pool| pool.asked.get(key).map(|asked| (now - asked.queued).max(0.0))) } /// The loader of `ctx` under `salt`, made with `options` the first time; its store is @@ -200,7 +203,7 @@ impl TextureLoader { Wake::new(move || repaint::request(&ctx)) }; let queue = - Arc::new(JobQueue::new(jobs, wake, QueueOptions { lanes: options.lanes, name: "craft-textures", ..QueueOptions::default() })); // P3(pdf-canvas-w7): SH-C32 + Arc::new(JobQueue::new(jobs, wake, QueueOptions { lanes: options.lanes, name: "craft-textures", ..QueueOptions::default() })); memory::with(ctx, |pools: &mut Pools| { let pool = pools.by_salt.entry(id).or_insert_with(|| Pool::new(queue, options.lanes)); (Arc::clone(&pool.queue), pool.lanes) @@ -245,7 +248,7 @@ impl TextureLoader { Some(()) })?; replay::note_unsettled(ctx); - Some(TextureState::Loading { stand_in: state.shown() }) + Some(TextureState::Loading { stand_in: state.shown(), waited: None }) } /// Queues `job` making `key`'s picture at `revision`, replacing a queued job of the key, and returns `Loading` @@ -264,7 +267,8 @@ impl TextureLoader { self.run_frame_work(ctx); let stand_in = self.store.state(ctx, &key, revision).shown(); let frame = pass::root_frame_nr(ctx); - self.with(ctx, |pool| pool.asked.insert(key.clone(), Asked { revision, priority, frame })); + let queued = pass::now(ctx); + self.with(ctx, |pool| pool.asked.insert(key.clone(), Asked { revision, priority, frame, queued })); // A panicking job is a failure, not a key that stays Loading for good. self.queue.submit(key, priority, move |cancel| { let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job(cancel))).unwrap_or(Err(LoadFailure::Panicked)); @@ -275,7 +279,7 @@ impl TextureLoader { repaint::request(ctx); } replay::note_unsettled(ctx); - TextureState::Loading { stand_in } + TextureState::Loading { stand_in, waited: None } } /// Stops the loader's queue: waiting jobs are dropped, running ones are cancelled, and the call waits up to diff --git a/crates/ui-contract/src/primitives/textures/store.rs b/crates/ui-contract/src/primitives/textures/store.rs index dc768870d..cd0814b81 100644 --- a/crates/ui-contract/src/primitives/textures/store.rs +++ b/crates/ui-contract/src/primitives/textures/store.rs @@ -167,6 +167,9 @@ pub enum TextureState { Loading { /// The key's picture of another revision, shown until the new one lands. stand_in: Option, + /// Seconds since the key's job was queued by the pass clock; `None` when the state does not know of a queued + /// job (`Thumbnails::state` fills it). + waited: Option, }, /// The picture for this revision. Ready(CachedTexture), @@ -206,6 +209,21 @@ pub struct TextureStatistics { pub evicted: usize, } +impl std::ops::Add for TextureStatistics { + type Output = TextureStatistics; + + /// The field-wise sum, for the statistics of several stores taken together. + fn add(self, other: TextureStatistics) -> TextureStatistics { + TextureStatistics { + entries: self.entries + other.entries, + bytes: self.bytes + other.bytes, + uploads: self.uploads + other.uploads, + upload_bytes: self.upload_bytes + other.upload_bytes, + evicted: self.evicted + other.evicted, + } + } +} + /// One key's picture. enum Picture { Texture { @@ -533,7 +551,7 @@ impl Inner { let same = entry.revision == revision; match &entry.picture { Picture::Texture { handle, source, factor } if same => TextureState::Ready(cached(handle, *source, *factor)), - Picture::Texture { handle, source, factor } => TextureState::Loading { stand_in: Some(cached(handle, *source, *factor)) }, + Picture::Texture { handle, source, factor } => TextureState::Loading { stand_in: Some(cached(handle, *source, *factor)), waited: None }, Picture::Empty if same => TextureState::Empty, Picture::Failed(failure) if same => TextureState::Failed { failure: failure.clone() }, Picture::Empty | Picture::Failed(_) => TextureState::Missing, diff --git a/crates/ui-contract/src/primitives/textures/thumbnails.rs b/crates/ui-contract/src/primitives/textures/thumbnails.rs index aba9daa85..e811c32d3 100644 --- a/crates/ui-contract/src/primitives/textures/thumbnails.rs +++ b/crates/ui-contract/src/primitives/textures/thumbnails.rs @@ -4,9 +4,11 @@ use super::limits::MAX_TEXTURE; use super::loader::{LoadFailure, LoadedPicture, LoaderOptions, Priority, TextureLoader}; use super::store::{Revision, TextureKey, TextureState, TextureStoreOptions}; -use crate::primitives::{ContentPainterCx, IconSpec, Surface}; +use super::words::TextureWords; +use crate::contract::WordSetCx as _; +use crate::primitives::{ContentPainterCx, HAlign, IconSpec, Surface, TextRun, Wrap}; use crate::runtime::egui::{memory, pass, repaint, textures}; -use crate::style::{Corners, DataColor, SurfaceKind, surface_style}; +use crate::style::{Corners, DataColor, SurfaceKind, TypeRole, surface_style}; use craft_behavior::{IconId, PixelSize}; use craft_host::Jobs; use craft_host::queue::{Cancel, QueueOptions}; @@ -34,6 +36,9 @@ pub struct ThumbRequest { /// Requested sides are multiples of this many pixels. const SIZE_STEP: u32 = 16; +/// Seconds of waiting after which a `Captioned` thumbnail says it is still rendering. +const STILL_RENDERING: f64 = 6.0; + impl ThumbRequest { /// The request for a cell `points` wide on a screen of `pixels_per_point`: the side in pixels rounded up to a /// multiple of 16, at least 16 and at most `MAX_TEXTURE`. 28 points at 2x is 64 pixels. Neighbouring cell sizes @@ -304,10 +309,10 @@ const _: () = { }; impl Thumbnails { - /// Seconds `key` has waited for its picture, `None` when it is not waiting. + /// Seconds `key` has waited for its picture since its job was queued, `None` when no job of it waits + /// (`TextureLoader::waited`). pub fn waited(&self, ctx: &Context, key: &K) -> Option { - let _ = (ctx, key); - todo!("CV-C16") + self.loader.waited(ctx, key) } /// The thumbnails stored in `ctx` under `salt`, made with `options` the first time; the loader and its store @@ -334,6 +339,13 @@ impl Thumbnails { /// `Ready` is put in the store (counted against the budget), `Blank` is stored as `Empty`, and `Later` is /// submitted at `priority`. pub fn state(&self, ctx: &Context, source: &dyn ThumbSource, key: &K, request: &ThumbRequest, priority: Priority) -> TextureState { + match self.resolve(ctx, source, key, request, priority) { + TextureState::Loading { stand_in, .. } => TextureState::Loading { stand_in, waited: self.loader.waited(ctx, key) }, + settled => settled, + } + } + + fn resolve(&self, ctx: &Context, source: &dyn ThumbSource, key: &K, request: &ThumbRequest, priority: Priority) -> TextureState { let max_side = self.lock().options.max_side; let side = request.side.min((max_side / SIZE_STEP * SIZE_STEP).max(SIZE_STEP)); let request = ThumbRequest { side, ..*request }; @@ -341,7 +353,7 @@ impl Thumbnails { if let Some(state) = self.loader.ask(ctx, key, revision, priority) { return state; } - let stand_in = || TextureState::Loading { stand_in: self.loader.cache().state(ctx, key, revision).shown() }; + let stand_in = || TextureState::Loading { stand_in: self.loader.cache().state(ctx, key, revision).shown(), waited: None }; { let mut inner = self.lock(); let frame = pass::root_frame_nr(ctx); @@ -379,6 +391,8 @@ impl Thumbnails { /// `paint.paper` when set). /// - `Failed`: the placeholder with the warning icon centred. The message is the host's tooltip /// (`ListRow::tooltip`). + /// - With `StateLook::Captioned`, the placeholder carries a caption below its centre in place of the icon: + /// "Rendering…", "Still rendering…" once the state's `waited` reaches 6 s, and the failure's text when it failed. /// - `Empty`: nothing; returns false, and the row paints its own tile. /// /// Rects are rounded to whole pixels. @@ -386,17 +400,24 @@ impl Thumbnails { let rect = rect.round_to_pixels(cx.pixels_per_point()); match state { TextureState::Empty => false, - TextureState::Ready(texture) | TextureState::Loading { stand_in: Some(texture) } => { + TextureState::Ready(texture) | TextureState::Loading { stand_in: Some(texture), .. } => { paint_picture(cx, rect, texture.id, texture.size_vec2(), paint); true } - TextureState::Missing | TextureState::Loading { stand_in: None } => { + TextureState::Missing | TextureState::Loading { stand_in: None, .. } => { paint_placeholder(cx, rect, paint.paper); + if paint.states == StateLook::Captioned { + let waited = if let TextureState::Loading { waited, .. } = state { *waited } else { None }; + paint_waiting(cx, rect, waited); + } true } - TextureState::Failed { .. } => { + TextureState::Failed { failure } => { paint_placeholder(cx, rect, paint.paper); - paint_failure(cx, rect); + match paint.states { + StateLook::Glyph => paint_failure(cx, rect), + StateLook::Captioned => paint_caption(cx, rect, failure.text(&cx.words::())), + } true } } @@ -500,6 +521,32 @@ fn paint_placeholder(cx: &ContentPainterCx<'_>, rect: Rect, paper: Option, rect: Rect, waited: Option) { + let words = cx.words::(); + let text = match waited { + Some(waited) if waited >= STILL_RENDERING => &words.still_rendering, + Some(waited) => { + crate::runtime::frame::request_repaint_after(cx.painter.ctx(), STILL_RENDERING - waited); + &words.rendering + } + None => &words.rendering, + }; + paint_caption(cx, rect, text.as_str()); +} + +/// `text` in the body role, centred below `rect`'s centre and wrapped to `rect` less the roomy padding on each side. +fn paint_caption(cx: &ContentPainterCx<'_>, rect: Rect, text: &str) { + let room = rect.shrink(cx.tokens.space.pad.roomy); + let below = Rect::from_min_max(pos2(room.min.x, rect.center().y), room.max); + if !below.is_positive() { + return; + } + let run = TextRun::new(text).role(TypeRole::Body).wrap(Wrap::Wrap).align(HAlign::Center); + let _ = cx.with_draw(|draw| draw.text(below, &run)); +} + /// The warning icon centred in `rect`, no larger than the small icon size. fn paint_failure(cx: &ContentPainterCx<'_>, rect: Rect) { let side = cx.tokens.size.icon.sm.min(rect.width().min(rect.height())); diff --git a/crates/ui-widgets/src/text/text_field.rs b/crates/ui-widgets/src/text/text_field.rs index 43f8bdd3f..98d1284b6 100644 --- a/crates/ui-widgets/src/text/text_field.rs +++ b/crates/ui-widgets/src/text/text_field.rs @@ -72,6 +72,8 @@ pub struct TextField<'a, C: Codec + Clone + 'static = PlainText> { /// the id the collection is built with (`Props::id`), so a pattern can name a collection it shows after the field. #[prop] drives: Option, + /// The whole text is selected in this pass unless the field is composing text (`select_all`). + select_all: bool, } impl<'a> TextField<'a, PlainText> { @@ -106,6 +108,7 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> { leading: Vec::new(), arrow: false, drives: None, + select_all: false, } .label(label) } @@ -153,9 +156,9 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> { /// With `on`, selects the whole text in this pass, so typing replaces it, unless the field is composing text; a /// request made during a composition is dropped. #[must_use] - pub fn select_all(self, on: bool) -> Self { - let _ = (self, on); - todo!("CV-C17") + pub fn select_all(mut self, on: bool) -> Self { + self.select_all = on; + self } /// Monospace text. @@ -354,6 +357,10 @@ impl Component for TextField<'_, C> { { cx.set(empty); } + // Selecting during a composition would make its commit replace the whole text, so the request is dropped. + if self.select_all && !cx.text(&text_part::()).is_some_and(|outcome| outcome.composing) { + cx.select_all_text(); + } } fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { diff --git a/migration/api-map/text-editing.toml b/migration/api-map/text-editing.toml index cddd0db80..0c6a98cff 100644 --- a/migration/api-map/text-editing.toml +++ b/migration/api-map/text-editing.toml @@ -63,19 +63,21 @@ name = "FindBar" old = "craft_text::ui::find::FindBar" new = "craft_text::ui::find::FindBar" status = "replaced" -note = "A pattern; `FindBar::new(query, options, matches)`, no id salt." +note = "A pattern; `FindBar::new(query, options, matches)`, no id salt; `replace(with, open)` adds the replace row." [[type]] name = "FindBarOutput" old = "craft_text::ui::find::FindBarOutput" new = "craft_text::ui::find::FindBarOutput" status = "same" +note = "`request` carries the replace row's Replace or Replace All as a `FindRequest`." [[type]] name = "FindBarState" old = "craft_text::ui::find::FindBarState" new = "craft_text::ui::find::FindBarState" status = "same" +note = "`taken` clears a request for a caller that shows no bar; `open_replace` opens the bar with its replace row." [[type]] name = "FindReplaceDialog"