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
600/// Where the painter draws in the container, as Compose's painter modifier
601/// places it: scaled, then aligned on sizes rounded to whole device pixels
602/// of `density`, overflowing the container where the scale makes it larger.
603fn destination_rect(
604    src_size: Size,
605    dst_size: Size,
606    alignment: Alignment,
607    content_scale: ContentScale,
608    density: f32,
609) -> Rect {
610    use cranpose_ui_layout::round_to_px;
611
612    let draw_size = content_scale.scaled_size(src_size, dst_size);
613    Rect {
614        x: alignment.horizontal.align(
615            round_to_px(dst_size.width, density),
616            round_to_px(draw_size.width, density),
617            density,
618        ),
619        y: alignment.vertical.align(
620            round_to_px(dst_size.height, density),
621            round_to_px(draw_size.height, density),
622            density,
623        ),
624        width: draw_size.width,
625        height: draw_size.height,
626    }
627}
628
629fn map_destination_clip_to_source(
630    src_rect: Rect,
631    dst_rect: Rect,
632    clipped_dst_rect: Rect,
633) -> Option<Rect> {
634    if src_rect.width <= 0.0
635        || src_rect.height <= 0.0
636        || dst_rect.width <= 0.0
637        || dst_rect.height <= 0.0
638        || clipped_dst_rect.width <= 0.0
639        || clipped_dst_rect.height <= 0.0
640    {
641        return None;
642    }
643
644    let scale_x = src_rect.width / dst_rect.width;
645    let scale_y = src_rect.height / dst_rect.height;
646
647    let src_min_x = src_rect.x;
648    let src_min_y = src_rect.y;
649    let src_max_x = src_rect.x + src_rect.width;
650    let src_max_y = src_rect.y + src_rect.height;
651
652    let raw_left = src_rect.x + (clipped_dst_rect.x - dst_rect.x) * scale_x;
653    let raw_top = src_rect.y + (clipped_dst_rect.y - dst_rect.y) * scale_y;
654    let raw_right =
655        src_rect.x + ((clipped_dst_rect.x + clipped_dst_rect.width) - dst_rect.x) * scale_x;
656    let raw_bottom =
657        src_rect.y + ((clipped_dst_rect.y + clipped_dst_rect.height) - dst_rect.y) * scale_y;
658
659    let left = raw_left.clamp(src_min_x, src_max_x);
660    let top = raw_top.clamp(src_min_y, src_max_y);
661    let right = raw_right.clamp(src_min_x, src_max_x);
662    let bottom = raw_bottom.clamp(src_min_y, src_max_y);
663    let width = right - left;
664    let height = bottom - top;
665
666    if width <= 0.0 || height <= 0.0 {
667        None
668    } else {
669        Some(Rect {
670            x: left,
671            y: top,
672            width,
673            height,
674        })
675    }
676}
677
678fn image_destination_clip(
679    src_size: Size,
680    container_size: Size,
681    alignment: Alignment,
682    content_scale: ContentScale,
683    density: f32,
684) -> Option<(Rect, Rect)> {
685    let dst_rect = destination_rect(src_size, container_size, alignment, content_scale, density);
686    if dst_rect.width <= 0.0 || dst_rect.height <= 0.0 {
687        return None;
688    }
689
690    let container_rect = Rect::from_size(container_size);
691    let clipped_dst_rect = dst_rect.intersect(container_rect)?;
692    Some((dst_rect, clipped_dst_rect))
693}
694
695fn draw_bitmap_painter(
696    scope: &mut dyn DrawScope,
697    bitmap: ImageBitmap,
698    intrinsic_size: Size,
699    alignment: Alignment,
700    content_scale: ContentScale,
701    alpha: f32,
702    color_filter: Option<ColorFilter>,
703    density: f32,
704) {
705    let container_size = scope.size();
706    let Some((dst_rect, clipped_dst_rect)) = image_destination_clip(
707        intrinsic_size,
708        container_size,
709        alignment,
710        content_scale,
711        density,
712    ) else {
713        return;
714    };
715    let full_src_rect = Rect::from_size(Size::new(bitmap.width() as f32, bitmap.height() as f32));
716    let Some(clipped_src_rect) =
717        map_destination_clip_to_source(full_src_rect, dst_rect, clipped_dst_rect)
718    else {
719        return;
720    };
721    scope.draw_image_src_sampled(
722        bitmap,
723        clipped_src_rect,
724        clipped_dst_rect,
725        alpha,
726        color_filter,
727        ImageSampling::Linear,
728    );
729}
730
731fn draw_bitmap_region_painter(
732    scope: &mut dyn DrawScope,
733    bitmap: ImageBitmap,
734    source: Rect,
735    alignment: Alignment,
736    content_scale: ContentScale,
737    alpha: f32,
738    color_filter: Option<ColorFilter>,
739    sampling: ImageSampling,
740    density: f32,
741) {
742    let source_size = Size::new(source.width.max(0.0), source.height.max(0.0));
743    let Some((dst_rect, clipped_dst_rect)) =
744        image_destination_clip(source_size, scope.size(), alignment, content_scale, density)
745    else {
746        return;
747    };
748    let Some(clipped_source) = map_destination_clip_to_source(source, dst_rect, clipped_dst_rect)
749    else {
750        return;
751    };
752    scope.draw_image_src_sampled(
753        bitmap,
754        clipped_source,
755        clipped_dst_rect,
756        alpha,
757        color_filter,
758        sampling,
759    );
760}
761
762/// Draws a list of source-to-destination quads, clipped to the container.
763///
764/// Every fill that is not a plain scale — tiling, nine-patch — reduces to this,
765/// so the clipping rule and the sampling choice are stated once.
766fn draw_patch_quads(
767    scope: &mut dyn DrawScope,
768    bitmap: &ImageBitmap,
769    quads: &[PatchQuad],
770    container: Rect,
771    alpha: f32,
772    color_filter: Option<ColorFilter>,
773    sampling: ImageSampling,
774) {
775    for quad in quads {
776        let Some(clipped_destination) = intersect(quad.destination, container) else {
777            continue;
778        };
779        let Some(clipped_source) =
780            map_destination_clip_to_source(quad.source, quad.destination, clipped_destination)
781        else {
782            continue;
783        };
784        scope.draw_image_src_sampled(
785            bitmap.clone(),
786            clipped_source,
787            clipped_destination,
788            alpha,
789            color_filter,
790            sampling,
791        );
792    }
793}
794
795fn intersect(rect: Rect, bounds: Rect) -> Option<Rect> {
796    let left = rect.x.max(bounds.x);
797    let top = rect.y.max(bounds.y);
798    let right = (rect.x + rect.width).min(bounds.x + bounds.width);
799    let bottom = (rect.y + rect.height).min(bounds.y + bounds.height);
800    if right <= left || bottom <= top {
801        return None;
802    }
803    Some(Rect {
804        x: left,
805        y: top,
806        width: right - left,
807        height: bottom - top,
808    })
809}
810
811/// Draws a tiled painter across the whole container.
812///
813/// Content scale and alignment do not apply: a tiled fill covers its bounds by
814/// definition, and scaling the source would defeat the reason for tiling it.
815fn draw_bitmap_tiled_painter(
816    scope: &mut dyn DrawScope,
817    bitmap: ImageBitmap,
818    source: Rect,
819    alpha: f32,
820    color_filter: Option<ColorFilter>,
821    sampling: ImageSampling,
822) {
823    let container = Rect::from_size(scope.size());
824    let quads = tile_quads(source, container);
825    draw_patch_quads(
826        scope,
827        &bitmap,
828        &quads,
829        container,
830        alpha,
831        color_filter,
832        sampling,
833    );
834}
835
836/// Draws a nine-patch painter across the whole container.
837///
838/// Like tiling, this fills its bounds by construction, so content scale and
839/// alignment have nothing left to decide.
840#[expect(clippy::too_many_arguments)]
841fn draw_nine_patch_painter(
842    scope: &mut dyn DrawScope,
843    bitmap: ImageBitmap,
844    source: Rect,
845    insets: NinePatchInsets,
846    center: PatchFill,
847    edges: PatchFill,
848    alpha: f32,
849    color_filter: Option<ColorFilter>,
850    sampling: ImageSampling,
851) {
852    let container = Rect::from_size(scope.size());
853    let quads = nine_patch_quads(source, container, insets, center, edges);
854    draw_patch_quads(
855        scope,
856        &bitmap,
857        &quads,
858        container,
859        alpha,
860        color_filter,
861        sampling,
862    );
863}
864
865fn draw_svg_painter(
866    scope: &mut dyn DrawScope,
867    svg: SvgPainter,
868    intrinsic_size: Size,
869    alignment: Alignment,
870    content_scale: ContentScale,
871    alpha: f32,
872    color_filter: Option<ColorFilter>,
873    density: f32,
874) {
875    let container_size = scope.size();
876    let Some((dst_rect, clipped_dst_rect)) = image_destination_clip(
877        intrinsic_size,
878        container_size,
879        alignment,
880        content_scale,
881        density,
882    ) else {
883        return;
884    };
885    let pixel_size = Size::new(dst_rect.width * density, dst_rect.height * density);
886    let bitmap = match svg.rasterize(pixel_size) {
887        Ok(bitmap) => bitmap,
888        Err(error) => {
889            log::warn!("failed to rasterize SVG painter: {error}");
890            return;
891        }
892    };
893    let full_src_rect = Rect::from_size(Size::new(bitmap.width() as f32, bitmap.height() as f32));
894    let Some(clipped_src_rect) =
895        map_destination_clip_to_source(full_src_rect, dst_rect, clipped_dst_rect)
896    else {
897        return;
898    };
899    scope.draw_image_src_sampled(
900        bitmap,
901        clipped_src_rect,
902        clipped_dst_rect,
903        alpha,
904        color_filter,
905        ImageSampling::Linear,
906    );
907}
908
909#[cfg(feature = "svg")]
910fn svg_raster_key(pixel_size: Size) -> Result<SvgRasterKey, SvgPainterError> {
911    let width = svg_raster_axis(pixel_size.width)?;
912    let height = svg_raster_axis(pixel_size.height)?;
913    width
914        .checked_mul(height)
915        .and_then(|value| value.checked_mul(4))
916        .ok_or(SvgPainterError::RasterDimensionsTooLarge)?;
917    Ok(SvgRasterKey { width, height })
918}
919
920#[cfg(feature = "svg")]
921fn svg_raster_axis(value: f32) -> Result<u32, SvgPainterError> {
922    if !value.is_finite() || value <= 0.0 {
923        return Err(SvgPainterError::InvalidRasterDimensions);
924    }
925
926    let rounded = value.ceil();
927    if rounded > u32::MAX as f32 {
928        return Err(SvgPainterError::RasterDimensionsTooLarge);
929    }
930    Ok(rounded as u32)
931}
932
933/// Displays a painter with an optional accessible description.
934///
935/// Images use the image accessibility role unless `modifier` supplies another role.
936/// Without a description or modifier semantics, the image is decorative.
937#[composable]
938pub fn Image<P>(
939    painter: P,
940    content_description: Option<String>,
941    modifier: Modifier,
942    alignment: Alignment,
943    content_scale: ContentScale,
944    alpha: f32,
945    color_filter: Option<ColorFilter>,
946) -> NodeId
947where
948    P: Into<Painter> + Clone + PartialEq + 'static,
949{
950    let painter = painter.into();
951    let intrinsic_dp = painter.intrinsic_size();
952    let draw_alpha = alpha.clamp(0.0, 1.0);
953
954    let semantics_modifier = Modifier::empty().semantics(move |config| {
955        config.content_description.clone_from(&content_description);
956    });
957
958    // The grid the image is aligned on: the composition's, as Text keeps it.
959    let density = crate::density::density().density();
960    let image_modifier = semantics_modifier
961        .then(modifier)
962        .semantics(|config| {
963            if config.role.is_none()
964                && config
965                    .content_description
966                    .as_ref()
967                    .is_some_and(|label| !label.trim().is_empty())
968            {
969                config.role = Some(crate::SemanticsWidgetRole::Image);
970            }
971        })
972        .draw_behind(move |scope: &mut dyn DrawScope| {
973            if draw_alpha <= 0.0 {
974                return;
975            }
976            let container_size = scope.size();
977            if container_size.width <= 0.0 || container_size.height <= 0.0 {
978                return;
979            }
980            match &painter.kind {
981                PainterKind::Bitmap(bitmap) => draw_bitmap_painter(
982                    scope,
983                    bitmap.clone(),
984                    intrinsic_dp,
985                    alignment,
986                    content_scale,
987                    draw_alpha,
988                    color_filter,
989                    density,
990                ),
991                PainterKind::BitmapRegion {
992                    bitmap,
993                    source,
994                    sampling,
995                } => draw_bitmap_region_painter(
996                    scope,
997                    bitmap.clone(),
998                    source.rect(),
999                    alignment,
1000                    content_scale,
1001                    draw_alpha,
1002                    color_filter,
1003                    *sampling,
1004                    density,
1005                ),
1006                PainterKind::BitmapTiled {
1007                    bitmap,
1008                    source,
1009                    sampling,
1010                } => draw_bitmap_tiled_painter(
1011                    scope,
1012                    bitmap.clone(),
1013                    source.rect(),
1014                    draw_alpha,
1015                    color_filter,
1016                    *sampling,
1017                ),
1018                PainterKind::NinePatch {
1019                    bitmap,
1020                    source,
1021                    insets,
1022                    center,
1023                    edges,
1024                    sampling,
1025                } => draw_nine_patch_painter(
1026                    scope,
1027                    bitmap.clone(),
1028                    source.rect(),
1029                    insets.insets(),
1030                    *center,
1031                    *edges,
1032                    draw_alpha,
1033                    color_filter,
1034                    *sampling,
1035                ),
1036                PainterKind::Svg(svg) => draw_svg_painter(
1037                    scope,
1038                    svg.clone(),
1039                    intrinsic_dp,
1040                    alignment,
1041                    content_scale,
1042                    draw_alpha,
1043                    color_filter,
1044                    density,
1045                ),
1046            }
1047        });
1048
1049    Layout(
1050        image_modifier,
1051        ImageMeasurePolicy {
1052            intrinsic_size: intrinsic_dp,
1053        },
1054        || {},
1055    )
1056}
1057
1058#[cfg(test)]
1059#[path = "tests/image_tests.rs"]
1060mod tests;