mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 12:32:10 +01:00
Merge main into feat/craft-testkit-guards
This commit is contained in:
commit
7490bfa805
34 files changed
+2243
-284
No files matched your search
@@ -11,6 +11,7 @@ repository.workspace = true
|
||||
reads = [
|
||||
"crates/ui-contract/fonts/inter/Inter-Regular.ttf",
|
||||
"crates/ui-contract/fonts/inter/Inter-SemiBold.ttf",
|
||||
"crates/font-subset/tests/data/orbitron/Orbitron[wght].ttf",
|
||||
"crates/font-subset/tests/data/sarabun/Sarabun-Regular.ttf",
|
||||
"crates/ui-contract/tests/fonts/NotoSansCJKsc-test.otf",
|
||||
]
|
||||
|
||||
@@ -32,13 +32,22 @@ The layout follows Adobe Fonts' and Google Fonts' browse pages.
|
||||
Preview, Installed, a progress bar while downloading,
|
||||
Couldn't install with Retry, "Not curated" for a source the user added), and a large sample in
|
||||
the face below. The list is virtual: only the cards on screen are laid out, and their faces load
|
||||
as they come into view. The arrow keys step through the cards and Enter opens one.
|
||||
- **Sample toolbar**: a preset (a sentence in the language filtered by, or in the family's own
|
||||
script when it has no Latin; the alphabet; numerals), the sample text, and the size.
|
||||
as they come into view. With a preview service set, families that aren't installed draw from
|
||||
small subsets of their face: the sample for the cards on screen, then one screen above and two
|
||||
below, then ASCII for the Latin cards on screen; typed text outside those asks for its own
|
||||
characters once typing pauses. A card the service draws offers no Preview; one whose subset
|
||||
failed does, and so does its details sheet. The arrow keys step through the cards and Enter
|
||||
opens one.
|
||||
- **Sample toolbar**: a preset (a sentence in the language filtered by, else the family's own
|
||||
sample from the index, by its `sample_script`; the alphabet; numerals), the sample text, and the
|
||||
size.
|
||||
- **Details sheet** over the list: every style in its own face with Install or Remove for each,
|
||||
Install all (with the same menu) and Remove all, whether the family is available to all apps
|
||||
with the switch that changes it, the source, designer, licence, scripts and languages, and what a
|
||||
preview downloads.
|
||||
preview downloads. With a preview service, styles not installed draw with its subsets: a static
|
||||
file's sample, and one subset of each variable file with every axis kept, drawn at each named
|
||||
instance and at the values of its axis sliders. The copyright and the upstream link, and
|
||||
an Apache family's NOTICE and, on request, the licence text, read through the store.
|
||||
- **Installed**: system and font store fonts as the same cards, filtered by source. Only font
|
||||
store families can be removed; system fonts are removed with the system's own tools.
|
||||
- **Sources** (`sources_ui`, for a host's settings page): the built-in sources, the index URLs the
|
||||
@@ -81,6 +90,10 @@ panel.ui(ui);
|
||||
| `set_look(look)` | The host's palettes (dark and light) and font families, and whether labels are set in capitals |
|
||||
| `settings()` | The panel's `FontsPanelSettings`: the sample text, preset and size, and whether the downloads note was closed. The panel reads them from the Host's `fonts_panel` section on its first frame and writes the section when they change; without a Host they stay in memory |
|
||||
| `downloads_allowed()`, `set_downloads_allowed(on)` | The download consent, for a host's settings page. It is the font store's own setting, shared by every Craft app |
|
||||
| `use_default_filters(language)` | Starts the catalogue on sans-serif families in the host's interface language (English when the index has none for it). Called once, after building the panel |
|
||||
| `with_previews(previews)` | The preview service's client (craft-font-store's `preview::Previews`), for a host that builds its own (native only) |
|
||||
| `reload_preview_settings()` | Reads the preview service and the previews setting again, after a host's settings page changed them. The panel also reads them when it first shows and when its window regains focus |
|
||||
| `loading_previews()` | Whether previews are being fetched |
|
||||
| `show_downloads_switch(false)` | For a host with the switch in its own settings |
|
||||
| `sources_ui(ui)` | The font sources, for a host's settings page |
|
||||
| `set_index(index)` | The indexes, after the host fetched them |
|
||||
@@ -88,17 +101,30 @@ panel.ui(ui);
|
||||
|
||||
## Network use
|
||||
|
||||
Nothing is downloaded until the user allows it. Downloads are off by default; the first Install or
|
||||
Preview asks first. Files come from each source's repositories at the commit or tag its index
|
||||
No font is installed or downloaded whole until the user allows it. Downloads are off by default; the
|
||||
first Install or Preview asks first. With a preview service set and previews on (a user setting, on by
|
||||
default), the panel fetches the small preview subsets of the fonts it shows without asking; with
|
||||
previews off it uses only those in the disk cache. Files come from each source's repositories at the commit or tag its index
|
||||
records, through jsDelivr (raw GitHub as the fallback), and each is checked against the index's
|
||||
size and sha256 before use. Previews stay in memory and are never installed. A source the user
|
||||
adds is an index at an https URL; its families are never curated.
|
||||
|
||||
## Strings
|
||||
|
||||
Every interface string goes through craft-i18n with the English text as the key. The panel embeds
|
||||
its own Japanese and Arabic catalogs (`src/panel/catalogs/`) until its rows are part of
|
||||
craft-i18n; style and weight names, licence names and product names stay in English.
|
||||
Every interface string is a word of the Host's `I18n` (`craft_ui::words!`), so the panel is in the Host's
|
||||
language when the app's catalogs have its rows and in English where they have none. `CATALOGS` holds the
|
||||
Japanese and Arabic rows, until they are part of craft-i18n's shared catalog, as data the app passes to
|
||||
its Host's `I18n`:
|
||||
|
||||
```rust
|
||||
// An app with no shared catalog of its own; one with a shared catalog joins the rows to it for
|
||||
// `I18n::from_owned`.
|
||||
let (i18n, problems) = craft_i18n::I18n::new(craft_font_manager::CATALOGS, &["ja", "ar"]);
|
||||
let lang = i18n.match_tag(language).unwrap_or(craft_i18n::Lang::EN);
|
||||
Host::builder(app).i18n(Arc::new(i18n)).lang(lang).install(ctx);
|
||||
```
|
||||
|
||||
Style and weight names, licence names and product names stay in English.
|
||||
|
||||
## Testing
|
||||
|
||||
|
||||
@@ -25,13 +25,14 @@ craft_ui::words! {
|
||||
width: "axisSliders.width" = "Width";
|
||||
slant: "axisSliders.slant" = "Slant";
|
||||
italic: "axisSliders.italic" = "Italic";
|
||||
optical_size: "axisSliders.opticalSize" = "Optical size";
|
||||
style: "axisSliders.style" = "Style";
|
||||
custom: "axisSliders.custom" = "Custom";
|
||||
}
|
||||
}
|
||||
|
||||
/// The label of an axis: its name when the font gives one, else the registered tag's
|
||||
/// (`Weight`, `Width`, `Slant`, `Italic`), else the tag itself.
|
||||
/// (`Weight`, `Width`, `Slant`, `Italic`, `Optical size`), else the tag itself.
|
||||
pub fn axis_label(axis: &FontAxis) -> String {
|
||||
label_in(axis, &AxisSlidersWords::default())
|
||||
}
|
||||
@@ -45,6 +46,7 @@ fn label_in(axis: &FontAxis, labels: &AxisSlidersWords) -> String {
|
||||
b"wdth" => labels.width.as_str().to_owned(),
|
||||
b"slnt" => labels.slant.as_str().to_owned(),
|
||||
b"ital" => labels.italic.as_str().to_owned(),
|
||||
b"opsz" => labels.optical_size.as_str().to_owned(),
|
||||
tag => Tag::new(tag).to_string(),
|
||||
}
|
||||
}
|
||||
@@ -70,9 +72,21 @@ fn set_value(values: &mut AxisValues, tag: [u8; 4], value: f32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The axes the sliders show: not hidden, not `opsz`, with a finite, non-empty range.
|
||||
fn shown_axes(axes: &[FontAxis]) -> impl Iterator<Item = &FontAxis> {
|
||||
axes.iter().filter(|a| !a.hidden && a.tag != *b"opsz" && a.min.is_finite() && a.max.is_finite() && a.min < a.max)
|
||||
/// Where the optical size axis (`opsz`) takes its value from.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum OpticalSize {
|
||||
/// The text layout sets it from the font size: it has no slider.
|
||||
#[default]
|
||||
FontSize,
|
||||
/// Its own slider, as any axis: for text drawn only to look at the face.
|
||||
Slider,
|
||||
}
|
||||
|
||||
/// The axes the sliders show: not hidden, `opsz` only where it has a slider, with a finite, non-empty range.
|
||||
pub(crate) fn shown_axes(axes: &[FontAxis], optical_size: OpticalSize) -> impl Iterator<Item = &FontAxis> {
|
||||
let slides = move |a: &FontAxis| a.tag != *b"opsz" || optical_size == OpticalSize::Slider;
|
||||
axes.iter().filter(move |a| !a.hidden && slides(a) && a.min.is_finite() && a.max.is_finite() && a.min < a.max)
|
||||
}
|
||||
|
||||
/// What changed in the sliders this pass.
|
||||
@@ -108,8 +122,8 @@ struct Drawn {
|
||||
}
|
||||
|
||||
/// One slider field per visible axis (label, slider, number field with the axis's range), plus a `Select` of named
|
||||
/// instances above them when the face has any. Hidden axes, `opsz` (the text layout sets the optical size from the
|
||||
/// font size) and axes with an empty or non-finite range are left out. Values are the current coordinates; an axis
|
||||
/// instances above them when the face has any. Hidden axes, `opsz` ([`OpticalSize::FontSize`]) and axes with an empty or
|
||||
/// non-finite range are left out. Values are the current coordinates; an axis
|
||||
/// without one shows what the layout draws (its style's weight and italic; else its default). Axes whose range is 10 wide
|
||||
/// or more step by whole units, the others by hundredths. A drag is one edit; an instance sets every axis in one
|
||||
/// edit.
|
||||
@@ -128,6 +142,9 @@ pub struct AxisSliders<'a> {
|
||||
/// Whether the style is italic: an unset `ital` axis then shows its maximum, once a weight is given.
|
||||
#[prop]
|
||||
italic: bool,
|
||||
/// Whether the `opsz` axis has a slider.
|
||||
#[prop]
|
||||
optical_size: OpticalSize,
|
||||
/// The axes (by tag) the selection mixes: each shows `Mixed` and is left out of the edit's held values.
|
||||
#[prop]
|
||||
#[allow(dead_code)] // P3(type-w3): ty.X21a
|
||||
@@ -137,12 +154,21 @@ pub struct AxisSliders<'a> {
|
||||
impl<'a> AxisSliders<'a> {
|
||||
/// Sliders named `label` over the `axes` of a face, editing the coordinates `values`.
|
||||
pub fn new(label: impl Into<Label>, axes: &'a [FontAxis], values: Bind<'a, AxisValues>) -> Self {
|
||||
AxisSliders { label: label.into(), axes, values, instances: &[], weight: None, italic: false, mixed: &[] }
|
||||
AxisSliders {
|
||||
label: label.into(),
|
||||
axes,
|
||||
values,
|
||||
instances: &[],
|
||||
weight: None,
|
||||
italic: false,
|
||||
optical_size: OpticalSize::default(),
|
||||
mixed: &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the sliders (and the instance list, if any) and reports the edit made this pass.
|
||||
pub fn show(self, ui: &mut Ui) -> AxisSlidersOutput {
|
||||
let AxisSliders { label, axes, mut values, instances, weight, italic, mixed: _ } = self;
|
||||
let AxisSliders { label, axes, mut values, instances, weight, italic, optical_size, mixed: _ } = self;
|
||||
let drawn = Drawn { weight, italic };
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<AxisSlidersWords>();
|
||||
@@ -172,7 +198,7 @@ impl<'a> AxisSliders<'a> {
|
||||
instance = Some(chosen.clone());
|
||||
}
|
||||
}
|
||||
for axis in shown_axes(axes) {
|
||||
for axis in shown_axes(axes, optical_size) {
|
||||
let held = read_bind(&mut values, cx).unwrap_or_default();
|
||||
let wide = axis.max - axis.min >= 10.0;
|
||||
let mut value = f64::from(value_of(&held, axis, drawn));
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, ValueAt, story};
|
||||
use egui::Ui;
|
||||
|
||||
use super::{AxisSliders, AxisValues};
|
||||
use super::{AxisSliders, AxisValues, OpticalSize};
|
||||
use crate::axes::{FontAxis, NamedInstance};
|
||||
|
||||
const WGHT: [u8; 4] = *b"wght";
|
||||
@@ -20,3 +20,11 @@ fn axis_sliders(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (values, values_at): (&mut AxisValues, ValueAt<'_>) = data.value_at("values", vec![(WGHT, 400.0), (WDTH, 100.0)]);
|
||||
AxisSliders::new("Axes", &axes, values_at.bind(values)).instances(&instances).show(ui).into()
|
||||
}
|
||||
|
||||
/// Sliders that also set the optical size, for text drawn only to look at the face.
|
||||
#[story(AxisSliders<'static>, covers = [], drive = Drive::Never)]
|
||||
fn axis_sliders_optical_size(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let axes = [FontAxis::new(WGHT, "", 100.0, 400.0, 900.0), FontAxis::new(*b"opsz", "", 8.0, 14.0, 144.0)];
|
||||
let (values, values_at): (&mut AxisValues, ValueAt<'_>) = data.value_at("values", vec![(WGHT, 400.0)]);
|
||||
AxisSliders::new("Axes", &axes, values_at.bind(values)).optical_size(OpticalSize::Slider).show(ui).into()
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub use craft_font_catalog;
|
||||
pub use craft_font_catalog::{Catalog, FaceInfo, FontEnv, Source};
|
||||
#[cfg(feature = "ui")]
|
||||
pub use panel::{
|
||||
FontSources, FontSourcesOutput, FontsBrowseWords, FontsCommand, FontsPanel, FontsPanelOutput, FontsPanelSettings, FontsPanelView,
|
||||
CATALOGS, FontSources, FontSourcesOutput, FontsBrowseWords, FontsCommand, FontsPanel, FontsPanelOutput, FontsPanelSettings, FontsPanelView,
|
||||
FontsPanelWords, Options, Preset, Tab, install_interface_fonts,
|
||||
};
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::sync::Arc;
|
||||
|
||||
use crate::craft_font_catalog::{FontEnv, Limits, Os};
|
||||
use crate::filter::{Query, Search};
|
||||
use crate::index::{Category, Family, Index, categories, source_label};
|
||||
use crate::index::{Category, Family, FontFile, Index, categories, source_label};
|
||||
use crate::installed::{InstalledFamily, group};
|
||||
use crate::store::{Conflict, Installer, MadeAvailable, RemoveRequest, StoreError};
|
||||
use crate::{Catalog, FaceInfo, Source};
|
||||
@@ -18,7 +18,7 @@ use craft_behavior::ColumnWidth;
|
||||
use craft_host::{Host, Section, Wake};
|
||||
use craft_i18n::Folder;
|
||||
use craft_i18n::matcher::Matcher;
|
||||
use craft_ui::contract::{NoValue, Outcome, Props as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Animate as _, NoValue, Outcome, Props as _, ShowContainer as _};
|
||||
use craft_ui::dialog::Prompt;
|
||||
use craft_ui::fonts::{EmbeddedFace, I18nScripts, UiFonts};
|
||||
use craft_ui::layout_components::{Grid, Stack};
|
||||
@@ -29,11 +29,14 @@ use craft_ui::runtime::words::CommonWords;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
use egui::{Context, Response, Ui};
|
||||
|
||||
use crate::axes::AxisValues;
|
||||
use crate::panel::browse::{FontsBrowseWords, Texts};
|
||||
use crate::panel::details::DetailsSheet;
|
||||
use crate::panel::i18n::LANGUAGES;
|
||||
use crate::panel::jobs::{self, Finished, Jobs, Kind, Request};
|
||||
use crate::panel::legal::LegalTexts;
|
||||
use crate::panel::samples;
|
||||
use crate::panel::subsets::Subsets;
|
||||
|
||||
/// Installs the standalone app's interface fonts in `ctx`: craft-ui's font stack for `language`, with `craft_faces`
|
||||
/// (craft-fonts' faces the app embeds with craft-fonts-build, or none) and the system's fonts for every other
|
||||
@@ -42,8 +45,11 @@ pub fn install_interface_fonts(ctx: &Context, language: &str, craft_faces: &[Emb
|
||||
UiFonts::new(&I18nScripts).languages(LANGUAGES).ui_language(language).craft_faces(craft_faces).install(ctx);
|
||||
}
|
||||
|
||||
/// The filters column takes the width of its widest section; the list and toolbar take the rest.
|
||||
const PANES: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)];
|
||||
/// The filters column, whatever the list beside it shows; the list and toolbar take the rest.
|
||||
const PANES: [ColumnWidth; 2] = [ColumnWidth::Fixed(248.0), ColumnWidth::fill(1.0)];
|
||||
/// The panes of a panel less than [`WIDE_PANEL`] wide.
|
||||
const NARROW_PANES: [ColumnWidth; 2] = [ColumnWidth::Fixed(212.0), ColumnWidth::fill(1.0)];
|
||||
const WIDE_PANEL: f32 = 860.0;
|
||||
|
||||
/// Preview downloads: at most this much per file, and this many faces in a session.
|
||||
const PREVIEW_LIMITS: Limits = Limits { max_file_bytes: 64 << 20, max_faces_per_file: 512, max_added_faces: 20_000 };
|
||||
@@ -289,6 +295,12 @@ pub struct FontsPanel {
|
||||
/// Downloaded preview files, never installed.
|
||||
pub(crate) previews: Arc<Catalog>,
|
||||
pub(crate) previewed: HashMap<String, Vec<FaceInfo>>,
|
||||
/// The previews from the font preview service.
|
||||
pub(crate) subsets: Subsets,
|
||||
/// The values the user set on the details sheet's axis sliders, by file sha256.
|
||||
pub(crate) detail_axes: HashMap<String, AxisValues>,
|
||||
/// Licence and NOTICE texts, by family, text and file.
|
||||
pub(crate) legal: LegalTexts,
|
||||
pub(crate) jobs: Jobs,
|
||||
pub(crate) asking: Option<Pending>,
|
||||
/// By lower-case family name.
|
||||
@@ -325,6 +337,11 @@ pub(crate) fn source_name(words: &FontsPanelWords, source: Source) -> &Label {
|
||||
}
|
||||
}
|
||||
|
||||
/// The file of the face the list shows for a family of the index: the one closest to an upright regular.
|
||||
pub(crate) fn list_file(family: &Family) -> Option<&FontFile> {
|
||||
family.files.iter().min_by_key(|f| (f.is_italic(), !f.has_weight(400, f.is_italic()), f.weight.abs_diff(400), !f.has_normal_width()))
|
||||
}
|
||||
|
||||
/// The face closest to an upright regular.
|
||||
pub(crate) fn regular(faces: &[FaceInfo]) -> Option<&FaceInfo> {
|
||||
faces.iter().min_by_key(|f| (f.italic, ((f.weight - 400.0).abs() * 10.0) as i64, ((f.width - 100.0).abs() * 10.0) as i64))
|
||||
@@ -357,6 +374,7 @@ impl FontsPanel {
|
||||
pub fn new(options: Options) -> FontsPanel {
|
||||
let catalogue = options.index.map(|index| Catalogue { search: Search::new(&index), index: Arc::new(index) });
|
||||
let previews = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false));
|
||||
let subsets = Subsets::new(Arc::clone(&options.installer));
|
||||
FontsPanel {
|
||||
settings: FontsPanelSettings::default(),
|
||||
saved: FontsPanelSettings::default(),
|
||||
@@ -389,6 +407,9 @@ impl FontsPanel {
|
||||
detail: None,
|
||||
previews,
|
||||
previewed: HashMap::new(),
|
||||
subsets,
|
||||
detail_axes: HashMap::new(),
|
||||
legal: LegalTexts::new(),
|
||||
jobs: Jobs::new(),
|
||||
asking: None,
|
||||
failed: HashMap::new(),
|
||||
@@ -399,6 +420,25 @@ impl FontsPanel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches the previews through `previews` instead of craft-font-store's client.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[must_use]
|
||||
pub fn with_previews(mut self, previews: craft_font_store::preview::Previews) -> FontsPanel {
|
||||
self.subsets.replace(previews);
|
||||
self
|
||||
}
|
||||
|
||||
/// Reads the preview service and the previews setting again on the next pass, after a host's settings page changed
|
||||
/// them. The panel also reads them when it first shows and when its window regains focus.
|
||||
pub fn reload_preview_settings(&mut self) {
|
||||
self.subsets.read_settings_soon();
|
||||
}
|
||||
|
||||
/// Whether previews from the font preview service are being fetched.
|
||||
pub fn loading_previews(&self) -> bool {
|
||||
self.subsets.loading()
|
||||
}
|
||||
|
||||
/// Shows `index` (after the host fetched the sources, say). The details sheet closes, as family positions
|
||||
/// change.
|
||||
pub fn set_index(&mut self, index: Result<Index, String>) {
|
||||
@@ -460,6 +500,25 @@ impl FontsPanel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the catalogue filtered to sans-serif families and to the language of `language` (a tag such as `de` or
|
||||
/// `pt-BR`; the most spoken language of the index with that ISO 639 code), or to English when the index has none for
|
||||
/// it. A host calls it once, after building the panel; the user changes both filters from there.
|
||||
pub fn use_default_filters(&mut self, language: &str) {
|
||||
let Ok(c) = &self.catalogue else { return };
|
||||
let code = language.split(['-', '_']).next().unwrap_or("").to_ascii_lowercase();
|
||||
let best = |code: &str| {
|
||||
c.index
|
||||
.languages()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, l)| !l.historical && l.id.split('_').next().is_some_and(|id| id.eq_ignore_ascii_case(code)))
|
||||
.max_by_key(|(_, l)| l.population)
|
||||
.map(|(i, _)| i)
|
||||
};
|
||||
self.query.category = Some(Category::SansSerif);
|
||||
self.query.language = best(&code).or_else(|| best("en"));
|
||||
}
|
||||
|
||||
/// Whether the panel shows its own "Allow downloads" switch. A host with the switch in its own settings turns it
|
||||
/// off; the panel still offers to allow downloads where one is needed.
|
||||
pub fn show_downloads_switch(&mut self, show: bool) {
|
||||
@@ -533,6 +592,7 @@ impl FontsPanel {
|
||||
self.catalog.rescan_if_changed();
|
||||
}
|
||||
self.consent = None;
|
||||
self.subsets.read_settings_soon();
|
||||
}
|
||||
self.window_active = window_active;
|
||||
self.refresh_installed();
|
||||
@@ -604,6 +664,7 @@ impl FontsPanel {
|
||||
}
|
||||
}
|
||||
self.poll_sources();
|
||||
self.poll_legal();
|
||||
}
|
||||
|
||||
fn record_copy(&mut self, family: &str, copied: Option<Result<MadeAvailable, StoreError>>) {
|
||||
@@ -731,8 +792,9 @@ impl FontsPanel {
|
||||
self.installed_shown.0.clone()
|
||||
}
|
||||
|
||||
/// The sample for a family with `scripts`: what the user typed, else the preset.
|
||||
pub(crate) fn sample_for<'a>(&self, scripts: impl IntoIterator<Item = &'a str>) -> String {
|
||||
/// The sample for a family with `scripts`, whose own sample in the index is `own`: what the user typed, else the
|
||||
/// preset.
|
||||
pub(crate) fn sample_for<'a>(&self, own: Option<&str>, scripts: impl IntoIterator<Item = &'a str>) -> String {
|
||||
if !self.settings.sample.trim().is_empty() {
|
||||
return self.settings.sample.clone();
|
||||
}
|
||||
@@ -741,7 +803,7 @@ impl FontsPanel {
|
||||
Preset::Numerals => samples::NUMERALS.to_owned(),
|
||||
Preset::Sentence => {
|
||||
let language = self.catalogue.as_ref().ok().zip(self.query.language).and_then(|(c, l)| c.index.languages().get(l));
|
||||
language.and_then(|l| samples::for_language(&l.id)).unwrap_or_else(|| samples::for_scripts(scripts)).to_owned()
|
||||
language.and_then(|l| samples::for_language(&l.id)).or(own).unwrap_or_else(|| samples::for_scripts(scripts)).to_owned()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -876,19 +938,39 @@ impl<'a> FontsPanelView<'a> {
|
||||
panel.prepare(host.as_ref(), view.shell().window.active);
|
||||
let search = ui.scope_id().with("search");
|
||||
let folder = env.folder();
|
||||
let shown = Stack::new().fill().label(words.panel.clone()).command_scope(FontsCommand::SCOPE).show(ui, |ui, root| {
|
||||
let wake = panel.jobs.waker();
|
||||
let panes = if ui.available_width() < WIDE_PANEL { &NARROW_PANES } else { &PANES };
|
||||
let mut begun = false;
|
||||
let mut shown = Stack::new().fill().label(words.panel.clone()).command_scope(FontsCommand::SCOPE).show(ui, |ui, root| {
|
||||
if !std::mem::replace(&mut begun, true) {
|
||||
panel.subsets.begin(root.now(), &wake);
|
||||
}
|
||||
while root.take_command::<FontsCommand>().is_some() {
|
||||
focus::request(ui.ctx(), FocusTarget::Id(search));
|
||||
}
|
||||
root.publish(FontsCommand::Find, CommandState::new());
|
||||
panel.top_bar(ui, &browse, texts.format, search);
|
||||
Grid::new(&PANES).fill().show(ui, |ui, _| {
|
||||
let shown = Grid::new(panes).fill().show(ui, |ui, _| {
|
||||
panel.filters(ui, &texts);
|
||||
panel.main(ui, &texts, &folder, host.as_ref());
|
||||
panel.main(ui, &texts, &folder, host.as_ref())
|
||||
});
|
||||
shown.inner.flatten()
|
||||
});
|
||||
if panel.detail.is_some() && DetailsSheet::new(panel).show(ui).closed {
|
||||
panel.detail = None;
|
||||
// A measuring run has no rows on screen, and a pass that runs again may have the wrong ones.
|
||||
let rerun = craft_ui::runtime::frame::will_rerun(ui.ctx());
|
||||
let real = shown.settle(|_, visible| (!rerun).then(|| panel.request_subsets(visible.take()))).flatten().is_some();
|
||||
if panel.detail.is_some() {
|
||||
if DetailsSheet::new(panel).show(ui).closed {
|
||||
panel.detail = None;
|
||||
}
|
||||
} else {
|
||||
if real {
|
||||
panel.subsets.request_detail(None, &[]);
|
||||
}
|
||||
panel.detail_axes.clear();
|
||||
}
|
||||
if let Some(seconds) = panel.subsets.next_wake() {
|
||||
craft_ui::runtime::frame::request_repaint_after(ui.ctx(), seconds);
|
||||
}
|
||||
panel.consent_prompt(ui, &env, &words, host.as_ref());
|
||||
panel.save_settings(host.as_ref());
|
||||
|
||||
@@ -6,6 +6,7 @@ pub(crate) mod stories;
|
||||
pub(crate) mod cards;
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::{ColumnWidth, DisplayOrder, Flow, ItemSource, Metrics, Proposal, Selection, SelectionChange, SpanLayout};
|
||||
@@ -17,7 +18,7 @@ use craft_ui::choice::{Checkbox, Radio, RadioGroup};
|
||||
use craft_ui::contract::{
|
||||
Access, ActivateOn, Bind, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps, Cx, Entry,
|
||||
ItemOutput, MeasureCx, Name, NoValue, Outcome, PartsCx, Props as _, Role, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _,
|
||||
Sizing, WrapWidth, clicked,
|
||||
Sizing, clicked,
|
||||
};
|
||||
use craft_ui::display::{Badge, Progress, Shade, Spinner, Text};
|
||||
use craft_ui::form::{SliderField, SliderFieldLayout};
|
||||
@@ -33,14 +34,16 @@ use craft_ui::tabs::{Tab as TabItem, TabKind, TabStrip};
|
||||
use craft_ui::text::TextField;
|
||||
use egui::{Id, Pos2, Rect, Response, Ui, Vec2};
|
||||
|
||||
use crate::index::{Category, Index, source_label};
|
||||
use crate::Source;
|
||||
use crate::index::{Category, Family, Index, source_label};
|
||||
use crate::panel::app::{
|
||||
Detail, FontsPanel, FontsPanelWords, Origin, Pending, Preset, Show, Tab, category_label, family_key, regular, source_name, style_count,
|
||||
};
|
||||
use crate::panel::faces::Owner;
|
||||
use crate::panel::jobs::Kind;
|
||||
use crate::panel::specimen::{FontSample, SampleFace};
|
||||
use crate::{Catalog, FaceInfo, Source};
|
||||
use crate::panel::samples;
|
||||
use crate::panel::specimen::{FontSample, HeldFace};
|
||||
use crate::panel::subsets::{Row as SubsetRow, Subsets};
|
||||
|
||||
/// The language filter lists this many matches under its search field.
|
||||
const LANGUAGE_MATCHES: usize = 8;
|
||||
@@ -90,6 +93,9 @@ craft_ui::words! {
|
||||
sample_text: "fontsBrowse.sampleText" = "Sample text";
|
||||
size: "fontsBrowse.size" = "Size";
|
||||
downloads_off: "fontsBrowse.downloadsOff" = "Downloads are off";
|
||||
installs_off_text: "fontsBrowse.installsOffText" = "Nothing is installed until you allow downloads.";
|
||||
previews_unavailable: "fontsBrowse.previewsUnavailable" = "Font previews are unavailable";
|
||||
previews_unreachable: template "fontsBrowse.previewsUnreachable" = "Can't reach the preview server {server}: {error}. Check the address in Settings → Advanced.";
|
||||
downloads_off_text: "fontsBrowse.downloadsOffText" = "Fonts that aren't installed show a sample once you preview them. Nothing is downloaded until you allow it.";
|
||||
cards: "fontsBrowse.cards" = "Families";
|
||||
no_match: "fontsBrowse.noMatch" = "No fonts match";
|
||||
@@ -197,7 +203,7 @@ impl FontsPanel {
|
||||
|
||||
pub(crate) fn filters(&mut self, ui: &mut Ui, texts: &Texts<'_>) {
|
||||
let browse = texts.browse;
|
||||
Stack::new().scroll(Scroll::vertical()).wrap_width(WrapWidth::Column).label(browse.filters.clone()).show(ui, |ui, _| {
|
||||
Stack::new().fill().scroll(Scroll::vertical()).label(browse.filters.clone()).show(ui, |ui, _| {
|
||||
match self.tab {
|
||||
Tab::Catalogue => self.catalogue_filters(ui, texts),
|
||||
Tab::Installed => self.installed_filters(ui, texts),
|
||||
@@ -265,7 +271,7 @@ impl FontsPanel {
|
||||
.activate(ActivateOn::Click)
|
||||
.allow_empty(false)
|
||||
.header(false)
|
||||
.sizing(Sizing::Content)
|
||||
.sizing(Sizing::FillWidth)
|
||||
.natural_height(true)
|
||||
.selection(Bind::given(current))
|
||||
.show_items(ui, &CardKeys::new(&rows, |_| None), &mut |key, _| {
|
||||
@@ -335,20 +341,31 @@ impl FontsPanel {
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn main(&mut self, ui: &mut Ui, texts: &Texts<'_>, folder: &Folder, host: Option<&Arc<Host>>) {
|
||||
Stack::new().fill().show(ui, |ui, _| {
|
||||
/// The toolbar, the notices and the cards; the positions of the catalogue cards on screen, or `None` while it shows
|
||||
/// none.
|
||||
pub(crate) fn main(&mut self, ui: &mut Ui, texts: &Texts<'_>, folder: &Folder, host: Option<&Arc<Host>>) -> Option<Range<usize>> {
|
||||
let shown = Stack::new().fill().show(ui, |ui, _| {
|
||||
self.toolbar(ui, texts.browse);
|
||||
self.subsets.typed(format!("{:?}\n{:?}\n{}", self.settings.preset, self.query.language, self.settings.sample));
|
||||
if let Some(problem) = &self.notice {
|
||||
Notice::new(Tone::Bad, Label::from(problem.text(texts.panel))).show(ui);
|
||||
}
|
||||
if let Some((server, error)) = self.subsets.unreachable() {
|
||||
let text = texts.browse.previews_unreachable.fill(&[("server", server), ("error", error)]);
|
||||
Notice::new(Tone::Warn, Label::from(text)).id_salt("previews").title(texts.browse.previews_unavailable.clone()).show(ui);
|
||||
}
|
||||
match self.tab {
|
||||
Tab::Catalogue => {
|
||||
self.download_note(ui, texts.browse);
|
||||
self.catalogue_list(ui, texts, host);
|
||||
self.catalogue_list(ui, texts, host)
|
||||
}
|
||||
Tab::Installed => {
|
||||
self.installed_list(ui, texts, folder, host);
|
||||
None
|
||||
}
|
||||
Tab::Installed => self.installed_list(ui, texts, folder, host),
|
||||
}
|
||||
});
|
||||
shown.inner.flatten()
|
||||
}
|
||||
|
||||
fn toolbar(&mut self, ui: &mut Ui, browse: &FontsBrowseWords) {
|
||||
@@ -363,7 +380,9 @@ impl FontsPanel {
|
||||
if self.settings.preset != before {
|
||||
self.settings.sample.clear();
|
||||
}
|
||||
let hint = self.sample_for(["Latn"]);
|
||||
let index = self.index();
|
||||
let latin = index.as_ref().and_then(|index| index.sample("Latn")).map(|sample| sample.text.as_str());
|
||||
let hint = self.sample_for(latin, ["Latn"]);
|
||||
TextField::new(browse.sample_text.clone(), Bind::bound(&mut self.settings.sample)).placeholder(Label::from(hint)).show(ui);
|
||||
let mut size = f64::from(self.settings.size);
|
||||
SliderField::new(browse.size.clone(), Bind::bound(&mut size), 12.0..=120.0)
|
||||
@@ -378,7 +397,9 @@ impl FontsPanel {
|
||||
if self.allowed() || self.settings.hide_download_note {
|
||||
return;
|
||||
}
|
||||
let out = Notice::new(Tone::Info, browse.downloads_off_text.clone())
|
||||
// With a preview service, samples show without asking: the note is about installs only.
|
||||
let text = if self.subsets.available() { &browse.installs_off_text } else { &browse.downloads_off_text };
|
||||
let out = Notice::new(Tone::Info, text.clone())
|
||||
.title(browse.downloads_off.clone())
|
||||
.action(NoticeAction::new(browse.allow_downloads.clone()))
|
||||
.dismiss()
|
||||
@@ -391,28 +412,28 @@ impl FontsPanel {
|
||||
}
|
||||
}
|
||||
|
||||
fn catalogue_list(&mut self, ui: &mut Ui, texts: &Texts<'_>, host: Option<&Arc<Host>>) {
|
||||
fn catalogue_list(&mut self, ui: &mut Ui, texts: &Texts<'_>, host: Option<&Arc<Host>>) -> Option<Range<usize>> {
|
||||
let browse = texts.browse;
|
||||
let index = match &self.catalogue {
|
||||
Ok(c) => Arc::clone(&c.index),
|
||||
Err(error) => {
|
||||
Notice::new(Tone::Bad, Label::from(browse.indexes_unreadable.fill(&[("error", error.as_str())]))).show(ui);
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
};
|
||||
self.source_problems(ui, texts, &index, host);
|
||||
Text::new(Label::from(texts.families(self.results.len()))).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
|
||||
if self.results.is_empty() {
|
||||
self.empty(ui, browse, &browse.no_match, &browse.no_match_hint, true);
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
let results = self.results.clone();
|
||||
let events = {
|
||||
let shown = {
|
||||
let me = &*self;
|
||||
let keys = CardKeys::new(&results, |i| index.families().get(i).map(|f| f.family.as_str()));
|
||||
FamilyCards::new(browse.cards.clone()).show_items(ui, &keys, &mut |key, _| FamilyCard::new(me.catalogue_card(&index, *key, texts))).events
|
||||
FamilyCards::new(browse.cards.clone()).show_items(ui, &keys, &mut |key, _| FamilyCard::new(me.catalogue_card(&index, *key, texts)))
|
||||
};
|
||||
for event in events {
|
||||
for event in shown.events {
|
||||
match event {
|
||||
CollectionEvent::Activate(i) => self.detail = Some(Detail::Family(i)),
|
||||
CollectionEvent::Item(i, CardEvent::Install(share)) => self.ask(host, Pending::Install(i, share)),
|
||||
@@ -430,6 +451,42 @@ impl FontsPanel {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(shown.visible)
|
||||
}
|
||||
|
||||
/// Asks the preview service for the subsets of the catalogue cards on screen, at the positions `visible` of the
|
||||
/// results, and round them; cancels what the list asked for when it shows no card.
|
||||
pub(crate) fn request_subsets(&mut self, visible: Option<Range<usize>>) {
|
||||
let Some((visible, index)) = visible.zip(self.index()) else {
|
||||
self.subsets.cancel_all();
|
||||
return;
|
||||
};
|
||||
let window = Subsets::window(&visible, self.results.len());
|
||||
let rows: Vec<Option<SubsetRow<'_>>> = window.clone().map(|n| self.subset_row(&index, *self.results.get(n)?)).collect();
|
||||
self.subsets.request(&index, window.start, &rows, visible);
|
||||
}
|
||||
|
||||
/// The family at `i` in the index as a row drawn with a subset: `None` when it is installed or previewed whole.
|
||||
fn subset_row<'a>(&self, index: &'a Index, i: usize) -> Option<SubsetRow<'a>> {
|
||||
let family = index.families().get(i)?;
|
||||
if self.installed_by_name.contains_key(&family.family.to_lowercase())
|
||||
|| self.previewed.contains_key(&family_key(&family.source, &family.family))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((family, self.family_sample(index, family)))
|
||||
}
|
||||
|
||||
/// The sample a family of the index shows.
|
||||
pub(crate) fn family_sample(&self, index: &Index, family: &Family) -> String {
|
||||
self.sample_for(samples::of_family(index, family), family.scripts.iter().map(String::as_str))
|
||||
}
|
||||
|
||||
/// The sample the installed family `name` shows: that of the index's family of the name, else the preset's.
|
||||
pub(crate) fn installed_sample(&self, name: &str) -> String {
|
||||
let index = self.index();
|
||||
let family = index.as_deref().and_then(|index| Some((index, index.family(name)?)));
|
||||
family.map_or_else(|| self.sample_for(None, []), |(index, family)| self.family_sample(index, family))
|
||||
}
|
||||
|
||||
/// Sources that couldn't be loaded, one note each above the list; the others show as usual.
|
||||
@@ -519,6 +576,8 @@ impl FontsPanel {
|
||||
let key = family_key(&family.source, &family.family);
|
||||
let installed = self.installed_by_name.get(&family.family.to_lowercase()).and_then(|f| regular(f)).cloned();
|
||||
let previewed = self.previewed.get(&key).and_then(|f| regular(f)).cloned();
|
||||
let row = self.subset_row(index, i);
|
||||
let drawn = row.as_ref().is_some_and(|row| self.subsets.draws(index, row));
|
||||
let state = if let Some(job) = self.jobs.of(&family.source, &family.family) {
|
||||
CardState::Running(job.kind, job.fraction())
|
||||
} else if let Some(failure) = self.failed.get(&key) {
|
||||
@@ -526,24 +585,16 @@ impl FontsPanel {
|
||||
} else if installed.is_some() {
|
||||
CardState::Installed
|
||||
} else {
|
||||
CardState::Offer { preview: !self.previewed.contains_key(&key), destinations: self.installer.available_to_all_supported() }
|
||||
CardState::Offer { preview: !drawn && !self.previewed.contains_key(&key), destinations: self.installer.available_to_all_supported() }
|
||||
};
|
||||
let (source, curated) = source_label(index, family);
|
||||
let meta = [texts.styles(style_count(family)), category_label(texts.panel, family), source.to_owned()].join(" · ");
|
||||
let face = match (installed, previewed) {
|
||||
(Some(face), _) => Some((Owner::Installed, face, Arc::clone(&self.catalog))),
|
||||
(None, Some(face)) => Some((Owner::Preview, face, Arc::clone(&self.previews))),
|
||||
(None, None) => None,
|
||||
(Some(face), _) => Some(HeldFace::local(Owner::Installed, face, &self.catalog)),
|
||||
(None, Some(face)) => Some(HeldFace::local(Owner::Preview, face, &self.previews)),
|
||||
(None, None) => row.as_ref().and_then(|row| self.subsets.font(index, row)).map(HeldFace::Subset),
|
||||
};
|
||||
CardData {
|
||||
name: family.family.clone(),
|
||||
meta,
|
||||
sample: self.sample_for(family.scripts.iter().map(String::as_str)),
|
||||
points: self.settings.size,
|
||||
curated,
|
||||
state,
|
||||
face,
|
||||
}
|
||||
CardData { name: family.family.clone(), meta, sample: self.family_sample(index, family), points: self.settings.size, curated, state, face }
|
||||
}
|
||||
|
||||
/// What an installed family's card shows.
|
||||
@@ -558,15 +609,14 @@ impl FontsPanel {
|
||||
None => CardState::System,
|
||||
},
|
||||
};
|
||||
let scripts = self.index().and_then(|index| index.family(&family.name).map(|f| f.scripts.clone())).unwrap_or_default();
|
||||
CardData {
|
||||
name: family.name.clone(),
|
||||
meta,
|
||||
sample: self.sample_for(scripts.iter().map(String::as_str)),
|
||||
sample: self.installed_sample(&family.name),
|
||||
points: self.settings.size,
|
||||
curated: true,
|
||||
state,
|
||||
face: regular(&family.faces).cloned().map(|face| (Owner::Installed, face, Arc::clone(&self.catalog))),
|
||||
face: regular(&family.faces).cloned().map(|face| HeldFace::local(Owner::Installed, face, &self.catalog)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,10 @@ use craft_ui::buttons::{SplitButton, SplitOutput};
|
||||
use craft_ui::contract::{Entry, Props as _, Styled as _, clicked};
|
||||
|
||||
use super::{
|
||||
Access, Arc, Badge, Button, Catalog, Collection, CollectionProps, CollectionResponse, Common, Component, ComponentStyle, ContainerProps, Cow, Cx,
|
||||
DisplayOrder, Emphasis, FaceInfo, Flow, FontSample, FontsBrowseWords, Ink, ItemOutput, ItemSource, Kind, Label, Link, MeasureCx, Metrics, Name,
|
||||
NoValue, Outcome, Owner, PartsCx, Pos2, Progress, Proposal, Rect, Response, Role, RuleKind, SampleFace, SelectMode, Selection, Shade, Sizing,
|
||||
SpanLayout, Stateful, StyleCx, Text, TextLook, TextRun, Tone, TypeRole, Variant, Vec2,
|
||||
Access, Badge, Button, Collection, CollectionProps, CollectionResponse, Common, Component, ComponentStyle, ContainerProps, Cow, Cx, DisplayOrder,
|
||||
Emphasis, Flow, FontSample, FontsBrowseWords, HeldFace, Ink, ItemOutput, ItemSource, Kind, Label, Link, MeasureCx, Metrics, Name, NoValue,
|
||||
Outcome, PartsCx, Pos2, Progress, Proposal, Rect, Response, Role, RuleKind, SelectMode, Selection, Shade, Sizing, SpanLayout, Stateful, StyleCx,
|
||||
Text, TextLook, TextRun, Tone, TypeRole, Variant, Vec2,
|
||||
};
|
||||
use craft_ui::primitives::RectSide;
|
||||
|
||||
@@ -66,8 +66,8 @@ pub struct CardData {
|
||||
pub curated: bool,
|
||||
/// What is at the reading end.
|
||||
pub state: CardState,
|
||||
/// The face the sample is drawn in, and whose catalog holds it.
|
||||
pub face: Option<(Owner, FaceInfo, Arc<Catalog>)>,
|
||||
/// The face the sample is drawn in.
|
||||
pub(crate) face: Option<HeldFace>,
|
||||
}
|
||||
|
||||
/// The pieces of a card at the reading end, in reading order.
|
||||
@@ -318,16 +318,8 @@ impl FamilyCard {
|
||||
ends
|
||||
}
|
||||
|
||||
/// The face the sample is drawn in: the card's own, or none.
|
||||
fn face(&self) -> SampleFace<'_> {
|
||||
match &self.data.face {
|
||||
Some((owner, face, catalog)) => SampleFace::Face { catalog, owner: *owner, face },
|
||||
None => SampleFace::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
fn sample<'a>(&'a self, words: &FontsBrowseWords) -> FontSample<'a> {
|
||||
FontSample::new(words.card_sample.clone(), self.data.sample.as_str(), self.face(), self.data.points)
|
||||
FontSample::new(words.card_sample.clone(), self.data.sample.as_str(), HeldFace::sample(self.data.face.as_ref()), self.data.points)
|
||||
}
|
||||
|
||||
/// The sizes of the parts at `width`.
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
# Arabic (ar) rows of the Fonts panel's words, for an app's shared catalog.
|
||||
# Format: context<TAB>source<TAB>translation; @id rows name a word by its id, @plural rows list the locale's plural forms.
|
||||
# Style and weight names (Regular, Bold, Italic), licence names and product names stay in English.
|
||||
@id fontsPanel.sansSerif بلا زوائد
|
||||
@id fontsPanel.serif بزوائد
|
||||
@id fontsPanel.display عرض
|
||||
@id fontsPanel.handwriting خط اليد
|
||||
@id fontsPanel.monospace أحادي المسافة
|
||||
@id fontsPanel.fontStore متجر الخطوط
|
||||
@id fontsPanel.system النظام
|
||||
@id fontsPanel.settingFailed تعذّر حفظ إعداد التنزيل: {error}
|
||||
@id fontsPanel.consentNote يبقى التنزيل مسموحًا حتى توقفه.
|
||||
@id fontsPanel.consentAllow تنزيل
|
||||
@id fontsBrowse.tabBrowse تصفّح
|
||||
@id fontsBrowse.tabInstalled مثبّت
|
||||
@id fontsBrowse.search بحث
|
||||
@id fontsBrowse.searchCatalogue ابحث في الخطوط بالاسم
|
||||
@id fontsBrowse.searchInstalled ابحث في الخطوط المثبّتة
|
||||
@id fontsBrowse.downloads التنزيلات
|
||||
@id fontsBrowse.allowDownloads السماح بالتنزيل
|
||||
@id fontsBrowse.category الفئة
|
||||
@id fontsBrowse.allCategories كل الفئات
|
||||
@id fontsBrowse.language اللغة
|
||||
@id fontsBrowse.anyLanguage أي لغة
|
||||
@id fontsBrowse.languagePlaceholder الاسم بالإنجليزية أو باللغة نفسها
|
||||
@id fontsBrowse.findLanguage ابحث عن لغة
|
||||
@id fontsBrowse.script نظام الكتابة
|
||||
@id fontsBrowse.anyScript أي نظام كتابة
|
||||
@id fontsBrowse.source المصدر
|
||||
@id fontsBrowse.allSources كل المصادر
|
||||
@id fontsBrowse.show إظهار
|
||||
@id fontsBrowse.allFonts كل الخطوط
|
||||
@id fontsBrowse.installed مثبّت
|
||||
@id fontsBrowse.notInstalled غير مثبّت
|
||||
@id fontsBrowse.clearFilters مسح عوامل التصفية
|
||||
@id fontsBrowse.installedNote تستخدم كل تطبيقات Craft الخطوط الموجودة في متجر الخطوط. تُضاف خطوط النظام وتُزال بأدوات الخطوط في نظامك.
|
||||
@id fontsBrowse.sample العينة
|
||||
@id fontsBrowse.sentence جملة
|
||||
@id fontsBrowse.alphabet الأبجدية
|
||||
@id fontsBrowse.numerals الأرقام والرموز
|
||||
@id fontsBrowse.sampleText نص العينة
|
||||
@id fontsBrowse.size الحجم
|
||||
@id fontsBrowse.downloadsOff التنزيل متوقف
|
||||
@id fontsBrowse.downloadsOffText تظهر عينة الخط غير المثبّت بعد معاينته. لا يُنزَّل شيء حتى تسمح بذلك.
|
||||
@id fontsBrowse.noMatch لا توجد خطوط مطابقة
|
||||
@id fontsBrowse.noMatchHint جرّب اسمًا آخر أو عوامل تصفية أقل.
|
||||
@id fontsBrowse.clearSearch مسح البحث وعوامل التصفية
|
||||
@id fontsBrowse.indexesUnreadable تتعذّر قراءة فهارس الخطوط: {error}
|
||||
@id fontsBrowse.sourceError {source}: {error}
|
||||
@id fontsBrowse.tryAgain إعادة المحاولة
|
||||
@id fontsBrowse.looking جارٍ البحث عن الخطوط المثبّتة…
|
||||
@id fontsBrowse.noInstalled لا توجد خطوط مثبّتة مطابقة
|
||||
@id fontsBrowse.installedEmpty تظهر هنا الخطوط التي تثبّتها من «تصفّح»، لكل تطبيقات Craft.
|
||||
@id fontsBrowse.tryName جرّب اسمًا آخر.
|
||||
@id fontsBrowse.installing جارٍ التثبيت
|
||||
@id fontsBrowse.removing جارٍ الإزالة
|
||||
@id fontsBrowse.downloading جارٍ التنزيل
|
||||
@id fontsBrowse.retry إعادة المحاولة
|
||||
@id fontsBrowse.failedInstall تعذّر التثبيت
|
||||
@id fontsBrowse.failedRemove تعذّرت الإزالة
|
||||
@id fontsBrowse.failedDownload تعذّر التنزيل
|
||||
@id fontsBrowse.install تثبيت
|
||||
@id fontsBrowse.installFamily تثبيت {family}
|
||||
@id fontsBrowse.preview معاينة
|
||||
@id fontsBrowse.previewFamily معاينة {family}
|
||||
@id fontsBrowse.remove إزالة
|
||||
@id fontsBrowse.removeFamily إزالة {family}
|
||||
@id fontsBrowse.notCurated غير مراجَع
|
||||
@id fontsBrowse.notCuratedTip تأتي هذه العائلة من مصدر أضفته. لا يراجعها Craft.
|
||||
@id fontsBrowse.cardSample العينة
|
||||
@id fontDetails.designedBy تصميم {designer}
|
||||
@id fontDetails.installing جارٍ التثبيت
|
||||
@id fontDetails.removing جارٍ الإزالة
|
||||
@id fontDetails.downloading جارٍ التنزيل
|
||||
@id fontDetails.installed مثبّت
|
||||
@id fontDetails.installedOnSystem مثبّت على هذا النظام
|
||||
@id fontDetails.installAll تثبيت الكل
|
||||
@id fontDetails.removeAll إزالة الكل
|
||||
@id fontDetails.preview معاينة
|
||||
@id fontDetails.install تثبيت
|
||||
@id fontDetails.remove إزالة
|
||||
@id fontDetails.installStyle تثبيت {style}
|
||||
@id fontDetails.removeStyle إزالة {style}
|
||||
@id fontDetails.downloadSizeLine تنزيل {size}
|
||||
@id fontDetails.previewNote تنزّل المعاينة هذا الخط ({size}) لهذه الجلسة فقط دون تثبيته.
|
||||
@id fontDetails.notCurated غير مراجَع
|
||||
@id fontDetails.notCuratedNote تأتي هذه العائلة من مصدر أضفته ({url}). لا يراجع Craft خطوطه ولا تراخيصها.
|
||||
@id fontDetails.couldntInstall تعذّر التثبيت
|
||||
@id fontDetails.couldntRemove تعذّرت الإزالة
|
||||
@id fontDetails.couldntDownload تعذّر التنزيل
|
||||
@id fontDetails.retry إعادة المحاولة
|
||||
@id fontDetails.systemFontsNote تُزال خطوط النظام بأدوات الخطوط في نظامك.
|
||||
@id fontDetails.systemFontsRemoval يُزال بأدوات الخطوط في نظامك
|
||||
@id fontDetails.source المصدر
|
||||
@id fontDetails.designer المصمم
|
||||
@id fontDetails.licence الترخيص
|
||||
@id fontDetails.stylesFact الأنماط
|
||||
@id fontDetails.filesFact الملفات
|
||||
@id fontDetails.downloadSize حجم التنزيل
|
||||
@id fontDetails.scripts أنظمة الكتابة
|
||||
@id fontDetails.languages اللغات · {n}
|
||||
@id fontDetails.languagesMore {list} و{n} غيرها
|
||||
@id fontSources.remove إزالة
|
||||
@id fontSources.removeSource إزالة {source}
|
||||
@id fontSources.notCurated غير مراجَع
|
||||
@id fontSources.changed تغيّر منذ إضافته
|
||||
@id fontSources.changedNote الفهرس على هذا العنوان ليس الذي نُزِّل منه أول مرة. تحقّق من المصدر قبل التثبيت منه.
|
||||
@id fontSources.addASource إضافة مصدر
|
||||
@id fontSources.add إضافة
|
||||
@id fontSources.indexAddress عنوان الفهرس
|
||||
@id fontSources.addWarning المصدر الذي تضيفه لا يُراجَع: أضف فقط الفهارس التي تثق بها. يُتحقَّق من كل خط مقابل فهرسه قبل استخدامه.
|
||||
@id fontSources.downloading جارٍ تنزيل المصادر…
|
||||
@id fontSources.update تحديث المصادر
|
||||
@id fontSources.allowToUpdate اسمح بالتنزيل للتحديث
|
||||
@id fontSources.added أُضيف. يُنزَّل عند السماح بالتنزيل.
|
||||
@id fontSources.couldntAdd تعذّرت إضافة المصدر: {error}
|
||||
@id fontSources.couldntRemove تعذّرت إزالة المصدر: {error}
|
||||
@id common.cancel إلغاء
|
||||
@id common.close إغلاق
|
||||
@plural {n} style|{n} styles {n} نمط|{n} نمط|{n} نمط|{n} أنماط|{n} نمطًا|{n} نمط
|
||||
@plural {n} family|{n} families {n} عائلة|{n} عائلة|{n} عائلة|{n} عائلات|{n} عائلة|{n} عائلة
|
||||
@plural {n} font source couldn't be loaded|{n} font sources couldn't be loaded تعذّر تحميل {n} مصدر خطوط|تعذّر تحميل {n} مصدر خطوط|تعذّر تحميل {n} مصدر خطوط|تعذّر تحميل {n} مصادر خطوط|تعذّر تحميل {n} مصدرًا للخطوط|تعذّر تحميل {n} مصدر خطوط
|
||||
@plural {n} style installed|{n} styles installed {n} نمط مثبّت|{n} نمط مثبّت|{n} نمط مثبّت|{n} أنماط مثبّتة|{n} نمطًا مثبّتًا|{n} نمط مثبّت
|
||||
|
@@ -0,0 +1,123 @@
|
||||
# Japanese (ja) rows of the Fonts panel's words, for an app's shared catalog.
|
||||
# Format: context<TAB>source<TAB>translation; @id rows name a word by its id, @plural rows list the locale's plural forms.
|
||||
# Style and weight names (Regular, Bold, Italic), licence names and product names stay in English.
|
||||
@id fontsPanel.sansSerif サンセリフ
|
||||
@id fontsPanel.serif セリフ
|
||||
@id fontsPanel.display ディスプレイ
|
||||
@id fontsPanel.handwriting 手書き
|
||||
@id fontsPanel.monospace 等幅
|
||||
@id fontsPanel.fontStore フォントストア
|
||||
@id fontsPanel.system システム
|
||||
@id fontsPanel.settingFailed ダウンロードの設定を保存できませんでした: {error}
|
||||
@id fontsPanel.consentNote ダウンロードは、オフにするまで許可されたままです。
|
||||
@id fontsPanel.consentAllow ダウンロード
|
||||
@id fontsBrowse.tabBrowse 探す
|
||||
@id fontsBrowse.tabInstalled インストール済み
|
||||
@id fontsBrowse.search 検索
|
||||
@id fontsBrowse.searchCatalogue フォントを名前で検索
|
||||
@id fontsBrowse.searchInstalled インストール済みのフォントを検索
|
||||
@id fontsBrowse.downloads ダウンロード
|
||||
@id fontsBrowse.allowDownloads ダウンロードを許可
|
||||
@id fontsBrowse.category カテゴリ
|
||||
@id fontsBrowse.allCategories すべてのカテゴリ
|
||||
@id fontsBrowse.language 言語
|
||||
@id fontsBrowse.anyLanguage すべての言語
|
||||
@id fontsBrowse.languagePlaceholder 英語名またはその言語での名前
|
||||
@id fontsBrowse.findLanguage 言語を検索
|
||||
@id fontsBrowse.script 文字体系
|
||||
@id fontsBrowse.anyScript すべての文字体系
|
||||
@id fontsBrowse.source 入手元
|
||||
@id fontsBrowse.allSources すべての入手元
|
||||
@id fontsBrowse.show 表示
|
||||
@id fontsBrowse.allFonts すべてのフォント
|
||||
@id fontsBrowse.installed インストール済み
|
||||
@id fontsBrowse.notInstalled 未インストール
|
||||
@id fontsBrowse.clearFilters 絞り込みを解除
|
||||
@id fontsBrowse.installedNote フォントストアのフォントはすべての Craft アプリで使えます。システムフォントの追加と削除は、システムのフォント管理ツールで行います。
|
||||
@id fontsBrowse.sample サンプル
|
||||
@id fontsBrowse.sentence 文
|
||||
@id fontsBrowse.alphabet アルファベット
|
||||
@id fontsBrowse.numerals 数字と記号
|
||||
@id fontsBrowse.sampleText サンプルテキスト
|
||||
@id fontsBrowse.size サイズ
|
||||
@id fontsBrowse.downloadsOff ダウンロードはオフです
|
||||
@id fontsBrowse.downloadsOffText インストールしていないフォントは、プレビューするとサンプルが表示されます。許可するまで何もダウンロードされません。
|
||||
@id fontsBrowse.noMatch 一致するフォントはありません
|
||||
@id fontsBrowse.noMatchHint 別の名前を試すか、絞り込みを減らしてください。
|
||||
@id fontsBrowse.clearSearch 検索と絞り込みを解除
|
||||
@id fontsBrowse.indexesUnreadable フォントの一覧を読み込めません: {error}
|
||||
@id fontsBrowse.sourceError {source}: {error}
|
||||
@id fontsBrowse.tryAgain もう一度試す
|
||||
@id fontsBrowse.looking インストール済みのフォントを探しています…
|
||||
@id fontsBrowse.noInstalled 一致するインストール済みフォントはありません
|
||||
@id fontsBrowse.installedEmpty 「探す」からインストールしたフォントがここに表示され、すべての Craft アプリで使えます。
|
||||
@id fontsBrowse.tryName 別の名前を試してください。
|
||||
@id fontsBrowse.installing インストール中
|
||||
@id fontsBrowse.removing 削除中
|
||||
@id fontsBrowse.downloading ダウンロード中
|
||||
@id fontsBrowse.retry 再試行
|
||||
@id fontsBrowse.failedInstall インストールできませんでした
|
||||
@id fontsBrowse.failedRemove 削除できませんでした
|
||||
@id fontsBrowse.failedDownload ダウンロードできませんでした
|
||||
@id fontsBrowse.install インストール
|
||||
@id fontsBrowse.installFamily {family} をインストール
|
||||
@id fontsBrowse.preview プレビュー
|
||||
@id fontsBrowse.previewFamily {family} をプレビュー
|
||||
@id fontsBrowse.remove 削除
|
||||
@id fontsBrowse.removeFamily {family} を削除
|
||||
@id fontsBrowse.notCurated 未審査
|
||||
@id fontsBrowse.notCuratedTip このファミリーは追加したソースのものです。Craft は審査していません。
|
||||
@id fontsBrowse.cardSample サンプル
|
||||
@id fontDetails.designedBy デザイン: {designer}
|
||||
@id fontDetails.installing インストール中
|
||||
@id fontDetails.removing 削除中
|
||||
@id fontDetails.downloading ダウンロード中
|
||||
@id fontDetails.installed インストール済み
|
||||
@id fontDetails.installedOnSystem このシステムにインストール済み
|
||||
@id fontDetails.installAll すべてインストール
|
||||
@id fontDetails.removeAll すべて削除
|
||||
@id fontDetails.preview プレビュー
|
||||
@id fontDetails.install インストール
|
||||
@id fontDetails.remove 削除
|
||||
@id fontDetails.installStyle {style} をインストール
|
||||
@id fontDetails.removeStyle {style} を削除
|
||||
@id fontDetails.downloadSizeLine ダウンロード {size}
|
||||
@id fontDetails.previewNote プレビューでは、このフォント ({size}) をこのセッションの間だけダウンロードし、インストールはしません。
|
||||
@id fontDetails.notCurated 未審査
|
||||
@id fontDetails.notCuratedNote このファミリーは追加したソース ({url}) のものです。Craft はフォントもライセンスも審査していません。
|
||||
@id fontDetails.couldntInstall インストールできませんでした
|
||||
@id fontDetails.couldntRemove 削除できませんでした
|
||||
@id fontDetails.couldntDownload ダウンロードできませんでした
|
||||
@id fontDetails.retry 再試行
|
||||
@id fontDetails.systemFontsNote システムフォントは、システムのフォント管理ツールで削除します。
|
||||
@id fontDetails.systemFontsRemoval システムのフォントツールで削除します
|
||||
@id fontDetails.source 入手元
|
||||
@id fontDetails.designer デザイナー
|
||||
@id fontDetails.licence ライセンス
|
||||
@id fontDetails.stylesFact スタイル
|
||||
@id fontDetails.filesFact ファイル
|
||||
@id fontDetails.downloadSize ダウンロードサイズ
|
||||
@id fontDetails.scripts 文字体系
|
||||
@id fontDetails.languages 言語 · {n}
|
||||
@id fontDetails.languagesMore {list} ほか {n} 言語
|
||||
@id fontSources.remove 削除
|
||||
@id fontSources.removeSource {source} を削除
|
||||
@id fontSources.notCurated 未審査
|
||||
@id fontSources.changed 追加後に変更あり
|
||||
@id fontSources.changedNote このアドレスの一覧は、最初にダウンロードしたものと異なります。インストールする前にソースを確認してください。
|
||||
@id fontSources.addASource ソースを追加
|
||||
@id fontSources.add 追加
|
||||
@id fontSources.indexAddress 一覧のアドレス
|
||||
@id fontSources.addWarning 追加したソースは審査されません。信頼できる一覧だけを追加してください。どのフォントも、使う前に一覧と照合されます。
|
||||
@id fontSources.downloading ソースをダウンロードしています…
|
||||
@id fontSources.update ソースを更新
|
||||
@id fontSources.allowToUpdate 更新するにはダウンロードを許可してください
|
||||
@id fontSources.added 追加しました。ダウンロードを許可するとダウンロードされます。
|
||||
@id fontSources.couldntAdd ソースを追加できませんでした: {error}
|
||||
@id fontSources.couldntRemove ソースを削除できませんでした: {error}
|
||||
@id common.cancel キャンセル
|
||||
@id common.close 閉じる
|
||||
@plural {n} style|{n} styles {n} スタイル
|
||||
@plural {n} family|{n} families {n} ファミリー
|
||||
@plural {n} font source couldn't be loaded|{n} font sources couldn't be loaded {n} 件のフォントソースを読み込めませんでした
|
||||
@plural {n} style installed|{n} styles installed インストール済み {n} スタイル
|
||||
|
@@ -1,10 +1,15 @@
|
||||
//! The details sheet: a family's every style in its own face, its facts and languages, and
|
||||
//! installing or removing it whole or a style at a time.
|
||||
//!
|
||||
//! With a preview service, the styles not installed draw with its subsets: a static file's own, and one subset of each
|
||||
//! variable file with every axis kept, drawn at each named instance and at the values of the file's axis sliders. The
|
||||
//! axis values go with the text drawn, not with the face registered, so the sliders never register the face again.
|
||||
|
||||
pub(crate) mod rows;
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -13,24 +18,33 @@ use craft_host::Host;
|
||||
use craft_theme::variant::{Emphasis, Tone};
|
||||
use craft_ui::buttons::{Button, Link, SplitButton};
|
||||
use craft_ui::contract::overlay::Outside;
|
||||
use craft_ui::contract::{Bind, CollectionEvent, Entry, NoValue, Outcome, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked};
|
||||
use craft_ui::contract::{
|
||||
Bind, CollectionEvent, Entry, NoValue, Outcome, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked,
|
||||
};
|
||||
use craft_ui::dialog::Dialog;
|
||||
use craft_ui::display::{Badge, Progress, Shade, Text};
|
||||
use craft_ui::layout_components::{Grid, Row, Stack};
|
||||
use craft_ui::notices::{Notice, NoticeAction};
|
||||
use craft_ui::primitives::Wrap;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::focus::Initial;
|
||||
use craft_ui::style::Variant;
|
||||
use craft_ui::text::TextField;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
use self::rows::{Action, Lines, StyleLine, StyleList, StyleRow};
|
||||
use crate::axes::{AxisSliders, AxisValues, FontAxis, OpticalSize, read_axes, shown_axes};
|
||||
use crate::index::{Family, FontFile, Index, script_name, source_label};
|
||||
use crate::panel::app::{
|
||||
Detail, FontsPanel, FontsPanelWords, NotCopied, Pending, category_label, family_key, regular, source_name, style_count, style_name,
|
||||
};
|
||||
use crate::panel::faces::Owner;
|
||||
use crate::panel::jobs::Kind;
|
||||
use crate::panel::specimen::{FontSample, SampleFace};
|
||||
use crate::{Catalog, FaceInfo, Source};
|
||||
use crate::panel::legal::{Legal, legal_key};
|
||||
use crate::panel::specimen::{FontSample, HeldFace};
|
||||
use crate::panel::subsets::SubsetFont;
|
||||
use crate::store::LegalText;
|
||||
use crate::{FaceInfo, Source};
|
||||
|
||||
/// The sample is at least this many points: the sheet shows styles, not thumbnails.
|
||||
const MIN_SAMPLE_POINTS: f32 = 24.0;
|
||||
@@ -39,12 +53,17 @@ const HERO_POINTS: f32 = 96.0;
|
||||
/// The most languages the sheet lists; the rest are counted.
|
||||
const LANGUAGES_SHOWN: usize = 60;
|
||||
|
||||
/// The most lines of a licence or NOTICE text in view; the rest scrolls.
|
||||
const LEGAL_LINES: usize = 10;
|
||||
/// The lines its box has for a shorter text: the least of a multi-line field.
|
||||
const LEGAL_LEAST_LINES: usize = 2;
|
||||
|
||||
/// The sheet's sliders show the face's optical sizes, which its samples are drawn at.
|
||||
const OPTICAL_SIZE: OpticalSize = OpticalSize::Slider;
|
||||
|
||||
/// The facts' labels over their values.
|
||||
const FACT_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)];
|
||||
|
||||
/// The installed catalog and the preview catalog, which the faces of the two owners load from.
|
||||
type Catalogs = (Arc<Catalog>, Arc<Catalog>);
|
||||
|
||||
craft_ui::words! {
|
||||
/// The details sheet's words, English by default.
|
||||
#[non_exhaustive]
|
||||
@@ -77,6 +96,16 @@ craft_ui::words! {
|
||||
preview: "fontDetails.preview" = "Preview";
|
||||
install: "fontDetails.install" = "Install";
|
||||
remove: "fontDetails.remove" = "Remove";
|
||||
copyright: "fontDetails.copyright" = "Copyright";
|
||||
/// `{url}`.
|
||||
upstream: template "fontDetails.upstream" = "Upstream: {url}";
|
||||
show_licence: "fontDetails.showLicence" = "Show licence text";
|
||||
show_notice: "fontDetails.showNotice" = "Show notice";
|
||||
licence_text: "fontDetails.licenceText" = "Licence text";
|
||||
notice_text: "fontDetails.noticeText" = "Notice";
|
||||
loading_text: "fontDetails.loadingText" = "Loading…";
|
||||
/// The style of a variable file that names no instances.
|
||||
default_style: "fontDetails.defaultStyle" = "Default";
|
||||
/// `{style}`.
|
||||
install_style: template "fontDetails.installStyle" = "Install {style}";
|
||||
/// `{style}`.
|
||||
@@ -172,6 +201,34 @@ enum Do {
|
||||
Ask(Pending),
|
||||
Remove { faces: Vec<FaceInfo>, whole: bool },
|
||||
AvailableToAll { files: Vec<PathBuf>, on: bool },
|
||||
ReadLegal(LegalText),
|
||||
}
|
||||
|
||||
/// A licence or NOTICE text as the sheet shows it.
|
||||
enum LegalShown {
|
||||
/// Not read yet.
|
||||
Offer,
|
||||
Loading,
|
||||
Text(String),
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// The licence and NOTICE texts `family` has, as far as they are read.
|
||||
fn legal_texts(panel: &FontsPanel, family: &Family) -> Vec<(LegalText, LegalShown)> {
|
||||
let files = [(LegalText::Notice, family.notice_file.is_some()), (LegalText::License, family.license_file_name().is_some())];
|
||||
files
|
||||
.into_iter()
|
||||
.filter(|(_, has)| *has)
|
||||
.filter_map(|(which, _)| {
|
||||
let shown = match panel.legal.get(&legal_key(family, which)) {
|
||||
None => LegalShown::Offer,
|
||||
Some(Legal::Loading(_)) => LegalShown::Loading,
|
||||
Some(Legal::Ready(text)) => LegalShown::Text(text.clone()?),
|
||||
Some(Legal::Failed(error)) => LegalShown::Failed(error.clone()),
|
||||
};
|
||||
Some((which, shown))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The job running for the whole family, as the header shows it.
|
||||
@@ -260,12 +317,19 @@ fn not_copied_text(words: &DetailsWords, not_copied: &NotCopied) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable file drawn by the preview service, and its axes.
|
||||
struct FileAxes {
|
||||
sha256: String,
|
||||
label: String,
|
||||
axes: Vec<FontAxis>,
|
||||
}
|
||||
|
||||
/// Everything the sheet shows, read from the panel before the pass draws it.
|
||||
struct Sheet {
|
||||
eyebrow: String,
|
||||
title: String,
|
||||
byline: Option<String>,
|
||||
hero: Option<(Owner, FaceInfo)>,
|
||||
hero: Option<HeldFace>,
|
||||
run: Option<Run>,
|
||||
badge: Option<Label>,
|
||||
/// The family's position in the index when it can be installed whole.
|
||||
@@ -281,9 +345,15 @@ struct Sheet {
|
||||
uncurated: Option<String>,
|
||||
failure: Option<Failed>,
|
||||
lines: Vec<StyleLine>,
|
||||
/// The family's files, by position, whose styles the preview service draws.
|
||||
subset_files: Vec<usize>,
|
||||
/// The variable files among them, with the sliders of their axes.
|
||||
axes: Vec<FileAxes>,
|
||||
facts: Vec<(Label, String)>,
|
||||
languages: Vec<String>,
|
||||
scripts: Vec<String>,
|
||||
/// The web page of the family's own project.
|
||||
upstream: Option<String>,
|
||||
legal: Vec<(LegalText, LegalShown)>,
|
||||
/// The family's position in the index; none for an installed family, whose styles cannot be installed.
|
||||
index: Option<usize>,
|
||||
sample: String,
|
||||
@@ -326,26 +396,33 @@ impl<'a> DetailsSheet<'a> {
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<DetailsWords>();
|
||||
let host: Option<Arc<Host>> = env.view().host().cloned();
|
||||
panel.read_notice(host.as_ref());
|
||||
let Some(sheet) = Sheet::read(panel, &env, &words) else {
|
||||
panel.detail = None;
|
||||
return DetailsOutput { response: ui.response(), closed: true };
|
||||
};
|
||||
let catalogs: Catalogs = (Arc::clone(&panel.catalog), Arc::clone(&panel.previews));
|
||||
let points = panel.settings.size.max(MIN_SAMPLE_POINTS);
|
||||
let mut todo: Vec<Do> = Vec::new();
|
||||
let mut open = true;
|
||||
let shown = Dialog::prompt(sheet.title.clone())
|
||||
// The sheet is for reading: no field of it takes the keyboard when it opens.
|
||||
let mut shown = Dialog::prompt(sheet.title.clone())
|
||||
.initial_focus(Initial::Keep)
|
||||
.overlay(|overlay| {
|
||||
let dismiss = overlay.dismiss.outside(Outside::Absorb);
|
||||
overlay.dismiss(dismiss)
|
||||
})
|
||||
.opened(Bind::bound(&mut open))
|
||||
.show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
sheet.header(ui, &env, &words, &catalogs, &mut todo);
|
||||
sheet.body(ui, &env, &words, &catalogs, points, &mut todo);
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
sheet.header(ui, &env, &words, &mut todo);
|
||||
sheet.body(ui, &env, &words, points, &mut panel.detail_axes, &mut todo);
|
||||
});
|
||||
});
|
||||
let index = panel.index();
|
||||
let family = sheet.index.zip(index.as_deref()).and_then(|(i, index)| Some((index, index.families().get(i)?, sheet.sample.as_str())));
|
||||
if !craft_ui::runtime::frame::will_rerun(ui.ctx()) {
|
||||
shown.settle(|_, ()| panel.subsets.request_detail(family, &sheet.subset_files));
|
||||
}
|
||||
let closed = shown.output.closed.is_some();
|
||||
if closed {
|
||||
panel.detail = None;
|
||||
@@ -354,6 +431,11 @@ impl<'a> DetailsSheet<'a> {
|
||||
match action {
|
||||
Do::Ask(pending) => panel.ask(host.as_ref(), pending),
|
||||
Do::Remove { faces, whole } => panel.remove(host.as_ref(), &sheet.title, &faces, whole),
|
||||
Do::ReadLegal(which) => {
|
||||
if let Some(i) = sheet.index {
|
||||
panel.load_legal(host.as_ref(), i, which);
|
||||
}
|
||||
}
|
||||
Do::AvailableToAll { files, on } => panel.set_available_to_all(host.as_ref(), &sheet.title, files, on),
|
||||
}
|
||||
}
|
||||
@@ -364,13 +446,10 @@ impl<'a> DetailsSheet<'a> {
|
||||
impl Sheet {
|
||||
/// The sheet of the panel's open detail; `None` when there is none or its family is gone.
|
||||
fn read(panel: &FontsPanel, env: &Env, words: &DetailsWords) -> Option<Sheet> {
|
||||
let mut sheet = match panel.detail.clone()? {
|
||||
Detail::Family(i) => Sheet::family(panel, env, words, i)?,
|
||||
Detail::Installed(name, source) => Sheet::installed(panel, env, words, &name, source)?,
|
||||
};
|
||||
// The sample is what the user typed, else the preset for the family's scripts.
|
||||
sheet.sample = panel.sample_for(sheet.scripts.iter().map(String::as_str));
|
||||
Some(sheet)
|
||||
match panel.detail.clone()? {
|
||||
Detail::Family(i) => Sheet::family(panel, env, words, i),
|
||||
Detail::Installed(name, source) => Sheet::installed(panel, env, words, &name, source),
|
||||
}
|
||||
}
|
||||
|
||||
fn family(panel: &FontsPanel, env: &Env, words: &DetailsWords, i: usize) -> Option<Sheet> {
|
||||
@@ -386,8 +465,8 @@ impl Sheet {
|
||||
let names = env.words::<FontsPanelWords>();
|
||||
let eyebrow = [source.to_owned(), category_label(&names, &family)].join(" · ");
|
||||
let byline = (!family.designer.is_empty()).then(|| words.designed_by.fill(&[("designer", &family.designer)]));
|
||||
let hero = regular(&installed).cloned().map(|f| (Owner::Installed, f));
|
||||
let hero = hero.or_else(|| previewed.as_deref().and_then(regular).cloned().map(|f| (Owner::Preview, f)));
|
||||
let hero = regular(&installed).cloned().map(|f| HeldFace::local(Owner::Installed, f, &panel.catalog));
|
||||
let hero = hero.or_else(|| previewed.as_deref().and_then(regular).cloned().map(|f| HeldFace::local(Owner::Preview, f, &panel.previews)));
|
||||
let size = env.units().file_size(family.size());
|
||||
let all_installed =
|
||||
!installed.is_empty() && (on_system || family.files.iter().all(|f| store.iter().any(|x| file_name(x).as_deref() == Some(f.file_name()))));
|
||||
@@ -396,10 +475,25 @@ impl Sheet {
|
||||
_ => None,
|
||||
};
|
||||
let installed_word = if on_system { &words.installed_on_system } else { &words.installed };
|
||||
let unseen = installed.is_empty() && previewed.is_none();
|
||||
let sample = panel.family_sample(&index, &family);
|
||||
let unseen = installed.is_empty() && previewed.is_none() && !panel.subsets.draws_detail(&index, &family, &sample);
|
||||
let uncurated = (!curated).then(|| index.source_of(&family).and_then(|f| f.user_url.clone()).unwrap_or_default());
|
||||
let failure = panel.failed.get(&key).map(|f| Failed { what: f.kind, error: f.error.clone(), retry: f.retry.clone() });
|
||||
let lines = family_lines(&names, &family, &installed, &store, on_system, previewed.as_deref(), &job);
|
||||
let styles = FamilyStyles {
|
||||
panel,
|
||||
names: &names,
|
||||
words,
|
||||
index: &index,
|
||||
family: &family,
|
||||
sample: &sample,
|
||||
installed: &installed,
|
||||
store: &store,
|
||||
on_system,
|
||||
previewed: previewed.as_deref(),
|
||||
job: &job,
|
||||
};
|
||||
let (lines, subset_files) = styles.lines();
|
||||
let axes = styles.axes(&subset_files);
|
||||
let mut facts = family_facts(env, words, &index, &family, &size);
|
||||
let not_curated = env.view().resolve(&words.not_curated);
|
||||
let source_fact = if curated { source.to_owned() } else { format!("{source} · {}", not_curated.as_str()) };
|
||||
@@ -425,18 +519,21 @@ impl Sheet {
|
||||
uncurated,
|
||||
failure,
|
||||
lines,
|
||||
subset_files,
|
||||
axes,
|
||||
facts,
|
||||
languages: languages.into_iter().map(|l| l.name.clone()).collect(),
|
||||
scripts: family.scripts.clone(),
|
||||
upstream: family.upstream.clone().filter(|url| url.starts_with("https://") || url.starts_with("http://")),
|
||||
legal: legal_texts(panel, &family),
|
||||
index: Some(i),
|
||||
sample: String::new(),
|
||||
sample,
|
||||
})
|
||||
}
|
||||
|
||||
fn installed(panel: &FontsPanel, env: &Env, words: &DetailsWords, name: &str, source: Source) -> Option<Sheet> {
|
||||
let family = panel.installed.iter().find(|f| f.name == name && f.source == source).cloned()?;
|
||||
let names = env.words::<FontsPanelWords>();
|
||||
let hero = regular(&family.faces).cloned().map(|f| (Owner::Installed, f));
|
||||
let hero = regular(&family.faces).cloned().map(|f| HeldFace::local(Owner::Installed, f, &panel.catalog));
|
||||
let job = panel.jobs.of("", &family.name).map(|j| (j.kind, j.file.clone(), j.fraction()));
|
||||
let run = match &job {
|
||||
Some((Kind::Remove, None, _)) => Some(Run { kind: Kind::Remove, fraction: None }),
|
||||
@@ -445,10 +542,9 @@ impl Sheet {
|
||||
let lines = family
|
||||
.faces
|
||||
.iter()
|
||||
.map(|face| StyleLine {
|
||||
label: style_name(&names, face).to_owned(),
|
||||
face: Some((Owner::Installed, face.clone())),
|
||||
action: if face.source == Source::Store { Action::Remove(Box::new(face.clone())) } else { Action::None },
|
||||
.map(|face| {
|
||||
let action = if face.source == Source::Store { Action::Remove(Box::new(face.clone())) } else { Action::None };
|
||||
StyleLine::new(style_name(&names, face), Some(HeldFace::local(Owner::Installed, face.clone(), &panel.catalog)), action)
|
||||
})
|
||||
.collect();
|
||||
let mut files: Vec<_> = family.faces.iter().filter_map(|f| f.path.clone()).collect();
|
||||
@@ -460,7 +556,6 @@ impl Sheet {
|
||||
(words.styles_fact.clone(), format.integer(family.faces.len() as u64)),
|
||||
(words.files_fact.clone(), format.integer(files.len() as u64)),
|
||||
];
|
||||
let scripts = panel.index().and_then(|index| index.family(&family.name).map(|f| f.scripts.clone())).unwrap_or_default();
|
||||
Some(Sheet {
|
||||
eyebrow: source_name(&names, source).as_str().to_owned(),
|
||||
title: family.name.clone(),
|
||||
@@ -479,24 +574,22 @@ impl Sheet {
|
||||
uncurated: None,
|
||||
failure: None,
|
||||
lines,
|
||||
subset_files: Vec::new(),
|
||||
axes: Vec::new(),
|
||||
facts,
|
||||
languages: Vec::new(),
|
||||
scripts,
|
||||
upstream: None,
|
||||
legal: Vec::new(),
|
||||
index: None,
|
||||
sample: String::new(),
|
||||
sample: panel.installed_sample(&family.name),
|
||||
})
|
||||
}
|
||||
|
||||
/// The eyebrow, the "Aa" in the family's face, the byline, and the family's install and remove controls.
|
||||
fn header(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, catalogs: &Catalogs, todo: &mut Vec<Do>) {
|
||||
fn header(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, todo: &mut Vec<Do>) {
|
||||
Text::new(self.eyebrow.clone()).shade(Shade::Faint).show(ui);
|
||||
if let Some((owner, face)) = &self.hero {
|
||||
let catalog = match owner {
|
||||
Owner::Installed => &catalogs.0,
|
||||
Owner::Preview => &catalogs.1,
|
||||
};
|
||||
let face = SampleFace::Face { catalog, owner: *owner, face };
|
||||
FontSample::new(format!("{}: Aa", self.title), "Aa", face, HERO_POINTS).show(ui);
|
||||
if let Some(face) = &self.hero {
|
||||
FontSample::new(format!("{}: Aa", self.title), "Aa", HeldFace::sample(Some(face)), HERO_POINTS).show(ui);
|
||||
}
|
||||
if let Some(byline) = &self.byline {
|
||||
Text::new(byline.clone()).shade(Shade::Muted).show(ui);
|
||||
@@ -583,35 +676,27 @@ impl Sheet {
|
||||
out.chosen.map(Some).or_else(|| out.activated.then_some(None))
|
||||
}
|
||||
|
||||
/// The styles, and beside them (or below, when narrow) the facts and the languages.
|
||||
fn body(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, catalogs: &Catalogs, points: f32, todo: &mut Vec<Do>) {
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| self.styles(ui, env, words, catalogs, points, todo));
|
||||
Stack::new().show(ui, |ui, _| self.side(ui, env, words));
|
||||
});
|
||||
/// The styles, the axis sliders of each variable file under its name, the facts, the languages and the licence.
|
||||
fn body(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, points: f32, axes: &mut HashMap<String, AxisValues>, todo: &mut Vec<Do>) {
|
||||
self.styles(ui, env, words, points, todo);
|
||||
for file in &self.axes {
|
||||
Text::new(file.label.clone()).shade(Shade::Faint).show(ui);
|
||||
let values = axes.entry(file.sha256.clone()).or_default();
|
||||
AxisSliders::new(file.label.clone(), &file.axes, Bind::bound(values)).optical_size(OPTICAL_SIZE).show(ui);
|
||||
}
|
||||
self.side(ui, env, words);
|
||||
self.licence(ui, words, todo);
|
||||
}
|
||||
|
||||
fn styles(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, catalogs: &Catalogs, points: f32, todo: &mut Vec<Do>) {
|
||||
let total = self.lines.len() as u64;
|
||||
let installed = self.lines.iter().filter(|l| matches!(l.face, Some((Owner::Installed, _)))).count();
|
||||
let count = env.format().integer(total);
|
||||
let heading = if installed == self.lines.len() { words.styles_installed.text(total, &count) } else { words.styles.text(total, &count) };
|
||||
Text::new(heading).shade(Shade::Faint).show(ui);
|
||||
fn styles(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, points: f32, todo: &mut Vec<Do>) {
|
||||
let total = self.lines.iter().filter(|line| !line.sliders).count();
|
||||
let installed = self.lines.iter().filter(|line| line.face.as_ref().is_some_and(HeldFace::installed)).count();
|
||||
let count = env.format().integer(total as u64);
|
||||
let counted = if installed == total { &words.styles_installed } else { &words.styles };
|
||||
Text::new(counted.text(total as u64, &count)).shade(Shade::Faint).show(ui);
|
||||
let source = Lines(&self.lines);
|
||||
let out = StyleList::new(self.title.clone(), words.no_styles.clone()).show_items(ui, &source, &mut |key, _| {
|
||||
let line = &self.lines[*key];
|
||||
let face = match &line.face {
|
||||
Some((owner, face)) => {
|
||||
let catalog = match owner {
|
||||
Owner::Installed => &catalogs.0,
|
||||
Owner::Preview => &catalogs.1,
|
||||
};
|
||||
SampleFace::Face { catalog, owner: *owner, face }
|
||||
}
|
||||
None => SampleFace::Missing,
|
||||
};
|
||||
StyleRow::new(line, &self.title, &self.sample, points, face, words)
|
||||
});
|
||||
let out = StyleList::new(self.title.clone(), words.no_styles.clone())
|
||||
.show_items(ui, &source, &mut |key, _| StyleRow::new(&self.lines[*key], &self.title, &self.sample, points, words));
|
||||
for event in out.events {
|
||||
let CollectionEvent::Item(key, _) = event else { continue };
|
||||
match &self.lines[key].action {
|
||||
@@ -648,6 +733,48 @@ impl Sheet {
|
||||
}
|
||||
}
|
||||
|
||||
impl Sheet {
|
||||
/// The project's page, and the licence and NOTICE texts: each a button that reads it, then the text, or why it
|
||||
/// couldn't be read.
|
||||
fn licence(&self, ui: &mut Ui, words: &DetailsWords, todo: &mut Vec<Do>) {
|
||||
if let Some(url) = &self.upstream {
|
||||
let shown = url.trim_start_matches("https://").trim_start_matches("http://").trim_end_matches('/');
|
||||
Link::new(shown.to_owned()).url(url.clone()).wrap(Wrap::Elide).description(words.upstream.fill(&[("url", url)])).show(ui);
|
||||
}
|
||||
for (at, (which, shown)) in self.legal.iter().enumerate() {
|
||||
let (show, title) = match which {
|
||||
LegalText::License => (&words.show_licence, &words.licence_text),
|
||||
LegalText::Notice => (&words.show_notice, &words.notice_text),
|
||||
};
|
||||
let read = match shown {
|
||||
LegalShown::Offer => clicked(&Button::new(show.clone()).variant(Variant::SECONDARY).show(ui)),
|
||||
LegalShown::Loading => {
|
||||
Text::new(words.loading_text.clone()).shade(Shade::Muted).show(ui);
|
||||
false
|
||||
}
|
||||
LegalShown::Text(text) => {
|
||||
Text::new(title.clone()).shade(Shade::Faint).show(ui);
|
||||
TextField::new(title.clone(), Bind::given(text.clone()))
|
||||
.lines(LEGAL_LEAST_LINES)
|
||||
.max_lines(LEGAL_LINES)
|
||||
.sizing(Sizing::FillWidth)
|
||||
.mono()
|
||||
.read_only(true)
|
||||
.show(ui);
|
||||
false
|
||||
}
|
||||
LegalShown::Failed(error) => {
|
||||
let retry = NoticeAction::new(words.retry.clone());
|
||||
Notice::new(Tone::Bad, error.clone()).id_salt(("legal", at)).title(title.clone()).action(retry).show(ui).action.is_some()
|
||||
}
|
||||
};
|
||||
if read {
|
||||
todo.push(Do::ReadLegal(*which));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A job's progress: the job and the percent done when known, with a bar.
|
||||
fn progress(ui: &mut Ui, env: &Env, words: &DetailsWords, what: &Label, fraction: Option<f32>) {
|
||||
let what = env.view().resolve(what);
|
||||
@@ -662,54 +789,136 @@ fn progress(ui: &mut Ui, env: &Env, words: &DetailsWords, what: &Label, fraction
|
||||
};
|
||||
}
|
||||
|
||||
/// The rows of the family sheet: the installed faces, then the index files not installed, as the previewed faces when
|
||||
/// the preview has them.
|
||||
fn family_lines(
|
||||
names: &FontsPanelWords,
|
||||
family: &Family,
|
||||
installed: &[FaceInfo],
|
||||
store: &[FaceInfo],
|
||||
/// The styles of a family of the index, as its sheet lists them.
|
||||
struct FamilyStyles<'a> {
|
||||
panel: &'a FontsPanel,
|
||||
names: &'a FontsPanelWords,
|
||||
words: &'a DetailsWords,
|
||||
index: &'a Index,
|
||||
family: &'a Family,
|
||||
sample: &'a str,
|
||||
installed: &'a [FaceInfo],
|
||||
store: &'a [FaceInfo],
|
||||
on_system: bool,
|
||||
previewed: Option<&[FaceInfo]>,
|
||||
job: &Option<(Kind, Option<String>, Option<f32>)>,
|
||||
) -> Vec<StyleLine> {
|
||||
let running = |path: &str| match job {
|
||||
Some((Kind::Install, Some(p), fraction)) if p == path => Some(*fraction),
|
||||
_ => None,
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
for face in installed {
|
||||
let action = match job {
|
||||
Some((Kind::Remove, Some(p), _)) if face.path.as_ref().is_some_and(|x| x.display().to_string() == *p) => Action::Running(None),
|
||||
_ if face.source == Source::Store => Action::Remove(Box::new(face.clone())),
|
||||
_ => Action::None,
|
||||
};
|
||||
lines.push(StyleLine { label: style_name(names, face).to_owned(), face: Some((Owner::Installed, face.clone())), action });
|
||||
}
|
||||
if on_system {
|
||||
return lines;
|
||||
}
|
||||
for file in &family.files {
|
||||
if store.iter().any(|x| file_name(x).as_deref() == Some(file.file_name())) {
|
||||
continue;
|
||||
previewed: Option<&'a [FaceInfo]>,
|
||||
job: &'a Option<(Kind, Option<String>, Option<f32>)>,
|
||||
}
|
||||
|
||||
impl FamilyStyles<'_> {
|
||||
/// The rows: the installed faces, then the index files not installed, as the previewed faces when the preview has
|
||||
/// them, else as the preview service draws them; and the files, by position, of the last kind.
|
||||
fn lines(&self) -> (Vec<StyleLine>, Vec<usize>) {
|
||||
let mut lines = Vec::new();
|
||||
let mut subset_files = Vec::new();
|
||||
for face in self.installed {
|
||||
let action = match self.job {
|
||||
Some((Kind::Remove, Some(p), _)) if face.path.as_ref().is_some_and(|x| x.display().to_string() == *p) => Action::Running(None),
|
||||
_ if face.source == Source::Store => Action::Remove(Box::new(face.clone())),
|
||||
_ => Action::None,
|
||||
};
|
||||
lines.push(self.line(Owner::Installed, face, action));
|
||||
}
|
||||
let preview_faces: Vec<&FaceInfo> =
|
||||
previewed.unwrap_or_default().iter().filter(|f| file_of(family, f).is_some_and(|x| x.path == file.path)).collect();
|
||||
let action = match running(&file.path) {
|
||||
Some(fraction) => Action::Running(fraction),
|
||||
None => Action::Install(file.path.clone()),
|
||||
};
|
||||
if preview_faces.is_empty() {
|
||||
lines.push(StyleLine { label: file_label(file), face: None, action });
|
||||
} else {
|
||||
for (n, face) in preview_faces.iter().enumerate() {
|
||||
if self.on_system {
|
||||
return (lines, subset_files);
|
||||
}
|
||||
for (n, file) in self.family.files.iter().enumerate() {
|
||||
if self.store.iter().any(|x| file_name(x).as_deref() == Some(file.file_name())) {
|
||||
continue;
|
||||
}
|
||||
let preview_faces: Vec<&FaceInfo> =
|
||||
self.previewed.unwrap_or_default().iter().filter(|f| file_of(self.family, f).is_some_and(|x| x.path == file.path)).collect();
|
||||
let action = match self.job {
|
||||
Some((Kind::Install, Some(p), fraction)) if *p == file.path => Action::Running(*fraction),
|
||||
_ => Action::Install(file.path.clone()),
|
||||
};
|
||||
if !preview_faces.is_empty() {
|
||||
// A variable file's instances install together: the file's action on its first.
|
||||
let action = if n == 0 { action.clone() } else { Action::None };
|
||||
lines.push(StyleLine { label: style_name(names, face).to_owned(), face: Some((Owner::Preview, (*face).clone())), action });
|
||||
let actions = std::iter::once(action).chain(std::iter::repeat(Action::None));
|
||||
lines.extend(preview_faces.into_iter().zip(actions).map(|(face, action)| self.line(Owner::Preview, face, action)));
|
||||
} else if self.panel.subsets.serves(self.family) {
|
||||
subset_files.push(n);
|
||||
self.subset_lines(file, action, &mut lines);
|
||||
} else {
|
||||
lines.push(StyleLine::new(file_label(file), None, action));
|
||||
}
|
||||
}
|
||||
(lines, subset_files)
|
||||
}
|
||||
lines
|
||||
|
||||
fn line(&self, owner: Owner, face: &FaceInfo, action: Action) -> StyleLine {
|
||||
let catalog = match owner {
|
||||
Owner::Installed => &self.panel.catalog,
|
||||
Owner::Preview => &self.panel.previews,
|
||||
};
|
||||
StyleLine::new(style_name(self.names, face), Some(HeldFace::local(owner, face.clone(), catalog)), action)
|
||||
}
|
||||
|
||||
/// The rows of a file drawn by the preview service: a static file's one, or a variable file's named instances and
|
||||
/// the row that follows its axis sliders, all at coordinates of one subset that keeps every axis.
|
||||
fn subset_lines(&self, file: &FontFile, action: Action, lines: &mut Vec<StyleLine>) {
|
||||
let face = self.subset(file).map(HeldFace::Subset);
|
||||
if !file.is_variable() {
|
||||
lines.push(StyleLine::new(file_label(file), face, action));
|
||||
return;
|
||||
}
|
||||
// A variable file installs whole: the file's action on its first row.
|
||||
if file.instances.is_empty() {
|
||||
lines.push(StyleLine::new(self.words.default_style.as_str(), face.clone(), action));
|
||||
} else {
|
||||
let actions = std::iter::once(action).chain(std::iter::repeat(Action::None));
|
||||
lines.extend(file.instances.iter().zip(actions).map(|(instance, action)| {
|
||||
let coords = instance.coordinates.iter().filter_map(|(tag, v)| Some((axis_tag(tag)?, *v))).collect();
|
||||
StyleLine::new(instance.name.clone(), face.clone(), action).at(coords)
|
||||
}));
|
||||
}
|
||||
let values = self.panel.detail_axes.get(&file.sha256).cloned().unwrap_or_default();
|
||||
lines.push(StyleLine { sliders: true, ..StyleLine::new(file_label(file), face, Action::None).at(values) });
|
||||
}
|
||||
|
||||
fn subset(&self, file: &FontFile) -> Option<SubsetFont> {
|
||||
self.panel.subsets.detail_font(self.index, self.family, file, self.sample)
|
||||
}
|
||||
|
||||
/// The axes of the variable files among `files` that have a slider: the subset's own once it is here, else the index's
|
||||
/// ranges.
|
||||
fn axes(&self, files: &[usize]) -> Vec<FileAxes> {
|
||||
files
|
||||
.iter()
|
||||
.filter_map(|n| self.family.files.get(*n))
|
||||
.filter(|file| file.is_variable())
|
||||
.map(|file| {
|
||||
let own = self.subset(file).map(|font| read_axes(&font.bytes, 0)).filter(|axes| !axes.is_empty());
|
||||
FileAxes { sha256: file.sha256.clone(), label: file_label(file), axes: own.unwrap_or_else(|| index_axes(file)) }
|
||||
})
|
||||
.filter(|file| shown_axes(&file.axes, OPTICAL_SIZE).next().is_some())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// `tag` as an OpenType tag: four printable ASCII characters, spaces only at the end.
|
||||
fn axis_tag(tag: &str) -> Option<[u8; 4]> {
|
||||
let tag: [u8; 4] = tag.as_bytes().try_into().ok()?;
|
||||
let printable = tag.iter().all(|b| (0x20..=0x7e).contains(b));
|
||||
let spaces_last = tag.iter().skip_while(|b| **b != b' ').all(|b| *b == b' ');
|
||||
(printable && spaces_last && tag[0] != b' ').then_some(tag)
|
||||
}
|
||||
|
||||
/// A variable file's axes as the index gives them: its ranges about the file's default style.
|
||||
fn index_axes(file: &FontFile) -> Vec<FontAxis> {
|
||||
file.axes
|
||||
.iter()
|
||||
.filter(|axis| axis.min < axis.max)
|
||||
.filter_map(|axis| {
|
||||
let tag = axis_tag(&axis.tag)?;
|
||||
let default = match &tag {
|
||||
b"wght" => f32::from(file.weight),
|
||||
b"wdth" => file.width,
|
||||
b"ital" => f32::from(u8::from(file.is_italic())),
|
||||
_ => 0.0,
|
||||
};
|
||||
Some(FontAxis::new(tag, "", axis.min, default.clamp(axis.min, axis.max), axis.max))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn family_facts(env: &Env, words: &DetailsWords, index: &Index, family: &Family, size: &str) -> Vec<(Label, String)> {
|
||||
@@ -720,6 +929,9 @@ fn family_facts(env: &Env, words: &DetailsWords, index: &Index, family: &Family,
|
||||
facts.push((words.designer.clone(), family.designer.clone()));
|
||||
}
|
||||
facts.push((words.licence.clone(), licence_name(&family.license).to_owned()));
|
||||
if let Some(copyright) = family.copyright.as_deref().map(str::trim).filter(|text| !text.is_empty()) {
|
||||
facts.push((words.copyright.clone(), copyright.to_owned()));
|
||||
}
|
||||
facts.push((words.styles_fact.clone(), format.integer(style_count(family) as u64)));
|
||||
facts.push((words.files_fact.clone(), format.integer(family.files.len() as u64)));
|
||||
facts.push((words.download_size.clone(), size.to_owned()));
|
||||
|
||||
@@ -18,8 +18,8 @@ use egui::{Pos2, Rect, Response, Vec2};
|
||||
|
||||
use super::DetailsWords;
|
||||
use crate::FaceInfo;
|
||||
use crate::panel::faces::Owner;
|
||||
use crate::panel::specimen::{FontSample, SampleFace};
|
||||
use crate::axes::AxisValues;
|
||||
use crate::panel::specimen::{FontSample, HeldFace};
|
||||
|
||||
/// What a style row offers at its end.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -34,13 +34,30 @@ pub(super) enum Action {
|
||||
}
|
||||
|
||||
/// One style of the sheet.
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone)]
|
||||
pub(super) struct StyleLine {
|
||||
pub label: String,
|
||||
pub face: Option<(Owner, FaceInfo)>,
|
||||
/// The face the sample is drawn in.
|
||||
pub face: Option<HeldFace>,
|
||||
/// The variation coordinates the face is drawn at.
|
||||
pub coords: AxisValues,
|
||||
/// The line follows the sheet's axis sliders, so it is no style of its own.
|
||||
pub sliders: bool,
|
||||
pub action: Action,
|
||||
}
|
||||
|
||||
impl StyleLine {
|
||||
/// A style drawn in `face` as it is.
|
||||
pub(super) fn new(label: impl Into<String>, face: Option<HeldFace>, action: Action) -> Self {
|
||||
StyleLine { label: label.into(), face, coords: AxisValues::new(), sliders: false, action }
|
||||
}
|
||||
|
||||
/// The style at `coords` of its face.
|
||||
pub(super) fn at(self, coords: AxisValues) -> Self {
|
||||
StyleLine { coords, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines as a collection source, keyed by position.
|
||||
pub(super) struct Lines<'a>(pub &'a [StyleLine]);
|
||||
|
||||
@@ -88,11 +105,11 @@ pub(super) struct StyleList {
|
||||
}
|
||||
|
||||
impl StyleList {
|
||||
/// A list named `label`; it is as tall as its rows, and shows `empty` while it has none.
|
||||
/// A list named `label`; it fills the width, is as tall as its rows, and shows `empty` while it has none.
|
||||
pub(super) fn new(label: impl Into<Label>, empty: impl Into<Label>) -> Self {
|
||||
StyleList {
|
||||
common: Common::new(),
|
||||
props: ContainerProps::new().sizing(Sizing::Content),
|
||||
props: ContainerProps::new().sizing(Sizing::FillWidth),
|
||||
items: CollectionProps::new().select(SelectMode::Single).natural_height(true).empty(empty),
|
||||
}
|
||||
.label(label)
|
||||
@@ -173,7 +190,6 @@ pub(super) struct StyleRow<'r> {
|
||||
family: &'r str,
|
||||
sample: &'r str,
|
||||
points: f32,
|
||||
face: SampleFace<'r>,
|
||||
words: &'r DetailsWords,
|
||||
pressed: bool,
|
||||
/// The width of the action, measured in the pass's measure step and read by its paint.
|
||||
@@ -181,10 +197,9 @@ pub(super) struct StyleRow<'r> {
|
||||
}
|
||||
|
||||
impl<'r> StyleRow<'r> {
|
||||
/// The row of `line`, a style of `family`, with the sample `sample` at `points` in `face`.
|
||||
pub(super) fn new(line: &'r StyleLine, family: &'r str, sample: &'r str, points: f32, face: SampleFace<'r>, words: &'r DetailsWords) -> Self {
|
||||
StyleRow { common: Common::new(), line, family, sample, points, face, words, pressed: false, action: Cell::new(0.0) }
|
||||
.label(line.label.clone())
|
||||
/// The row of `line`, a style of `family`, with the sample `sample` at `points`.
|
||||
pub(super) fn new(line: &'r StyleLine, family: &'r str, sample: &'r str, points: f32, words: &'r DetailsWords) -> Self {
|
||||
StyleRow { common: Common::new(), line, family, sample, points, words, pressed: false, action: Cell::new(0.0) }.label(line.label.clone())
|
||||
}
|
||||
|
||||
fn style_name(&self) -> [(&'static str, &str); 1] {
|
||||
@@ -208,7 +223,8 @@ impl<'r> StyleRow<'r> {
|
||||
}
|
||||
|
||||
fn sample_leaf(&self) -> FontSample<'r> {
|
||||
FontSample::new(format!("{} {}: {}", self.family, self.line.label, self.sample), self.sample, self.face, self.points)
|
||||
let face = HeldFace::sample(self.line.face.as_ref());
|
||||
FontSample::new(format!("{} {}: {}", self.family, self.line.label, self.sample), self.sample, face, self.points).coords(&self.line.coords)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,9 +9,10 @@ use super::rows::{Action, Lines, StyleLine, StyleList, StyleRow};
|
||||
use super::{DetailsSheet, DetailsWords};
|
||||
use crate::panel::app::Detail;
|
||||
use crate::panel::faces::Owner;
|
||||
use crate::panel::fixtures::{SharedPanel, story_catalog, story_panel};
|
||||
use crate::panel::fixtures::{SharedPanel, VARIABLE, story_catalog, story_panel};
|
||||
use crate::panel::samples::PANGRAM;
|
||||
use crate::panel::specimen::SampleFace;
|
||||
use crate::panel::specimen::HeldFace;
|
||||
use crate::panel::subsets::SubsetFont;
|
||||
|
||||
/// The sample size of the stories, in points.
|
||||
const POINTS: f32 = 24.0;
|
||||
@@ -44,28 +45,22 @@ fn lines(count: usize) -> Vec<StyleLine> {
|
||||
let catalog = story_catalog();
|
||||
let face = catalog.styles("Hack").into_iter().next();
|
||||
(0..count)
|
||||
.map(|n| StyleLine {
|
||||
label: format!("Style {n}"),
|
||||
face: face.clone().map(|face| (Owner::Installed, face)),
|
||||
action: if n % 2 == 0 { Action::Install(format!("ofl/hack/Style{n}.ttf")) } else { Action::None },
|
||||
.map(|n| {
|
||||
let action = if n % 2 == 0 { Action::Install(format!("ofl/hack/Style{n}.ttf")) } else { Action::None };
|
||||
StyleLine::new(format!("Style {n}"), face.clone().map(|face| HeldFace::local(Owner::Installed, face, &catalog)), action)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn list(ui: &mut Ui, count: usize) -> StoryOutput {
|
||||
let lines = lines(count);
|
||||
let catalog = story_catalog();
|
||||
list_of(ui, &lines(count), PANGRAM)
|
||||
}
|
||||
|
||||
fn list_of(ui: &mut Ui, lines: &[StyleLine], sample: &str) -> StoryOutput {
|
||||
let words = Env::of(ui).words::<DetailsWords>();
|
||||
let source = Lines(&lines);
|
||||
let source = Lines(lines);
|
||||
StyleList::new("Styles", words.no_styles.clone())
|
||||
.show_items(ui, &source, &mut |key, _| {
|
||||
let line = &lines[*key];
|
||||
let face = match &line.face {
|
||||
Some((owner, face)) => SampleFace::Face { catalog: &catalog, owner: *owner, face },
|
||||
None => SampleFace::Missing,
|
||||
};
|
||||
StyleRow::new(line, "Hack", PANGRAM, POINTS, face, &words)
|
||||
})
|
||||
.show_items(ui, &source, &mut |key, _| StyleRow::new(&lines[*key], "Hack", sample, POINTS, &words))
|
||||
.into()
|
||||
}
|
||||
|
||||
@@ -84,9 +79,18 @@ fn style_list_many(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
list(ui, 4)
|
||||
}
|
||||
|
||||
/// The styles of one variable subset from the preview service.
|
||||
#[story(StyleList, covers = [], drive = Drive::Never)]
|
||||
fn style_list_variable(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let face = HeldFace::Subset(SubsetFont { key: "story/orbitron".to_owned(), bytes: VARIABLE.into() });
|
||||
let styles = [("Regular", 400.0), ("Bold", 700.0), ("Black", 900.0)];
|
||||
let lines = styles.map(|(name, weight)| StyleLine::new(name, Some(face.clone()), Action::None).at(vec![(*b"wght", weight)]));
|
||||
list_of(ui, &lines, "Orbitron")
|
||||
}
|
||||
|
||||
#[story(StyleRow<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn style_row_installing(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let line = StyleLine { label: "Bold".to_owned(), face: None, action: Action::Running(Some(0.4)) };
|
||||
let line = StyleLine::new("Bold", None, Action::Running(Some(0.4)));
|
||||
let words = Env::of(ui).words::<DetailsWords>();
|
||||
show_as_only_item(ui, StyleRow::new(&line, "Hack", PANGRAM, POINTS, SampleFace::Missing, &words)).into()
|
||||
show_as_only_item(ui, StyleRow::new(&line, "Hack", PANGRAM, POINTS, &words)).into()
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use craft_ui::primitives::{ContentPainterCx, DocRun, DocText, FacesCx, TextLayou
|
||||
use craft_ui::style::DataColor;
|
||||
use egui::{Color32, Pos2, Rect};
|
||||
|
||||
use crate::panel::subsets::SubsetFont;
|
||||
use crate::{Catalog, FaceInfo};
|
||||
|
||||
/// Larger files are not drawn: a whole CJK family can be hundreds of megabytes.
|
||||
@@ -56,6 +57,14 @@ pub(crate) fn shown(at: &impl FacesCx, catalog: &Arc<Catalog>, owner: Owner, fac
|
||||
})
|
||||
}
|
||||
|
||||
/// The font that draws a subset of the preview service, once the registry has taken it.
|
||||
pub(crate) fn subset(at: &impl FacesCx, subset: &SubsetFont) -> Shown {
|
||||
at.document_face(&format!("subset:{}", subset.key), || {
|
||||
let face = subset.face();
|
||||
move || Some(face)
|
||||
})
|
||||
}
|
||||
|
||||
/// The bytes of `face` once [`shown`] has it ready, for reading its tables without loading the file again.
|
||||
pub(crate) fn bytes(at: &impl FacesCx, owner: Owner, face: &FaceInfo) -> Option<FaceBytes> {
|
||||
at.document_face_bytes(&key(owner, face))
|
||||
@@ -82,25 +91,41 @@ pub(crate) struct SampleLine {
|
||||
pub(crate) baseline: f32,
|
||||
}
|
||||
|
||||
/// `text` in `font` for a band `band` high, laid out by `layout` (a measure's or a painter's) and cut to `room` as
|
||||
/// A sample's text and the face, size and colour it is drawn in.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Sample<'a> {
|
||||
pub(crate) text: &'a str,
|
||||
pub(crate) font: &'a FontRef,
|
||||
/// The variation coordinates (axis tag, value) the face is drawn at; empty for the face as registered.
|
||||
pub(crate) coords: &'a [([u8; 4], f32)],
|
||||
pub(crate) points: f32,
|
||||
pub(crate) color: DataColor,
|
||||
}
|
||||
|
||||
impl<'a> Sample<'a> {
|
||||
/// `text` in `font` as it is registered, at `points` in `color`.
|
||||
pub(crate) fn new(text: &'a str, font: &'a FontRef, points: f32, color: DataColor) -> Self {
|
||||
Sample { text, font, coords: &[], points, color }
|
||||
}
|
||||
|
||||
/// The sample drawn at the coordinates `coords` of its face.
|
||||
pub(crate) fn at(self, coords: &'a [([u8; 4], f32)]) -> Self {
|
||||
Sample { coords, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
/// `sample` for a band `band` high, laid out by `layout` (a measure's or a painter's) and cut to `room` as
|
||||
/// [`sample_text`] cuts it. Every face sits on one baseline: that of the interface face's line at `points` centred in
|
||||
/// the band, as a control's line sets its texts. The sample is laid out at `points`, or, where its ink (what the
|
||||
/// layout draws, as `Galley::mesh_bounds` holds it) would cross the band's top or bottom from that baseline, at the
|
||||
/// largest size whose ink stays inside the band.
|
||||
pub(crate) fn sample_line(
|
||||
layout: impl Fn(&DocText<'_>) -> TextLayout,
|
||||
font: &FontRef,
|
||||
text: &str,
|
||||
points: f32,
|
||||
band: f32,
|
||||
room: Option<f32>,
|
||||
color: DataColor,
|
||||
) -> SampleLine {
|
||||
pub(crate) fn sample_line(layout: impl Fn(&DocText<'_>) -> TextLayout, sample: Sample<'_>, band: f32, room: Option<f32>) -> SampleLine {
|
||||
let Sample { text, font, coords, points, color } = sample;
|
||||
let probe = [DocRun::new(BASELINE_PROBE, FontRef::proportional(), points, color)];
|
||||
let line = layout(&DocText::new(&probe));
|
||||
let baseline = (band - line.size().y) / 2.0 + line.first_baseline;
|
||||
let at = |size: f32| {
|
||||
let runs = [DocRun::new(text, font.clone(), size, color)];
|
||||
let runs = [DocRun::new(text, font.clone(), size, color).coords(coords)];
|
||||
layout(&sample_text(&runs, room))
|
||||
};
|
||||
let mut size = points;
|
||||
@@ -127,8 +152,6 @@ fn share(room: f32, ink: f32) -> f32 {
|
||||
if ink > room { room / ink } else { 1.0 }
|
||||
}
|
||||
|
||||
/// `text` on one line in `font` at `points` in the band `rect` ([`sample_line`]), at the reading start of `rect`,
|
||||
/// clipped to `rect`. The sample keeps its own direction whatever the interface's.
|
||||
/// The ink of a sample over `rect`: black on a white paper it fills, in every theme, when `on_white`; else `ink`.
|
||||
pub(crate) fn sample_ink(painter: &ContentPainterCx<'_>, rect: Rect, on_white: bool, ink: Color32) -> DataColor {
|
||||
if !on_white {
|
||||
@@ -138,10 +161,12 @@ pub(crate) fn sample_ink(painter: &ContentPainterCx<'_>, rect: Rect, on_white: b
|
||||
DataColor::new(Color32::from(Srgba::BLACK))
|
||||
}
|
||||
|
||||
pub(crate) fn paint_sample(painter: &ContentPainterCx<'_>, rect: Rect, font: &FontRef, text: &str, points: f32, color: DataColor) {
|
||||
let line = sample_line(|doc| painter.layout(doc), font, text, points, rect.height(), Some(rect.width()), color);
|
||||
/// `sample` on one line in the band `rect` ([`sample_line`]), at the reading start of `rect`, clipped to `rect`. The
|
||||
/// sample keeps its own direction whatever the interface's.
|
||||
pub(crate) fn paint_sample(painter: &ContentPainterCx<'_>, rect: Rect, sample: Sample<'_>) {
|
||||
let line = sample_line(|doc| painter.layout(doc), sample, rect.height(), Some(rect.width()));
|
||||
let size = line.layout.size();
|
||||
let x = match base_direction(text) {
|
||||
let x = match base_direction(sample.text) {
|
||||
Some(Direction::Rtl) => rect.right() - size.x,
|
||||
_ => rect.left(),
|
||||
};
|
||||
|
||||
@@ -47,6 +47,10 @@ pub(crate) fn story_catalog() -> Arc<Catalog> {
|
||||
catalog
|
||||
}
|
||||
|
||||
/// A variable font (`wght`), for the samples drawn at variation coordinates.
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) const VARIABLE: &[u8] = include_bytes!("../../../font-subset/tests/data/orbitron/Orbitron[wght].ttf");
|
||||
|
||||
/// The panel over the story catalog and index; its store is a fake that refuses downloads.
|
||||
pub(crate) fn story_panel() -> FontsPanel {
|
||||
let store = FakeStore::new(std::env::temp_dir().join("craft-fonts-panel-story"), HashMap::new());
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
//! The interface languages the panel offers.
|
||||
//! The interface languages the panel offers, and its words in them.
|
||||
|
||||
use craft_i18n::Embedded;
|
||||
|
||||
/// The interface languages offered, in menu order.
|
||||
pub const LANGUAGES: &[&str] = &["en", "ja", "ar"];
|
||||
|
||||
/// The panel's words in Japanese and Arabic: the shared catalogs an app gives the `I18n` of its Host, alone or after its
|
||||
/// own shared rows. A word without a row shows in English.
|
||||
pub const CATALOGS: &Embedded = &[("ja", include_str!("catalogs/ja.tsv"), ""), ("ar", include_str!("catalogs/ar.tsv"), "")];
|
||||
@@ -0,0 +1,90 @@
|
||||
//! A family's licence and NOTICE texts, read through the store on request.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{Receiver, TryRecvError, channel};
|
||||
|
||||
use craft_host::Host;
|
||||
|
||||
use crate::index::Family;
|
||||
use crate::panel::app::{Detail, FontsPanel, family_key};
|
||||
use crate::panel::jobs;
|
||||
use crate::store::{LegalText, StoreError};
|
||||
|
||||
/// A licence or NOTICE text being read, or read.
|
||||
pub(crate) enum Legal {
|
||||
Loading(Receiver<Result<Option<String>, StoreError>>),
|
||||
/// `None` when the family has no such file.
|
||||
Ready(Option<String>),
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// What a licence or NOTICE text is kept by: the family's key, which text, and the file's sha256 (else its path), so a
|
||||
/// file an index refresh changed is read again.
|
||||
pub(crate) type LegalKey = (String, LegalText, String);
|
||||
|
||||
pub(crate) type LegalTexts = HashMap<LegalKey, Legal>;
|
||||
|
||||
pub(crate) fn legal_key(family: &Family, which: LegalText) -> LegalKey {
|
||||
let file = match which {
|
||||
LegalText::License => family.license_file.as_ref(),
|
||||
LegalText::Notice => family.notice_file.as_ref(),
|
||||
};
|
||||
let identity = match (file, which) {
|
||||
(Some(file), _) => file.sha256.clone(),
|
||||
(None, LegalText::License) => family.license_path.clone().unwrap_or_default(),
|
||||
(None, LegalText::Notice) => String::new(),
|
||||
};
|
||||
(family_key(&family.source, &family.family), which, identity)
|
||||
}
|
||||
|
||||
impl FontsPanel {
|
||||
/// Takes in the texts that were read.
|
||||
pub(crate) fn poll_legal(&mut self) {
|
||||
for state in self.legal.values_mut() {
|
||||
if let Legal::Loading(rx) = state {
|
||||
match rx.try_recv() {
|
||||
Ok(Ok(text)) => *state = Legal::Ready(text),
|
||||
Ok(Err(e)) => *state = Legal::Failed(e.0),
|
||||
Err(TryRecvError::Empty) => {}
|
||||
Err(TryRecvError::Disconnected) => *state = Legal::Ready(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the NOTICE of the family the details sheet shows once downloads are allowed: an Apache family's NOTICE is
|
||||
/// shown with its fonts.
|
||||
pub(crate) fn read_notice(&mut self, host: Option<&Arc<Host>>) {
|
||||
let Some((index, i)) = self.index().zip(self.detail_family()) else { return };
|
||||
let unread = index.families().get(i).is_some_and(|f| f.notice_file.is_some() && !self.legal.contains_key(&legal_key(f, LegalText::Notice)));
|
||||
if unread && self.allowed() {
|
||||
self.load_legal(host, i, LegalText::Notice);
|
||||
}
|
||||
}
|
||||
|
||||
fn detail_family(&self) -> Option<usize> {
|
||||
match &self.detail {
|
||||
Some(Detail::Family(i)) => Some(*i),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the licence or NOTICE text of the `i`th family through the store, as a job.
|
||||
pub(crate) fn load_legal(&mut self, host: Option<&Arc<Host>>, i: usize, which: LegalText) {
|
||||
let Some(index) = self.index() else { return };
|
||||
let Some(family) = index.families().get(i).cloned() else { return };
|
||||
let (tx, rx) = channel();
|
||||
self.legal.insert(legal_key(&family, which), Legal::Loading(rx));
|
||||
let installer = Arc::clone(&self.installer);
|
||||
let wake = self.jobs.waker();
|
||||
jobs::spawn(
|
||||
host,
|
||||
"font-licence",
|
||||
Box::new(move || {
|
||||
let _ = tx.send(installer.legal_text(&index, &family, which));
|
||||
wake.wake();
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,12 +10,15 @@ pub(crate) mod faces;
|
||||
#[cfg(feature = "screen-testing")]
|
||||
pub(crate) mod fixtures;
|
||||
pub(crate) mod jobs;
|
||||
pub(crate) mod legal;
|
||||
pub(crate) mod samples;
|
||||
pub(crate) mod sources;
|
||||
pub(crate) mod specimen;
|
||||
pub(crate) mod subsets;
|
||||
|
||||
pub use app::{
|
||||
FontsCommand, FontsPanel, FontsPanelOutput, FontsPanelSettings, FontsPanelView, FontsPanelWords, Options, Preset, Tab, install_interface_fonts,
|
||||
};
|
||||
pub use browse::FontsBrowseWords;
|
||||
pub use i18n::CATALOGS;
|
||||
pub use sources::{FontSources, FontSourcesOutput};
|
||||
@@ -1,5 +1,9 @@
|
||||
//! Sample text: a sentence in the language the catalogue is filtered by, or in a family's own
|
||||
//! script when it has no Latin, so a sample never comes out as boxes.
|
||||
//! Sample text: a family's own sentence from the index (its script's, by `sample_script`), the one the preview
|
||||
//! service's sample subsets hold; a sentence in the language the catalogue is filtered by; and built-in sentences by
|
||||
//! script for families the index has no sample for, so a sample never comes out as boxes.
|
||||
|
||||
use crate::index::{Family, Index};
|
||||
use crate::panel::app::list_file;
|
||||
|
||||
/// The English pangram, the sample for Latin.
|
||||
pub const PANGRAM: &str = "The quick brown fox jumps over the lazy dog";
|
||||
@@ -81,6 +85,12 @@ pub fn for_script(script: &str) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The sample of the face the list shows for `family`, from the index: the sentence of the face's `sample_script` (else
|
||||
/// the family's), or the face's own text.
|
||||
pub(crate) fn of_family<'a>(index: &'a Index, family: &'a Family) -> Option<&'a str> {
|
||||
list_file(family).and_then(|file| index.sample_text(family, file))
|
||||
}
|
||||
|
||||
/// The sample for a family with `scripts`: the pangram when it has Latin, else a sentence in the
|
||||
/// first of its scripts there is one for.
|
||||
pub fn for_scripts<'a>(scripts: impl IntoIterator<Item = &'a str>) -> &'static str {
|
||||
|
||||
@@ -12,7 +12,8 @@ use egui::{Color32, Vec2};
|
||||
|
||||
use crate::Catalog;
|
||||
use crate::FaceInfo;
|
||||
use crate::panel::faces::{self, Owner, Shown};
|
||||
use crate::panel::faces::{self, Owner, Sample, Shown};
|
||||
use crate::panel::subsets::SubsetFont;
|
||||
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
@@ -35,6 +36,8 @@ pub(crate) struct FontSampleStyle {
|
||||
pub(crate) enum SampleFace<'a> {
|
||||
/// A face of `catalog`, which the document-face registry loads when the sample is measured or painted.
|
||||
Face { catalog: &'a Arc<Catalog>, owner: Owner, face: &'a FaceInfo },
|
||||
/// A subset of a face from the preview service.
|
||||
Subset(&'a SubsetFont),
|
||||
/// A face the host gives, ready as it is (a host row of the picker).
|
||||
Font(&'a FontRef),
|
||||
/// No face is here to draw with: the sample keeps its band and shows nothing.
|
||||
@@ -47,16 +50,51 @@ impl SampleFace<'_> {
|
||||
/// may lack the sample's characters.
|
||||
pub(crate) fn ready(&self, at: &impl craft_ui::primitives::FacesCx) -> Option<FontRef> {
|
||||
match self {
|
||||
SampleFace::Face { catalog, owner, face } => match faces::shown(at, catalog, *owner, face) {
|
||||
Shown::Ready(font) => Some(font),
|
||||
_ => None,
|
||||
},
|
||||
SampleFace::Face { catalog, owner, face } => ready(faces::shown(at, catalog, *owner, face)),
|
||||
SampleFace::Subset(subset) => ready(faces::subset(at, subset)),
|
||||
SampleFace::Font(font) => Some((*font).clone()),
|
||||
SampleFace::Missing => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ready(shown: Shown) -> Option<FontRef> {
|
||||
match shown {
|
||||
Shown::Ready(font) => Some(font),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The face a card or a style row draws its sample in, as the panel holds it.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum HeldFace {
|
||||
/// A face of `catalog`.
|
||||
Local { owner: Owner, face: Box<FaceInfo>, catalog: Arc<Catalog> },
|
||||
/// A subset of a face from the preview service.
|
||||
Subset(SubsetFont),
|
||||
}
|
||||
|
||||
impl HeldFace {
|
||||
/// `face` of `owner`'s catalog `catalog`.
|
||||
pub(crate) fn local(owner: Owner, face: FaceInfo, catalog: &Arc<Catalog>) -> HeldFace {
|
||||
HeldFace::Local { owner, face: Box::new(face), catalog: Arc::clone(catalog) }
|
||||
}
|
||||
|
||||
/// Whether the face is installed here.
|
||||
pub(crate) fn installed(&self) -> bool {
|
||||
matches!(self, HeldFace::Local { owner: Owner::Installed, .. })
|
||||
}
|
||||
|
||||
/// The face of a sample: `face`, or none.
|
||||
pub(crate) fn sample(face: Option<&HeldFace>) -> SampleFace<'_> {
|
||||
match face {
|
||||
Some(HeldFace::Local { owner, face, catalog }) => SampleFace::Face { catalog, owner: *owner, face },
|
||||
Some(HeldFace::Subset(subset)) => SampleFace::Subset(subset),
|
||||
None => SampleFace::Missing,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A sample of `text` in `face`, `points` high. Until the face is ready (while it loads, and for good when it is not
|
||||
/// available) the sample shows nothing and keeps its band. `points` is the user's sample size (data, as
|
||||
/// `DocRun::size`), not a UI size. The label names the sample for a screen reader (the family and the sample text).
|
||||
@@ -81,12 +119,16 @@ pub(crate) struct FontSample<'a> {
|
||||
/// [`LINE_EM`] of its size.
|
||||
#[prop(quantity = "band height the caller's layout gives, in points")]
|
||||
band: Option<f32>,
|
||||
/// The variation coordinates (axis tag, value) the face is drawn at, over its own: one registered variable face
|
||||
/// draws every named instance and every axis value.
|
||||
#[prop]
|
||||
coords: &'a [([u8; 4], f32)],
|
||||
}
|
||||
|
||||
impl<'a> FontSample<'a> {
|
||||
/// A sample of `text` in `face` at `points`, named `label`.
|
||||
pub(crate) fn new(label: impl Into<Label>, text: impl Into<Cow<'a, str>>, face: SampleFace<'a>, points: f32) -> Self {
|
||||
FontSample { common: Common::new(), text: text.into(), face, points, on_white: false, band: None }.label(label)
|
||||
FontSample { common: Common::new(), text: text.into(), face, points, on_white: false, band: None, coords: &[] }.label(label)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,7 +155,8 @@ impl Component for FontSample<'_> {
|
||||
return Vec2::new(cx.room.unwrap_or(0.0), band);
|
||||
};
|
||||
let ink = DataColor::new(Color32::PLACEHOLDER);
|
||||
let line = faces::sample_line(|doc| cx.layout_doc(doc), &font, &self.text, self.points, band, cx.room, ink);
|
||||
let sample = Sample::new(&self.text, &font, self.points, ink).at(self.coords);
|
||||
let line = faces::sample_line(|doc| cx.layout_doc(doc), sample, band, cx.room);
|
||||
Vec2::new(line.layout.size().x, band)
|
||||
}
|
||||
|
||||
@@ -121,7 +164,7 @@ impl Component for FontSample<'_> {
|
||||
let painter = ui.content_painter(cx);
|
||||
let ink = faces::sample_ink(&painter, cx.rect, self.on_white, cx.style.ink.egui());
|
||||
if let Some(font) = self.face.ready(cx) {
|
||||
faces::paint_sample(&painter, cx.content_rect, &font, &self.text, self.points, ink);
|
||||
faces::paint_sample(&painter, cx.content_rect, Sample::new(&self.text, &font, self.points, ink).at(self.coords));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
//! Stories of `FontSample`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
use super::{FontSample, SampleFace};
|
||||
use crate::craft_font_catalog::{Limits, Os};
|
||||
use crate::panel::faces::Owner;
|
||||
use crate::panel::fixtures::story_catalog;
|
||||
use crate::panel::fixtures::{VARIABLE, story_catalog};
|
||||
use crate::panel::samples::PANGRAM;
|
||||
use crate::panel::subsets::SubsetFont;
|
||||
use crate::{Catalog, FontEnv, Source};
|
||||
|
||||
/// The sample size of the stories: the panel's default sample size in points.
|
||||
const POINTS: f32 = 24.0;
|
||||
/// A sample a wide face shows whole in a story's room: where an ellipsis cuts moves with the display's scale.
|
||||
const SHORT: &str = "Quick brown fox";
|
||||
|
||||
#[story(FontSample<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn ready(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
@@ -23,6 +30,25 @@ fn ready(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
FontSample::new("Hack: sample", PANGRAM, face, POINTS).show(ui).into()
|
||||
}
|
||||
|
||||
/// A variable face at a coordinate it is not registered at: its boldest weight.
|
||||
#[story(FontSample<'static>, covers = [], drive = Drive::Never)]
|
||||
fn at_coordinates(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let catalog = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false));
|
||||
let faces = catalog.add_bytes(VARIABLE.to_vec(), Source::Bundled, &Limits::default()).unwrap_or_default();
|
||||
let face = match faces.first() {
|
||||
Some(face) => SampleFace::Face { catalog: &catalog, owner: Owner::Installed, face },
|
||||
None => SampleFace::Missing,
|
||||
};
|
||||
FontSample::new("Orbitron: sample", SHORT, face, POINTS).coords(&[(*b"wght", 900.0)]).show(ui).into()
|
||||
}
|
||||
|
||||
/// A subset from the preview service.
|
||||
#[story(FontSample<'static>, covers = [], drive = Drive::Never)]
|
||||
fn subset(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let font = SubsetFont { key: "story/orbitron".to_owned(), bytes: VARIABLE.into() };
|
||||
FontSample::new("Orbitron: sample", SHORT, SampleFace::Subset(&font), POINTS).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(FontSample<'static>, covers = [], drive = Drive::Never)]
|
||||
fn unavailable(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
FontSample::new("Hack: sample", PANGRAM, SampleFace::Missing, POINTS).show(ui).into()
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
//! The panel's previews from the font preview service: a small subset of a face instead of the whole family.
|
||||
//!
|
||||
//! The service's client is native only; on the web there is no service, and the panel keeps its whole-family previews.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_ui::fonts::FaceBytes;
|
||||
|
||||
use crate::index::Family;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod none;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod service;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) use none::Subsets;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use service::Subsets;
|
||||
|
||||
/// A row of the list: the family, whose list face draws it, and the text it shows.
|
||||
pub(crate) type Row<'a> = (&'a Family, String);
|
||||
|
||||
/// A subset that is here: its key among the document faces, and the font.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct SubsetFont {
|
||||
pub(crate) key: String,
|
||||
pub(crate) bytes: Arc<[u8]>,
|
||||
}
|
||||
|
||||
impl SubsetFont {
|
||||
/// The face of the subset, at its default coordinates.
|
||||
pub(crate) fn face(&self) -> FaceBytes {
|
||||
FaceBytes::new(Arc::clone(&self.bytes), 0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Where the preview service's client does not build: no service.
|
||||
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_host::Wake;
|
||||
|
||||
use super::{Row, SubsetFont};
|
||||
use crate::index::{Family, FontFile, Index};
|
||||
use crate::store::Installer;
|
||||
|
||||
pub(crate) struct Subsets;
|
||||
|
||||
impl Subsets {
|
||||
pub(crate) fn new(_: Arc<dyn Installer>) -> Subsets {
|
||||
Subsets
|
||||
}
|
||||
|
||||
pub(crate) fn read_settings_soon(&mut self) {}
|
||||
|
||||
pub(crate) fn available(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn serves(&self, _: &Family) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn loading(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn draws(&self, _: &Index, _: &Row<'_>) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn draws_detail(&self, _: &Index, _: &Family, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn unreachable(&self) -> Option<(&str, &str)> {
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn begin(&mut self, _: f64, _: &Wake) {}
|
||||
|
||||
pub(crate) fn next_wake(&self) -> Option<f64> {
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn typed(&mut self, _: String) {}
|
||||
|
||||
pub(crate) fn font(&self, _: &Index, _: &Row<'_>) -> Option<SubsetFont> {
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn detail_font(&self, _: &Index, _: &Family, _: &FontFile, _: &str) -> Option<SubsetFont> {
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn window(visible: &Range<usize>, _: usize) -> Range<usize> {
|
||||
visible.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn request(&mut self, _: &Index, _: usize, _: &[Option<Row<'_>>], _: Range<usize>) {}
|
||||
|
||||
pub(crate) fn request_detail(&mut self, _: Option<(&Index, &Family, &str)>, _: &[usize]) {}
|
||||
|
||||
pub(crate) fn cancel_all(&mut self) {}
|
||||
}
|
||||
@@ -0,0 +1,518 @@
|
||||
//! The subsets of the preview service.
|
||||
//!
|
||||
//! The rows on screen ask for their face's sample subset first, then the rows one screen above and two below; rows
|
||||
//! that leave that window are cancelled. Once the screen's samples are in, its Latin rows also get the ASCII subset, so
|
||||
//! typed ASCII and the presets draw at once. Other typed text asks for a subset of its own characters, for the rows on
|
||||
//! screen only, once the typing pauses. Without a service nothing is asked and the list keeps its whole-family
|
||||
//! previews; with the previews setting off, only subsets in the disk cache are shown.
|
||||
//!
|
||||
//! The details sheet asks for each file it shows, before the list's rows: a static file's subset as the list would, a
|
||||
//! variable file's at the `var` instance, which keeps every axis.
|
||||
//!
|
||||
//! Drawing only looks subsets up ([`Subsets::font`], [`Subsets::detail_font`]). What the pass showed is taken in once,
|
||||
//! after the real run of the list ([`Subsets::request`]) and of the sheet ([`Subsets::request_detail`]).
|
||||
//!
|
||||
//! The service holds the built-in sources' files only, and asking it for another file would tell it the file's hash: a
|
||||
//! family of a source the user added is never asked for (`key_of`).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_font_store::preview::{Codepoints, Instance, PreviewError, PreviewKey, Previews, SampleHash, Subset};
|
||||
use craft_host::Wake;
|
||||
|
||||
use super::{Row, SubsetFont};
|
||||
use crate::index::{Family, FontFile, Index};
|
||||
use crate::panel::app::list_file;
|
||||
use crate::store::{Installer, PreviewStore};
|
||||
|
||||
/// Rows on screen.
|
||||
const VISIBLE: u32 = 3;
|
||||
/// Rows one screen above and two below.
|
||||
const WINDOW: u32 = 2;
|
||||
/// ASCII subsets for the rows on screen, once their samples are in.
|
||||
const BACKGROUND: u32 = 1;
|
||||
/// The files of the family the details sheet shows.
|
||||
const DETAIL: u32 = 4;
|
||||
|
||||
/// How long typing pauses before its characters are asked for.
|
||||
const PAUSE_SECS: f64 = 0.25;
|
||||
/// A failed subset is asked for again after this long, not every frame.
|
||||
const RETRY_SECS: f64 = 30.0;
|
||||
/// Decoded subsets kept in memory, more while more are in use; the disk cache holds more.
|
||||
const MAX_HELD: usize = 256;
|
||||
/// A subset wanted within this many passes is in use.
|
||||
const IN_USE: u64 = 2;
|
||||
|
||||
/// A decoded subset and the pass it was last wanted in.
|
||||
struct Held {
|
||||
bytes: Arc<[u8]>,
|
||||
used: u64,
|
||||
}
|
||||
|
||||
pub(crate) struct Subsets {
|
||||
installer: Arc<dyn Installer>,
|
||||
/// `None` only while it is being given its wake.
|
||||
pool: Option<Previews>,
|
||||
woken: bool,
|
||||
/// A service is set, so rows draw from subsets; and previews are on, so subsets not in the disk cache are fetched.
|
||||
available: bool,
|
||||
fetching: bool,
|
||||
/// The effective service the last settings read saw; another one starts afresh.
|
||||
service: Option<String>,
|
||||
/// The settings are read on the next pass.
|
||||
settings_stale: bool,
|
||||
fonts: HashMap<PreviewKey, Held>,
|
||||
/// Subsets that didn't load, and when; kept until one loads, so a family whose subset is asked for again still
|
||||
/// offers a session preview meanwhile.
|
||||
failed: HashMap<PreviewKey, f64>,
|
||||
/// Sample subsets the service doesn't have for the text this index gives (HTTP 404), so those faces draw from a
|
||||
/// subset of the sample text's characters. Keyed by the sample's hash too, so another sample text asks for the
|
||||
/// sample again.
|
||||
sample_missing: HashSet<PreviewKey>,
|
||||
/// Asked for and not back yet, at this priority.
|
||||
asked: HashMap<PreviewKey, u32>,
|
||||
/// The subset each face (by sha256 and instance) was last drawn with, drawn while the next one loads.
|
||||
shown: HashMap<(String, Instance), PreviewKey>,
|
||||
/// Asked for by the details sheet; the list leaves them be.
|
||||
detail: HashSet<PreviewKey>,
|
||||
/// The text setting as last seen, and since when.
|
||||
typed: (String, f64),
|
||||
/// The details sheet or the list shows typed characters that are asked for once typing pauses.
|
||||
waits: bool,
|
||||
/// The service and the error of its last failed request, until a preview loads from it: the page tells the user the
|
||||
/// server can't be reached instead of showing no previews silently.
|
||||
unreachable: Option<(String, String)>,
|
||||
pass: u64,
|
||||
now: f64,
|
||||
}
|
||||
|
||||
impl Subsets {
|
||||
/// Subsets fetched with `installer`'s own client and cache.
|
||||
pub(crate) fn new(installer: Arc<dyn Installer>) -> Subsets {
|
||||
let store: Arc<dyn PreviewStore> = Arc::clone(&installer) as Arc<dyn PreviewStore>;
|
||||
Subsets::with_pool(installer, Previews::new(store))
|
||||
}
|
||||
|
||||
fn with_pool(installer: Arc<dyn Installer>, pool: Previews) -> Subsets {
|
||||
Subsets {
|
||||
installer,
|
||||
pool: Some(pool),
|
||||
woken: false,
|
||||
available: false,
|
||||
fetching: false,
|
||||
service: None,
|
||||
settings_stale: true,
|
||||
fonts: HashMap::new(),
|
||||
failed: HashMap::new(),
|
||||
sample_missing: HashSet::new(),
|
||||
asked: HashMap::new(),
|
||||
shown: HashMap::new(),
|
||||
detail: HashSet::new(),
|
||||
typed: (String::new(), f64::NEG_INFINITY),
|
||||
waits: false,
|
||||
unreachable: None,
|
||||
pass: 0,
|
||||
now: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches through `pool` instead.
|
||||
pub(crate) fn replace(&mut self, pool: Previews) {
|
||||
*self = Subsets::with_pool(Arc::clone(&self.installer), pool);
|
||||
}
|
||||
|
||||
/// Reads the service and previews settings again on the next pass.
|
||||
pub(crate) fn read_settings_soon(&mut self) {
|
||||
self.settings_stale = true;
|
||||
}
|
||||
|
||||
/// Whether rows draw from subsets: a service is set.
|
||||
pub(crate) fn available(&self) -> bool {
|
||||
self.available
|
||||
}
|
||||
|
||||
/// Whether the details sheet draws the styles of `family` from subsets: a service is set, which holds its files.
|
||||
pub(crate) fn serves(&self, family: &Family) -> bool {
|
||||
self.available && family.is_curated()
|
||||
}
|
||||
|
||||
/// Whether rows and the details sheet get their previews from the service: a service is set and previews are on.
|
||||
/// Otherwise a session download is the only way to see a font.
|
||||
fn previewing(&self) -> bool {
|
||||
self.available && self.fetching
|
||||
}
|
||||
|
||||
/// Whether the service draws `row`, or is still loading it: previews are on and its subset hasn't failed. A row it
|
||||
/// doesn't draw offers a session preview.
|
||||
pub(crate) fn draws(&self, index: &Index, row: &Row<'_>) -> bool {
|
||||
self.previewing() && self.key(index, row).is_some_and(|k| !self.failed.contains_key(&k))
|
||||
}
|
||||
|
||||
/// Whether the service draws every file of `family` in the details sheet with `text`, or is still loading them: for
|
||||
/// each, the subset `text` needs or the sample subset hasn't failed.
|
||||
pub(crate) fn draws_detail(&self, index: &Index, family: &Family, text: &str) -> bool {
|
||||
let fine = |key: Option<PreviewKey>| key.is_some_and(|k| !self.failed.contains_key(&k));
|
||||
self.previewing()
|
||||
&& family.files.iter().all(|file| {
|
||||
let instance = detail_instance(file);
|
||||
fine(text_key(index, family, file, instance, text, &self.sample_missing)) || fine(self.sample_key(index, family, file, instance))
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads which service is set and whether previews are on; a change asks for everything again.
|
||||
fn read_settings(&mut self) {
|
||||
let service = self.installer.preview_service();
|
||||
let available = service.is_some();
|
||||
let fetching = self.pool.as_ref().is_some_and(Previews::available);
|
||||
if (available, fetching, &service) != (self.available, self.fetching, &self.service) {
|
||||
(self.available, self.fetching, self.service) = (available, fetching, service);
|
||||
self.failed.clear();
|
||||
self.detail.clear();
|
||||
self.sample_missing.clear();
|
||||
self.unreachable = None;
|
||||
self.cancel_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// The preview server and the error of its last failed request, while none has loaded since.
|
||||
pub(crate) fn unreachable(&self) -> Option<(&str, &str)> {
|
||||
self.unreachable.as_ref().map(|(service, error)| (service.as_str(), error.as_str()))
|
||||
}
|
||||
|
||||
/// Whether subsets are being fetched.
|
||||
pub(crate) fn loading(&self) -> bool {
|
||||
!self.asked.is_empty()
|
||||
}
|
||||
|
||||
/// Takes in what the pool fetched, at the pass time `now`. `wake` asks the UI for a pass when a fetch ends.
|
||||
pub(crate) fn begin(&mut self, now: f64, wake: &Wake) {
|
||||
self.now = now;
|
||||
self.waits = false;
|
||||
if !std::mem::replace(&mut self.woken, true) {
|
||||
let wake = wake.clone();
|
||||
self.pool = self.pool.take().map(|pool| pool.on_ready(move || wake.wake()));
|
||||
}
|
||||
if std::mem::take(&mut self.settings_stale) {
|
||||
self.read_settings();
|
||||
}
|
||||
let Some(pool) = &self.pool else { return };
|
||||
for preview in pool.poll() {
|
||||
// A result for a key no longer asked for still fills the cache in memory.
|
||||
self.asked.remove(&preview.key);
|
||||
match preview.font {
|
||||
Ok(font) => {
|
||||
self.unreachable = None;
|
||||
self.failed.remove(&preview.key);
|
||||
self.fonts.insert(preview.key, Held { bytes: font.into(), used: self.pass });
|
||||
}
|
||||
Err(e) => {
|
||||
log::debug!("preview {}: {e}", preview.key.path());
|
||||
if let (PreviewError::Failed(message), Some(service)) = (&e, &self.service) {
|
||||
if self.unreachable.as_ref().is_none_or(|(s, _)| s != service) {
|
||||
log::warn!("font preview server {service} didn't answer: {message}");
|
||||
}
|
||||
self.unreachable = Some((service.clone(), message.clone()));
|
||||
}
|
||||
if e == PreviewError::NotFound && matches!(preview.key.subset(), Subset::Sample(_)) {
|
||||
self.sample_missing.insert(preview.key);
|
||||
} else {
|
||||
self.failed.insert(preview.key, self.now);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In how many seconds the next pass asks for something this one waited with: typed characters, or a subset that
|
||||
/// failed.
|
||||
pub(crate) fn next_wake(&self) -> Option<f64> {
|
||||
let typed = self.waits.then_some(PAUSE_SECS - (self.now - self.typed.1));
|
||||
let retries = self.failed.values().map(|at| RETRY_SECS - (self.now - at));
|
||||
typed.into_iter().chain(retries).filter(|seconds| *seconds > 0.0).reduce(f64::min)
|
||||
}
|
||||
|
||||
/// Takes in the text setting (the sample typed, the preset and the language filtered by) once the controls have
|
||||
/// changed it this pass, before anything is asked for: typed characters are asked for once it pauses.
|
||||
pub(crate) fn typed(&mut self, typed: String) {
|
||||
if typed != self.typed.0 {
|
||||
self.typed = (typed, self.now);
|
||||
}
|
||||
}
|
||||
|
||||
fn paused(&self) -> bool {
|
||||
self.now - self.typed.1 >= PAUSE_SECS
|
||||
}
|
||||
|
||||
/// The subset `row` draws with: the one its text needs, else while that loads the one its face was last drawn with.
|
||||
/// `None` without a service, and for a row whose subset failed: the row then shows what it shows without the
|
||||
/// service.
|
||||
pub(crate) fn font(&self, index: &Index, row: &Row<'_>) -> Option<SubsetFont> {
|
||||
if !self.available {
|
||||
return None;
|
||||
}
|
||||
self.drawn(&self.key(index, row)?).and_then(|key| self.subset_font(key))
|
||||
}
|
||||
|
||||
/// The subset that draws `text` in `file` of `family` in the details sheet, which asks for it with
|
||||
/// [`Subsets::request_detail`]: the one `text` needs, else the file's sample subset, which draws while that loads,
|
||||
/// when it failed, and for text of more characters than a request may name. `None` without a service, while nothing
|
||||
/// of the file has loaded, and when both failed.
|
||||
pub(crate) fn detail_font(&self, index: &Index, family: &Family, file: &FontFile, text: &str) -> Option<SubsetFont> {
|
||||
if !self.available {
|
||||
return None;
|
||||
}
|
||||
self.detail_drawn(index, family, file, text).and_then(|key| self.subset_font(&key))
|
||||
}
|
||||
|
||||
fn detail_drawn(&self, index: &Index, family: &Family, file: &FontFile, text: &str) -> Option<PreviewKey> {
|
||||
let instance = detail_instance(file);
|
||||
let drawn = |key: Option<PreviewKey>| key.and_then(|key| self.drawn(&key).cloned());
|
||||
drawn(text_key(index, family, file, instance, text, &self.sample_missing)).or_else(|| drawn(self.sample_key(index, family, file, instance)))
|
||||
}
|
||||
|
||||
/// The key of the subset drawn where `want` is wanted: `want` if it is here, else the one its face was last drawn
|
||||
/// with at its instance. `None` when `want` failed.
|
||||
fn drawn<'a>(&'a self, want: &'a PreviewKey) -> Option<&'a PreviewKey> {
|
||||
if self.has_failed(want) {
|
||||
return None;
|
||||
}
|
||||
if self.fonts.contains_key(want) {
|
||||
return Some(want);
|
||||
}
|
||||
self.shown.get(&face_of(want)).filter(|last| self.fonts.contains_key(*last))
|
||||
}
|
||||
|
||||
fn subset_font(&self, key: &PreviewKey) -> Option<SubsetFont> {
|
||||
self.fonts.get(key).map(|held| SubsetFont { key: key.path(), bytes: Arc::clone(&held.bytes) })
|
||||
}
|
||||
|
||||
/// Takes in that this pass drew the subset `key`.
|
||||
fn note_drawn(&mut self, key: PreviewKey) {
|
||||
if let Some(held) = self.fonts.get_mut(&key) {
|
||||
held.used = self.pass;
|
||||
self.shown.insert(face_of(&key), key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks for the subsets of the files (by position) of `shown`'s family that the sheet draws with its text, before
|
||||
/// the list's rows; called at the end of each pass, also when the sheet is closed. What it no longer wants goes back
|
||||
/// to the list, which cancels what it doesn't want either.
|
||||
pub(crate) fn request_detail(&mut self, shown: Option<(&Index, &Family, &str)>, files: &[usize]) {
|
||||
self.pass += 1;
|
||||
let Some((index, family, text)) = shown.filter(|_| self.available) else {
|
||||
self.detail.clear();
|
||||
return;
|
||||
};
|
||||
let mut asking = HashMap::new();
|
||||
for file in files.iter().filter_map(|n| family.files.get(*n)) {
|
||||
let instance = detail_instance(file);
|
||||
if let Some(sample) = self.sample_key(index, family, file, instance) {
|
||||
self.want(&mut asking, sample, DETAIL);
|
||||
}
|
||||
if let Some(want) = text_key(index, family, file, instance, text, &self.sample_missing) {
|
||||
if matches!(want.subset(), Subset::Codepoints(_)) && !self.paused() {
|
||||
self.waits = true;
|
||||
} else {
|
||||
self.want(&mut asking, want, DETAIL);
|
||||
}
|
||||
}
|
||||
if let Some(key) = self.detail_drawn(index, family, file, text) {
|
||||
self.note_drawn(key);
|
||||
}
|
||||
}
|
||||
self.detail = asking.keys().cloned().collect();
|
||||
self.ask(asking);
|
||||
}
|
||||
|
||||
/// The rows to pass to [`Subsets::request`] when `visible` of `count` rows are on screen: those and one screen above
|
||||
/// and two below.
|
||||
pub(crate) fn window(visible: &Range<usize>, count: usize) -> Range<usize> {
|
||||
let screen = visible.len();
|
||||
visible.start.saturating_sub(screen)..visible.end.saturating_add(2 * screen).min(count)
|
||||
}
|
||||
|
||||
/// Asks for the subsets of the list's rows from `start` on (`None` for a row drawn without the service, such as an
|
||||
/// installed family), `visible` of them on screen, and cancels those no longer wanted.
|
||||
pub(crate) fn request(&mut self, index: &Index, start: usize, rows: &[Option<Row<'_>>], visible: Range<usize>) {
|
||||
if !self.available {
|
||||
return;
|
||||
}
|
||||
let row = |n: usize| rows.get(n.checked_sub(start)?)?.as_ref();
|
||||
let mut wanted: HashMap<PreviewKey, u32> = HashMap::new();
|
||||
let screen = visible.len();
|
||||
let paused = self.paused();
|
||||
let mut settled = true;
|
||||
let mut latin = Vec::new();
|
||||
for row in visible.clone().filter_map(row) {
|
||||
let family = row.0;
|
||||
// A family without a sample text still gets the subset its row's text needs.
|
||||
if let Some(sample) = list_file(family).and_then(|f| self.sample_key(index, family, f, Instance::List)) {
|
||||
settled &= self.fonts.contains_key(&sample) || self.has_failed(&sample);
|
||||
self.want(&mut wanted, sample, VISIBLE);
|
||||
}
|
||||
if let Some(ascii) = list_file(family).filter(|_| covers_latin(family)).and_then(|f| key_of(family, f, Instance::List, Subset::Ascii)) {
|
||||
latin.push(ascii);
|
||||
}
|
||||
let Some(key) = self.key(index, row) else { continue };
|
||||
if let Some(drawn) = self.drawn(&key).cloned() {
|
||||
self.note_drawn(drawn);
|
||||
}
|
||||
if matches!(key.subset(), Subset::Codepoints(_)) && !paused {
|
||||
self.waits = true;
|
||||
} else {
|
||||
self.want(&mut wanted, key, VISIBLE);
|
||||
}
|
||||
}
|
||||
if settled {
|
||||
for ascii in latin {
|
||||
self.want(&mut wanted, ascii, BACKGROUND);
|
||||
}
|
||||
}
|
||||
let above = visible.start.saturating_sub(screen)..visible.start;
|
||||
let below = visible.end..visible.end.saturating_add(2 * screen);
|
||||
for (family, _) in above.chain(below).filter_map(row) {
|
||||
if let Some(sample) =
|
||||
list_file(family).and_then(|f| sample_subset(index, family, f, Instance::List)).filter(|k| !self.sample_missing.contains(k))
|
||||
{
|
||||
self.want(&mut wanted, sample, WINDOW);
|
||||
}
|
||||
}
|
||||
|
||||
let detail = &self.detail;
|
||||
let keep = |k: &PreviewKey| wanted.contains_key(k) || detail.contains(k);
|
||||
if let Some(pool) = &self.pool
|
||||
&& self.asked.keys().any(|k| !keep(k))
|
||||
{
|
||||
pool.retain(&keep);
|
||||
self.asked.retain(|k, _| keep(k));
|
||||
}
|
||||
wanted.retain(|key, _| !detail.contains(key));
|
||||
self.ask(wanted);
|
||||
self.trim();
|
||||
}
|
||||
|
||||
/// Sends `wanted` to the pool, where it does not know them at this priority.
|
||||
fn ask(&mut self, wanted: HashMap<PreviewKey, u32>) {
|
||||
let Some(pool) = &self.pool else { return };
|
||||
for (key, priority) in wanted {
|
||||
if self.asked.get(&key) != Some(&priority) {
|
||||
pool.request(key.clone(), priority);
|
||||
self.asked.insert(key, priority);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sample subset of `file` at `instance`, or when the service doesn't have it for this text its
|
||||
/// [`sample_fallback`]. `None` when there is neither.
|
||||
fn sample_key(&self, index: &Index, family: &Family, file: &FontFile, instance: Instance) -> Option<PreviewKey> {
|
||||
let sample = sample_subset(index, family, file, instance)?;
|
||||
if self.sample_missing.contains(&sample) { sample_fallback(index, family, file, instance) } else { Some(sample) }
|
||||
}
|
||||
|
||||
fn key(&self, index: &Index, (family, text): &Row<'_>) -> Option<PreviewKey> {
|
||||
text_key(index, family, list_file(family)?, Instance::List, text, &self.sample_missing)
|
||||
}
|
||||
|
||||
/// Adds `key` to `wanted` at `priority` unless it is here, failed lately, or can't load: with previews off, only
|
||||
/// what the disk cache has.
|
||||
fn want(&mut self, wanted: &mut HashMap<PreviewKey, u32>, key: PreviewKey, priority: u32) {
|
||||
if let Some(held) = self.fonts.get_mut(&key) {
|
||||
held.used = self.pass;
|
||||
return;
|
||||
}
|
||||
if self.has_failed(&key) || wanted.get(&key).is_some_and(|p| *p >= priority) {
|
||||
return;
|
||||
}
|
||||
let cached = || self.pool.as_ref().and_then(Previews::cache).is_some_and(|c| c.contains(&key.path()));
|
||||
if self.fetching || self.asked.contains_key(&key) || cached() {
|
||||
wanted.insert(key, priority);
|
||||
}
|
||||
}
|
||||
|
||||
fn has_failed(&self, key: &PreviewKey) -> bool {
|
||||
self.failed.get(key).is_some_and(|at| self.now - at < RETRY_SECS)
|
||||
}
|
||||
|
||||
/// Cancels everything the list asked for, as when it isn't shown.
|
||||
pub(crate) fn cancel_all(&mut self) {
|
||||
if self.asked.keys().all(|k| self.detail.contains(k)) {
|
||||
return;
|
||||
}
|
||||
let detail = &self.detail;
|
||||
if let Some(pool) = &self.pool {
|
||||
pool.retain(|k| detail.contains(k));
|
||||
}
|
||||
self.asked.retain(|k, _| detail.contains(k));
|
||||
}
|
||||
|
||||
/// Drops the subsets wanted least recently past [`MAX_HELD`], but none in use.
|
||||
fn trim(&mut self) {
|
||||
if self.fonts.len() <= MAX_HELD {
|
||||
return;
|
||||
}
|
||||
let mut by_use: Vec<(u64, PreviewKey)> =
|
||||
self.fonts.iter().filter(|(_, held)| held.used + IN_USE < self.pass).map(|(k, held)| (held.used, k.clone())).collect();
|
||||
by_use.sort_by_key(|(used, _)| *used);
|
||||
for (_, key) in by_use.into_iter().take(self.fonts.len() - MAX_HELD) {
|
||||
self.fonts.remove(&key);
|
||||
}
|
||||
self.shown.retain(|_, k| self.fonts.contains_key(k));
|
||||
}
|
||||
}
|
||||
|
||||
/// The face a subset is of, and the instance.
|
||||
fn face_of(key: &PreviewKey) -> (String, Instance) {
|
||||
(key.sha256().to_owned(), key.instance())
|
||||
}
|
||||
|
||||
/// The instance the details sheet draws `file` at: every axis for a variable file.
|
||||
fn detail_instance(file: &FontFile) -> Instance {
|
||||
if file.is_variable() { Instance::Var } else { Instance::List }
|
||||
}
|
||||
|
||||
/// The key of `subset` of `file` at `instance`; `None` for a family of a source the user added.
|
||||
fn key_of(family: &Family, file: &FontFile, instance: Instance, subset: Subset) -> Option<PreviewKey> {
|
||||
family.is_curated().then(|| PreviewKey::new(&file.sha256, instance, subset)).flatten()
|
||||
}
|
||||
|
||||
fn covers_latin(family: &Family) -> bool {
|
||||
family.scripts.iter().any(|s| s == "Latn")
|
||||
}
|
||||
|
||||
/// The sample subset of `file` at `instance` for the text `index` gives it.
|
||||
fn sample_subset(index: &Index, family: &Family, file: &FontFile, instance: Instance) -> Option<PreviewKey> {
|
||||
let text = index.sample_text(family, file)?;
|
||||
key_of(family, file, instance, Subset::Sample(SampleHash::of(text)))
|
||||
}
|
||||
|
||||
/// The subset that draws `text` in `file`: the sample when the sample subset has every character (the sentence and the
|
||||
/// family name), else ASCII for printable ASCII in a Latin face, else the text's own characters. A sample the service
|
||||
/// doesn't have gives [`sample_fallback`] instead. `None` for text of more characters than a request may name.
|
||||
fn text_key(index: &Index, family: &Family, file: &FontFile, instance: Instance, text: &str, missing: &HashSet<PreviewKey>) -> Option<PreviewKey> {
|
||||
let sample = index.sample_text(family, file);
|
||||
let in_sample = |c: char| c == ' ' || sample.is_some_and(|s| s.contains(c)) || family.family.contains(c);
|
||||
if sample == Some(text) || (sample.is_some() && text.chars().all(in_sample)) {
|
||||
let key = sample_subset(index, family, file, instance)?;
|
||||
if !missing.contains(&key) {
|
||||
return Some(key);
|
||||
}
|
||||
if let Some(fallback) = sample_fallback(index, family, file, instance) {
|
||||
return Some(fallback);
|
||||
}
|
||||
}
|
||||
let subset = if covers_latin(family) && text.chars().all(|c| matches!(c, ' '..='~')) {
|
||||
Subset::Ascii
|
||||
} else {
|
||||
Subset::Codepoints(Codepoints::from_text(text))
|
||||
};
|
||||
key_of(family, file, instance, subset)
|
||||
}
|
||||
|
||||
/// The subset of the sample text's characters and the family name, which the sample subset holds too. `None` when that
|
||||
/// is more characters than a request may name.
|
||||
fn sample_fallback(index: &Index, family: &Family, file: &FontFile, instance: Instance) -> Option<PreviewKey> {
|
||||
let text = index.sample_text(family, file)?;
|
||||
key_of(family, file, instance, Subset::Codepoints(Codepoints::from_text(&format!("{text}{}", family.family))))
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::{ComponentStyle, Corners, DataColor, Metrics, StyleColor, StyleCx, SurfaceKind};
|
||||
use egui::{Color32, Pos2, Rect, Vec2};
|
||||
|
||||
use crate::panel::faces;
|
||||
use crate::panel::faces::{self, Sample};
|
||||
use crate::panel::specimen::SampleFace;
|
||||
|
||||
use super::SAMPLE_EM;
|
||||
@@ -92,7 +92,8 @@ impl Component for FontPreviewBanner<'_> {
|
||||
let inner = cx.room.map(|room| (room - 2.0 * style.pad).max(0.0));
|
||||
let sample = self.face.ready(cx).map_or(0.0, |font| {
|
||||
let ink = DataColor::new(Color32::PLACEHOLDER);
|
||||
faces::sample_line(|doc| cx.layout_doc(doc), &font, self.text, style.band * SAMPLE_EM, style.band, inner, ink).layout.size().x
|
||||
let sample = Sample::new(self.text, &font, style.band * SAMPLE_EM, ink);
|
||||
faces::sample_line(|doc| cx.layout_doc(doc), sample, style.band, inner).layout.size().x
|
||||
});
|
||||
let name = TextRun::new(self.name).role(TypeRole::Caption);
|
||||
let name = inner.map_or_else(|| cx.layout(&name), |width| cx.layout_at(&name, width)).size().x;
|
||||
@@ -114,7 +115,7 @@ impl Component for FontPreviewBanner<'_> {
|
||||
let painter = ui.content_painter(cx);
|
||||
let ink = faces::sample_ink(&painter, band, self.on_white, style.ink.egui());
|
||||
if let Some(font) = self.face.ready(cx) {
|
||||
faces::paint_sample(&painter, band, &font, self.text, points, ink);
|
||||
faces::paint_sample(&painter, band, Sample::new(self.text, &font, points, ink));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,16 +4,22 @@ use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_font_manager::craft_font_catalog::Os;
|
||||
use craft_font_manager::index::Index;
|
||||
use craft_font_manager::store::{Call, Conflict, FakeStore, Installer as _};
|
||||
use craft_font_manager::{Catalog, FontEnv, FontsPanel, FontsPanelView, Options};
|
||||
use craft_font_manager::{CATALOGS, Catalog, FontEnv, FontsPanel, FontsPanelView, Options};
|
||||
use craft_font_store::preview::{Fetch, Previews};
|
||||
use craft_font_store::{Cancel, FetchError};
|
||||
use craft_host::{AppInfo, Host, InlineJobs, Jobs, MemorySections};
|
||||
use craft_i18n::I18n;
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::{Fixture, Room, Target, trial};
|
||||
use egui::{Key, Modifiers, Pos2};
|
||||
use egui::{Event, Key, Modifiers, Pos2, Vec2};
|
||||
|
||||
const HACK: &str = "ofl/hack/Hack-Regular.ttf";
|
||||
const UBUNTU: &str = "ufl/ubuntu/Ubuntu-Light.ttf";
|
||||
@@ -107,15 +113,26 @@ fn setup_seeded(name: &str, sections: Arc<MemorySections>, jobs: Arc<dyn Jobs>,
|
||||
|
||||
/// The panel over the system under `root` and `store`, as at a start of the app.
|
||||
fn start(root: &Path, store: Arc<FakeStore>, sections: Arc<MemorySections>, jobs: Arc<dyn Jobs>) -> Rig {
|
||||
let panel = FontsPanel::new(Options::new(catalog(root), store.clone(), Ok(index())));
|
||||
show(panel, store, host_with(sections, jobs))
|
||||
}
|
||||
|
||||
/// The fonts installed under `root`, its store folder included.
|
||||
fn catalog(root: &Path) -> Arc<Catalog> {
|
||||
let env = FontEnv { os: Os::Unix, root: root.to_owned(), font_store: Some(root.join("store")), ..FontEnv::default() };
|
||||
let catalog = Arc::new(Catalog::new(env).with_font_service(false));
|
||||
catalog.rescan();
|
||||
let panel = Rc::new(RefCell::new(FontsPanel::new(Options::new(catalog, store.clone(), Ok(index())))));
|
||||
catalog
|
||||
}
|
||||
|
||||
/// `panel` over `store`, shown to a window of `host`.
|
||||
fn show(panel: FontsPanel, store: Arc<FakeStore>, host: Arc<Host>) -> Rig {
|
||||
let panel = Rc::new(RefCell::new(panel));
|
||||
let shown = Rc::clone(&panel);
|
||||
let mut fx = Fixture::new(move |ui| {
|
||||
FontsPanelView::new(&mut shown.borrow_mut()).show(ui);
|
||||
});
|
||||
fx.in_room(Room::Window).host(host_with(sections, jobs));
|
||||
fx.in_room(Room::Window).host(host);
|
||||
fx.settle();
|
||||
Rig { fx, panel, store }
|
||||
}
|
||||
@@ -329,3 +346,371 @@ fn a_cards_install_menu_chooses_where_the_fonts_go() {
|
||||
assert_eq!(rig.store.calls(), [Call::Install("Hack".into())]);
|
||||
assert_eq!(rig.panel.borrow().details_family(), None);
|
||||
}
|
||||
|
||||
/// A preview service that answers every subset with the same small font, and logs what it answered. While held it
|
||||
/// answers nothing, and a request cancelled meanwhile is logged as cancelled instead.
|
||||
#[derive(Default)]
|
||||
struct FakeService {
|
||||
answered: Mutex<Vec<String>>,
|
||||
cancelled: Mutex<Vec<String>>,
|
||||
/// Requests that reached the service.
|
||||
started: AtomicUsize,
|
||||
held: AtomicBool,
|
||||
/// Answers sample subsets with HTTP 404, as for a sample text the service doesn't have.
|
||||
no_samples: AtomicBool,
|
||||
/// Answers every subset with HTTP 500.
|
||||
failing: AtomicBool,
|
||||
}
|
||||
|
||||
impl Fetch for FakeService {
|
||||
fn get(&self, url: &str, _: u64, cancel: &Cancel) -> Result<Vec<u8>, FetchError> {
|
||||
self.started.fetch_add(1, Ordering::SeqCst);
|
||||
while self.held.load(Ordering::SeqCst) && !cancel.is_cancelled() {
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
self.cancelled.lock().unwrap_or_else(PoisonError::into_inner).push(url.to_owned());
|
||||
return Err(FetchError::Cancelled);
|
||||
}
|
||||
self.answered.lock().unwrap_or_else(PoisonError::into_inner).push(url.to_owned());
|
||||
if self.no_samples.load(Ordering::SeqCst) && url.contains("/sample-") {
|
||||
return Err(FetchError::Failed("HTTP 404".into()));
|
||||
}
|
||||
if self.failing.load(Ordering::SeqCst) {
|
||||
return Err(FetchError::Failed("HTTP 500".into()));
|
||||
}
|
||||
Ok(include_bytes!("../data/Tiny-glyf.woff2").to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
impl FakeService {
|
||||
/// The URLs answered since the last call.
|
||||
fn urls(&self) -> Vec<String> {
|
||||
std::mem::take(&mut *self.answered.lock().unwrap_or_else(PoisonError::into_inner))
|
||||
}
|
||||
|
||||
/// The numbers of the families whose `subset` the URLs of `answered` name: `sample`, `ascii`, or `u/` for typed
|
||||
/// characters.
|
||||
fn numbers(answered: &[String], subset: &str) -> Vec<usize> {
|
||||
let mut numbers: Vec<usize> = answered
|
||||
.iter()
|
||||
.filter_map(|url| url.split_once("/v1/faces/"))
|
||||
.filter(|(_, path)| path[64..].starts_with(&format!("/list/{subset}")))
|
||||
.map(|(_, path)| usize::from_str_radix(&path[..2], 16).unwrap())
|
||||
.collect();
|
||||
numbers.sort_unstable();
|
||||
numbers
|
||||
}
|
||||
}
|
||||
|
||||
const SERVICE: &str = "http://127.0.0.1:9";
|
||||
const SAMPLE: &str = "Sphinx of black quartz, judge my vow";
|
||||
|
||||
/// An index of `families` with `SAMPLE` as the sample text of Latin.
|
||||
fn service_index(families: &str) -> Index {
|
||||
Index::from_json(service_json(families).as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
fn service_json(families: &str) -> String {
|
||||
format!(
|
||||
r#"{{"schema":1,"version":"1.2","source":"google/fonts","commit":"45e3d5269e4a17d823f6d84470bc084dc5ae46f6","base_url":"https://cdn.jsdelivr.net/gh/google/fonts@45e3d5269e4a17d823f6d84470bc084dc5ae46f6/",
|
||||
"languages":[{{"id":"en_Latn","name":"English","script":"Latn","population":1}}],
|
||||
"scripts":[{{"id":"Latn","name":"Latin"}}],
|
||||
"samples":{{"Latn":{{"text":"{SAMPLE}","method":"udhr","language":"en_Latn"}}}},
|
||||
"families":[{families}]}}"#
|
||||
)
|
||||
}
|
||||
|
||||
/// Sixty Latin families, `Family 01` to `Family 60`, whose one file's sha256 starts with the family's number in hex.
|
||||
fn latin_index() -> Index {
|
||||
let families: Vec<String> = (1..=60)
|
||||
.map(|n| {
|
||||
format!(
|
||||
r#"{{"family":"Family {n:02}","categories":["SANS_SERIF"],"languages":[0],"scripts":["Latn"],"license":"OFL","sample_script":"Latn",
|
||||
"files":[{{"path":"ofl/family{n}/Family-Regular.ttf","size":1000,"sha256":"{}","style":"normal","weight":400,"axes":[],"postscript":[]}}]}}"#,
|
||||
format!("{n:02x}").repeat(32)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
service_index(&families.join(","))
|
||||
}
|
||||
|
||||
/// The panel over `index` with no installed fonts and previews from `service`, whose address is not set yet.
|
||||
fn service_rig(name: &str, service: &Arc<FakeService>, index: Index) -> Rig {
|
||||
let root = root(name);
|
||||
std::fs::create_dir_all(root.join("store")).unwrap();
|
||||
let store = Arc::new(FakeStore::new(root.join("store"), HashMap::new()));
|
||||
let previews = Previews::new(store.clone()).with_fetcher(service.clone()).with_cache(None);
|
||||
let panel = FontsPanel::new(Options::new(catalog(&root), store.clone(), Ok(index))).with_previews(previews);
|
||||
show(panel, store, host_with(Arc::new(MemorySections::default()), Arc::new(InlineJobs)))
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
/// Sets the preview service and the previews setting, as a host's settings page does.
|
||||
fn set_previews(&mut self, on: bool) {
|
||||
self.store.set_preview_service(Some(SERVICE)).unwrap();
|
||||
self.store.set_previews_enabled(on).unwrap();
|
||||
self.panel.borrow_mut().reload_preview_settings();
|
||||
self.fx.settle();
|
||||
}
|
||||
|
||||
/// Runs passes until the panel has fetched what it asks for and asks for nothing more.
|
||||
fn load(&mut self) {
|
||||
let mut quiet = 0;
|
||||
for _ in 0..500 {
|
||||
self.fx.frame(Vec::new());
|
||||
quiet = if self.panel.borrow().loading_previews() { 0 } else { quiet + 1 };
|
||||
if quiet == 3 {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
panic!("previews kept loading");
|
||||
}
|
||||
|
||||
/// Types `text` as the sample, waits for the pause and loads what it asks for.
|
||||
fn sample(&mut self, text: &str) {
|
||||
self.type_into("Sample text", text);
|
||||
self.fx.advance(1.0);
|
||||
self.load();
|
||||
}
|
||||
|
||||
/// The numbers of the family cards on screen.
|
||||
fn numbers(&self) -> Vec<usize> {
|
||||
let numbers = self.cards().iter().filter_map(|name| name.strip_prefix("Family ")?.get(..2)?.parse().ok()).collect();
|
||||
sorted(numbers)
|
||||
}
|
||||
|
||||
/// Scrolls the cards by `points`.
|
||||
fn scroll(&mut self, points: f32) {
|
||||
let cards = self.named(Role::LIST, "Families").center();
|
||||
self.fx.frame(vec![Event::PointerMoved(cards)]).frame(vec![craft_ui::testing::pointer::wheel(-points)]);
|
||||
for _ in 0..4 {
|
||||
self.fx.advance(0.5);
|
||||
self.fx.frame(Vec::new());
|
||||
}
|
||||
self.fx.settle();
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted(mut numbers: Vec<usize>) -> Vec<usize> {
|
||||
numbers.sort_unstable();
|
||||
numbers
|
||||
}
|
||||
|
||||
/// The cards on screen and round them draw from the preview service without a click, and the typed text too; a card that
|
||||
/// scrolls away is not asked for any more.
|
||||
#[trial]
|
||||
fn previews_follow_the_screen_and_the_typed_text() {
|
||||
let service = Arc::new(FakeService::default());
|
||||
let mut rig = service_rig("previews", &service, latin_index());
|
||||
assert!(service.urls().is_empty(), "no service, no request");
|
||||
assert!(rig.present("Preview"), "the whole-family preview is offered");
|
||||
rig.set_previews(false);
|
||||
assert!(!rig.panel.borrow().loading_previews() && service.urls().is_empty(), "previews are off");
|
||||
|
||||
rig.set_previews(true);
|
||||
rig.load();
|
||||
assert!(!rig.panel.borrow().downloads_allowed(), "installs are still not allowed");
|
||||
assert!(rig.present("Nothing is installed until you allow downloads."));
|
||||
assert!(!rig.present("Preview"), "no session download while the service previews");
|
||||
let shown = rig.numbers();
|
||||
let answered = service.urls();
|
||||
let samples = FakeService::numbers(&answered, "sample-");
|
||||
assert!(shown.len() > 1 && shown.len() < 20, "{shown:?}");
|
||||
assert!(shown.iter().all(|n| samples.contains(n)) && samples.len() > shown.len(), "the screen, then the rows below it: {samples:?}");
|
||||
assert!(samples.len() < 60, "not the whole catalogue: {samples:?}");
|
||||
assert_eq!(FakeService::numbers(&answered, "ascii"), shown, "ASCII for the screen");
|
||||
|
||||
rig.sample("Hello, world");
|
||||
assert!(service.urls().is_empty(), "the ASCII subsets have typed ASCII");
|
||||
rig.sample("สวัสดี");
|
||||
assert_eq!(FakeService::numbers(&service.urls(), "u/"), shown, "one subset of the typed characters per row on screen");
|
||||
|
||||
service.held.store(true, Ordering::SeqCst);
|
||||
rig.scroll(6.0 * 400.0);
|
||||
assert!(rig.panel.borrow().loading_previews());
|
||||
let passed = rig.numbers();
|
||||
// The first wheel goes to the end of the list as its unshown cards are estimated, the second to its end.
|
||||
rig.scroll(100_000.0);
|
||||
rig.scroll(100_000.0);
|
||||
service.held.store(false, Ordering::SeqCst);
|
||||
rig.load();
|
||||
let last = rig.numbers();
|
||||
assert!(passed[0] > shown[shown.len() - 1] && last[0] > passed[passed.len() - 1] && last.contains(&60), "{shown:?} {passed:?} {last:?}");
|
||||
let answered = FakeService::numbers(&service.urls(), "u/");
|
||||
assert!(!answered.is_empty() && answered.iter().all(|n| last.contains(n)), "rows that left were asked for: {answered:?} {last:?}");
|
||||
}
|
||||
|
||||
/// A resize and a search that keep the cards on screen cancel nothing that is being fetched.
|
||||
#[trial]
|
||||
fn a_resize_and_a_search_cancel_no_preview() {
|
||||
let service = Arc::new(FakeService::default());
|
||||
service.held.store(true, Ordering::SeqCst);
|
||||
let mut rig = service_rig("previews-kept", &service, latin_index());
|
||||
rig.set_previews(true);
|
||||
for _ in 0..500 {
|
||||
if service.started.load(Ordering::SeqCst) > 0 {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
assert!(service.started.load(Ordering::SeqCst) > 0, "the service was asked");
|
||||
let shown = rig.numbers();
|
||||
rig.fx.room(Room::Window.size() + Vec2::new(40.0, 120.0)).settle();
|
||||
rig.type_into("Search", "Family");
|
||||
service.held.store(false, Ordering::SeqCst);
|
||||
rig.load();
|
||||
assert!(shown.iter().all(|n| rig.numbers().contains(n)), "the cards stayed on screen: {shown:?} {:?}", rig.numbers());
|
||||
let cancelled = std::mem::take(&mut *service.cancelled.lock().unwrap_or_else(PoisonError::into_inner));
|
||||
assert!(cancelled.is_empty(), "{cancelled:?}");
|
||||
let samples = FakeService::numbers(&service.urls(), "sample-");
|
||||
assert!(shown.iter().all(|n| samples.contains(n)), "{shown:?} {samples:?}");
|
||||
}
|
||||
|
||||
/// The service is not asked for the files of a source the user added, which offer the whole-family preview.
|
||||
#[trial]
|
||||
fn a_family_of_an_added_source_is_not_asked_of_the_service() {
|
||||
let service = Arc::new(FakeService::default());
|
||||
let file = format!(
|
||||
r#"{{"path":"ofl/added/Added-Regular.ttf","size":1000,"sha256":"{}","style":"normal","weight":400,"axes":[],"postscript":[]}}"#,
|
||||
"ef".repeat(32)
|
||||
);
|
||||
let family = format!(
|
||||
r#"{{"family":"Added","categories":["SANS_SERIF"],"languages":[0],"scripts":["Latn"],"license":"OFL","sample_script":"Latn","files":[{file}]}}"#
|
||||
);
|
||||
let index = Index::from_user_bytes(service_json(&family).as_bytes(), "https://fonts.example.org/index.json").unwrap();
|
||||
let mut rig = service_rig("previews-added", &service, index);
|
||||
rig.set_previews(true);
|
||||
rig.load();
|
||||
rig.sample("Hello, world");
|
||||
assert!(rig.present("Preview"), "the card offers the whole-family preview");
|
||||
rig.open("Added");
|
||||
rig.load();
|
||||
rig.named(Role::BUTTON, "Preview");
|
||||
assert_eq!(service.started.load(Ordering::SeqCst), 0, "{:?}", service.urls());
|
||||
}
|
||||
|
||||
/// A sample the service has not (another text) is asked for as the sample's characters, once.
|
||||
#[trial]
|
||||
fn a_sample_the_service_lacks_falls_back_to_its_characters_once() {
|
||||
let service = Arc::new(FakeService::default());
|
||||
service.no_samples.store(true, Ordering::SeqCst);
|
||||
let mut rig = service_rig("previews-404", &service, latin_index());
|
||||
rig.set_previews(true);
|
||||
rig.load();
|
||||
let shown = rig.numbers();
|
||||
assert_eq!(FakeService::numbers(&service.urls(), "u/"), shown, "one subset of the sample's characters per row on screen");
|
||||
rig.fx.advance(60.0);
|
||||
rig.load();
|
||||
assert!(FakeService::numbers(&service.urls(), "sample-").is_empty(), "the sample is not asked for again");
|
||||
}
|
||||
|
||||
/// A family the service can't draw offers the whole-family preview, and the panel names the server that failed.
|
||||
#[trial]
|
||||
fn a_failing_preview_service_is_named_and_previews_are_offered() {
|
||||
let service = Arc::new(FakeService::default());
|
||||
service.failing.store(true, Ordering::SeqCst);
|
||||
let mut rig = service_rig("previews-failing", &service, latin_index());
|
||||
rig.set_previews(true);
|
||||
rig.load();
|
||||
assert!(!service.urls().is_empty());
|
||||
assert!(rig.present("Font previews are unavailable"));
|
||||
assert!(rig.fx.texts().iter().any(|painted| painted.text.contains(SERVICE)), "the notice names the server");
|
||||
assert!(rig.present("Preview"), "the card offers the whole-family preview");
|
||||
rig.open("Family 01");
|
||||
// The sheet's is a button, a card's a link.
|
||||
rig.named(Role::BUTTON, "Preview");
|
||||
}
|
||||
|
||||
/// One family: a variable upright file with three named instances, whose sha256 is `ab…`, and a static italic, `cd…`.
|
||||
fn variable_index() -> Index {
|
||||
let file = |path: &str, sha: &str, style: &str, more: &str| {
|
||||
format!(r#"{{"path":"ofl/varia/{path}","size":1000,"sha256":"{}","style":"{style}","weight":400,"postscript":[],{more}}}"#, sha.repeat(32))
|
||||
};
|
||||
let instance = |name: &str, weight: u32| format!(r#"{{"name":"{name}","coordinates":{{"wght":{weight}}}}}"#);
|
||||
let instances = [instance("Thin", 100), instance("Regular", 400), instance("Bold", 700)].join(",");
|
||||
let axes = format!(r#""axes":[{{"tag":"wght","min":100,"max":900}}],"instances":[{instances}],"list_instance":1"#);
|
||||
let files = [file("Varia[wght].ttf", "ab", "normal", &axes), file("Varia-Italic.ttf", "cd", "italic", r#""axes":[]"#)].join(",");
|
||||
service_index(&format!(
|
||||
r#"{{"family":"Varia","categories":["SANS_SERIF"],"languages":[0],"scripts":["Latn"],"license":"OFL","sample_script":"Latn","files":[{files}]}}"#
|
||||
))
|
||||
}
|
||||
|
||||
/// Every style of a variable file draws from one subset, whatever its axis sliders say.
|
||||
#[trial]
|
||||
fn a_variable_family_draws_one_subset_at_every_axis_value() {
|
||||
let service = Arc::new(FakeService::default());
|
||||
let mut rig = service_rig("previews-variable", &service, variable_index());
|
||||
rig.set_previews(true);
|
||||
rig.load();
|
||||
service.urls();
|
||||
rig.open("Varia");
|
||||
rig.load();
|
||||
let urls = service.urls();
|
||||
let var: Vec<&String> = urls.iter().filter(|url| url.contains("/var/")).collect();
|
||||
assert!(var.len() == 1 && var[0].contains(&"ab".repeat(32)) && var[0].contains("/var/sample-"), "one subset for the variable file: {urls:?}");
|
||||
assert!(urls.iter().any(|url| url.contains(&"cd".repeat(32)) && url.contains("/list/sample-")), "the static italic's own: {urls:?}");
|
||||
for style in ["Thin", "Regular", "Bold", "Italic"] {
|
||||
assert!(rig.present(style), "no {style} row");
|
||||
}
|
||||
|
||||
rig.fx.type_text("9");
|
||||
assert!(rig.present("400"), "no field of the sheet has the keyboard when it opens");
|
||||
let weight = rig.named(Role::SLIDER, "Weight");
|
||||
assert!(rig.present("400") && !rig.present("401"));
|
||||
rig.fx.access(AccessActionKind::Increment, &weight);
|
||||
rig.load();
|
||||
assert!(rig.present("401"), "the slider moved");
|
||||
assert!(service.urls().is_empty(), "the slider asked for another subset");
|
||||
}
|
||||
|
||||
/// The rows the crate exports read without a problem, and a Host with them shows the panel in its language.
|
||||
#[trial]
|
||||
fn the_exported_rows_show_the_panel_in_japanese() {
|
||||
let (i18n, problems) = I18n::new(CATALOGS, &["ja", "ar"]);
|
||||
assert!(problems.is_empty() && i18n.check_all().is_empty(), "{problems:?} {:?}", i18n.check_all());
|
||||
let lang = i18n.from_code("ja").unwrap();
|
||||
let root = root("japanese");
|
||||
let store = Arc::new(FakeStore::new(root.join("store"), HashMap::new()));
|
||||
let panel = FontsPanel::new(Options::new(catalog(&root), store.clone(), Ok(index())));
|
||||
let rig = show(panel, store, Arc::new(Host::builder(APP).i18n(Arc::new(i18n)).lang(lang).jobs(Arc::new(InlineJobs)).build()));
|
||||
assert!(rig.present("すべてのカテゴリ") && !rig.present("All categories"));
|
||||
}
|
||||
|
||||
/// With downloads off, a family's NOTICE is offered in its sheet and not read until the user asks.
|
||||
#[trial]
|
||||
fn a_notice_is_read_only_when_asked_while_downloads_are_off() {
|
||||
let file = format!(
|
||||
r#"{{"path":"apache/a/A-Regular.ttf","size":1000,"sha256":"{}","style":"normal","weight":400,"axes":[],"postscript":[]}}"#,
|
||||
"aa".repeat(32)
|
||||
);
|
||||
let notice = format!(r#"{{"path":"apache/a/NOTICE","size":10,"sha256":"{}"}}"#, "bb".repeat(32));
|
||||
let family = format!(
|
||||
r#"{{"family":"Noticed","categories":["SANS_SERIF"],"languages":[0],"scripts":["Latn"],"license":"APACHE2","notice_file":{notice},"files":[{file}]}}"#
|
||||
);
|
||||
let root = root("notice");
|
||||
let files = HashMap::from([("apache/a/NOTICE".to_owned(), b"Copyright Noticed".to_vec())]);
|
||||
let store = Arc::new(FakeStore::new(root.join("store"), files));
|
||||
let panel = FontsPanel::new(Options::new(catalog(&root), store.clone(), Ok(service_index(&family))));
|
||||
let mut rig = show(panel, store, host_with(Arc::new(MemorySections::default()), Arc::new(InlineJobs)));
|
||||
rig.open("Noticed");
|
||||
assert!(!rig.panel.borrow().downloads_allowed());
|
||||
rig.named(Role::BUTTON, "Show notice");
|
||||
assert!(!rig.present("Copyright Noticed"), "the text is not read");
|
||||
assert!(!rig.present("Retry"), "nor was a read refused");
|
||||
|
||||
rig.allow();
|
||||
assert!(rig.fx.texts().iter().any(|painted| painted.text.contains("Copyright Noticed")), "read once downloads are allowed");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn default_filters_are_sans_serif_and_the_system_language() {
|
||||
let mut rig = setup("default-filters");
|
||||
rig.panel.borrow_mut().use_default_filters("ja-JP");
|
||||
rig.fx.settle();
|
||||
assert_eq!(rig.panel.borrow().results(), ["Noto Sans JP"]);
|
||||
rig.panel.borrow_mut().use_default_filters("fr");
|
||||
rig.fx.settle();
|
||||
assert_eq!(rig.panel.borrow().results(), ["Noto Sans JP", "Ubuntu"], "no French in the index: English");
|
||||
}
|
||||
@@ -7,6 +7,9 @@ repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Runtime, style, fonts, primitives, the component contract, layout and the test kit of the craft UI library, on egui"
|
||||
|
||||
[package.metadata.craft]
|
||||
reads = ["crates/font-subset/tests/data/orbitron/Orbitron[wght].ttf"]
|
||||
|
||||
[lib]
|
||||
# Every test lives in the `it` integration binary.
|
||||
test = false
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::runtime::egui::text_layout;
|
||||
use crate::runtime::env::Env;
|
||||
use crate::style::{DataColor, Ink, StyleCx, UiTokens, ink_color};
|
||||
use craft_i18n::{Direction, Format, WordSet};
|
||||
use egui::epaint::text::{FontId, TextDirection};
|
||||
use egui::epaint::text::{FontId, TextDirection, VariationCoords};
|
||||
use egui::text::{LayoutJob, TextFormat};
|
||||
use egui::{Color32, Context, FontFamily, Painter, Stroke};
|
||||
use std::borrow::Cow;
|
||||
@@ -188,6 +188,7 @@ impl<'a> DocText<'a> {
|
||||
italics: run.italic,
|
||||
underline: line(run.underline),
|
||||
strikethrough: line(run.strikethrough),
|
||||
coords: VariationCoords::new(run.coords.iter().copied()),
|
||||
..TextFormat::default()
|
||||
},
|
||||
);
|
||||
@@ -222,6 +223,10 @@ pub struct DocRun<'a> {
|
||||
/// Space in points before the run. On the first run of a paragraph it is the first-line indent: a wrapped row
|
||||
/// starts at the edge.
|
||||
pub indent: f32,
|
||||
/// The variation coordinates the run is drawn at (axis tag, value), over those of its face
|
||||
/// ([`FaceBytes::coords`](crate::fonts::FaceBytes::coords)): one variable face registered once draws every style a
|
||||
/// document or an axis slider asks for. Empty draws the face as it is registered.
|
||||
pub coords: Cow<'a, [([u8; 4], f32)]>,
|
||||
}
|
||||
|
||||
/// A run of text in one face of a document's fonts, which [`Draw::face_run`](super::Draw::face_run) draws on a
|
||||
@@ -272,7 +277,18 @@ impl<'a> FaceRun<'a> {
|
||||
impl<'a> DocRun<'a> {
|
||||
/// A regular-weight upright run without lines or indent.
|
||||
pub fn new(text: impl Into<Cow<'a, str>>, font: FontRef, size: f32, color: DataColor) -> Self {
|
||||
DocRun { text: text.into(), font, size, weight: REGULAR, italic: false, color, underline: false, strikethrough: false, indent: 0.0 }
|
||||
DocRun {
|
||||
text: text.into(),
|
||||
font,
|
||||
size,
|
||||
weight: REGULAR,
|
||||
italic: false,
|
||||
color,
|
||||
underline: false,
|
||||
strikethrough: false,
|
||||
indent: 0.0,
|
||||
coords: Cow::Borrowed(&[]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Italic.
|
||||
@@ -310,7 +326,14 @@ impl<'a> DocRun<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The run owning its text.
|
||||
/// The run drawn at the variation coordinates `coords` (axis tag, value) of its face.
|
||||
#[must_use]
|
||||
pub fn coords(mut self, coords: impl Into<Cow<'a, [([u8; 4], f32)]>>) -> Self {
|
||||
self.coords = coords.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// The run owning its text and coordinates.
|
||||
pub fn into_owned(self) -> DocRun<'static> {
|
||||
DocRun {
|
||||
text: Cow::Owned(self.text.into_owned()),
|
||||
@@ -322,6 +345,7 @@ impl<'a> DocRun<'a> {
|
||||
underline: self.underline,
|
||||
strikethrough: self.strikethrough,
|
||||
indent: self.indent,
|
||||
coords: Cow::Owned(self.coords.into_owned()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -209,11 +209,15 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>)
|
||||
// A laid-out galley sits at the rect's corner, as a painted run does.
|
||||
.align(match (centred, rtl) {
|
||||
_ if galley.is_some() => egui::Align2::LEFT_TOP,
|
||||
(true, _) => egui::Align2::CENTER_CENTER,
|
||||
(false, rtl) => match (end_aligned, rtl) {
|
||||
(true, false) | (false, true) => egui::Align2::RIGHT_CENTER,
|
||||
(true, true) | (false, false) => egui::Align2::LEFT_CENTER,
|
||||
},
|
||||
(centred, rtl) => {
|
||||
let across = match (centred, end_aligned == rtl) {
|
||||
(true, _) => egui::Align::Center,
|
||||
(false, true) => egui::Align::Min,
|
||||
(false, false) => egui::Align::Max,
|
||||
};
|
||||
// A multi-line text starts at the part's top, however many of its lines the text fills.
|
||||
egui::Align2([across, if multiline { egui::Align::Min } else { egui::Align::Center }])
|
||||
}
|
||||
});
|
||||
if let Some(hint) = hint_text.clone() {
|
||||
edit = edit.hint_text(hint);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Document faces read from a catalog: loaded off the pass, ready from the pass after, kept across a definitions
|
||||
//! replacement and while drawn lately (a settled view's replay counts), served to egui without making its fonts again,
|
||||
//! and held within one budget; and a face's chain of sibling subsets.
|
||||
//! and held within one budget; a face's chain of sibling subsets; and a run at variation coordinates of its face.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
@@ -17,6 +17,8 @@ use craft_ui::testing::{Frames, MemoRun, document_face_budget, last_frame_memo_r
|
||||
use egui::{Color32, FontId, Response, Vec2};
|
||||
|
||||
const FONT: &[u8] = include_bytes!("../../fonts/NotoSans-test.ttf");
|
||||
/// A variable font (`wght`, 400 to 900).
|
||||
const VARIABLE: &[u8] = include_bytes!("../../../../font-subset/tests/data/orbitron/Orbitron[wght].ttf");
|
||||
const ARABIC: &[u8] = include_bytes!("../../fonts/NotoSansArabic-test.ttf");
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
|
||||
@@ -32,6 +34,8 @@ struct Tally {
|
||||
loads: Arc<AtomicUsize>,
|
||||
threads: Arc<Mutex<Vec<ThreadId>>>,
|
||||
states: Arc<Mutex<HashMap<String, FaceState>>>,
|
||||
/// The widths of the same run in the face "variable" at its default, at `wght` 400 and at 900.
|
||||
widths: Arc<Mutex<Vec<f32>>>,
|
||||
}
|
||||
|
||||
impl Tally {
|
||||
@@ -48,12 +52,13 @@ impl Tally {
|
||||
}
|
||||
}
|
||||
|
||||
/// The face `key` loads: "split" is a Latin subset chained to the Arabic subset "arabic"; every other key loads the
|
||||
/// Latin subset alone.
|
||||
/// The face `key` loads: "split" is a Latin subset chained to the Arabic subset "arabic", "variable" a variable
|
||||
/// font; every other key loads the Latin subset alone.
|
||||
fn face_of(key: &str) -> FaceBytes {
|
||||
match key {
|
||||
"split" => FaceBytes::new(Arc::from(FONT), 0).chain(["arabic"]),
|
||||
"arabic" => FaceBytes::new(Arc::from(ARABIC), 0),
|
||||
"variable" => FaceBytes::new(Arc::from(VARIABLE), 0),
|
||||
_ => FaceBytes::new(Arc::from(FONT), 0),
|
||||
}
|
||||
}
|
||||
@@ -101,6 +106,14 @@ impl Component for Owner {
|
||||
if let FaceState::Ready(font) = &state {
|
||||
let runs = [DocRun::new("Ag", font.clone(), 14.0, DataColor::new(Color32::BLACK))];
|
||||
let _ = cx.layout_doc(&DocText::new(&runs));
|
||||
if key == "variable" {
|
||||
let at = [vec![], vec![(*b"wght", 400.0)], vec![(*b"wght", 900.0)]];
|
||||
let width = |coords: &Vec<([u8; 4], f32)>| {
|
||||
let runs = [DocRun::new("Hamburg", font.clone(), 100.0, DataColor::new(Color32::BLACK)).coords(coords)];
|
||||
cx.layout_doc(&DocText::new(&runs)).size().x
|
||||
};
|
||||
*self.tally.widths.lock().expect("the widths") = at.iter().map(width).collect();
|
||||
}
|
||||
}
|
||||
self.tally.states.lock().expect("the states").insert(key.clone(), state);
|
||||
}
|
||||
@@ -152,6 +165,16 @@ fn generation(frames: &Frames) -> u64 {
|
||||
frames.ctx.fonts(|fonts| fonts.atlas_generation())
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_run_is_laid_out_at_its_variation_coordinates() {
|
||||
let (mut frames, jobs, tally) = rig();
|
||||
shown(&mut frames, &jobs, &tally, &["variable".to_owned()]);
|
||||
let widths = tally.widths.lock().expect("the widths").clone();
|
||||
let [plain, regular, black] = widths[..] else { panic!("{widths:?}") };
|
||||
assert_ne!(black, regular, "the run is laid out at its coordinates");
|
||||
assert_eq!(plain, regular, "the face's default weight");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_catalog_face_loads_off_the_pass_and_is_ready_in_the_pass_after_its_load() {
|
||||
let (mut frames, jobs, tally) = rig();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
use super::{FieldStyle, text_part};
|
||||
use super::{FieldStyle, lines_inset, text_part};
|
||||
use crate::choice::Checkbox;
|
||||
use crate::contract::{
|
||||
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, OverlayUi, PaintUi, PartsCx, Props as _, Role, WordSetCx as _,
|
||||
@@ -133,11 +133,12 @@ fn shown_of(shown: Option<&AltText>) -> AltText {
|
||||
shown.cloned().unwrap_or_else(|| AltText::parts(Mixed::Mixed, Mixed::Mixed))
|
||||
}
|
||||
|
||||
/// The height of the description box and the size of the check.
|
||||
fn sizes(cx: &MeasureCx<'_, AltTextField<'_>>) -> (f32, Vec2) {
|
||||
/// The height of the description's lines, the space above and below them, and the size of the check.
|
||||
fn sizes(cx: &MeasureCx<'_, AltTextField<'_>>) -> (f32, f32, Vec2) {
|
||||
let words = cx.words::<AltTextWords>();
|
||||
let line = cx.layout(&TextRun::new("M")).size().y;
|
||||
(line * LINES as f32, cx.child("decorative", &mut check_face(Mixed::Same(false), &words), Proposal::Ideal))
|
||||
let check = cx.child("decorative", &mut check_face(Mixed::Same(false), &words), Proposal::Ideal);
|
||||
(line * LINES as f32, lines_inset(&cx.style.metrics, line), check)
|
||||
}
|
||||
|
||||
impl Component for AltTextField<'_> {
|
||||
@@ -156,9 +157,9 @@ impl Component for AltTextField<'_> {
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let (text, check) = sizes(cx);
|
||||
let (text, inset, check) = sizes(cx);
|
||||
let width = cx.room.unwrap_or(check.x);
|
||||
Vec2::new(width, text + cx.gap() + check.y)
|
||||
Vec2::new(width, 2.0 * inset + text + cx.gap() + check.y)
|
||||
}
|
||||
|
||||
/// The description box (a text part, disabled while every object is decorative, showing the mixed word as its
|
||||
@@ -166,10 +167,10 @@ impl Component for AltTextField<'_> {
|
||||
/// its own value.
|
||||
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let content = cx.content_rect;
|
||||
let (text, check) = sizes(cx);
|
||||
let (text, inset, check) = sizes(cx);
|
||||
let words = cx.words::<AltTextWords>();
|
||||
let area = Rect::from_min_size(content.min, vec2(content.width(), text));
|
||||
let check_at = Rect::from_min_size(pos2(content.min.x, area.max.y + cx.gap()), vec2(content.width(), check.y));
|
||||
let area = Rect::from_min_size(content.min + vec2(0.0, inset), vec2(content.width(), text));
|
||||
let check_at = Rect::from_min_size(pos2(content.min.x, area.max.y + inset + cx.gap()), vec2(content.width(), check.y));
|
||||
let value = shown_of(cx.value());
|
||||
let placeholder = if value.text.same().is_some() { words.alt_text.clone() } else { words.mixed.clone() };
|
||||
let options = TextOptions { lines: Some(LINES), placeholder: Some(placeholder), enabled: !value.all_decorative(), ..TextOptions::default() };
|
||||
|
||||
@@ -53,6 +53,12 @@ pub struct FieldStyle {
|
||||
button: f32,
|
||||
}
|
||||
|
||||
/// The space above the first and below the last of the lines of a multi-line text in a field of `metrics`, its lines
|
||||
/// `line` high: that of a single line in its control, so a box of `n` lines shows them whole.
|
||||
pub(crate) fn lines_inset(metrics: &Metrics, line: f32) -> f32 {
|
||||
((metrics.min_size.y - line) / 2.0).max(0.0)
|
||||
}
|
||||
|
||||
impl FieldStyle {
|
||||
/// The style a text-like field reads from the theme.
|
||||
pub fn at(cx: &StyleCx<'_>) -> FieldStyle {
|
||||
|
||||
@@ -4,13 +4,14 @@
|
||||
pub(crate) mod stories;
|
||||
|
||||
use super::adorn::{self, Adornment};
|
||||
use super::{FieldStyle, completions, text_part, words};
|
||||
use super::{FieldStyle, completions, lines_inset, text_part, words};
|
||||
use crate::contract::{
|
||||
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, OverlayUi, PaintUi, PartsCx, Pointer as _, Props as _, Role, Sizing,
|
||||
Styled as _, WordSetCx as _,
|
||||
};
|
||||
use crate::primitives::{Completer, IconSpec, SubmitKey, TabKey, TextOptions, TextRun, Wrap};
|
||||
use crate::runtime::env::{Label, Message};
|
||||
use crate::style::Span;
|
||||
use craft_behavior::{Codec, EditEvent, IconId, Mixed, PartKey, PlainText, Proposal, Sense};
|
||||
use egui::{Id, Rect, Vec2};
|
||||
use smallvec::SmallVec;
|
||||
@@ -339,6 +340,18 @@ impl<C: Codec + Clone + 'static> TextField<'_, C> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Codec + Clone + 'static> TextField<'_, C> {
|
||||
/// `text` as the editor sets it.
|
||||
fn run<'t>(&self, text: impl Into<Cow<'t, str>>) -> TextRun<'t> {
|
||||
if self.options.mono { TextRun::spans(vec![Span::new(text).mono()]) } else { TextRun::new(text).role(self.options.role) }
|
||||
}
|
||||
|
||||
/// The height of one line of the editor's text.
|
||||
fn line(&self, cx: &MeasureCx<'_, Self>) -> f32 {
|
||||
cx.layout(&self.run("M")).size().y
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Codec + Clone + 'static> Component for TextField<'_, C> {
|
||||
const ROLE: Role = Role::TEXT_INPUT;
|
||||
const INPUT: crate::contract::Input = crate::contract::Input::Text;
|
||||
@@ -373,10 +386,10 @@ impl<C: Codec + Clone + 'static> Component for TextField<'_, C> {
|
||||
// field's own text wrapped as the editor wraps it, not the codec's width sample, which a plain field leaves
|
||||
// empty.
|
||||
if let Some(lines) = self.options.lines.filter(|_| self.options.multiline()) {
|
||||
let line = cx.layout(&TextRun::new("M").role(self.options.role)).size().y;
|
||||
let height = |lines: usize| cx.style.metrics().min_size.y + line * lines.saturating_sub(1) as f32;
|
||||
let line = self.line(cx);
|
||||
let height = |lines: usize| 2.0 * lines_inset(&cx.style.metrics, line) + line * lines as f32;
|
||||
let shown = cx.value().map(|value| self.codec.format(value)).unwrap_or_default();
|
||||
let tall = cx.layout(&TextRun::new(shown).role(self.options.role).wrap(Wrap::Wrap)).size().y;
|
||||
let tall = cx.layout(&self.run(shown).wrap(Wrap::Wrap)).size().y;
|
||||
let rows = if line > 0.0 { (tall / line).round() as usize } else { 1 };
|
||||
size.y = size.y.max(height(lines.max(rows)));
|
||||
if let Some(most) = self.max_lines {
|
||||
@@ -416,12 +429,16 @@ impl<C: Codec + Clone + 'static> Component for TextField<'_, C> {
|
||||
let clear = self.clear_shown(value).then(|| Self::clear_name(&cx.words::<words::TextWords>()));
|
||||
let trailing = self.trailing(clear, cx.env.get());
|
||||
self.leading = std::mem::take(&mut self.leading).into_iter().map(|adornment| adornment.measured(cx)).collect();
|
||||
let placed = adorn::place(cx.content_rect, cx.style, &self.leading, &trailing, cx.flow.is_rtl());
|
||||
let mut placed = adorn::place(cx.content_rect, cx.style, &self.leading, &trailing, cx.flow.is_rtl());
|
||||
for (adornment, rect) in trailing.iter().zip(&placed.trailing) {
|
||||
if adornment.part() == Some(CLEAR) {
|
||||
cx.part(CLEAR, *rect).sense(Sense::CLICK | Sense::KEEP_FOCUS).pointer_only("Escape clears the text");
|
||||
}
|
||||
}
|
||||
if self.options.multiline() {
|
||||
let inset = lines_inset(&cx.style.metrics, self.line(cx));
|
||||
placed.text = placed.text.shrink2(Vec2::new(0.0, inset.min(placed.text.height() / 2.0)));
|
||||
}
|
||||
if let Some(start) = value.or(self.empty.as_ref()) {
|
||||
let limit = self.limit.effective(self.options.multiline());
|
||||
// The bound caret goes to the text part every pass; the part places it only when it differs from the caret
|
||||
|
||||
@@ -3055,14 +3055,15 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`.
|
||||
- `pub fn scaled(self, scale: f32) -> Self`. The width with a document width multiplied by `scale` (a view's zoom); a theme width stays as the theme names
|
||||
- `craft_ui::primitives::DataWidth`: `pub struct DataWidth`. A line width the data gives (a path's thickness, a pen size), in screen points: the caller maps a document width
|
||||
- `pub const fn points(points: f32) -> Self`. A width of `points`.
|
||||
- `craft_ui::primitives::DocRun`: `pub struct DocRun<'a> { pub text: Cow<'a, str>, pub font: FontRef, pub size: f32, pub weight: u16, pub italic: bool, pub color: DataColor, pub underline: bool, pub strikethrough: bool, pub indent: f32 }`. One run of document text.
|
||||
- `craft_ui::primitives::DocRun`: `pub struct DocRun<'a> { pub text: Cow<'a, str>, pub font: FontRef, pub size: f32, pub weight: u16, pub italic: bool, pub color: DataColor, pub underline: bool, pub strikethrough: bool, pub indent: f32, pub coords: Cow<'a, [([u8; 4], f32)]> }`. One run of document text.
|
||||
- `pub fn new(text: impl Into<Cow<'a, str>>, font: FontRef, size: f32, color: DataColor) -> Self`. A regular-weight upright run without lines or indent.
|
||||
- `pub fn italic(mut self) -> Self`. Italic.
|
||||
- `pub fn bold(mut self) -> Self`. Bold weight.
|
||||
- `pub fn underline(mut self) -> Self`. Underlined.
|
||||
- `pub fn strikethrough(mut self) -> Self`. Struck through.
|
||||
- `pub fn indent(mut self, points: f32) -> Self`. `points` of space before the run.
|
||||
- `pub fn into_owned(self) -> DocRun<'static>`. The run owning its text.
|
||||
- `pub fn coords(mut self, coords: impl Into<Cow<'a, [([u8; 4], f32)]>>) -> Self`. The run drawn at the variation coordinates `coords` (axis tag, value) of its face.
|
||||
- `pub fn into_owned(self) -> DocRun<'static>`. The run owning its text and coordinates.
|
||||
- `craft_ui::primitives::DocText`: `pub struct DocText<'a> { pub runs: &'a [DocRun<'a>], pub wrap: Option<f32>, pub align: HAlign, pub elide: bool }`. Document text: runs with their own font, size and colour. On `TextRun` these fields would let any component
|
||||
- `pub const fn new(runs: &'a [DocRun<'a>]) -> Self`. Unwrapped document text of `runs`.
|
||||
- `pub const fn elide(mut self) -> Self`. Cuts the text to one row with an ellipsis at the end.
|
||||
|
||||
Reference in new issue
Block a user