Skip to main content

cranpose_ui/widgets/
image.rs

1//! Image composable and painter primitives.
2
3#![expect(non_snake_case)]
4#![expect(clippy::too_many_arguments)]
5
6#[cfg(feature = "svg")]
7use std::sync::{Mutex, MutexGuard};
8use std::{
9    hash::{Hash, Hasher},
10    sync::Arc,
11};
12
13use cranpose_core::NodeId;
14use cranpose_ui_graphics::{ColorFilter, DrawScope, ImageBitmap, ImageSampling};
15use cranpose_ui_layout::{Constraints, MeasurePolicy, MeasureResult, MeasureScope, Placement};
16use thiserror::Error;
17
18use crate::{
19    composable,
20    layout::core::{Alignment, Measurable},
21    modifier::{Modifier, Rect, Size},
22    nine_patch::{NinePatchInsets, PatchFill, PatchQuad, nine_patch_quads, tile_quads},
23    widgets::Layout,
24};
25
26#[cfg(feature = "svg")]
27#[path = "image_svg.rs"]
28mod image_svg;
29
30pub const DEFAULT_ALPHA: f32 = 1.0;
31#[cfg(feature = "svg")]
32const SVG_RASTER_CACHE_LIMIT: usize = 8;
33
34#[derive(Clone, Copy, Debug, PartialEq)]
35pub enum ContentScale {
36    Fit,
37    Crop,
38    FillBounds,
39    FillWidth,
40    FillHeight,
41    Inside,
42    None,
43}
44
45impl ContentScale {
46    pub fn scaled_size(self, src_size: Size, dst_size: Size) -> Size {
47        if src_size.width <= 0.0
48            || src_size.height <= 0.0
49            || dst_size.width <= 0.0
50            || dst_size.height <= 0.0
51        {
52            return Size::ZERO;
53        }
54
55        let scale_x = dst_size.width / src_size.width;
56        let scale_y = dst_size.height / src_size.height;
57
58        let (factor_x, factor_y) = match self {
59            Self::Fit => {
60                let factor = scale_x.min(scale_y);
61                (factor, factor)
62            }
63            Self::Crop => {
64                let factor = scale_x.max(scale_y);
65                (factor, factor)
66            }
67            Self::FillBounds => (scale_x, scale_y),
68            Self::FillWidth => (scale_x, scale_x),
69            Self::FillHeight => (scale_y, scale_y),
70            Self::Inside => {
71                if src_size.width <= dst_size.width && src_size.height <= dst_size.height {
72                    (1.0, 1.0)
73                } else {
74                    let factor = scale_x.min(scale_y);
75                    (factor, factor)
76                }
77            }
78            Self::None => (1.0, 1.0),
79        };
80
81        Size {
82            width: src_size.width * factor_x,
83            height: src_size.height * factor_y,
84        }
85    }
86}
87
88#[derive(Clone, Debug, PartialEq, Eq, Hash)]
89pub struct Painter {
90    kind: PainterKind,
91}
92
93#[derive(Clone, Debug, PartialEq, Eq, Hash)]
94enum PainterKind {
95    Bitmap(ImageBitmap),
96    BitmapRegion {
97        bitmap: ImageBitmap,
98        source: Quad,
99        sampling: ImageSampling,
100    },
101    /// A source repeated at its own size across whatever space it is given,
102    /// rather than scaled to fit it.
103    BitmapTiled {
104        bitmap: ImageBitmap,
105        source: Quad,
106        sampling: ImageSampling,
107    },
108    /// A source whose corners keep their size while its edges and middle grow.
109    NinePatch {
110        bitmap: ImageBitmap,
111        source: Quad,
112        insets: Quad,
113        center: PatchFill,
114        edges: PatchFill,
115        sampling: ImageSampling,
116    },
117    Svg(SvgPainter),
118}
119
120/// Four `f32`s carried as bits.
121///
122/// A painter is compared and hashed so a composable can skip when it has not
123/// changed, and floats are neither `Eq` nor `Hash`. Keeping the bits makes the
124/// comparison exact — two painters built from the same numbers are the same
125/// painter — without asking the caller to think about it.
126#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
127struct Quad {
128    a: u32,
129    b: u32,
130    c: u32,
131    d: u32,
132}
133
134impl Quad {
135    fn of(a: f32, b: f32, c: f32, d: f32) -> Self {
136        Self {
137            a: a.to_bits(),
138            b: b.to_bits(),
139            c: c.to_bits(),
140            d: d.to_bits(),
141        }
142    }
143
144    fn values(self) -> (f32, f32, f32, f32) {
145        (
146            f32::from_bits(self.a),
147            f32::from_bits(self.b),
148            f32::from_bits(self.c),
149            f32::from_bits(self.d),
150        )
151    }
152
153    fn from_rect(source: Rect) -> Self {
154        Self::of(source.x, source.y, source.width, source.height)
155    }
156
157    fn rect(self) -> Rect {
158        let (x, y, width, height) = self.values();
159        Rect {
160            x,
161            y,
162            width,
163            height,
164        }
165    }
166
167    fn from_insets(insets: NinePatchInsets) -> Self {
168        Self::of(insets.left, insets.top, insets.right, insets.bottom)
169    }
170
171    fn insets(self) -> NinePatchInsets {
172        let (left, top, right, bottom) = self.values();
173        NinePatchInsets::new(left, top, right, bottom)
174    }
175}
176
177impl Painter {
178    pub fn from_bitmap(bitmap: ImageBitmap) -> Self {
179        Self {
180            kind: PainterKind::Bitmap(bitmap),
181        }
182    }
183
184    /// Creates a painter for one source region of a bitmap atlas.
185    pub fn from_bitmap_region(bitmap: ImageBitmap, source: Rect, sampling: ImageSampling) -> Self {
186        Self {
187            kind: PainterKind::BitmapRegion {
188                bitmap,
189                source: Quad::from_rect(source),
190                sampling,
191            },
192        }
193    }
194
195    /// Creates a painter that repeats `source` at its own size across whatever
196    /// space it is given, instead of scaling it to fit.
197    ///
198    /// A texture, a hatch or a skin background covers an area of any size
199    /// without going soft. `source` is a region of `bitmap`, so an application
200    /// tiles one sprite out of an atlas and never the whole sheet.
201    pub fn from_bitmap_tiled(bitmap: ImageBitmap, source: Rect, sampling: ImageSampling) -> Self {
202        Self {
203            kind: PainterKind::BitmapTiled {
204                bitmap,
205                source: Quad::from_rect(source),
206                sampling,
207            },
208        }
209    }
210
211    /// Creates a painter whose corners keep their own size while its edges and
212    /// middle grow — one drawing of a button, panel or trough used at every
213    /// size.
214    ///
215    /// `center` and `edges` decide whether the growing parts are stretched or
216    /// tiled. Insets that leave no middle, or a destination with no room for
217    /// the corners, fall back to a plain scale rather than drawing corners over
218    /// each other.
219    pub fn from_nine_patch(
220        bitmap: ImageBitmap,
221        source: Rect,
222        insets: NinePatchInsets,
223        center: PatchFill,
224        edges: PatchFill,
225        sampling: ImageSampling,
226    ) -> Self {
227        Self {
228            kind: PainterKind::NinePatch {
229                bitmap,
230                source: Quad::from_rect(source),
231                insets: Quad::from_insets(insets),
232                center,
233                edges,
234                sampling,
235            },
236        }
237    }
238
239    pub fn from_svg(svg: SvgPainter) -> Self {
240        Self {
241            kind: PainterKind::Svg(svg),
242        }
243    }
244
245    pub fn intrinsic_size(&self) -> Size {
246        match &self.kind {
247            PainterKind::Bitmap(bitmap) => bitmap.intrinsic_size(),
248            PainterKind::BitmapRegion { source, .. }
249            | PainterKind::BitmapTiled { source, .. }
250            | PainterKind::NinePatch { source, .. } => {
251                let source = source.rect();
252                Size::new(source.width.max(0.0), source.height.max(0.0))
253            }
254            PainterKind::Svg(svg) => svg.intrinsic_size(),
255        }
256    }
257
258    pub fn as_bitmap(&self) -> Option<&ImageBitmap> {
259        match &self.kind {
260            PainterKind::Bitmap(bitmap) => Some(bitmap),
261            PainterKind::BitmapRegion { bitmap, .. }
262            | PainterKind::BitmapTiled { bitmap, .. }
263            | PainterKind::NinePatch { bitmap, .. } => Some(bitmap),
264            PainterKind::Svg(_) => None,
265        }
266    }
267
268    /// Returns the underlying bitmap when this painter is bitmap-backed.
269    pub fn bitmap(&self) -> Option<&ImageBitmap> {
270        self.as_bitmap()
271    }
272}
273
274impl From<ImageBitmap> for Painter {
275    fn from(value: ImageBitmap) -> Self {
276        Self::from_bitmap(value)
277    }
278}
279
280impl From<SvgPainter> for Painter {
281    fn from(value: SvgPainter) -> Self {
282        Self::from_svg(value)
283    }
284}
285
286pub fn BitmapPainter(bitmap: ImageBitmap) -> Painter {
287    Painter::from_bitmap(bitmap)
288}
289
290/// Creates a painter that draws one region from a bitmap atlas.
291pub fn BitmapRegionPainter(bitmap: ImageBitmap, source: Rect, sampling: ImageSampling) -> Painter {
292    Painter::from_bitmap_region(bitmap, source, sampling)
293}
294
295/// Creates a painter that repeats one region of a bitmap across its bounds.
296pub fn TiledPainter(bitmap: ImageBitmap, source: Rect, sampling: ImageSampling) -> Painter {
297    Painter::from_bitmap_tiled(bitmap, source, sampling)
298}
299
300/// Creates a painter whose corners stay put while its edges and middle grow.
301pub fn NinePatchPainter(
302    bitmap: ImageBitmap,
303    source: Rect,
304    insets: NinePatchInsets,
305    center: PatchFill,
306    edges: PatchFill,
307    sampling: ImageSampling,
308) -> Painter {
309    Painter::from_nine_patch(bitmap, source, insets, center, edges, sampling)
310}
311
312/// Errors returned while parsing or rasterizing an SVG painter.
313#[derive(Debug, Clone, PartialEq, Eq, Error)]
314pub enum SvgPainterError {
315    #[error("SVG support is disabled; enable the cranpose-ui `svg` feature")]
316    SvgFeatureDisabled,
317    #[error("failed to parse SVG: {0}")]
318    Parse(String),
319    #[error("SVG raster dimensions must be greater than zero")]
320    InvalidRasterDimensions,
321    #[error("SVG raster dimensions are too large")]
322    RasterDimensionsTooLarge,
323    #[error("failed to allocate SVG raster {width}x{height}")]
324    RasterAllocationFailed { width: u32, height: u32 },
325    #[error("SVG raster cache is unavailable")]
326    RasterCacheUnavailable,
327    #[error(transparent)]
328    ImageBitmap(#[from] cranpose_ui_graphics::ImageBitmapError),
329}
330
331/// Parsed SVG image data that rasterizes on demand for the requested draw size.
332#[derive(Clone)]
333pub struct SvgPainter {
334    inner: Arc<SvgPainterInner>,
335}
336
337struct SvgPainterInner {
338    #[cfg(feature = "svg")]
339    document: image_svg::SvgDocument,
340    intrinsic_size: Size,
341    #[cfg(feature = "svg")]
342    cache: Mutex<SvgRasterCache>,
343}
344
345#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
346#[cfg(feature = "svg")]
347struct SvgRasterKey {
348    width: u32,
349    height: u32,
350}
351
352#[derive(Clone, Debug)]
353#[cfg(feature = "svg")]
354struct SvgRasterEntry {
355    key: SvgRasterKey,
356    bitmap: ImageBitmap,
357}
358
359#[derive(Default, Debug)]
360#[cfg(feature = "svg")]
361struct SvgRasterCache {
362    entries: Vec<SvgRasterEntry>,
363}
364
365impl SvgPainter {
366    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SvgPainterError> {
367        #[cfg(not(feature = "svg"))]
368        {
369            let _ = bytes;
370            Err(SvgPainterError::SvgFeatureDisabled)
371        }
372        #[cfg(feature = "svg")]
373        {
374            let document = image_svg::parse_svg_document(bytes)?;
375            let intrinsic_size = document.intrinsic_size();
376
377            Ok(Self {
378                inner: Arc::new(SvgPainterInner {
379                    document,
380                    intrinsic_size,
381                    cache: Mutex::new(SvgRasterCache::default()),
382                }),
383            })
384        }
385    }
386
387    pub fn id(&self) -> u64 {
388        Arc::as_ptr(&self.inner) as usize as u64
389    }
390
391    pub fn intrinsic_size(&self) -> Size {
392        self.inner.intrinsic_size
393    }
394
395    pub fn rasterize(&self, pixel_size: Size) -> Result<ImageBitmap, SvgPainterError> {
396        #[cfg(not(feature = "svg"))]
397        {
398            let _ = pixel_size;
399            Err(SvgPainterError::SvgFeatureDisabled)
400        }
401        #[cfg(feature = "svg")]
402        {
403            let key = svg_raster_key(pixel_size)?;
404            if let Some(bitmap) = self.cached_bitmap(key)? {
405                return Ok(bitmap);
406            }
407
408            let bitmap = self.rasterize_uncached(key)?;
409            self.cache_bitmap(key, bitmap.clone())?;
410            Ok(bitmap)
411        }
412    }
413
414    #[cfg(feature = "svg")]
415    fn cached_bitmap(&self, key: SvgRasterKey) -> Result<Option<ImageBitmap>, SvgPainterError> {
416        let mut cache = self.lock_cache();
417        Ok(cache.get(key))
418    }
419
420    #[cfg(feature = "svg")]
421    fn cache_bitmap(&self, key: SvgRasterKey, bitmap: ImageBitmap) -> Result<(), SvgPainterError> {
422        let mut cache = self.lock_cache();
423        cache.insert(key, bitmap);
424        Ok(())
425    }
426
427    #[cfg(feature = "svg")]
428    fn lock_cache(&self) -> MutexGuard<'_, SvgRasterCache> {
429        self.inner
430            .cache
431            .lock()
432            .unwrap_or_else(std::sync::PoisonError::into_inner)
433    }
434
435    #[cfg(feature = "svg")]
436    fn rasterize_uncached(&self, key: SvgRasterKey) -> Result<ImageBitmap, SvgPainterError> {
437        (key.width as usize)
438            .checked_mul(key.height as usize)
439            .and_then(|value| value.checked_mul(4))
440            .ok_or(SvgPainterError::RasterDimensionsTooLarge)?;
441
442        let mut pixmap = tiny_skia::Pixmap::new(key.width, key.height).ok_or(
443            SvgPainterError::RasterAllocationFailed {
444                width: key.width,
445                height: key.height,
446            },
447        )?;
448        image_svg::rasterize_svg_document(&self.inner.document, &mut pixmap);
449        let pixels = image_svg::demultiplied_rgba_pixels(&pixmap);
450        Ok(ImageBitmap::from_rgba8(key.width, key.height, pixels)?)
451    }
452}
453
454impl std::fmt::Debug for SvgPainter {
455    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
456        f.debug_struct("SvgPainter")
457            .field("id", &self.id())
458            .field("intrinsic_size", &self.intrinsic_size())
459            .finish_non_exhaustive()
460    }
461}
462
463impl PartialEq for SvgPainter {
464    fn eq(&self, other: &Self) -> bool {
465        self.id() == other.id()
466    }
467}
468
469impl Eq for SvgPainter {}
470
471impl Hash for SvgPainter {
472    fn hash<H: Hasher>(&self, state: &mut H) {
473        self.id().hash(state);
474    }
475}
476
477#[cfg(feature = "svg")]
478impl SvgRasterCache {
479    fn get(&mut self, key: SvgRasterKey) -> Option<ImageBitmap> {
480        let position = self.entries.iter().position(|entry| entry.key == key)?;
481        let entry = self.entries.remove(position);
482        let bitmap = entry.bitmap.clone();
483        self.entries.push(entry);
484        Some(bitmap)
485    }
486
487    fn insert(&mut self, key: SvgRasterKey, bitmap: ImageBitmap) {
488        if let Some(position) = self.entries.iter().position(|entry| entry.key == key) {
489            self.entries.remove(position);
490        } else if self.entries.len() >= SVG_RASTER_CACHE_LIMIT {
491            self.entries.remove(0);
492        }
493        self.entries.push(SvgRasterEntry { key, bitmap });
494    }
495}
496
497#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
498struct SvgBytesKey {
499    ptr: usize,
500    len: usize,
501}
502
503impl SvgBytesKey {
504    fn new(bytes: &'static [u8]) -> Self {
505        Self {
506            ptr: bytes.as_ptr() as usize,
507            len: bytes.len(),
508        }
509    }
510}
511
512pub fn rememberSvg(bytes: &'static [u8]) -> Result<SvgPainter, SvgPainterError> {
513    let key = SvgBytesKey::new(bytes);
514    cranpose_core::withCurrentComposer(|composer| {
515        composer.with_key(&key, |composer| {
516            composer
517                .remember(|| SvgPainter::from_bytes(bytes))
518                .with(Clone::clone)
519        })
520    })
521}
522
523/// Measure policy for Image that preserves aspect ratio when constraints
524/// force the image smaller than its intrinsic size.
525///
526/// Unlike [`LeafMeasurePolicy`] which clamps width and height independently,
527/// this scales both dimensions by the same factor so the image is never
528/// distorted by layout constraints.
529#[derive(Clone, Debug, PartialEq)]
530struct ImageMeasurePolicy {
531    intrinsic_size: Size,
532}
533
534impl MeasurePolicy for ImageMeasurePolicy {
535    fn measure(
536        &self,
537        scope: &dyn MeasureScope,
538        _measurables: &[Box<dyn Measurable>],
539        constraints: Constraints,
540    ) -> MeasureResult {
541        let mut placements = Vec::new();
542        let size = self.measure_into(scope, &[], constraints, &mut placements);
543        MeasureResult::new(size, placements)
544    }
545
546    fn measure_into(
547        &self,
548        _scope: &dyn MeasureScope,
549        _measurables: &[Box<dyn Measurable>],
550        constraints: Constraints,
551        placements: &mut Vec<Placement>,
552    ) -> Size {
553        placements.clear();
554        let iw = self.intrinsic_size.width;
555        let ih = self.intrinsic_size.height;
556
557        if iw <= 0.0 || ih <= 0.0 {
558            let (w, h) = constraints.constrain(0.0, 0.0);
559            return Size {
560                width: w,
561                height: h,
562            };
563        }
564
565        let cw = iw.clamp(constraints.min_width, constraints.max_width);
566        let ch = ih.clamp(constraints.min_height, constraints.max_height);
567
568        let scale_x = cw / iw;
569        let scale_y = ch / ih;
570
571        let (width, height) = if scale_x < 1.0 || scale_y < 1.0 {
572            let factor = scale_x.min(scale_y);
573            let w = (iw * factor).clamp(constraints.min_width, constraints.max_width);
574            let h = (ih * factor).clamp(constraints.min_height, constraints.max_height);
575            (w, h)
576        } else {
577            (cw, ch)
578        };
579
580        Size { width, height }
581    }
582
583    fn min_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
584        self.intrinsic_size.width
585    }
586
587    fn max_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
588        self.intrinsic_size.width
589    }
590
591    fn min_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
592        self.intrinsic_size.height
593    }
594
595    fn max_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
596        self.intrinsic_size.height
597    }
598}
599
600fn destination_rect(
601    src_size: Size,
602    dst_size: Size,
603    alignment: Alignment,
604    content_scale: ContentScale,
605) -> Rect {
606    let draw_size = content_scale.scaled_size(src_size, dst_size);
607    let allows_overflow = content_scale == ContentScale::Crop;
608    let offset_x = aligned_x_offset(
609        alignment.horizontal,
610        dst_size.width,
611        draw_size.width,
612        allows_overflow,
613    );
614    let offset_y = aligned_y_offset(
615        alignment.vertical,
616        dst_size.height,
617        draw_size.height,
618        allows_overflow,
619    );
620    Rect {
621        x: offset_x,
622        y: offset_y,
623        width: draw_size.width,
624        height: draw_size.height,
625    }
626}
627
628fn aligned_x_offset(
629    alignment: cranpose_ui_layout::HorizontalAlignment,
630    available: f32,
631    child: f32,
632    allows_overflow: bool,
633) -> f32 {
634    if !allows_overflow {
635        return alignment.align(available, child);
636    }
637
638    match alignment {
639        cranpose_ui_layout::HorizontalAlignment::Start => 0.0,
640        cranpose_ui_layout::HorizontalAlignment::CenterHorizontally => (available - child) / 2.0,
641        cranpose_ui_layout::HorizontalAlignment::End => available - child,
642    }
643}
644
645fn aligned_y_offset(
646    alignment: cranpose_ui_layout::VerticalAlignment,
647    available: f32,
648    child: f32,
649    allows_overflow: bool,
650) -> f32 {
651    if !allows_overflow {
652        return alignment.align(available, child);
653    }
654
655    match alignment {
656        cranpose_ui_layout::VerticalAlignment::Top => 0.0,
657        cranpose_ui_layout::VerticalAlignment::CenterVertically => (available - child) / 2.0,
658        cranpose_ui_layout::VerticalAlignment::Bottom => available - child,
659    }
660}
661
662fn map_destination_clip_to_source(
663    src_rect: Rect,
664    dst_rect: Rect,
665    clipped_dst_rect: Rect,
666) -> Option<Rect> {
667    if src_rect.width <= 0.0
668        || src_rect.height <= 0.0
669        || dst_rect.width <= 0.0
670        || dst_rect.height <= 0.0
671        || clipped_dst_rect.width <= 0.0
672        || clipped_dst_rect.height <= 0.0
673    {
674        return None;
675    }
676
677    let scale_x = src_rect.width / dst_rect.width;
678    let scale_y = src_rect.height / dst_rect.height;
679
680    let src_min_x = src_rect.x;
681    let src_min_y = src_rect.y;
682    let src_max_x = src_rect.x + src_rect.width;
683    let src_max_y = src_rect.y + src_rect.height;
684
685    let raw_left = src_rect.x + (clipped_dst_rect.x - dst_rect.x) * scale_x;
686    let raw_top = src_rect.y + (clipped_dst_rect.y - dst_rect.y) * scale_y;
687    let raw_right =
688        src_rect.x + ((clipped_dst_rect.x + clipped_dst_rect.width) - dst_rect.x) * scale_x;
689    let raw_bottom =
690        src_rect.y + ((clipped_dst_rect.y + clipped_dst_rect.height) - dst_rect.y) * scale_y;
691
692    let left = raw_left.clamp(src_min_x, src_max_x);
693    let top = raw_top.clamp(src_min_y, src_max_y);
694    let right = raw_right.clamp(src_min_x, src_max_x);
695    let bottom = raw_bottom.clamp(src_min_y, src_max_y);
696    let width = right - left;
697    let height = bottom - top;
698
699    if width <= 0.0 || height <= 0.0 {
700        None
701    } else {
702        Some(Rect {
703            x: left,
704            y: top,
705            width,
706            height,
707        })
708    }
709}
710
711fn image_destination_clip(
712    src_size: Size,
713    container_size: Size,
714    alignment: Alignment,
715    content_scale: ContentScale,
716) -> Option<(Rect, Rect)> {
717    let dst_rect = destination_rect(src_size, container_size, alignment, content_scale);
718    if dst_rect.width <= 0.0 || dst_rect.height <= 0.0 {
719        return None;
720    }
721
722    let container_rect = Rect::from_size(container_size);
723    let clipped_dst_rect = dst_rect.intersect(container_rect)?;
724    Some((dst_rect, clipped_dst_rect))
725}
726
727fn draw_bitmap_painter(
728    scope: &mut dyn DrawScope,
729    bitmap: ImageBitmap,
730    intrinsic_size: Size,
731    alignment: Alignment,
732    content_scale: ContentScale,
733    alpha: f32,
734    color_filter: Option<ColorFilter>,
735) {
736    let container_size = scope.size();
737    let Some((dst_rect, clipped_dst_rect)) =
738        image_destination_clip(intrinsic_size, container_size, alignment, content_scale)
739    else {
740        return;
741    };
742    let full_src_rect = Rect::from_size(Size::new(bitmap.width() as f32, bitmap.height() as f32));
743    let Some(clipped_src_rect) =
744        map_destination_clip_to_source(full_src_rect, dst_rect, clipped_dst_rect)
745    else {
746        return;
747    };
748    scope.draw_image_src_sampled(
749        bitmap,
750        clipped_src_rect,
751        clipped_dst_rect,
752        alpha,
753        color_filter,
754        ImageSampling::Linear,
755    );
756}
757
758fn draw_bitmap_region_painter(
759    scope: &mut dyn DrawScope,
760    bitmap: ImageBitmap,
761    source: Rect,
762    alignment: Alignment,
763    content_scale: ContentScale,
764    alpha: f32,
765    color_filter: Option<ColorFilter>,
766    sampling: ImageSampling,
767) {
768    let source_size = Size::new(source.width.max(0.0), source.height.max(0.0));
769    let Some((dst_rect, clipped_dst_rect)) =
770        image_destination_clip(source_size, scope.size(), alignment, content_scale)
771    else {
772        return;
773    };
774    let Some(clipped_source) = map_destination_clip_to_source(source, dst_rect, clipped_dst_rect)
775    else {
776        return;
777    };
778    scope.draw_image_src_sampled(
779        bitmap,
780        clipped_source,
781        clipped_dst_rect,
782        alpha,
783        color_filter,
784        sampling,
785    );
786}
787
788/// Draws a list of source-to-destination quads, clipped to the container.
789///
790/// Every fill that is not a plain scale — tiling, nine-patch — reduces to this,
791/// so the clipping rule and the sampling choice are stated once.
792fn draw_patch_quads(
793    scope: &mut dyn DrawScope,
794    bitmap: &ImageBitmap,
795    quads: &[PatchQuad],
796    container: Rect,
797    alpha: f32,
798    color_filter: Option<ColorFilter>,
799    sampling: ImageSampling,
800) {
801    for quad in quads {
802        let Some(clipped_destination) = intersect(quad.destination, container) else {
803            continue;
804        };
805        let Some(clipped_source) =
806            map_destination_clip_to_source(quad.source, quad.destination, clipped_destination)
807        else {
808            continue;
809        };
810        scope.draw_image_src_sampled(
811            bitmap.clone(),
812            clipped_source,
813            clipped_destination,
814            alpha,
815            color_filter,
816            sampling,
817        );
818    }
819}
820
821fn intersect(rect: Rect, bounds: Rect) -> Option<Rect> {
822    let left = rect.x.max(bounds.x);
823    let top = rect.y.max(bounds.y);
824    let right = (rect.x + rect.width).min(bounds.x + bounds.width);
825    let bottom = (rect.y + rect.height).min(bounds.y + bounds.height);
826    if right <= left || bottom <= top {
827        return None;
828    }
829    Some(Rect {
830        x: left,
831        y: top,
832        width: right - left,
833        height: bottom - top,
834    })
835}
836
837/// Draws a tiled painter across the whole container.
838///
839/// Content scale and alignment do not apply: a tiled fill covers its bounds by
840/// definition, and scaling the source would defeat the reason for tiling it.
841fn draw_bitmap_tiled_painter(
842    scope: &mut dyn DrawScope,
843    bitmap: ImageBitmap,
844    source: Rect,
845    alpha: f32,
846    color_filter: Option<ColorFilter>,
847    sampling: ImageSampling,
848) {
849    let container = Rect::from_size(scope.size());
850    let quads = tile_quads(source, container);
851    draw_patch_quads(
852        scope,
853        &bitmap,
854        &quads,
855        container,
856        alpha,
857        color_filter,
858        sampling,
859    );
860}
861
862/// Draws a nine-patch painter across the whole container.
863///
864/// Like tiling, this fills its bounds by construction, so content scale and
865/// alignment have nothing left to decide.
866#[expect(clippy::too_many_arguments)]
867fn draw_nine_patch_painter(
868    scope: &mut dyn DrawScope,
869    bitmap: ImageBitmap,
870    source: Rect,
871    insets: NinePatchInsets,
872    center: PatchFill,
873    edges: PatchFill,
874    alpha: f32,
875    color_filter: Option<ColorFilter>,
876    sampling: ImageSampling,
877) {
878    let container = Rect::from_size(scope.size());
879    let quads = nine_patch_quads(source, container, insets, center, edges);
880    draw_patch_quads(
881        scope,
882        &bitmap,
883        &quads,
884        container,
885        alpha,
886        color_filter,
887        sampling,
888    );
889}
890
891fn draw_svg_painter(
892    scope: &mut dyn DrawScope,
893    svg: SvgPainter,
894    intrinsic_size: Size,
895    alignment: Alignment,
896    content_scale: ContentScale,
897    alpha: f32,
898    color_filter: Option<ColorFilter>,
899) {
900    let container_size = scope.size();
901    let Some((dst_rect, clipped_dst_rect)) =
902        image_destination_clip(intrinsic_size, container_size, alignment, content_scale)
903    else {
904        return;
905    };
906    let density = crate::render_state::current_density();
907    let pixel_size = Size::new(dst_rect.width * density, dst_rect.height * density);
908    let bitmap = match svg.rasterize(pixel_size) {
909        Ok(bitmap) => bitmap,
910        Err(error) => {
911            log::warn!("failed to rasterize SVG painter: {error}");
912            return;
913        }
914    };
915    let full_src_rect = Rect::from_size(Size::new(bitmap.width() as f32, bitmap.height() as f32));
916    let Some(clipped_src_rect) =
917        map_destination_clip_to_source(full_src_rect, dst_rect, clipped_dst_rect)
918    else {
919        return;
920    };
921    scope.draw_image_src_sampled(
922        bitmap,
923        clipped_src_rect,
924        clipped_dst_rect,
925        alpha,
926        color_filter,
927        ImageSampling::Linear,
928    );
929}
930
931#[cfg(feature = "svg")]
932fn svg_raster_key(pixel_size: Size) -> Result<SvgRasterKey, SvgPainterError> {
933    let width = svg_raster_axis(pixel_size.width)?;
934    let height = svg_raster_axis(pixel_size.height)?;
935    width
936        .checked_mul(height)
937        .and_then(|value| value.checked_mul(4))
938        .ok_or(SvgPainterError::RasterDimensionsTooLarge)?;
939    Ok(SvgRasterKey { width, height })
940}
941
942#[cfg(feature = "svg")]
943fn svg_raster_axis(value: f32) -> Result<u32, SvgPainterError> {
944    if !value.is_finite() || value <= 0.0 {
945        return Err(SvgPainterError::InvalidRasterDimensions);
946    }
947
948    let rounded = value.ceil();
949    if rounded > u32::MAX as f32 {
950        return Err(SvgPainterError::RasterDimensionsTooLarge);
951    }
952    Ok(rounded as u32)
953}
954
955/// Displays a painter with an optional accessible description.
956///
957/// Images use the image accessibility role unless `modifier` supplies another role.
958/// Without a description or modifier semantics, the image is decorative.
959#[composable]
960pub fn Image<P>(
961    painter: P,
962    content_description: Option<String>,
963    modifier: Modifier,
964    alignment: Alignment,
965    content_scale: ContentScale,
966    alpha: f32,
967    color_filter: Option<ColorFilter>,
968) -> NodeId
969where
970    P: Into<Painter> + Clone + PartialEq + 'static,
971{
972    let painter = painter.into();
973    let intrinsic_dp = painter.intrinsic_size();
974    let draw_alpha = alpha.clamp(0.0, 1.0);
975
976    let semantics_modifier = Modifier::empty().semantics(move |config| {
977        config.content_description.clone_from(&content_description);
978    });
979
980    let image_modifier = semantics_modifier
981        .then(modifier)
982        .semantics(|config| {
983            if config.role.is_none()
984                && config
985                    .content_description
986                    .as_ref()
987                    .is_some_and(|label| !label.trim().is_empty())
988            {
989                config.role = Some(crate::SemanticsWidgetRole::Image);
990            }
991        })
992        .draw_behind(move |scope: &mut dyn DrawScope| {
993            if draw_alpha <= 0.0 {
994                return;
995            }
996            let container_size = scope.size();
997            if container_size.width <= 0.0 || container_size.height <= 0.0 {
998                return;
999            }
1000            match &painter.kind {
1001                PainterKind::Bitmap(bitmap) => draw_bitmap_painter(
1002                    scope,
1003                    bitmap.clone(),
1004                    intrinsic_dp,
1005                    alignment,
1006                    content_scale,
1007                    draw_alpha,
1008                    color_filter,
1009                ),
1010                PainterKind::BitmapRegion {
1011                    bitmap,
1012                    source,
1013                    sampling,
1014                } => draw_bitmap_region_painter(
1015                    scope,
1016                    bitmap.clone(),
1017                    source.rect(),
1018                    alignment,
1019                    content_scale,
1020                    draw_alpha,
1021                    color_filter,
1022                    *sampling,
1023                ),
1024                PainterKind::BitmapTiled {
1025                    bitmap,
1026                    source,
1027                    sampling,
1028                } => draw_bitmap_tiled_painter(
1029                    scope,
1030                    bitmap.clone(),
1031                    source.rect(),
1032                    draw_alpha,
1033                    color_filter,
1034                    *sampling,
1035                ),
1036                PainterKind::NinePatch {
1037                    bitmap,
1038                    source,
1039                    insets,
1040                    center,
1041                    edges,
1042                    sampling,
1043                } => draw_nine_patch_painter(
1044                    scope,
1045                    bitmap.clone(),
1046                    source.rect(),
1047                    insets.insets(),
1048                    *center,
1049                    *edges,
1050                    draw_alpha,
1051                    color_filter,
1052                    *sampling,
1053                ),
1054                PainterKind::Svg(svg) => draw_svg_painter(
1055                    scope,
1056                    svg.clone(),
1057                    intrinsic_dp,
1058                    alignment,
1059                    content_scale,
1060                    draw_alpha,
1061                    color_filter,
1062                ),
1063            }
1064        });
1065
1066    Layout(
1067        image_modifier,
1068        ImageMeasurePolicy {
1069            intrinsic_size: intrinsic_dp,
1070        },
1071        || {},
1072    )
1073}
1074
1075#[cfg(test)]
1076#[path = "tests/image_tests.rs"]
1077mod tests;