Skip to main content

pretty_text/
access.rs

1//! Provides a [system param](SystemParam) for retrieving the text data pointed
2//! to by [`Glyph`] entities.
3
4use bevy::ecs::system::SystemParam;
5use bevy::prelude::*;
6use bevy::text::ComputedTextBlock;
7
8use crate::glyph::{Glyph, GlyphOf};
9
10/// Utility for reading the text data pointed to by a [`Glyph`] entity.
11#[derive(Debug, SystemParam)]
12pub struct GlyphReader<'w, 's> {
13    computed: Query<'w, 's, &'static ComputedTextBlock>,
14    glyphs: Query<'w, 's, (&'static Glyph, &'static GlyphOf)>,
15}
16
17impl<'w, 's> GlyphReader<'w, 's> {
18    /// Retrieve the text data pointed to by a `glyph`.
19    pub fn read(&self, glyph: Entity) -> Result<&str> {
20        Ok(self.glyphs.get(glyph).map(|(glyph, glyph_of)| {
21            self.computed.get(glyph_of.root()).map(|computed| {
22                let text = &computed.buffer().lines[glyph.0.line_index].text();
23                &text[glyph.0.byte_index..glyph.0.byte_index + glyph.0.byte_length]
24            })
25        })??)
26    }
27}
28
29#[cfg(test)]
30mod test {
31    // This test currently fails for wide glyphs due to an upstream issue.
32
33    // use bevy::prelude::*;
34    //
35    // use crate::glyph::Glyphs;
36    // use crate::test::{prepare_app, run, run_tests};
37    //
38    // use super::GlyphReader;
39    //
40    // #[test]
41    // fn glyph_reader() {
42    //     run_tests(prepare_app, |app, _, str| {
43    //         app.world_mut().run_schedule(PostUpdate);
44    //         app.world_mut().flush();
45    //         run(app, move |reader: GlyphReader, root: Single<&Glyphs>| {
46    //             let repro = root
47    //                 .iter()
48    //                 .map(|glyph| reader.read(glyph).unwrap())
49    //                 .collect::<String>();
50    //
51    //             assert_eq!(
52    //                 repro.chars().count(),
53    //                 str.chars().count(),
54    //                 "failed with: \"{}\", read as \"{}\"",
55    //                 str,
56    //                 repro
57    //             );
58    //         });
59    //     });
60    // }
61}