Merge pull request #8227 from dotCooCoo/feat/font-menu-recently-added

Font menu: a Recently Added filter lists the families installed in the last 30 days, newest first
This commit is contained in:
BFlat
2026-11-17 09:49:44 +07:00
committed by GitHub
40 changed files with 948 additions and 40 deletions
+4
View File
@@ -17,6 +17,7 @@ use crate::GlyphImage;
use crate::colr::ColourContent;
use vectorcraft_doc::color::Color;
mod added;
mod alternates;
mod build;
mod cache;
@@ -33,6 +34,9 @@ mod stylistic_sets;
mod traits;
mod wanted;
#[cfg(test)]
pub(crate) use added::recently_added_of;
pub use added::{RECENTLY_ADDED_WITHIN, RecentlyAdded};
pub use alternates::GlyphAlternate;
pub(crate) use alternates::listed;
pub use build::style_weight;
+69
View File
@@ -0,0 +1,69 @@
//! Recently added fonts: the installed families with a font file created on this computer in the
//! last 30 days ([`FontDb::recently_added`]).
use std::time::{Duration, SystemTime};
use super::FontDb;
/// How long a family counts as recently added after its newest font file was created: 30 days.
pub const RECENTLY_ADDED_WITHIN: Duration = Duration::from_secs(30 * 24 * 60 * 60);
/// The installed families added recently ([`FontDb::recently_added`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RecentlyAdded {
/// The families by their catalog names, the one with the newest font file first. Families
/// whose newest files were created at the same instant are in name order, case ignored.
pub families: Vec<String>,
/// The list is the same for every time from the one asked for up to this instant, and is to be
/// asked for again from it on: when a listed family's newest file turns
/// [`RECENTLY_ADDED_WITHIN`] old, or when a file dated after the time asked for starts to
/// count. `None`: the list stays as it is until fonts are installed or removed.
pub recheck_at: Option<SystemTime>,
}
impl FontDb {
/// The installed families with a font file created within [`RECENTLY_ADDED_WITHIN`] before
/// `now`, the boundary included, newest first. A family's date is that of its newest font file
/// created at or before `now`. A file without a creation time (the file system keeps none)
/// or dated after `now` does not count, so a family with no other file is left out. The
/// creation time is when the file was made on this computer: copying a font in or installing
/// it makes a new file, while a font kept elsewhere and linked or activated by a font manager
/// is dated by the file the link leads to. Fonts loaded from bytes and the bundled fonts are
/// never listed. Empty on wasm, which has no installed fonts.
pub fn recently_added(&self, now: SystemTime) -> RecentlyAdded {
let catalog = self.read_catalog();
recently_added_of(catalog.values().map(|c| (c.name.as_str(), c.faces.iter().map(|f| f.created))), now)
}
}
/// [`FontDb::recently_added`] of `families`, each a name with the creation times of its faces'
/// files (`None`: unknown).
pub(crate) fn recently_added_of<'a, T>(families: impl IntoIterator<Item = (&'a str, T)>, now: SystemTime) -> RecentlyAdded
where
T: IntoIterator<Item = Option<SystemTime>>,
{
let mut dated: Vec<(SystemTime, &str)> = Vec::new();
let mut recheck_at: Option<SystemTime> = None;
let mut sooner = |t: SystemTime| recheck_at = Some(recheck_at.map_or(t, |r| r.min(t)));
for (name, times) in families {
let mut newest: Option<SystemTime> = None;
for t in times.into_iter().flatten() {
if t > now {
sooner(t);
} else if newest.is_none_or(|n| t > n) {
newest = Some(t);
}
}
let Some(newest) = newest else { continue };
match newest.checked_add(RECENTLY_ADDED_WITHIN) {
Some(leaves) if leaves < now => {}
Some(leaves) => {
sooner(leaves);
dated.push((newest, name));
}
None => dated.push((newest, name)),
}
}
dated.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.to_lowercase().cmp(&b.1.to_lowercase())).then_with(|| a.1.cmp(b.1)));
RecentlyAdded { families: dated.into_iter().map(|(_, name)| name.to_string()).collect(), recheck_at }
}
+3
View File
@@ -24,6 +24,9 @@ pub(super) struct CatalogFace {
/// Weight and italic as the style lists them (by its name, or a named instance's axes).
pub(super) weight: f32,
pub(super) italic: bool,
/// When the file was created ([`FontDb::recently_added`]); `None` when the file system keeps
/// no creation time.
pub(super) created: Option<std::time::SystemTime>,
}
/// The installed fonts by ASCII-lowercased family name (lookups ignore ASCII case, as
+3 -1
View File
@@ -419,6 +419,8 @@ impl FontDb {
if !named && !is_font_file(&p) && !crate::suitcase::is_suitcase(&p) {
continue;
}
// The file's creation time, once for all its faces (a collection holds several).
let created = std::fs::metadata(&p).and_then(|m| m.created()).ok();
for FaceStyle { family, native_family, style, keys, weight, italic, traits, .. } in file_face_names(&p) {
for (k, a) in Alias::of(&family, &style, &keys) {
aliases.entry(k).or_default().push(a);
@@ -440,7 +442,7 @@ impl FontDb {
entry.native = native_family;
}
let (weight, italic) = (weight.unwrap_or_else(|| style_weight(&style)), italic || style_italic(&style));
entry.faces.push(CatalogFace { style, path: p.clone(), weight, italic });
entry.faces.push(CatalogFace { style, path: p.clone(), weight, italic, created });
n += 1;
}
}
+3 -3
View File
@@ -42,9 +42,9 @@ pub use features::{
};
pub use fontdb::{
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphCategory,
GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind,
WantedFont, WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs,
set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs,
GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded,
StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir,
set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs,
};
pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions};
pub use layout::{envelope_ink, layout_inputs, register_envelope_ink};
+1
View File
@@ -26,6 +26,7 @@ mod kept_layouts;
mod kerning_before;
mod ligature_carets;
mod path_joins;
mod recently_added;
mod ruby;
mod scripts;
mod shape_plans;
+77
View File
@@ -0,0 +1,77 @@
//! Recently added fonts ([`FontDb::recently_added`]): which installed families count, in which
//! order, and until when, at a time the tests choose.
use std::time::{Duration, SystemTime};
use crate::fontdb::recently_added_of;
use crate::*;
const DAY: Duration = Duration::from_secs(24 * 60 * 60);
/// A fixed instant the tests count from.
fn now() -> SystemTime {
SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000)
}
/// `days` days (and `secs` seconds) before [`now`].
fn ago(days: u32, secs: u64) -> Option<SystemTime> {
now().checked_sub(DAY * days + Duration::from_secs(secs))
}
/// [`recently_added_of`] for families with these creation times, at `at`.
fn added(families: &[(&str, &[Option<SystemTime>])], at: SystemTime) -> RecentlyAdded {
recently_added_of(families.iter().map(|(name, times)| (*name, times.iter().copied())), at)
}
/// A family counts for 30 days after its newest file was created, the 30th day's last instant
/// included; the newest comes first.
#[test]
fn families_added_in_the_last_30_days_are_listed_newest_first() {
let families: &[(&str, &[Option<SystemTime>])] =
&[("Older", &[ago(29, 0)]), ("Boundary", &[ago(30, 0)]), ("Expired", &[ago(30, 1)]), ("Newest", &[ago(0, 5)]), ("Middle", &[ago(3, 0)])];
let list = added(families, now());
assert_eq!(list.families, ["Newest", "Middle", "Older", "Boundary"]);
assert_eq!(list.recheck_at, Some(now()), "Boundary leaves after this instant");
// A day and a second later, the two oldest have left, without the files changing.
let later = added(families, now() + DAY + Duration::from_secs(1));
assert_eq!(later.families, ["Newest", "Middle"]);
assert_eq!(later.recheck_at, ago(3, 0).map(|t| t + RECENTLY_ADDED_WITHIN));
}
/// A family is dated by its newest file at or before the time asked for. Files without a creation
/// time, or dated after that time, do not count, and a family with no other file is left out until
/// its future-dated file's time comes.
#[test]
fn a_family_is_dated_by_its_newest_valid_file() {
let future = now() + DAY;
let families: &[(&str, &[Option<SystemTime>])] = &[
("Several", &[ago(40, 0), ago(2, 0), None, Some(future)]),
("Unknown", &[None, None]),
("Future", &[Some(future)]),
("Old", &[ago(31, 0)]),
("One", &[ago(1, 0)]),
];
let list = added(families, now());
assert_eq!(list.families, ["One", "Several"]);
assert_eq!(list.recheck_at, Some(future), "the future-dated files count from their time on");
assert_eq!(added(families, future).families, ["Future", "Several", "One"]);
assert!(added(&[("Unknown", &[None])], now()).recheck_at.is_none());
}
/// Families added at the same instant are in name order, case ignored, whatever order the
/// catalog gives them in.
#[test]
fn families_added_at_the_same_instant_are_in_name_order() {
let t = ago(1, 0);
let families: &[(&str, &[Option<SystemTime>])] = &[("delta", &[t]), ("Bravo", &[t]), ("alpha", &[t]), ("Charlie", &[t])];
assert_eq!(added(families, now()).families, ["alpha", "Bravo", "Charlie", "delta"]);
let reversed: Vec<_> = families.iter().rev().copied().collect();
assert_eq!(added(&reversed, now()).families, ["alpha", "Bravo", "Charlie", "delta"]);
}
/// Nothing installed, or nothing dated: an empty list with nothing to recheck.
#[test]
fn no_dated_families_list_nothing() {
assert_eq!(added(&[], now()), RecentlyAdded::default());
assert_eq!(FontDb::with_font_dirs(vec![]).recently_added(now()), RecentlyAdded::default(), "the bundled fonts are not installed fonts");
}
+24
View File
@@ -298,6 +298,30 @@ fn rescanning_drops_loaded_fonts_removed_since() {
assert_eq!(db.outline(&again, glyph).elements(), db.outline(&face, glyph).elements());
}
/// The scan dates each installed family by its font files' creation times: a family installed
/// just now is recently added for 30 days, and leaves the list when its files are removed and the
/// folders scanned again. Where the file system keeps no creation time, nothing is listed.
#[test]
fn installed_fonts_are_recently_added_by_their_files_creation_time() {
let dir = font_dir("recently-added");
let regular = dir.join("Sysfont-Regular.ttf");
let created = std::fs::metadata(&regular).and_then(|m| m.created()).ok();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
let now = std::time::SystemTime::now();
let list = db.recently_added(now);
let Some(created) = created else {
assert_eq!(list, RecentlyAdded::default(), "no creation times: nothing is dated");
return;
};
assert_eq!(list.families, [FAMILY]);
assert!(list.recheck_at.is_some_and(|t| t >= created + RECENTLY_ADDED_WITHIN), "{list:?}");
assert!(db.recently_added(now + RECENTLY_ADDED_WITHIN + std::time::Duration::from_secs(60)).families.is_empty(), "31 days on");
std::fs::remove_file(&regular).unwrap();
std::fs::remove_file(dir.join("Sub/Sysfont-Bold.TTF")).unwrap();
assert_eq!(db.load_system_fonts(), 0);
assert_eq!(db.recently_added(now), RecentlyAdded::default(), "removed fonts leave the list");
}
#[test]
fn a_background_scan_serves_the_first_lookup() {
let dir = font_dir("background");
+305 -29
View File
@@ -4,13 +4,17 @@
//! or reached with ↑/↓ previews its font on the selected text (one live interaction, nothing in
//! the history); a click or Enter applies it as one step, Escape or closing the menu puts the text
//! back. The Glyphs panel and Find Font only pick a font ([`picked`]): nothing is previewed on the
//! document. A star marks a favourite family, and the ★ filter lists only those. The ≈ button
//! before a family's star (Show Similar Fonts) orders the listed families by how alike they look to
//! it ([`vectorcraft_text::FontDb::similar_families`]), that family first and without the Recent
//! document. A star marks a favourite family, and the ★ filter lists only those. The Document
//! filter lists only the families that type in the current document is set in
//! ([`document_families`]), and is unavailable while no document is open. The Recently Added
//! filter lists only the installed families with a font file created in the last 30 days, the
//! newest first and without the Recent Fonts section ([`vectorcraft_text::FontDb::recently_added`]).
//! The ≈ button before a family's star (Show Similar Fonts) orders the listed families by how alike
//! they look to it ([`vectorcraft_text::FontDb::similar_families`]), that family first and without the Recent
//! Fonts section, until the ≈ chip under the filters clears it or the menu closes. The Font
//! Technology filter's Variable lists only variable font families. Preferences › Type › Enable
//! in-menu font previews and Font Preview Size turn the samples off or size the rows. The menu lays
//! out its filters on the same four rows wherever it opens. However narrow its field, it opens at
//! out its filters on the same five rows wherever it opens. However narrow its field, it opens at
//! least wide enough for those rows and for a family name up to 220 points wide with its sample
//! beside it, up to 60% of the window; each sample fills its row's height. Recently used families
//! appear first, in the order they were last applied, within the same search and filters as the
@@ -119,10 +123,49 @@ pub struct MenuLook<'a> {
pub wheel_owner: Option<WheelOwner>,
/// The name screen readers give the closed field when no label stands beside it.
pub name: Option<&'a str>,
/// The current document, which the Document filter lists the families of. `None`: no document
/// is open, and the filter is unavailable.
pub document: Option<MenuDocument<'a>>,
/// The time the Recently Added filter counts back from. `None`: the system clock.
pub clock: Option<std::time::SystemTime>,
}
/// The current document as the Document filter reads it.
#[derive(Clone, Copy, Debug)]
pub struct MenuDocument<'a> {
/// The document's identity.
pub uid: u64,
/// Its content: while an interaction is open (a font previewed from the menu), the content it
/// started from, so a preview does not change the families listed. Its families are listed
/// again when this is another version of the document.
pub doc: &'a Arc<vectorcraft_doc::Document>,
}
impl MenuDocument<'_> {
/// Which document and which version of it the families were read from.
fn key(&self) -> DocumentKey {
DocumentKey { uid: self.uid, doc: Arc::downgrade(self.doc) }
}
}
/// A document and a version of its content, compared by identity. The weak reference keeps the
/// version's allocation, so a later version is never placed at the same address while the key is
/// kept.
#[derive(Clone, Debug)]
struct DocumentKey {
uid: u64,
doc: std::sync::Weak<vectorcraft_doc::Document>,
}
impl PartialEq for DocumentKey {
fn eq(&self, other: &Self) -> bool {
self.uid == other.uid && std::sync::Weak::ptr_eq(&self.doc, &other.doc)
}
}
impl Default for MenuLook<'static> {
/// Samples on in the theme's colors, English names, medium rows, no favorites, no wheel.
/// Samples on in the theme's colors, English names, medium rows, no favorites, no wheel, no
/// document, the system clock.
fn default() -> Self {
Self {
samples: true,
@@ -134,6 +177,8 @@ impl Default for MenuLook<'static> {
wheel: false,
wheel_owner: None,
name: None,
document: None,
clock: None,
}
}
}
@@ -155,6 +200,11 @@ impl<'a> MenuLook<'a> {
wheel: false,
wheel_owner: None,
name: None,
document: app
.session
.active()
.map(|state| MenuDocument { uid: state.uid, doc: state.interaction.as_ref().map_or(&state.doc, |interaction| &interaction.doc) }),
clock: None,
}
}
}
@@ -310,8 +360,52 @@ fn remap_highlight(before: &[Row], selected: Option<usize>, after: &[Row]) -> Op
/// What the rows were listed for: the query, the script, kind, font technology (variable only) and
/// favourites filters, Show Font Names in English, the expanded families, favourites, recent
/// history, font list generation and the family Show Similar Fonts orders by.
type RowsKey = (String, usize, Option<FontClass>, bool, bool, bool, Vec<String>, Vec<String>, Vec<String>, u64, Option<String>);
/// history, font list generation, the family Show Similar Fonts orders by, the document version
/// while the Document filter lists its families, and the recently added families while the
/// Recently Added filter lists them.
type RowsKey = (
String,
usize,
Option<FontClass>,
bool,
bool,
bool,
Vec<String>,
Vec<String>,
Vec<String>,
u64,
Option<String>,
(Option<DocumentKey>, Option<Arc<AddedFonts>>),
);
/// The installed families the Recently Added filter lists: each one's place in the list
/// (lowercase name to place, newest first), and the instant from which they are to be found again
/// ([`vectorcraft_text::RecentlyAdded::recheck_at`]).
#[derive(Debug, Default, PartialEq, Eq)]
struct AddedFonts {
place: HashMap<String, usize>,
recheck_at: Option<std::time::SystemTime>,
}
impl AddedFonts {
fn of(list: &vectorcraft_text::RecentlyAdded) -> Self {
Self { place: list.families.iter().enumerate().map(|(i, f)| (f.to_lowercase(), i)).collect(), recheck_at: list.recheck_at }
}
/// Orders `families` (the listed ones) newest first.
fn order(&self, families: &mut [String]) {
families.sort_by_cached_key(|f| self.place.get(&f.to_lowercase()).copied().unwrap_or(usize::MAX));
}
}
/// The recently added families a [`MenuState`] found, the database and font list generation they
/// were found in ([`vectorcraft_text::FontDb::id`], [`vectorcraft_text::FontDb::generation`]), and
/// the time they were found for.
type RecentlyAddedFonts = ((u64, u64), std::time::SystemTime, Arc<AddedFonts>);
/// The families a [`MenuState`] found in a document (lowercase), and the document version and font
/// list generation they were found for.
type DocumentFonts = ((DocumentKey, u64), Arc<HashSet<String>>);
/// The menu's state between frames.
#[derive(Clone, Default)]
@@ -327,12 +421,21 @@ struct MenuState {
highlight: Option<usize>,
query: String,
/// The filters (kept from one opening to the next, and the same in every font menu:
/// [`Filters`]): script (0..[`SCRIPTS`]), kind, font technology (variable fonts only) and
/// favorites only.
/// [`Filters`]): script (0..[`SCRIPTS`]), kind, font technology (variable fonts only),
/// favorites only, the current document's families only and recently added families only.
script: usize,
class: Option<FontClass>,
variable_only: bool,
favorites_only: bool,
document_only: bool,
added_only: bool,
/// The recently added families the Recently Added filter last listed.
added: Option<RecentlyAddedFonts>,
/// The families of the current document the Document filter last listed.
document_fonts: Option<DocumentFonts>,
/// The Document filter lists nothing because the document's type uses none of the menu's
/// families (none at all, or only missing ones), whatever the other filters.
none_used: bool,
/// Families whose styles are listed (lowercase).
expanded: Vec<String>,
/// Show Similar Fonts: the family the list is ordered by likeness to, until it is cleared or
@@ -352,7 +455,10 @@ struct MenuState {
filters: f32,
/// The families the wheel steps through, listed at its first notch over the closed field and
/// kept for that text selection while the pointer stays on it: each step makes its family a recent one, which would
/// otherwise move it in the order.
/// otherwise move it in the order. The Document filter's families are kept the same way: a
/// step that leaves a family unused keeps it in the order, so turning the wheel back returns
/// to it. They are listed again at the first notch after the pointer leaves the field or the
/// selection changes.
wheel_order: Option<Arc<[String]>>,
wheel_target: Option<WheelTarget>,
}
@@ -366,11 +472,20 @@ struct Filters {
class: Option<FontClass>,
variable_only: bool,
favorites_only: bool,
document_only: bool,
added_only: bool,
}
impl Filters {
fn of(st: &MenuState) -> Self {
Self { script: st.script, class: st.class, variable_only: st.variable_only, favorites_only: st.favorites_only }
Self {
script: st.script,
class: st.class,
variable_only: st.variable_only,
favorites_only: st.favorites_only,
document_only: st.document_only,
added_only: st.added_only,
}
}
fn apply(self, st: &mut MenuState) {
@@ -378,9 +493,99 @@ impl Filters {
st.class = self.class;
st.variable_only = self.variable_only;
st.favorites_only = self.favorites_only;
st.document_only = self.document_only;
st.added_only = self.added_only;
}
}
/// The families the type in `doc` is set in, lowercase and by the name the menu lists them under
/// ([`vectorcraft_text::FontDb::canonical`]): the runs of every text object in the layers, symbols,
/// patterns and graph designs, hidden, locked and masked ones included, with a composite font named
/// as such. A pattern being edited is read from its editing layer only. Each run's family is looked
/// up with its style, so a family and style split from a PostScript name (`Honoka`, `Mincho`) find
/// the installed font of that name. Styles no type uses are left out.
fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Document) -> HashSet<String> {
// Each family and style once, so a document with many runs in a few fonts looks each one up
// once.
let mut named: HashMap<String, HashSet<String>> = HashMap::new();
let mut add = |n: &vectorcraft_doc::Node| {
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
for r in &t.runs {
let (family, style) = (&r.style.font_family, &r.style.font_style);
match named.get_mut(family) {
Some(styles) => {
if !styles.contains(style) {
styles.insert(style.clone());
}
}
None => {
named.insert(family.clone(), HashSet::from([style.clone()]));
}
}
}
}
};
let editing = doc.pattern_edit.as_ref().map(|e| e.pattern.as_str());
let patterns = doc.patterns.iter().filter(|p| Some(p.name.as_str()) != editing).flat_map(|p| p.art.iter().map(|a| &**a));
let designs = doc.graph_designs.iter().map(|g| &*g.art);
for n in doc.layers.iter().map(|l| &**l).chain(doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(designs) {
vectorcraft_doc::swatches::walk_with_masks(n, &mut add);
}
named.iter().flat_map(|(f, styles)| styles.iter().map(move |s| db.canonical(f, s).0.to_lowercase())).collect()
}
/// The families the Document filter lists, when it is on and a document is open: those of
/// `look`'s document, found again only when the document, its version or the font list changed.
fn used_families(db: &vectorcraft_text::FontDb, st: &mut MenuState, look: MenuLook) -> Option<Arc<HashSet<String>>> {
let document = look.document.filter(|_| st.document_only)?;
let key = (document.key(), db.generation());
if let Some((k, families)) = &st.document_fonts
&& *k == key
{
return Some(families.clone());
}
let families = Arc::new(document_families(db, document.doc));
st.document_fonts = Some((key, families.clone()));
Some(families)
}
/// The time the Recently Added filter counts back from: `look`'s clock, else the system clock. On
/// wasm, which has no installed fonts to date, the Unix epoch.
fn added_clock(look: MenuLook) -> std::time::SystemTime {
look.clock.unwrap_or_else(|| {
#[cfg(not(target_arch = "wasm32"))]
{
std::time::SystemTime::now()
}
#[cfg(target_arch = "wasm32")]
{
std::time::SystemTime::UNIX_EPOCH
}
})
}
/// The families the Recently Added filter lists, when it is on: those `db` dates within
/// [`vectorcraft_text::RECENTLY_ADDED_WITHIN`] before `look`'s clock, found again only when the
/// font list changed, the clock reached the instant the list may change at, or the clock went back
/// before the time the list was found for.
fn added_families(db: &vectorcraft_text::FontDb, st: &mut MenuState, look: MenuLook) -> Option<Arc<AddedFonts>> {
if !st.added_only {
return None;
}
let now = added_clock(look);
let key = (db.id(), db.generation());
if let Some((k, asked, added)) = &st.added
&& *k == key
&& *asked <= now
&& added.recheck_at.is_none_or(|t| now < t)
{
return Some(added.clone());
}
let added = Arc::new(AddedFonts::of(&db.recently_added(now)));
st.added = Some((key, now, added.clone()));
Some(added)
}
/// Where the filters every font menu shares are kept ([`Filters`]).
fn filters_id() -> egui::Id {
egui::Id::unique("font-menu-filters")
@@ -448,7 +653,7 @@ pub fn font_menu(
WheelInput::Leave => st.wheel_order = None,
WheelInput::Notches(notches) => {
if st.wheel_order.is_none() {
st.wheel_order = Some(wheel_order(&st, look).into());
st.wheel_order = Some(wheel_order(&mut st, look).into());
}
if let Some(order) = st.wheel_order.as_deref() {
let next = wheel_steps(order, &own, notches);
@@ -488,8 +693,24 @@ pub fn font_menu(
out
}
/// Does the menu list family `f` for search `query` (lowercase) under the filters of `st`?
fn listed(db: &vectorcraft_text::FontDb, f: &str, query: &str, st: &MenuState, look: MenuLook) -> bool {
/// Does the menu list family `f` for search `query` (lowercase) under the filters of `st`, among
/// `used` (lowercase) while the Document filter lists the document's families, and among `added`
/// while the Recently Added filter lists the recently added ones?
fn listed(
db: &vectorcraft_text::FontDb,
f: &str,
query: &str,
st: &MenuState,
look: MenuLook,
used: Option<&HashSet<String>>,
added: Option<&AddedFonts>,
) -> bool {
if used.is_some_and(|used| !used.contains(&f.to_lowercase())) {
return false;
}
if added.is_some_and(|added| !added.place.contains_key(&f.to_lowercase())) {
return false;
}
let label = db.family_display_name(f, look.english_names);
if !(query.is_empty() || f.to_lowercase().contains(query) || label.to_lowercase().contains(query)) {
return false;
@@ -505,11 +726,22 @@ fn listed(db: &vectorcraft_text::FontDb, f: &str, query: &str, st: &MenuState, l
}
/// The families the closed field's wheel steps through, in the open menu's order with no search:
/// the recent families first, then the others, under the menu's filters.
fn wheel_order(st: &MenuState, look: MenuLook) -> Vec<String> {
let db = vectorcraft_text::FontDb::global();
let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, "", st, look)).cloned().collect();
grouped_rows(&families, look.recent, &[], |_| vec![])
/// the recent families first, then the others, under the menu's filters; with Recently Added, the
/// newest first. Listed once per wheel gesture ([`MenuState`]'s `wheel_order`).
fn wheel_order(st: &mut MenuState, look: MenuLook) -> Vec<String> {
wheel_order_in(vectorcraft_text::FontDb::global(), st, look)
}
/// [`wheel_order`] of the families in `db`.
fn wheel_order_in(db: &vectorcraft_text::FontDb, st: &mut MenuState, look: MenuLook) -> Vec<String> {
let used = used_families(db, st, look);
let added = added_families(db, st, look);
let mut families: Vec<_> =
db.menu_family_list().iter().filter(|f| listed(db, f, "", st, look, used.as_deref(), added.as_deref())).cloned().collect();
if let Some(added) = &added {
added.order(&mut families);
}
grouped_rows(&families, if added.is_some() { &[] } else { look.recent }, &[], |_| vec![])
.into_iter()
.filter_map(|r| match r {
Row::Family(f) => Some(f),
@@ -1075,7 +1307,14 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id,
ui.memory_mut(|m| m.request_focus(field.with("edit")));
}
let query = widgets::search_field(ui, field, tl!("Search")).to_lowercase();
let refilter = filters(ui, st, &t);
let refilter = filters(ui, st, &t, look.document.is_some());
let added = added_families(db, st, look);
// On the system clock, the list is drawn again when a family's 30 days end.
if let (Some(at), None) = (added.as_ref().and_then(|a| a.recheck_at), look.clock)
&& let Ok(wait) = at.duration_since(added_clock(look))
{
ui.ctx().request_repaint_after(wait);
}
let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
// The current family by its own name (a document may name it in Japanese: ヒラギノ角ゴシック),
// as it was before any preview.
@@ -1094,13 +1333,26 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id,
look.recent.to_vec(),
db.generation(),
st.similar.clone(),
(look.document.filter(|_| st.document_only).map(|d| d.key()), added.clone()),
);
if st.rows_key.as_ref() != Some(&key) {
let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, &query, st, look)).cloned().collect();
let used = used_families(db, st, look);
let mut families: Vec<_> =
db.menu_family_list().iter().filter(|f| listed(db, f, &query, st, look, used.as_deref(), added.as_deref())).cloned().collect();
st.none_used = families.is_empty() && used.is_some_and(|used| !db.menu_family_list().iter().any(|f| used.contains(&f.to_lowercase())));
// Recently Added lists every family it finds once, newest first: the recent ones among
// them, without the Recent Fonts section.
let recent = match &added {
Some(added) => {
added.order(&mut families);
&[]
}
None => look.recent,
};
// Show Similar Fonts orders every listed family by likeness, the recent ones among them.
let rows = match &st.similar {
Some(base) => grouped_rows(&db.similar_families(base, &families), &[], &st.expanded, |f| db.styles(f)),
None => grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f)),
None => grouped_rows(&families, recent, &st.expanded, |f| db.styles(f)),
};
// Filter changes (including un-starring a favourite) may remove rows; expanding
// another family or a background font scan can insert rows before the highlight.
@@ -1145,7 +1397,9 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id,
}
st.header = ui.min_rect().height();
if rows.is_empty() {
widgets::dim_label(ui, tl!("No matching fonts"));
// The Document filter on a document whose type uses none of the listed families (none at
// all, or only missing ones) says so, whatever the other filters.
widgets::dim_label(ui, if st.none_used { tl!("This document uses no available fonts") } else { tl!("No matching fonts") });
}
ui.spacing_mut().item_spacing.y = 0.0;
// The scroll bar beside the rows, not over them: a floating one covered the stars at their
@@ -1160,6 +1414,10 @@ enum Chip {
/// A script ([`SCRIPTS`]).
Script(usize),
Favorites,
/// The families the current document's type uses.
Document,
/// The families installed in the last 30 days.
Added,
AnyKind,
Class(FontClass),
/// The Font Technology label, which filters nothing.
@@ -1167,21 +1425,24 @@ enum Chip {
Variable,
}
/// The filters, row by row, the same wherever the menu opens: the scripts; favorites, any kind
/// and the first three kinds; the other kinds; font technology.
fn filter_rows() -> [Vec<Chip>; 4] {
/// The filters, row by row, the same wherever the menu opens: the scripts; favorites, the
/// document's fonts, any kind and the first three kinds; the other kinds; font technology; the
/// recently added fonts.
fn filter_rows() -> [Vec<Chip>; 5] {
let (first, rest) = FontClass::ALL.split_at(3);
[
(0..SCRIPTS).map(Chip::Script).collect(),
[Chip::Favorites, Chip::AnyKind].into_iter().chain(first.iter().copied().map(Chip::Class)).collect(),
[Chip::Favorites, Chip::Document, Chip::AnyKind].into_iter().chain(first.iter().copied().map(Chip::Class)).collect(),
rest.iter().copied().map(Chip::Class).collect(),
vec![Chip::Technology, Chip::Variable],
vec![Chip::Added],
]
}
/// The filters on their rows ([`filter_rows`]): a row wraps only where the menu is narrower than
/// it. Records in `st` the width of the widest row unwrapped; whether a filter changed.
fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens) -> bool {
/// it. The Document filter is unavailable without a `document`. Records in `st` the width of the
/// widest row unwrapped; whether a filter changed.
fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool) -> bool {
let mut refilter = false;
let mut widest = 0.0_f32;
for row in filter_rows() {
@@ -1194,6 +1455,19 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens) -> bool {
let resp = match chip {
Chip::Script(i) => ui.selectable_label(st.script == i, text(script_label(i))),
Chip::Favorites => ui.selectable_label(st.favorites_only, text("★")).on_hover_text(tl!("Favorites")),
Chip::Document => {
let on = st.document_only && document;
let tip = tl!("Fonts used in this document");
let resp = ui
.add_enabled(document, egui::Button::selectable(on, text(tl!("Document"))))
.on_hover_text(tip)
.on_disabled_hover_text(tip);
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, document, on, tip));
resp
}
Chip::Added => {
ui.selectable_label(st.added_only, text(tl!("Recently Added"))).on_hover_text(tl!("Fonts added in the last 30 days"))
}
Chip::AnyKind => ui.selectable_label(st.class.is_none(), text(tl!("Any Kind"))),
Chip::Class(c) => ui.selectable_label(st.class == Some(c), text(class_label(c))),
Chip::Technology => ui.label(text(tl!("Font Technology")).color(t.text_dim)),
@@ -1206,6 +1480,8 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens) -> bool {
match chip {
Chip::Script(i) => st.script = i,
Chip::Favorites => st.favorites_only = !st.favorites_only,
Chip::Document => st.document_only = !st.document_only,
Chip::Added => st.added_only = !st.added_only,
Chip::AnyKind => st.class = None,
Chip::Class(c) => st.class = if st.class == Some(c) { None } else { Some(c) },
Chip::Technology => continue,
+340 -3
View File
@@ -380,15 +380,15 @@ fn the_wheel_follows_the_menus_order_and_filters() {
}
let recent = vec![names[2].clone()];
let look = super::MenuLook { samples: false, recent: &recent, ..Default::default() };
let order = super::wheel_order(&super::MenuState::default(), look);
let order = super::wheel_order(&mut super::MenuState::default(), look);
assert_eq!(order.first(), Some(&names[2]), "the recent family first");
// Other tests add fonts to the process-wide database meanwhile: compare places, not neighbours.
let at = |f: &String| order.iter().position(|x| x == f);
assert!(matches!((at(&names[0]), at(&names[1])), (Some(a), Some(b)) if 0 < a && a < b), "then the others in the menu's order");
assert_eq!(order.iter().filter(|f| **f == names[2]).count(), 1, "once each");
let favorites = vec![names[0].clone(), names[1].clone()];
let st = super::MenuState { favorites_only: true, ..Default::default() };
let order = super::wheel_order(&st, super::MenuLook { favorites: &favorites, ..look });
let mut st = super::MenuState { favorites_only: true, ..Default::default() };
let order = super::wheel_order(&mut st, super::MenuLook { favorites: &favorites, ..look });
assert_eq!(order, favorites, "the favourites filter");
}
@@ -1131,3 +1131,340 @@ fn show_similar_fonts_orders_the_list_by_likeness() {
frame(vec![], &mut st);
assert_eq!((st.similar.as_deref(), families(&st)), (None, menu_order));
}
/// An app with a new document holding type set in each of `fonts`, one text object each.
fn app_with_type(fonts: &[&str]) -> crate::VectorcraftApp {
let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", serde_json::json!({})).unwrap();
for (i, font) in fonts.iter().enumerate() {
app.run("text.create", serde_json::json!({"x": 20, "y": 40 + 30 * i, "text": "Type", "font": font})).unwrap();
}
app
}
/// Draws the open menu (its header and rows) for `look` under the filters of `st`, with `events`;
/// returns the shapes drawn.
fn menu_frame(ctx: &egui::Context, st: &mut super::MenuState, look: super::MenuLook, events: Vec<egui::Event>) -> Vec<egui::epaint::ClippedShape> {
let input =
egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 900.0))), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| {
super::list(ui, egui::Id::unique("document-filter"), st, "Inter", None, look);
});
out.textures_delta.clear();
out.shapes
}
/// The families `st`'s rows list, in their order.
fn listed_families(st: &super::MenuState) -> Vec<String> {
st.rows
.iter()
.filter_map(|r| match r {
Row::Family(f) => Some(f.clone()),
Row::Heading(_) | Row::Style(..) => None,
})
.collect()
}
/// The Document filter's chip lists only the families the document's type uses (hidden and locked
/// type included, a missing family left out), in the menu's order, and lists every family again
/// when it is clicked off.
#[test]
fn the_document_filter_lists_the_families_the_documents_type_uses() {
let mut app = app_with_type(&["Source Serif 4", "Inter"]);
app.run("object.hide", serde_json::json!({})).unwrap();
app.run("text.create", serde_json::json!({"x": 20, "y": 120, "text": "Locked", "font": "Source Sans 3"})).unwrap();
app.run("object.lock", serde_json::json!({})).unwrap();
app.run("text.create", serde_json::json!({"x": 20, "y": 150, "text": "Missing", "font": "Missing Family 7059"})).unwrap();
let db = vectorcraft_text::FontDb::global();
let used = super::document_families(db, &app.session.active().unwrap().doc);
let mut names: Vec<_> = used.iter().cloned().collect();
names.sort();
assert_eq!(names, ["inter", "missing family 7059", "source sans 3", "source serif 4"], "each run's family, as named");
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let mut st = super::MenuState::default();
let look = super::MenuLook { samples: false, ..super::MenuLook::of(&app) };
for _ in 0..3 {
menu_frame(&ctx, &mut st, look, vec![]);
}
let every = listed_families(&st);
assert!(every.len() > 3, "every family: {every:?}");
let click = |st: &mut super::MenuState, at: egui::Pos2| {
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
menu_frame(&ctx, st, look, vec![egui::Event::PointerMoved(at), button(true)]);
menu_frame(&ctx, st, look, vec![button(false)]);
menu_frame(&ctx, st, look, vec![])
};
let chip = text_at(&menu_frame(&ctx, &mut st, look, vec![]), |t| t == "Document").expect("the Document chip is drawn");
click(&mut st, chip);
assert!(st.document_only);
let in_menu: Vec<String> = every.iter().filter(|f| ["Inter", "Source Sans 3", "Source Serif 4"].contains(&f.as_str())).cloned().collect();
assert_eq!(listed_families(&st), in_menu, "the document's available families, in the menu's order");
click(&mut st, chip);
assert!(!st.document_only);
assert_eq!(listed_families(&st), every, "every family again");
}
/// Type kept in a graph design counts as the document's type, as type in a symbol does.
#[test]
fn the_document_filter_counts_type_in_graph_designs() {
let mut app = app_with_type(&["Inter"]);
let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Bar", "font": "JetBrains Mono"})).unwrap()["id"].as_u64().unwrap();
let art = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().expect("the new type");
app.run("edit.undo", serde_json::json!({})).unwrap();
let mut doc = (*app.session.active().unwrap().doc).clone();
let db = vectorcraft_text::FontDb::global();
assert!(!super::document_families(db, &doc).contains("jetbrains mono"));
doc.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Bars".into(), art: std::sync::Arc::new(art) });
let mut names: Vec<_> = super::document_families(db, &doc).into_iter().collect();
names.sort();
assert_eq!(names, ["inter", "jetbrains mono"]);
}
/// A run whose family and style were split from a PostScript name (as an importer without the font
/// splits one) counts under the family of the installed font of that name, found with its style.
#[test]
fn the_document_filter_finds_a_postscript_name_split_into_family_and_style() {
let mut app = app_with_type(&[]);
let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Split", "font": "Inter"})).unwrap()["id"].as_u64().unwrap();
let mut art = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().expect("the new type");
app.run("edit.undo", serde_json::json!({})).unwrap();
let vectorcraft_doc::NodeKind::Text(t) = &mut art.kind else { panic!("type") };
for r in &mut t.runs {
// SourceSans3-Semibold, split after "Semi".
r.style.font_family = "SourceSans3Semi".into();
r.style.font_style = "bold".into();
}
let mut doc = (*app.session.active().unwrap().doc).clone();
doc.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Split".into(), art: std::sync::Arc::new(art) });
let db = vectorcraft_text::FontDb::global();
let names: Vec<_> = super::document_families(db, &doc).into_iter().collect();
assert_eq!(names, ["source sans 3"]);
}
/// The Document filter combines with the others and with Recent Fonts, follows edits and undo
/// without the menu reopening, and steers the closed field's wheel.
#[test]
fn the_document_filter_combines_with_the_others_and_follows_edits() {
let mut app = app_with_type(&["Inter", "Source Serif 4"]);
let ctx = egui::Context::default();
let mut st = super::MenuState { document_only: true, favorites_only: true, ..Default::default() };
let favorites = vec!["Inter".to_string(), "Source Sans 3".to_string()];
let recent = vec!["Source Sans 3".to_string(), "Source Serif 4".to_string()];
let frames = |app: &crate::VectorcraftApp, st: &mut super::MenuState| {
let look = super::MenuLook { samples: false, favorites: &favorites, recent: &recent, ..super::MenuLook::of(app) };
for _ in 0..2 {
menu_frame(&ctx, st, look, vec![]);
}
};
frames(&app, &mut st);
assert_eq!(listed_families(&st), ["Inter"], "favorites the document uses");
st.favorites_only = false;
frames(&app, &mut st);
assert_eq!(st.rows.first(), Some(&Row::Heading("Recent Fonts")));
assert_eq!(listed_families(&st), ["Source Serif 4", "Inter"], "only the recent family the document uses comes first");
app.run("text.create", serde_json::json!({"x": 20, "y": 120, "text": "New", "font": "Source Sans 3"})).unwrap();
frames(&app, &mut st);
assert_eq!(listed_families(&st), ["Source Sans 3", "Source Serif 4", "Inter"], "an edit lists the new family");
app.run("edit.undo", serde_json::json!({})).unwrap();
frames(&app, &mut st);
assert_eq!(listed_families(&st), ["Source Serif 4", "Inter"], "undo takes it out again");
let look = super::MenuLook { samples: false, recent: &recent, ..super::MenuLook::of(&app) };
assert_eq!(super::wheel_order(&mut st, look), ["Source Serif 4", "Inter"], "the wheel steps through the same families");
}
/// A font previewed from the menu does not change what the Document filter lists: the family the
/// previewed text had stays listed, though no other type uses it. A pick lists the families again.
#[test]
fn a_preview_keeps_the_document_filters_families() {
let mut app = app_with_type(&["Source Serif 4", "Inter"]);
let ctx = egui::Context::default();
let mut st = super::MenuState { document_only: true, ..Default::default() };
let frames = |app: &crate::VectorcraftApp, st: &mut super::MenuState| {
let look = super::MenuLook { samples: false, recent: &[], ..super::MenuLook::of(app) };
for _ in 0..2 {
menu_frame(&ctx, st, look, vec![]);
}
};
frames(&app, &mut st);
assert_eq!(listed_families(&st), ["Inter", "Source Serif 4"]);
// The selected text, the only type in Inter, previewed in Source Serif 4.
super::apply(&mut app, &ctx, super::FontPick::Preview("Source Serif 4".into(), None));
assert!(app.session.active().unwrap().interaction.is_some(), "the preview is open");
frames(&app, &mut st);
assert_eq!(listed_families(&st), ["Inter", "Source Serif 4"], "the preview leaves the list as it was");
super::apply(&mut app, &ctx, super::FontPick::Preview("Inter".into(), None));
frames(&app, &mut st);
assert_eq!(listed_families(&st), ["Inter", "Source Serif 4"], "previewing back changes nothing");
super::apply(&mut app, &ctx, super::FontPick::Chosen("Source Serif 4".into(), None));
frames(&app, &mut st);
assert_eq!(listed_families(&st), ["Source Serif 4"], "the pick is an edit: Inter is no longer used");
app.run("edit.undo", serde_json::json!({})).unwrap();
frames(&app, &mut st);
assert_eq!(listed_families(&st), ["Inter", "Source Serif 4"], "undo lists it again");
}
/// The Document filter on a document without type lists nothing and says why; without a document
/// it is unavailable and lists every family; the filter is shared like the others.
#[test]
fn the_document_filter_on_an_empty_document_or_none() {
let app = app_with_type(&[]);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let mut st = super::MenuState { document_only: true, ..Default::default() };
let look = super::MenuLook { samples: false, ..super::MenuLook::of(&app) };
let mut shapes = vec![];
for _ in 0..3 {
shapes = menu_frame(&ctx, &mut st, look, vec![]);
}
assert!(st.rows.is_empty(), "{:?}", st.rows);
assert!(text_at(&shapes, |t| t == "This document uses no available fonts").is_some(), "the filter says the list is empty because of it");
// A search that matches nothing still says so in its own words.
st.document_only = false;
shapes = menu_frame(&ctx, &mut st, look, vec![egui::Event::Text("NoSuchFontFor7059".into())]);
shapes = if st.rows.is_empty() { menu_frame(&ctx, &mut st, look, vec![]) } else { shapes };
assert!(text_at(&shapes, |t| t == "No matching fonts").is_some());
// No document: the filter, kept on, lists every family.
let mut st = super::MenuState { document_only: true, ..Default::default() };
let none = egui::Context::default();
for _ in 0..3 {
menu_frame(&none, &mut st, super::MenuLook { samples: false, ..Default::default() }, vec![]);
}
assert!(st.document_only && !listed_families(&st).is_empty(), "no document: every family");
let mut other = super::MenuState::default();
super::Filters::of(&st).apply(&mut other);
assert!(other.document_only, "every font menu shares the filter");
}
/// A fixed time the Recently Added tests count from.
fn clock() -> std::time::SystemTime {
std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_800_000_000)
}
const DAY: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
/// The Recently Added filter's list of `families` (newest first), as found in `db` at [`clock`],
/// to be found again from `recheck_at` on.
fn added_in(db: &vectorcraft_text::FontDb, families: &[&str], recheck_at: Option<std::time::SystemTime>) -> Option<super::RecentlyAddedFonts> {
let list = vectorcraft_text::RecentlyAdded { families: families.iter().map(|f| f.to_string()).collect(), recheck_at };
// The font folders' first scan changes the generation: it runs before the generation is read.
db.family_list();
Some(((db.id(), db.generation()), clock(), std::sync::Arc::new(super::AddedFonts::of(&list))))
}
/// Draws the open menu of the families in `db` twice for `look` under the filters of `st`, with
/// `events` in the first pass; returns the shapes of the second.
fn settle_menu_of(
ctx: &egui::Context,
db: &vectorcraft_text::FontDb,
st: &mut super::MenuState,
look: super::MenuLook,
events: Vec<egui::Event>,
) -> Vec<egui::epaint::ClippedShape> {
let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 900.0));
let mut shapes = vec![];
for events in [events, vec![]] {
let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(area), ..Default::default() }, |ui| {
let _ = super::list_of(ui, db, egui::Id::unique("recently-added"), st, "Inter", None, look);
});
out.textures_delta.clear();
shapes = out.shapes;
}
shapes
}
/// The Recently Added filter lists only the families added recently, the newest first and without
/// the Recent Fonts section, the recent family among them; it combines with the ★ filter and the
/// search, Show Similar Fonts orders what it lists, and the closed field's wheel follows its order.
#[test]
fn the_recently_added_filter_lists_new_families_newest_first() {
// The bundled fonts alone: fonts that tests running alongside add stay out of the rows.
let db = vectorcraft_text::FontDb::with_font_dirs(vec![]);
let ctx = egui::Context::default();
let recent = vec!["Inter".to_string()];
let favorites = vec!["Inter".to_string(), "Source Serif 4".to_string()];
let look = super::MenuLook { samples: false, recent: &recent, clock: Some(clock()), ..Default::default() };
let newest_first = ["Source Serif 4", "JetBrains Mono", "Inter"];
let mut st = super::MenuState { added_only: true, added: added_in(&db, &newest_first, None), ..Default::default() };
settle_menu_of(&ctx, &db, &mut st, look, vec![]);
assert_eq!(listed_families(&st), newest_first, "newest first, the recent family among them");
assert!(!st.rows.iter().any(|r| matches!(r, Row::Heading(_))), "no Recent Fonts section: {:?}", st.rows);
assert_eq!(super::wheel_order_in(&db, &mut st, look), newest_first, "the wheel steps through the same families");
st.favorites_only = true;
settle_menu_of(&ctx, &db, &mut st, super::MenuLook { favorites: &favorites, ..look }, vec![]);
assert_eq!(listed_families(&st), ["Source Serif 4", "Inter"], "only the favorites among them");
st.favorites_only = false;
st.similar = Some("Inter".into());
settle_menu_of(&ctx, &db, &mut st, look, vec![]);
let listed: Vec<String> = newest_first.iter().map(|f| f.to_string()).collect();
assert_eq!(listed_families(&st), db.similar_families("Inter", &listed), "Show Similar Fonts orders only these");
st.similar = None;
settle_menu_of(&ctx, &db, &mut st, look, vec![]);
assert_eq!(listed_families(&st), newest_first, "newest first again once it is cleared");
settle_menu_of(&ctx, &db, &mut st, look, vec![egui::Event::Text("mono".into())]);
assert_eq!(listed_families(&st), ["JetBrains Mono"], "the search narrows the list");
}
/// A family leaves the list when its 30 days end, while the menu is open; with none left the
/// filter stays on and the menu says nothing matches. Its chip turns it off, and every font menu
/// shares it.
#[test]
fn the_recently_added_filter_drops_families_as_their_30_days_end() {
let db = vectorcraft_text::FontDb::with_font_dirs(vec![]);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let look = super::MenuLook { samples: false, clock: Some(clock()), ..Default::default() };
let mut st = super::MenuState { added_only: true, added: added_in(&db, &["Inter"], Some(clock() + DAY)), ..Default::default() };
settle_menu_of(&ctx, &db, &mut st, look, vec![]);
assert_eq!(listed_families(&st), ["Inter"]);
let mut other = super::MenuState::default();
super::Filters::of(&st).apply(&mut other);
assert!(other.added_only, "every font menu shares the filter");
let later = super::MenuLook { clock: Some(clock() + DAY), ..look };
let shapes = settle_menu_of(&ctx, &db, &mut st, later, vec![]);
assert!(st.rows.is_empty(), "{:?}", st.rows);
assert!(st.added_only, "the filter stays on");
assert!(text_at(&shapes, |t| t == "No matching fonts").is_some(), "the menu says nothing matches");
let chip = text_at(&shapes, |t| t == "Recently Added").expect("the Recently Added chip is drawn");
let button = |pressed| egui::Event::PointerButton { pos: chip, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
settle_menu_of(&ctx, &db, &mut st, later, vec![egui::Event::PointerMoved(chip), button(true)]);
settle_menu_of(&ctx, &db, &mut st, later, vec![button(false)]);
assert!(!st.added_only, "the chip turns the filter off");
assert!(listed_families(&st).len() > 1, "every family: {:?}", st.rows);
}
/// When the clock goes back before the time the list was found for (the system clock is set back),
/// the filter finds its families again rather than keep the list it found.
#[test]
fn the_recently_added_filter_finds_its_families_again_when_the_clock_goes_back() {
// The bundled fonts alone, which are never recently added.
let db = vectorcraft_text::FontDb::with_font_dirs(vec![]);
let ctx = egui::Context::default();
let mut st = super::MenuState { added_only: true, added: added_in(&db, &["Inter"], None), ..Default::default() };
settle_menu_of(&ctx, &db, &mut st, super::MenuLook { samples: false, clock: Some(clock()), ..Default::default() }, vec![]);
assert_eq!(listed_families(&st), ["Inter"]);
settle_menu_of(&ctx, &db, &mut st, super::MenuLook { samples: false, clock: Some(clock() - DAY), ..Default::default() }, vec![]);
assert!(st.rows.is_empty(), "found again a day earlier: {:?}", st.rows);
}
/// A font file installed just now is recently added by its creation time, and no longer 31 days
/// later. Where the file system keeps no creation time, the filter lists nothing.
#[test]
fn the_recently_added_filter_lists_a_font_installed_just_now() {
let dir = std::env::temp_dir().join(format!("vc-font-menu-recently-added-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("SourceSerif4-Regular.ttf");
std::fs::copy(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSerif4-Regular.ttf"), &file).unwrap();
let dated = std::fs::metadata(&file).and_then(|m| m.created()).is_ok();
let db = vectorcraft_text::FontDb::with_font_dirs(vec![dir.clone()]);
let ctx = egui::Context::default();
let now = std::time::SystemTime::now();
let mut st = super::MenuState { added_only: true, ..Default::default() };
settle_menu_of(&ctx, &db, &mut st, super::MenuLook { samples: false, clock: Some(now), ..Default::default() }, vec![]);
let expected: &[&str] = if dated { &["Source Serif 4"] } else { &[] };
assert_eq!(listed_families(&st), expected);
settle_menu_of(&ctx, &db, &mut st, super::MenuLook { samples: false, clock: Some(now + DAY * 31), ..Default::default() }, vec![]);
assert!(st.rows.is_empty(), "31 days later: {:?}", st.rows);
std::fs::remove_dir_all(&dir).unwrap();
}
+4
View File
@@ -1290,6 +1290,10 @@ font-technology Variable Променливи
Font List Списък с шрифтове
Show Similar Fonts Показване на подобни шрифтове
Clear Similar Fonts Изчистване на подобните шрифтове
Fonts used in this document Шрифтове, използвани в този документ
This document uses no available fonts Този документ не използва налични шрифтове
Recently Added Наскоро добавени
Fonts added in the last 30 days Шрифтове, добавени през последните 30 дни
Font Preview Size Размер за преглед на шрифта
Font Size Размер на шрифта
Variable Font Променлив шрифт
Can't render this file because it is too large.
+4
View File
@@ -3613,6 +3613,10 @@ theme Appearance Izgled
Font List Lista fontova
Show Similar Fonts Prikaži slične fontove
Clear Similar Fonts Očisti slične fontove
Fonts used in this document Fontovi korišteni u ovom dokumentu
This document uses no available fonts Ovaj dokument ne koristi dostupne fontove
Recently Added Nedavno dodani
Fonts added in the last 30 days Fontovi dodani u posljednjih 30 dana
Fonts in Document Fontovi u dokumentu
Refresh Font List Osvježi listu fontova
Replace Font Zamijeni font
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -1807,6 +1807,10 @@ digits Malayalam Malaiàlam
Font List Llista de tipus de lletra
Show Similar Fonts Mostra tipus de lletra semblants
Clear Similar Fonts Esborra els tipus de lletra semblants
Fonts used in this document Tipus de lletra utilitzats en aquest document
This document uses no available fonts Aquest document no utilitza cap tipus de lletra disponible
Recently Added Afegits recentment
Fonts added in the last 30 days Tipus de lletra afegits en els darrers 30 dies
Font Preview Size Mida de previsualització del tipus de lletra
Font Size Mida del tipus de lletra
Font Style: Estil de tipus de lletra:
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -3715,6 +3715,10 @@ theme Appearance Motiv
Font List Seznam písem
Show Similar Fonts Zobrazit podobná písma
Clear Similar Fonts Zrušit podobná písma
Fonts used in this document Písma použitá v tomto dokumentu
This document uses no available fonts Tento dokument nepoužívá žádná dostupná písma
Recently Added Nedávno přidané
Fonts added in the last 30 days Písma přidaná za posledních 30 dní
Fonts in Document Písma v dokumentu
Refresh Font List Obnovit seznam písem
Replace Font Nahradit písmo
Can't render this file because it is too large.
+4
View File
@@ -6131,6 +6131,10 @@ theme Appearance Udseende
Font List Skrifttypeliste
Show Similar Fonts Vis lignende skrifttyper
Clear Similar Fonts Ryd lignende skrifttyper
Fonts used in this document Skrifttyper brugt i dette dokument
This document uses no available fonts Dette dokument bruger ingen tilgængelige skrifttyper
Recently Added Nyligt tilføjet
Fonts added in the last 30 days Skrifttyper tilføjet inden for de sidste 30 dage
Fonts in Document Skrifttyper i dokumentet
Refresh Font List Opdatér skrifttypeliste
Replace Font Erstat skrifttype
Can't render this file because it is too large.
+4
View File
@@ -1340,6 +1340,10 @@ file-filter Templates Vorlagen
Font List Schriftliste
Show Similar Fonts Ähnliche Schriften anzeigen
Clear Similar Fonts Ähnliche Schriften zurücksetzen
Fonts used in this document In diesem Dokument verwendete Schriften
This document uses no available fonts Dieses Dokument verwendet keine verfügbaren Schriften
Recently Added Kürzlich hinzugefügt
Fonts added in the last 30 days In den letzten 30 Tagen hinzugefügte Schriften
Font Preview Size Größe der Schriftvorschau
Font Size Schriftgrad
Variable Font Variable Schrift
Can't render this file because it is too large.
+4
View File
@@ -1275,6 +1275,10 @@ font-technology Variable Μεταβλητές
Font List Λίστα γραμματοσειρών
Show Similar Fonts Εμφάνιση παρόμοιων γραμματοσειρών
Clear Similar Fonts Απαλοιφή παρόμοιων γραμματοσειρών
Fonts used in this document Γραμματοσειρές που χρησιμοποιούνται σε αυτό το έγγραφο
This document uses no available fonts Αυτό το έγγραφο δεν χρησιμοποιεί διαθέσιμες γραμματοσειρές
Recently Added Πρόσφατες προσθήκες
Fonts added in the last 30 days Γραμματοσειρές που προστέθηκαν τις τελευταίες 30 ημέρες
Font Preview Size Μέγεθος προεπισκόπησης γραμματοσειράς
Font Size Μέγεθος γραμματοσειράς
Variable Font Μεταβλητή γραμματοσειρά
Can't render this file because it is too large.
+4
View File
@@ -1355,6 +1355,10 @@ font-technology Variable Variables
Font List Lista de fuentes
Show Similar Fonts Mostrar fuentes similares
Clear Similar Fonts Borrar fuentes similares
Fonts used in this document Fuentes usadas en este documento
This document uses no available fonts Este documento no usa ninguna fuente disponible
Recently Added Añadidas recientemente
Fonts added in the last 30 days Fuentes añadidas en los últimos 30 días
Font Preview Size Tamaño de vista previa de fuente
Font Size Tamaño de fuente
Variable Font Fuente variable
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -3653,6 +3653,10 @@ theme Appearance Ulkoasu
Font List Fonttiluettelo
Show Similar Fonts Näytä samankaltaiset fontit
Clear Similar Fonts Tyhjennä samankaltaiset fontit
Fonts used in this document Tässä asiakirjassa käytetyt fontit
This document uses no available fonts Tämä asiakirja ei käytä saatavilla olevia fontteja
Recently Added Äskettäin lisätyt
Fonts added in the last 30 days Viimeisten 30 päivän aikana lisätyt fontit
Fonts in Document Asiakirjan fontit
Refresh Font List Päivitä fonttiluettelo
Replace Font Korvaa fontti
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -1345,6 +1345,10 @@ font-technology Variable Variables
Font List Liste des polices
Show Similar Fonts Afficher les polices similaires
Clear Similar Fonts Effacer les polices similaires
Fonts used in this document Polices utilisées dans ce document
This document uses no available fonts Ce document n’utilise aucune police disponible
Recently Added Ajoutées récemment
Fonts added in the last 30 days Polices ajoutées au cours des 30 derniers jours
Font Preview Size Taille de l’aperçu des polices
Font Size Taille de police
Variable Font Police variable
Can't render this file because it is too large.
+4
View File
@@ -1461,6 +1461,10 @@
Font List ફોન્ટ યાદી
Show Similar Fonts સમાન ફોન્ટ બતાવો
Clear Similar Fonts સમાન ફોન્ટ સાફ કરો
Fonts used in this document આ દસ્તાવેજમાં વપરાયેલા ફોન્ટ્સ
This document uses no available fonts આ દસ્તાવેજ કોઈ ઉપલબ્ધ ફોન્ટ વાપરતો નથી
Recently Added તાજેતરમાં ઉમેરેલા
Fonts added in the last 30 days છેલ્લા 30 દિવસમાં ઉમેરેલા ફોન્ટ્સ
Font Preview Size ફોન્ટ પૂર્વાવલોકન સાઇઝ
Font Size ફોન્ટ સાઇઝ
Font Style: ફોન્ટ સ્ટાઇલ:
Can't render this file because it contains an unexpected character in line 72 and column 5.
+4
View File
@@ -2007,6 +2007,10 @@ antiAlias Sharp शार्प
Font List फ़ॉन्ट सूची
Show Similar Fonts समान फ़ॉन्ट दिखाएँ
Clear Similar Fonts समान फ़ॉन्ट साफ़ करें
Fonts used in this document इस डॉक्यूमेंट में उपयोग किए गए फ़ॉन्ट
This document uses no available fonts यह डॉक्यूमेंट कोई उपलब्ध फ़ॉन्ट उपयोग नहीं करता
Recently Added हाल में जोड़े गए
Fonts added in the last 30 days पिछले 30 दिनों में जोड़े गए फ़ॉन्ट
Font Preview Size फ़ॉन्ट प्रीव्यू साइज़
Font Size फ़ॉन्ट साइज़
Font Size: फ़ॉन्ट साइज़:
Can't render this file because it is too large.
+4
View File
@@ -1680,6 +1680,10 @@ file-filter Templates Sablonok
Font List Betűtípuslista
Show Similar Fonts Hasonló betűtípusok megjelenítése
Clear Similar Fonts Hasonló betűtípusok törlése
Fonts used in this document A dokumentumban használt betűtípusok
This document uses no available fonts A dokumentum nem használ elérhető betűtípust
Recently Added Nemrég hozzáadott
Fonts added in the last 30 days Az elmúlt 30 napban hozzáadott betűtípusok
Font Preview Size Betűtípus-előnézet mérete
Font Size Betűméret
Variable Font Változó betűtípus
Can't render this file because it is too large.
+4
View File
@@ -3389,6 +3389,10 @@ theme Appearance Tampilan
Font List Daftar font
Show Similar Fonts Tampilkan font serupa
Clear Similar Fonts Hapus font serupa
Fonts used in this document Font yang digunakan dalam dokumen ini
This document uses no available fonts Dokumen ini tidak menggunakan font yang tersedia
Recently Added Baru ditambahkan
Fonts added in the last 30 days Font yang ditambahkan dalam 30 hari terakhir
Fonts in Document Font dalam dokumen
Refresh Font List Segarkan daftar font
Replace Font Ganti font
Can't render this file because it contains an unexpected character in line 2495 and column 5.
+4
View File
@@ -1374,6 +1374,10 @@ file-filter Templates Modelli
Font List Elenco font
Show Similar Fonts Mostra font simili
Clear Similar Fonts Cancella font simili
Fonts used in this document Font usati in questo documento
This document uses no available fonts Questo documento non usa font disponibili
Recently Added Aggiunti di recente
Fonts added in the last 30 days Font aggiunti negli ultimi 30 giorni
Font Preview Size Dimensione anteprima font
Font Size Dimensione font
Variable Font Font variabile
Can't render this file because it is too large.
+4
View File
@@ -1869,6 +1869,10 @@ antiAlias Sharp シャープ
Font List フォントリスト
Show Similar Fonts 類似フォントを表示
Clear Similar Fonts 類似フォントの表示を解除
Fonts used in this document このドキュメントで使用されているフォント
This document uses no available fonts このドキュメントでは使用可能なフォントが使われていません
Recently Added 最近追加
Fonts added in the last 30 days 過去 30 日間に追加されたフォント
Font Preview Size フォントプレビューのサイズ
Font: フォント:
Fonts フォント
Can't render this file because it is too large.
+4
View File
@@ -5484,6 +5484,10 @@ theme Appearance იერსახე
Font List შრიფტების სია
Show Similar Fonts მსგავსი შრიფტების ჩვენება
Clear Similar Fonts მსგავსი შრიფტების გასუფთავება
Fonts used in this document ამ დოკუმენტში გამოყენებული შრიფტები
This document uses no available fonts ეს დოკუმენტი არ იყენებს ხელმისაწვდომ შრიფტებს
Recently Added ახლახან დამატებული
Fonts added in the last 30 days ბოლო 30 დღეში დამატებული შრიფტები
Fonts in Document დოკუმენტის შრიფტები
Refresh Font List შრიფტების სიის განახლება
Replace Font შრიფტის ჩანაცვლება
Can't render this file because it is too large.
+4
View File
@@ -1859,6 +1859,10 @@ antiAlias Sharp 날카롭게
Font List 글꼴 목록
Show Similar Fonts 유사한 글꼴 표시
Clear Similar Fonts 유사한 글꼴 지우기
Fonts used in this document 이 문서에서 사용된 글꼴
This document uses no available fonts 이 문서는 사용 가능한 글꼴을 사용하지 않습니다
Recently Added 최근 추가됨
Fonts added in the last 30 days 최근 30일 동안 추가된 글꼴
Font Preview Size 글꼴 미리 보기 크기
Font: 글꼴:
Fonts 글꼴
Can't render this file because it is too large.
+4
View File
@@ -4006,6 +4006,10 @@ theme Appearance Vormgeving
Font List Lettertypelijst
Show Similar Fonts Vergelijkbare lettertypen tonen
Clear Similar Fonts Vergelijkbare lettertypen wissen
Fonts used in this document Lettertypen gebruikt in dit document
This document uses no available fonts Dit document gebruikt geen beschikbare lettertypen
Recently Added Recent toegevoegd
Fonts added in the last 30 days Lettertypen die in de afgelopen 30 dagen zijn toegevoegd
Fonts in Document Lettertypen in document
Refresh Font List Lettertypelijst vernieuwen
Replace Font Lettertype vervangen
Can't render this file because it is too large.
+4
View File
@@ -3594,6 +3594,10 @@ theme Appearance Wygląd
Font List Lista czcionek
Show Similar Fonts Pokaż podobne czcionki
Clear Similar Fonts Wyczyść podobne czcionki
Fonts used in this document Czcionki użyte w tym dokumencie
This document uses no available fonts Ten dokument nie używa żadnych dostępnych czcionek
Recently Added Ostatnio dodane
Fonts added in the last 30 days Czcionki dodane w ciągu ostatnich 30 dni
Fonts in Document Czcionki w dokumencie
Refresh Font List Odśwież listę czcionek
Replace Font Zastąp czcionkę
Can't render this file because it is too large.
+4
View File
@@ -1214,6 +1214,10 @@ antiAlias Sharp Nítido
Font List Lista de Fontes
Show Similar Fonts Mostrar Fontes Semelhantes
Clear Similar Fonts Limpar Fontes Semelhantes
Fonts used in this document Fontes usadas neste documento
This document uses no available fonts Este documento não usa nenhuma fonte disponível
Recently Added Adicionadas recentemente
Fonts added in the last 30 days Fontes adicionadas nos últimos 30 dias
Font Preview Size Tamanho da Visualização da Fonte
Font Size Tamanho da Fonte
Variable Font Fonte Variável
Can't render this file because it is too large.
+4
View File
@@ -1365,6 +1365,10 @@ file-filter Templates Шаблоны
Font List Список шрифтов
Show Similar Fonts Показать похожие шрифты
Clear Similar Fonts Сбросить похожие шрифты
Fonts used in this document Шрифты, используемые в этом документе
This document uses no available fonts В этом документе не используются доступные шрифты
Recently Added Недавно добавленные
Fonts added in the last 30 days Шрифты, добавленные за последние 30 дней
Font Preview Size Размер предварительного просмотра шрифта
Font Size Размер шрифта
Variable Font Вариативный шрифт
Can't render this file because it is too large.
+4
View File
@@ -1308,6 +1308,10 @@ font-technology Variable Variabla
Font List Typsnittslista
Show Similar Fonts Visa liknande typsnitt
Clear Similar Fonts Rensa liknande typsnitt
Fonts used in this document Typsnitt som används i det här dokumentet
This document uses no available fonts Det här dokumentet använder inga tillgängliga typsnitt
Recently Added Nyligen tillagda
Fonts added in the last 30 days Typsnitt som lagts till de senaste 30 dagarna
Font Preview Size Storlek på typsnittsförhandsgranskning
Font Size Teckenstorlek
Variable Font Variabelt typsnitt
Can't render this file because it is too large.
+4
View File
@@ -1304,6 +1304,10 @@ font-technology Variable Değişken
Font List Yazı Tipi Listesi
Show Similar Fonts Benzer Yazı Tiplerini Göster
Clear Similar Fonts Benzer Yazı Tiplerini Temizle
Fonts used in this document Bu belgede kullanılan yazı tipleri
This document uses no available fonts Bu belge kullanılabilir hiçbir yazı tipini kullanmıyor
Recently Added Son eklenenler
Fonts added in the last 30 days Son 30 günde eklenen yazı tipleri
Font Preview Size Yazı Tipi Önizleme Boyutu
Font Size Yazı Tipi Boyutu
Font: Yazı tipi:
Can't render this file because it is too large.
+4
View File
@@ -1368,6 +1368,10 @@ file-filter Templates Шаблони
Font List Список шрифтів
Show Similar Fonts Показати схожі шрифти
Clear Similar Fonts Скинути схожі шрифти
Fonts used in this document Шрифти, використані в цьому документі
This document uses no available fonts Цей документ не використовує доступних шрифтів
Recently Added Нещодавно додані
Fonts added in the last 30 days Шрифти, додані за останні 30 днів
Font Preview Size Розмір попереднього перегляду шрифту
Font Size Розмір шрифту
Variable Font Варіативний шрифт
Can't render this file because it is too large.
+4
View File
@@ -1591,6 +1591,10 @@ file-filter Templates Mẫu
Font List Danh sách phông
Show Similar Fonts Hiển thị phông tương tự
Clear Similar Fonts Xóa phông tương tự
Fonts used in this document Phông được dùng trong tài liệu này
This document uses no available fonts Tài liệu này không dùng phông nào có sẵn
Recently Added Mới thêm gần đây
Fonts added in the last 30 days Phông được thêm trong 30 ngày qua
Font Preview Size Cỡ xem trước phông
Font Size Cỡ chữ
Variable Font Phông chữ biến thiên
Can't render this file because it contains an unexpected character in line 205 and column 5.
+4
View File
@@ -1303,6 +1303,10 @@ file-filter Templates 模板
Font List 字体列表
Show Similar Fonts 显示相似字体
Clear Similar Fonts 清除相似字体
Fonts used in this document 此文档中使用的字体
This document uses no available fonts 此文档未使用任何可用字体
Recently Added 最近添加
Fonts added in the last 30 days 最近 30 天内添加的字体
Font Preview Size 字体预览大小
Font Size 字号
Variable Font 可变字体
Can't render this file because it is too large.
+4
View File
@@ -1338,6 +1338,10 @@ file-filter Templates 範本
Font List 字體清單
Show Similar Fonts 顯示相似字體
Clear Similar Fonts 清除相似字體
Fonts used in this document 此文件中使用的字體
This document uses no available fonts 此文件未使用任何可用字體
Recently Added 最近新增
Fonts added in the last 30 days 最近 30 天內新增的字體
Font Preview Size 字體預覽大小
Font Size 字體大小
Variable Font 可變字體
Can't render this file because it is too large.
+5 -4
View File
@@ -983,18 +983,19 @@ impl Drawn {
fn filter_rows(&self) -> Vec<(f32, f32)> {
use crate::i18n::{current, t, tr_ctx};
let variable = tr_ctx(current(), "font-technology", "Variable");
[(t("All Scripts"), t("Thai")), ("★", t("Rounded")), (t("Script / Brush"), t("Decorative")), (t("Font Technology"), variable)]
let added = t("Recently Added");
[(t("All Scripts"), t("Thai")), ("★", t("Rounded")), (t("Script / Brush"), t("Decorative")), (t("Font Technology"), variable), (added, added)]
.map(|(first, last)| (self.text(first).center().y, self.text(last).center().y))
.to_vec()
}
/// The filters lie on their four rows, none wrapped.
/// The filters lie on their five rows, none wrapped.
fn assert_filter_rows(&self) {
let rows = self.filter_rows();
for (i, (first, last)) in rows.iter().enumerate() {
assert!((first - last).abs() < 1.0, "filter row {i} wraps: its first chip at {first}, its last at {last}");
}
assert!(rows.windows(2).all(|w| w[1].0 > w[0].0 + 4.0), "four rows of filters, in order: {rows:?}");
assert!(rows.windows(2).all(|w| w[1].0 > w[0].0 + 4.0), "five rows of filters, in order: {rows:?}");
}
}
@@ -1149,7 +1150,7 @@ fn a_narrow_field_opens_a_menu_wide_enough_for_the_filters_and_names() {
}
}
/// In every UI language the filters keep their four rows unwrapped when the window has room for
/// In every UI language the filters keep their five rows unwrapped when the window has room for
/// them: the longest translated labels set the menu's width.
#[test]
fn the_filter_rows_stay_whole_in_every_language() {
+2
View File
@@ -1861,6 +1861,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font, and Print and Print Preview warn about the type that prints in it; `textAs: outlines` keeps the PDF's embedded glyphs). Two installed versions of one family and style (a font library keeping an old file beside a new one) both load, the first staying the one the family and style resolve to; PDF and `.ai` import tries each version when the glyphs differ, and type set in a version other than that one names it (`CharStyle::font_version`), which layout, the substituted-glyph highlight, Find Font, Package and Document Info follow. Fonts outside the font folders are listed too: those font services such as Adobe Fonts load on Windows, through DirectWrite and, for those only GDI lists, through GDI (#1258), and those apps and font managers register with CoreText on macOS (#579). When a document opens with fonts that aren't available, fonts used only in symbols included, a Missing Fonts dialog lists them after the linked-file questions, with Find Fonts (Type › Find Font on them) and Close. Its Find in Folder… (in Find Font too) searches a folder on several threads, reads only what the font scan reads of font files and skips app packages, the Program Files and ProgramData folders, the system's folders and the app data folders in a home folder; Add Fonts copies the font files the user chooses, suitcase fonts with their resource fork, into VectorCraft's own Fonts folder, which the desktop app and `vectorcraft-cli` read (`text.missingFonts`, `text.findFontFiles`, `text.addFontFiles`). The font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux).
A variable font's type gets one slider and field per variation axis under the Character panel's Variable Font button, each named as the font names the axis (Weight, Width), so the type can be set between or past its named instances: the settings stay with the characters (`CharStyle::font_axes`, `text.setFormat {fontAxes}` and `text.setRangeStyle {fontAxes}`, clamped to each axis's range; `text.fontList {family, style}` lists the axes), and layout, outlines, the substituted-glyph highlight and PDF and SVG export (`font-variation-settings`, embedded fonts) use the font instanced at them. Another font or style clears them; legacy `.ai` export writes the style and warns that they are left out.
The font menu's Font Technology › Variable (under the kind filter, as [Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html) places Variable in the classification filter's Font Technology section) lists only the families with variation axes, a family with a variable file beside static ones included, and works together with the script, kind, ★ and search filters; it stays set from one opening to the next. Measured by `font_menu::tests::the_variable_filter_lists_only_variable_families`, `font_menu::tests::the_variable_filter_is_named_as_fonts_are`, `tests_axes::a_family_with_variation_axes_is_variable` and `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable`.
The font menu's Document filter (beside ★) lists only the families that type in the current document is set in, as the quick filter for fonts used in the document does on the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html). It works together with the search, script, kind, Variable and ★ filters, Recent Fonts and Show Similar Fonts, steers the closed field's wheel, follows edits and undo while the menu is open, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: hidden, locked, masked, symbol, pattern and graph design type counts, styles no type uses do not, a composite font lists under its own name, a family the document names but this computer lacks is not listed (Find Font reports it), a document without available fonts lists nothing with its own message, and with no document open the filter is unavailable. Measured by `font_menu::tests::the_document_filter_lists_the_families_the_documents_type_uses`, `font_menu::tests::the_document_filter_combines_with_the_others_and_follows_edits`, `font_menu::tests::the_document_filter_counts_type_in_graph_designs` and `font_menu::tests::the_document_filter_on_an_empty_document_or_none`.
The font menu's Recently Added filter (on its own row under Font Technology) lists only the installed families added in the last 30 days, the newest at the top, as the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=486) and the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describe it (`vectorcraft_text::FontDb::recently_added`). It works together with the search, script, kind, Variable, ★ and Document filters, lists only the families every active filter matches, steers the closed field's wheel, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: a family is dated by the creation time of its newest font file on this computer (a file the file system keeps no creation time for, or one dated in the future, does not count), the 30th day is included, families added at the same instant are in name order, the recently used families appear in that order without the Recent Fonts section, Show Similar Fonts orders only the families the filter lists, a family leaves the list when its 30 days end while the menu is open, an empty list keeps the filter on and says no fonts match, and fonts bundled with the app or loaded from documents are never listed. Measured by `font_menu::tests::the_recently_added_filter_lists_new_families_newest_first`, `font_menu::tests::the_recently_added_filter_drops_families_as_their_30_days_end`, `font_menu::tests::the_recently_added_filter_lists_a_font_installed_just_now`, `tests::recently_added::families_added_in_the_last_30_days_are_listed_newest_first`, `tests::recently_added::a_family_is_dated_by_its_newest_valid_file` and `tests::sysfonts::installed_fonts_are_recently_added_by_their_files_creation_time`.
The font database looks up a name that is neither a loaded nor an installed family among the other names of the loaded and installed fonts once for each style it is asked in, and keeps the answer until fonts are added or rescanned. Laying out a story of 1,000 paragraphs set in a font that is not installed, with 400 more fonts loaded, takes a median of 56 to 71 ms instead of 409 to 507 ms on Windows 11 (`CRAFT_FONTS_DIR=<craft-fonts checkout> cargo test --release -p vectorcraft-text --lib missing_font_story_layout_timing -- --ignored --nocapture`).
A font family removed while the app runs leaves the font menus when the app scans the font folders again (when its window comes to the front after a font folder changed, or Refresh Font List), also when type had used it: that type then draws in the fallback font and Find Font lists the font as missing, until the font is installed again and the folders are scanned.
- **Files (M4):**