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
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use serde::{Serialize, Deserialize};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use std::sync::mpsc::{channel, Sender};
use std::thread::{spawn};
use image::{DynamicImage, Rgba};
use rusttype::Scale;
use crate::core::{SDCore};
use crate::core::button::{Component, parse_unique_button_to_component};
use crate::core::methods::{CoreHandle, get_current_screen};
use crate::font::get_font_from_collection;
use crate::threads::streamdeck::StreamDeckCommand;
use crate::util::rendering::{image_from_horiz_gradient, image_from_solid, image_from_vert_gradient, load_image, render_aligned_shadowed_text_on_image, render_aligned_text_on_image, TextAlignment};
#[derive(Debug)]
pub struct RendererHandle {
tx: Sender<RendererCommunication>,
}
impl RendererHandle {
pub fn redraw(&self) {
self.tx.send(RendererCommunication::Redraw).ok();
}
}
#[allow(dead_code)]
enum RendererCommunication {
Nothing,
Redraw,
}
pub struct RendererState {
render_cache: RwLock<HashMap<u64, DynamicImage>>,
image_cache: RwLock<HashMap<u64, DynamicImage>>
}
pub fn spawn_rendering_thread(core: Arc<SDCore>) -> RendererHandle {
let (tx, rx) = channel::<RendererCommunication>();
spawn(move || {
let core = core.clone();
let state = RendererState {
render_cache: Default::default(),
image_cache: Default::default()
};
loop {
if core.is_closed() {
break;
}
if let Ok(com) = rx.recv() {
match com {
RendererCommunication::Redraw => redraw(core.clone(), &state),
_ => {}
}
} else {
break;
}
}
log::trace!("rendering closed");
});
tx.send(RendererCommunication::Redraw).ok();
RendererHandle {
tx,
}
}
fn redraw(core: Arc<SDCore>, state: &RendererState) {
let core_handle = CoreHandle::wrap(core.clone());
let current_screen = get_current_screen(&core_handle);
let mut commands = vec![];
for i in 0..core.key_count {
if let Some(current_screen) = ¤t_screen {
if let Some(button) = current_screen.get(&i) {
if let Ok(renderer) = parse_unique_button_to_component::<RendererComponent>(button) {
let renderer_hash = hash_renderer(&renderer);
let mut cache_handle = state.render_cache.write().unwrap();
let cache_entry = cache_handle.get(&renderer_hash);
let mut image = if cache_entry.is_some() && renderer.to_cache {
cache_entry.unwrap().clone()
} else {
let image = match renderer.background {
ButtonBackground::Solid(color) => {
image_from_solid(core.image_size, Rgba([color.0, color.1, color.2, 255]))
}
ButtonBackground::HorizontalGradient(start, end) => {
image_from_horiz_gradient(core.image_size, Rgba([start.0, start.1, start.2, 255]), Rgba([end.0, end.1, end.2, 255]))
}
ButtonBackground::VerticalGradient(start, end) => {
image_from_vert_gradient(core.image_size, Rgba([start.0, start.1, start.2, 255]), Rgba([end.0, end.1, end.2, 255]))
}
ButtonBackground::Image(path, disable_caching) => {
let image_hash = hash_path(&path);
let mut image_cache = state.image_cache.write().unwrap();
let image_cache_entry = image_cache.get(&image_hash);
let image = if image_cache_entry.is_some() && (!disable_caching) {
image_cache_entry.unwrap().clone()
} else {
if let Some(image) = load_image(core.image_size, path.deref()) {
image
} else {
log::error!("Failed to load image at '{}'", path.to_string_lossy());
continue;
}
};
if !disable_caching {
image_cache.insert(image_hash, image.clone());
}
drop(image_cache);
image
}
};
if renderer.to_cache {
cache_handle.insert(renderer_hash, image.clone());
}
image
};
drop(cache_handle);
for button_text in renderer.text {
let text = button_text.text.as_str();
let scale = Scale { x: button_text.scale.0, y: button_text.scale.1 };
let align = button_text.alignment.clone();
let padding = button_text.padding;
let offset = button_text.offset.clone();
let color = button_text.color.clone();
if let Some(font) = get_font_from_collection(&button_text.font) {
if let Some(shadow) = &button_text.shadow {
render_aligned_shadowed_text_on_image(
core.image_size,
&mut image,
font.as_ref(),
text,
scale,
align,
padding,
offset,
color,
shadow.offset.clone(),
shadow.color.clone()
)
} else {
render_aligned_text_on_image(
core.image_size,
&mut image,
font.as_ref(),
text,
scale,
align,
padding,
offset,
color
)
}
}
}
commands.push(StreamDeckCommand::SetButtonImage(i, image));
} else {
commands.push(StreamDeckCommand::ClearButtonImage(i));
}
} else {
commands.push(StreamDeckCommand::ClearButtonImage(i));
}
} else {
commands.push(StreamDeckCommand::ClearButtonImage(i));
}
}
core.send_commands(commands);
}
pub type Color = (u8, u8, u8, u8);
#[derive(Serialize, Deserialize, Debug, Clone, Hash)]
pub enum ButtonBackground {
Solid(Color),
HorizontalGradient(Color, Color),
VerticalGradient(Color, Color),
Image(PathBuf, bool),
}
impl Default for ButtonBackground {
fn default() -> Self {
Self::Solid((0, 0, 0, 0))
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ButtonText {
pub text: String,
pub font: String,
pub scale: (f32, f32),
pub alignment: TextAlignment,
pub padding: u32,
pub offset: (f32, f32),
pub color: Color,
pub shadow: Option<ButtonTextShadow>,
}
impl Hash for ButtonText {
fn hash<H: Hasher>(&self, state: &mut H) {
self.text.hash(state);
self.font.hash(state);
self.alignment.hash(state);
self.padding.hash(state);
self.color.hash(state);
self.shadow.hash(state);
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Hash)]
pub struct ButtonTextShadow {
pub offset: (i32, i32),
pub color: Color
}
#[derive(Serialize, Deserialize, Clone, Hash, Debug)]
pub struct RendererComponent {
#[serde(default)]
pub background: ButtonBackground,
#[serde(default)]
pub text: Vec<ButtonText>,
#[serde(default = "make_true")]
pub to_cache: bool
}
fn make_true() -> bool { true }
impl Default for RendererComponent {
fn default() -> Self {
Self {
background: ButtonBackground::Solid((255, 255, 255, 255)),
text: vec![],
to_cache: true
}
}
}
impl Component for RendererComponent {
const NAME: &'static str = "renderer";
}
pub(crate) fn hash_renderer(renderer: &RendererComponent) -> u64 {
let mut hasher = DefaultHasher::new();
renderer.hash(&mut hasher);
hasher.finish()
}
pub(crate) fn hash_path(path: &PathBuf) -> u64 {
let mut hasher = DefaultHasher::new();
path.hash(&mut hasher);
hasher.finish()
}