egui/widgets/
image.rs

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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
use std::{borrow::Cow, sync::Arc, time::Duration};

use emath::{Float as _, Rot2};
use epaint::RectShape;

use crate::{
    load::{Bytes, SizeHint, SizedTexture, TextureLoadResult, TexturePoll},
    pos2, Align2, Color32, Context, Id, Mesh, Painter, Rect, Response, Rounding, Sense, Shape,
    Spinner, Stroke, TextStyle, TextureOptions, Ui, Vec2, Widget,
};

/// A widget which displays an image.
///
/// The task of actually loading the image is deferred to when the `Image` is added to the [`Ui`],
/// and how it is loaded depends on the provided [`ImageSource`]:
///
/// - [`ImageSource::Uri`] will load the image using the [asynchronous loading process][`crate::load`].
/// - [`ImageSource::Bytes`] will also load the image using the [asynchronous loading process][`crate::load`], but with lower latency.
/// - [`ImageSource::Texture`] will use the provided texture.
///
/// See [`crate::load`] for more information.
///
/// ### Examples
/// // Using it in a layout:
/// ```
/// # egui::__run_test_ui(|ui| {
/// ui.add(
///     egui::Image::new(egui::include_image!("../../assets/ferris.png"))
///         .rounding(5.0)
/// );
/// # });
/// ```
///
/// // Using it just to paint:
/// ```
/// # egui::__run_test_ui(|ui| {
/// # let rect = egui::Rect::from_min_size(Default::default(), egui::Vec2::splat(100.0));
/// egui::Image::new(egui::include_image!("../../assets/ferris.png"))
///     .rounding(5.0)
///     .tint(egui::Color32::LIGHT_BLUE)
///     .paint_at(ui, rect);
/// # });
/// ```
///
#[must_use = "You should put this widget in a ui with `ui.add(widget);`"]
#[derive(Debug, Clone)]
pub struct Image<'a> {
    source: ImageSource<'a>,
    texture_options: TextureOptions,
    image_options: ImageOptions,
    sense: Sense,
    size: ImageSize,
    pub(crate) show_loading_spinner: Option<bool>,
}

impl<'a> Image<'a> {
    /// Load the image from some source.
    pub fn new(source: impl Into<ImageSource<'a>>) -> Self {
        fn new_mono(source: ImageSource<'_>) -> Image<'_> {
            let size = if let ImageSource::Texture(tex) = &source {
                // User is probably expecting their texture to have
                // the exact size of the provided `SizedTexture`.
                ImageSize {
                    maintain_aspect_ratio: true,
                    max_size: Vec2::INFINITY,
                    fit: ImageFit::Exact(tex.size),
                }
            } else {
                Default::default()
            };

            Image {
                source,
                texture_options: Default::default(),
                image_options: Default::default(),
                sense: Sense::hover(),
                size,
                show_loading_spinner: None,
            }
        }

        new_mono(source.into())
    }

    /// Load the image from a URI.
    ///
    /// See [`ImageSource::Uri`].
    pub fn from_uri(uri: impl Into<Cow<'a, str>>) -> Self {
        Self::new(ImageSource::Uri(uri.into()))
    }

    /// Load the image from an existing texture.
    ///
    /// See [`ImageSource::Texture`].
    pub fn from_texture(texture: impl Into<SizedTexture>) -> Self {
        Self::new(ImageSource::Texture(texture.into()))
    }

    /// Load the image from some raw bytes.
    ///
    /// For better error messages, use the `bytes://` prefix for the URI.
    ///
    /// See [`ImageSource::Bytes`].
    pub fn from_bytes(uri: impl Into<Cow<'static, str>>, bytes: impl Into<Bytes>) -> Self {
        Self::new(ImageSource::Bytes {
            uri: uri.into(),
            bytes: bytes.into(),
        })
    }

    /// Texture options used when creating the texture.
    #[inline]
    pub fn texture_options(mut self, texture_options: TextureOptions) -> Self {
        self.texture_options = texture_options;
        self
    }

    /// Set the max width of the image.
    ///
    /// No matter what the image is scaled to, it will never exceed this limit.
    #[inline]
    pub fn max_width(mut self, width: f32) -> Self {
        self.size.max_size.x = width;
        self
    }

    /// Set the max height of the image.
    ///
    /// No matter what the image is scaled to, it will never exceed this limit.
    #[inline]
    pub fn max_height(mut self, height: f32) -> Self {
        self.size.max_size.y = height;
        self
    }

    /// Set the max size of the image.
    ///
    /// No matter what the image is scaled to, it will never exceed this limit.
    #[inline]
    pub fn max_size(mut self, size: Vec2) -> Self {
        self.size.max_size = size;
        self
    }

    /// Whether or not the [`ImageFit`] should maintain the image's original aspect ratio.
    #[inline]
    pub fn maintain_aspect_ratio(mut self, value: bool) -> Self {
        self.size.maintain_aspect_ratio = value;
        self
    }

    /// Fit the image to its original size with some scaling.
    ///
    /// This will cause the image to overflow if it is larger than the available space.
    ///
    /// If [`Image::max_size`] is set, this is guaranteed to never exceed that limit.
    #[inline]
    pub fn fit_to_original_size(mut self, scale: f32) -> Self {
        self.size.fit = ImageFit::Original { scale };
        self
    }

    /// Fit the image to an exact size.
    ///
    /// If [`Image::max_size`] is set, this is guaranteed to never exceed that limit.
    #[inline]
    pub fn fit_to_exact_size(mut self, size: Vec2) -> Self {
        self.size.fit = ImageFit::Exact(size);
        self
    }

    /// Fit the image to a fraction of the available space.
    ///
    /// If [`Image::max_size`] is set, this is guaranteed to never exceed that limit.
    #[inline]
    pub fn fit_to_fraction(mut self, fraction: Vec2) -> Self {
        self.size.fit = ImageFit::Fraction(fraction);
        self
    }

    /// Fit the image to 100% of its available size, shrinking it if necessary.
    ///
    /// This is a shorthand for [`Image::fit_to_fraction`] with `1.0` for both width and height.
    ///
    /// If [`Image::max_size`] is set, this is guaranteed to never exceed that limit.
    #[inline]
    pub fn shrink_to_fit(self) -> Self {
        self.fit_to_fraction(Vec2::new(1.0, 1.0))
    }

    /// Make the image respond to clicks and/or drags.
    #[inline]
    pub fn sense(mut self, sense: Sense) -> Self {
        self.sense = sense;
        self
    }

    /// Select UV range. Default is (0,0) in top-left, (1,1) bottom right.
    #[inline]
    pub fn uv(mut self, uv: impl Into<Rect>) -> Self {
        self.image_options.uv = uv.into();
        self
    }

    /// A solid color to put behind the image. Useful for transparent images.
    #[inline]
    pub fn bg_fill(mut self, bg_fill: impl Into<Color32>) -> Self {
        self.image_options.bg_fill = bg_fill.into();
        self
    }

    /// Multiply image color with this. Default is WHITE (no tint).
    #[inline]
    pub fn tint(mut self, tint: impl Into<Color32>) -> Self {
        self.image_options.tint = tint.into();
        self
    }

    /// Rotate the image about an origin by some angle
    ///
    /// Positive angle is clockwise.
    /// Origin is a vector in normalized UV space ((0,0) in top-left, (1,1) bottom right).
    ///
    /// To rotate about the center you can pass `Vec2::splat(0.5)` as the origin.
    ///
    /// Due to limitations in the current implementation,
    /// this will turn off rounding of the image.
    #[inline]
    pub fn rotate(mut self, angle: f32, origin: Vec2) -> Self {
        self.image_options.rotation = Some((Rot2::from_angle(angle), origin));
        self.image_options.rounding = Rounding::ZERO; // incompatible with rotation
        self
    }

    /// Round the corners of the image.
    ///
    /// The default is no rounding ([`Rounding::ZERO`]).
    ///
    /// Due to limitations in the current implementation,
    /// this will turn off any rotation of the image.
    #[inline]
    pub fn rounding(mut self, rounding: impl Into<Rounding>) -> Self {
        self.image_options.rounding = rounding.into();
        if self.image_options.rounding != Rounding::ZERO {
            self.image_options.rotation = None; // incompatible with rounding
        }
        self
    }

    /// Show a spinner when the image is loading.
    ///
    /// By default this uses the value of [`crate::Visuals::image_loading_spinners`].
    #[inline]
    pub fn show_loading_spinner(mut self, show: bool) -> Self {
        self.show_loading_spinner = Some(show);
        self
    }
}

impl<'a, T: Into<ImageSource<'a>>> From<T> for Image<'a> {
    fn from(value: T) -> Self {
        Image::new(value)
    }
}

impl<'a> Image<'a> {
    /// Returns the size the image will occupy in the final UI.
    #[inline]
    pub fn calc_size(&self, available_size: Vec2, original_image_size: Option<Vec2>) -> Vec2 {
        let original_image_size = original_image_size.unwrap_or(Vec2::splat(24.0)); // Fallback for still-loading textures, or failure to load.
        self.size.calc_size(available_size, original_image_size)
    }

    pub fn load_and_calc_size(&self, ui: &Ui, available_size: Vec2) -> Option<Vec2> {
        let image_size = self.load_for_size(ui.ctx(), available_size).ok()?.size()?;
        Some(self.size.calc_size(available_size, image_size))
    }

    #[inline]
    pub fn size(&self) -> Option<Vec2> {
        match &self.source {
            ImageSource::Texture(texture) => Some(texture.size),
            ImageSource::Uri(_) | ImageSource::Bytes { .. } => None,
        }
    }

    /// Returns the URI of the image.
    ///
    /// For GIFs, returns the URI without the frame number.
    #[inline]
    pub fn uri(&self) -> Option<&str> {
        let uri = self.source.uri()?;

        if let Ok((gif_uri, _index)) = decode_gif_uri(uri) {
            Some(gif_uri)
        } else {
            Some(uri)
        }
    }

    #[inline]
    pub fn image_options(&self) -> &ImageOptions {
        &self.image_options
    }

    #[inline]
    pub fn source(&'a self, ctx: &Context) -> ImageSource<'a> {
        match &self.source {
            ImageSource::Uri(uri) if is_gif_uri(uri) => {
                let frame_uri = encode_gif_uri(uri, gif_frame_index(ctx, uri));
                ImageSource::Uri(Cow::Owned(frame_uri))
            }

            ImageSource::Bytes { uri, bytes } if is_gif_uri(uri) || has_gif_magic_header(bytes) => {
                let frame_uri = encode_gif_uri(uri, gif_frame_index(ctx, uri));
                ctx.include_bytes(uri.clone(), bytes.clone());
                ImageSource::Uri(Cow::Owned(frame_uri))
            }
            _ => self.source.clone(),
        }
    }

    /// Load the image from its [`Image::source`], returning the resulting [`SizedTexture`].
    ///
    /// The `available_size` is used as a hint when e.g. rendering an svg.
    ///
    /// # Errors
    /// May fail if they underlying [`Context::try_load_texture`] call fails.
    pub fn load_for_size(&self, ctx: &Context, available_size: Vec2) -> TextureLoadResult {
        let size_hint = self.size.hint(available_size, ctx.pixels_per_point());
        self.source(ctx)
            .clone()
            .load(ctx, self.texture_options, size_hint)
    }

    /// Paint the image in the given rectangle.
    ///
    /// ```
    /// # egui::__run_test_ui(|ui| {
    /// # let rect = egui::Rect::from_min_size(Default::default(), egui::Vec2::splat(100.0));
    /// egui::Image::new(egui::include_image!("../../assets/ferris.png"))
    ///     .rounding(5.0)
    ///     .tint(egui::Color32::LIGHT_BLUE)
    ///     .paint_at(ui, rect);
    /// # });
    /// ```
    #[inline]
    pub fn paint_at(&self, ui: &Ui, rect: Rect) {
        paint_texture_load_result(
            ui,
            &self.load_for_size(ui.ctx(), rect.size()),
            rect,
            self.show_loading_spinner,
            &self.image_options,
        );
    }
}

impl<'a> Widget for Image<'a> {
    fn ui(self, ui: &mut Ui) -> Response {
        let tlr = self.load_for_size(ui.ctx(), ui.available_size());
        let original_image_size = tlr.as_ref().ok().and_then(|t| t.size());
        let ui_size = self.calc_size(ui.available_size(), original_image_size);

        let (rect, response) = ui.allocate_exact_size(ui_size, self.sense);
        if ui.is_rect_visible(rect) {
            paint_texture_load_result(
                ui,
                &tlr,
                rect,
                self.show_loading_spinner,
                &self.image_options,
            );
        }
        texture_load_result_response(&self.source(ui.ctx()), &tlr, response)
    }
}

/// This type determines the constraints on how
/// the size of an image should be calculated.
#[derive(Debug, Clone, Copy)]
pub struct ImageSize {
    /// Whether or not the final size should maintain the original aspect ratio.
    ///
    /// This setting is applied last.
    ///
    /// This defaults to `true`.
    pub maintain_aspect_ratio: bool,

    /// Determines the maximum size of the image.
    ///
    /// Defaults to `Vec2::INFINITY` (no limit).
    pub max_size: Vec2,

    /// Determines how the image should shrink/expand/stretch/etc. to fit within its allocated space.
    ///
    /// This setting is applied first.
    ///
    /// Defaults to `ImageFit::Fraction([1, 1])`
    pub fit: ImageFit,
}

/// This type determines how the image should try to fit within the UI.
///
/// The final fit will be clamped to [`ImageSize::max_size`].
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum ImageFit {
    /// Fit the image to its original size, scaled by some factor.
    ///
    /// Ignores how much space is actually available in the ui.
    Original { scale: f32 },

    /// Fit the image to a fraction of the available size.
    Fraction(Vec2),

    /// Fit the image to an exact size.
    ///
    /// Ignores how much space is actually available in the ui.
    Exact(Vec2),
}

impl ImageFit {
    pub fn resolve(self, available_size: Vec2, image_size: Vec2) -> Vec2 {
        match self {
            Self::Original { scale } => image_size * scale,
            Self::Fraction(fract) => available_size * fract,
            Self::Exact(size) => size,
        }
    }
}

impl ImageSize {
    /// Size hint for e.g. rasterizing an svg.
    pub fn hint(&self, available_size: Vec2, pixels_per_point: f32) -> SizeHint {
        let size = match self.fit {
            ImageFit::Original { scale } => return SizeHint::Scale(scale.ord()),
            ImageFit::Fraction(fract) => available_size * fract,
            ImageFit::Exact(size) => size,
        };
        let size = size.min(self.max_size);
        let size = size * pixels_per_point;

        // `inf` on an axis means "any value"
        match (size.x.is_finite(), size.y.is_finite()) {
            (true, true) => SizeHint::Size(size.x.round() as u32, size.y.round() as u32),
            (true, false) => SizeHint::Width(size.x.round() as u32),
            (false, true) => SizeHint::Height(size.y.round() as u32),
            (false, false) => SizeHint::Scale(pixels_per_point.ord()),
        }
    }

    /// Calculate the final on-screen size in points.
    pub fn calc_size(&self, available_size: Vec2, original_image_size: Vec2) -> Vec2 {
        let Self {
            maintain_aspect_ratio,
            max_size,
            fit,
        } = *self;
        match fit {
            ImageFit::Original { scale } => {
                let image_size = original_image_size * scale;
                if image_size.x <= max_size.x && image_size.y <= max_size.y {
                    image_size
                } else {
                    scale_to_fit(image_size, max_size, maintain_aspect_ratio)
                }
            }
            ImageFit::Fraction(fract) => {
                let scale_to_size = (available_size * fract).min(max_size);
                scale_to_fit(original_image_size, scale_to_size, maintain_aspect_ratio)
            }
            ImageFit::Exact(size) => {
                let scale_to_size = size.min(max_size);
                scale_to_fit(original_image_size, scale_to_size, maintain_aspect_ratio)
            }
        }
    }
}

// TODO(jprochazk): unit-tests
fn scale_to_fit(image_size: Vec2, available_size: Vec2, maintain_aspect_ratio: bool) -> Vec2 {
    if maintain_aspect_ratio {
        let ratio_x = available_size.x / image_size.x;
        let ratio_y = available_size.y / image_size.y;
        let ratio = if ratio_x < ratio_y { ratio_x } else { ratio_y };
        let ratio = if ratio.is_finite() { ratio } else { 1.0 };
        image_size * ratio
    } else {
        available_size
    }
}

impl Default for ImageSize {
    #[inline]
    fn default() -> Self {
        Self {
            max_size: Vec2::INFINITY,
            fit: ImageFit::Fraction(Vec2::new(1.0, 1.0)),
            maintain_aspect_ratio: true,
        }
    }
}

/// This type tells the [`Ui`] how to load an image.
///
/// This is used by [`Image::new`] and [`Ui::image`].
#[derive(Clone)]
pub enum ImageSource<'a> {
    /// Load the image from a URI, e.g. `https://example.com/image.png`.
    ///
    /// This could be a `file://` path, `https://` url, `bytes://` identifier, or some other scheme.
    ///
    /// How the URI will be turned into a texture for rendering purposes is
    /// up to the registered loaders to handle.
    ///
    /// See [`crate::load`] for more information.
    Uri(Cow<'a, str>),

    /// Load the image from an existing texture.
    ///
    /// The user is responsible for loading the texture, determining its size,
    /// and allocating a [`crate::TextureId`] for it.
    Texture(SizedTexture),

    /// Load the image from some raw bytes.
    ///
    /// The [`Bytes`] may be:
    /// - `'static`, obtained from `include_bytes!` or similar
    /// - Anything that can be converted to `Arc<[u8]>`
    ///
    /// This instructs the [`Ui`] to cache the raw bytes, which are then further processed by any registered loaders.
    ///
    /// See also [`crate::include_image`] for an easy way to load and display static images.
    ///
    /// See [`crate::load`] for more information.
    Bytes {
        /// The unique identifier for this image, e.g. `bytes://my_logo.png`.
        ///
        /// You should use a proper extension (`.jpg`, `.png`, `.svg`, etc) for the image to load properly.
        ///
        /// Use the `bytes://` scheme for the URI for better error messages.
        uri: Cow<'static, str>,

        bytes: Bytes,
    },
}

impl<'a> std::fmt::Debug for ImageSource<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ImageSource::Bytes { uri, .. } | ImageSource::Uri(uri) => uri.as_ref().fmt(f),
            ImageSource::Texture(st) => st.id.fmt(f),
        }
    }
}

impl<'a> ImageSource<'a> {
    /// Size of the texture, if known.
    #[inline]
    pub fn texture_size(&self) -> Option<Vec2> {
        match self {
            ImageSource::Texture(texture) => Some(texture.size),
            ImageSource::Uri(_) | ImageSource::Bytes { .. } => None,
        }
    }

    /// # Errors
    /// Failure to load the texture.
    pub fn load(
        self,
        ctx: &Context,
        texture_options: TextureOptions,
        size_hint: SizeHint,
    ) -> TextureLoadResult {
        match self {
            Self::Texture(texture) => Ok(TexturePoll::Ready { texture }),
            Self::Uri(uri) => ctx.try_load_texture(uri.as_ref(), texture_options, size_hint),
            Self::Bytes { uri, bytes } => {
                ctx.include_bytes(uri.clone(), bytes);
                ctx.try_load_texture(uri.as_ref(), texture_options, size_hint)
            }
        }
    }

    /// Get the `uri` that this image was constructed from.
    ///
    /// This will return `None` for [`Self::Texture`].
    pub fn uri(&self) -> Option<&str> {
        match self {
            ImageSource::Bytes { uri, .. } | ImageSource::Uri(uri) => Some(uri),
            ImageSource::Texture(_) => None,
        }
    }
}

pub fn paint_texture_load_result(
    ui: &Ui,
    tlr: &TextureLoadResult,
    rect: Rect,
    show_loading_spinner: Option<bool>,
    options: &ImageOptions,
) {
    match tlr {
        Ok(TexturePoll::Ready { texture }) => {
            paint_texture_at(ui.painter(), rect, options, texture);
        }
        Ok(TexturePoll::Pending { .. }) => {
            let show_loading_spinner =
                show_loading_spinner.unwrap_or(ui.visuals().image_loading_spinners);
            if show_loading_spinner {
                Spinner::new().paint_at(ui, rect);
            }
        }
        Err(_) => {
            let font_id = TextStyle::Body.resolve(ui.style());
            ui.painter().text(
                rect.center(),
                Align2::CENTER_CENTER,
                "⚠",
                font_id,
                ui.visuals().error_fg_color,
            );
        }
    }
}

/// Attach tooltips like "Loading…" or "Failed loading: …".
pub fn texture_load_result_response(
    source: &ImageSource<'_>,
    tlr: &TextureLoadResult,
    response: Response,
) -> Response {
    match tlr {
        Ok(TexturePoll::Ready { .. }) => response,
        Ok(TexturePoll::Pending { .. }) => {
            let uri = source.uri().unwrap_or("image");
            response.on_hover_text(format!("Loading {uri}…"))
        }
        Err(err) => {
            let uri = source.uri().unwrap_or("image");
            response.on_hover_text(format!("Failed loading {uri}: {err}"))
        }
    }
}

impl<'a> From<&'a str> for ImageSource<'a> {
    #[inline]
    fn from(value: &'a str) -> Self {
        Self::Uri(value.into())
    }
}

impl<'a> From<&'a String> for ImageSource<'a> {
    #[inline]
    fn from(value: &'a String) -> Self {
        Self::Uri(value.as_str().into())
    }
}

impl From<String> for ImageSource<'static> {
    fn from(value: String) -> Self {
        Self::Uri(value.into())
    }
}

impl<'a> From<&'a Cow<'a, str>> for ImageSource<'a> {
    #[inline]
    fn from(value: &'a Cow<'a, str>) -> Self {
        Self::Uri(value.clone())
    }
}

impl<'a> From<Cow<'a, str>> for ImageSource<'a> {
    #[inline]
    fn from(value: Cow<'a, str>) -> Self {
        Self::Uri(value)
    }
}

impl<T: Into<Bytes>> From<(&'static str, T)> for ImageSource<'static> {
    #[inline]
    fn from((uri, bytes): (&'static str, T)) -> Self {
        Self::Bytes {
            uri: uri.into(),
            bytes: bytes.into(),
        }
    }
}

impl<T: Into<Bytes>> From<(Cow<'static, str>, T)> for ImageSource<'static> {
    #[inline]
    fn from((uri, bytes): (Cow<'static, str>, T)) -> Self {
        Self::Bytes {
            uri,
            bytes: bytes.into(),
        }
    }
}

impl<T: Into<Bytes>> From<(String, T)> for ImageSource<'static> {
    #[inline]
    fn from((uri, bytes): (String, T)) -> Self {
        Self::Bytes {
            uri: uri.into(),
            bytes: bytes.into(),
        }
    }
}

impl<T: Into<SizedTexture>> From<T> for ImageSource<'static> {
    fn from(value: T) -> Self {
        Self::Texture(value.into())
    }
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct ImageOptions {
    /// Select UV range. Default is (0,0) in top-left, (1,1) bottom right.
    pub uv: Rect,

    /// A solid color to put behind the image. Useful for transparent images.
    pub bg_fill: Color32,

    /// Multiply image color with this. Default is WHITE (no tint).
    pub tint: Color32,

    /// Rotate the image about an origin by some angle
    ///
    /// Positive angle is clockwise.
    /// Origin is a vector in normalized UV space ((0,0) in top-left, (1,1) bottom right).
    ///
    /// To rotate about the center you can pass `Vec2::splat(0.5)` as the origin.
    ///
    /// Due to limitations in the current implementation,
    /// this will turn off rounding of the image.
    pub rotation: Option<(Rot2, Vec2)>,

    /// Round the corners of the image.
    ///
    /// The default is no rounding ([`Rounding::ZERO`]).
    ///
    /// Due to limitations in the current implementation,
    /// this will turn off any rotation of the image.
    pub rounding: Rounding,
}

impl Default for ImageOptions {
    fn default() -> Self {
        Self {
            uv: Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
            bg_fill: Default::default(),
            tint: Color32::WHITE,
            rotation: None,
            rounding: Rounding::ZERO,
        }
    }
}

pub fn paint_texture_at(
    painter: &Painter,
    rect: Rect,
    options: &ImageOptions,
    texture: &SizedTexture,
) {
    if options.bg_fill != Default::default() {
        painter.add(RectShape::filled(rect, options.rounding, options.bg_fill));
    }

    match options.rotation {
        Some((rot, origin)) => {
            // TODO(emilk): implement this using `PathShape` (add texture support to it).
            // This will also give us anti-aliasing of rotated images.
            debug_assert!(
                options.rounding == Rounding::ZERO,
                "Image had both rounding and rotation. Please pick only one"
            );

            let mut mesh = Mesh::with_texture(texture.id);
            mesh.add_rect_with_uv(rect, options.uv, options.tint);
            mesh.rotate(rot, rect.min + origin * rect.size());
            painter.add(Shape::mesh(mesh));
        }
        None => {
            painter.add(RectShape {
                rect,
                rounding: options.rounding,
                fill: options.tint,
                stroke: Stroke::NONE,
                blur_width: 0.0,
                fill_texture_id: texture.id,
                uv: options.uv,
            });
        }
    }
}

/// gif uris contain the uri & the frame that will be displayed
fn encode_gif_uri(uri: &str, frame_index: usize) -> String {
    format!("{uri}#{frame_index}")
}

/// extracts uri and frame index
/// # Errors
/// Will return `Err` if `uri` does not match pattern {uri}-{frame_index}
pub fn decode_gif_uri(uri: &str) -> Result<(&str, usize), String> {
    let (uri, index) = uri
        .rsplit_once('#')
        .ok_or("Failed to find index separator '#'")?;
    let index: usize = index
        .parse()
        .map_err(|_err| format!("Failed to parse gif frame index: {index:?} is not an integer"))?;
    Ok((uri, index))
}

/// checks if uri is a gif file
fn is_gif_uri(uri: &str) -> bool {
    uri.ends_with(".gif") || uri.contains(".gif#")
}

/// checks if bytes are gifs
pub fn has_gif_magic_header(bytes: &[u8]) -> bool {
    bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a")
}

/// calculates at which frame the gif is
fn gif_frame_index(ctx: &Context, uri: &str) -> usize {
    let now = ctx.input(|i| Duration::from_secs_f64(i.time));

    let durations: Option<GifFrameDurations> = ctx.data(|data| data.get_temp(Id::new(uri)));
    if let Some(durations) = durations {
        let frames: Duration = durations.0.iter().sum();
        let pos_ms = now.as_millis() % frames.as_millis().max(1);
        let mut cumulative_ms = 0;
        for (i, duration) in durations.0.iter().enumerate() {
            cumulative_ms += duration.as_millis();
            if pos_ms < cumulative_ms {
                let ms_until_next_frame = cumulative_ms - pos_ms;
                ctx.request_repaint_after(Duration::from_millis(ms_until_next_frame as u64));
                return i;
            }
        }
        0
    } else {
        0
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
/// Stores the durations between each frame of a gif
pub struct GifFrameDurations(pub Arc<Vec<Duration>>);