1use crate::lengths::{PhysicalPx, ScaleFactor};
9use crate::slice::Slice;
10#[allow(unused)]
11use crate::{SharedString, SharedVector};
12
13use super::{IntRect, IntSize};
14use crate::items::{ImageFit, ImageHorizontalAlignment, ImageTiling, ImageVerticalAlignment};
15
16#[cfg(feature = "image-decoders")]
17pub mod cache;
18#[cfg(target_arch = "wasm32")]
19mod htmlimage;
20#[cfg(feature = "svg")]
21mod svg;
22
23#[allow(missing_docs)]
24#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
25#[vtable::vtable]
26#[repr(C)]
27pub struct OpaqueImageVTable {
28 drop_in_place: extern "C" fn(VRefMut<OpaqueImageVTable>) -> Layout,
29 dealloc: extern "C" fn(&OpaqueImageVTable, ptr: *mut u8, layout: Layout),
30 size: extern "C" fn(VRef<OpaqueImageVTable>) -> IntSize,
32 cache_key: extern "C" fn(VRef<OpaqueImageVTable>) -> ImageCacheKey,
34}
35
36#[cfg(feature = "svg")]
37OpaqueImageVTable_static! {
38 pub static PARSED_SVG_VT for svg::ParsedSVG
40}
41
42#[cfg(target_arch = "wasm32")]
43OpaqueImageVTable_static! {
44 pub static HTML_IMAGE_VT for htmlimage::HTMLImage
46}
47
48OpaqueImageVTable_static! {
49 pub static NINE_SLICE_VT for NineSliceImage
51}
52
53#[derive(Debug, Clone)]
63#[repr(C)]
64pub struct SharedPixelBuffer<Pixel> {
65 width: u32,
66 height: u32,
67 pub(crate) data: SharedVector<Pixel>,
68}
69
70impl<Pixel> SharedPixelBuffer<Pixel> {
71 pub fn width(&self) -> u32 {
73 self.width
74 }
75
76 pub fn height(&self) -> u32 {
78 self.height
79 }
80
81 pub fn size(&self) -> IntSize {
83 [self.width, self.height].into()
84 }
85}
86
87impl<Pixel: Clone> SharedPixelBuffer<Pixel> {
88 pub fn make_mut_slice(&mut self) -> &mut [Pixel] {
90 self.data.make_mut_slice()
91 }
92}
93
94impl<Pixel: Clone + rgb::Pod> SharedPixelBuffer<Pixel>
95where
96 [Pixel]: rgb::ComponentBytes<u8>,
97{
98 pub fn as_bytes(&self) -> &[u8] {
100 use rgb::ComponentBytes;
101 self.data.as_slice().as_bytes()
102 }
103
104 pub fn make_mut_bytes(&mut self) -> &mut [u8] {
106 use rgb::ComponentBytes;
107 self.data.make_mut_slice().as_bytes_mut()
108 }
109}
110
111impl<Pixel> SharedPixelBuffer<Pixel> {
112 pub fn as_slice(&self) -> &[Pixel] {
114 self.data.as_slice()
115 }
116}
117
118impl<Pixel: Clone + Default> SharedPixelBuffer<Pixel> {
119 pub fn new(width: u32, height: u32) -> Self {
122 Self {
123 width,
124 height,
125 data: core::iter::repeat(Pixel::default())
126 .take(width as usize * height as usize)
127 .collect(),
128 }
129 }
130}
131
132impl<Pixel: Clone> SharedPixelBuffer<Pixel> {
133 pub fn clone_from_slice<SourcePixelType>(
137 pixel_slice: &[SourcePixelType],
138 width: u32,
139 height: u32,
140 ) -> Self
141 where
142 [SourcePixelType]: rgb::AsPixels<Pixel>,
143 {
144 use rgb::AsPixels;
145 Self { width, height, data: pixel_slice.as_pixels().into() }
146 }
147}
148
149pub type Rgb8Pixel = rgb::RGB8;
152pub type Rgba8Pixel = rgb::RGBA8;
155
156#[derive(Clone, Debug)]
161#[repr(C)]
162pub enum SharedImageBuffer {
164 RGB8(SharedPixelBuffer<Rgb8Pixel>),
167 RGBA8(SharedPixelBuffer<Rgba8Pixel>),
170 RGBA8Premultiplied(SharedPixelBuffer<Rgba8Pixel>),
177}
178
179impl SharedImageBuffer {
180 #[inline]
182 pub fn width(&self) -> u32 {
183 match self {
184 Self::RGB8(buffer) => buffer.width(),
185 Self::RGBA8(buffer) => buffer.width(),
186 Self::RGBA8Premultiplied(buffer) => buffer.width(),
187 }
188 }
189
190 #[inline]
192 pub fn height(&self) -> u32 {
193 match self {
194 Self::RGB8(buffer) => buffer.height(),
195 Self::RGBA8(buffer) => buffer.height(),
196 Self::RGBA8Premultiplied(buffer) => buffer.height(),
197 }
198 }
199
200 #[inline]
202 pub fn size(&self) -> IntSize {
203 match self {
204 Self::RGB8(buffer) => buffer.size(),
205 Self::RGBA8(buffer) => buffer.size(),
206 Self::RGBA8Premultiplied(buffer) => buffer.size(),
207 }
208 }
209}
210
211impl PartialEq for SharedImageBuffer {
212 fn eq(&self, other: &Self) -> bool {
213 match self {
214 Self::RGB8(lhs_buffer) => {
215 matches!(other, Self::RGB8(rhs_buffer) if lhs_buffer.data.as_ptr().eq(&rhs_buffer.data.as_ptr()))
216 }
217 Self::RGBA8(lhs_buffer) => {
218 matches!(other, Self::RGBA8(rhs_buffer) if lhs_buffer.data.as_ptr().eq(&rhs_buffer.data.as_ptr()))
219 }
220 Self::RGBA8Premultiplied(lhs_buffer) => {
221 matches!(other, Self::RGBA8Premultiplied(rhs_buffer) if lhs_buffer.data.as_ptr().eq(&rhs_buffer.data.as_ptr()))
222 }
223 }
224 }
225}
226
227#[repr(u8)]
228#[derive(Clone, PartialEq, Debug, Copy)]
229pub enum TexturePixelFormat {
231 Rgb,
233 Rgba,
235 RgbaPremultiplied,
237 AlphaMap,
239 SignedDistanceField,
244}
245
246impl TexturePixelFormat {
247 pub fn bpp(self) -> usize {
249 match self {
250 TexturePixelFormat::Rgb => 3,
251 TexturePixelFormat::Rgba => 4,
252 TexturePixelFormat::RgbaPremultiplied => 4,
253 TexturePixelFormat::AlphaMap => 1,
254 TexturePixelFormat::SignedDistanceField => 1,
255 }
256 }
257}
258
259#[repr(C)]
260#[derive(Clone, PartialEq, Debug)]
261pub struct StaticTexture {
263 pub rect: IntRect,
265 pub format: TexturePixelFormat,
267 pub color: crate::Color,
269 pub index: usize,
271}
272
273#[repr(C)]
275#[derive(Clone, PartialEq, Debug)]
276pub struct StaticTextures {
277 pub size: IntSize,
280 pub original_size: IntSize,
282 pub data: Slice<'static, u8>,
284 pub textures: Slice<'static, StaticTexture>,
286}
287
288#[derive(PartialEq, Eq, Debug, Hash, Clone)]
291#[repr(C)]
292#[cfg(feature = "std")]
293pub struct CachedPath {
294 path: SharedString,
295 last_modified: u32,
297}
298
299#[cfg(feature = "std")]
300impl CachedPath {
301 fn new<P: AsRef<std::path::Path>>(path: P) -> Self {
302 let path_str = path.as_ref().to_string_lossy().as_ref().into();
303 let timestamp = std::fs::metadata(path)
304 .and_then(|md| md.modified())
305 .unwrap_or(std::time::UNIX_EPOCH)
306 .duration_since(std::time::UNIX_EPOCH)
307 .map(|t| t.as_secs() as u32)
308 .unwrap_or_default();
309 Self { path: path_str, last_modified: timestamp }
310 }
311}
312
313#[derive(PartialEq, Eq, Debug, Hash, Clone)]
316#[repr(u8)]
317pub enum ImageCacheKey {
318 Invalid = 0,
321 #[cfg(feature = "std")]
322 Path(CachedPath) = 1,
324 #[cfg(target_arch = "wasm32")]
326 URL(SharedString) = 2,
327 EmbeddedData(usize) = 3,
329}
330
331impl ImageCacheKey {
332 pub fn new(resource: &ImageInner) -> Option<Self> {
335 let key = match resource {
336 ImageInner::None => return None,
337 ImageInner::EmbeddedImage { cache_key, .. } => cache_key.clone(),
338 ImageInner::StaticTextures(textures) => {
339 Self::from_embedded_image_data(textures.data.as_slice())
340 }
341 #[cfg(feature = "svg")]
342 ImageInner::Svg(parsed_svg) => parsed_svg.cache_key(),
343 #[cfg(target_arch = "wasm32")]
344 ImageInner::HTMLImage(htmlimage) => Self::URL(htmlimage.source().into()),
345 ImageInner::BackendStorage(x) => vtable::VRc::borrow(x).cache_key(),
346 #[cfg(not(target_arch = "wasm32"))]
347 ImageInner::BorrowedOpenGLTexture(..) => return None,
348 ImageInner::NineSlice(nine) => vtable::VRc::borrow(nine).cache_key(),
349 #[cfg(feature = "unstable-wgpu-26")]
350 ImageInner::WGPUTexture(..) => return None,
351 };
352 if matches!(key, ImageCacheKey::Invalid) {
353 None
354 } else {
355 Some(key)
356 }
357 }
358
359 pub fn from_embedded_image_data(data: &'static [u8]) -> Self {
361 Self::EmbeddedData(data.as_ptr() as usize)
362 }
363}
364
365pub struct NineSliceImage(pub ImageInner, pub [u16; 4]);
367
368impl NineSliceImage {
369 pub fn image(&self) -> Image {
371 Image(self.0.clone())
372 }
373}
374
375impl OpaqueImage for NineSliceImage {
376 fn size(&self) -> IntSize {
377 self.0.size()
378 }
379 fn cache_key(&self) -> ImageCacheKey {
380 ImageCacheKey::new(&self.0).unwrap_or(ImageCacheKey::Invalid)
381 }
382}
383
384#[cfg(feature = "unstable-wgpu-26")]
386#[derive(Clone, Debug)]
387pub enum WGPUTexture {
388 #[cfg(feature = "unstable-wgpu-26")]
390 WGPU26Texture(wgpu_26::Texture),
391}
392
393#[cfg(feature = "unstable-wgpu-26")]
394impl OpaqueImage for WGPUTexture {
395 fn size(&self) -> IntSize {
396 match self {
397 Self::WGPU26Texture(texture) => {
398 let size = texture.size();
399 (size.width, size.height).into()
400 }
401 }
402 }
403 fn cache_key(&self) -> ImageCacheKey {
404 ImageCacheKey::Invalid
405 }
406}
407
408#[derive(Clone, Debug, Default)]
413#[repr(u8)]
414#[allow(missing_docs)]
415pub enum ImageInner {
416 #[default]
418 None = 0,
419 EmbeddedImage {
420 cache_key: ImageCacheKey,
421 buffer: SharedImageBuffer,
422 } = 1,
423 #[cfg(feature = "svg")]
424 Svg(vtable::VRc<OpaqueImageVTable, svg::ParsedSVG>) = 2,
425 StaticTextures(&'static StaticTextures) = 3,
426 #[cfg(target_arch = "wasm32")]
427 HTMLImage(vtable::VRc<OpaqueImageVTable, htmlimage::HTMLImage>) = 4,
428 BackendStorage(vtable::VRc<OpaqueImageVTable>) = 5,
429 #[cfg(not(target_arch = "wasm32"))]
430 BorrowedOpenGLTexture(BorrowedOpenGLTexture) = 6,
431 NineSlice(vtable::VRc<OpaqueImageVTable, NineSliceImage>) = 7,
432 #[cfg(feature = "unstable-wgpu-26")]
433 WGPUTexture(WGPUTexture) = 8,
434}
435
436impl ImageInner {
437 pub fn render_to_buffer(
444 &self,
445 _target_size_for_scalable_source: Option<euclid::Size2D<u32, PhysicalPx>>,
446 ) -> Option<SharedImageBuffer> {
447 match self {
448 ImageInner::EmbeddedImage { buffer, .. } => Some(buffer.clone()),
449 #[cfg(feature = "svg")]
450 ImageInner::Svg(svg) => match svg.render(_target_size_for_scalable_source) {
451 Ok(b) => Some(b),
452 Err(resvg::usvg::Error::InvalidSize) => None,
454 Err(err) => {
455 std::eprintln!("Error rendering SVG: {err}");
456 None
457 }
458 },
459 ImageInner::StaticTextures(ts) => {
460 let mut buffer =
461 SharedPixelBuffer::<Rgba8Pixel>::new(ts.size.width, ts.size.height);
462 let stride = buffer.width() as usize;
463 let slice = buffer.make_mut_slice();
464 for t in ts.textures.iter() {
465 let rect = t.rect.to_usize();
466 for y in 0..rect.height() {
467 let slice = &mut slice[(rect.min_y() + y) * stride..][rect.x_range()];
468 let source = &ts.data[t.index + y * rect.width() * t.format.bpp()..];
469 match t.format {
470 TexturePixelFormat::Rgb => {
471 let mut iter = source.chunks_exact(3).map(|p| Rgba8Pixel {
472 r: p[0],
473 g: p[1],
474 b: p[2],
475 a: 255,
476 });
477 slice.fill_with(|| iter.next().unwrap());
478 }
479 TexturePixelFormat::RgbaPremultiplied => {
480 let mut iter = source.chunks_exact(4).map(|p| Rgba8Pixel {
481 r: p[0],
482 g: p[1],
483 b: p[2],
484 a: p[3],
485 });
486 slice.fill_with(|| iter.next().unwrap());
487 }
488 TexturePixelFormat::Rgba => {
489 let mut iter = source.chunks_exact(4).map(|p| {
490 let a = p[3];
491 Rgba8Pixel {
492 r: (p[0] as u16 * a as u16 / 255) as u8,
493 g: (p[1] as u16 * a as u16 / 255) as u8,
494 b: (p[2] as u16 * a as u16 / 255) as u8,
495 a,
496 }
497 });
498 slice.fill_with(|| iter.next().unwrap());
499 }
500 TexturePixelFormat::AlphaMap => {
501 let col = t.color.to_argb_u8();
502 let mut iter = source.iter().map(|p| {
503 let a = *p as u32 * col.alpha as u32;
504 Rgba8Pixel {
505 r: (col.red as u32 * a / (255 * 255)) as u8,
506 g: (col.green as u32 * a / (255 * 255)) as u8,
507 b: (col.blue as u32 * a / (255 * 255)) as u8,
508 a: (a / 255) as u8,
509 }
510 });
511 slice.fill_with(|| iter.next().unwrap());
512 }
513 TexturePixelFormat::SignedDistanceField => {
514 todo!("converting from a signed distance field to an image")
515 }
516 };
517 }
518 }
519 Some(SharedImageBuffer::RGBA8Premultiplied(buffer))
520 }
521 ImageInner::NineSlice(nine) => nine.0.render_to_buffer(None),
522 _ => None,
523 }
524 }
525
526 pub fn is_svg(&self) -> bool {
528 match self {
529 #[cfg(feature = "svg")]
530 Self::Svg(_) => true,
531 #[cfg(target_arch = "wasm32")]
532 Self::HTMLImage(html_image) => html_image.is_svg(),
533 _ => false,
534 }
535 }
536
537 pub fn size(&self) -> IntSize {
539 match self {
540 ImageInner::None => Default::default(),
541 ImageInner::EmbeddedImage { buffer, .. } => buffer.size(),
542 ImageInner::StaticTextures(StaticTextures { original_size, .. }) => *original_size,
543 #[cfg(feature = "svg")]
544 ImageInner::Svg(svg) => svg.size(),
545 #[cfg(target_arch = "wasm32")]
546 ImageInner::HTMLImage(htmlimage) => htmlimage.size().unwrap_or_default(),
547 ImageInner::BackendStorage(x) => vtable::VRc::borrow(x).size(),
548 #[cfg(not(target_arch = "wasm32"))]
549 ImageInner::BorrowedOpenGLTexture(BorrowedOpenGLTexture { size, .. }) => *size,
550 ImageInner::NineSlice(nine) => nine.0.size(),
551 #[cfg(feature = "unstable-wgpu-26")]
552 ImageInner::WGPUTexture(texture) => texture.size(),
553 }
554 }
555}
556
557impl PartialEq for ImageInner {
558 fn eq(&self, other: &Self) -> bool {
559 match (self, other) {
560 (
561 Self::EmbeddedImage { cache_key: l_cache_key, buffer: l_buffer },
562 Self::EmbeddedImage { cache_key: r_cache_key, buffer: r_buffer },
563 ) => l_cache_key == r_cache_key && l_buffer == r_buffer,
564 #[cfg(feature = "svg")]
565 (Self::Svg(l0), Self::Svg(r0)) => vtable::VRc::ptr_eq(l0, r0),
566 (Self::StaticTextures(l0), Self::StaticTextures(r0)) => l0 == r0,
567 #[cfg(target_arch = "wasm32")]
568 (Self::HTMLImage(l0), Self::HTMLImage(r0)) => vtable::VRc::ptr_eq(l0, r0),
569 (Self::BackendStorage(l0), Self::BackendStorage(r0)) => vtable::VRc::ptr_eq(l0, r0),
570 #[cfg(not(target_arch = "wasm32"))]
571 (Self::BorrowedOpenGLTexture(l0), Self::BorrowedOpenGLTexture(r0)) => l0 == r0,
572 (Self::NineSlice(l), Self::NineSlice(r)) => l.0 == r.0 && l.1 == r.1,
573 _ => false,
574 }
575 }
576}
577
578impl<'a> From<&'a Image> for &'a ImageInner {
579 fn from(other: &'a Image) -> Self {
580 &other.0
581 }
582}
583
584#[derive(Default, Debug, PartialEq)]
586pub struct LoadImageError(());
587
588impl core::fmt::Display for LoadImageError {
589 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
590 f.write_str("The image cannot be loaded")
591 }
592}
593
594#[cfg(feature = "std")]
595impl std::error::Error for LoadImageError {}
596
597#[repr(transparent)]
694#[derive(Default, Clone, Debug, PartialEq, derive_more::From)]
695pub struct Image(pub(crate) ImageInner);
696
697impl Image {
698 #[cfg(feature = "image-decoders")]
699 pub fn load_from_path(path: &std::path::Path) -> Result<Self, LoadImageError> {
706 self::cache::IMAGE_CACHE.with(|global_cache| {
707 let path: SharedString = path.to_str().ok_or(LoadImageError(()))?.into();
708 global_cache.borrow_mut().load_image_from_path(&path).ok_or(LoadImageError(()))
709 })
710 }
711
712 pub fn from_rgb8(buffer: SharedPixelBuffer<Rgb8Pixel>) -> Self {
715 Image(ImageInner::EmbeddedImage {
716 cache_key: ImageCacheKey::Invalid,
717 buffer: SharedImageBuffer::RGB8(buffer),
718 })
719 }
720
721 pub fn from_rgba8(buffer: SharedPixelBuffer<Rgba8Pixel>) -> Self {
724 Image(ImageInner::EmbeddedImage {
725 cache_key: ImageCacheKey::Invalid,
726 buffer: SharedImageBuffer::RGBA8(buffer),
727 })
728 }
729
730 pub fn from_rgba8_premultiplied(buffer: SharedPixelBuffer<Rgba8Pixel>) -> Self {
736 Image(ImageInner::EmbeddedImage {
737 cache_key: ImageCacheKey::Invalid,
738 buffer: SharedImageBuffer::RGBA8Premultiplied(buffer),
739 })
740 }
741
742 pub fn to_rgb8(&self) -> Option<SharedPixelBuffer<Rgb8Pixel>> {
745 self.0.render_to_buffer(None).and_then(|image| match image {
746 SharedImageBuffer::RGB8(buffer) => Some(buffer),
747 _ => None,
748 })
749 }
750
751 pub fn to_rgba8(&self) -> Option<SharedPixelBuffer<Rgba8Pixel>> {
754 self.0.render_to_buffer(None).map(|image| match image {
755 SharedImageBuffer::RGB8(buffer) => SharedPixelBuffer::<Rgba8Pixel> {
756 width: buffer.width,
757 height: buffer.height,
758 data: buffer.data.into_iter().map(Into::into).collect(),
759 },
760 SharedImageBuffer::RGBA8(buffer) => buffer,
761 SharedImageBuffer::RGBA8Premultiplied(buffer) => SharedPixelBuffer::<Rgba8Pixel> {
762 width: buffer.width,
763 height: buffer.height,
764 data: buffer
765 .data
766 .into_iter()
767 .map(|rgba_premul| {
768 if rgba_premul.a == 0 {
769 Rgba8Pixel::new(0, 0, 0, 0)
770 } else {
771 let af = rgba_premul.a as f32 / 255.0;
772 Rgba8Pixel {
773 r: (rgba_premul.r as f32 * 255. / af) as u8,
774 g: (rgba_premul.g as f32 * 255. / af) as u8,
775 b: (rgba_premul.b as f32 * 255. / af) as u8,
776 a: rgba_premul.a,
777 }
778 }
779 })
780 .collect(),
781 },
782 })
783 }
784
785 pub fn to_rgba8_premultiplied(&self) -> Option<SharedPixelBuffer<Rgba8Pixel>> {
789 self.0.render_to_buffer(None).map(|image| match image {
790 SharedImageBuffer::RGB8(buffer) => SharedPixelBuffer::<Rgba8Pixel> {
791 width: buffer.width,
792 height: buffer.height,
793 data: buffer.data.into_iter().map(Into::into).collect(),
794 },
795 SharedImageBuffer::RGBA8(buffer) => SharedPixelBuffer::<Rgba8Pixel> {
796 width: buffer.width,
797 height: buffer.height,
798 data: buffer
799 .data
800 .into_iter()
801 .map(|rgba| {
802 if rgba.a == 255 {
803 rgba
804 } else {
805 let af = rgba.a as f32 / 255.0;
806 Rgba8Pixel {
807 r: (rgba.r as f32 * af / 255.) as u8,
808 g: (rgba.g as f32 * af / 255.) as u8,
809 b: (rgba.b as f32 * af / 255.) as u8,
810 a: rgba.a,
811 }
812 }
813 })
814 .collect(),
815 },
816 SharedImageBuffer::RGBA8Premultiplied(buffer) => buffer,
817 })
818 }
819
820 #[cfg(feature = "unstable-wgpu-26")]
826 pub fn to_wgpu_26_texture(&self) -> Option<wgpu_26::Texture> {
827 match &self.0 {
828 ImageInner::WGPUTexture(WGPUTexture::WGPU26Texture(texture)) => Some(texture.clone()),
829 _ => None,
830 }
831 }
832
833 #[allow(unsafe_code)]
853 #[cfg(not(target_arch = "wasm32"))]
854 #[deprecated(since = "1.2.0", note = "Use BorrowedOpenGLTextureBuilder")]
855 pub unsafe fn from_borrowed_gl_2d_rgba_texture(
856 texture_id: core::num::NonZeroU32,
857 size: IntSize,
858 ) -> Self {
859 BorrowedOpenGLTextureBuilder::new_gl_2d_rgba_texture(texture_id, size).build()
860 }
861
862 #[cfg(feature = "svg")]
864 pub fn load_from_svg_data(buffer: &[u8]) -> Result<Self, LoadImageError> {
865 let cache_key = ImageCacheKey::Invalid;
866 Ok(Image(ImageInner::Svg(vtable::VRc::new(
867 svg::load_from_data(buffer, cache_key).map_err(|_| LoadImageError(()))?,
868 ))))
869 }
870
871 pub fn set_nine_slice_edges(&mut self, top: u16, right: u16, bottom: u16, left: u16) {
877 if top == 0 && left == 0 && right == 0 && bottom == 0 {
878 if let ImageInner::NineSlice(n) = &self.0 {
879 self.0 = n.0.clone();
880 }
881 } else {
882 let array = [top, right, bottom, left];
883 let inner = if let ImageInner::NineSlice(n) = &mut self.0 {
884 n.0.clone()
885 } else {
886 self.0.clone()
887 };
888 self.0 = ImageInner::NineSlice(vtable::VRc::new(NineSliceImage(inner, array)));
889 }
890 }
891
892 pub fn size(&self) -> IntSize {
894 self.0.size()
895 }
896
897 #[cfg(feature = "std")]
898 pub fn path(&self) -> Option<&std::path::Path> {
910 match &self.0 {
911 ImageInner::EmbeddedImage {
912 cache_key: ImageCacheKey::Path(CachedPath { path, .. }),
913 ..
914 } => Some(std::path::Path::new(path.as_str())),
915 ImageInner::NineSlice(nine) => match &nine.0 {
916 ImageInner::EmbeddedImage {
917 cache_key: ImageCacheKey::Path(CachedPath { path, .. }),
918 ..
919 } => Some(std::path::Path::new(path.as_str())),
920 _ => None,
921 },
922 _ => None,
923 }
924 }
925}
926
927#[derive(Copy, Clone, Debug, PartialEq, Default)]
930#[repr(u8)]
931#[non_exhaustive]
932pub enum BorrowedOpenGLTextureOrigin {
933 #[default]
935 TopLeft,
936 BottomLeft,
939}
940
941#[cfg(not(target_arch = "wasm32"))]
959pub struct BorrowedOpenGLTextureBuilder(BorrowedOpenGLTexture);
960
961#[cfg(not(target_arch = "wasm32"))]
962impl BorrowedOpenGLTextureBuilder {
963 #[allow(unsafe_code)]
981 pub unsafe fn new_gl_2d_rgba_texture(texture_id: core::num::NonZeroU32, size: IntSize) -> Self {
982 Self(BorrowedOpenGLTexture { texture_id, size, origin: Default::default() })
983 }
984
985 pub fn origin(mut self, origin: BorrowedOpenGLTextureOrigin) -> Self {
987 self.0.origin = origin;
988 self
989 }
990
991 pub fn build(self) -> Image {
993 Image(ImageInner::BorrowedOpenGLTexture(self.0))
994 }
995}
996
997#[cfg(feature = "image-decoders")]
1000pub fn load_image_from_embedded_data(data: Slice<'static, u8>, format: Slice<'_, u8>) -> Image {
1001 self::cache::IMAGE_CACHE.with(|global_cache| {
1002 global_cache.borrow_mut().load_image_from_embedded_data(data, format).unwrap_or_default()
1003 })
1004}
1005
1006#[test]
1007fn test_image_size_from_buffer_without_backend() {
1008 {
1009 assert_eq!(Image::default().size(), Default::default());
1010 assert!(Image::default().to_rgb8().is_none());
1011 assert!(Image::default().to_rgba8().is_none());
1012 assert!(Image::default().to_rgba8_premultiplied().is_none());
1013 }
1014 {
1015 let buffer = SharedPixelBuffer::<Rgb8Pixel>::new(320, 200);
1016 let image = Image::from_rgb8(buffer.clone());
1017 assert_eq!(image.size(), [320, 200].into());
1018 assert_eq!(image.to_rgb8().as_ref().map(|b| b.as_slice()), Some(buffer.as_slice()));
1019 }
1020}
1021
1022#[cfg(feature = "svg")]
1023#[test]
1024fn test_image_size_from_svg() {
1025 let simple_svg = r#"<svg width="320" height="200" xmlns="http://www.w3.org/2000/svg"></svg>"#;
1026 let image = Image::load_from_svg_data(simple_svg.as_bytes()).unwrap();
1027 assert_eq!(image.size(), [320, 200].into());
1028 assert_eq!(image.to_rgba8().unwrap().size(), image.size());
1029}
1030
1031#[cfg(feature = "svg")]
1032#[test]
1033fn test_image_invalid_svg() {
1034 let invalid_svg = r#"AaBbCcDd"#;
1035 let result = Image::load_from_svg_data(invalid_svg.as_bytes());
1036 assert!(result.is_err());
1037}
1038
1039#[derive(Debug)]
1041pub struct FitResult {
1042 pub clip_rect: IntRect,
1044 pub source_to_target_x: f32,
1046 pub source_to_target_y: f32,
1048 pub size: euclid::Size2D<f32, PhysicalPx>,
1050 pub offset: euclid::Point2D<f32, PhysicalPx>,
1052 pub tiled: Option<euclid::default::Point2D<u32>>,
1056}
1057
1058impl FitResult {
1059 fn adjust_for_tiling(
1060 self,
1061 ratio: f32,
1062 alignment: (ImageHorizontalAlignment, ImageVerticalAlignment),
1063 tiling: (ImageTiling, ImageTiling),
1064 ) -> Self {
1065 let mut r = self;
1066 let mut tiled = euclid::Point2D::default();
1067 let target = r.size;
1068 let o = r.clip_rect.size.cast::<f32>();
1069 match tiling.0 {
1070 ImageTiling::None => {
1071 r.size.width = o.width * r.source_to_target_x;
1072 if (o.width as f32) > target.width / r.source_to_target_x {
1073 let diff = (o.width as f32 - target.width / r.source_to_target_x) as i32;
1074 r.clip_rect.size.width -= diff;
1075 r.clip_rect.origin.x += match alignment.0 {
1076 ImageHorizontalAlignment::Center => diff / 2,
1077 ImageHorizontalAlignment::Left => 0,
1078 ImageHorizontalAlignment::Right => diff,
1079 };
1080 r.size.width = target.width;
1081 } else if (o.width as f32) < target.width / r.source_to_target_x {
1082 r.offset.x += match alignment.0 {
1083 ImageHorizontalAlignment::Center => {
1084 (target.width - o.width as f32 * r.source_to_target_x) / 2.
1085 }
1086 ImageHorizontalAlignment::Left => 0.,
1087 ImageHorizontalAlignment::Right => {
1088 target.width - o.width as f32 * r.source_to_target_x
1089 }
1090 };
1091 }
1092 }
1093 ImageTiling::Repeat => {
1094 tiled.x = match alignment.0 {
1095 ImageHorizontalAlignment::Left => 0,
1096 ImageHorizontalAlignment::Center => {
1097 ((o.width - target.width / ratio) / 2.).rem_euclid(o.width) as u32
1098 }
1099 ImageHorizontalAlignment::Right => {
1100 (-target.width / ratio).rem_euclid(o.width) as u32
1101 }
1102 };
1103 r.source_to_target_x = ratio;
1104 }
1105 ImageTiling::Round => {
1106 if target.width / ratio <= o.width * 1.5 {
1107 r.source_to_target_x = target.width / o.width;
1108 } else {
1109 let mut rem = (target.width / ratio).rem_euclid(o.width);
1110 if rem > o.width / 2. {
1111 rem -= o.width;
1112 }
1113 r.source_to_target_x = ratio * target.width / (target.width - rem * ratio);
1114 }
1115 }
1116 }
1117
1118 match tiling.1 {
1119 ImageTiling::None => {
1120 r.size.height = o.height * r.source_to_target_y;
1121 if (o.height as f32) > target.height / r.source_to_target_y {
1122 let diff = (o.height as f32 - target.height / r.source_to_target_y) as i32;
1123 r.clip_rect.size.height -= diff;
1124 r.clip_rect.origin.y += match alignment.1 {
1125 ImageVerticalAlignment::Center => diff / 2,
1126 ImageVerticalAlignment::Top => 0,
1127 ImageVerticalAlignment::Bottom => diff,
1128 };
1129 r.size.height = target.height;
1130 } else if (o.height as f32) < target.height / r.source_to_target_y {
1131 r.offset.y += match alignment.1 {
1132 ImageVerticalAlignment::Center => {
1133 (target.height - o.height as f32 * r.source_to_target_y) / 2.
1134 }
1135 ImageVerticalAlignment::Top => 0.,
1136 ImageVerticalAlignment::Bottom => {
1137 target.height - o.height as f32 * r.source_to_target_y
1138 }
1139 };
1140 }
1141 }
1142 ImageTiling::Repeat => {
1143 tiled.y = match alignment.1 {
1144 ImageVerticalAlignment::Top => 0,
1145 ImageVerticalAlignment::Center => {
1146 ((o.height - target.height / ratio) / 2.).rem_euclid(o.height) as u32
1147 }
1148 ImageVerticalAlignment::Bottom => {
1149 (-target.height / ratio).rem_euclid(o.height) as u32
1150 }
1151 };
1152 r.source_to_target_y = ratio;
1153 }
1154 ImageTiling::Round => {
1155 if target.height / ratio <= o.height * 1.5 {
1156 r.source_to_target_y = target.height / o.height;
1157 } else {
1158 let mut rem = (target.height / ratio).rem_euclid(o.height);
1159 if rem > o.height / 2. {
1160 rem -= o.height;
1161 }
1162 r.source_to_target_y = ratio * target.height / (target.height - rem * ratio);
1163 }
1164 }
1165 }
1166 let has_tiling = tiling != (ImageTiling::None, ImageTiling::None);
1167 r.tiled = has_tiling.then_some(tiled);
1168 r
1169 }
1170}
1171
1172#[cfg(not(feature = "std"))]
1173trait RemEuclid {
1174 fn rem_euclid(self, b: f32) -> f32;
1175}
1176#[cfg(not(feature = "std"))]
1177impl RemEuclid for f32 {
1178 fn rem_euclid(self, b: f32) -> f32 {
1179 return num_traits::Euclid::rem_euclid(&self, &b);
1180 }
1181}
1182
1183pub fn fit(
1185 image_fit: ImageFit,
1186 target: euclid::Size2D<f32, PhysicalPx>,
1187 source_rect: IntRect,
1188 scale_factor: ScaleFactor,
1189 alignment: (ImageHorizontalAlignment, ImageVerticalAlignment),
1190 tiling: (ImageTiling, ImageTiling),
1191) -> FitResult {
1192 let has_tiling = tiling != (ImageTiling::None, ImageTiling::None);
1193 let o = source_rect.size.cast::<f32>();
1194 let ratio = match image_fit {
1195 _ if has_tiling => scale_factor.get(),
1197 ImageFit::Fill => {
1198 return FitResult {
1199 clip_rect: source_rect,
1200 source_to_target_x: target.width / o.width,
1201 source_to_target_y: target.height / o.height,
1202 size: target,
1203 offset: Default::default(),
1204 tiled: None,
1205 }
1206 }
1207 ImageFit::Preserve => scale_factor.get(),
1208 ImageFit::Contain => f32::min(target.width / o.width, target.height / o.height),
1209 ImageFit::Cover => f32::max(target.width / o.width, target.height / o.height),
1210 };
1211
1212 FitResult {
1213 clip_rect: source_rect,
1214 source_to_target_x: ratio,
1215 source_to_target_y: ratio,
1216 size: target,
1217 offset: euclid::Point2D::default(),
1218 tiled: None,
1219 }
1220 .adjust_for_tiling(ratio, alignment, tiling)
1221}
1222
1223pub fn fit9slice(
1225 source_rect: IntSize,
1226 [t, r, b, l]: [u16; 4],
1227 target: euclid::Size2D<f32, PhysicalPx>,
1228 scale_factor: ScaleFactor,
1229 alignment: (ImageHorizontalAlignment, ImageVerticalAlignment),
1230 tiling: (ImageTiling, ImageTiling),
1231) -> impl Iterator<Item = FitResult> {
1232 let fit_to = |clip_rect: euclid::default::Rect<u16>, target: euclid::Rect<f32, PhysicalPx>| {
1233 (!clip_rect.is_empty() && !target.is_empty()).then(|| {
1234 FitResult {
1235 clip_rect: clip_rect.cast(),
1236 source_to_target_x: target.width() / clip_rect.width() as f32,
1237 source_to_target_y: target.height() / clip_rect.height() as f32,
1238 size: target.size,
1239 offset: target.origin,
1240 tiled: None,
1241 }
1242 .adjust_for_tiling(scale_factor.get(), alignment, tiling)
1243 })
1244 };
1245 use euclid::rect;
1246 let sf = |x| scale_factor.get() * x as f32;
1247 let source = source_rect.cast::<u16>();
1248 if t + b > source.height || l + r > source.width {
1249 [None, None, None, None, None, None, None, None, None]
1250 } else {
1251 [
1252 fit_to(rect(0, 0, l, t), rect(0., 0., sf(l), sf(t))),
1253 fit_to(
1254 rect(l, 0, source.width - l - r, t),
1255 rect(sf(l), 0., target.width - sf(l) - sf(r), sf(t)),
1256 ),
1257 fit_to(rect(source.width - r, 0, r, t), rect(target.width - sf(r), 0., sf(r), sf(t))),
1258 fit_to(
1259 rect(0, t, l, source.height - t - b),
1260 rect(0., sf(t), sf(l), target.height - sf(t) - sf(b)),
1261 ),
1262 fit_to(
1263 rect(l, t, source.width - l - r, source.height - t - b),
1264 rect(sf(l), sf(t), target.width - sf(l) - sf(r), target.height - sf(t) - sf(b)),
1265 ),
1266 fit_to(
1267 rect(source.width - r, t, r, source.height - t - b),
1268 rect(target.width - sf(r), sf(t), sf(r), target.height - sf(t) - sf(b)),
1269 ),
1270 fit_to(rect(0, source.height - b, l, b), rect(0., target.height - sf(b), sf(l), sf(b))),
1271 fit_to(
1272 rect(l, source.height - b, source.width - l - r, b),
1273 rect(sf(l), target.height - sf(b), target.width - sf(l) - sf(r), sf(b)),
1274 ),
1275 fit_to(
1276 rect(source.width - r, source.height - b, r, b),
1277 rect(target.width - sf(r), target.height - sf(b), sf(r), sf(b)),
1278 ),
1279 ]
1280 }
1281 .into_iter()
1282 .flatten()
1283}
1284
1285#[cfg(feature = "ffi")]
1286pub(crate) mod ffi {
1287 #![allow(unsafe_code)]
1288
1289 use super::*;
1290
1291 #[cfg(cbindgen)]
1294 #[repr(C)]
1295 struct Rgb8Pixel {
1296 r: u8,
1298 g: u8,
1300 b: u8,
1302 }
1303
1304 #[cfg(cbindgen)]
1307 #[repr(C)]
1308 struct Rgba8Pixel {
1309 r: u8,
1311 g: u8,
1313 b: u8,
1315 a: u8,
1317 }
1318
1319 #[cfg(feature = "image-decoders")]
1320 #[unsafe(no_mangle)]
1321 pub unsafe extern "C" fn slint_image_load_from_path(path: &SharedString, image: *mut Image) {
1322 core::ptr::write(
1323 image,
1324 Image::load_from_path(std::path::Path::new(path.as_str())).unwrap_or(Image::default()),
1325 )
1326 }
1327
1328 #[cfg(feature = "std")]
1329 #[unsafe(no_mangle)]
1330 pub unsafe extern "C" fn slint_image_load_from_embedded_data(
1331 data: Slice<'static, u8>,
1332 format: Slice<'static, u8>,
1333 image: *mut Image,
1334 ) {
1335 core::ptr::write(image, super::load_image_from_embedded_data(data, format));
1336 }
1337
1338 #[unsafe(no_mangle)]
1339 pub unsafe extern "C" fn slint_image_size(image: &Image) -> IntSize {
1340 image.size()
1341 }
1342
1343 #[unsafe(no_mangle)]
1344 pub extern "C" fn slint_image_path(image: &Image) -> Option<&SharedString> {
1345 match &image.0 {
1346 ImageInner::EmbeddedImage { cache_key, .. } => match cache_key {
1347 #[cfg(feature = "std")]
1348 ImageCacheKey::Path(CachedPath { path, .. }) => Some(path),
1349 _ => None,
1350 },
1351 ImageInner::NineSlice(nine) => match &nine.0 {
1352 ImageInner::EmbeddedImage { cache_key, .. } => match cache_key {
1353 #[cfg(feature = "std")]
1354 ImageCacheKey::Path(CachedPath { path, .. }) => Some(path),
1355 _ => None,
1356 },
1357 _ => None,
1358 },
1359 _ => None,
1360 }
1361 }
1362
1363 #[unsafe(no_mangle)]
1364 pub unsafe extern "C" fn slint_image_from_embedded_textures(
1365 textures: &'static StaticTextures,
1366 image: *mut Image,
1367 ) {
1368 core::ptr::write(image, Image::from(ImageInner::StaticTextures(textures)));
1369 }
1370
1371 #[unsafe(no_mangle)]
1372 pub unsafe extern "C" fn slint_image_compare_equal(image1: &Image, image2: &Image) -> bool {
1373 image1.eq(image2)
1374 }
1375
1376 #[unsafe(no_mangle)]
1378 pub extern "C" fn slint_image_set_nine_slice_edges(
1379 image: &mut Image,
1380 top: u16,
1381 right: u16,
1382 bottom: u16,
1383 left: u16,
1384 ) {
1385 image.set_nine_slice_edges(top, right, bottom, left);
1386 }
1387
1388 #[unsafe(no_mangle)]
1389 pub extern "C" fn slint_image_to_rgb8(
1390 image: &Image,
1391 data: &mut SharedVector<Rgb8Pixel>,
1392 width: &mut u32,
1393 height: &mut u32,
1394 ) -> bool {
1395 image.to_rgb8().is_some_and(|pixel_buffer| {
1396 *data = pixel_buffer.data.clone();
1397 *width = pixel_buffer.width();
1398 *height = pixel_buffer.height();
1399 true
1400 })
1401 }
1402
1403 #[unsafe(no_mangle)]
1404 pub extern "C" fn slint_image_to_rgba8(
1405 image: &Image,
1406 data: &mut SharedVector<Rgba8Pixel>,
1407 width: &mut u32,
1408 height: &mut u32,
1409 ) -> bool {
1410 image.to_rgba8().is_some_and(|pixel_buffer| {
1411 *data = pixel_buffer.data.clone();
1412 *width = pixel_buffer.width();
1413 *height = pixel_buffer.height();
1414 true
1415 })
1416 }
1417
1418 #[unsafe(no_mangle)]
1419 pub extern "C" fn slint_image_to_rgba8_premultiplied(
1420 image: &Image,
1421 data: &mut SharedVector<Rgba8Pixel>,
1422 width: &mut u32,
1423 height: &mut u32,
1424 ) -> bool {
1425 image.to_rgba8_premultiplied().is_some_and(|pixel_buffer| {
1426 *data = pixel_buffer.data.clone();
1427 *width = pixel_buffer.width();
1428 *height = pixel_buffer.height();
1429 true
1430 })
1431 }
1432}
1433
1434#[derive(Clone, Debug, PartialEq)]
1442#[non_exhaustive]
1443#[cfg(not(target_arch = "wasm32"))]
1444#[repr(C)]
1445pub struct BorrowedOpenGLTexture {
1446 pub texture_id: core::num::NonZeroU32,
1448 pub size: IntSize,
1450 pub origin: BorrowedOpenGLTextureOrigin,
1452}