use crate::paint::{AbsoluteColor, Color};
use crate::style::{
StyleError, box_values::unsupported, component::Component, grammar::Keyword, units::Relative,
};
use serde::Serialize;
use std::sync::Arc;
const SHADOW_LENGTHS_SLOT: usize = 0;
const SHADOW_COLOR_SLOT: usize = 1;
const SHADOW_BLUR_INDEX: usize = 2;
const EMPHASIS_FILL_SLOT: usize = 0;
const EMPHASIS_SHAPE_SLOT: usize = 1;
#[derive(Clone, Debug, PartialEq, Serialize)]
pub(crate) struct InheritedColor {
pub used: Color,
#[serde(skip)]
current: Option<Arc<Component>>,
}
impl Default for InheritedColor {
fn default() -> Self {
Self {
used: Color::BLACK,
current: Some(Arc::new(Component::MathColor(
crate::style::colors::CURRENT_COLOR.into(),
))),
}
}
}
impl InheritedColor {
pub(super) fn specified(used: Color) -> Self {
Self {
used,
current: None,
}
}
pub(super) fn depends_on_color(&self) -> bool {
self.current.is_some()
}
pub(super) fn compute(
value: &Component,
relative: &Relative<'_>,
current: &AbsoluteColor,
) -> Result<Self, StyleError> {
Ok(Self {
used: crate::style::colors::color(value, relative, current)?,
current: crate::style::resolution::contains_current_color(value)
.then(|| Arc::new(value.unwrap().clone())),
})
}
pub(super) fn resolve(
&mut self,
relative: &Relative<'_>,
current: &AbsoluteColor,
) -> Result<(), StyleError> {
if let Some(value) = &self.current {
self.used = crate::style::colors::color(value, relative, current)?;
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub(crate) struct TextShadow {
pub offset: [f32; 2],
pub blur: f32,
pub color: InheritedColor,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub(crate) enum EmphasisShape {
Dot,
Circle,
DoubleCircle,
Triangle,
Sesame,
}
impl EmphasisShape {
fn character(self, filled: bool) -> char {
match (self, filled) {
(Self::Dot, true) => '\u{2022}',
(Self::Dot, false) => '\u{25E6}',
(Self::Circle, true) => '\u{25CF}',
(Self::Circle, false) => '\u{25CB}',
(Self::DoubleCircle, true) => '\u{25C9}',
(Self::DoubleCircle, false) => '\u{25CE}',
(Self::Triangle, true) => '\u{25B2}',
(Self::Triangle, false) => '\u{25B3}',
(Self::Sesame, true) => '\u{FE45}',
(Self::Sesame, false) => '\u{FE46}',
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub(crate) enum EmphasisStyle {
#[default]
None,
Shape {
filled: bool,
shape: EmphasisShape,
},
String(Box<str>),
}
impl EmphasisStyle {
pub(super) fn from_component(value: &Component) -> Result<Self, StyleError> {
if value.keyword() == Some(Keyword::None) {
return Ok(Self::None);
}
if let Component::String(text) = value.unwrap() {
return Ok(Self::String(text.clone()));
}
let filled = match value.slot(EMPHASIS_FILL_SLOT).and_then(Component::keyword) {
None | Some(Keyword::Filled) => true,
Some(Keyword::Open) => false,
Some(_) => return Err(unsupported(value)),
};
let shape = match value.slot(EMPHASIS_SHAPE_SLOT).and_then(Component::keyword) {
Some(Keyword::Dot) => EmphasisShape::Dot,
None | Some(Keyword::Circle) => EmphasisShape::Circle,
Some(Keyword::DoubleCircle) => EmphasisShape::DoubleCircle,
Some(Keyword::Triangle) => EmphasisShape::Triangle,
Some(Keyword::Sesame) => EmphasisShape::Sesame,
Some(_) => return Err(unsupported(value)),
};
Ok(Self::Shape { filled, shape })
}
pub(crate) fn shape(&self) -> Option<(EmphasisShape, bool)> {
match self {
Self::Shape { filled, shape } => Some((*shape, *filled)),
Self::None | Self::String(_) => None,
}
}
pub(crate) fn mark(&self) -> Option<String> {
use unicode_segmentation::UnicodeSegmentation;
match self {
Self::None => None,
Self::Shape { filled, shape } => Some(shape.character(*filled).to_string()),
Self::String(text) => text.graphemes(true).next().map(str::to_owned),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub(crate) enum EmphasisSide {
#[default]
Auto,
Over,
Under,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub(crate) struct EmphasisPosition {
pub side: EmphasisSide,
pub left: bool,
}
impl EmphasisPosition {
pub(super) fn from_component(value: &Component) -> Result<Self, StyleError> {
let mut keywords = Vec::new();
value.keywords(&mut keywords);
let mut position = Self::default();
for keyword in keywords {
match keyword {
Keyword::Auto => position.side = EmphasisSide::Auto,
Keyword::Over => position.side = EmphasisSide::Over,
Keyword::Under => position.side = EmphasisSide::Under,
Keyword::Left => position.left = true,
Keyword::Right => position.left = false,
_ => return Err(unsupported(value)),
}
}
Ok(position)
}
pub(crate) fn under(self, style: &crate::style::Style) -> bool {
const CHINESE: &str = "zh";
if style.vertical_typographic_mode() {
return self.left;
}
match self.side {
EmphasisSide::Over => false,
EmphasisSide::Under => true,
EmphasisSide::Auto => crate::style::has_primary_language(&style.language, CHINESE),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct EmphasisSkip {
pub spaces: bool,
pub punctuation: bool,
pub symbols: bool,
pub narrow: bool,
}
impl Default for EmphasisSkip {
fn default() -> Self {
Self {
spaces: true,
punctuation: true,
symbols: false,
narrow: false,
}
}
}
impl EmphasisSkip {
pub(super) fn from_component(value: &Component) -> Result<Self, StyleError> {
let mut keywords = Vec::new();
value.keywords(&mut keywords);
let mut skip = Self {
spaces: false,
punctuation: false,
symbols: false,
narrow: false,
};
for keyword in keywords {
match keyword {
Keyword::Spaces => skip.spaces = true,
Keyword::Punctuation => skip.punctuation = true,
Keyword::Symbols => skip.symbols = true,
Keyword::Narrow => skip.narrow = true,
_ => return Err(unsupported(value)),
}
}
Ok(skip)
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub(crate) struct TextPaint {
pub fill: InheritedColor,
pub stroke_width: f32,
pub stroke_color: InheritedColor,
pub shadows: Arc<[TextShadow]>,
pub emphasis: EmphasisStyle,
pub emphasis_color: InheritedColor,
pub emphasis_position: EmphasisPosition,
pub emphasis_skip: EmphasisSkip,
}
impl TextPaint {
pub(super) fn resolve(
&mut self,
relative: &Relative<'_>,
current: &AbsoluteColor,
) -> Result<(), StyleError> {
self.fill.resolve(relative, current)?;
self.stroke_color.resolve(relative, current)?;
self.emphasis_color.resolve(relative, current)?;
resolve_shadows(&mut self.shadows, relative, current)
}
}
pub(super) fn resolve_shadows(
shadows: &mut Arc<[TextShadow]>,
relative: &Relative<'_>,
current: &AbsoluteColor,
) -> Result<(), StyleError> {
if shadows.iter().any(|shadow| shadow.color.current.is_some()) {
let mut resolved = shadows.to_vec();
for shadow in &mut resolved {
shadow.color.resolve(relative, current)?;
}
*shadows = resolved.into();
}
Ok(())
}
pub(super) fn text_shadows(
value: &Component,
relative: &Relative<'_>,
current: &AbsoluteColor,
) -> Result<Arc<[TextShadow]>, StyleError> {
if value.keyword() == Some(Keyword::None) {
return Ok(Arc::from([]));
}
value
.items()
.iter()
.map(|item| {
let lengths = item
.slot(SHADOW_LENGTHS_SLOT)
.ok_or_else(|| unsupported(item))?
.items()
.iter()
.map(|length| crate::style::values::length(length, relative))
.collect::<Result<Vec<_>, _>>()?;
let blur = lengths.get(SHADOW_BLUR_INDEX).copied().unwrap_or(0.0);
if blur < 0.0 {
return Err(format!("negative text-shadow blur radius: {item}").into());
}
let color = match item
.slot(SHADOW_COLOR_SLOT)
.and_then(|color| color.items().first())
{
Some(color) => InheritedColor::compute(color, relative, current)?,
None => InheritedColor {
used: current.used(),
..InheritedColor::default()
},
};
Ok(TextShadow {
offset: [lengths[0], lengths[1]],
blur,
color,
})
})
.collect()
}
pub(super) fn stroke_width(value: &Component, relative: &Relative<'_>) -> Result<f32, StyleError> {
let width = crate::style::values::length(value, relative)?;
if width < 0.0 {
return Err(format!("negative -webkit-text-stroke-width: {value}").into());
}
Ok(width)
}