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
use crate::caches::TextureCache;
use crate::primitives::draw_base;
use crate::properties::{
WidgetProperties, PROPERTY_BORDER_WIDTH, PROPERTY_IMAGE_FILENAME, PROPERTY_IMAGE_POSITION,
PROPERTY_IMAGE_SCALED,
};
use crate::texture_store::TextureStore;
use crate::widget::Widget;
use sdl2::rect::Rect;
use sdl2::render::{Canvas, Texture, TextureQuery};
use sdl2::video::Window;
pub const COMPASS_NW: i32 = 1;
pub const COMPASS_N: i32 = 2;
pub const COMPASS_NE: i32 = 3;
pub const COMPASS_E: i32 = 4;
pub const COMPASS_SE: i32 = 5;
pub const COMPASS_S: i32 = 6;
pub const COMPASS_SW: i32 = 7;
pub const COMPASS_W: i32 = 8;
pub const COMPASS_CENTER: i32 = 9;
#[derive(Default)]
pub struct ImageWidget {
texture_store: TextureStore,
properties: WidgetProperties,
}
impl Widget for ImageWidget {
widget_default_impl!();
fn draw(&mut self, c: &mut Canvas<Window>, t: &mut TextureCache) -> Option<&Texture> {
if self.invalidated() {
let bounds = self.properties.get_bounds();
self.texture_store
.create_or_resize_texture(c, bounds.0, bounds.1);
let widget_w = bounds.0;
let widget_h = bounds.1;
let image_texture = t.get_image(c, self.properties.get(PROPERTY_IMAGE_FILENAME));
let TextureQuery { width, height, .. } = image_texture.query();
let scaled = self.properties.get_bool(PROPERTY_IMAGE_SCALED);
let texture_x = match self.properties.get_value(PROPERTY_IMAGE_POSITION) {
COMPASS_NW | COMPASS_W | COMPASS_SW => 0,
COMPASS_N | COMPASS_CENTER | COMPASS_S => (widget_w - width) / 2,
COMPASS_NE | COMPASS_E | COMPASS_SE => widget_w - width,
_ => 0,
};
let texture_y = match self.properties.get_value(PROPERTY_IMAGE_POSITION) {
COMPASS_NW | COMPASS_N | COMPASS_NE => 0,
COMPASS_W | COMPASS_CENTER | COMPASS_E => (widget_h - height) / 2,
COMPASS_SW | COMPASS_S | COMPASS_SE => widget_h - height,
_ => 0,
};
let cloned_properties = self.properties.clone();
c.with_texture_canvas(self.texture_store.get_mut_ref(), |texture| {
draw_base(texture, &cloned_properties, None);
let border_width = cloned_properties.get_value(PROPERTY_BORDER_WIDTH);
if !scaled {
texture
.copy(
image_texture,
None,
Rect::new(
texture_x as i32 + border_width,
texture_y as i32 + border_width,
width - (border_width as u32 * 2),
height - (border_width as u32 * 2),
),
)
.unwrap();
} else {
texture
.copy(
image_texture,
None,
Rect::new(
border_width,
border_width,
widget_w as u32 - (border_width as u32 * 2),
widget_h as u32 - (border_width as u32 * 2),
),
)
.unwrap();
}
})
.unwrap();
}
self.texture_store.get_optional_ref()
}
}