use super::{GlyphEngine, TextVerticalExtents};
use crate::layout::{
quad::RichTextSpan,
text_style::{TextStyle, VerticalAlign},
};
pub(crate) fn offset_for_extents(align: VerticalAlign, extents: TextVerticalExtents, box_height: f32) -> f32 {
match align {
VerticalAlign::Top => -extents.ink_top,
VerticalAlign::Center => (box_height - (extents.optical_bottom - extents.optical_top)) * 0.5 - extents.optical_top,
VerticalAlign::Bottom => box_height - extents.ink_bottom,
VerticalAlign::LineBox => 0.0,
}
}
impl GlyphEngine {
pub(crate) fn text_vertical_align_offset(
&mut self,
text: &str,
style: &TextStyle,
max_width: f32,
wrap: bool,
align: VerticalAlign,
box_height: f32,
) -> f32 {
if box_height <= 0.0 || align == VerticalAlign::LineBox {
return 0.0;
}
if align == VerticalAlign::Center {
let Some((top, bottom)) = self.text_optical_extents(text, style, max_width, wrap) else {
return 0.0;
};
return (box_height - (bottom - top)) * 0.5 - top;
}
let Some(extents) = self.text_vertical_extents(text, style, max_width, wrap) else {
return 0.0;
};
offset_for_extents(align, extents, box_height)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn painted_text_offset(
&mut self,
text: &str,
style: &TextStyle,
scaled_style: &TextStyle,
width: f32,
height: f32,
max_width: f32,
wrap: bool,
align: VerticalAlign,
scale: f32,
) -> f32 {
self
.painted_wrap_offset(text, style, scaled_style, width, height, max_width, wrap, align, scale)
.unwrap_or_else(|| self.text_vertical_align_offset(text, scaled_style, max_width, wrap, align, height * scale))
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn painted_wrap_offset(
&mut self,
text: &str,
style: &TextStyle,
scaled_style: &TextStyle,
width: f32,
height: f32,
max_width: f32,
wrap: bool,
align: VerticalAlign,
scale: f32,
) -> Option<f32> {
if !wrap || width <= 0.0 || height <= 0.0 || matches!(align, VerticalAlign::LineBox | VerticalAlign::Top) {
return None;
}
let laid_out = self.text_vertical_align_offset(text, style, width, wrap, align, height) * scale;
let painted = self.text_vertical_align_offset(text, scaled_style, max_width, wrap, align, height * scale);
((laid_out - painted).abs() > scaled_style.font_size * 0.4).then_some(laid_out)
}
pub(crate) fn rich_text_vertical_align_offset(
&mut self,
spans: &[RichTextSpan],
scale: f32,
max_width: f32,
wrap: bool,
align: VerticalAlign,
box_height: f32,
) -> f32 {
if box_height <= 0.0 {
return 0.0;
}
if let [span] = spans {
let mut style = span.style.clone();
style.scale_pixels(scale);
return self.text_vertical_align_offset(&span.text, &style, max_width, wrap, align, box_height);
}
let measured = self.measure_rich_text(spans, scale, max_width).height;
offset_for_extents(
align,
TextVerticalExtents {
ink_top: 0.0,
ink_bottom: measured,
optical_top: 0.0,
optical_bottom: measured,
},
box_height,
)
}
}