use std::sync::Arc;
use super::{LayoutEngine, TextLayoutOutput};
use crate::{
app::glyph_engine::GlyphEngine,
layout::{
Size,
layout_result::LayoutResult,
text_style::{TextAlign, TextStyle},
},
node::{
Node,
node_kind::{NodeKind, PaintedCarets},
},
};
struct PaintedText {
carets: PaintedCarets,
top: f32,
}
pub(super) fn painted_max_width(scale: f32, wrap: bool, align: TextAlign, width: f32) -> f32 {
if (wrap || align != TextAlign::Left) && width > 0.0 {
(width * scale).ceil()
} else {
f32::MAX
}
}
impl LayoutEngine {
pub(super) fn lay_out_text_selection(&self, glyph_engine: &mut GlyphEngine, node: &Node, result: &mut LayoutResult) {
let Some(TextLayoutOutput::Text(output)) = result.text_layout.as_deref() else {
return;
};
let painted = match node.node_kind() {
NodeKind::Text { state, style, .. } if state.measures_carets() => {
let style = style.resolve(&self.typography.borrow(), &self.palette.borrow());
let content = node.text_content().unwrap_or_default();
let text = output.display_text.as_deref().unwrap_or(content);
self.painted_text(glyph_engine, text, &style, output.render_wrap, result.size)
}
NodeKind::RichText { state, spans, .. } if state.measures_carets() => {
let wrap = node.text_wrap && node.text_overflow == crate::node::node_kind::TextOverflow::Clip;
let objects = self.object_spans(glyph_engine, node, spans, result.size.width);
let laid_out = objects
.as_ref()
.map_or(spans.as_slice(), |(widened, _)| widened.as_slice());
self.painted_rich_text(glyph_engine, laid_out, wrap, result.size)
}
_ => return,
};
let output = output.with_selection(painted.carets, painted.top);
result.text_layout = Some(Arc::new(TextLayoutOutput::Text(output)));
Self::restore_text_layout_output(node, result);
}
fn painted_text(
&self,
glyph_engine: &mut GlyphEngine,
text: &str,
style: &TextStyle,
wrap: bool,
size: Size,
) -> PaintedText {
let scale = self.paint_scale.get();
let mut scaled = style.clone();
scaled.scale_pixels(scale);
let max_width = painted_max_width(scale, wrap, style.text_align, size.width);
let positions = glyph_engine.caret_positions(text, &scaled, max_width, wrap);
let top = glyph_engine.painted_text_offset(
text,
style,
&scaled,
size.width,
size.height,
max_width,
wrap,
style.vertical_align,
scale,
) / scale;
PaintedText {
carets: PaintedCarets { positions, scale },
top,
}
}
fn painted_rich_text(
&self,
glyph_engine: &mut GlyphEngine,
spans: &[crate::layout::quad::RichTextSpan],
wrap: bool,
size: Size,
) -> PaintedText {
let scale = self.paint_scale.get();
let align = spans.first().map_or(TextAlign::Left, |span| span.style.text_align);
let max_width = painted_max_width(scale, wrap, align, size.width);
let positions = glyph_engine.rich_text_caret_positions(spans, scale, max_width, wrap);
let top = glyph_engine.rich_text_vertical_align_offset(
spans,
scale,
max_width,
wrap,
crate::layout::text_style::VerticalAlign::Center,
size.height * scale,
) / scale;
PaintedText {
carets: PaintedCarets { positions, scale },
top,
}
}
}