Skip to main content

ferroui_base/media/text_formatting/
text_shaper.rs

1use std::rc::Rc;
2
3use crate::media::text_formatting::{ShapedBuffer, TextShaperOptions};
4use crate::platform::ITextShaperImpl;
5use crate::{FerroLocator, LocatorExtensions};
6use crate::utilities::ReadOnlyMemory;
7
8/// A class that is responsible for text shaping.
9pub struct TextShaper {
10    platform_impl: Rc<dyn ITextShaperImpl>,
11}
12
13impl TextShaper {
14    pub fn new(platform_impl: Rc<dyn ITextShaperImpl>) -> Self {
15        Self { platform_impl }
16    }
17
18    /// Gets the current text shaper.
19    ///
20    /// Panics when no text shaper backend is registered.
21    pub fn current() -> Rc<TextShaper> {
22        if let Some(current) = FerroLocator::current().get_service::<TextShaper>() {
23            return current;
24        }
25
26        let text_shaper_impl = FerroLocator::current().get_required_service::<dyn ITextShaperImpl>();
27
28        let current = Rc::new(TextShaper::new(text_shaper_impl));
29
30        FerroLocator::current_mutable().bind::<TextShaper>().to_constant(current.clone());
31
32        current
33    }
34
35    /// Shapes UTF-16 text.
36    pub fn shape_text(&self, text: &ReadOnlyMemory<u16>, options: &TextShaperOptions) -> Rc<ShapedBuffer> {
37        crate::perf_count!(TextRunsShaped);
38        self.platform_impl.shape_text(text, options)
39    }
40
41    /// Shapes a string.
42    pub fn shape_str(&self, text: &str, options: &TextShaperOptions) -> Rc<ShapedBuffer> {
43        self.shape_text(&ReadOnlyMemory::<u16>::from_str(text), options)
44    }
45}