Skip to main content

euv_engine/asset/
impl.rs

1use super::*;
2
3/// Implements cache query and management for `AssetCache`.
4impl AssetCache {
5    /// Returns the state of the asset with the given URL, or `None` if not cached.
6    ///
7    /// # Arguments
8    ///
9    /// - `U: AsRef<str>` - The asset URL.
10    ///
11    /// # Returns
12    ///
13    /// - `Option<AssetState>` - The asset state, or `None`.
14    pub fn get_state<U>(&self, url: U) -> Option<AssetState>
15    where
16        U: AsRef<str>,
17    {
18        self.get_entries()
19            .get(url.as_ref())
20            .map(|entry: &AssetEntry| entry.get_state())
21    }
22
23    /// Returns the loaded image for the given URL, or `None` if not loaded.
24    ///
25    /// # Arguments
26    ///
27    /// - `U: AsRef<str>` - The asset URL.
28    ///
29    /// # Returns
30    ///
31    /// - `Option<HtmlImageElement>` - The loaded image, or `None`.
32    pub fn get_image<U>(&self, url: U) -> Option<HtmlImageElement>
33    where
34        U: AsRef<str>,
35    {
36        let entry: &AssetEntry = self.get_entries().get(url.as_ref())?;
37        if entry.get_state() != AssetState::Loaded {
38            return None;
39        }
40        entry.get_image()
41    }
42
43    /// Returns `true` if all assets in the cache have finished loading.
44    ///
45    /// # Returns
46    ///
47    /// - `bool` - True if no assets are in the `Loading` state.
48    pub fn is_all_loaded(&self) -> bool {
49        self.get_entries()
50            .values()
51            .all(|entry: &AssetEntry| entry.get_state() != AssetState::Loading)
52    }
53
54    /// Returns the number of assets that have been successfully loaded.
55    ///
56    /// # Returns
57    ///
58    /// - `usize` - The count of loaded assets.
59    pub fn loaded_count(&self) -> usize {
60        self.get_entries()
61            .values()
62            .filter(|entry: &&AssetEntry| entry.get_state() == AssetState::Loaded)
63            .count()
64    }
65
66    /// Removes all entries from the cache.
67    pub fn clear(&mut self) {
68        self.get_mut_entries().clear();
69    }
70}
71
72/// Implements `Default` for `AssetCache` as a new empty cache.
73impl Default for AssetCache {
74    fn default() -> AssetCache {
75        AssetCache::new()
76    }
77}
78
79/// Implements asynchronous asset loading for `AssetLoader`.
80impl AssetLoader {
81    /// Begins loading an image asset from the given URL.
82    ///
83    /// Creates an `HtmlImageElement`, sets its `src`, and registers `onload`/`onerror`
84    /// callbacks to update the shared cache state. The image loads asynchronously.
85    ///
86    /// # Arguments
87    ///
88    /// - `String` - The URL of the image to load.
89    pub fn load_image(&mut self, url: String) {
90        let image: HtmlImageElement = HtmlImageElement::new().expect("should create image element");
91        let entry: AssetEntry = AssetEntry::new(
92            AssetType::Image,
93            AssetState::Loading,
94            Some(image.clone()),
95            url.clone(),
96        );
97        self.get_cache()
98            .get_mut()
99            .get_mut_entries()
100            .insert(url.clone(), entry);
101        *self.get_mut_pending_count() += 1;
102        let cache_clone: Rc<EngineCell<AssetCache>> = self.get_cache().clone();
103        let url_for_onload: String = url.clone();
104        let url_for_onerror: String = url.clone();
105        let onload_closure: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
106            let cache_ref: &mut AssetCache = cache_clone.get_mut();
107            if let Some(mut entry) = cache_ref.get_entries().get(&url_for_onload).cloned() {
108                entry.set_state(AssetState::Loaded);
109                cache_ref
110                    .get_mut_entries()
111                    .insert(url_for_onload.clone(), entry);
112            }
113        }));
114        let cache_clone_err: Rc<EngineCell<AssetCache>> = self.get_cache().clone();
115        let onerror_closure: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
116            let cache_ref: &mut AssetCache = cache_clone_err.get_mut();
117            if let Some(mut entry) = cache_ref.get_entries().get(&url_for_onerror).cloned() {
118                entry.set_state(AssetState::Error);
119                cache_ref
120                    .get_mut_entries()
121                    .insert(url_for_onerror.clone(), entry);
122            }
123        }));
124        image.set_onload(Some(onload_closure.as_ref().unchecked_ref()));
125        image.set_onerror(Some(onerror_closure.as_ref().unchecked_ref()));
126        image.set_src(&url);
127        self.get_closures().get_mut().push(onload_closure);
128        self.get_closures().get_mut().push(onerror_closure);
129    }
130
131    /// Returns whether all requested assets have finished loading.
132    ///
133    /// # Returns
134    ///
135    /// - `bool` - True if no assets are pending.
136    pub fn is_all_loaded(&self) -> bool {
137        self.get_cache().get().is_all_loaded()
138    }
139
140    /// Returns the loaded image for the given URL.
141    ///
142    /// # Arguments
143    ///
144    /// - `U: AsRef<str>` - The asset URL.
145    ///
146    /// # Returns
147    ///
148    /// - `Option<HtmlImageElement>` - The loaded image, or `None`.
149    pub fn get_image<U>(&self, url: U) -> Option<HtmlImageElement>
150    where
151        U: AsRef<str>,
152    {
153        self.get_cache().get().get_image(url.as_ref())
154    }
155
156    /// Returns the progress ratio of loaded assets.
157    ///
158    /// # Returns
159    ///
160    /// - `f64` - The ratio in the range 0.0 to 1.0.
161    pub fn progress(&self) -> f64 {
162        let cache_ref: &AssetCache = self.get_cache().get();
163        let total: usize = cache_ref.get_entries().len();
164        if total == 0 {
165            return 1.0;
166        }
167        cache_ref.loaded_count() as f64 / total as f64
168    }
169}
170
171/// Implements `Default` for `AssetLoader` as a new empty loader.
172impl Default for AssetLoader {
173    fn default() -> AssetLoader {
174        AssetLoader::new()
175    }
176}
177
178/// Implements static asset creation utilities for `AssetLoader`.
179impl AssetLoader {
180    /// Creates an `HtmlImageElement` from the given URL without caching.
181    ///
182    /// The image loads asynchronously. Returns immediately with the image element
183    /// whose `src` is set but may not have finished loading yet.
184    ///
185    /// # Arguments
186    ///
187    /// - `U: AsRef<str>` - The image URL.
188    ///
189    /// # Returns
190    ///
191    /// - `Option<HtmlImageElement>` - The image element, or `None` if creation failed.
192    pub fn create_image_element<U>(url: U) -> Option<HtmlImageElement>
193    where
194        U: AsRef<str>,
195    {
196        let image: HtmlImageElement = HtmlImageElement::new().ok()?;
197        image.set_src(url.as_ref());
198        Some(image)
199    }
200}