Skip to content
This repository was archived by the owner on Nov 12, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/leaf-dioxus-tui/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ fn App() -> Element {
size: SIZE,
leading: LEADING,
grid: Some(grid()),
faces: Default::default(),
},
measure: OPTIONS.get().measure,
appearance: if dark {
Expand Down
1 change: 1 addition & 0 deletions apps/leaf-dioxus/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ impl Settings {
size: self.size.px() * zoom,
leading: self.spacing.ratio(),
grid: None,
faces: Default::default(),
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/leaf-dioxus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,6 @@ pub use input::{TableCommand, ZoomCommand};
pub use keys::pressed;
pub use link::{Context, Footnote};
pub use row::{PAD, Pointer, PressMode, Target};
pub use text::{Grid, Type};
pub use text::{Blob, Faces, Grid, Type};
pub use trace::trace;
pub use view::{Appearance, Palette, stylesheet, themed};
117 changes: 112 additions & 5 deletions crates/leaf-dioxus/src/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,14 @@
//! repeats on every line — the shape Swift's `BlockChrome` draws.

use std::borrow::Cow;
use std::collections::HashSet;
use std::fmt;
use std::ops::Range;
use std::sync::Arc;

use crate::bridge::rows::{RowView, Run};
pub use parley::Alignment;
pub use parley::fontique::Blob;
use parley::{
Affinity, AlignmentOptions, Cursor, FontContext, FontFamily, FontStyle, FontWeight, InlineBox,
InlineBoxKind, Layout, LayoutContext, LineHeight, StyleProperty, VerticalAlign,
Expand Down Expand Up @@ -54,6 +58,49 @@ pub struct Type {
/// find bar, the status line and a table's padding and rules, is sized
/// in whole cells.
pub grid: Option<Grid>,
/// Font files the host brings, measured beside the system's: what lets
/// `body` and `mono` name a face the system does not have. The host
/// gives the renderer the same files, or Blitz draws a fallback where
/// parley measured the face.
pub faces: Faces,
}

/// Font files a host brings with it, as TrueType or OpenType bytes (a
/// collection is one file of several faces). Which faces they are is the
/// host's choice; the editor only measures with them. Cheap to clone, and
/// two are equal when they hold the same files.
#[derive(Clone, Default)]
pub struct Faces(Arc<[Blob<u8>]>);

impl Faces {
/// The files, as parley holds them: what a host hands its renderer's
/// font collection too, so both read one copy.
pub fn blobs(&self) -> &[Blob<u8>] {
&self.0
}
}

impl<T: AsRef<[u8]> + Send + Sync + 'static> FromIterator<T> for Faces {
fn from_iter<I: IntoIterator<Item = T>>(files: I) -> Self {
Self(files.into_iter().map(|f| Blob::new(Arc::new(f))).collect())
}
}

impl PartialEq for Faces {
fn eq(&self, other: &Self) -> bool {
self.0.len() == other.0.len()
&& self
.0
.iter()
.zip(other.0.iter())
.all(|(a, b)| a.id() == b.id())
}
}

impl fmt::Debug for Faces {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Faces({} files)", self.0.len())
}
}

/// One character cell of a grid surface, in CSS pixels: the monospace
Expand All @@ -73,6 +120,7 @@ impl Default for Type {
size: 16.0,
leading: 1.5,
grid: None,
faces: Faces::default(),
}
}
}
Expand Down Expand Up @@ -115,15 +163,22 @@ pub struct Fonts {
fcx: FontContext,
lcx: LayoutContext<()>,
ty: Type,
/// The [`Faces`] files already in `fcx`, by blob id: a collection
/// cannot forget a font, so a file is registered once however often the
/// type changes.
registered: HashSet<u64>,
}

impl Fonts {
pub fn new(ty: Type) -> Self {
Self {
let mut fonts = Self {
fcx: FontContext::new(),
lcx: LayoutContext::new(),
ty,
}
ty: Type::default(),
registered: HashSet::new(),
};
fonts.set_ty(ty);
fonts
}

pub fn ty(&self) -> &Type {
Expand All @@ -132,11 +187,17 @@ impl Fonts {

/// Set the text in another type. Every layout made before is stale.
pub fn set_ty(&mut self, ty: Type) {
for blob in ty.faces.blobs() {
if self.registered.insert(blob.id()) {
self.fcx.collection.register_fonts(blob.clone(), None);
}
}
self.ty = ty;
}

/// Whether the system has a family by this name — a settings choice
/// that is not installed would only fall back to the next in its list.
/// Whether the system, or the host's [`Faces`], has a family by this
/// name — a settings choice that is not installed would only fall back
/// to the next in its list.
pub fn has_family(&mut self, name: &str) -> bool {
self.fcx.collection.family_by_name(name).is_some()
}
Expand Down Expand Up @@ -773,6 +834,52 @@ mod tests {
assert!((f.char_width() - 2.0 * body).abs() < 0.2);
}

#[test]
fn a_face_the_host_brings_is_measured() {
const FACE: &[u8] = include_bytes!("../tests/faces/leaf-test-face.ttf");
const NAME: &str = "Leaf Test Face";
let mut f = Fonts::new(Type::default());
assert!(!f.has_family(NAME));

let faces: Faces = [FACE].into_iter().collect();
let ty = Type {
body: format!("\"{NAME}\", serif"),
faces: faces.clone(),
..Type::default()
};
f.set_ty(ty.clone());
assert!(f.has_family(NAME));
// The same files again are already in the collection.
f.set_ty(ty.clone());
assert_eq!(f.registered.len(), 1);
assert_eq!(
ty,
Type {
faces: faces.clone(),
..ty.clone()
}
);
assert_ne!(
ty,
Type {
faces: Faces::default(),
..ty.clone()
}
);

let fonts: Vec<u64> = f
.build(&[plain("abc")], Kind::Prose, None)
.layout
.lines()
.flat_map(|line| line.items().collect::<Vec<_>>())
.filter_map(|item| match item {
parley::PositionedLayoutItem::GlyphRun(g) => Some(g.run().font().data.id()),
_ => None,
})
.collect();
assert_eq!(fonts, [faces.blobs()[0].id()]);
}

#[test]
fn a_family_is_known_by_name() {
let mut f = Fonts::new(Type::default());
Expand Down
3 changes: 3 additions & 0 deletions crates/leaf-dioxus/src/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ pub fn css(ty: &Type) -> String {
size,
leading,
grid,
// Files, not rules: the host gives Blitz's collection the same ones.
faces: _,
} = ty;
let quote = ty.quote_indent();
let Rules {
Expand Down Expand Up @@ -411,6 +413,7 @@ mod tests {
size: 19.0,
leading: 1.75,
grid: None,
faces: Default::default(),
};
let css = css(&ty);
assert!(
Expand Down
93 changes: 93 additions & 0 deletions crates/leaf-dioxus/tests/faces/OFL.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
Copyright 2020-2024 The Atkinson Hyperlegible Next Project Authors (https://github.com/googlefonts/atkinson-hyperlegible-next)

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org


-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
7 changes: 7 additions & 0 deletions crates/leaf-dioxus/tests/faces/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# A face for the tests

`leaf-test-face.ttf` is Atkinson Hyperlegible Next (SIL Open Font License,
`OFL.txt`), cut down to the Latin letters and a space, fixed at weight 400,
and renamed `Leaf Test Face` so that no system has a family by its name.
`text.rs`'s tests bring it as a host's [`Faces`] and check that parley sets
text in it.
Binary file not shown.
Loading