From 5b26e4fd3dac22a954c0c5505add4bad039cc6a8 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 21:27:24 +0700 Subject: [PATCH] type-w4: net change of 2 commits - type-w4: written from its sheet - type-w4: repair 1 --- crates/font-manager/src/glyphs.rs | 311 +++++++++++++++------- crates/font-manager/src/glyphs/stories.rs | 154 ++++++++--- crates/font-manager/tests/it/glyphs.rs | 138 ++++++++++ crates/font-manager/tests/it/main.rs | 1 + 4 files changed, 461 insertions(+), 143 deletions(-) create mode 100644 crates/font-manager/tests/it/glyphs.rs diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 248de60d4..74cd2e1ba 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -7,7 +7,7 @@ mod stories; use std::sync::Arc; -use craft_behavior::Selection; +use craft_behavior::{IconId, Selection}; use craft_host::Section; use craft_ui::contract::{ ActivateOn, Bind, CollectionEvent, CommandSet, Entry, NoValue, Outcome, Pad, Pattern, Props, Remember as _, SelectMode, Show as _, @@ -18,12 +18,14 @@ use craft_ui::layout_components::{Row, Stack}; use craft_ui::list::ThumbAspect; use craft_ui::list::ThumbSize; use craft_ui::pickers::Select; +use craft_ui::popover::Popover; use craft_ui::primitives::ContentPainterCx; use craft_ui::primitives::textures::{Priority, Revision, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails}; +use craft_ui::runtime::commands::{CommandSet as _, CommandState, Commands as _}; use craft_ui::runtime::env::{Env, Label}; use craft_ui::style::{DataColor, SurfaceKind}; -use craft_ui::tile_grid::{CaptionPlace, ThumbnailSlider, Tile, TileGrid, TileZoom}; -use egui::{ColorImage, Rect, Response, Ui}; +use craft_ui::tile_grid::{CaptionPlace, ThumbnailSlider, Tile, TileGrid, TilePartEvent, TileZoom}; +use egui::{ColorImage, Context, Rect, Response, Ui}; use serde::{Deserialize, Serialize}; use crate::panel::browse::SCAN_POLL_SECONDS; @@ -71,7 +73,7 @@ craft_ui::words! { } /// The glyph categories, Photoshop's list in order. These English names are the stable ids stored in the settings -/// and passed to [`GlyphSource::in_category`]; the panel shows them through [`GlyphsWords::category_name`]. +/// and passed to [`GlyphSource::cells`]; the panel shows them through [`GlyphsWords::category_name`]. pub const CATEGORIES: &[&str] = &[ "Entire Font", "Recently Used", @@ -140,10 +142,8 @@ pub struct CellInfo { } /// Where glyph cells come from: the app's text engine draws a glyph of a face at a pixel size and lists the -/// characters a face has. Apps plug in their own. +/// cells a face has. Apps plug in their own. pub trait GlyphSource: Send + Sync { - /// Every character the face (family, style) has a glyph for, in code point order. - fn charmap(&self, family: &str, style: &str) -> Vec; /// The cells of a category: characters in code point order, then unencoded glyphs. `"Entire Font"` is every /// cell; any other id is a [`CATEGORIES`] id or one of the source's [`categories`](GlyphSource::categories). fn cells(&self, family: &str, style: &str, category: &str) -> Vec; @@ -151,14 +151,12 @@ pub trait GlyphSource: Send + Sync { /// the face lacks it. The panel tints the image with the text colour, so a glyph is white with its coverage in /// the alpha channel. fn glyph(&self, family: &str, style: &str, cell: GlyphCell, px: u32) -> Option; - /// Whether `c` is in `category` (one of [`CATEGORIES`]). - fn in_category(&self, c: char, category: &str) -> bool; /// Whether the fonts are read. Not ready, the panel shows a spinner and muted text and no grid, and asks for a /// repaint after the poll interval. fn ready(&self) -> bool { true } - /// Changes when the source's faces change, so the pictures and the character lists are read again. + /// Changes when the source's faces change, so the pictures and the cell lists are read again. fn revision(&self) -> u64 { 0 } @@ -184,7 +182,7 @@ pub trait GlyphSource: Send + Sync { #[serde(default)] #[non_exhaustive] pub struct GlyphsPanelSettings { - /// The chosen category, one of [`CATEGORIES`]. + /// The chosen category, one of [`CATEGORIES`] or a category the source offers. pub category: String, /// The cell size as a multiple of the medium thumbnail, within [`ZOOM`]; a missing or unusable value is the /// zoom's default. @@ -203,8 +201,6 @@ impl Section for GlyphsPanelSettings { pub struct GlyphsPanelOutput { /// The panel's response. pub response: Response, - /// A glyph to insert at the caret (double-click, Enter on the focused cell); only where the app can insert. - pub insert: Option, /// Double-click or Enter on a cell (grid or recents) while `can_insert`; the host inserts or applies it. A /// `Char` cell still enters the recents. pub activated: Option, @@ -244,10 +240,15 @@ pub fn glyph_painter<'s>( style: &str, cell: GlyphCell, ) -> impl Fn(&ContentPainterCx, Rect) + use<'s> { - let _ = (ctx, family, style, cell); - move |_, _| { - let _ = source; - todo!("ty.X54") + let thumbs = Thumbnails::::in_context(ctx, "craft-font-manager-glyphs", ThumbnailOptions::new()); + let ctx = ctx.clone(); + let key = GlyphKey { family: family.to_owned(), style: style.to_owned(), cell }; + move |cx: &ContentPainterCx<'_>, rect: Rect| { + let rect = rect.shrink(rect.width().min(rect.height()) * GLYPH_INSET_RATIO); + let request = ThumbRequest::for_cell(rect.width().max(rect.height()), ctx.pixels_per_point()); + let picture = thumbs.state(&ctx, &GlyphPictures(source), &key, &request, Priority::VISIBLE); + let ink = DataColor::new(cx.ink()); + thumbs.paint(cx, rect, &picture, &ThumbPaint::default().checker(false).tint(ink)); } } @@ -267,13 +268,17 @@ pub const ZOOM: TileZoom = TileZoom::bounded(1.0, 2.625, 0.125, 1.25); const RECENT_ZOOM: f32 = 0.75; /// The room round a glyph in its cell, as a fraction of the cell. const GLYPH_INSET_RATIO: f32 = 0.1; +/// The most columns the alternates popup lays its cells in. +const ALTERNATE_COLUMNS: usize = 8; +/// The icon of the cell's corner action. +const ALTERNATES_ICON: &str = "more"; -/// A glyph picture's key: the face and the character. +/// A glyph picture's key: the face and the cell. #[derive(Clone, Debug, PartialEq, Eq, Hash)] struct GlyphKey { family: String, style: String, - c: char, + cell: GlyphCell, } /// The glyph pictures of a [`GlyphSource`]. @@ -285,55 +290,66 @@ impl ThumbSource for GlyphPictures<'_> { } fn render(&self, key: &GlyphKey, request: &ThumbRequest) -> ThumbRender { - // P3(type-w4): ty.X43 - match self.0.glyph(&key.family, &key.style, GlyphCell::Char(key.c), request.side) { + match self.0.glyph(&key.family, &key.style, key.cell, request.side) { Some(image) => ThumbRender::Ready(image), None => ThumbRender::Blank, } } } -/// The characters of a face in a category, kept until the face or the category changes. +/// The cells of a face in a category, kept until the face or the category changes. #[derive(Clone, Default)] -struct CharsCache { +struct CellsCache { key: (String, String, String), revision: u64, - chars: Arc>, + cells: Arc>, } /// The tile selection of the main grid. #[derive(Clone, Default)] struct Marked(Selection); +/// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when +/// it opened. +#[derive(Clone, Default)] +struct Popup { + open: bool, + cell: Option, + cells: Vec, +} + fn code(c: char) -> String { format!("{:04X}", c as u32) } -/// The characters of the shown set: the recents, or the face's charmap narrowed by the category. -fn category_chars(cache: &mut CharsCache, source: &dyn GlyphSource, family: &str, style: &str, category: &str, recent: &[String]) -> Arc> { - if category == "Recently Used" { - let mut seen = Vec::new(); - for c in recent.iter().filter_map(|g| g.chars().next()) { - if !seen.contains(&c) { - seen.push(c); - } +/// The recents as `Char` cells, each once, most recent first. +fn recent_cells(recent: &[String]) -> Vec { + let mut seen = Vec::new(); + for c in recent.iter().filter_map(|g| g.chars().next()) { + if !seen.contains(&c) { + seen.push(c); } - return Arc::new(seen); + } + seen.into_iter().map(GlyphCell::Char).collect() +} + +/// The cells of the shown set: the recents, or the source's cells of the category. +fn category_cells(cache: &mut CellsCache, source: &dyn GlyphSource, family: &str, style: &str, category: &str, recent: &[String]) -> Arc> { + if category == "Recently Used" { + return Arc::new(recent_cells(recent)); } let key = (family.to_owned(), style.to_owned(), category.to_owned()); let revision = source.revision(); if cache.key != key || cache.revision != revision { - let charmap = source.charmap(family, style); - let chars = if category == CATEGORIES[0] { charmap } else { charmap.into_iter().filter(|c| source.in_category(*c, category)).collect() }; - *cache = CharsCache { key, revision, chars: Arc::new(chars) }; + *cache = CellsCache { key, revision, cells: Arc::new(source.cells(family, style, category)) }; } - Arc::clone(&cache.chars) + Arc::clone(&cache.cells) } -/// The characters as a tile source: a character's position is its key. -struct Chars<'a>(&'a [char]); +/// The cells as a tile source: a cell's position is its key. +struct Cells<'a>(&'a [GlyphCell]); -impl craft_behavior::DisplayOrder for Chars<'_> { +impl craft_behavior::DisplayOrder for Cells<'_> { fn len(&self) -> usize { self.0.len() } @@ -347,15 +363,36 @@ impl craft_behavior::DisplayOrder for Chars<'_> { } } -impl craft_behavior::ItemSource for Chars<'_> {} +impl craft_behavior::ItemSource for Cells<'_> {} + +/// The tile of one glyph cell: its name for assistive tech and the glyph picture. +fn cell_tile<'s>( + ctx: &Context, + source: &'s dyn GlyphSource, + words: &GlyphsWords, + (family, style): (&str, &str), + cell: GlyphCell, + info: &CellInfo, +) -> Tile<'s> { + let name = match cell { + GlyphCell::Char(c) => words.cell.fill(&[("char", &c.to_string()), ("code", &code(c))]), + GlyphCell::Glyph(id) => { + let gid = id.to_string(); + words.glyph_cell.fill(&[("name", info.name.as_deref().unwrap_or(gid.as_str())), ("gid", gid.as_str())]) + } + }; + Tile::new(name).thumb(ThumbAspect::SQUARE, glyph_painter(ctx, source, family, style, cell)) +} /// The Glyphs panel body. The family comes from the text selection while editing (the panel follows the caret), /// else from the panel's own picker. /// /// - Keys: the grid is one Tab stop; arrows move the focused cell, Page Up/Down a screen, Home/End to the ends, /// Enter inserts. Hovering a cell shows its character and code point as a tooltip. -/// - A cell is drawn from [`GlyphSource::glyph`] at the zoom size, cached per face and character. The grid shows +/// - A cell is drawn from [`GlyphSource::glyph`] at the zoom size, cached per face and cell. The grid shows /// only the current category; a cell the source returns no image for stays empty. +/// - A cell the source says has alternates shows a corner action that opens a popup of them; a pick is reported +/// as [`GlyphsPanelOutput::alternate`]. /// - Where the app cannot insert, the cells still show, Enter and double-click do nothing and the footer says so. /// - While the source is not [ready](GlyphSource::ready) the panel shows a spinner and "Loading fonts…" only. /// - The font and style lists come from the app ([`families`](GlyphsPanel::families), @@ -415,8 +452,19 @@ impl<'a> GlyphsPanel<'a> { /// Shows the panel. pub fn show(self, ui: &mut Ui) -> GlyphsPanelOutput { - let GlyphsPanel { label, source, mut family, mut style, mut settings, families, styles, can_insert, marked, reveal, empty } = self; - let _ = (marked, reveal, empty); // P3(type-w4): ty.X47, ty.X48 + let GlyphsPanel { + label, + source, + mut family, + mut style, + mut settings, + families, + styles, + can_insert, + marked: marked_cell, + reveal: reveal_cell, + empty, + } = self; let env = Env::of(ui); let words = env.words::(); if !source.ready() { @@ -427,13 +475,14 @@ impl<'a> GlyphsPanel<'a> { }); }); craft_ui::runtime::frame::request_repaint_after(ui.ctx(), SCAN_POLL_SECONDS); - return GlyphsPanelOutput { response: shown.output, insert: None, activated: None, alternate: None, font_changed: false }; + return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false }; } - let thumbs = Thumbnails::::in_context(ui.ctx(), "craft-font-manager-glyphs", ThumbnailOptions::new()); - let pictures = GlyphPictures(source); - let mut insert: Option = None; + let ctx = ui.ctx().clone(); + let mut activated_out: Option = None; + let mut picked: Option = None; let mut font_changed = false; - let shown = Stack::new().label(label).show(ui, |ui, cx| { + let shown = Stack::new().label(label).command_scope(GlyphsCommand::SCOPE).show(ui, |ui, cx| { + cx.publish(GlyphsCommand::Alternates, CommandState::new()); let mut state = read_bind(&mut settings, cx).unwrap_or_default(); if state.category.is_empty() { state.category = CATEGORIES[0].to_owned(); @@ -469,33 +518,30 @@ impl<'a> GlyphsPanel<'a> { write_bind(&mut style, cx, face_style.clone(), "Glyphs style"); } font_changed = face_family != held_family || face_style != held_style; + let face = (face_family.as_str(), face_style.as_str()); + // A category the face no longer offers shows the whole font. + let extra = source.categories(face.0, face.1); + if !CATEGORIES.contains(&state.category.as_str()) && !extra.iter().any(|(id, _)| *id == state.category) { + state.category = CATEGORIES[0].to_owned(); + } let mut category = state.category.clone(); Row::new().show(ui, |ui, _| { Text::new(words.show.clone()).show(ui); - let entries: Vec> = - CATEGORIES.iter().map(|name| Entry::new((*name).to_owned(), words.category_name(name).to_owned())).collect(); + let entries: Vec> = CATEGORIES + .iter() + .map(|name| Entry::new((*name).to_owned(), words.category_name(name).to_owned())) + .chain(extra.iter().map(|(id, name)| Entry::new(id.clone(), name.clone()))) + .collect(); Select::new(words.category.clone(), Bind::bound(&mut category), &entries).show(ui); }); state.category = category; - let paint = |family: &str, style: &str, c: char| { - let (thumbs, pictures) = (thumbs.clone(), &pictures); - let key = GlyphKey { family: family.to_owned(), style: style.to_owned(), c }; - move |cx: &ContentPainterCx<'_>, rect: Rect| { - let ctx = cx.painter.ctx().clone(); - let rect = rect.shrink(rect.width().min(rect.height()) * GLYPH_INSET_RATIO); - let request = ThumbRequest::for_cell(rect.width().max(rect.height()), ctx.pixels_per_point()); - let picture = thumbs.state(&ctx, pictures, &key, &request, Priority::VISIBLE); - let ink = DataColor::new(cx.ink()); - thumbs.paint(cx, rect, &picture, &ThumbPaint::default().checker(false).tint(ink)); - } - }; - // Recently used. Text::new(words.recent.clone()).show(ui); - let recent: Vec = state.recent.iter().filter_map(|g| g.chars().next()).collect(); - let mut activated: Option = None; + let recent = recent_cells(&state.recent); + let plain = CellInfo::default(); + let mut activated: Option = None; let strip = TileGrid::::new(words.recent.clone()) .thumb_size(ThumbSize::Medium) .zoom(RECENT_ZOOM) @@ -505,48 +551,112 @@ impl<'a> GlyphsPanel<'a> { .sizing(craft_ui::contract::Sizing::FillWidth) .surface(SurfaceKind::Sunken) .pad(Pad::Control) - .show_items(ui, &Chars(&recent), &mut |key, _| { - let c = recent[*key]; - let name = words.cell.fill(&[("char", &c.to_string()), ("code", &code(c))]); - Tile::new(name).thumb(ThumbAspect::SQUARE, paint(&face_family, &face_style, c)) - }) + .show_items(ui, &Cells(&recent), &mut |key, _| cell_tile(&ctx, source, &words, face, recent[*key], &plain)) .response .events; for event in strip { if let CollectionEvent::Activate(key) = event - && let Some(c) = recent.get(key) + && let Some(&cell) = recent.get(key) { - activated = Some(c.to_string()); + activated = Some(cell); } } // The grid. - let chars = category_chars(cx.memory::(), source, &face_family, &face_style, &state.category, &state.recent); + let cells = category_cells(cx.memory::(), source, face.0, face.1, &state.category, &state.recent); + let index_of = |cell: GlyphCell| cells.iter().position(|c| *c == cell); let mut marked = cx.memory::().clone(); - let grid = TileGrid::::new(words.grid.clone()) - .thumb_size(ThumbSize::Medium) - .zoom(size as f32) - .caption(CaptionPlace::None) - .select(SelectMode::Single) - .selection(Bind::bound(&mut marked.0)) - .show_items(ui, &Chars(&chars), &mut |key, _| { - let c = chars[*key]; - let name = words.cell.fill(&[("char", &c.to_string()), ("code", &code(c))]); - Tile::new(name).thumb(ThumbAspect::SQUARE, paint(&face_family, &face_style, c)) - }); - for event in grid.response.events { - if let CollectionEvent::Activate(key) = event - && let Some(c) = chars.get(key) - { - activated = Some(c.to_string()); + if let Some(at) = marked_cell.and_then(index_of) + && marked.0.lead != Some(at) + { + marked.0 = Selection::single(at); + } + match &empty { + Some(text) if cells.is_empty() => { + Text::new(text.clone()).shade(Shade::Muted).show(ui); + } + _ => { + let mut grid = TileGrid::::new(words.grid.clone()) + .thumb_size(ThumbSize::Medium) + .zoom(size as f32) + .caption(CaptionPlace::None) + .select(SelectMode::Single) + .selection(Bind::bound(&mut marked.0)); + if let Some(at) = reveal_cell.and_then(index_of) { + grid = grid.reveal(at); + } + let shown_grid = grid.show_items(ui, &Cells(&cells), &mut |key, _| { + let cell = cells[*key]; + let info = source.describe(face.0, face.1, cell); + let mut tile = cell_tile(&ctx, source, &words, face, cell, &info); + if info.dimmed { + tile = tile.dimmed(); + } + if info.has_alternates { + tile = tile.corner_action(IconId::new(ALTERNATES_ICON), GlyphsCommand::Alternates); + } + match info.note { + Some(note) => tile.tooltip(note), + None => tile, + } + }); + for event in shown_grid.response.events { + match event { + CollectionEvent::Activate(key) => activated = cells.get(key).copied().or(activated), + CollectionEvent::Item(key, TilePartEvent::CornerAction) => { + if let Some(&cell) = cells.get(key) { + *cx.memory::() = Popup { open: true, cell: Some(cell), cells: source.alternates(face.0, face.1, cell) }; + } + } + _ => {} + } + } } } + // The alternates popup, hung from the pointer where the corner action was pressed. + let mut popup = std::mem::take(cx.memory::()); + if let Some(cell) = popup.cell + && popup.open + { + Popover::new(words.alternates.clone(), Bind::bound(&mut popup.open)).at_pointer().show(ui, |ui, body| { + let events = TileGrid::::new(words.alternates.clone()) + .thumb_size(ThumbSize::Medium) + .caption(CaptionPlace::None) + .select(SelectMode::Single) + .activate(ActivateOn::Click) + .card_columns(popup.cells.len().min(ALTERNATE_COLUMNS)) + .show_items(ui, &Cells(&popup.cells), &mut |key, _| { + let alternate = popup.cells[*key]; + let info = source.describe(face.0, face.1, alternate); + cell_tile(&ctx, source, &words, face, alternate, &info) + }) + .response + .events; + for event in events { + if let CollectionEvent::Activate(key) = event + && let Some(&glyph) = popup.cells.get(key) + { + picked = Some(AlternatePick { cell, glyph }); + body.request_close(); + } + } + }); + } + if !popup.open || picked.is_some() { + popup = Popup::default(); + } + *cx.memory::() = popup; + // Footer: the selection, the count and the zoom. - let n = chars.len() as u64; + let n = cells.len() as u64; let count = words.count.text(n, &env.format().integer(n)); - let info = match marked.0.lead.and_then(|lead| chars.get(lead)) { - Some(&c) => words.selected.fill(&[("code", &code(c)), ("count", &count)]), + let info = match marked.0.lead.and_then(|lead| cells.get(lead)).copied() { + Some(GlyphCell::Char(c)) => match source.describe(face.0, face.1, GlyphCell::Char(c)).gid { + Some(gid) => words.selected_glyph.fill(&[("code", &code(c)), ("gid", &gid.to_string()), ("count", &count)]), + None => words.selected.fill(&[("code", &code(c)), ("count", &count)]), + }, + Some(GlyphCell::Glyph(gid)) => words.unencoded.fill(&[("gid", &gid.to_string()), ("count", &count)]), None => count, }; *cx.memory::() = marked; @@ -559,18 +669,21 @@ impl<'a> GlyphsPanel<'a> { } state.zoom = zoom_value as f32; - if let Some(glyph) = activated + if let Some(cell) = activated && can_insert { - state.recent.retain(|g| *g != glyph); - state.recent.insert(0, glyph.clone()); - state.recent.truncate(RECENT_LIMIT); - insert = Some(glyph); + if let GlyphCell::Char(c) = cell { + let glyph = c.to_string(); + state.recent.retain(|g| *g != glyph); + state.recent.insert(0, glyph); + state.recent.truncate(RECENT_LIMIT); + } + activated_out = Some(cell); } if read_bind(&mut settings, cx).is_none_or(|held| held != state) { write_bind(&mut settings, cx, state, "Glyphs panel"); } }); - GlyphsPanelOutput { response: shown.output, insert, activated: None, alternate: None, font_changed } + GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed } } } diff --git a/crates/font-manager/src/glyphs/stories.rs b/crates/font-manager/src/glyphs/stories.rs index ffc6dc829..64199090d 100644 --- a/crates/font-manager/src/glyphs/stories.rs +++ b/crates/font-manager/src/glyphs/stories.rs @@ -1,14 +1,16 @@ //! Stories of `GlyphsPanel`: the panel over Ubuntu Light and Hack with three recent glyphs, while text is edited and //! while it is not, and while the source is not ready. The glyph source draws the shipped faces' outlines with skrifa. +use std::collections::HashSet; + use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::{Color32, ColorImage, Ui}; use skrifa::instance::{LocationRef, Size}; use skrifa::outline::{DrawSettings, OutlinePen}; -use skrifa::{FontRef, MetadataProvider as _}; +use skrifa::{FontRef, GlyphId, MetadataProvider as _}; -use super::{GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings}; +use super::{CATEGORIES, CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings}; const UBUNTU: &[u8] = epaint_default_fonts::UBUNTU_LIGHT; const HACK: &[u8] = epaint_default_fonts::HACK_REGULAR; @@ -21,7 +23,9 @@ struct Demo { settings: GlyphsPanelSettings, } -fn show_panel(ui: &mut Ui, data: &mut StoryData, editing: bool) -> StoryOutput { +/// The panel over the shipped faces. A `marked` cell is also revealed, in the first pass only. +fn show_panel(ui: &mut Ui, data: &mut StoryData, editing: bool, marked: Option) -> StoryOutput { + let shown_before = std::mem::replace(data.value("shown", false), true); let init = Demo { family: "Ubuntu".to_owned(), style: "Light".to_owned(), @@ -31,24 +35,53 @@ fn show_panel(ui: &mut Ui, data: &mut StoryData, editing: bool) -> StoryOutput { let families = ["Ubuntu".to_owned(), "Hack".to_owned()]; let styles = [if family == "Hack" { "Regular" } else { "Light" }.to_owned()]; style.clone_from(&styles[0]); - GlyphsPanel::new("Glyphs", &FaceGlyphs, Bind::bound(family), Bind::bound(style), Bind::bound(settings)) + let mut panel = GlyphsPanel::new("Glyphs", &FaceGlyphs, Bind::bound(family), Bind::bound(style), Bind::bound(settings)) .can_insert(editing) .families(&families) - .styles(&styles) - .show(ui) - .into() + .styles(&styles); + if let Some(cell) = marked { + panel = panel.marked(cell); + if !shown_before { + panel = panel.reveal(cell); + } + } + panel.show(ui).into() } /// The panel while text is edited, so a double-click inserts a glyph. #[story(GlyphsPanel<'static>, covers = [Default, Many], drive = Drive::Never)] fn glyphs_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - show_panel(ui, data, true) + show_panel(ui, data, true, None) +} + +/// A letter with alternates: hovering its cell shows the corner action that opens the popup of them. +#[story(GlyphsPanel<'static>, covers = [], drive = Drive::Never)] +fn glyphs_panel_alternates(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + show_panel(ui, data, true, Some(GlyphCell::Char('a'))) +} + +/// A marked cell far down the grid, scrolled into view in the first pass. +#[story(GlyphsPanel<'static>, covers = [], drive = Drive::Never)] +fn glyphs_panel_marked(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + show_panel(ui, data, true, Some(GlyphCell::Char('€'))) +} + +/// A category with no cells: the empty text replaces the grid. +#[story(GlyphsPanel<'static>, covers = [], drive = Drive::Never)] +fn glyphs_panel_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let Demo { family, style, settings } = + data.value("empty", Demo { family: String::new(), style: String::new(), settings: GlyphsPanelSettings::default() }); + GlyphsPanel::new("Glyphs", &Empty { ready: true }, Bind::bound(family), Bind::bound(style), Bind::bound(settings)) + .can_insert(true) + .empty("No fonts are available.") + .show(ui) + .into() } /// The panel with no text being edited: it says how to insert glyphs. #[story(GlyphsPanel<'static>, covers = [], drive = Drive::Never)] fn glyphs_panel_not_editing(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - show_panel(ui, data, false) + show_panel(ui, data, false, None) } /// The panel while the app is still reading its fonts: a spinner and the loading line, no grid. @@ -56,31 +89,28 @@ fn glyphs_panel_not_editing(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn glyphs_panel_loading(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let Demo { family, style, settings } = data.value("loading", Demo { family: String::new(), style: String::new(), settings: GlyphsPanelSettings::default() }); - GlyphsPanel::new("Glyphs", &NotReady, Bind::bound(family), Bind::bound(style), Bind::bound(settings)).can_insert(true).show(ui).into() + GlyphsPanel::new("Glyphs", &Empty { ready: false }, Bind::bound(family), Bind::bound(style), Bind::bound(settings)) + .can_insert(true) + .show(ui) + .into() } -/// A source whose fonts are not read yet. -struct NotReady; - -impl GlyphSource for NotReady { - fn charmap(&self, _: &str, _: &str) -> Vec { - Vec::new() - } +/// A source with no cells, ready or still reading its fonts. +struct Empty { + ready: bool, +} +impl GlyphSource for Empty { fn cells(&self, _: &str, _: &str, _: &str) -> Vec { - todo!("ty.X41") + Vec::new() } fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { None } - fn in_category(&self, _: char, _: &str) -> bool { - false - } - fn ready(&self) -> bool { - false + self.ready } } @@ -91,36 +121,22 @@ impl FaceGlyphs { fn font(family: &str) -> Option> { FontRef::new(if family == "Hack" { HACK } else { UBUNTU }).ok() } -} -impl GlyphSource for FaceGlyphs { - fn charmap(&self, family: &str, _style: &str) -> Vec { - let Some(font) = Self::font(family) else { return Vec::new() }; + /// The characters the face maps, in code point order. + fn chars(font: &FontRef<'_>) -> Vec { let mut chars: Vec = font.charmap().mappings().filter_map(|(code, _)| char::from_u32(code)).filter(|c| !c.is_control()).collect(); chars.sort_unstable(); chars.dedup(); chars } - fn cells(&self, _: &str, _: &str, _: &str) -> Vec { - todo!("ty.X41") + /// The glyph ids no character maps. + fn unencoded(font: &FontRef<'_>) -> Vec { + let mapped: HashSet = font.charmap().mappings().map(|(_, id)| id.to_u32()).collect(); + font.outline_glyphs().iter().map(|(id, _)| id.to_u32()).filter(|id| !mapped.contains(id)).collect() } - fn glyph(&self, family: &str, _style: &str, cell: GlyphCell, px: u32) -> Option { - // P3(type-w4): ty.X43 - let GlyphCell::Char(c) = cell else { return None }; - let font = Self::font(family)?; - let id = font.charmap().map(c)?; - let em = px as f32 * 0.8; - let size = Size::new(em); - let advance = font.glyph_metrics(size, LocationRef::default()).advance_width(id).unwrap_or(em); - let baseline = px as f32 * 0.78; - let mut pen = Outline { edges: Vec::new(), start: (0.0, 0.0), at: (0.0, 0.0), dx: (px as f32 - advance) / 2.0, baseline }; - font.outline_glyphs().get(id)?.draw(DrawSettings::unhinted(size, LocationRef::default()), &mut pen).ok()?; - Some(rasterize(&pen.edges, px as usize)) - } - - fn in_category(&self, c: char, category: &str) -> bool { + fn in_category(c: char, category: &str) -> bool { let code = c as u32; match category { "Punctuation" => c.is_ascii_punctuation() && !"$+<=>^`|~".contains(c) || "¡¿«»·".contains(c) || (0x2010..=0x2027).contains(&code), @@ -140,6 +156,56 @@ impl GlyphSource for FaceGlyphs { } } +impl GlyphSource for FaceGlyphs { + fn cells(&self, family: &str, _style: &str, category: &str) -> Vec { + let Some(font) = Self::font(family) else { return Vec::new() }; + let whole = category == CATEGORIES[0]; + let mut cells: Vec = + Self::chars(&font).into_iter().filter(|c| whole || Self::in_category(*c, category)).map(GlyphCell::Char).collect(); + if whole && family == "Hack" { + cells.extend(Self::unencoded(&font).into_iter().map(GlyphCell::Glyph)); + } + cells + } + + fn describe(&self, family: &str, _style: &str, cell: GlyphCell) -> CellInfo { + let mut info = CellInfo::default(); + let Some(font) = Self::font(family) else { return info }; + match cell { + GlyphCell::Char(c) => { + info.gid = font.charmap().map(c).map(GlyphId::to_u32); + info.name = Some(format!("uni{:04X}", c as u32)); + info.dimmed = c == 'Z'; + info.has_alternates = c == 'a'; + } + GlyphCell::Glyph(id) => { + info.gid = Some(id); + info.name = Some(format!("glyph{id}")); + } + } + info + } + + fn alternates(&self, _family: &str, _style: &str, cell: GlyphCell) -> Vec { + if cell == GlyphCell::Char('a') { ['a', 'à', 'á', 'â'].map(GlyphCell::Char).to_vec() } else { Vec::new() } + } + + fn glyph(&self, family: &str, _style: &str, cell: GlyphCell, px: u32) -> Option { + let font = Self::font(family)?; + let id = match cell { + GlyphCell::Char(c) => font.charmap().map(c)?, + GlyphCell::Glyph(id) => GlyphId::new(id), + }; + let em = px as f32 * 0.8; + let size = Size::new(em); + let advance = font.glyph_metrics(size, LocationRef::default()).advance_width(id).unwrap_or(em); + let baseline = px as f32 * 0.78; + let mut pen = Outline { edges: Vec::new(), start: (0.0, 0.0), at: (0.0, 0.0), dx: (px as f32 - advance) / 2.0, baseline }; + font.outline_glyphs().get(id)?.draw(DrawSettings::unhinted(size, LocationRef::default()), &mut pen).ok()?; + Some(rasterize(&pen.edges, px as usize)) + } +} + type Segment = ((f32, f32), (f32, f32)); /// An outline flattened to line segments in image pixels, y down. diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs new file mode 100644 index 000000000..5aa7a2c64 --- /dev/null +++ b/crates/font-manager/tests/it/glyphs.rs @@ -0,0 +1,138 @@ +//! The Glyphs panel's flows over a source of plain cells: a marked cell far down the grid, and a pick in a cell's +//! alternates popup. + +use std::cell::RefCell; +use std::rc::Rc; + +use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings}; +use craft_ui::contract::Bind; +use craft_ui::testing::{Fixture, Room, trial}; +use egui::{ColorImage, Event}; + +/// The first cell, which has alternates. +const FIRST: char = 'Ā'; +/// A cell several screens below the first. +const FAR: char = 'Ǻ'; + +/// Three hundred characters from U+0100 on, no pictures; the first has three alternates. +struct Plain; + +impl GlyphSource for Plain { + fn cells(&self, _: &str, _: &str, _: &str) -> Vec { + (0..300).filter_map(|i| char::from_u32(0x100 + i)).map(GlyphCell::Char).collect() + } + + fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { + None + } + + fn describe(&self, _: &str, _: &str, cell: GlyphCell) -> CellInfo { + let mut info = CellInfo::default(); + info.has_alternates = cell == GlyphCell::Char(FIRST); + info + } + + fn alternates(&self, _: &str, _: &str, cell: GlyphCell) -> Vec { + if cell == GlyphCell::Char(FIRST) { ['Ⓐ', 'Ⓑ', 'Ⓒ'].map(GlyphCell::Char).to_vec() } else { Vec::new() } + } +} + +/// What the host passes and what the panel reported over the passes. +#[derive(Default)] +struct Seen { + marked: Option, + reveal: Option, + picks: Vec<(GlyphCell, GlyphCell)>, +} + +fn rig() -> (Fixture, Rc>) { + let seen = Rc::new(RefCell::new(Seen::default())); + let shown = Rc::clone(&seen); + let (mut family, mut style, mut settings) = ("Plain".to_owned(), "Regular".to_owned(), GlyphsPanelSettings::default()); + let mut fx = Fixture::new(move |ui| { + let (marked, reveal) = { + let mut seen = shown.borrow_mut(); + (seen.marked, seen.reveal.take()) + }; + let mut panel = + GlyphsPanel::new("Glyphs", &Plain, Bind::bound(&mut family), Bind::bound(&mut style), Bind::bound(&mut settings)).can_insert(true); + if let Some(cell) = marked { + panel = panel.marked(cell); + } + if let Some(cell) = reveal { + panel = panel.reveal(cell); + } + if let Some(pick) = panel.show(ui).alternate { + shown.borrow_mut().picks.push((pick.cell, pick.glyph)); + } + }); + fx.in_room(Room::Window); + fx.settle(); + (fx, seen) +} + +fn name(c: char) -> String { + format!("{c}, U+{:04X}", c as u32) +} + +fn visible(fx: &Fixture, c: char) -> bool { + fx.by_label(&name(c)).and_then(|cell| fx.visible(&cell)).is_some() +} + +fn selected(fx: &Fixture, c: char) -> bool { + fx.by_label(&name(c)).is_some_and(|cell| fx.tree().data_of(cell.node).and_then(|data| data.is_selected()).unwrap_or(false)) +} + +#[trial] +fn the_marked_cell_is_selected_and_revealed_only_in_the_pass_that_carries_reveal() { + let (mut fx, seen) = rig(); + assert!(visible(&fx, FIRST), "the grid starts at its first cell"); + assert!(!visible(&fx, FAR), "a cell several screens down is out of view"); + + { + let mut seen = seen.borrow_mut(); + seen.marked = Some(GlyphCell::Char(FAR)); + seen.reveal = Some(GlyphCell::Char(FAR)); + } + fx.frame(Vec::new()); + fx.settle(); + assert!(visible(&fx, FAR), "the pass with reveal scrolls the marked cell into view"); + assert!(selected(&fx, FAR), "the marked cell is the selected one, not a position"); + + fx.frame(Vec::new()); + fx.settle(); + assert!(visible(&fx, FAR), "a pass without reveal keeps the scroll"); + assert!(!visible(&fx, FIRST), "the grid does not jump back to its start"); +} + +#[trial] +fn a_corner_pick_reports_the_cell_and_the_glyph() { + let (mut fx, seen) = rig(); + let cell = fx.by_label(&name(FIRST)).expect("the first cell"); + fx.frame(vec![Event::PointerMoved(cell.center())]); + let action = fx.by_label("Show Alternates").expect("the corner action shows while the pointer is over the cell"); + fx.click(&action); + fx.settle(); + assert!(visible(&fx, 'Ⓑ'), "the corner action opens the popup of alternates"); + assert!(seen.borrow().picks.is_empty(), "opening the popup picks nothing"); + + let second = fx.by_label(&name('Ⓑ')).expect("the second alternate"); + fx.click(&second); + fx.settle(); + assert_eq!(seen.borrow().picks, vec![(GlyphCell::Char(FIRST), GlyphCell::Char('Ⓑ'))], "one pick, with the cell the popup was opened for"); + assert!(!visible(&fx, 'Ⓑ'), "a pick closes the popup"); +} + +#[trial] +fn glyphs_panel_alternates() { + let (mut fx, _seen) = rig(); + let cell = fx.by_label(&name(FIRST)).expect("the first cell"); + assert!(fx.by_label("Show Alternates").is_none(), "the corner action stays hidden while the pointer is elsewhere"); + fx.frame(vec![Event::PointerMoved(cell.center())]); + let action = fx.by_label("Show Alternates").expect("the corner action shows while the pointer is over the cell"); + fx.click(&action); + fx.settle(); + for alternate in ['Ⓐ', 'Ⓑ', 'Ⓒ'] { + assert!(visible(&fx, alternate), "the popup lists every alternate of the cell"); + } +} diff --git a/crates/font-manager/tests/it/main.rs b/crates/font-manager/tests/it/main.rs index 76d76dfab..84a67af5e 100644 --- a/crates/font-manager/tests/it/main.rs +++ b/crates/font-manager/tests/it/main.rs @@ -1,5 +1,6 @@ //! The integration binary of craft-font-manager: every test is a registered trial. +mod glyphs; mod missing; mod panel; mod picker;