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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use crate::{
    Color, ContentMode, CornerRounding, DrawWithTooltips, EdgeInsets, EventCtx, GeomBatch,
    JustDraw, RewriteColor, ScreenDims, ScreenPt, Text, Widget,
};
use geom::{Bounds, Polygon, Pt2D};

use std::borrow::Cow;

/// A stylable UI component builder which presents vector graphics from an [`ImageSource`].
#[derive(Clone, Debug, Default)]
pub struct Image<'a, 'c> {
    source: Option<Cow<'c, ImageSource<'a>>>,
    tooltip: Option<Text>,
    color: Option<RewriteColor>,
    content_mode: Option<ContentMode>,
    corner_rounding: Option<CornerRounding>,
    padding: Option<EdgeInsets>,
    bg_color: Option<Color>,
    dims: Option<ScreenDims>,
}

/// The visual
#[derive(Clone, Debug)]
pub enum ImageSource<'a> {
    /// Path to an SVG file
    Path(&'a str),

    /// UTF-8 encoded bytes of an SVG
    Bytes { bytes: &'a [u8], cache_key: &'a str },

    /// Previously rendered graphics, in the form of a [`GeomBatch`], can
    /// be packaged as an `Image`.
    GeomBatch(GeomBatch, geom::Bounds),
}

impl ImageSource<'_> {
    /// Process `self` into a [`GeomBatch`].
    ///
    /// The underlying implementation makes use of caching to avoid re-parsing SVGs.
    pub fn load(&self, prerender: &crate::Prerender) -> (GeomBatch, geom::Bounds) {
        use crate::svg;
        match self {
            ImageSource::Path(image_path) => svg::load_svg(prerender, image_path),
            ImageSource::Bytes { bytes, cache_key } => {
                svg::load_svg_bytes(prerender, cache_key, bytes).unwrap_or_else(|_| {
                    panic!("Failed to load svg from bytes. cache_key: {}", cache_key)
                })
            }
            ImageSource::GeomBatch(geom_batch, bounds) => (geom_batch.clone(), *bounds),
        }
    }
}

impl<'a, 'c> Image<'a, 'c> {
    /// An `Image` with no renderable content. Useful for starting a template for creating
    /// several similar images using a builder pattern.
    pub fn empty() -> Self {
        Self {
            ..Default::default()
        }
    }

    /// Create an SVG `Image`, read from `filename`, which is colored to match `Style.icon_fg`
    pub fn from_path(filename: &'a str) -> Self {
        Self {
            source: Some(Cow::Owned(ImageSource::Path(filename))),
            ..Default::default()
        }
    }

    /// Create an SVG `Image`, read from `filename`.
    ///
    /// The image's intrinsic colors will be used, it will not be tinted like `Image::icon`, unless
    /// you also call `color()`
    pub fn untinted(filename: &'a str) -> Self {
        Self::from_path(filename).color(RewriteColor::NoOp)
    }

    /// Create a new SVG `Image` from bytes.
    ///
    /// * `labeled_bytes`: is a (`label`, `bytes`) tuple you can generate with
    ///   [`include_labeled_bytes!`]
    /// * `label`: a label to describe the bytes for debugging purposes
    /// * `bytes`: UTF-8 encoded bytes of the SVG
    pub fn from_bytes(labeled_bytes: (&'a str, &'a [u8])) -> Self {
        Self {
            source: Some(Cow::Owned(ImageSource::Bytes {
                cache_key: labeled_bytes.0,
                bytes: labeled_bytes.1,
            })),
            ..Default::default()
        }
    }

    /// Create a new `Image` from a [`GeomBatch`].
    ///
    /// By default, the given `bounds` will be used for padding, background, etc.
    pub fn from_batch(batch: GeomBatch, bounds: Bounds) -> Self {
        Self {
            source: Some(Cow::Owned(ImageSource::GeomBatch(batch, bounds))),
            dims: Some(bounds.into()),
            ..Default::default()
        }
    }

    /// Set a new source for the `Image`'s data.
    ///
    /// This will replace any previously set source.
    pub fn source(mut self, source: ImageSource<'a>) -> Self {
        self.source = Some(Cow::Owned(source));
        self
    }

    /// Set the path to an SVG file for the image.
    ///
    /// This will replace any image source previously set.
    pub fn source_path(self, path: &'a str) -> Self {
        self.source(ImageSource::Path(path))
    }

    /// Set the bytes for the image.
    ///
    /// This will replace any image source previously set.
    ///
    /// * `labeled_bytes`: is a (`label`, `bytes`) tuple you can generate with
    ///   [`include_labeled_bytes!`]
    /// * `label`: a label to describe the bytes for debugging purposes
    /// * `bytes`: UTF-8 encoded bytes of the SVG
    pub fn source_bytes(self, labeled_bytes: (&'a str, &'a [u8])) -> Self {
        let (label, bytes) = labeled_bytes;
        self.source(ImageSource::Bytes {
            bytes,
            cache_key: label,
        })
    }

    /// Set the GeomBatch for the button.
    ///
    /// This will replace any image source previously set.
    ///
    /// This method is useful when doing more complex transforms. For example, to re-write more than
    /// one color for your image, do so externally and pass in the resultant GeomBatch here.
    pub fn source_batch(self, batch: GeomBatch, bounds: geom::Bounds) -> Self {
        self.source(ImageSource::GeomBatch(batch, bounds))
    }

    /// Add a tooltip to appear when hovering over the image.
    pub fn tooltip(mut self, tooltip: impl Into<Text>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }

    /// Create a new `Image` based on `self`, but overriding with any values set on `other`.
    pub fn merged_image_style(&'c self, other: &'c Self) -> Self {
        let source_cow: Option<&Cow<'c, ImageSource>> =
            other.source.as_ref().or_else(|| self.source.as_ref());
        let source: Option<Cow<'c, ImageSource>> = source_cow.map(|source: &Cow<ImageSource>| {
            let source: &ImageSource = source;
            Cow::Borrowed(source)
        });

        Self {
            source,
            // PERF: we could make tooltip a cow to eliminate clone
            tooltip: other.tooltip.clone().or_else(|| self.tooltip.clone()),
            color: other.color.or(self.color),
            content_mode: other.content_mode.or(self.content_mode),
            corner_rounding: other.corner_rounding.or(self.corner_rounding),
            padding: other.padding.or(self.padding),
            bg_color: other.bg_color.or(self.bg_color),
            dims: other.dims.or(self.dims),
        }
    }

    /// Rewrite the color of the image.
    pub fn color<RWC: Into<RewriteColor>>(mut self, value: RWC) -> Self {
        self.color = Some(value.into());
        self
    }

    /// Set a background color for the image. Has no effect unless custom `dims` are explicitly set.
    pub fn bg_color(mut self, value: Color) -> Self {
        self.bg_color = Some(value);
        self
    }

    /// Scale the bounds containing the image. If `dims` are not specified, the image's intrinsic
    /// size will be used, but padding and background settings will be ignored.
    ///
    /// See [`Self::content_mode`] to control how the image scales to fit its custom bounds.
    pub fn dims<D: Into<ScreenDims>>(mut self, dims: D) -> Self {
        self.dims = Some(dims.into());
        self
    }

    /// If a custom `dims` was set, control how the image should be scaled to its new bounds.
    ///
    /// If `dims` were not specified, the image will not be scaled, so content_mode has no
    /// affect.
    ///
    /// The default, [`ContentMode::ScaleAspectFit`] will only grow as much as it can while
    /// maintaining its aspect ratio and not exceeding its bounds
    pub fn content_mode(mut self, value: ContentMode) -> Self {
        self.content_mode = Some(value);
        self
    }

    /// Set independent rounding for each of the image's corners. Has no effect unless custom
    /// `dims` are explicitly set.
    pub fn corner_rounding<R: Into<CornerRounding>>(mut self, value: R) -> Self {
        self.corner_rounding = Some(value.into());
        self
    }

    /// Set padding for the image. Has no effect unless custom `dims` are explicitly set.
    pub fn padding<EI: Into<EdgeInsets>>(mut self, value: EI) -> Self {
        self.padding = Some(value.into());
        self
    }

    /// Padding above the image. Has no effect unless custom `dims` are explicitly set.
    pub fn padding_top(mut self, new_value: f64) -> Self {
        let mut padding = self.padding.unwrap_or_default();
        padding.top = new_value;
        self.padding = Some(padding);
        self
    }

    /// Padding to the left of the image. Has no effect unless custom `dims` are explicitly set.
    pub fn padding_left(mut self, new_value: f64) -> Self {
        let mut padding = self.padding.unwrap_or_default();
        padding.left = new_value;
        self.padding = Some(padding);
        self
    }

    /// Padding below the image. Has no effect unless custom `dims` are explicitly set.
    pub fn padding_bottom(mut self, new_value: f64) -> Self {
        let mut padding = self.padding.unwrap_or_default();
        padding.bottom = new_value;
        self.padding = Some(padding);
        self
    }

    /// Padding to the right of the image. Has no effect unless custom `dims` are explicitly set.
    pub fn padding_right(mut self, new_value: f64) -> Self {
        let mut padding = self.padding.unwrap_or_default();
        padding.right = new_value;
        self.padding = Some(padding);
        self
    }

    /// Render the `Image` and any styling (padding, background, etc.) to a `GeomBatch`.
    pub fn build_batch(&self, ctx: &EventCtx) -> Option<(GeomBatch, Bounds)> {
        // TODO: unwrap/panic if source is empty?
        self.source.as_ref().map(|source| {
            let (mut image_batch, image_bounds) = source.load(ctx.prerender);

            image_batch = image_batch.color(
                self.color
                    .unwrap_or_else(|| RewriteColor::ChangeAll(ctx.style().icon_fg)),
            );

            match self.dims {
                None => {
                    // Preserve any padding intrinsic to the SVG.
                    image_batch.push(Color::CLEAR, image_bounds.get_rectangle());
                    (image_batch, image_bounds)
                }
                Some(image_dims) => {
                    if image_bounds.width() != 0.0 && image_bounds.height() != 0.0 {
                        let (x_factor, y_factor) = (
                            image_dims.width / image_bounds.width(),
                            image_dims.height / image_bounds.height(),
                        );
                        image_batch = match self.content_mode.unwrap_or_default() {
                            ContentMode::ScaleToFill => image_batch.scale_xy(x_factor, y_factor),
                            ContentMode::ScaleAspectFit => {
                                image_batch.scale(x_factor.min(y_factor))
                            }
                            ContentMode::ScaleAspectFill => {
                                image_batch.scale(x_factor.max(y_factor))
                            }
                        };
                    }

                    let image_corners = self.corner_rounding.unwrap_or_default();
                    let padding = self.padding.unwrap_or_default();

                    let mut container_batch = GeomBatch::new();
                    let container_bounds = Bounds {
                        min_x: 0.0,
                        min_y: 0.0,
                        max_x: image_dims.width + padding.left + padding.right,
                        max_y: image_dims.height + padding.top + padding.bottom,
                    };
                    let container = match image_corners {
                        CornerRounding::FullyRounded => {
                            Polygon::pill(container_bounds.width(), container_bounds.height())
                        }
                        CornerRounding::CornerRadii(image_corners) => Polygon::rounded_rectangle(
                            container_bounds.width(),
                            container_bounds.height(),
                            image_corners,
                        ),
                    };

                    let image_bg = self.bg_color.unwrap_or(Color::CLEAR);
                    container_batch.push(image_bg, container);

                    let center = Pt2D::new(
                        image_dims.width / 2.0 + padding.left,
                        image_dims.height / 2.0 + padding.top,
                    );
                    image_batch = image_batch.autocrop().centered_on(center);
                    container_batch.append(image_batch);

                    (container_batch, container_bounds)
                }
            }
        })
    }

    pub fn into_widget(self, ctx: &EventCtx) -> Widget {
        match self.build_batch(ctx) {
            None => Widget::nothing(),
            Some((batch, bounds)) => {
                if let Some(tooltip) = self.tooltip {
                    DrawWithTooltips::new_widget(
                        ctx,
                        batch,
                        vec![(bounds.get_rectangle(), tooltip, None)],
                        Box::new(|_| GeomBatch::new()),
                    )
                } else {
                    Widget::new(Box::new(JustDraw {
                        dims: ScreenDims::new(bounds.width(), bounds.height()),
                        draw: ctx.upload(batch),
                        top_left: ScreenPt::new(0.0, 0.0),
                    }))
                }
            }
        }
    }
}