
# Objective **This implementation is based on https://github.com/bevyengine/rfcs/pull/59.** --- Resolves #4597 Full details and motivation can be found in the RFC, but here's a brief summary. `FromReflect` is a very powerful and important trait within the reflection API. It allows Dynamic types (e.g., `DynamicList`, etc.) to be formed into Real ones (e.g., `Vec<i32>`, etc.). This mainly comes into play concerning deserialization, where the reflection deserializers both return a `Box<dyn Reflect>` that almost always contain one of these Dynamic representations of a Real type. To convert this to our Real type, we need to use `FromReflect`. It also sneaks up in other ways. For example, it's a required bound for `T` in `Vec<T>` so that `Vec<T>` as a whole can be made `FromReflect`. It's also required by all fields of an enum as it's used as part of the `Reflect::apply` implementation. So in other words, much like `GetTypeRegistration` and `Typed`, it is very much a core reflection trait. The problem is that it is not currently treated like a core trait and is not automatically derived alongside `Reflect`. This makes using it a bit cumbersome and easy to forget. ## Solution Automatically derive `FromReflect` when deriving `Reflect`. Users can then choose to opt-out if needed using the `#[reflect(from_reflect = false)]` attribute. ```rust #[derive(Reflect)] struct Foo; #[derive(Reflect)] #[reflect(from_reflect = false)] struct Bar; fn test<T: FromReflect>(value: T) {} test(Foo); // <-- OK test(Bar); // <-- Panic! Bar does not implement trait `FromReflect` ``` #### `ReflectFromReflect` This PR also automatically adds the `ReflectFromReflect` (introduced in #6245) registration to the derived `GetTypeRegistration` impl— if the type hasn't opted out of `FromReflect` of course. <details> <summary><h4>Improved Deserialization</h4></summary> > **Warning** > This section includes changes that have since been descoped from this PR. They will likely be implemented again in a followup PR. I am mainly leaving these details in for archival purposes, as well as for reference when implementing this logic again. And since we can do all the above, we might as well improve deserialization. We can now choose to deserialize into a Dynamic type or automatically convert it using `FromReflect` under the hood. `[Un]TypedReflectDeserializer::new` will now perform the conversion and return the `Box`'d Real type. `[Un]TypedReflectDeserializer::new_dynamic` will work like what we have now and simply return the `Box`'d Dynamic type. ```rust // Returns the Real type let reflect_deserializer = UntypedReflectDeserializer::new(®istry); let mut deserializer = ron:🇩🇪:Deserializer::from_str(input)?; let output: SomeStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?; // Returns the Dynamic type let reflect_deserializer = UntypedReflectDeserializer::new_dynamic(®istry); let mut deserializer = ron:🇩🇪:Deserializer::from_str(input)?; let output: DynamicStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?; ``` </details> --- ## Changelog * `FromReflect` is now automatically derived within the `Reflect` derive macro * This includes auto-registering `ReflectFromReflect` in the derived `GetTypeRegistration` impl * ~~Renamed `TypedReflectDeserializer::new` and `UntypedReflectDeserializer::new` to `TypedReflectDeserializer::new_dynamic` and `UntypedReflectDeserializer::new_dynamic`, respectively~~ **Descoped** * ~~Changed `TypedReflectDeserializer::new` and `UntypedReflectDeserializer::new` to automatically convert the deserialized output using `FromReflect`~~ **Descoped** ## Migration Guide * `FromReflect` is now automatically derived within the `Reflect` derive macro. Items with both derives will need to remove the `FromReflect` one. ```rust // OLD #[derive(Reflect, FromReflect)] struct Foo; // NEW #[derive(Reflect)] struct Foo; ``` If using a manual implementation of `FromReflect` and the `Reflect` derive, users will need to opt-out of the automatic implementation. ```rust // OLD #[derive(Reflect)] struct Foo; impl FromReflect for Foo {/* ... */} // NEW #[derive(Reflect)] #[reflect(from_reflect = false)] struct Foo; impl FromReflect for Foo {/* ... */} ``` <details> <summary><h4>Removed Migrations</h4></summary> > **Warning** > This section includes changes that have since been descoped from this PR. They will likely be implemented again in a followup PR. I am mainly leaving these details in for archival purposes, as well as for reference when implementing this logic again. * The reflect deserializers now perform a `FromReflect` conversion internally. The expected output of `TypedReflectDeserializer::new` and `UntypedReflectDeserializer::new` is no longer a Dynamic (e.g., `DynamicList`), but its Real counterpart (e.g., `Vec<i32>`). ```rust let reflect_deserializer = UntypedReflectDeserializer::new_dynamic(®istry); let mut deserializer = ron:🇩🇪:Deserializer::from_str(input)?; // OLD let output: DynamicStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?; // NEW let output: SomeStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?; ``` Alternatively, if this behavior isn't desired, use the `TypedReflectDeserializer::new_dynamic` and `UntypedReflectDeserializer::new_dynamic` methods instead: ```rust // OLD let reflect_deserializer = UntypedReflectDeserializer::new(®istry); // NEW let reflect_deserializer = UntypedReflectDeserializer::new_dynamic(®istry); ``` </details> --------- Co-authored-by: Carter Anderson <mcanders1@gmail.com>
213 lines
7.1 KiB
Rust
213 lines
7.1 KiB
Rust
use bevy_asset::Handle;
|
|
use bevy_ecs::{prelude::Component, reflect::ReflectComponent};
|
|
use bevy_reflect::prelude::*;
|
|
use bevy_render::color::Color;
|
|
use bevy_utils::default;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::{Font, DEFAULT_FONT_HANDLE};
|
|
|
|
#[derive(Component, Debug, Clone, Reflect)]
|
|
#[reflect(Component, Default)]
|
|
pub struct Text {
|
|
pub sections: Vec<TextSection>,
|
|
/// The text's internal alignment.
|
|
/// Should not affect its position within a container.
|
|
pub alignment: TextAlignment,
|
|
/// How the text should linebreak when running out of the bounds determined by max_size
|
|
pub linebreak_behavior: BreakLineOn,
|
|
}
|
|
|
|
impl Default for Text {
|
|
fn default() -> Self {
|
|
Self {
|
|
sections: Default::default(),
|
|
alignment: TextAlignment::Left,
|
|
linebreak_behavior: BreakLineOn::WordBoundary,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Text {
|
|
/// Constructs a [`Text`] with a single section.
|
|
///
|
|
/// ```
|
|
/// # use bevy_asset::Handle;
|
|
/// # use bevy_render::color::Color;
|
|
/// # use bevy_text::{Font, Text, TextStyle, TextAlignment};
|
|
/// #
|
|
/// # let font_handle: Handle<Font> = Default::default();
|
|
/// #
|
|
/// // Basic usage.
|
|
/// let hello_world = Text::from_section(
|
|
/// // Accepts a String or any type that converts into a String, such as &str.
|
|
/// "hello world!",
|
|
/// TextStyle {
|
|
/// font: font_handle.clone(),
|
|
/// font_size: 60.0,
|
|
/// color: Color::WHITE,
|
|
/// },
|
|
/// );
|
|
///
|
|
/// let hello_bevy = Text::from_section(
|
|
/// "hello bevy!",
|
|
/// TextStyle {
|
|
/// font: font_handle,
|
|
/// font_size: 60.0,
|
|
/// color: Color::WHITE,
|
|
/// },
|
|
/// ) // You can still add an alignment.
|
|
/// .with_alignment(TextAlignment::Center);
|
|
/// ```
|
|
pub fn from_section(value: impl Into<String>, style: TextStyle) -> Self {
|
|
Self {
|
|
sections: vec![TextSection::new(value, style)],
|
|
..default()
|
|
}
|
|
}
|
|
|
|
/// Constructs a [`Text`] from a list of sections.
|
|
///
|
|
/// ```
|
|
/// # use bevy_asset::Handle;
|
|
/// # use bevy_render::color::Color;
|
|
/// # use bevy_text::{Font, Text, TextStyle, TextSection};
|
|
/// #
|
|
/// # let font_handle: Handle<Font> = Default::default();
|
|
/// #
|
|
/// let hello_world = Text::from_sections([
|
|
/// TextSection::new(
|
|
/// "Hello, ",
|
|
/// TextStyle {
|
|
/// font: font_handle.clone(),
|
|
/// font_size: 60.0,
|
|
/// color: Color::BLUE,
|
|
/// },
|
|
/// ),
|
|
/// TextSection::new(
|
|
/// "World!",
|
|
/// TextStyle {
|
|
/// font: font_handle,
|
|
/// font_size: 60.0,
|
|
/// color: Color::RED,
|
|
/// },
|
|
/// ),
|
|
/// ]);
|
|
/// ```
|
|
pub fn from_sections(sections: impl IntoIterator<Item = TextSection>) -> Self {
|
|
Self {
|
|
sections: sections.into_iter().collect(),
|
|
..default()
|
|
}
|
|
}
|
|
|
|
/// Returns this [`Text`] with a new [`TextAlignment`].
|
|
pub const fn with_alignment(mut self, alignment: TextAlignment) -> Self {
|
|
self.alignment = alignment;
|
|
self
|
|
}
|
|
|
|
/// Returns this [`Text`] with soft wrapping disabled.
|
|
/// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, will still occur.
|
|
pub const fn with_no_wrap(mut self) -> Self {
|
|
self.linebreak_behavior = BreakLineOn::NoWrap;
|
|
self
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Default, Clone, Reflect)]
|
|
pub struct TextSection {
|
|
pub value: String,
|
|
pub style: TextStyle,
|
|
}
|
|
|
|
impl TextSection {
|
|
/// Create a new [`TextSection`].
|
|
pub fn new(value: impl Into<String>, style: TextStyle) -> Self {
|
|
Self {
|
|
value: value.into(),
|
|
style,
|
|
}
|
|
}
|
|
|
|
/// Create an empty [`TextSection`] from a style. Useful when the value will be set dynamically.
|
|
pub const fn from_style(style: TextStyle) -> Self {
|
|
Self {
|
|
value: String::new(),
|
|
style,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Describes horizontal alignment preference for positioning & bounds.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
|
|
#[reflect(Serialize, Deserialize)]
|
|
pub enum TextAlignment {
|
|
/// Leftmost character is immediately to the right of the render position.<br/>
|
|
/// Bounds start from the render position and advance rightwards.
|
|
Left,
|
|
/// Leftmost & rightmost characters are equidistant to the render position.<br/>
|
|
/// Bounds start from the render position and advance equally left & right.
|
|
Center,
|
|
/// Rightmost character is immediately to the left of the render position.<br/>
|
|
/// Bounds start from the render position and advance leftwards.
|
|
Right,
|
|
}
|
|
|
|
impl From<TextAlignment> for glyph_brush_layout::HorizontalAlign {
|
|
fn from(val: TextAlignment) -> Self {
|
|
match val {
|
|
TextAlignment::Left => glyph_brush_layout::HorizontalAlign::Left,
|
|
TextAlignment::Center => glyph_brush_layout::HorizontalAlign::Center,
|
|
TextAlignment::Right => glyph_brush_layout::HorizontalAlign::Right,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, Reflect)]
|
|
pub struct TextStyle {
|
|
pub font: Handle<Font>,
|
|
pub font_size: f32,
|
|
pub color: Color,
|
|
}
|
|
|
|
impl Default for TextStyle {
|
|
fn default() -> Self {
|
|
Self {
|
|
font: DEFAULT_FONT_HANDLE.typed(),
|
|
font_size: 12.0,
|
|
color: Color::WHITE,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Determines how lines will be broken when preventing text from running out of bounds.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
|
|
#[reflect(Serialize, Deserialize)]
|
|
pub enum BreakLineOn {
|
|
/// Uses the [Unicode Line Breaking Algorithm](https://www.unicode.org/reports/tr14/).
|
|
/// Lines will be broken up at the nearest suitable word boundary, usually a space.
|
|
/// This behavior suits most cases, as it keeps words intact across linebreaks.
|
|
WordBoundary,
|
|
/// Lines will be broken without discrimination on any character that would leave bounds.
|
|
/// This is closer to the behavior one might expect from text in a terminal.
|
|
/// However it may lead to words being broken up across linebreaks.
|
|
AnyCharacter,
|
|
/// No soft wrapping, where text is automatically broken up into separate lines when it overflows a boundary, will ever occur.
|
|
/// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, is still enabled.
|
|
NoWrap,
|
|
}
|
|
|
|
impl From<BreakLineOn> for glyph_brush_layout::BuiltInLineBreaker {
|
|
fn from(val: BreakLineOn) -> Self {
|
|
match val {
|
|
// If `NoWrap` is set the choice of `BuiltInLineBreaker` doesn't matter as the text is given unbounded width and soft wrapping will never occur.
|
|
// But `NoWrap` does not disable hard breaks where a [`Text`] contains a newline character.
|
|
BreakLineOn::WordBoundary | BreakLineOn::NoWrap => {
|
|
glyph_brush_layout::BuiltInLineBreaker::UnicodeLineBreaker
|
|
}
|
|
BreakLineOn::AnyCharacter => glyph_brush_layout::BuiltInLineBreaker::AnyCharLineBreaker,
|
|
}
|
|
}
|
|
}
|