Skip to main content

slint_interpreter/
static_resources.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4//! The pre-rendered textures and bitmap fonts of a design, in the form the software renderer
5//! takes them.
6
7use crate::prelude::*;
8use i_slint_common::bitmapfont::{BitmapFont, OwnedStorage};
9use i_slint_common::pre_rendered::{PreRenderedResource, StaticTextures};
10use i_slint_compiler::embedded_resources::EmbeddedResourcesIdx;
11use i_slint_core::graphics::{Image, ImageInner};
12use typed_index_collections::TiVec;
13
14#[derive(Clone)]
15enum Resource {
16    Texture(Rc<StaticTextures<OwnedStorage>>),
17    BitmapFont(Rc<BitmapFont<OwnedStorage>>),
18}
19
20impl From<PreRenderedResource> for Resource {
21    fn from(resource: PreRenderedResource) -> Self {
22        match resource {
23            PreRenderedResource::Texture(texture) => Self::Texture(Rc::new(texture)),
24            PreRenderedResource::BitmapFont(font) => Self::BitmapFont(Rc::new(font)),
25        }
26    }
27}
28
29/// This is an internal type without API stability guarantees.
30/// A pre-rendered resource of a compilation unit, in the form the renderer takes it,
31/// for [`crate::CompilationResult::from_compilation_unit()`].
32#[doc(hidden)]
33#[derive(Clone)]
34pub struct LoadedResource(Option<Resource>);
35
36impl LoadedResource {
37    /// Converts `resource`, such as one that `i_slint_compiler::llr::serialize` read.
38    /// `None` stands for a resource that the compiler didn't pre-render.
39    pub fn new(resource: Option<PreRenderedResource>, _: i_slint_core::InternalToken) -> Self {
40        Self(resource.map(Resource::from))
41    }
42}
43
44/// The pre-rendered resources that the compiled code refers to by index.
45/// The other indexes refer to files, which the interpreter loads itself.
46#[derive(Clone, Default)]
47pub struct PreRendered(TiVec<EmbeddedResourcesIdx, Option<Resource>>);
48
49impl PreRendered {
50    #[cfg(feature = "std")]
51    pub fn from_document(document: &i_slint_compiler::object_tree::Document) -> Self {
52        Self::from_sendable(i_slint_compiler::embedded_resources::pre_rendered_resources(document))
53    }
54
55    pub fn from_sendable(resources: impl IntoIterator<Item = Option<PreRenderedResource>>) -> Self {
56        Self(resources.into_iter().map(|resource| resource.map(Resource::from)).collect())
57    }
58
59    pub fn from_loaded(resources: impl IntoIterator<Item = LoadedResource>) -> Self {
60        Self(resources.into_iter().map(|resource| resource.0).collect())
61    }
62
63    pub fn into_sendable(self) -> Vec<Option<PreRenderedResource>> {
64        self.0
65            .into_iter()
66            .map(|resource| match resource? {
67                Resource::Texture(texture) => {
68                    Some(PreRenderedResource::Texture(Rc::unwrap_or_clone(texture)))
69                }
70                Resource::BitmapFont(font) => {
71                    Some(PreRenderedResource::BitmapFont(Rc::unwrap_or_clone(font)))
72                }
73            })
74            .collect()
75    }
76
77    pub fn image(&self, id: EmbeddedResourcesIdx) -> Option<Image> {
78        let Some(Resource::Texture(texture)) = self.0.get(id)? else { return None };
79        Some(Image::from(ImageInner::OwnedTextures(texture.clone())))
80    }
81
82    pub fn bitmap_font(&self, id: EmbeddedResourcesIdx) -> Option<Rc<BitmapFont<OwnedStorage>>> {
83        let Some(Resource::BitmapFont(font)) = self.0.get(id)? else { return None };
84        Some(font.clone())
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91
92    #[cfg(all(feature = "internal", feature = "internal-embed-textures", feature = "std"))]
93    #[test]
94    fn a_sent_or_loaded_design_keeps_its_fonts() {
95        use i_slint_core::InternalToken;
96        let mut compiler = crate::Compiler::default();
97        compiler.set_embed_resources(i_slint_compiler::EmbedResourcesKind::EmbedTextures);
98        let source = r#"export component Live inherits Window {
99            Text { text: "Version 1"; font-size: 32px; }
100        }"#;
101        let result =
102            spin_on::spin_on(compiler.build_from_source(source.into(), Default::default()));
103        assert!(!result.has_errors(), "{:?}", result.diagnostics().collect::<Vec<_>>());
104        let loaded = {
105            let sent = result.clone().into_send();
106            let resources = sent
107                .pre_rendered
108                .into_iter()
109                .map(|resource| LoadedResource::new(resource, InternalToken));
110            let unit = sent.compilation_unit.unwrap();
111            crate::CompilationResult::from_compilation_unit(unit, resources, InternalToken)
112        };
113        let sent = crate::CompilationResult::from(result.into_send());
114
115        for result in [sent, loaded] {
116            let definition = result.components().next().unwrap();
117            let pre_rendered = &definition.inner.resources.pre_rendered;
118            let font = (0..pre_rendered.0.len())
119                .find_map(|id| pre_rendered.bitmap_font(EmbeddedResourcesIdx(id)))
120                .unwrap();
121
122            let weak = Rc::downgrade(&font);
123            drop(font);
124            assert!(weak.upgrade().is_some());
125            drop((definition, result));
126            assert!(weak.upgrade().is_none());
127        }
128    }
129
130    #[test]
131    fn a_texture_becomes_the_whole_image() {
132        use i_slint_common::pre_rendered::{StaticTexture, TexturePixelFormat};
133        use i_slint_core::graphics::{IntRect, IntSize, Rgba8Pixel};
134        let texture = StaticTextures::<OwnedStorage> {
135            size: IntSize::new(2, 1),
136            original_size: IntSize::new(2, 1),
137            data: vec![10, 20, 30, 255],
138            textures: vec![StaticTexture {
139                rect: IntRect::new((1, 0).into(), (1, 1).into()),
140                format: TexturePixelFormat::Rgba,
141                color: 0,
142                index: 0,
143            }],
144        };
145        let pixels = PreRendered::from_sendable([Some(PreRenderedResource::Texture(texture))])
146            .image(EmbeddedResourcesIdx(0))
147            .unwrap()
148            .to_rgba8()
149            .unwrap();
150        assert_eq!(
151            pixels.as_slice(),
152            [Rgba8Pixel::new(0, 0, 0, 0), Rgba8Pixel::new(10, 20, 30, 255)]
153        );
154    }
155}