moly_kit/utils/
makepad.rs

1//! Utilities to deal with stuff that is highly specific to Makepad.
2
3pub mod events;
4pub mod hits;
5pub mod portal_list;
6pub mod ui_runner;
7
8use makepad_widgets::*;
9use std::path::Path;
10use std::sync::Arc;
11
12/// Convert from hex color notation to makepad's Vec4 color.
13/// Ex: Converts `0xff33cc` into `vec4(1.0, 0.2, 0.8, 1.0)`.
14pub fn hex_rgb_color(hex: u32) -> Vec4 {
15    let r = ((hex >> 16) & 0xFF) as f32 / 255.0;
16    let g = ((hex >> 8) & 0xFF) as f32 / 255.0;
17    let b = (hex & 0xFF) as f32 / 255.0;
18    vec4(r, g, b, 1.0)
19}
20
21/// Loads an image into an [`ImageRef`] from a resource registered via
22/// `crate_resource()`.
23///
24/// `abs_path` is the absolute filesystem path stored as the resource's
25/// `abs_path` when it was registered with the script resource system.
26/// The function looks up the corresponding [`ScriptHandle`], ensures
27/// the resource data is loaded, and feeds the bytes to the image
28/// widget's async decoder.
29///
30/// Returns `Ok(())` if the image was decoded or if the resource data
31/// is not yet available (e.g. pending HTTP fetch on web) — the caller
32/// should retry on the next draw pass, matching the behavior of
33/// Makepad's built-in [`Image`] widget.
34///
35/// # Errors
36///
37/// Returns [`ImageError::PathNotFound`] if no script resource matches
38/// `abs_path`.
39pub fn load_image_from_resource(
40    image: &ImageRef,
41    cx: &mut Cx,
42    abs_path: &str,
43) -> Result<(), ImageError> {
44    let handle = cx
45        .script_data
46        .resources
47        .get_handle_by_abs_path(abs_path)
48        .ok_or_else(|| ImageError::PathNotFound(abs_path.into()))?;
49    cx.load_script_resource(handle);
50    let Some(data) = cx.get_resource(handle) else {
51        return Ok(());
52    };
53    let path = Path::new(abs_path);
54    let data = Arc::new((*data).clone());
55    image.load_image_from_data_async(cx, path, data)
56}