type-w2: net change of 2 commits

- type-w2: written from its sheet
- type-w2: repair 1
This commit is contained in:
bflatastic committed 2026-11-21 21:27:21 +07:00
1 parent 67c3c579a9
commit be2fb0ff2c
5 files changed
+450 -81

No files matched your search

+58 -36
View File
@@ -11,16 +11,18 @@ mod stories;
use std::sync::Arc;
use craft_behavior::{Codec, EditEvent, IconId, Mixed, NotAValue, PartKey, Sense, Value};
use craft_behavior::{HitLevel, HitPriority, NavMove, Preview};
use craft_behavior::nav::{StepResult, ValueAxes, ValueSteps, wheel_step};
use craft_behavior::{HitLevel, HitPriority, NavMove, Preview, WheelPhase};
use craft_font_catalog::Catalog;
use craft_host::Section;
use craft_ui::buttons::IconButton;
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, WordSetCx as _,
Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, step_stop,
};
use craft_ui::list::{ThumbSize, TrailingPart};
use craft_ui::primitives::{IconSpec, TextKey, TextOptions, TextRun};
use craft_ui::runtime::edit::PreviewWatch;
use craft_ui::runtime::env::{EnvView, Label};
use craft_ui::runtime::memory::StageAccess;
use craft_ui::text::{Adornment, place, reserve};
@@ -191,7 +193,6 @@ impl FontScript {
/// A family set the host gives (VectorCraft: Document, Recently Added), one filter toggle each. An `ordered` set that
/// is on lists in its own order. A disabled set's toggle is off and dimmed, with its hint as the reason.
#[allow(dead_code)] // P3(type-w2): ty.X11
pub struct FamilySet<'a> {
key: &'a str,
label: Label,
@@ -204,25 +205,30 @@ pub struct FamilySet<'a> {
impl<'a> FamilySet<'a> {
/// The set `key` named `label` over `families`.
pub fn new(key: &'a str, label: impl Into<Label>, families: &'a [String]) -> Self {
let _ = (key, label.into(), families);
todo!("ty.X11")
FamilySet { key, label: label.into(), hint: None, families, ordered: false, enabled: true }
}
/// The reason shown while the set is disabled.
pub fn hint(self, hint: impl Into<Label>) -> Self {
let _ = hint.into();
todo!("ty.X11")
pub fn hint(mut self, hint: impl Into<Label>) -> Self {
self.hint = Some(hint.into());
self
}
/// Lists the set in its own order while it is on.
pub fn ordered(self) -> Self {
todo!("ty.X11")
pub fn ordered(mut self) -> Self {
self.ordered = true;
self
}
/// Whether the set's toggle can be turned on.
pub fn enabled(self, on: bool) -> Self {
let _ = on;
todo!("ty.X11")
pub fn enabled(mut self, on: bool) -> Self {
self.enabled = on;
self
}
/// The family's place in the set. A host may give canonical lowercase names, so case does not matter.
fn position(&self, family: &str) -> Option<usize> {
self.families.iter().position(|f| f.eq_ignore_ascii_case(family))
}
}
@@ -383,9 +389,8 @@ pub fn family_rows(
sets: &[FamilySet<'_>],
language: &str,
) -> Vec<FamilyRow> {
let _ = sets; // P3(type-w2): ty.X7
let (folder, collator) = (craft_i18n::Folder::new(language), craft_i18n::Collator::new(language));
let listing = rank::Listing { query, settings, filters, language, served: &[] };
let listing = rank::Listing { query, settings, filters, language, served: &[], sets };
rank::list(catalog, &infos(catalog), &listing, &rank::Language { folder: &folder, collator: &collator }, true).0
}
@@ -430,6 +435,8 @@ const CHEVRON_ICON: &str = "chevron_down";
const POPUP: &str = "list";
/// The star at the end of a row.
const STAR: TrailingPart = TrailingPart::new(0);
/// The Show Similar part before the star, in the `Chips` layout.
const SIMILAR: TrailingPart = TrailingPart::new(1);
/// The widest family names in common use, which the field's width is sized by.
const NAME_SAMPLE: &str = "Source Sans Pro Semibold Condensed";
@@ -472,10 +479,12 @@ impl Codec for FamilyCodec {
}
/// 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.
/// whether the class column is hidden, the watch that reports a preview the picker stopped showing, and, for the open
/// list only, the families whose styles show and the families already reported as rested.
#[derive(Clone, Default)]
struct Typing {
/// Armed while a preview shows: the picker's eviction then ends the preview it proposed.
watch: PreviewWatch,
draft: Option<String>,
lead: Option<String>,
/// The lead's family was proposed by the pointer, so it ends when the pointer leaves the rows.
@@ -555,15 +564,12 @@ pub struct FontPicker<'a> {
served: &'a [String],
/// The host's family sets; their toggles follow Favorites.
#[prop]
#[allow(dead_code)] // P3(type-w2): ty.X12
sets: &'a [FamilySet<'a>],
/// The scripts the script row offers (with All Scripts first); empty: no script row.
#[prop]
#[allow(dead_code)] // P3(type-w2): ty.X13
scripts: &'a [FontScript],
/// Picks the layout of the filter area.
#[prop]
#[allow(dead_code)] // P3(type-w2): ty.X15
filter_layout: FilterLayout,
}
@@ -597,14 +603,16 @@ impl<'a> FontPicker<'a> {
FamilyCodec { infos: infos(self.catalog), language: ui_language(env) }
}
/// The families in list order without filters or recents, which the arrows and the wheel step through.
fn ordered(&self, cx: &Cx<'_, Self>, settings: Option<&FontPickerSettings>) -> Vec<FamilyRow> {
/// The families in the list's narrowed order (the bound filters and the host's sets apply) without the Recent
/// group, which the arrows and the wheel step through.
fn ordered(&self, cx: &Cx<'_, Self>, settings: Option<&FontPickerSettings>, filters: &FontFilters) -> Vec<FamilyRow> {
let infos = infos(self.catalog);
let (folder, collator) = (cx.env.folder(), cx.env.collator());
let filters = FontFilters::default();
let language = ui_language(&cx.env);
let listing = rank::Listing { query: "", settings, filters: &filters, language: &language, served: &[] };
rank::list(self.catalog, &infos, &listing, &rank::Language { folder: &folder, collator: &collator }, false).0
let listing = rank::Listing { query: "", settings, filters, language: &language, served: &[], sets: self.sets };
let mut rows = rank::list(self.catalog, &infos, &listing, &rank::Language { folder: &folder, collator: &collator }, true).0;
rows.retain(|row| !row.recent);
rows
}
}
@@ -682,25 +690,39 @@ impl Component for FontPicker<'_> {
typing.expanded.clear();
typing.rested.clear();
let settings = read(&mut self.settings, cx);
let current = cx.value().cloned().unwrap_or_default();
let all = self.ordered(cx, settings.as_ref());
let Some(here) = all.iter().position(|row| row.family == current) else { return };
let filters = read(&mut self.filters, cx).unwrap_or_default();
let all = self.ordered(cx, settings.as_ref(), &filters);
let stops: Vec<usize> = (0..all.len()).collect();
let here = cx.value().and_then(|current| all.iter().position(|row| row.family == *current));
let mut to = here;
while let Some((step, mods)) = cx.intents().take_move() {
match step {
NavMove::Down if !mods.fine => to = (to + 1).min(all.len() - 1),
NavMove::Up if !mods.fine => to = to.saturating_sub(1),
NavMove::Down if !mods.fine => to = step_stop(&stops, to, true),
NavMove::Up if !mods.fine => to = step_stop(&stops, to, false),
_ => {}
}
}
if let Some(wheel) = cx.take_wheel()
&& wheel.scroll.y != 0.0
if to != here
&& let Some(row) = to.and_then(|at| all.get(at))
{
to = if wheel.scroll.y < 0.0 { (to + 1).min(all.len() - 1) } else { to.saturating_sub(1) };
cx.set(row.family.clone());
}
if to != here {
self.picked = Some(all[to].family.clone());
cx.set(all[to].family.clone());
// The wheel steps one family a line down for a step forward, as one run the wheel's end commits.
if let Some(wheel) = cx.take_wheel() {
if wheel.phase == WheelPhase::End {
cx.wheel_run(wheel.phase, None);
} else if let StepResult::Set(along) =
wheel_step(&ValueSteps::new(0.0, -f64::MAX, f64::MAX, 1.0, 1.0).fine(1.0), ValueAxes::Both, &wheel, cx.env.direction().is_rtl())
&& along != 0.0
{
let mut stop = cx.value().and_then(|current| all.iter().position(|row| row.family == *current));
for _ in 0..along.abs().round() as usize {
stop = step_stop(&stops, stop, along < 0.0);
}
if let Some(row) = stop.and_then(|at| all.get(at)) {
cx.wheel_run(wheel.phase, Some(row.family.clone()));
}
}
}
}
+44 -8
View File
@@ -10,7 +10,7 @@ use craft_i18n::{Collator, Folder};
use skrifa::MetadataProvider as _;
use skrifa::raw::{FontRef, TableProvider};
use super::{FamilyRow, FontClass, FontFilters, FontFormat, FontPickerSettings, SIMILAR_COUNT};
use super::{FamilyRow, FamilySet, FontClass, FontFilters, FontFormat, FontPickerSettings, FontScript, SIMILAR_COUNT};
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
@@ -33,6 +33,8 @@ pub(super) struct Traits {
pub(super) class: Option<FontClass>,
pub(super) panose: [u8; 10],
pub(super) weight: u16,
/// The scripts the face covers.
pub(super) scripts: Vec<FontScript>,
}
impl Traits {
@@ -181,7 +183,12 @@ pub(super) fn shown_name(info: &Info, family: &str, language: &str, english: boo
info.localized.iter().find(exact).or_else(|| info.localized.iter().find(same_language)).map_or_else(|| family.to_owned(), |n| n.name.clone())
}
/// A face's class, PANOSE and weight from its `OS/2` and `post` tables.
/// Whether a family name of the face is in Japanese.
fn japanese_name(face: &FaceInfo) -> bool {
face.localized_families.iter().any(|n| n.language.as_deref().and_then(|l| l.split(['-', '_']).next()).is_some_and(|l| l.eq_ignore_ascii_case("ja")))
}
/// A face's class, PANOSE, weight and scripts from its `OS/2`, `post` and `cmap` tables.
fn read_traits(catalog: &Catalog, face: &FaceInfo) -> Option<Traits> {
let data = catalog.load(face).ok()?;
let font = FontRef::from_index(&data.bytes, face.index).ok()?;
@@ -195,7 +202,17 @@ fn read_traits(catalog: &Catalog, face: &FaceInfo) -> Option<Traits> {
}
let weight = os2.as_ref().map_or(400, |t| t.us_weight_class()).clamp(1, 1000);
let fixed_pitch = font.post().ok().is_some_and(|p| p.is_fixed_pitch() != 0);
Some(Traits { class: classify(&face.family, family_class, panose, fixed_pitch), panose, weight })
let map = font.charmap();
let latin = ('A'..='Z').chain('a'..='z').all(|c| map.map(c).is_some());
let scripts = [
(FontScript::Latin, latin),
(FontScript::Japanese, face.traits.japanese || japanese_name(face)),
(FontScript::Thai, face.traits.thai),
]
.into_iter()
.filter_map(|(script, covered)| covered.then_some(script))
.collect();
Some(Traits { class: classify(&face.family, family_class, panose, fixed_pitch), panose, weight, scripts })
}
/// The class of a family from its regular face, `None` when the face can't be read.
@@ -278,6 +295,14 @@ pub(super) struct Listing<'a> {
pub(super) language: &'a str,
/// Families the host can fetch but the catalog lacks; they list with the matches, by rank and name, with no class, format or sample.
pub(super) served: &'a [String],
/// The host's family sets; those whose key is in the filters and that are enabled narrow the list.
pub(super) sets: &'a [FamilySet<'a>],
}
/// The sets that filter: their key is in `filters.sets` and they are enabled. A key naming a disabled set or no set
/// filters nothing, so a toggle the user cannot turn off never hides families.
fn active<'s, 'a>(sets: &'s [FamilySet<'a>], filters: &FontFilters) -> Vec<&'s FamilySet<'a>> {
sets.iter().filter(|set| set.enabled && filters.sets.iter().any(|key| key == set.key)).collect()
}
/// How the interface language folds and orders text.
@@ -339,16 +364,26 @@ pub(super) fn list(catalog: &Arc<Catalog>, infos: &Infos, listing: &Listing<'_>,
r.class == Some(class)
});
}
if let Some(script) = filters.script {
rows.retain(|r| infos.traits(catalog, &r.family).is_some_and(|t| t.scripts.contains(&script)));
}
let on = active(listing.sets, filters);
for set in &on {
rows.retain(|r| set.position(&r.family).is_some());
}
// The first set that is on and ordered gives the order; the others only filter.
if let Some(set) = on.iter().find(|set| set.ordered) {
rows.sort_by_cached_key(|r| set.position(&r.family));
}
let mut comparable = true;
// P3(type-w2): ty.X7
if let Some(current) = filters.similar.as_deref() {
let reference = infos.traits(catalog, current).filter(|t| t.class.is_some() || t.panose.iter().any(|d| *d > 1));
if let Some(reference_family) = filters.similar.as_deref() {
let reference = infos.traits(catalog, reference_family).filter(|t| t.class.is_some() || t.panose.iter().any(|d| *d > 1));
if let Some(reference) = reference {
let mut scored: Vec<(f32, FamilyRow)> = rows
.drain(..)
.filter_map(|r| {
let traits = infos.traits(catalog, &r.family)?;
let distance = if r.family == current { -1.0 } else { reference.difference(&traits) };
let distance = if r.family == reference_family { -1.0 } else { reference.difference(&traits) };
Some((distance, r))
})
.collect();
@@ -358,9 +393,10 @@ pub(super) fn list(catalog: &Arc<Catalog>, infos: &Infos, listing: &Listing<'_>,
comparable = false;
}
}
let narrowing = !on.is_empty() || (FontFilters { sets: Vec::new(), ..filters.clone() }).any();
if narrowed
&& matcher.is_empty()
&& !filters.any()
&& !narrowing
&& let Some(settings) = settings
{
let recent: Vec<FamilyRow> = settings
+161 -22
View File
@@ -8,7 +8,7 @@ use std::sync::Arc;
use craft_behavior::{DisplayOrder, IconId, ItemSource, Preview, Selection};
use craft_font_catalog::Catalog;
use craft_ui::buttons::{Button, ToggleButton};
use craft_ui::buttons::{Button, IconButton, ToggleButton};
use craft_ui::choice::{Radio, RadioGroup};
use craft_ui::contract::overlay::Dismiss;
use craft_ui::contract::{
@@ -20,12 +20,13 @@ 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::runtime::env::Label;
use egui::Rect;
use craft_ui::runtime::memory::StageAccess;
use egui::{Color32, Rect};
use super::rank::{Infos, Language, Listing, list, shown_name};
use super::{
FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos, read, ui_language,
write,
FamilyRow, FamilySet, FilterLayout, FontClass, FontFilters, FontFormat, FontPicker, FontPickerSettings, FontPickerWords, FontPreviewSize,
FontScript, POPUP, SIMILAR, STAR, Typing, infos, read, ui_language, write,
};
use crate::panel::faces::{Owner, Shown, paint_sample, shown};
use craft_ui::style::DataColor;
@@ -199,7 +200,6 @@ fn filter_bar(ui: &mut egui::Ui, filters: &mut FontFilters, hide_classes: &mut b
ToggleButton::new(words.variable.clone(), Bind::bound(&mut filters.variable)).icon(IconId::new("font_variable")).icon_only().show(ui);
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);
// P3(type-w2): ty.X7
let mut similar = filters.similar.is_some();
ToggleButton::new(words.similar.clone(), Bind::bound(&mut similar)).icon(IconId::new("font_similar")).icon_only().show(ui);
if similar != filters.similar.is_some() {
@@ -226,24 +226,136 @@ fn class_column(ui: &mut egui::Ui, filters: &mut FontFilters, words: &FontPicker
filters.class = usize::from(chosen).checked_sub(1).and_then(|i| FontClass::ALL.get(i).copied());
}
/// The sizes the preview size row offers; the three largest sizes share the largest thumbnail.
const PREVIEW_SIZES: [FontPreviewSize; 3] = [FontPreviewSize::Small, FontPreviewSize::Medium, FontPreviewSize::Large];
fn script_label(script: FontScript, words: &FontPickerWords) -> Label {
match script {
FontScript::Latin => words.script_latin.clone(),
FontScript::Japanese => words.script_japanese.clone(),
FontScript::Thai => words.script_thai.clone(),
}
}
/// A chip of an exclusive choice: on while `slot` holds `value`. A click sets `value`, or `off` when it was on.
fn choice_chip<T: PartialEq>(ui: &mut egui::Ui, label: Label, slot: &mut T, value: T, off: T) {
let held = *slot == value;
let mut on = held;
ToggleButton::new(label, Bind::bound(&mut on)).show(ui);
if on != held {
*slot = if on { value } else { off };
}
}
/// The chip of a host set: on while its key is in `keys` and the set is enabled.
fn set_chip(ui: &mut egui::Ui, set: &FamilySet<'_>, keys: &mut Vec<String>) {
let held = set.enabled && keys.iter().any(|key| key == set.key);
let mut on = held;
ToggleButton::new(set.label.clone(), Bind::bound(&mut on)).enabled(set.enabled).show(ui);
if on != held {
keys.retain(|key| key != set.key);
if on {
keys.push(set.key.to_owned());
}
}
}
/// The `Chips` filter area: the script row; Favorites, the host sets, Any Kind and the classes; Font Technology and
/// Variable; the similar chip while Show Similar Fonts is on; and the Font Preview Size row while samples show.
fn filter_chips(
ui: &mut egui::Ui,
filters: &mut FontFilters,
preview: &mut Option<FontPreviewSize>,
sets: &[FamilySet<'_>],
scripts: &[FontScript],
words: &FontPickerWords,
) {
Stack::new().show(ui, |ui, _| {
if !scripts.is_empty() {
Row::new().wrap(true).show(ui, |ui, _| {
choice_chip(ui, words.all_scripts.clone(), &mut filters.script, None, None);
for script in scripts {
choice_chip(ui, script_label(*script, words), &mut filters.script, Some(*script), None);
}
});
}
Row::new().wrap(true).show(ui, |ui, _| {
ToggleButton::new(words.favorites.clone(), Bind::bound(&mut filters.favorites)).show(ui);
for set in sets {
set_chip(ui, set, &mut filters.sets);
}
choice_chip(ui, words.any_kind.clone(), &mut filters.class, None, None);
for class in FontClass::ALL {
choice_chip(ui, class_label(class, words), &mut filters.class, Some(class), None);
}
});
for hint in sets.iter().filter(|set| !set.enabled).filter_map(|set| set.hint.as_ref()) {
Text::new(hint.clone()).show(ui);
}
Row::new().wrap(true).show(ui, |ui, _| {
Text::new(words.font_technology.clone()).show(ui);
ToggleButton::new(words.variable.clone(), Bind::bound(&mut filters.variable)).show(ui);
});
if let Some(reference) = filters.similar.clone() {
Row::new().show(ui, |ui, _| {
Text::new(Label::from(words.similar_to.fill(&[("family", reference.as_str())]))).show(ui);
let clear = IconButton::new(IconId::new("close")).label(words.clear_similar.clone()).show(ui);
if clicked(&clear) {
filters.similar = None;
}
});
}
if let Some(size) = preview.as_mut().filter(|size| **size != FontPreviewSize::None) {
let last = PREVIEW_SIZES.len() as u8 - 1;
let before = PREVIEW_SIZES.iter().position(|s| s == size).map_or(last, |at| at as u8);
let mut chosen = before;
Text::new(words.preview_size.clone()).show(ui);
RadioGroup::new(words.preview_size.clone(), Bind::bound(&mut chosen)).show(ui, |ui, _| {
Row::new().wrap(true).show(ui, |ui, _| {
for (at, label) in [&words.preview_small, &words.preview_medium, &words.preview_large].into_iter().enumerate() {
Radio::new(at as u8).label(label.clone()).show(ui);
}
});
});
if chosen != before
&& let Some(next) = PREVIEW_SIZES.get(usize::from(chosen))
{
*size = *next;
}
}
});
}
/// 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 Infos, family: &'a str, text: String) -> impl Fn(&ContentPainterCx<'_>, Rect) + 'a {
/// text, and nothing until the face is loaded. `on_white` paints black type on a white paper fill, in every theme.
fn face_thumb<'a>(
catalog: &'a Arc<Catalog>,
infos: &'a Infos,
family: &'a str,
text: String,
on_white: bool,
) -> impl Fn(&ContentPainterCx<'_>, Rect) + 'a {
move |cx, rect| {
let Some(info) = infos.families.get(family) else { return };
if text.is_empty() {
return;
}
let ink = if on_white {
cx.painter.rect_filled(rect, 0.0, Color32::WHITE);
DataColor::new(Color32::BLACK)
} else {
DataColor::new(cx.ink())
};
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);
}
}
}
/// 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: &Infos, 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()))
fn banner(ui: &mut egui::Ui, catalog: &Arc<Catalog>, infos: &Infos, family: &str, shown_name: &str, text: &str, on_white: bool) {
let aspect = ThumbAspect::new(BANNER_ASPECT.0, BANNER_ASPECT.1);
Picture::painter(shown_name.to_owned(), aspect, face_thumb(catalog, infos, family, text.to_owned(), on_white))
.extent(PictureSize::Thumb(ThumbSize::Large))
.show(ui);
}
@@ -273,10 +385,12 @@ fn rest<'a>(picker: &mut FontPicker<'a>, cx: &mut Cx<'_, FontPicker<'a>>, family
/// Shows `family` as the live preview, led by the pointer or by the keys; the pass reports it when the family changes.
fn show_preview<'a>(picker: &mut FontPicker<'a>, cx: &mut Cx<'_, FontPicker<'a>>, family: String, by_pointer: bool) {
let (ctx, owner) = (cx.stage().ctx().clone(), cx.base());
let typing = cx.memory::<Typing>();
typing.lead_by_pointer = by_pointer;
if typing.lead.as_ref() != Some(&family) {
typing.lead = Some(family.clone());
typing.watch.arm(&ctx, owner);
picker.preview = Preview::Shows(family);
}
}
@@ -285,6 +399,7 @@ fn show_preview<'a>(picker: &mut FontPicker<'a>, cx: &mut Cx<'_, FontPicker<'a>>
pub(super) fn end_preview<'a>(picker: &mut FontPicker<'a>, cx: &mut Cx<'_, FontPicker<'a>>) {
let typing = cx.memory::<Typing>();
typing.lead_by_pointer = false;
typing.watch.disarm();
if typing.lead.take().is_some() {
picker.preview = Preview::Ended;
}
@@ -305,12 +420,16 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
let settings = read(&mut picker.settings, cx);
let mut filters = read(&mut picker.filters, cx);
let has_filters = filters.is_some();
let chips = picker.filter_layout == FilterLayout::Chips;
let on_white = settings.as_ref().is_some_and(|s| s.samples_on_white);
let mut preview_size = settings.as_ref().map(|s| s.preview);
let (sets, scripts) = (picker.sets, picker.scripts);
let narrowing = filters.clone().unwrap_or_default();
let catalog = picker.catalog;
let infos = infos(catalog);
let language_code = ui_language(&cx.env);
let (folder, collator) = (cx.env.folder(), cx.env.collator());
let listing = Listing { query: &query, settings: settings.as_ref(), filters: &narrowing, language: &language_code, served: picker.served };
let listing = Listing { query: &query, settings: settings.as_ref(), filters: &narrowing, language: &language_code, served: picker.served, sets };
let (found, comparable) = list(catalog, &infos, &listing, &Language { folder: &folder, collator: &collator }, true);
let slots = slots(catalog, found, &expanded);
let current = slots.iter().position(|slot| matches!(slot, Slot::Family { row, .. } if row.family == family));
@@ -318,8 +437,8 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
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();
// P3(type-w2): ty.X7
(&query, narrowing.class, narrowing.favorites, narrowing.variable, &narrowing.similar).hash(&mut stamp);
(&query, narrowing.class, narrowing.favorites, narrowing.variable, &narrowing.similar, narrowing.script, &narrowing.sets, on_white, chips)
.hash(&mut stamp);
let banner_family = lead.unwrap_or_else(|| family.clone());
let banner_text = picker.preview_text;
let name = words.list.clone();
@@ -331,13 +450,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);
banner(ui, catalog, &infos, &banner_family, &shown_name, text, on_white);
}
if let Some(filters) = filters.as_mut() {
filter_bar(ui, filters, &mut hide_classes, &family, &words);
if chips {
filter_chips(ui, filters, &mut preview_size, sets, scripts, &words);
} else {
filter_bar(ui, filters, &mut hide_classes, &family, &words);
}
}
Row::new().show(ui, |ui, _| {
if let (Some(filters), false) = (filters.as_mut(), hide_classes) {
if let (Some(filters), false, false) = (filters.as_mut(), hide_classes, chips) {
class_column(ui, filters, &words);
}
Stack::new().show(ui, |ui, _| {
@@ -369,8 +492,13 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
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)).trailing_part(STAR, star, name);
let mut line = ListRow::new(row.shown.clone()).option().depth(0).check(current == Some(item.at));
if chips && has_filters {
let similar = TrailingFace::Icon(IconSpec::svg(IconId::new("font_similar")));
let similar_name = Label::from(words.show_similar.fill(&[("row", row.shown.as_str())]));
line = line.trailing_part(SIMILAR, similar, similar_name);
}
line = line.trailing_part(STAR, star, name);
if source.has_children(item.at) {
line = line.group(*open);
}
@@ -387,9 +515,9 @@ 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.thumb_aspect(size, aspect, face_thumb(catalog, &infos, &row.family, samples.latin, on_white));
match samples.arabic {
Some(arabic) => line.extra_thumb(face_thumb(catalog, &infos, &row.family, arabic)),
Some(arabic) => line.extra_thumb(face_thumb(catalog, &infos, &row.family, arabic, on_white)),
None => line,
}
}
@@ -426,6 +554,11 @@ 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 == SIMILAR => {
if let (Some(filters), Some(Slot::Family { row, .. })) = (filters.as_mut(), slot_of(&slots, &key)) {
filters.similar = Some(row.family.clone());
}
}
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));
@@ -450,11 +583,17 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
{
show_preview(picker, cx, family, true);
}
if let Some(mut changed) = settings.clone().filter(|_| !stars.is_empty()) {
if let Some(mut changed) = settings.clone() {
for (family, on) in &stars {
changed.set_favorite(family, *on);
}
write(&mut picker.settings, cx, changed, "Favorite font");
if let Some(size) = preview_size {
changed.preview = size;
}
if Some(&changed) != settings.as_ref() {
let label = if stars.is_empty() { "Font preview size" } else { "Favorite font" };
write(&mut picker.settings, cx, changed, label);
}
}
if has_filters
&& filters != Some(narrowing)
+34 -4
View File
@@ -10,7 +10,7 @@ use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use egui::{Key, Modifiers, Ui};
use super::{FontFilters, FontPicker, FontPickerSettings};
use super::{FamilySet, FilterLayout, FontFilters, FontPicker, FontPickerSettings, FontScript};
use crate::Catalog;
use crate::craft_font_catalog::{Limits, Source};
use crate::panel::fixtures::story_catalog;
@@ -55,6 +55,9 @@ fn styled_catalog() -> Arc<Catalog> {
struct Extras<'a> {
served: &'a [String],
banner: Option<&'a str>,
sets: &'a [FamilySet<'a>],
scripts: &'a [FontScript],
layout: FilterLayout,
}
fn show_with(ui: &mut Ui, data: &mut StoryData, init: Demo, catalog: &Arc<Catalog>, extras: &Extras<'_>) -> StoryOutput {
@@ -62,7 +65,10 @@ fn show_with(ui: &mut Ui, data: &mut StoryData, init: Demo, catalog: &Arc<Catalo
let mut picker = FontPicker::new("Font family", Bind::bound(family), catalog)
.settings(Bind::bound(settings))
.filters(Bind::bound(filters))
.served(extras.served);
.served(extras.served)
.sets(extras.sets)
.scripts(extras.scripts)
.filter_layout(extras.layout);
if let Some(text) = extras.banner {
picker = picker.preview_text(text);
}
@@ -123,13 +129,13 @@ fn font_picker_expanded_styles(ui: &mut Ui, data: &mut StoryData) -> StoryOutput
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
fn font_picker_served(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let served = ["Gotham".to_owned(), "Proxima Nova".to_owned()];
show_with(ui, data, demo("Hack", FontPickerSettings::default(), FontFilters::default()), &catalog(), &Extras { served: &served, banner: None })
show_with(ui, data, demo("Hack", FontPickerSettings::default(), FontFilters::default()), &catalog(), &Extras { served: &served, ..Extras::default() })
}
/// The preview banner above the filters.
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
fn font_picker_banner_text(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let extras = Extras { served: &[], banner: Some("The quick brown fox") };
let extras = Extras { banner: Some("The quick brown fox"), ..Extras::default() };
show_with(ui, data, demo("Ubuntu", FontPickerSettings::default(), FontFilters::default()), &catalog(), &extras)
}
@@ -140,6 +146,30 @@ fn font_picker_arabic_sample(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show_with(ui, data, demo("Inter", settings, FontFilters::default()), &styled_catalog(), &Extras::default())
}
/// The `Chips` filter area: the script row, a host set that is on and one that is disabled with its reason, the
/// classes, Variable and the preview size row.
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
fn font_picker_filter_chips(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let document = ["ubuntu".to_owned(), "hack".to_owned()];
let added: [String; 0] = [];
let sets = [
FamilySet::new("document", "Document", &document),
FamilySet::new("added", "Recently Added", &added).ordered().enabled(false).hint("No fonts were added recently"),
];
let scripts = [FontScript::Latin, FontScript::Japanese, FontScript::Thai];
let filters = FontFilters { sets: vec!["document".to_owned()], ..FontFilters::default() };
let extras = Extras { sets: &sets, scripts: &scripts, layout: FilterLayout::Chips, ..Extras::default() };
show_with(ui, data, demo("Hack", FontPickerSettings::default(), filters), &catalog(), &extras)
}
/// The "≈ family ✕" chip while Show Similar Fonts is on, and the Show Similar part on each row.
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
fn font_picker_filter_chips_similar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let filters = FontFilters { similar: Some("Inter".to_owned()), ..FontFilters::default() };
let extras = Extras { layout: FilterLayout::Chips, ..Extras::default() };
show_with(ui, data, demo("Inter", FontPickerSettings::default(), filters), &styled_catalog(), &extras)
}
/// The family of a selection whose members differ.
#[story(FontPicker<'static>, covers = [Mixed], drive = Drive::Never)]
fn font_picker_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
+153 -11
View File
@@ -1,18 +1,21 @@
//! The font picker's flows: style rows under an expanded family, served families and the rested report, and similar
//! fonts.
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use craft_behavior::Preview;
use craft_behavior::{GESTURE_GAP, Preview};
use craft_font_manager::craft_font_catalog::{Limits, Os, Source};
use craft_font_manager::picker::{FontFilters, FontPicker, FontPickerSettings, SIMILAR_COUNT, family_rows};
use craft_font_manager::picker::{FamilySet, FontFilters, FontPicker, FontPickerSettings, FontScript, SIMILAR_COUNT, family_rows};
use craft_font_manager::{Catalog, FontEnv};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::runtime::frame::take_output;
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::pointer::{moved, wheel_lines};
use craft_ui::testing::{Fixture, Room, trial};
use egui::{Event, Key, Modifiers};
use craft_theme::{Contrast, Mode};
use egui::{Color32, Event, Key, Modifiers, Shape};
const INTER_REGULAR: &[u8] = include_bytes!("../../../ui-contract/fonts/inter/Inter-Regular.ttf");
const INTER_SEMIBOLD: &[u8] = include_bytes!("../../../ui-contract/fonts/inter/Inter-SemiBold.ttf");
@@ -36,13 +39,22 @@ struct Seen {
}
fn rig(catalog: Arc<Catalog>, served: Vec<String>) -> (Fixture, Rc<RefCell<Seen>>) {
rig_with(catalog, served, FontPickerSettings::default(), None)
}
/// A rig whose picker keeps `settings` and, when given, `filters`.
fn rig_with(catalog: Arc<Catalog>, served: Vec<String>, settings: FontPickerSettings, filters: Option<FontFilters>) -> (Fixture, Rc<RefCell<Seen>>) {
let seen = Rc::new(RefCell::new(Seen::default()));
let shown = Rc::clone(&seen);
let mut settings = FontPickerSettings::default();
let (mut settings, mut filters) = (settings, filters);
let mut fx = Fixture::new(move |ui| {
let mut seen = shown.borrow_mut();
let out =
FontPicker::new("Font family", Bind::bound(&mut seen.family), &catalog).settings(Bind::bound(&mut settings)).served(&served).show(ui);
let mut picker =
FontPicker::new("Font family", Bind::bound(&mut seen.family), &catalog).settings(Bind::bound(&mut settings)).served(&served);
if let Some(filters) = filters.as_mut() {
picker = picker.filters(Bind::bound(filters));
}
let out = picker.show(ui);
match out.preview {
Preview::Shows(family) => seen.preview = Some(family),
Preview::Ended => seen.preview = None,
@@ -111,16 +123,16 @@ fn a_served_family_lists_without_a_sample_and_is_reported_rested_once() {
}
#[trial]
fn similar_fonts_put_the_current_family_first_and_leave_the_list_alone_without_a_reference() {
fn similar_fonts_put_the_reference_family_first_and_leave_the_list_alone_without_a_reference() {
let catalog = catalog_of(&[epaint_default_fonts::HACK_REGULAR, epaint_default_fonts::UBUNTU_LIGHT, INTER_REGULAR]);
let mut similar = FontFilters::default();
similar.similar = Some("Inter".to_owned()); // P3(type-w2): ty.X7
similar.similar = Some("Inter".to_owned());
let rows = family_rows(&catalog, "", None, &similar, &[], "en");
let names: Vec<&str> = rows.iter().map(|row| row.family.as_str()).collect();
assert_eq!(names.first(), Some(&"Inter"), "the current family first, though it is not first by name");
assert_eq!(names.first(), Some(&"Inter"), "the reference family first, though it is not first by name");
assert!(rows.len() <= SIMILAR_COUNT);
// A current family the catalog lacks has no traits: the list stays as unfiltered.
// A reference family the catalog lacks has no traits: the list stays as unfiltered.
let unfiltered = family_rows(&catalog, "", None, &FontFilters::default(), &[], "en");
similar.similar = Some("Missing".to_owned());
assert_eq!(family_rows(&catalog, "", None, &similar, &[], "en"), unfiltered);
@@ -187,3 +199,133 @@ fn a_click_on_the_focused_closed_field_selects_the_name_so_typing_replaces_it()
assert_eq!(seen.borrow().picks.last().map(|(picked, _)| picked.as_str()), Some(family), "the typed name is picked");
}
}
fn three_faces() -> Arc<Catalog> {
catalog_of(&[epaint_default_fonts::HACK_REGULAR, epaint_default_fonts::UBUNTU_LIGHT, INTER_REGULAR])
}
/// The families of `catalog` in list order under `filters` and `sets`.
fn listed(catalog: &Arc<Catalog>, filters: &FontFilters, sets: &[FamilySet<'_>]) -> Vec<String> {
family_rows(catalog, "", None, filters, sets, "en").into_iter().map(|row| row.family).collect()
}
/// Focuses the field and rests the pointer on it, so the wheel turns over the closed field.
fn aim_at_field(fx: &mut Fixture) {
let field = fx.by_label("Font family").expect("the family field");
fx.key(Key::Tab, Modifiers::NONE);
fx.frame(vec![moved(field.center())]);
}
#[trial]
fn the_closed_fields_wheel_steps_one_family_per_line_through_the_filtered_order_and_commits_one_gesture() {
let all = listed(&three_faces(), &FontFilters::default(), &[]);
assert_eq!(all.len(), 3);
let (mut fx, seen) = rig(three_faces(), vec![]);
seen.borrow_mut().family = all[0].clone();
aim_at_field(&mut fx);
fx.frame(vec![wheel_lines(-1.0), wheel_lines(1.0)]);
fx.advance(GESTURE_GAP * 2.0).idle(3);
assert_eq!(seen.borrow().family, all[0], "opposite notches in one pass step nothing");
assert!(seen.borrow().picks.is_empty());
fx.frame(vec![wheel_lines(-2.0)]);
assert_eq!(seen.borrow().family, all[2], "two lines step two families");
assert!(seen.borrow().picks.is_empty(), "nothing is picked while the wheel turns");
fx.advance(GESTURE_GAP * 2.0).idle(3);
assert_eq!(seen.borrow().picks, [(all[2].clone(), None)], "the run's end picks once");
let settings = FontPickerSettings { favorites: vec![all[0].clone(), all[2].clone()], ..FontPickerSettings::default() };
let mut favorites = FontFilters::default();
favorites.favorites = true;
let (mut fx, seen) = rig_with(three_faces(), vec![], settings, Some(favorites));
seen.borrow_mut().family = all[0].clone();
aim_at_field(&mut fx);
fx.frame(vec![wheel_lines(-1.0)]);
assert_eq!(seen.borrow().family, all[2], "a line steps over the family the favorites filter hides");
fx.advance(GESTURE_GAP * 2.0).idle(3);
assert_eq!(seen.borrow().picks, [(all[2].clone(), None)]);
}
#[trial]
fn a_script_filter_keeps_only_the_families_whose_face_covers_the_script() {
let catalog = three_faces();
let unfiltered = listed(&catalog, &FontFilters::default(), &[]);
let with = |script: FontScript| {
let mut filters = FontFilters::default();
filters.script = Some(script);
listed(&catalog, &filters, &[])
};
assert_eq!(with(FontScript::Latin), unfiltered, "every shipped face covers Latin");
assert!(with(FontScript::Thai).is_empty(), "none covers Thai");
assert!(with(FontScript::Japanese).is_empty(), "none covers Japanese");
}
#[trial]
fn a_host_set_keeps_only_its_families_and_an_ordered_one_lists_them_in_its_order() {
let catalog = three_faces();
let all = listed(&catalog, &FontFilters::default(), &[]);
// The host keeps canonical lowercase names.
let members = vec![all[2].to_ascii_lowercase(), all[0].to_ascii_lowercase()];
let mut on = FontFilters::default();
on.sets = vec!["document".to_owned()];
let plain = [FamilySet::new("document", "Document", &members)];
assert_eq!(listed(&catalog, &on, &plain), [all[0].clone(), all[2].clone()], "its families, in the name order");
let ordered = [FamilySet::new("document", "Document", &members).ordered()];
assert_eq!(listed(&catalog, &on, &ordered), [all[2].clone(), all[0].clone()], "its families, in its own order");
let disabled = [FamilySet::new("document", "Document", &members).ordered().enabled(false)];
assert_eq!(listed(&catalog, &on, &disabled), all, "a disabled set's key filters nothing");
assert_eq!(listed(&catalog, &on, &[]), all, "a key naming no set filters nothing");
}
#[trial]
fn a_picker_that_stops_showing_with_a_preview_is_reported_once_in_ended_previews() {
let catalog = catalog_of(&[INTER_REGULAR, epaint_default_fonts::HACK_REGULAR]);
let shown = Rc::new(Cell::new(true));
let id = Rc::new(Cell::new(None));
let (visible, at) = (Rc::clone(&shown), Rc::clone(&id));
let mut family = String::new();
let mut fx = Fixture::new(move |ui| {
if visible.get() {
let out = FontPicker::new("Font family", Bind::bound(&mut family), &catalog).show(ui);
at.set(Some(out.edit.response.id));
}
});
fx.in_room(Room::Window);
fx.settle();
let hover_hack = |fx: &mut Fixture| {
open(fx);
let hack = fx.by_label("Hack").expect("the Hack row");
fx.frame(vec![Event::PointerMoved(hack.center())]);
fx.settle();
};
hover_hack(&mut fx);
fx.key(Key::Escape, Modifiers::NONE);
fx.settle();
assert!(take_output(fx.ctx()).ended_previews.is_empty(), "a picker that ended its own preview names none");
hover_hack(&mut fx);
shown.set(false);
fx.settle();
fx.idle(3);
let ended = take_output(fx.ctx()).ended_previews;
assert_eq!(ended.iter().filter(|ended| Some(**ended) == id.get()).count(), 1, "the picker that stopped showing is named once: {ended:?}");
}
#[trial]
fn samples_on_white_paint_dark_ink_on_a_lighter_paper_in_a_dark_theme() {
let white_papers = |on_white: bool| {
let settings = FontPickerSettings { samples_on_white: on_white, ..FontPickerSettings::default() };
let (mut fx, _) = rig_with(three_faces(), vec![], settings, None);
fx.theme(Mode::Dark, Contrast::Standard);
fx.settle();
open(&mut fx);
fx.frame_shapes().into_iter().filter(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == Color32::WHITE)).count()
};
assert!(white_papers(true) >= 3, "each family's sample sits on a white paper, in a dark theme");
assert_eq!(white_papers(false), 0, "without the setting no sample paper is white");
}