use std::hash::Hash;
use std::panic::Location;
use glam::Vec2;
use taffy::{AvailableSpace, Size};
use super::emit::{content_width, underline};
use super::inline::{InlineLayout, InlineRun, RunFont, Wrap};
use super::style::{Display, TextDecoration, WhiteSpace};
use super::{Behavior, Content, FrameNode, KeySource, Response, Ui, hash_of};
use crate::draw_list::DrawList;
use crate::style::{Declaration, NodeSelector, PseudoClasses};
use crate::text::{ASCENDER, FontAtlas};
use crate::widget::NATURAL_FONT_SIZE;
#[derive(Debug)]
pub struct ParagraphBuilder<'a> {
ui: &'a mut Ui,
}
impl ParagraphBuilder<'_> {
#[track_caller]
pub fn run(&mut self, selector: &str, text: &str, inline: &[Declaration]) -> Response {
let parsed = self.ui.node_selector(selector);
let key = self.ui.selector_key(parsed, Location::caller());
self.ui.push_run(key, parsed, text, inline)
}
pub fn run_keyed(
&mut self,
key: impl Hash,
selector: &str,
text: &str,
inline: &[Declaration],
) -> Response {
let parsed = self.ui.node_selector(selector);
let key = self.ui.key(KeySource::Keyed(hash_of(key)));
self.ui.push_run(key, parsed, text, inline)
}
}
#[derive(Clone, Debug)]
pub(super) struct LaidOut {
pub paragraph: usize,
pub runs: Vec<usize>,
pub layout: InlineLayout,
}
impl Ui {
#[track_caller]
pub fn paragraph(
&mut self,
selector: &str,
inline: &[Declaration],
build: impl FnOnce(&mut ParagraphBuilder<'_>),
) -> Response {
let parsed = self.node_selector(selector);
let key = self.selector_key(parsed, Location::caller());
let index = self.push(
key,
parsed,
inline,
Behavior::NONE,
PseudoClasses::NONE,
Content::Paragraph,
);
let response = self.response(index);
self.open.push(index);
build(&mut ParagraphBuilder { ui: self });
self.open.pop();
let mut hash = hash_of(self.nodes[index].style.white_space);
let mut next = self.nodes[index].first_child;
while let Some(run) = next {
let node = &self.nodes[run];
hash = hash_of((hash, node.content_hash, node.style.display));
next = node.next_sibling;
}
self.nodes[index].content_hash = hash;
self.live_text.insert(hash);
self.close(index);
response
}
fn push_run(
&mut self,
key: super::NodeKey,
selector: NodeSelector<'_>,
text: &str,
inline: &[Declaration],
) -> Response {
let start = self.text.len();
self.text.push_str(text);
let content = Content::Run {
start,
end: self.text.len(),
};
let index = self.push(
key,
selector,
inline,
Behavior::NONE,
PseudoClasses::NONE,
content,
);
self.close(index);
self.response(index)
}
pub(super) fn lay_out_paragraphs(&mut self, atlas: &FontAtlas) {
self.paragraphs.clear();
for (paragraph, node) in self.nodes.iter().enumerate() {
if node.content != Content::Paragraph {
continue;
}
let (runs, inputs) = inline_runs(&self.nodes, &self.text, paragraph);
let wrap = match node.style.white_space {
WhiteSpace::Normal => {
Wrap::Width(content_width(&self.store.get(node.slot).unrounded))
}
WhiteSpace::NoWrap => Wrap::None,
};
let mut layout = InlineLayout::new(&inputs, wrap, atlas);
layout.align(content_width(&node.layout), node.style.text_align);
self.paragraphs.push(LaidOut {
paragraph,
runs,
layout,
});
}
}
pub(super) fn place_runs(&mut self) {
for laid in &self.paragraphs {
for &run in &laid.runs {
self.store.get_mut(self.nodes[run].slot).fragments.clear();
}
let origin = self.content_origin(laid.paragraph);
for fragment in laid.layout.fragments() {
let line = &laid.layout.lines()[fragment.line];
let min = origin + Vec2::new(fragment.x, line.top);
let max = min + Vec2::new(fragment.width, line.height);
let stored = self.store.get_mut(self.nodes[laid.runs[fragment.run]].slot);
stored.rect = if stored.fragments.is_empty() {
(min, max)
} else {
(stored.rect.0.min(min), stored.rect.1.max(max))
};
stored.fragments.push((min, max));
}
}
}
fn content_origin(&self, index: usize) -> Vec2 {
let node = &self.nodes[index];
let (border, padding) = (node.layout.border, node.layout.padding);
self.store.get(node.slot).rect.0
+ Vec2::new(border.left + padding.left, border.top + padding.top)
}
pub(super) fn emit_paragraph(&self, index: usize, list: &mut DrawList) {
let Some(laid) = self.paragraphs.iter().find(|laid| laid.paragraph == index) else {
return;
};
let origin = self.content_origin(index);
for fragment in laid.layout.fragments() {
let run = &self.nodes[laid.runs[fragment.run]];
let Content::Run { start, end } = run.content else {
continue;
};
let run_text = &self.text[start..end];
let text = &run_text[fragment.text.clone()];
let style = &run.style;
let line = &laid.layout.lines()[fragment.line];
if style.text_decoration == TextDecoration::Underline {
let (min, max) = underline(
run.font.as_ref(),
style.font_size,
line.baseline,
fragment.x,
fragment.width,
);
list.rect(origin + min, origin + max, style.color);
}
match &run.font {
Some(font) => {
for (face, glyphs, bytes) in laid.layout.face_runs(fragment) {
list.text_glyphs(
origin,
font.face(face),
style.font_size,
style.color,
glyphs,
&run_text[bytes],
);
}
}
None => {
let scale = style.font_size / NATURAL_FONT_SIZE;
let top = line.baseline - ASCENDER as f32 * scale;
list.text(
origin + Vec2::new(fragment.x, top),
text,
style.color,
style.font_size,
);
}
}
}
}
}
pub(super) fn inline_runs<'a>(
nodes: &'a [FrameNode],
text: &'a str,
paragraph: usize,
) -> (Vec<usize>, Vec<InlineRun<'a>>) {
let mut indices = Vec::new();
let mut runs = Vec::new();
let mut next = nodes[paragraph].first_child;
while let Some(index) = next {
let node = &nodes[index];
next = node.next_sibling;
let Content::Run { start, end } = node.content else {
continue;
};
if node.style.display == Display::None {
continue;
}
let style = &node.style;
let run = match &node.font {
Some(font) => InlineRun::new(
&text[start..end],
RunFont::Parsed(font),
style.font_size,
style.text_line_height(font),
),
None => InlineRun::new(
&text[start..end],
RunFont::Bitmap(style.font_size / NATURAL_FONT_SIZE),
style.font_size,
0.0,
),
};
indices.push(index);
runs.push(run);
}
(indices, runs)
}
pub(super) fn measure_runs(
runs: &[InlineRun<'_>],
white_space: WhiteSpace,
width: AvailableSpace,
atlas: &FontAtlas,
) -> Size<f32> {
let wrap = match (white_space, width) {
(WhiteSpace::NoWrap, _) | (_, AvailableSpace::MaxContent) => Wrap::None,
(WhiteSpace::Normal, AvailableSpace::MinContent) => Wrap::MinContent,
(WhiteSpace::Normal, AvailableSpace::Definite(width)) => Wrap::Width(width),
};
let measured = InlineLayout::new(runs, wrap, atlas).measure();
Size {
width: measured.x,
height: measured.y,
}
}