Expand description
Fonts service and text shaping.
The most common types in this module are used through the Text! widget properties related to font configuration.
use zng::{font::FontName, prelude::*};
Text! {
txt = "hello";
font_family = FontName::monospace();
}Internally the Text! widget implements text segmenting and shaping using the types provided by this module,
but you only need to interact with these types directly if you are authoring new text properties or a new custom
text rendering widget.
The second most common type used is the FONTS service. The service can be used to register custom fonts, query system fonts and
manage the font cache.
§Fonts Service
The example below demonstrates a font query and custom embedded font installation.
/// set custom fallback font for the ⌫ symbol.
async fn set_fallback_font() {
use zng::font::*;
let und = lang!(und);
let shaped_icon = FONTS
.list(
&FontNames::system_ui(&und),
FontStyle::Normal,
FontWeight::NORMAL,
FontStretch::NORMAL,
&und,
)
.wait_rsp()
.await
.sized(layout::Px(11), vec![])
.shape_text(&SegmentedText::new("⌫", layout::LayoutDirection::LTR), &TextShapingArgs::default());
if shaped_icon.is_empty() || shaped_icon.glyphs().flat_map(|g| g.1).any(|g| g.index == 0) {
// OS UI and fallback fonts do not support `⌫`, load custom font that does.
static FALLBACK: &[u8] = include_bytes!("res/calculator/notosanssymbols2-regular-subset.ttf");
let fallback = CustomFont::from_bytes("fallback", FontBytes::from_static(FALLBACK), 0);
FONTS.register(fallback).wait_rsp().await.unwrap();
FONTS.generics().set_fallback(und, "fallback");
}
}This code is taken from the examples/calculator.rs example,
it uses FONTS.list to get the font system_ui fonts that are used by default. The code
then checks if any of system fonts has a glyph for the ⌫ character, if none of the fonts support it a CustomFont is
loaded from an embedded font and installed using FONTS.register. Finally the FONTS.generics
is used to override the fallback font.
The FONTS.generics can also be used to change what font is used for the specially named fonts like FontName::sans_serif.
§Text Segmenting and Shaping
The most advance feature provided by this module is text segmenting and shaping. Text segmenting is the process of analyzing
raw text and splitting it into distinct segments that define things like the layout direction of text runs, words and spaces,
points where text can be inserted and where wrap line-breaks can happen, this is defined the type SegmentedText.
A segmented text can then be shaped, that is actual glyphs resolved for each segment and positioned according to available space,
this is defined by the ShapedText type.
The example below segments and shapes a text, generating a markdown report from some of the data computed.
use std::fmt::Write as _;
use zng::{font::*, l10n::Lang, prelude_wgt::Px, text::*, var::Var};
async fn report_segment_and_glyphs(txt: &str, lang: &Lang) -> Txt {
let mut report = formatx!("# Shape & Segment\n\n{txt}\n\n");
// start font query in parallel
let font_face = FONTS.list(
&FontNames::system_ui(lang),
FontStyle::Normal,
FontWeight::NORMAL,
FontStretch::NORMAL,
lang,
);
// segment text
let segmented_txt = SegmentedText::new(Txt::from_str(txt), lang.direction());
write!(&mut report, "### Segments\n\n|text|kind|\n|--|--|\n").unwrap();
for (txt, seg) in segmented_txt.iter() {
writeln!(&mut report, "|{txt:?}|{:?}|", seg.kind).unwrap();
}
// wait font query
let font = font_face.wait_rsp().await;
// gets the best font for the size
let font = font.sized(Px(20), vec![]);
write!(&mut report, "### Fonts\n\n").unwrap();
let mut sep = "";
for f in font.iter() {
write!(&mut report, "{sep}{}", f.face().family_name()).unwrap();
sep = ", ";
}
writeln!(&mut report, "\n").unwrap();
// shape text
let mut args = TextShapingArgs::default();
args.lang = lang.clone();
args.direction = segmented_txt.base_direction();
args.line_height = font.best().metrics().line_height();
let shaped_txt = font.shape_text(&segmented_txt, &args);
write!(&mut report, "### Glyphs\n\n|text|glyphs|\n|--|--|\n").unwrap();
for line in shaped_txt.lines() {
for seg in line.segs() {
let txt = seg.text(txt);
write!(&mut report, "|{txt:?}|").unwrap();
let mut sep = "";
for (font, glyphs) in seg.glyphs() {
write!(&mut report, "{sep}**{}** ", font.face().family_name(),).unwrap();
sep = " | ";
let mut sep = "";
for g in glyphs {
write!(&mut report, "{sep}{}", g.index).unwrap();
sep = ", ";
}
}
writeln!(&mut report).unwrap();
}
}
report
}Note that you can access the segmented and shaped text of a Text! widget using the TEXT service.
§Full API
See zng_ext_font for the full font and shaping API.
Modules§
- font_
features - Font features and variation types.
Structs§
- Bidi
Level - Embedding Level
- Caret
Index - Defines an insert offset in a shaped text.
- Color
Glyph - Color glyph layers.
- Color
Glyphs - COLR table.
- Color
Palette - Represents a color palette entry.
- Color
Palette Type - Represents a color palette v1 flag.
- Color
Palettes - CPAL table.
- Custom
Font - Custom font builder.
- FONTS
- Font loading, custom fonts and app font configuration.
- Font
- A sized font face.
- Font
Bytes - Reference to in memory font data.
- Font
Changed Args FONT_CHANGED_EVENTarguments.- Font
Face - A font face selected from a font family.
- Font
Face List - A list of
FontFaceresolved from aFontNamelist, plus the fallback font. - Font
Face Metrics - Various metrics that apply to the entire
FontFace. - Font
List - A list of
Fontcreated from aFontFaceList. - Font
Metrics - Various metrics about a
Font. - Font
Name - Font family name.
- Font
Names - A list of font names in priority order.
- Font
Stretch - The width of a font as an approximate fraction of the normal width.
- Font
Weight - The degree of stroke thickness of a font. This value ranges from 100.0 to 900.0, with 400.0 as normal.
- HYPHENATION
- Hyphenation service.
- Hyphenation
Data Dir - Represents a hyphenation data source that searches a directory.
- Layout
Directions - Identifies what direction segments a
ShapedLinehas. - Segmented
Text - A string segmented in sequences of words, spaces, tabs and separated line breaks.
- Segmented
Text Iter - Segmented text iterator.
- Shaped
Line - Represents a line selection of a
ShapedText. - Shaped
Segment - Represents a word or space selection of a
ShapedText. - Shaped
Text - Output of text layout.
- Text
Overflow Info - Info about a shaped text overflow in constraint.
- Text
Segment - Represents a single text segment in a
SegmentedText. - Text
Shaping Args - Extra configuration for
shape_text.
Enums§
- Font
Change - Possible changes in a
FontChangedArgs. - Font
Color Palette - Color palette selector for colored fonts.
- Font
Style - The italic or oblique form of a font.
- Hyphens
- Hyphenation mode.
- Justify
- Text alignment justification mode.
- Line
Break - Configuration of text wrapping for Chinese, Japanese, or Korean text.
- Shaped
Colored Glyphs - Represents normal and colored glyphs in
ShapedText::colored_glyphs. - Text
Segment Kind - The type of an inline/text segment.
- Text
Transform Fn - Text transform function.
- White
Space - Text white space transform.
- Word
Break - Configure line breaks inside words during text wrap.
Statics§
- FONT_
CHANGED_ EVENT - Change in
FONTSthat may cause a font query to now give a different result.
Traits§
- Hyphenation
Data Source - Represents a hyphenation dictionary source.
- Outline
Sink - Receives Bézier path rendering commands from
Font::outline.
Functions§
- unicode_
bidi_ levels - Compute initial bidirectional levels of each segment of a
line. - unicode_
bidi_ sort - Compute a map of segments in
lineto their final LTR display order.
Type Aliases§
- Font
Size - Text font size.
- Letter
Spacing - Extra spacing added in between text letters.
- Line
Height - Text line height.
- Line
Spacing - Extra spacing in-between text lines.
- Paragraph
Spacing - Extra spacing in-between paragraphs.
- TabLength
- Length of a
TABspace. - Text
Line Thickness - Height of the text overline or strikethrough decoration.
- Underline
Thickness - Height of the text underline decoration.
- Word
Spacing - Extra spacing added to the Unicode
U+0020 SPACEcharacter.