pub use crate::font::canonical::{
check_fonts, check_fonts_with_operation, font_families, font_families_with_operation,
FontDiscovery, FontFamily, FontFamilyReport, FontScope, FontSourceIssue, FontStack, FontStyle,
FontSupport, FontVariantReport, GenericFontFamily,
};
pub use crate::spec::TextWeight;
mod fit;
pub(crate) mod layout;
pub(crate) mod value;
pub use fit::{TextFit, TextFitGrouping, TextFitPriority};
pub(crate) mod orientation;
pub(crate) mod position;
pub use orientation::{TextOrientation, TextRotation, TextRotationMode};
pub(crate) mod roles;
mod service;
pub use layout::{
TextAnchor, TextBounds, TextDirection, TextElision, TextEllipsis, TextFailure, TextOffset,
TextOffsetFrame, TextOverflow, TextOverlap, TextVisibility, TextWrapping,
};
pub use position::{TextCoordinate, TextPosition};
pub(crate) use service::{TextRequestContext, TextService};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TextLayout {
pub(crate) alignment: Option<TextAlignment>,
instructions: Option<std::sync::Arc<TextInstructions>>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct TextInstructions {
pub(crate) fit: Option<TextFit>,
pub(crate) fit_priority: Option<TextFitPriority>,
pub(crate) direction: Option<TextDirection>,
pub(crate) orientation: Option<TextOrientation>,
pub(crate) rotation_mode: Option<TextRotationMode>,
pub(crate) anchor: Option<TextAnchor>,
pub(crate) offset: Option<TextOffset>,
pub(crate) bounds: Option<TextBounds>,
pub(crate) wrapping: Option<TextWrapping>,
pub(crate) overflow: Option<TextOverflow>,
pub(crate) overlap: Option<TextOverlap>,
pub(crate) visibility: Option<TextVisibility>,
}
impl TextLayout {
#[must_use]
pub const fn get_alignment(&self) -> Option<TextAlignment> {
self.alignment
}
#[must_use]
pub fn get_fit(&self) -> Option<TextFit> {
self.instructions().fit
}
#[must_use]
pub fn get_fit_priority(&self) -> Option<TextFitPriority> {
self.instructions().fit_priority
}
#[must_use]
pub fn get_direction(&self) -> Option<TextDirection> {
self.instructions().direction
}
#[must_use]
pub fn get_orientation(&self) -> Option<&TextOrientation> {
self.instructions().orientation.as_ref()
}
#[must_use]
pub fn get_rotation_mode(&self) -> Option<TextRotationMode> {
self.instructions().rotation_mode
}
#[must_use]
pub fn get_anchor(&self) -> Option<TextAnchor> {
self.instructions().anchor
}
#[must_use]
pub fn get_offset(&self) -> Option<TextOffset> {
self.instructions().offset
}
#[must_use]
pub fn get_bounds(&self) -> Option<TextBounds> {
self.instructions().bounds
}
#[must_use]
pub fn get_wrapping(&self) -> Option<TextWrapping> {
self.instructions().wrapping
}
#[must_use]
pub fn get_overflow(&self) -> Option<&TextOverflow> {
self.instructions().overflow.as_ref()
}
#[must_use]
pub fn get_overlap(&self) -> Option<TextOverlap> {
self.instructions().overlap
}
#[must_use]
pub fn get_visibility(&self) -> Option<&TextVisibility> {
self.instructions().visibility.as_ref()
}
pub(crate) fn hidden(&self) -> bool {
self.instructions()
.visibility
.as_ref()
.is_some_and(|visibility| visibility.hidden)
}
pub(crate) const EMPTY: Self = Self {
alignment: None,
instructions: None,
};
pub(crate) fn instructions(&self) -> &TextInstructions {
static EMPTY: TextInstructions = TextInstructions {
fit: None,
fit_priority: None,
direction: None,
orientation: None,
rotation_mode: None,
anchor: None,
offset: None,
bounds: None,
wrapping: None,
overflow: None,
overlap: None,
visibility: None,
};
self.instructions.as_deref().unwrap_or(&EMPTY)
}
pub(crate) fn edit_instructions(&mut self) -> &mut TextInstructions {
std::sync::Arc::make_mut(
self.instructions
.get_or_insert_with(|| std::sync::Arc::new(TextInstructions::default())),
)
}
#[must_use]
pub const fn alignment(mut self, alignment: TextAlignment) -> Self {
self.alignment = Some(alignment);
self
}
}
macro_rules! layout_edits {
($($field:ident:$value:ty),+ $(,)?) => {impl TextLayout {$(
#[doc = concat!("Replace this request's `",stringify!($field),"` instruction.")]
#[must_use]
pub fn $field(mut self,value:$value) -> Self {self.edit_instructions().$field=Some(value);self}
)+}};
}
layout_edits! {anchor:TextAnchor,offset:TextOffset,bounds:TextBounds,wrapping:TextWrapping,overflow:TextOverflow,overlap:TextOverlap,visibility:TextVisibility,orientation:TextOrientation,rotation_mode:TextRotationMode,direction:TextDirection,fit:TextFit,fit_priority:TextFitPriority}
impl TextLayout {
#[must_use]
pub fn rotation(self, value: TextRotation) -> Self {
self.orientation(TextOrientation::fixed(value))
}
}
#[derive(Clone, Copy)]
pub(crate) struct TextAppearance<'a> {
pub(crate) theme: &'a crate::theme::TextTheme,
pub(crate) exact_override: bool,
pub(crate) layout: Option<&'a TextLayout>,
}
impl<'a> From<&'a crate::theme::TextTheme> for TextAppearance<'a> {
fn from(theme: &'a crate::theme::TextTheme) -> Self {
Self {
theme,
exact_override: false,
layout: None,
}
}
}
impl TextAppearance<'_> {
pub(crate) fn require_single(self) -> crate::Result<Self> {
if !self.hidden()
&& self
.layout
.and_then(|request| request.instructions().orientation.as_ref())
.is_some_and(|orientation| {
matches!(orientation.0, orientation::Orientation::Automatic(_))
})
{
return Err(crate::Error::Data(
"automatic orientation requires an actual tick group".into(),
));
}
if self
.layout
.and_then(|request| request.instructions().visibility.as_ref())
.is_some_and(crate::text::TextVisibility::reduces)
{
return Err(crate::Error::Data("text visibility reduction requires an actual label group, not an independent authored slot".into()));
}
Ok(self)
}
pub(crate) fn includes(self, index: usize, eligible: &[usize]) -> bool {
self.layout
.and_then(|request| request.instructions().visibility.as_ref())
.is_none_or(|policy| policy.includes(index, eligible))
}
pub(crate) fn hidden(self) -> bool {
self.layout.is_some_and(|layout| {
layout
.instructions()
.visibility
.as_ref()
.is_some_and(|visibility| visibility.hidden)
})
}
}
impl<'a> TextAppearance<'a> {
pub(crate) fn layout(mut self, layout: Option<&'a TextLayout>) -> Self {
self.layout = layout;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextAlignment {
Start,
Center,
End,
}
impl TextAlignment {
pub(crate) fn resolve_physical(
self,
span_start: f64,
span_end: f64,
) -> (f64, crate::render::backend::TextAnchor) {
use crate::render::backend::TextAnchor;
match self {
Self::Start => (span_start, TextAnchor::Start),
Self::Center => (
span_start + (span_end - span_start) / 2.0,
TextAnchor::Middle,
),
Self::End => (span_end, TextAnchor::End),
}
}
}
#[derive(Debug, Clone, Copy, thiserror::Error)]
#[error("display text contains unsupported control character U+{scalar:04X}")]
pub(crate) struct UnsupportedControl {
pub(crate) scalar: u32,
start: usize,
end: usize,
}
pub(crate) fn validate(source: &str) -> Result<(), UnsupportedControl> {
match source
.char_indices()
.find(|(_, scalar)| is_unsupported_control(*scalar))
{
Some((start, scalar)) => Err(UnsupportedControl {
scalar: scalar as u32,
start,
end: start + scalar.len_utf8(),
}),
None => Ok(()),
}
}
pub(crate) fn validate_for(source: &str, role: &str) -> crate::Result<()> {
if let Err(error) = validate(source) {
use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, TextSpan};
return Err(crate::Error::Data(
Diagnostic::new(
DiagnosticKind::InvalidValue {
value: Some(crate::data::RawKey::from(&source[error.start..error.end])),
constraint: "supported text scalar".to_owned(),
},
format!("{role}: {error}"),
)
.with_context(ErrorContext::new().with_span(TextSpan::new(
source,
error.start,
error.end,
)?)),
));
}
Ok(())
}
pub(crate) fn is_unsupported_control(scalar: char) -> bool {
scalar.is_control()
&& !is_nonrendering_mandatory_break(scalar)
&& !is_nonpainting_control(scalar)
}
pub(crate) const fn is_nonrendering_mandatory_break(scalar: char) -> bool {
matches!(
scalar,
'\u{000A}' | '\u{000B}' | '\u{000C}' | '\u{000D}' | '\u{0085}' | '\u{2028}' | '\u{2029}'
)
}
pub(crate) const fn is_nonpainting_control(scalar: char) -> bool {
matches!(scalar as u32, 0x00AD | 0x034F | 0x061C | 0x115F..=0x1160
| 0x17B4..=0x17B5 | 0x180B..=0x180F | 0x200B..=0x200F
| 0x202A..=0x202E | 0x2060..=0x206F | 0x3164 | 0xFE00..=0xFE0F
| 0xFEFF | 0xFFA0 | 0xFFF0..=0xFFF8 | 0x1BCA0..=0x1BCA3
| 0x1D173..=0x1D17A | 0xE0000..=0xE0FFF)
}
#[cfg(test)]
mod tests {
use crate::{
coordinates::{AxisTick, DataAreaCorner},
elements::PlotTextAnnotation,
formatting::Labels,
layout::TextPanel,
Canvas, NumericValues, Plot,
};
#[test]
fn content_replacement_retains_instructions_until_a_whole_request_replaces_them() {
use crate::{
text::{TextAlignment, TextLayout},
Text,
};
const BEFORE_CONTENT: Text = {
let mut slot = Text::UNSET;
slot.edit_alignment(TextAlignment::End);
slot
};
let mut slot = BEFORE_CONTENT;
assert!(slot.provided().is_none());
let style = crate::Theme::publication()
.typography()
.get_root()
.get_title()
.clone();
slot.replace_from(Text::new("first").style(style.clone()))
.unwrap();
slot.replace_from(Text::new("replacement")).unwrap();
assert_eq!(
slot.provided(),
Some(
&Text::new("replacement")
.style(style.clone())
.alignment(TextAlignment::End)
)
);
slot.replace_from(Text::new("reset").layout(TextLayout::default()))
.unwrap();
assert_eq!(
slot.provided(),
Some(
&Text::new("reset")
.style(style.clone())
.layout(TextLayout::default())
)
);
slot.edit_alignment(TextAlignment::Start);
assert_eq!(
slot.provided(),
Some(
&Text::new("reset")
.style(style)
.alignment(TextAlignment::Start)
)
);
}
#[test]
fn required_reception_rejects_unset_before_mutating_instructions() {
use crate::{text::TextAlignment, Text};
let mut text = Text::new("retained").alignment(TextAlignment::End);
let previous = text.clone();
assert!(matches!(
text.replace_from(Text::UNSET),
Err(crate::Error::Render(_))
));
assert_eq!(text, previous);
assert!(matches!(
Text::UNSET.required_source("required"),
Err(crate::Error::Render(_))
));
assert_eq!(Text::new("").required_source("required").unwrap(), "");
assert!(matches!(
Text::new("invalid\tcontrol").required_source("required"),
Err(crate::Error::Data(_))
));
assert!(TextPanel::new(Text::UNSET, "body").is_err());
assert!(PlotTextAnnotation::new(DataAreaCorner::TopLeft, Text::UNSET).is_err());
}
#[test]
fn unsupported_display_controls_fail_before_font_discovery() {
let before = crate::font::canonical::FONT_DISCOVERY_CALLS.with(std::cell::Cell::get);
let plot = || {
Plot::scatter(
NumericValues::new("x", [0.0, 1.0]),
NumericValues::new("y", [1.0, 0.0]),
)
};
let canvas = || {
Canvas::grid(1, 1)
.unwrap()
.panel(0, 0, TextPanel::new("", "body").unwrap())
.unwrap()
};
let errors = [
PlotTextAnnotation::new(DataAreaCorner::TopLeft, "a\tb").unwrap_err(),
TextPanel::new("title", "a\tb").unwrap_err(),
canvas().column_header(0, 1, "a\tb").err().unwrap(),
canvas().title("a\tb").preflight().unwrap_err(),
plot().caption("a\tb").preflight().unwrap_err(),
plot().x_label("a\tb").preflight().unwrap_err(),
plot()
.x_ticks(vec![AxisTick::new(0.0, "a\tb")])
.preflight()
.unwrap_err(),
Labels::humanized()
.alias("raw", "a\tb")
.resolve("raw")
.unwrap_err(),
];
for error in errors {
assert!(
error
.to_string()
.contains("unsupported control character U+0009"),
"{error}"
);
}
assert_eq!(
crate::font::canonical::FONT_DISCOVERY_CALLS.with(std::cell::Cell::get),
before
);
}
}