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
use std::collections::HashMap;
use std::fs;
use std::ops::Deref;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use image::{DynamicImage};
use serde::{Serialize, Deserialize};
use serde::de::DeserializeOwned;
use crate::core::RawButtonPanel;
use serde_json::Value;
use streamdeck::Kind;
use crate::ImageCollection;
use crate::images::{SDImage, SDSerializedImage};
use crate::util::{hash_image, hash_str};
use crate::thread::util::resize_for_streamdeck;
pub const DEFAULT_POOL_RATE: u32 = 1000;
pub const DEFAULT_RECONNECT_TIME: f32 = 1.0;
pub const DEFAULT_CONFIG_PATH: &'static str = "devices";
pub const DEFAULT_PLUGIN_PATH: &'static str = "plugins";
pub const DEFAULT_PLUGIN_SETTINGS_PATH: &'static str = "global.json";
pub type UniqueDeviceConfig = Arc<RwLock<DeviceConfig>>;
#[derive(Serialize, Deserialize, Default)]
pub struct Config {
pool_rate: Option<u32>,
reconnect_rate: Option<f32>,
device_config_path: Option<PathBuf>,
plugin_path: Option<PathBuf>,
plugin_settings_path: Option<PathBuf>,
#[serde(skip)]
pub plugin_settings: RwLock<HashMap<String, Value>>,
#[serde(skip)]
pub loaded_configs: RwLock<HashMap<String, UniqueDeviceConfig>>,
#[serde(skip)]
pub loaded_images: RwLock<HashMap<String, ImageCollection>>
}
#[allow(dead_code)]
impl Config {
pub fn get() -> Config {
let config: Config = if let Ok(content) = fs::read_to_string("config.toml") {
if let Ok(config) = toml::from_str(&content) {
config
} else {
Default::default()
}
} else {
Default::default()
};
config.load_plugin_settings();
config
}
pub fn pool_rate(&self) -> u32 {
self.pool_rate.unwrap_or(DEFAULT_POOL_RATE)
}
pub fn reconnect_rate(&self) -> f32 {
self.reconnect_rate.unwrap_or(DEFAULT_RECONNECT_TIME)
}
pub fn device_config_path(&self) -> PathBuf {
self.device_config_path.clone().unwrap_or(PathBuf::from(DEFAULT_CONFIG_PATH))
}
pub fn plugin_path(&self) -> PathBuf {
self.plugin_path.clone().unwrap_or(PathBuf::from(DEFAULT_PLUGIN_PATH))
}
pub fn plugin_settings_path(&self) -> PathBuf {
self.plugin_settings_path.clone().unwrap_or(PathBuf::from(DEFAULT_PLUGIN_SETTINGS_PATH))
}
pub fn load_plugin_settings(&self) {
if let Ok(settings) = fs::read_to_string(self.plugin_settings_path()) {
let mut lock = self.plugin_settings.write().unwrap();
match serde_json::from_str(&settings) {
Ok(vals) => *lock = vals,
Err(err) => log::error!("Failed to parse plugin settings: {:?}", err),
}
}
}
pub fn get_plugin_settings<T: PluginConfig + DeserializeOwned>(&self) -> Option<T> {
let lock = self.plugin_settings.read().unwrap();
Some(serde_json::from_value(lock.get(T::NAME)?.clone()).ok()?)
}
pub fn set_plugin_settings<T: PluginConfig + Serialize>(&self, value: T) {
let mut lock = self.plugin_settings.write().unwrap();
lock.insert(T::NAME.to_string(), serde_json::to_value(value).unwrap());
drop(lock);
self.write_plugin_settings();
}
pub fn write_plugin_settings(&self) {
let lock = self.plugin_settings.read().unwrap();
if let Err(err) = fs::write(self.plugin_settings_path(), serde_json::to_string(lock.deref()).unwrap()) {
log::error!("Failed to write plugin settings: {:?}", err);
}
}
pub fn reload_device_config(&self, serial: &str) -> Result<(), ConfigError> {
self.get_image_collection(serial).write().unwrap().clear();
let mut devices = self.loaded_configs.write().unwrap();
let mut path = self.device_config_path();
path.push(format!("{}.json", serial));
let content = fs::read_to_string(path)?;
let device = serde_json::from_str::<DeviceConfig>(&content)?;
if let Some(device_config) = devices.get(serial) {
*device_config.write().unwrap() = device;
} else {
devices.insert(serial.to_string(), Arc::new(RwLock::new(device)));
}
self.update_collection(devices.get(serial).unwrap());
Ok(())
}
pub fn reload_device_configs(&self) -> Result<(), ConfigError> {
let mut devices = self.loaded_configs.write().unwrap();
let dir = fs::read_dir(self.device_config_path())?;
for item in dir {
let item = item?;
if item.path().is_file() {
if let Some(extension) = item.path().extension() {
if extension == "json" {
let content = fs::read_to_string(item.path())?;
let device = serde_json::from_str::<DeviceConfig>(&content)?;
let serial = device.serial.to_string();
self.get_image_collection(&device.serial).write().unwrap().clear();
if let Some(device_config) = devices.get(&serial) {
*device_config.write().unwrap() = device;
} else {
devices.insert(serial.to_string(), Arc::new(RwLock::new(device)));
}
self.update_collection(devices.get(&serial).unwrap());
}
}
}
}
Ok(())
}
pub fn save_device_config(&self, serial: &str) -> Result<(), ConfigError> {
let devices = self.loaded_configs.read().unwrap();
if let Some(device) = devices.get(serial).cloned() {
self.update_collection(&device);
let mut path = self.device_config_path();
fs::create_dir_all(&path).ok();
path.push(format!("{}.json", serial));
fs::write(path, serde_json::to_string(device.read().unwrap().deref()).unwrap())?;
Ok(())
} else {
Err(ConfigError::DeviceNotFound)
}
}
pub fn save_device_configs(&self) -> Result<(), ConfigError> {
let devices = self.loaded_configs.read().unwrap();
let path = self.device_config_path();
fs::create_dir_all(&path).ok();
for (serial, device) in devices.iter() {
let device= device.clone();
self.update_collection(&device);
let mut file_path = path.clone();
file_path.push(format!("{}.json", serial));
fs::write(file_path, serde_json::to_string(device.read().unwrap().deref()).unwrap())?;
}
Ok(())
}
pub fn get_device_config(&self, serial: &str) -> Option<UniqueDeviceConfig> {
self.loaded_configs.read().unwrap().get(serial).cloned()
}
pub fn set_device_config(&self, serial: &str, config: DeviceConfig) {
let mut handle = self.loaded_configs.write().unwrap();
if let Some(device_config) = handle.get(serial) {
*device_config.write().unwrap() = config;
} else {
handle.insert(serial.to_string(), Arc::new(RwLock::new(config)));
}
}
pub fn get_all_device_configs(&self) -> Vec<UniqueDeviceConfig> {
self.loaded_configs.read().unwrap().values().map(|x| x.clone()).collect()
}
pub fn disable_device_config(&self, serial: &str) -> bool {
let path = self.device_config_path();
let mut initial_path = path.clone();
initial_path.push(format!("{}.json", serial));
let mut new_path = path.clone();
new_path.push(format!("{}.json_disabled", serial));
fs::rename(initial_path, new_path).is_ok()
}
pub fn restore_device_config(&self, serial: &str) -> bool {
let path = self.device_config_path();
let mut initial_path = path.clone();
initial_path.push(format!("{}.json_disabled", serial));
let mut new_path = path.clone();
new_path.push(format!("{}.json", serial));
fs::rename(initial_path, new_path).is_ok()
}
pub fn add_image(&self, serial: &str, image: String) -> Option<String> {
if let Some(config) = self.get_device_config(serial) {
let mut config_handle = config.write().unwrap();
let identifier = hash_str(&image);
if let Ok(image) = SDImage::from_base64(&image, config_handle.kind().image_size()) {
config_handle.images.insert(identifier.clone(), image.into());
drop(config_handle);
self.update_collection(&config);
Some(identifier)
} else {
None
}
} else {
None
}
}
pub fn add_image_encode(&self, serial: &str, image: DynamicImage) -> Option<String> {
if let Some(config) = self.get_device_config(serial) {
let mut config_handle = config.write().unwrap();
let serialized_image = SDImage::SingleImage(resize_for_streamdeck(config_handle.kind().image_size(), image)).into();
let identifier = hash_image(&serialized_image);
config_handle.images.insert(identifier.clone(), serialized_image);
drop(config_handle);
self.update_collection(&config);
return Some(identifier);
}
None
}
pub fn get_images(&self, serial: &str) -> Option<HashMap<String, SDSerializedImage>> {
if let Some(config) = self.get_device_config(serial) {
let config_handle = config.read().unwrap();
Some(config_handle.images.clone())
} else {
None
}
}
pub fn remove_image(&self, serial: &str, identifier: &str) -> bool {
if let Some(config) = self.get_device_config(serial) {
let mut config_handle = config.write().unwrap();
config_handle.images.remove(identifier);
drop(config_handle);
self.remove_from_collection(serial, identifier);
true
} else {
false
}
}
pub fn sync_images(&self, serial: &str) {
if let Some(config) = self.get_device_config(serial) {
self.update_collection(&config);
}
}
pub fn get_image_collection(&self, serial: &str) -> ImageCollection {
let mut handle = self.loaded_images.write().unwrap();
if let Some(collection) = handle.get(serial) {
collection.clone()
} else {
let collection: ImageCollection = Default::default();
handle.insert(serial.to_string(), collection.clone());
collection
}
}
fn update_collection(&self, device_config: &UniqueDeviceConfig) {
let mut device_config = device_config.write().unwrap();
let mut handle = self.loaded_images.write().unwrap();
if let Some(collection) = handle.get_mut(&device_config.serial) {
let mut collection_handle = collection.write().unwrap();
for (key, image) in &device_config.images {
if !collection_handle.contains_key(key) {
if let Ok(image) = image.try_into() {
collection_handle.insert(key.to_string(), image);
}
}
}
for (key, image) in collection_handle.iter() {
if !device_config.images.contains_key(key) {
device_config.images.insert(key.to_string(), image.into());
}
}
}
}
fn remove_from_collection(&self, serial: &str, identifier: &str) {
let mut handle = self.loaded_images.write().unwrap();
if let Some(collection) = handle.get_mut(serial) {
let mut collection_handle = collection.write().unwrap();
collection_handle.remove(identifier);
}
}
}
pub trait PluginConfig {
const NAME: &'static str;
}
#[derive(Debug)]
pub enum ConfigError {
IoError(std::io::Error),
ParseError(serde_json::Error),
DeviceNotFound
}
impl From<std::io::Error> for ConfigError {
fn from(err: std::io::Error) -> Self {
ConfigError::IoError(err)
}
}
impl From<serde_json::Error> for ConfigError {
fn from(err: serde_json::Error) -> Self {
ConfigError::ParseError(err)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct DeviceConfig {
pub vid: u16,
pub pid: u16,
pub serial: String,
pub brightness: u8,
pub layout: RawButtonPanel,
pub images: HashMap<String, SDSerializedImage>,
pub plugin_data: HashMap<String, Value>,
}
impl DeviceConfig {
pub fn kind(&self) -> Kind {
match self.pid {
streamdeck::pids::ORIGINAL_V2 => Kind::OriginalV2,
streamdeck::pids::MINI => Kind::Mini,
streamdeck::pids::MK2 => Kind::Mk2,
streamdeck::pids::XL => Kind::Xl,
_ => Kind::Original,
}
}
}