use f_office_paint::{Join, Outline, Rgb};
use f_office_units::Length;
use f_office_units::scale::PERCENT;
use super::{Glyph, OPERATOR_BREAK_SPACE, ShaperSettings, SpaceKind};
use crate::FaceMetrics;
use crate::character_class::CharacterClass;
use crate::grid::{Dot, Rounding};
use crate::props::{
Color, MathScript, MathStep, MathStyle, OutlineColor, RunProps, TextOutline, VerticalAlign,
};
use crate::styles::FullWidthSpacing;
#[derive(Clone, Copy)]
pub(super) enum ScriptMove<'a> {
LostSize(Option<Length>),
LineEdges(Edges<'a>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ScriptScale {
TwoThirds,
Fallback,
OwnShare { part: i64, whole: i64 },
}
impl ScriptScale {
pub(super) fn of_face(metrics: &FaceMetrics, vertical: Option<VerticalAlign>) -> Self {
let em = i64::from(metrics.units_per_em.max(1));
let size = i64::from(metrics.superscript_size);
let offset = i64::from(metrics.superscript_offset);
let at_most = |value: i64, (part, whole): (i64, i64)| value * whole <= part * em;
let own = match vertical {
Some(VerticalAlign::Subscript) => i64::from(metrics.subscript_size),
Some(VerticalAlign::Superscript | VerticalAlign::Baseline) | None => size,
};
let kept = at_most(size, crate::params::SCRIPT_KEPT_SIZE_MAX)
&& offset > 0
&& at_most(offset, crate::params::SCRIPT_KEPT_OFFSET_MAX)
&& own > 0;
if kept {
Self::OwnShare {
part: own,
whole: em,
}
} else {
Self::Fallback
}
}
pub(super) fn falls_back(self, full: Length) -> bool {
match self {
Self::TwoThirds => false,
Self::Fallback => true,
Self::OwnShare { part, whole } => {
let (most, of) = crate::params::SCRIPT_FALLBACK_LINE_SHARE;
nearest_half_points(full, part, whole) * of <= full * most
}
}
}
fn size(self, full: Length) -> Length {
match self {
Self::TwoThirds => {
let (part, whole) = crate::params::SCRIPT_SIZE;
whole_half_points((full * part).div_toward_zero(whole))
}
Self::Fallback => {
let (part, whole) = crate::params::SCRIPT_FALLBACK_SIZE;
nearest_half_points(full, part, whole)
}
Self::OwnShare { .. } if self.falls_back(full) => Self::Fallback.size(full),
Self::OwnShare { part, whole } => nearest_half_points(full, part, whole),
}
}
}
#[derive(Clone, Copy)]
pub(super) struct Edges<'a> {
pub(super) metrics: &'a FaceMetrics,
pub(super) dot: Dot,
pub(super) heights: &'a dyn Fn(u16) -> Option<(i16, i16)>,
pub(super) room: i64,
}
impl Edges<'_> {
fn top(&self, size: Length, gap: i64) -> Length {
let dots = self.pixels(size).map_or_else(
|| self.dots(i64::from(self.metrics.script_top) + gap, size),
|(y_max, _)| i64::from(y_max) + self.dots(gap, size),
);
half_points(dots, self.dot)
}
fn bottom(&self, size: Length) -> Length {
let dots = self.pixels(size).map_or_else(
|| self.dots(i64::from(self.metrics.descent) + self.room, size),
|(_, y_min)| -i64::from(y_min) + self.dots(self.room, size),
);
half_points(dots, self.dot)
}
fn dots(&self, font_units: i64, size: Length) -> i64 {
let em = i64::from(self.metrics.units_per_em.max(1));
let units = i128::from(font_units) * i128::from(size.units());
self.dot.count_exact(units, i128::from(em)).unwrap_or(0)
}
fn pixels(&self, size: Length) -> Option<(i16, i16)> {
let pels = u16::try_from(self.dot.count(size, Rounding::HalfUp)).ok()?;
(self.heights)(pels)
}
}
pub(super) fn size_and_rise(
props: &RunProps,
how: ScriptMove<'_>,
scale: ScriptScale,
) -> (Length, Length) {
let full = full_size(props);
let small = scale.size(full);
let lost = full - small;
let rise = match (props.vertical, how) {
(Some(VerticalAlign::Superscript), ScriptMove::LostSize(cap)) => {
cap.map_or(lost, |cap| lost.min(cap))
}
(Some(VerticalAlign::Subscript), ScriptMove::LostSize(_)) => {
-lost.div_round(crate::params::SUBSCRIPT_DROP_PARTS)
}
(Some(VerticalAlign::Superscript), ScriptMove::LineEdges(edges))
if scale.falls_back(full) =>
{
if edges.metrics.east_asian {
lost
} else {
let m = edges.metrics;
let gap = i64::from(m.line_top) - i64::from(m.script_top);
edges.top(full, gap).min(full) - edges.top(small, 0).min(small)
}
}
(Some(VerticalAlign::Superscript), ScriptMove::LineEdges(edges)) => {
let m = edges.metrics;
let gap = i64::from(m.line_top) - i64::from(m.script_top);
let rise = edges.top(full, gap) - edges.top(small, 0);
capped(rise, m.superscript_offset, m, full)
}
(Some(VerticalAlign::Subscript), ScriptMove::LineEdges(edges)) => {
-edge_drop(edges, scale, full, small)
}
(Some(VerticalAlign::Baseline) | None, _) => Length::ZERO,
};
let size = match props.vertical {
Some(VerticalAlign::Superscript | VerticalAlign::Subscript) => small,
Some(VerticalAlign::Baseline) | None => full,
};
(size, rise + props.position.unwrap_or(Length::ZERO))
}
fn edge_drop(edges: Edges<'_>, scale: ScriptScale, full: Length, small: Length) -> Length {
let m = edges.metrics;
let edges = match scale {
ScriptScale::TwoThirds => Edges { room: 0, ..edges },
ScriptScale::Fallback | ScriptScale::OwnShare { .. } => edges,
};
let drop = edges.bottom(full) - edges.bottom(small);
if scale.falls_back(full) {
let (part, whole) = crate::params::SCRIPT_FALLBACK_DROP_MAX;
drop.min(nearest_half_points(full, part, whole))
} else if matches!(scale, ScriptScale::OwnShare { .. }) && m.subscript_offset <= 0 {
Length::ZERO
} else {
capped(drop, m.subscript_offset, m, full)
}
}
fn nearest_half_points(length: Length, part: i64, whole: i64) -> Length {
let half_point = Length::UNITS_PER_HALF_POINT;
(length * part).div_round(whole * half_point) * half_point
}
fn whole_half_points(length: Length) -> Length {
let half_point = Length::UNITS_PER_HALF_POINT;
length.div_toward_zero(half_point) * half_point
}
impl MathStyle {
fn size(self, full: Length) -> Length {
let percent = match self {
Self::Display | Self::Text => return full,
Self::Script => crate::params::MATH_SCRIPT_PERCENT,
Self::ScriptScript => crate::params::MATH_SCRIPT_SCRIPT_PERCENT,
};
whole_half_points((full * percent).div_toward_zero(PERCENT))
}
}
pub(super) fn math_size_and_rise(
props: &RunProps,
script: MathScript,
dot: Dot,
limit: &dyn Fn(MathStep, Length) -> Option<Length>,
axis: &dyn Fn(char, Length) -> Option<Length>,
) -> (Length, Length, bool) {
let full = full_size(props);
let mut style = script.outermost_style();
let mut rise = Length::ZERO;
let mut in_fraction = false;
let mut cramped = script.is_cramped();
for (step, control_size) in script.steps_with_control_sizes() {
in_fraction |= matches!(
step,
MathStep::Numerator
| MathStep::Denominator
| MathStep::UpperLimit(_)
| MathStep::LowerLimit(_)
);
let structure = control_size
.filter(|half_points| *half_points > 0)
.and_then(Length::from_half_points)
.unwrap_or(full);
let base = style.size(structure);
let ((units, em), sign) = step_shift(step, style == MathStyle::Display, cramped);
rise += limit(step, base).unwrap_or_else(|| (base * units).div_round(em) * sign);
cramped |= matches!(
step,
MathStep::Denominator | MathStep::Limit { lower: true }
);
style = script.step_style(style, step);
}
let size = style.size(full);
rise += script
.axis_character()
.and_then(|ch| axis(ch, size))
.unwrap_or(Length::ZERO);
let position = props.position.unwrap_or(Length::ZERO);
(size, dot.snap(rise) + position, in_fraction)
}
const fn step_shift(step: MathStep, display: bool, cramped: bool) -> ((i64, i64), i64) {
match step {
MathStep::Superscript if cramped => (crate::params::MATH_SUPERSCRIPT_SHIFT_UP_CRAMPED, 1),
MathStep::Superscript | MathStep::SuperscriptBesideSubscript | MathStep::UpperLimit(_) => {
(crate::params::MATH_SUPERSCRIPT_SHIFT_UP, 1)
}
MathStep::Subscript | MathStep::LowerLimit(_) => {
(crate::params::MATH_SUBSCRIPT_SHIFT_DOWN, -1)
}
MathStep::Numerator if display => (crate::params::MATH_NUMERATOR_DISPLAY_SHIFT_UP, 1),
MathStep::Numerator => (crate::params::MATH_NUMERATOR_SHIFT_UP, 1),
MathStep::Denominator if display => {
(crate::params::MATH_DENOMINATOR_DISPLAY_SHIFT_DOWN, -1)
}
MathStep::Denominator => (crate::params::MATH_DENOMINATOR_SHIFT_DOWN, -1),
MathStep::Degree | MathStep::Limit { .. } => ((0, 1), 1),
}
}
fn half_points(dots: i64, dot: Dot) -> Length {
let half_point = Length::UNITS_PER_HALF_POINT;
dot.dots(dots).div_round(half_point) * half_point
}
fn capped(distance: Length, offset: i16, metrics: &FaceMetrics, full: Length) -> Length {
let em = i64::from(metrics.units_per_em.max(1));
let half_point = Length::UNITS_PER_HALF_POINT;
if offset > 0 {
let cap = (full * i64::from(offset)).div_round(em * half_point) * half_point;
distance.min(cap)
} else {
distance
}
}
pub(super) fn superscript_cap(props: &RunProps, metrics: &FaceMetrics) -> Option<Length> {
let offset = i64::from(metrics.superscript_offset);
let em = i64::from(metrics.units_per_em);
(offset > 0 && em > 0).then(|| (full_size(props) * offset).div_round(em))
}
pub(super) fn scale(glyphs: &mut [Glyph], percent: Option<i64>) {
let Some(percent) = percent.filter(|p| *p != PERCENT) else {
return;
};
for glyph in glyphs {
glyph.advance = (glyph.advance * percent).div_toward_zero(PERCENT);
}
}
pub(super) fn spread(glyphs: &mut [Glyph], spacing: Option<Length>, settings: &ShaperSettings) {
let Some(spacing) = spacing.filter(|s| *s != Length::ZERO) else {
return;
};
for glyph in glyphs.iter_mut().filter(|g| !g.part) {
let twice = settings.full_width_spacing == FullWidthSpacing::Twice;
let cells = if twice && CharacterClass::FullWidthCell.contains(glyph.ch) {
2
} else {
1
};
let delta = (spacing * cells).max(-glyph.advance);
glyph.advance += delta;
if let Some(own) = settings.spacing_on_its_own(delta) {
glyph.spacing += own;
}
}
}
pub(super) fn hold_math_spaces(glyphs: &mut [Glyph]) {
let mut before: Option<&mut Glyph> = None;
for glyph in glyphs.iter_mut() {
match glyph.ch {
' ' => glyph.space = SpaceKind::Equation,
OPERATOR_BREAK_SPACE => {
glyph.ch = '\u{00A0}';
glyph.space = SpaceKind::Operator;
if let Some(before) = before
&& before.ch == crate::math::HAIR_SPACE
{
before.space = SpaceKind::Operator;
}
}
_ => {}
}
before = Some(glyph);
}
}
pub(super) fn kerned(props: &RunProps) -> bool {
let size = props.drawn_half_points();
props
.kern
.is_some_and(|threshold| threshold > 0 && size >= threshold)
}
pub(super) fn math_ink_below(props: &RunProps, in_fraction: bool) -> bool {
in_fraction && !props.math_script.is_some_and(MathScript::is_display)
}
pub(super) fn full_size(props: &RunProps) -> Length {
Length::from_half_points(props.drawn_half_points()).unwrap_or(Length::ZERO)
}
pub(super) fn color(props: &RunProps) -> Rgb {
props.color.map_or(Rgb::BLACK, Color::drawn)
}
pub(super) fn background(props: &RunProps) -> Option<Rgb> {
props
.highlight
.and_then(Color::rgb)
.or_else(|| props.shading.and_then(Color::rgb))
}
pub(super) fn outline(props: &RunProps) -> Option<Outline> {
const SCHEME_YELLOW: Rgb = {
let [r, g, b] = crate::params::OUTLINE_THEME_COLOR;
Rgb { r, g, b }
};
match props.outline? {
TextOutline::None => None,
TextOutline::Solid { width, color } => Some(Outline {
width,
color: match color {
OutlineColor::Rgb([r, g, b]) => Rgb { r, g, b },
OutlineColor::Scheme => SCHEME_YELLOW,
},
join: Join::Round,
}),
}
}