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
use crate::{
Color, DrawWithTooltips, EventCtx, GeomBatch, JustDraw, RewriteColor, ScreenDims, ScreenPt,
Text, Widget,
};
use geom::Bounds;
#[derive(Clone, Debug)]
pub struct Image<'a> {
source: ImageSource<'a>,
tooltip: Option<Text>,
color: Option<RewriteColor>,
}
#[derive(Clone, Debug)]
pub enum ImageSource<'a> {
Path(&'a str),
Bytes { bytes: &'a [u8], cache_key: &'a str },
GeomBatch(GeomBatch, geom::Bounds),
}
impl ImageSource<'_> {
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).expect(&format!(
"Failed to load svg from bytes. cache_key: {}",
cache_key
))
}
ImageSource::GeomBatch(geom_batch, bounds) => (geom_batch.clone(), *bounds),
}
}
}
impl<'a> Image<'a> {
pub fn icon(filename: &'a str) -> Self {
Self {
source: ImageSource::Path(filename),
tooltip: None,
color: None,
}
}
pub fn untinted(filename: &'a str) -> Self {
Self::icon(filename).color(RewriteColor::NoOp)
}
pub fn bytes(labeled_bytes: (&'a str, &'a [u8])) -> Self {
Self {
source: ImageSource::Bytes {
cache_key: labeled_bytes.0,
bytes: labeled_bytes.1,
},
tooltip: None,
color: None,
}
}
pub fn tooltip(mut self, tooltip: Text) -> Self {
self.tooltip = Some(tooltip);
self
}
pub fn color<RWC: Into<RewriteColor>>(mut self, color: RWC) -> Self {
self.color = Some(color.into());
self
}
pub fn batch(&self, ctx: &EventCtx) -> (GeomBatch, Bounds) {
let (mut batch, bounds) = self.source.load(&ctx.prerender);
let color = self
.color
.unwrap_or(RewriteColor::ChangeAll(ctx.style.icon_fg));
batch = batch.color(color);
batch.push(Color::CLEAR, bounds.get_rectangle());
(batch, bounds)
}
pub fn into_widget(self, ctx: &EventCtx) -> Widget {
let (batch, bounds) = self.batch(ctx);
if let Some(tooltip) = self.tooltip {
DrawWithTooltips::new(
ctx,
batch,
vec![(bounds.get_rectangle(), tooltip)],
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),
}))
}
}
}