use crate::{Font, TextLayoutInfo, TextSpanAccess, TextSpanComponent};1use bevy_asset::Handle;2use bevy_color::Color;3use bevy_derive::{Deref, DerefMut};4use bevy_ecs::{prelude::*, reflect::ReflectComponent};5use bevy_reflect::prelude::*;6use bevy_utils::{default, once};7use cosmic_text::{Buffer, Metrics};8use serde::{Deserialize, Serialize};9use smallvec::SmallVec;10use tracing::warn;1112/// Wrapper for [`cosmic_text::Buffer`]13#[derive(Deref, DerefMut, Debug, Clone)]14pub struct CosmicBuffer(pub Buffer);1516impl Default for CosmicBuffer {17fn default() -> Self {18Self(Buffer::new_empty(Metrics::new(0.0, 0.000001)))19}20}2122/// A sub-entity of a [`ComputedTextBlock`].23///24/// Returned by [`ComputedTextBlock::entities`].25#[derive(Debug, Copy, Clone, Reflect)]26#[reflect(Debug, Clone)]27pub struct TextEntity {28/// The entity.29pub entity: Entity,30/// Records the hierarchy depth of the entity within a `TextLayout`.31pub depth: usize,32}3334/// Computed information for a text block.35///36/// See [`TextLayout`].37///38/// Automatically updated by 2d and UI text systems.39#[derive(Component, Debug, Clone, Reflect)]40#[reflect(Component, Debug, Default, Clone)]41pub struct ComputedTextBlock {42/// Buffer for managing text layout and creating [`TextLayoutInfo`].43///44/// This is private because buffer contents are always refreshed from ECS state when writing glyphs to45/// `TextLayoutInfo`. If you want to control the buffer contents manually or use the `cosmic-text`46/// editor, then you need to not use `TextLayout` and instead manually implement the conversion to47/// `TextLayoutInfo`.48#[reflect(ignore, clone)]49pub(crate) buffer: CosmicBuffer,50/// Entities for all text spans in the block, including the root-level text.51///52/// The [`TextEntity::depth`] field can be used to reconstruct the hierarchy.53pub(crate) entities: SmallVec<[TextEntity; 1]>,54/// Flag set when any change has been made to this block that should cause it to be rerendered.55///56/// Includes:57/// - [`TextLayout`] changes.58/// - [`TextFont`] or `Text2d`/`Text`/`TextSpan` changes anywhere in the block's entity hierarchy.59// TODO: This encompasses both structural changes like font size or justification and non-structural60// changes like text color and font smoothing. This field currently causes UI to 'remeasure' text, even if61// the actual changes are non-structural and can be handled by only rerendering and not remeasuring. A full62// solution would probably require splitting TextLayout and TextFont into structural/non-structural63// components for more granular change detection. A cost/benefit analysis is needed.64pub(crate) needs_rerender: bool,65}6667impl ComputedTextBlock {68/// Accesses entities in this block.69///70/// Can be used to look up [`TextFont`] components for glyphs in [`TextLayoutInfo`] using the `span_index`71/// stored there.72pub fn entities(&self) -> &[TextEntity] {73&self.entities74}7576/// Indicates if the text needs to be refreshed in [`TextLayoutInfo`].77///78/// Updated automatically by [`detect_text_needs_rerender`] and cleared79/// by [`TextPipeline`](crate::TextPipeline) methods.80pub fn needs_rerender(&self) -> bool {81self.needs_rerender82}83/// Accesses the underlying buffer which can be used for `cosmic-text` APIs such as accessing layout information84/// or calculating a cursor position.85///86/// Mutable access is not offered because changes would be overwritten during the automated layout calculation.87/// If you want to control the buffer contents manually or use the `cosmic-text`88/// editor, then you need to not use `TextLayout` and instead manually implement the conversion to89/// `TextLayoutInfo`.90pub fn buffer(&self) -> &CosmicBuffer {91&self.buffer92}93}9495impl Default for ComputedTextBlock {96fn default() -> Self {97Self {98buffer: CosmicBuffer::default(),99entities: SmallVec::default(),100needs_rerender: true,101}102}103}104105/// Component with text format settings for a block of text.106///107/// A block of text is composed of text spans, which each have a separate string value and [`TextFont`]. Text108/// spans associated with a text block are collected into [`ComputedTextBlock`] for layout, and then inserted109/// to [`TextLayoutInfo`] for rendering.110///111/// See `Text2d` in `bevy_sprite` for the core component of 2d text, and `Text` in `bevy_ui` for UI text.112#[derive(Component, Debug, Copy, Clone, Default, Reflect)]113#[reflect(Component, Default, Debug, Clone)]114#[require(ComputedTextBlock, TextLayoutInfo)]115pub struct TextLayout {116/// The text's internal alignment.117/// Should not affect its position within a container.118pub justify: Justify,119/// How the text should linebreak when running out of the bounds determined by `max_size`.120pub linebreak: LineBreak,121}122123impl TextLayout {124/// Makes a new [`TextLayout`].125pub const fn new(justify: Justify, linebreak: LineBreak) -> Self {126Self { justify, linebreak }127}128129/// Makes a new [`TextLayout`] with the specified [`Justify`].130pub fn new_with_justify(justify: Justify) -> Self {131Self::default().with_justify(justify)132}133134/// Makes a new [`TextLayout`] with the specified [`LineBreak`].135pub fn new_with_linebreak(linebreak: LineBreak) -> Self {136Self::default().with_linebreak(linebreak)137}138139/// Makes a new [`TextLayout`] with soft wrapping disabled.140/// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, will still occur.141pub fn new_with_no_wrap() -> Self {142Self::default().with_no_wrap()143}144145/// Returns this [`TextLayout`] with the specified [`Justify`].146pub const fn with_justify(mut self, justify: Justify) -> Self {147self.justify = justify;148self149}150151/// Returns this [`TextLayout`] with the specified [`LineBreak`].152pub const fn with_linebreak(mut self, linebreak: LineBreak) -> Self {153self.linebreak = linebreak;154self155}156157/// Returns this [`TextLayout`] with soft wrapping disabled.158/// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, will still occur.159pub const fn with_no_wrap(mut self) -> Self {160self.linebreak = LineBreak::NoWrap;161self162}163}164165/// A span of text in a tree of spans.166///167/// A `TextSpan` is only valid when it exists as a child of a parent that has either `Text` or168/// `Text2d`. The parent's `Text` / `Text2d` component contains the base text content. Any children169/// with `TextSpan` extend this text by appending their content to the parent's text in sequence to170/// form a [`ComputedTextBlock`]. The parent's [`TextLayout`] determines the layout of the block171/// but each node has its own [`TextFont`] and [`TextColor`].172#[derive(Component, Debug, Default, Clone, Deref, DerefMut, Reflect)]173#[reflect(Component, Default, Debug, Clone)]174#[require(TextFont, TextColor)]175pub struct TextSpan(pub String);176177impl TextSpan {178/// Makes a new text span component.179pub fn new(text: impl Into<String>) -> Self {180Self(text.into())181}182}183184impl TextSpanComponent for TextSpan {}185186impl TextSpanAccess for TextSpan {187fn read_span(&self) -> &str {188self.as_str()189}190fn write_span(&mut self) -> &mut String {191&mut *self192}193}194195impl From<&str> for TextSpan {196fn from(value: &str) -> Self {197Self(String::from(value))198}199}200201impl From<String> for TextSpan {202fn from(value: String) -> Self {203Self(value)204}205}206207/// Describes the horizontal alignment of multiple lines of text relative to each other.208///209/// This only affects the internal positioning of the lines of text within a text entity and210/// does not affect the text entity's position.211///212/// _Has no affect on a single line text entity_, unless used together with a213/// [`TextBounds`](super::bounds::TextBounds) component with an explicit `width` value.214#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]215#[reflect(Serialize, Deserialize, Clone, PartialEq, Hash)]216pub enum Justify {217/// Leftmost character is immediately to the right of the render position.218/// Bounds start from the render position and advance rightwards.219#[default]220Left,221/// Leftmost & rightmost characters are equidistant to the render position.222/// Bounds start from the render position and advance equally left & right.223Center,224/// Rightmost character is immediately to the left of the render position.225/// Bounds start from the render position and advance leftwards.226Right,227/// Words are spaced so that leftmost & rightmost characters228/// align with their margins.229/// Bounds start from the render position and advance equally left & right.230Justified,231}232233impl From<Justify> for cosmic_text::Align {234fn from(justify: Justify) -> Self {235match justify {236Justify::Left => cosmic_text::Align::Left,237Justify::Center => cosmic_text::Align::Center,238Justify::Right => cosmic_text::Align::Right,239Justify::Justified => cosmic_text::Align::Justified,240}241}242}243244/// `TextFont` determines the style of a text span within a [`ComputedTextBlock`], specifically245/// the font face, the font size, and the color.246#[derive(Component, Clone, Debug, Reflect, PartialEq)]247#[reflect(Component, Default, Debug, Clone)]248pub struct TextFont {249/// The specific font face to use, as a `Handle` to a [`Font`] asset.250///251/// If the `font` is not specified, then252/// * if `default_font` feature is enabled (enabled by default in `bevy` crate),253/// `FiraMono-subset.ttf` compiled into the library is used.254/// * otherwise no text will be rendered, unless a custom font is loaded into the default font255/// handle.256pub font: Handle<Font>,257/// The vertical height of rasterized glyphs in the font atlas in pixels.258///259/// This is multiplied by the window scale factor and `UiScale`, but not the text entity260/// transform or camera projection.261///262/// A new font atlas is generated for every combination of font handle and scaled font size263/// which can have a strong performance impact.264pub font_size: f32,265/// The vertical height of a line of text, from the top of one line to the top of the266/// next.267///268/// Defaults to `LineHeight::RelativeToFont(1.2)`269pub line_height: LineHeight,270/// The antialiasing method to use when rendering text.271pub font_smoothing: FontSmoothing,272}273274impl TextFont {275/// Returns a new [`TextFont`] with the specified font size.276pub fn from_font_size(font_size: f32) -> Self {277Self::default().with_font_size(font_size)278}279280/// Returns this [`TextFont`] with the specified font face handle.281pub fn with_font(mut self, font: Handle<Font>) -> Self {282self.font = font;283self284}285286/// Returns this [`TextFont`] with the specified font size.287pub const fn with_font_size(mut self, font_size: f32) -> Self {288self.font_size = font_size;289self290}291292/// Returns this [`TextFont`] with the specified [`FontSmoothing`].293pub const fn with_font_smoothing(mut self, font_smoothing: FontSmoothing) -> Self {294self.font_smoothing = font_smoothing;295self296}297298/// Returns this [`TextFont`] with the specified [`LineHeight`].299pub const fn with_line_height(mut self, line_height: LineHeight) -> Self {300self.line_height = line_height;301self302}303}304305impl From<Handle<Font>> for TextFont {306fn from(font: Handle<Font>) -> Self {307Self { font, ..default() }308}309}310311impl From<LineHeight> for TextFont {312fn from(line_height: LineHeight) -> Self {313Self {314line_height,315..default()316}317}318}319320impl Default for TextFont {321fn default() -> Self {322Self {323font: Default::default(),324font_size: 20.0,325line_height: LineHeight::default(),326font_smoothing: Default::default(),327}328}329}330331/// Specifies the height of each line of text for `Text` and `Text2d`332///333/// Default is 1.2x the font size334#[derive(Debug, Clone, Copy, PartialEq, Reflect)]335#[reflect(Debug, Clone, PartialEq)]336pub enum LineHeight {337/// Set line height to a specific number of pixels338Px(f32),339/// Set line height to a multiple of the font size340RelativeToFont(f32),341}342343impl LineHeight {344pub(crate) fn eval(self, font_size: f32) -> f32 {345match self {346LineHeight::Px(px) => px,347LineHeight::RelativeToFont(scale) => scale * font_size,348}349}350}351352impl Default for LineHeight {353fn default() -> Self {354LineHeight::RelativeToFont(1.2)355}356}357358/// The color of the text for this section.359#[derive(Component, Copy, Clone, Debug, Deref, DerefMut, Reflect, PartialEq)]360#[reflect(Component, Default, Debug, PartialEq, Clone)]361pub struct TextColor(pub Color);362363impl Default for TextColor {364fn default() -> Self {365Self::WHITE366}367}368369impl<T: Into<Color>> From<T> for TextColor {370fn from(color: T) -> Self {371Self(color.into())372}373}374375impl TextColor {376/// Black colored text377pub const BLACK: Self = TextColor(Color::BLACK);378/// White colored text379pub const WHITE: Self = TextColor(Color::WHITE);380}381382/// The background color of the text for this section.383#[derive(Component, Copy, Clone, Debug, Deref, DerefMut, Reflect, PartialEq)]384#[reflect(Component, Default, Debug, PartialEq, Clone)]385pub struct TextBackgroundColor(pub Color);386387impl Default for TextBackgroundColor {388fn default() -> Self {389Self(Color::BLACK)390}391}392393impl<T: Into<Color>> From<T> for TextBackgroundColor {394fn from(color: T) -> Self {395Self(color.into())396}397}398399impl TextBackgroundColor {400/// Black background401pub const BLACK: Self = TextBackgroundColor(Color::BLACK);402/// White background403pub const WHITE: Self = TextBackgroundColor(Color::WHITE);404}405406/// Determines how lines will be broken when preventing text from running out of bounds.407#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Reflect, Serialize, Deserialize)]408#[reflect(Serialize, Deserialize, Clone, PartialEq, Hash, Default)]409pub enum LineBreak {410/// Uses the [Unicode Line Breaking Algorithm](https://www.unicode.org/reports/tr14/).411/// Lines will be broken up at the nearest suitable word boundary, usually a space.412/// This behavior suits most cases, as it keeps words intact across linebreaks.413#[default]414WordBoundary,415/// Lines will be broken without discrimination on any character that would leave bounds.416/// This is closer to the behavior one might expect from text in a terminal.417/// However it may lead to words being broken up across linebreaks.418AnyCharacter,419/// Wraps at the word level, or fallback to character level if a word can’t fit on a line by itself420WordOrCharacter,421/// No soft wrapping, where text is automatically broken up into separate lines when it overflows a boundary, will ever occur.422/// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, is still enabled.423NoWrap,424}425426/// Determines which antialiasing method to use when rendering text. By default, text is427/// rendered with grayscale antialiasing, but this can be changed to achieve a pixelated look.428///429/// **Note:** Subpixel antialiasing is not currently supported.430#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Reflect, Serialize, Deserialize)]431#[reflect(Serialize, Deserialize, Clone, PartialEq, Hash, Default)]432#[doc(alias = "antialiasing")]433#[doc(alias = "pixelated")]434pub enum FontSmoothing {435/// No antialiasing. Useful for when you want to render text with a pixel art aesthetic.436///437/// Combine this with `UiAntiAlias::Off` and `Msaa::Off` on your 2D camera for a fully pixelated look.438///439/// **Note:** Due to limitations of the underlying text rendering library,440/// this may require specially-crafted pixel fonts to look good, especially at small sizes.441None,442/// The default grayscale antialiasing. Produces text that looks smooth,443/// even at small font sizes and low resolutions with modern vector fonts.444#[default]445AntiAliased,446// TODO: Add subpixel antialias support447// SubpixelAntiAliased,448}449450/// System that detects changes to text blocks and sets `ComputedTextBlock::should_rerender`.451///452/// Generic over the root text component and text span component. For example, `Text2d`/[`TextSpan`] for453/// 2d or `Text`/[`TextSpan`] for UI.454pub fn detect_text_needs_rerender<Root: Component>(455changed_roots: Query<456Entity,457(458Or<(459Changed<Root>,460Changed<TextFont>,461Changed<TextLayout>,462Changed<Children>,463)>,464With<Root>,465With<TextFont>,466With<TextLayout>,467),468>,469changed_spans: Query<470(Entity, Option<&ChildOf>, Has<TextLayout>),471(472Or<(473Changed<TextSpan>,474Changed<TextFont>,475Changed<Children>,476Changed<ChildOf>, // Included to detect broken text block hierarchies.477Added<TextLayout>,478)>,479With<TextSpan>,480With<TextFont>,481),482>,483mut computed: Query<(484Option<&ChildOf>,485Option<&mut ComputedTextBlock>,486Has<TextSpan>,487)>,488) {489// Root entity:490// - Root component changed.491// - TextFont on root changed.492// - TextLayout changed.493// - Root children changed (can include additions and removals).494for root in changed_roots.iter() {495let Ok((_, Some(mut computed), _)) = computed.get_mut(root) else {496once!(warn!("found entity {} with a root text component ({}) but no ComputedTextBlock; this warning only \497prints once", root, core::any::type_name::<Root>()));498continue;499};500computed.needs_rerender = true;501}502503// Span entity:504// - Span component changed.505// - Span TextFont changed.506// - Span children changed (can include additions and removals).507for (entity, maybe_span_child_of, has_text_block) in changed_spans.iter() {508if has_text_block {509once!(warn!("found entity {} with a TextSpan that has a TextLayout, which should only be on root \510text entities (that have {}); this warning only prints once",511entity, core::any::type_name::<Root>()));512}513514let Some(span_child_of) = maybe_span_child_of else {515once!(warn!(516"found entity {} with a TextSpan that has no parent; it should have an ancestor \517with a root text component ({}); this warning only prints once",518entity,519core::any::type_name::<Root>()520));521continue;522};523let mut parent: Entity = span_child_of.parent();524525// Search for the nearest ancestor with ComputedTextBlock.526// Note: We assume the perf cost from duplicate visits in the case that multiple spans in a block are visited527// is outweighed by the expense of tracking visited spans.528loop {529let Ok((maybe_child_of, maybe_computed, has_span)) = computed.get_mut(parent) else {530once!(warn!("found entity {} with a TextSpan that is part of a broken hierarchy with a ChildOf \531component that points at non-existent entity {}; this warning only prints once",532entity, parent));533break;534};535if let Some(mut computed) = maybe_computed {536computed.needs_rerender = true;537break;538}539if !has_span {540once!(warn!("found entity {} with a TextSpan that has an ancestor ({}) that does not have a text \541span component or a ComputedTextBlock component; this warning only prints once",542entity, parent));543break;544}545let Some(next_child_of) = maybe_child_of else {546once!(warn!(547"found entity {} with a TextSpan that has no ancestor with the root text \548component ({}); this warning only prints once",549entity,550core::any::type_name::<Root>()551));552break;553};554parent = next_child_of.parent();555}556}557}558559560