FontPicker: production's row (star column, aligned names, unframed sample column, format badge), preview banner on a well, class column as options, ghost Clear All, rule after recents, private families hidden, samples need outlines, loading state

This commit is contained in:
aiongg
2026-11-22 06:07:57 +00:00
parent f1351c0a63
commit 2450df6735
6 changed files with 415 additions and 123 deletions
+9 -7
View File
@@ -1,5 +1,7 @@
//! `FontSample`: text in a font face at the user's sample size, on one line at the reading start of its rect.
use std::borrow::Cow;
use craft_behavior::Sense;
use craft_ui::contract::{Common, Component, Cx, DisabledLook, MeasureCx, PaintUi, Props as _, Role};
use craft_ui::fonts::FontRef;
@@ -37,7 +39,7 @@ pub(crate) enum SampleFace<'a> {
}
impl SampleFace<'_> {
fn shown(&self, at: &impl craft_ui::primitives::FacesCx) -> Shown {
pub(crate) fn shown(&self, at: &impl craft_ui::primitives::FacesCx) -> Shown {
match self {
SampleFace::Face { catalog, owner, face } => faces::shown(at, catalog, *owner, face),
SampleFace::Interface => Shown::Unavailable,
@@ -57,15 +59,15 @@ impl SampleFace<'_> {
pub(crate) struct FontSample<'a> {
#[common]
common: Common,
text: &'a str,
text: Cow<'a, str>,
face: SampleFace<'a>,
points: f32,
}
impl<'a> FontSample<'a> {
/// A sample of `text` in `face` at `points`, named `label`.
pub(crate) fn new(label: impl Into<Label>, text: &'a str, face: SampleFace<'a>, points: f32) -> Self {
FontSample { common: Common::new(), text, face, points }.label(label)
pub(crate) fn new(label: impl Into<Label>, text: impl Into<Cow<'a, str>>, face: SampleFace<'a>, points: f32) -> Self {
FontSample { common: Common::new(), text: text.into(), face, points }.label(label)
}
}
@@ -93,7 +95,7 @@ impl Component for FontSample<'_> {
Shown::Ready(font) => font,
_ => FontRef::proportional(),
};
let runs = [DocRun::new(self.text, font, self.points, DataColor::new(Color32::PLACEHOLDER))];
let runs = [DocRun::new(self.text.as_ref(), font, self.points, DataColor::new(Color32::PLACEHOLDER))];
cx.layout_doc(&faces::sample_text(&runs, cx.room)).size()
}
@@ -101,9 +103,9 @@ impl Component for FontSample<'_> {
let painter = ui.content_painter(cx);
let ink = |color: StyleColor| DataColor::new(color.egui());
match self.face.shown(cx) {
Shown::Ready(font) => faces::paint_sample(&painter, cx.content_rect, &font, self.text, self.points, ink(cx.style.ink)),
Shown::Ready(font) => faces::paint_sample(&painter, cx.content_rect, &font, &self.text, self.points, ink(cx.style.ink)),
Shown::Unavailable => {
faces::paint_sample(&painter, cx.content_rect, &FontRef::proportional(), self.text, self.points, ink(cx.style.muted));
faces::paint_sample(&painter, cx.content_rect, &FontRef::proportional(), &self.text, self.points, ink(cx.style.muted));
}
_ => {}
}
+76 -20
View File
@@ -3,6 +3,7 @@
//! drawn in their own face, favourites (stars), recent families at the top, class and feature filters above the
//! list and a "similar fonts" filter. Behaviour follows Photoshop's font menu.
mod banner;
pub(crate) mod rank;
mod rows;
#[cfg(feature = "suite")]
@@ -20,7 +21,8 @@ use craft_ui::contract::{
Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _,
};
use craft_ui::list::{ThumbSize, TrailingPart};
use craft_ui::controls::disclosure::DisclosureGlyph;
use craft_ui::list::{ListRow, ThumbSize};
use craft_ui::primitives::{IconSpec, TextKey, TextOptions, TextRun};
use craft_ui::runtime::env::{EnvView, Label};
use craft_ui::runtime::memory::StageAccess;
@@ -30,6 +32,7 @@ use egui::{Rect, Response, Vec2};
use serde::{Deserialize, Serialize};
use crate::missing::{DocumentFont, FontStatus, MissingFontsWords, document_fonts};
use crate::panel::browse::SCAN_POLL_SECONDS;
pub use rank::FamilyInfos;
use rank::{Info, shown_name};
@@ -50,6 +53,8 @@ craft_ui::words! {
all_classes: "fontPicker.allClasses" = "All Classes";
clear_all: "fontPicker.clearAll" = "Clear All";
sample: "fontPicker.sample" = "Sample";
/// The name of the preview banner, with `{family}` for the family it shows.
preview_of: template "fontPicker.previewOf" = "Font preview: {family}";
no_match: "fontPicker.noMatch" = "No fonts match";
/// The name of a row's star, with `{row}` for the row's label.
favorite: template "fontPicker.favorite" = "Favorite {row}";
@@ -67,15 +72,6 @@ craft_ui::words! {
handwritten: "fontPicker.classHandwritten" = "Handwritten";
blackletter: "fontPicker.classBlackletter" = "Blackletter";
decorative: "fontPicker.classDecorative" = "Decorative";
/// The short mark at the end of a row for a class.
mark_serif: "fontPicker.markSerif" = "Se";
mark_slab_serif: "fontPicker.markSlabSerif" = "Sl";
mark_sans_serif: "fontPicker.markSansSerif" = "Sa";
mark_script: "fontPicker.markScript" = "Sc";
mark_monospace: "fontPicker.markMonospace" = "Mo";
mark_handwritten: "fontPicker.markHandwritten" = "Ha";
mark_blackletter: "fontPicker.markBlackletter" = "Bl";
mark_decorative: "fontPicker.markDecorative" = "De";
show_styles: "fontPicker.showStyles" = "Show styles";
hide_styles: "fontPicker.hideStyles" = "Hide styles";
sample_arabic: "fontPicker.sampleArabic" = "أبجد";
@@ -83,10 +79,12 @@ craft_ui::words! {
format_true_type: "fontPicker.formatTrueType" = "TrueType";
format_variable: "fontPicker.formatVariable" = "Variable";
served: "fontPicker.served" = "Not installed";
/// The field's text while the installed fonts are still being read.
loading: "fontPicker.loading" = "Loading fonts…";
}
}
/// Photoshop's font classes, in its filter menu order (the class glyph at the row's right).
/// Photoshop's font classes, in its filter menu order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
@@ -372,14 +370,11 @@ impl Outcome for FontPickerOutput {
const TEXT: PartKey = PartKey::new("text");
/// The chevron that opens and closes the list.
const CHEVRON: PartKey = PartKey::new("chevron");
const CHEVRON_ICON: &str = "chevron_down";
/// The mark before the chevron of a shown font that is not installed; its tooltip is the note.
const WARNING: PartKey = PartKey::new("missing");
const WARNING_ICON: &str = "warning";
/// The popup the chevron and Alt+Down toggle.
const POPUP: &str = "list";
/// The star at the end of a row.
const STAR: TrailingPart = TrailingPart::new(0);
/// The widest family names in common use, which the field's width is sized by.
const NAME_SAMPLE: &str = "Source Sans Pro Semibold Condensed";
@@ -428,6 +423,22 @@ impl Codec for FamilyCodec {
}
}
/// The field's text while the installed fonts are still being read: the loading words, whatever the family.
#[derive(Clone)]
struct Loading(Label);
impl Codec for Loading {
type Value = String;
fn format(&self, _: &String) -> String {
self.0.as_str().to_owned()
}
fn parse(&self, _: &str, _: &String) -> Result<String, NotAValue> {
Err(NotAValue)
}
}
/// What the picker keeps between passes: the draft the list was last filtered for, the family the list previews,
/// whether the class column is hidden, and, for the open list only, the families whose styles show and the families
/// already reported as rested.
@@ -547,6 +558,7 @@ impl<'a> FontPicker<'a> {
action: None,
}
.label(label)
.enabled(catalog.is_ready())
}
/// The adornments at the end of the field: the missing mark when `missing`, then the chevron. The mark is a glyph
@@ -556,14 +568,14 @@ impl<'a> FontPicker<'a> {
if missing {
all.push(Adornment::glyph(IconSpec::svg(IconId::new(WARNING_ICON))));
}
all.push(Adornment::button(CHEVRON, IconSpec::svg(IconId::new(CHEVRON_ICON)), name));
all.push(Adornment::button(CHEVRON, DisclosureGlyph::dropdown(), name));
all
}
/// The note for `family` when it is shown in another face because the catalog lacks it, by the rule the Missing
/// Fonts dialog uses: the missing-font sentence, then the advice the host chose.
fn missing_note(&self, family: &str, words: &MissingFontsWords) -> Option<Label> {
let face = self.shown_as?;
let face = self.shown_as.filter(|_| self.catalog.is_ready())?;
let status = document_fonts(self.catalog, &[DocumentFont::new(family, "", None)]).into_iter().next()?.status;
if status != FontStatus::Missing {
return None;
@@ -603,6 +615,28 @@ pub struct FontPickerStyle {
field: FieldStyle,
/// The ink of the missing-font warning icon (`status.warn.fg`), dimmed to `text.disabled` while disabled.
warning: Stateful<StyleColor>,
/// The list's sample height and family row height at each preview size, none first: the thumbnail sides
/// (`size.thumb.*`) and the height of a list row holding one.
pub(crate) samples: [Sample; 4],
}
/// The sample of a family row at one preview size: how high its band is, and how high the row holding it is.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Sample {
pub(crate) side: f32,
pub(crate) row: f32,
}
impl FontPickerStyle {
/// The sample at `size`.
pub(crate) fn sample(&self, size: ThumbSize) -> Sample {
match size {
ThumbSize::Small => self.samples[1],
ThumbSize::Medium => self.samples[2],
ThumbSize::Large => self.samples[3],
_ => self.samples[0],
}
}
}
impl Component for FontPicker<'_> {
@@ -619,7 +653,16 @@ impl Component for FontPicker<'_> {
let field = if cx.env::<ControlPlace>() == ControlPlace::Ribbon { field.held_at(cx.tokens.size.length.field.sm) } else { field };
let warn = cx.tone(Tone::Warn);
let off = cx.color(cx.tokens.color.text.disabled);
FontPickerStyle { surface: cx.field(), metrics: field.metrics(), field, warning: Stateful::new(warn).off(States::new(warn, warn, warn, off)) }
let thumb = &cx.tokens.size.thumb;
let sample = |size: ThumbSize, side: f32| Sample { side, row: ListRow::row_height(cx, size, false) };
let samples = [
sample(ThumbSize::None, 0.0),
sample(ThumbSize::Small, thumb.sm),
sample(ThumbSize::Medium, thumb.md),
sample(ThumbSize::Large, thumb.lg),
];
let warning = Stateful::new(warn).off(States::new(warn, warn, warn, off));
FontPickerStyle { surface: cx.field(), metrics: field.metrics(), field, warning, samples }
}
/// The wheel steps the family through the list.
@@ -658,9 +701,17 @@ impl Component for FontPicker<'_> {
.pointer_only("Alt+Down opens the list")
.toggles(POPUP);
}
let codec = self.codec(infos_of(cx.ui.ctx(), cx.id, self.catalog), &cx.env);
let mut options = TextOptions::new();
options.select_on_focus = true;
if !self.catalog.is_ready() {
// The first scan runs on a background thread; the field asks again until it ends.
self.catalog.scan_in_background();
craft_ui::runtime::frame::request_repaint_after(cx.ui.ctx(), SCAN_POLL_SECONDS);
let loading = Loading(cx.words::<FontPickerWords>().loading.clone());
cx.text(text_key(), placed.text, &loading, &family, &options);
return;
}
let codec = self.codec(infos_of(cx.ui.ctx(), cx.id, self.catalog), &cx.env);
cx.text(text_key(), placed.text, &codec, &family, &options);
}
@@ -672,6 +723,9 @@ impl Component for FontPicker<'_> {
/// cancelled or replaced by a pick). A preview that the list closed on without a pick is cancelled. While the
/// list is closed, the arrows and the wheel step through the families.
fn update(&mut self, cx: &mut Cx<'_, Self>) {
if !self.catalog.is_ready() {
return;
}
let list = cx.popup(POPUP);
let draft = cx.text(&text_key()).and_then(|outcome| outcome.draft.clone());
let before = std::mem::replace(&mut cx.memory::<Typing>().draft, draft.clone());
@@ -719,7 +773,9 @@ impl Component for FontPicker<'_> {
}
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
rows::popup(self, ui, cx);
if self.catalog.is_ready() {
rows::popup(self, ui, cx);
}
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
@@ -732,7 +788,7 @@ impl Component for FontPicker<'_> {
let color = cx.resolve(&cx.style.warning);
ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON)).color(color));
}
ui.face(CHEVRON, IconButton::new(IconId::new(CHEVRON_ICON)).label(name));
ui.face(CHEVRON, IconButton::new(DisclosureGlyph::dropdown()).label(name));
}
fn finish(self, mut cx: Cx<'_, Self>) -> FontPickerOutput {
+114
View File
@@ -0,0 +1,114 @@
//! `FontPreviewBanner`: the family the picker previews, named and set in its own face, on a well at the top of the
//! list.
use craft_behavior::Sense;
use craft_theme::TypeRole;
use craft_ui::contract::{Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role};
use craft_ui::fonts::FontRef;
use craft_ui::primitives::TextRun;
use craft_ui::runtime::env::Label;
use craft_ui::style::{ComponentStyle, Corners, DataColor, Metrics, StyleColor, StyleCx, SurfaceKind};
use egui::{Pos2, Rect, Vec2};
use crate::panel::faces::{self, Shown};
use crate::panel::specimen::SampleFace;
/// The share of the sample band's height the sample's em takes, as in the list's rows.
const SAMPLE_EM: f32 = 0.7;
/// The style of the banner: the well's padding, the name line and the sample band.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub(crate) struct FontPreviewBannerStyle {
#[style(metrics)]
metrics: Metrics,
/// Around the name and the sample, inside the well: `space.pad.regular`.
pad: f32,
/// Between the name and the sample: `space.gap.tight`.
gap: f32,
/// The name's line: the caption role's line height.
name_line: f32,
/// The name's ink: `text.faint`.
name: StyleColor,
/// The sample band: the large thumbnail side (`size.thumb.lg`).
band: f32,
/// The sample's ink: `text.normal`.
ink: StyleColor,
}
/// The preview at the top of the font list: a well (`SurfaceKind::Sunken`) as wide as the list, the family's name in
/// the caption role and under it `text` in the family's face, one line cut at the end. While the face loads the band
/// stays empty. The label names it for a screen reader.
#[derive(craft_ui::contract::Component)]
#[component(content_painter)]
pub(crate) struct FontPreviewBanner<'a> {
#[common]
common: Common,
name: &'a str,
text: &'a str,
face: SampleFace<'a>,
}
impl<'a> FontPreviewBanner<'a> {
/// The banner of the family named `name`, setting `text` in `face`, named `label`.
pub(crate) fn new(label: impl Into<Label>, name: &'a str, text: &'a str, face: SampleFace<'a>) -> Self {
FontPreviewBanner { common: Common::new(), name, text, face }.label(label)
}
}
impl Component for FontPreviewBanner<'_> {
const ROLE: Role = Role::LABEL;
const PARTS: bool = false;
const INPUT: craft_ui::contract::Input = craft_ui::contract::Input::Display;
const OVERLAYS: bool = false;
type Style = FontPreviewBannerStyle;
type Output = egui::Response;
fn style(cx: &StyleCx<'_>, _: FontPreviewBannerStyleKey) -> FontPreviewBannerStyle {
let tokens = cx.tokens;
FontPreviewBannerStyle {
metrics: Metrics::new(),
pad: tokens.space.pad.regular,
gap: tokens.space.gap.tight,
name_line: tokens.typography.get(TypeRole::Caption).line_height,
name: cx.color(tokens.color.text.faint),
band: tokens.size.thumb.lg,
ink: cx.color(tokens.color.text.normal),
}
}
fn sense(&self) -> Sense {
Sense::empty()
}
/// As wide as the room; as high as the padding, the name line, the gap and the sample band.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let style = cx.style;
Vec2::new(cx.room.unwrap_or(0.0), 2.0 * style.pad + style.name_line + style.gap + style.band)
}
fn fills(&self) -> Option<craft_behavior::Axis> {
Some(craft_behavior::Axis::X)
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let style = cx.style;
ui.draw().surface(cx.rect, SurfaceKind::Sunken, Corners::All);
let inner = cx.rect.shrink(style.pad);
let name = Rect::from_min_size(inner.min, Vec2::new(inner.width(), style.name_line));
ui.draw().text(name, &TextRun::new(self.name).role(TypeRole::Caption).color(style.name));
let band = Rect::from_min_max(Pos2::new(inner.left(), name.bottom() + style.gap), inner.max);
let points = style.band * SAMPLE_EM;
let ink = DataColor::new(style.ink.egui());
let painter = ui.content_painter(cx);
match self.face.shown(cx) {
Shown::Ready(font) => faces::paint_sample(&painter, band, &font, self.text, points, ink),
Shown::Unavailable => faces::paint_sample(&painter, band, &FontRef::proportional(), self.text, points, ink),
_ => {}
}
}
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
cx.response.clone()
}
}
+23 -3
View File
@@ -4,9 +4,10 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
use craft_font_catalog::{Catalog, FaceInfo, LocalizedName, Outlines};
use craft_font_catalog::{Catalog, FaceInfo, LocalizedName, Outlines, is_private_family};
use craft_i18n::matcher::{Matcher, Rank};
use craft_i18n::{Collator, Folder};
use skrifa::GlyphId;
use skrifa::MetadataProvider as _;
use skrifa::raw::{FontRef, TableProvider};
@@ -138,7 +139,8 @@ fn draws(catalog: &Catalog, face: &FaceInfo, sample: &str, arabic: &str, shown:
let data = catalog.load(face).ok()?;
let font = FontRef::from_index(&data.bytes, face.index).ok()?;
let map = font.charmap();
let drawn = |t: &str| t.chars().filter(|c| !c.is_whitespace()).all(|c| map.map(c).is_some());
let inked = inked(&font);
let drawn = |t: &str| t.chars().filter(|c| !c.is_whitespace()).all(|c| map.map(c).is_some_and(&inked));
if drawn(sample) {
let arabic = has_arabic_sample(&drawn, sample, arabic).then(|| arabic.to_owned());
return Some(Samples { latin: sample.to_owned(), arabic });
@@ -146,10 +148,27 @@ fn draws(catalog: &Catalog, face: &FaceInfo, sample: &str, arabic: &str, shown:
if drawn(shown) {
return Some(Samples { latin: shown.to_owned(), arabic: None });
}
let first = map.mappings().filter_map(|(cp, _)| char::from_u32(cp)).filter(|c| !c.is_whitespace() && !c.is_control()).take(6).collect();
let first = map
.mappings()
.filter(|(_, glyph)| inked(*glyph))
.filter_map(|(cp, _)| char::from_u32(cp))
.filter(|c| !c.is_whitespace() && !c.is_control())
.take(6)
.collect();
Some(Samples { latin: first, arabic: None })
}
/// Whether a glyph of `font` has an outline, which is all the sample painter draws: a TrueType glyph with contours, or
/// any glyph of a CFF face. A colour bitmap face (sbix, CBDT) maps its characters to glyphs without outlines.
fn inked<'a>(font: &FontRef<'a>) -> impl Fn(GlyphId) -> bool + 'a {
let truetype = font.loca(None).ok().zip(font.glyf().ok());
let cff = font.cff().is_ok() || font.cff2().is_ok();
move |glyph| match &truetype {
Some((loca, glyf)) => loca.get_glyf(glyph, glyf).ok().flatten().is_some(),
None => cff,
}
}
/// The upright face nearest weight 400.
pub(super) fn regular_face(faces: &[FaceInfo]) -> Option<&FaceInfo> {
faces.iter().min_by_key(|f| (f.italic, (f.weight - 400.0).abs() as u32))
@@ -291,6 +310,7 @@ pub(super) fn list(
let mut ranked: Vec<(Rank, FamilyRow)> = catalog
.families()
.iter()
.filter(|family| !is_private_family(family))
.filter_map(|family| {
let info = infos.families.get(family)?;
let shown = shown_name(info, family, listing.language, english);
+125 -93
View File
@@ -1,41 +1,45 @@
//! The picker's popup: the preview banner, the filter toggles, the class column and the list of family rows with the
//! styles of the families opened in it.
//! styles of the families opened in it. A family row reads, in reading order: its star, the disclosure of its styles
//! (or the empty disclosure column), the name, the format badge and the sample in the family's face.
use std::borrow::Cow;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use craft_behavior::{DisplayOrder, IconId, ItemSource, Preview, Selection};
use craft_behavior::{ColumnKey, ColumnWidth, DisplayOrder, IconId, ItemSource, Preview, Selection, SizeHint};
use craft_font_catalog::Catalog;
use craft_theme::variant::Variant;
use craft_ui::buttons::{Button, ToggleButton};
use craft_ui::choice::{Radio, RadioGroup};
use craft_ui::contract::overlay::Dismiss;
use craft_ui::contract::{
Bind, CollectionEvent, Cx, Edit as _, LeadSource, Overlay, OverlayUi, Overlays as _, Props as _, Remember as _, Show as _, ShowCollection as _,
ShowContainer as _, WordSetCx as _, clicked,
Bind, CollectionEvent, ColumnSpec, Cx, Edit as _, LeadSource, Overlay, OverlayUi, Overlays as _, Props as _, Remember as _, Show as _,
ShowCollection as _, ShowContainer as _, Styled as _, ToggleColumn, WordSetCx as _, clicked,
};
use craft_ui::display::{Picture, PictureSize, Text};
use craft_ui::display::{Divider, Text};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::list::{List, ListRow, RowEvent, ThumbAspect, ThumbSize, TrailingFace};
use craft_ui::primitives::{ContentPainterCx, IconSpec};
use craft_ui::list::{List, ListRow, ThumbSize, ToggleCell, ToggleFace, ToggleState, TreeLeaves};
use craft_ui::runtime::env::Label;
use egui::Rect;
use super::banner::FontPreviewBanner;
use super::rank::{FamilyInfos, Language, Listing, list, shown_name};
use super::{
FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos_of,
read, ui_language, write,
FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, Typing, infos_of, read,
ui_language, write,
};
use crate::panel::faces::{Owner, Shown, paint_sample, shown};
use craft_ui::style::DataColor;
use crate::panel::faces::Owner;
use crate::panel::specimen::{FontSample, SampleFace};
/// The share of a sample thumbnail's height the sample's em takes.
/// The share of a sample band's height the sample's em takes.
const SAMPLE_EM: f32 = 0.7;
/// The sample thumbnail is this many times as wide as high.
const SAMPLE_ASPECT: (u16, u16) = (4, 1);
/// The banner's sample is this many times as wide as high.
const BANNER_ASPECT: (u16, u16) = (12, 1);
/// The sample column is this many times as wide as the sample band is high.
const SAMPLE_WIDTH: f32 = 4.0;
/// The star column: a favourite's star, on every family row.
const STAR: ColumnKey = ColumnKey::new("star");
/// The column of the name, the disclosure, the check and, at its end, the format badge.
const NAME: ColumnKey = ColumnKey::new("name");
/// The column of the sample in the family's face.
const SAMPLE: ColumnKey = ColumnKey::new("sample");
/// The headings of the `Plain` list.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -107,41 +111,45 @@ fn slot_of<'s>(slots: &'s [Slot], key: &SlotKey) -> Option<&'s Slot> {
slots.iter().find(|slot| slot.key() == *key)
}
/// The list's slots as a collection source: a tree two levels deep.
struct Slots<'a>(&'a [Slot]);
/// The list's slots as a collection source: a tree two levels deep. A family row is as high as its sample needs.
struct Slots<'a> {
slots: &'a [Slot],
/// The family rows' height.
row: f32,
}
impl DisplayOrder<SlotKey> for Slots<'_> {
fn len(&self) -> usize {
self.0.len()
self.slots.len()
}
fn key(&self, at: usize) -> SlotKey {
self.0[at].key()
self.slots[at].key()
}
fn index_of(&self, key: &SlotKey) -> Option<usize> {
self.0.iter().position(|slot| slot.key() == *key)
self.slots.iter().position(|slot| slot.key() == *key)
}
fn depth(&self, at: usize) -> usize {
usize::from(matches!(self.0[at], Slot::Style { .. }))
usize::from(matches!(self.slots[at], Slot::Style { .. }))
}
/// A family with several styles. A recent row has none: the family is listed again below the gap.
fn has_children(&self, at: usize) -> bool {
matches!(&self.0[at], Slot::Family { row, .. } if row.styles > 1 && !row.recent)
matches!(&self.slots[at], Slot::Family { row, .. } if row.styles > 1 && !row.recent)
}
fn open(&self, at: usize) -> bool {
matches!(self.0[at], Slot::Family { open: true, .. })
matches!(self.slots[at], Slot::Family { open: true, .. })
}
fn is_section(&self, at: usize) -> bool {
matches!(self.0[at], Slot::Gap | Slot::Heading(_))
matches!(self.slots[at], Slot::Gap | Slot::Heading(_))
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
match &self.0[at] {
match &self.slots[at] {
Slot::Family { row, .. } => Some(Cow::Borrowed(row.shown.as_str())),
Slot::Style { style, .. } => Some(Cow::Borrowed(style.as_str())),
Slot::Gap | Slot::Heading(_) | Slot::Action(_) => None,
@@ -149,7 +157,18 @@ impl DisplayOrder<SlotKey> for Slots<'_> {
}
}
impl ItemSource<SlotKey> for Slots<'_> {}
impl ItemSource<SlotKey> for Slots<'_> {
fn size_hint(&self, at: usize) -> SizeHint {
match self.slots[at] {
Slot::Family { .. } => SizeHint::Height(self.row),
_ => SizeHint::Auto,
}
}
fn toggled(&self, at: usize, column: &ColumnKey) -> bool {
*column == STAR && matches!(&self.slots[at], Slot::Family { row, .. } if row.starred)
}
}
/// The rows with a gap after the recents (headings over the recents and the families under `layout.sections`), the
/// styles of each expanded family under its row, and the action rows at the end.
@@ -200,20 +219,6 @@ fn class_label(class: FontClass, words: &FontPickerWords) -> Label {
}
}
/// The short mark at the end of a row for a class.
fn class_mark(class: FontClass, words: &FontPickerWords) -> Label {
match class {
FontClass::Serif => words.mark_serif.clone(),
FontClass::SlabSerif => words.mark_slab_serif.clone(),
FontClass::SansSerif => words.mark_sans_serif.clone(),
FontClass::Script => words.mark_script.clone(),
FontClass::Monospace => words.mark_monospace.clone(),
FontClass::Handwritten => words.mark_handwritten.clone(),
FontClass::Blackletter => words.mark_blackletter.clone(),
FontClass::Decorative => words.mark_decorative.clone(),
}
}
/// The name of a format's badge.
fn format_label(format: FontFormat, words: &FontPickerWords) -> Label {
match format {
@@ -233,47 +238,55 @@ fn filter_bar(ui: &mut egui::Ui, filters: &mut FontFilters, hide_classes: &mut b
let star = if filters.favorites { "star_filled" } else { "star" };
ToggleButton::new(words.favorites.clone(), Bind::bound(&mut filters.favorites)).icon(IconId::new(star)).icon_only().show(ui);
ToggleButton::new(words.similar.clone(), Bind::bound(&mut filters.similar)).icon(IconId::new("font_similar")).icon_only().show(ui);
let clear = Button::new(words.clear_all.clone()).enabled(filters.any()).show(ui);
let clear = Button::new(words.clear_all.clone()).variant(Variant::GHOST).enabled(filters.any()).show(ui);
if clicked(&clear) {
filters.clear();
}
});
}
/// The class column: All Classes and the eight classes, one chosen.
fn class_column(ui: &mut egui::Ui, filters: &mut FontFilters, words: &FontPickerWords) {
let mut chosen = filters.class.and_then(|c| FontClass::ALL.iter().position(|a| *a == c)).map_or(0u8, |i| i as u8 + 1);
RadioGroup::new(words.classes.clone(), Bind::bound(&mut chosen)).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
Radio::new(0u8).label(words.all_classes.clone()).show(ui);
for (at, class) in FontClass::ALL.into_iter().enumerate() {
Radio::new(at as u8 + 1).label(class_label(class, words)).show(ui);
}
});
});
filters.class = usize::from(chosen).checked_sub(1).and_then(|i| FontClass::ALL.get(i).copied());
}
/// The classes as a collection source: All Classes (key 0), then each class (its position in `FontClass::ALL` plus one).
struct Classes<'a>(&'a [Label]);
/// A thumbnail painting `text` in the regular face of `family`; nothing for a family the catalog lacks or an empty
/// text, and nothing until the face is loaded.
fn face_thumb<'a>(catalog: &'a Arc<Catalog>, infos: &'a FamilyInfos, family: &'a str, text: String) -> impl Fn(&ContentPainterCx<'_>, Rect) + 'a {
move |cx, rect| {
let Some(info) = infos.families.get(family) else { return };
if text.is_empty() {
return;
}
if let Shown::Ready(font) = shown(cx, catalog, Owner::Installed, &info.regular) {
let ink = DataColor::new(cx.ink());
paint_sample(cx, rect, &font, &text, rect.height() * SAMPLE_EM, ink);
}
impl DisplayOrder<u8> for Classes<'_> {
fn len(&self) -> usize {
self.0.len()
}
fn key(&self, at: usize) -> u8 {
at as u8
}
fn index_of(&self, key: &u8) -> Option<usize> {
(usize::from(*key) < self.0.len()).then_some(usize::from(*key))
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
Some(Cow::Borrowed(self.0[at].as_str()))
}
}
/// The banner: `text` in the face of `family`, on one line cut at the end, in a picture as high as the large thumbnail.
fn banner(ui: &mut egui::Ui, catalog: &Arc<Catalog>, infos: &FamilyInfos, family: &str, shown_name: &str, text: &str) {
Picture::painter(shown_name.to_owned(), ThumbAspect::new(BANNER_ASPECT.0, BANNER_ASPECT.1), face_thumb(catalog, infos, family, text.to_owned()))
.extent(PictureSize::Thumb(ThumbSize::Large))
.show(ui);
impl ItemSource<u8> for Classes<'_> {}
/// The class column: All Classes and the eight classes as a list of options, the chosen one selected.
fn class_column(ui: &mut egui::Ui, filters: &mut FontFilters, words: &FontPickerWords) {
let chosen = filters.class.and_then(|c| FontClass::ALL.iter().position(|a| *a == c)).map_or(0u8, |i| i as u8 + 1);
let labels: Vec<Label> =
std::iter::once(words.all_classes.clone()).chain(FontClass::ALL.into_iter().map(|class| class_label(class, words))).collect();
let mut selection = Selection::single(chosen);
List::<u8>::options(words.classes.clone())
.selection(Bind::bound(&mut selection))
.show_items(ui, &Classes(&labels), &mut |key, _| ListRow::new(labels[usize::from(*key)].clone()).option().check(*key == chosen));
let picked = selection.items.first().copied().unwrap_or(chosen);
filters.class = usize::from(picked).checked_sub(1).and_then(|i| FontClass::ALL.get(i).copied());
}
/// The sample of a family row: `text` in the regular face of `family` at `points`, named by the family; the
/// interface face for a family the catalog lacks.
fn sample<'a>(catalog: &'a Catalog, infos: &'a FamilyInfos, family: &str, text: String, points: f32) -> FontSample<'a> {
let face =
infos.families.get(family).map_or(SampleFace::Interface, |info| SampleFace::Face { catalog, owner: Owner::Installed, face: &info.regular });
FontSample::new(Label::from(family.to_owned()), text, face, points)
}
/// The name the banner shows for `family`: its row's shown name when the list holds one, else its name in the
@@ -354,12 +367,23 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
let slots = slots(catalog, found, &expanded, &layout);
let current = slots.iter().position(|slot| matches!(slot, Slot::Family { row, .. } if row.family == family));
let size = settings.as_ref().map_or(ThumbSize::None, |s| s.preview.thumb());
let sample_size = cx.style.sample(size);
let points = sample_size.side * SAMPLE_EM;
let mut columns = Vec::with_capacity(4);
if !plain {
columns.push(ColumnSpec::toggle(STAR, words.favorites.clone(), ToggleColumn::default()).icon(IconId::new("star")));
}
columns.push(ColumnSpec::new(NAME, words.list.clone(), ColumnWidth::fill(1.0)));
if size != ThumbSize::None {
columns.push(ColumnSpec::new(SAMPLE, words.sample.clone(), ColumnWidth::Fixed(sample_size.side * SAMPLE_WIDTH)));
}
let favorites_empty = settings.as_ref().is_none_or(|s| s.favorites.is_empty());
// Rows are keyed, so the stamp names only what rebuilds the list: opening a family keeps the lead.
let mut stamp = DefaultHasher::new();
(&query, narrowing.class, narrowing.favorites, narrowing.variable, narrowing.similar).hash(&mut stamp);
let banner_family = lead.unwrap_or_else(|| family.clone());
let banner_text = picker.preview_text;
// The library picker always shows the banner, with the sample word when the host gives no text.
let banner_text = picker.preview_text.or((!plain).then_some(words.sample.as_str()));
let name = words.list.clone();
let mut stars: Vec<(String, bool)> = Vec::new();
let mut over_rows = false;
@@ -369,10 +393,17 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
Stack::new().show(ui, |ui, _| {
if let Some(text) = banner_text {
let shown_name = banner_shown_name(&slots, &infos, &banner_family, &language_code, settings.as_ref());
banner(ui, catalog, &infos, &banner_family, &shown_name, text);
let face = infos.families.get(&banner_family).map_or(SampleFace::Interface, |info| SampleFace::Face {
catalog,
owner: Owner::Installed,
face: &info.regular,
});
let label = words.preview_of.fill(&[("family", shown_name.as_str())]);
FontPreviewBanner::new(label, &shown_name, text, face).show(ui);
}
if let Some(filters) = filters.as_mut() {
filter_bar(ui, filters, &mut hide_classes, &words);
Divider::horizontal().show(ui);
}
Row::new().show(ui, |ui, _| {
if let (Some(filters), false) = (filters.as_mut(), hide_classes) {
@@ -393,33 +424,31 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
Text::new(message.clone()).show(ui);
return;
}
let source = Slots(&slots);
let source = Slots { slots: &slots, row: sample_size.row };
let selection =
current.filter(|_| query.trim().is_empty()).map_or_else(Selection::default, |at| Selection::single(slots[at].key()));
let rows = List::<SlotKey>::options(name.clone())
.tree(true)
.tree_leaves(TreeLeaves::Aligned)
.columns(columns.clone())
.selection(Bind::given(selection))
.rows_stamp(stamp.finish())
.show_items(ui, &source, &mut |_, item| match &slots[item.at] {
Slot::Gap => ListRow::spacer(),
Slot::Gap => ListRow::separator(),
Slot::Heading(Heading::Recent) => ListRow::new(words.recently_used.clone()).section_heading(),
Slot::Heading(Heading::All) => ListRow::new(words.all_fonts.clone()).section_heading(),
Slot::Action(at) => ListRow::new(actions[*at].clone()).option().depth(0),
Slot::Style { style, .. } => ListRow::new(style.clone()).option().depth(1),
Slot::Style { style, .. } => ListRow::new(style.clone()).cells(item.cells()).option().depth(1),
Slot::Family { row, open } => {
let icon = if row.starred { "star_filled" } else { "star" };
let name = Label::from(words.favorite.fill(&[("row", row.shown.as_str())]));
let star = TrailingFace::Icon(IconSpec::svg(IconId::new(icon)));
let mut line = ListRow::new(row.shown.clone()).option().depth(0).check(current == Some(item.at));
let mut line = ListRow::new(row.shown.clone()).cells(item.cells()).option().depth(0).check(current == Some(item.at));
if !plain {
line = line.trailing_part(STAR, star, name);
let face = ToggleFace::icons(IconId::new("star_filled"), IconId::new("star"));
let name = Label::from(words.favorite.fill(&[("row", row.shown.as_str())]));
line = line.toggle(ToggleCell::new(STAR, face, ToggleState::of(row.starred), name).always_visible());
}
if source.has_children(item.at) {
line = line.group(*open);
}
if let Some(class) = row.class.filter(|_| !plain) {
line = line.trailing_named(class_mark(class, &words), class_label(class, &words));
}
line = match row.format {
Some(format) if !plain => {
line.trailing_named(Label::from(format.badge().to_owned()), format_label(format, &words))
@@ -432,10 +461,10 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
}
let samples =
infos.sample_text(catalog, &row.family, words.sample.as_str(), words.sample_arabic.as_str(), &row.shown);
let aspect = ThumbAspect::new(SAMPLE_ASPECT.0, SAMPLE_ASPECT.1);
line = line.thumb_aspect(size, aspect, face_thumb(catalog, &infos, &row.family, samples.latin));
line = line.cell_field(SAMPLE, sample(catalog, &infos, &row.family, samples.latin, points), |_| {});
// The Arabic sample ends the name's band, so the sample column keeps one width.
match samples.arabic {
Some(arabic) => line.extra_thumb(face_thumb(catalog, &infos, &row.family, arabic)),
Some(arabic) => line.trailing_space(sample(catalog, &infos, &row.family, arabic, points)),
None => line,
}
}
@@ -472,9 +501,12 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
}
}
CollectionEvent::Activate(key) => picked = Some(key),
CollectionEvent::Item(key, RowEvent::Trailing { part, .. }) if part == STAR => {
if let Some(Slot::Family { row, .. }) = slot_of(&slots, &key) {
stars.push((row.family.clone(), !row.starred));
CollectionEvent::Toggle(edit) => {
if let Some(toggle) = edit.value()
&& toggle.column == STAR
&& let Some(Slot::Family { row, .. }) = slot_of(&slots, &toggle.key)
{
stars.push((row.family.clone(), toggle.on));
}
}
_ => {}
+68
View File
@@ -475,3 +475,71 @@ fn the_missing_font_warning_icon_paints_in_status_warn_fg_and_dims_when_disabled
"a disabled picker paints its warning icon in text.disabled {text_disabled:?}, not {tints:?}"
);
}
/// A library list with Hack as a recent family: the shown picker and the catalog of Inter (two styles) and Hack (one).
fn library_rig() -> Fixture {
let catalog = catalog_of(&[INTER_REGULAR, INTER_SEMIBOLD, epaint_default_fonts::HACK_REGULAR]);
let mut family = "Inter".to_owned();
let mut settings = FontPickerSettings::default();
settings.recent = vec!["Hack".to_owned()];
let mut filters = FontFilters::default();
let mut fx = Fixture::new(move |ui| {
FontPicker::new("Font family", Bind::bound(&mut family), &catalog)
.settings(Bind::bound(&mut settings))
.filters(Bind::bound(&mut filters))
.show(ui);
});
fx.in_room(Room::Window);
fx.settle();
open(&mut fx);
fx
}
/// Production's and Photoshop's row: the star first, then the names in one column whether or not a family has styles
/// to open (a recent row included), the sample after the name; and a rule, not blank room, ends the recent group.
#[trial]
fn family_names_line_up_after_the_star_and_before_the_sample() {
let fx = library_rig();
let banner = fx.by_label("Font preview: Inter").expect("the banner names the current family").rect;
let names: Vec<egui::Rect> = fx
.texts()
.iter()
.filter(|painted| (painted.text == "Inter" || painted.text == "Hack") && !banner.intersects(painted.rect))
.map(|painted| painted.rect)
.collect();
assert_eq!(names.len(), 3, "Hack in the recent group and in the list, Inter once: {names:?}");
assert!(names.iter().all(|rect| (rect.left() - names[0].left()).abs() < 0.5), "the names start at one x: {names:?}");
let star = fx.by_label("Favorite Inter").expect("Inter's star").rect;
let inter = names.iter().find(|rect| (rect.center().y - star.center().y).abs() < star.height()).expect("Inter's name beside its star");
assert!(star.right() <= inter.left(), "the star comes first: {star:?} {inter:?}");
let sample = fx.texts().iter().all(|painted| painted.text != "Sample" || painted.rect.left() >= inter.right());
assert!(sample, "no sample before a name");
let recent = names.iter().map(|rect| rect.bottom()).fold(f32::INFINITY, f32::min);
let rule = fx.shape_bounds().iter().any(|shape| shape.top() >= recent && shape.height() < 2.0 && shape.width() > star.width() * 4.0);
assert!(rule, "a rule under the recent group");
}
/// A click on a row's star stars the family without picking it or closing the list.
#[trial]
fn a_star_flips_the_favourite_without_picking_or_closing() {
let mut fx = library_rig();
let star = fx.by_label("Favorite Hack").expect("Hack's star");
fx.click(&star);
fx.settle();
assert!(fx.by_label("Favorite Inter").is_some(), "the list stays open");
}
/// The class column is a list of options: a class narrows the list, All Classes brings every family back.
#[trial]
fn a_class_narrows_the_list_and_all_classes_restores_it() {
let mut fx = library_rig();
let monospace = fx.by_label("Monospace").expect("the Monospace class");
fx.click(&monospace);
fx.settle();
assert!(fx.by_label("Favorite Hack").is_some(), "Hack is monospaced");
assert!(fx.by_label("Favorite Inter").is_none(), "Inter is not");
let all = fx.by_label("All Classes").expect("All Classes");
fx.click(&all);
fx.settle();
assert!(fx.by_label("Favorite Inter").is_some(), "every family is back");
}