1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
//! A widget that displays an image/texture.

use figures::units::{Px, UPx};
use figures::{FloatConversion, IntoSigned, IntoUnsigned, Point, Rect, ScreenScale, Size, Zero};
use kludgine::shapes::{CornerRadii, Shape};
use kludgine::{
    AnyTexture, CollectedTexture, Color, LazyTexture, SharedTexture, Texture, TextureRegion,
};

use crate::animation::ZeroToOne;
use crate::context::{LayoutContext, Trackable};
use crate::styles::Dimension;
use crate::value::{IntoValue, Source, Value};
use crate::widget::Widget;
use crate::ConstraintLimit;

/// A widget that displays an image/texture.
#[derive(Debug)]
pub struct Image {
    /// The texture to render.
    pub contents: Value<AnyTexture>,
    /// The scaling strategy to apply.
    pub scaling: Value<ImageScaling>,
    /// The opacity to render the image with.
    pub opacity: Value<ZeroToOne>,
}

impl Image {
    /// Returns a new image widget that renders `contents`, using the default
    /// [`ImageScaling`] strategy.
    pub fn new(contents: impl IntoValue<AnyTexture>) -> Self {
        Self {
            contents: contents.into_value(),
            scaling: Value::default(),
            opacity: Value::Constant(ZeroToOne::ONE),
        }
    }

    /// Applies the `scaling` strategies and returns self.
    #[must_use]
    pub fn scaling(mut self, scaling: impl IntoValue<ImageScaling>) -> Self {
        self.scaling = scaling.into_value();
        self
    }

    /// Applies `opacity` when drawing the image, returns self.
    #[must_use]
    pub fn opacity(mut self, opacity: impl IntoValue<ZeroToOne>) -> Self {
        self.opacity = opacity.into_value();
        self
    }

    /// Applies the aspect-fit scaling strategy and returns self.
    ///
    /// The aspect-fit scaling strategy scales the image to be the largest size
    /// it can be without clipping. Any remaining whitespace will be at the
    /// right or bottom edge.
    ///
    /// To apply a different orientation for the whitespace, use
    /// [`Self::aspect_fit_around`].
    #[must_use]
    pub fn aspect_fit(self) -> Self {
        self.aspect_fit_around(Size::ZERO)
    }

    /// Applies the aspect-fit scaling strategy and returns self.
    ///
    /// The aspect-fit scaling strategy scales the image to be the largest size
    /// it can be without clipping. Any remaining whitespace will be divided
    /// using the ratio `orientation`.
    #[must_use]
    pub fn aspect_fit_around(self, orientation: Size<ZeroToOne>) -> Self {
        self.scaling(ImageScaling::Aspect {
            mode: Aspect::Fit,
            orientation,
        })
    }

    /// Applies the aspect-fill scaling strategy and returns self.
    ///
    /// The aspect-fill scaling strategy scales the image to be the smallest
    /// size it can be to cover the entire surface. The bottom or right sides of
    /// the image will be clipped.
    ///
    /// To apply a different orientation for the clipping, use
    /// [`Self::aspect_fill_around`].
    #[must_use]
    pub fn aspect_fill(self) -> Self {
        self.aspect_fill_around(Size::ZERO)
    }

    /// Applies the aspect-fill scaling strategy and returns self.
    ///
    /// The aspect-fill scaling strategy scales the image to be the smallest
    /// size it can be to cover the entire surface. The side that is cropped
    /// will be positioned using `orientation`.
    #[must_use]
    pub fn aspect_fill_around(self, orientation: Size<ZeroToOne>) -> Self {
        self.scaling(ImageScaling::Aspect {
            mode: Aspect::Fill,
            orientation,
        })
    }

    /// Applies the stretch scaling strategy and returns self.
    ///
    /// The stretch scaling strategy stretches the image to fill the surface,
    /// ignoring the aspect ratio.
    #[must_use]
    pub fn stretch(self) -> Self {
        self.scaling(ImageScaling::Stretch)
    }

    /// Applies a scaling factor strategy and returns self.
    ///
    /// The image will be displayed at a scaling factor of `amount`. In this
    /// mode, the widget will request that its size be the size of the contained
    /// image.
    #[must_use]
    pub fn scaled(self, amount: impl IntoValue<f32>) -> Self {
        self.scaling(match amount.into_value() {
            Value::Constant(amount) => Value::Constant(ImageScaling::Scale(amount)),
            Value::Dynamic(amount) => Value::Dynamic(amount.map_each_cloned(ImageScaling::Scale)),
        })
    }

    fn calculate_image_rect(
        &self,
        texture: &AnyTexture,
        within_size: Size<UPx>,
        context: &mut crate::context::GraphicsContext<'_, '_, '_, '_>,
    ) -> Rect<Px> {
        let within_size = within_size.into_signed();
        let size = texture.size().into_signed();
        match self.scaling.get_tracking_invalidate(context) {
            ImageScaling::Aspect { mode, orientation } => {
                let scale_width = within_size.width.into_float() / size.width.into_float();
                let scale_height = within_size.height.into_float() / size.height.into_float();

                let effective_scale = match mode {
                    Aspect::Fill => scale_width.max(scale_height),
                    Aspect::Fit => scale_width.min(scale_height),
                };
                let scaled = size * effective_scale;

                let x = (within_size.width - scaled.width) * *orientation.width;
                let y = (within_size.height - scaled.height) * *orientation.height;

                Rect::new(Point::new(x, y), scaled)
            }
            ImageScaling::Stretch => within_size.into(),
            ImageScaling::Scale(factor) => {
                let size = size.map(|px| px * factor);
                size.into()
            }
        }
    }
}

impl Widget for Image {
    fn redraw(&mut self, context: &mut crate::context::GraphicsContext<'_, '_, '_, '_>) {
        self.contents.invalidate_when_changed(context);
        let opacity = self.opacity.get_tracking_redraw(context);
        let radii = context.get(&ImageCornerRadius);
        let radii = radii.map(|r| r.into_px(context.gfx.scale()));

        self.contents.map(|texture| {
            let rect = self.calculate_image_rect(texture, context.gfx.size(), context);
            if radii.is_zero() {
                context.gfx.draw_texture(texture, rect, opacity);
            } else {
                context.gfx.draw_textured_shape(
                    &Shape::textured_round_rect(
                        rect,
                        radii,
                        Rect::from(texture.size()),
                        Color::WHITE,
                    ),
                    texture,
                    opacity,
                );
            }
        });
    }

    fn layout(
        &mut self,
        available_space: Size<ConstraintLimit>,
        context: &mut LayoutContext<'_, '_, '_, '_>,
    ) -> Size<UPx> {
        let rect = self.contents.map(|texture| {
            self.calculate_image_rect(texture, available_space.map(ConstraintLimit::max), context)
        });
        rect.size.into_unsigned()
    }
}

/// A scaling strategy for an [`Image`] widget.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ImageScaling {
    /// Scales the image keeping the aspect ratio the same.
    Aspect {
        /// The strategy to use to pick a scaling factor.
        mode: Aspect,
        /// The orientation to either crop or align using.
        orientation: Size<ZeroToOne>,
    },

    /// The stretch scaling strategy stretches the image to fill the surface,
    /// ignoring the aspect ratio.
    Stretch,

    /// The image will be displayed at a scaling factor of the contained `f32`.
    /// In this mode, the widget will request that its size be the size of the
    /// contained image.
    Scale(f32),
}

impl Default for ImageScaling {
    /// Returns `ImageScaling::Scale(1.)`.
    fn default() -> Self {
        Self::Scale(1.)
    }
}

impl IntoValue<AnyTexture> for Texture {
    fn into_value(self) -> Value<AnyTexture> {
        Value::Constant(AnyTexture::from(self))
    }
}

impl IntoValue<AnyTexture> for LazyTexture {
    fn into_value(self) -> Value<AnyTexture> {
        Value::Constant(AnyTexture::from(self))
    }
}

impl IntoValue<AnyTexture> for SharedTexture {
    fn into_value(self) -> Value<AnyTexture> {
        Value::Constant(AnyTexture::from(self))
    }
}

impl IntoValue<AnyTexture> for CollectedTexture {
    fn into_value(self) -> Value<AnyTexture> {
        Value::Constant(AnyTexture::from(self))
    }
}

impl IntoValue<AnyTexture> for TextureRegion {
    fn into_value(self) -> Value<AnyTexture> {
        Value::Constant(AnyTexture::from(self))
    }
}

/// An aspect mode for scaling an [`Image`].
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
pub enum Aspect {
    /// The aspect-fit scaling strategy scales the image to be the largest size
    /// it can be without clipping.
    #[default]
    Fit,

    /// The aspect-fill scaling strategy scales the image to be the smallest
    /// size it can be to cover the entire surface.
    Fill,
}

define_components! {
    Image {
        /// The corner radius to use to clip when rendering an [`Image`].
        ImageCornerRadius(CornerRadii<Dimension>, "corner_radius", CornerRadii::ZERO)
    }
}