Compare commits
2 Commits
9ec030488a
...
86e9b072bc
Author | SHA1 | Date | |
---|---|---|---|
86e9b072bc | |||
535f731770 |
@ -17,14 +17,6 @@ pub enum Border {
|
|||||||
Right,
|
Right,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
|
|
||||||
pub struct LedStripConfigOfBorders {
|
|
||||||
pub top: Option<LedStripConfig>,
|
|
||||||
pub bottom: Option<LedStripConfig>,
|
|
||||||
pub left: Option<LedStripConfig>,
|
|
||||||
pub right: Option<LedStripConfig>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
|
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
|
||||||
pub struct LedStripConfig {
|
pub struct LedStripConfig {
|
||||||
pub index: usize,
|
pub index: usize,
|
||||||
@ -119,6 +111,7 @@ impl LedStripConfigGroup {
|
|||||||
mappers.push(SamplePointMapper {
|
mappers.push(SamplePointMapper {
|
||||||
start: (j + i * 4) * 30,
|
start: (j + i * 4) * 30,
|
||||||
end: (j + i * 4 + 1) * 30,
|
end: (j + i * 4 + 1) * 30,
|
||||||
|
pos: (j + i * 4) * 30,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -126,124 +119,11 @@ impl LedStripConfigGroup {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
|
|
||||||
pub struct LedStripConfigOfDisplays {
|
|
||||||
pub id: u32,
|
|
||||||
pub index_of_display: usize,
|
|
||||||
pub led_strip_of_borders: LedStripConfigOfBorders,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LedStripConfigOfBorders {
|
|
||||||
pub fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
top: None,
|
|
||||||
bottom: None,
|
|
||||||
left: None,
|
|
||||||
right: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LedStripConfigOfDisplays {
|
|
||||||
pub fn default(id: u32, index_of_display: usize) -> Self {
|
|
||||||
Self {
|
|
||||||
id,
|
|
||||||
index_of_display,
|
|
||||||
led_strip_of_borders: LedStripConfigOfBorders::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn read_from_disk() -> anyhow::Result<Self> {
|
|
||||||
let path = config_dir()
|
|
||||||
.unwrap_or(current_dir().unwrap())
|
|
||||||
.join("led_strip_config_of_displays.toml");
|
|
||||||
|
|
||||||
let exists = tokio::fs::try_exists(path.clone())
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow::anyhow!("Failed to check config file exists: {}", e))?;
|
|
||||||
|
|
||||||
if exists {
|
|
||||||
let config = tokio::fs::read_to_string(path).await?;
|
|
||||||
|
|
||||||
let config: Self = toml::from_str(&config)
|
|
||||||
.map_err(|e| anyhow::anyhow!("Failed to parse config file: {}", e))?;
|
|
||||||
|
|
||||||
Ok(config)
|
|
||||||
} else {
|
|
||||||
info!("config file not exist, fallback to default config");
|
|
||||||
Ok(Self::get_default_config().await?)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn write_to_disk(&self) -> anyhow::Result<()> {
|
|
||||||
let path = config_dir()
|
|
||||||
.unwrap_or(current_dir().unwrap())
|
|
||||||
.join("led_strip_config_of_displays.toml");
|
|
||||||
|
|
||||||
let config = toml::to_string(self).map_err(|e| {
|
|
||||||
anyhow::anyhow!("Failed to parse config file: {}. config: {:?}", e, self)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
tokio::fs::write(&path, config).await.map_err(|e| {
|
|
||||||
anyhow::anyhow!("Failed to write config file: {}. path: {:?}", e, &path)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_default_config() -> anyhow::Result<Self> {
|
|
||||||
let displays = display_info::DisplayInfo::all().map_err(|e| {
|
|
||||||
error!("can not list display info: {}", e);
|
|
||||||
anyhow::anyhow!("can not list display info: {}", e)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let mut configs = Vec::new();
|
|
||||||
for (i, display) in displays.iter().enumerate() {
|
|
||||||
let config = Self {
|
|
||||||
id: display.id,
|
|
||||||
index_of_display: i,
|
|
||||||
led_strip_of_borders: LedStripConfigOfBorders {
|
|
||||||
top: Some(LedStripConfig {
|
|
||||||
index: i * 4 * 30,
|
|
||||||
display_id: display.id,
|
|
||||||
border: Border::Top,
|
|
||||||
start_pos: i * 4 * 30,
|
|
||||||
len: 30,
|
|
||||||
}),
|
|
||||||
bottom: Some(LedStripConfig {
|
|
||||||
index: i * 4 * 30 + 30,
|
|
||||||
display_id: display.id,
|
|
||||||
border: Border::Bottom,
|
|
||||||
start_pos: i * 4 * 30 + 30,
|
|
||||||
len: 30,
|
|
||||||
}),
|
|
||||||
left: Some(LedStripConfig {
|
|
||||||
index: i * 4 * 30 + 60,
|
|
||||||
display_id: display.id,
|
|
||||||
border: Border::Left,
|
|
||||||
start_pos: i * 4 * 30 + 60,
|
|
||||||
len: 30,
|
|
||||||
}),
|
|
||||||
right: Some(LedStripConfig {
|
|
||||||
index: i * 4 * 30 + 90,
|
|
||||||
display_id: display.id,
|
|
||||||
border: Border::Right,
|
|
||||||
start_pos: i * 4 * 30 + 90,
|
|
||||||
len: 30,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
configs.push(config);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(configs[0])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct SamplePointMapper {
|
pub struct SamplePointMapper {
|
||||||
pub start: usize,
|
pub start: usize,
|
||||||
pub end: usize,
|
pub end: usize,
|
||||||
|
pub pos: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
@ -122,7 +122,8 @@ impl ConfigManager {
|
|||||||
log::info!("mapper: {:?}", mapper);
|
log::info!("mapper: {:?}", mapper);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log::info!("mapper: {:?}", config.mappers[4]);
|
|
||||||
|
Self::rebuild_mappers(&mut config);
|
||||||
|
|
||||||
let cloned_config = config.clone();
|
let cloned_config = config.clone();
|
||||||
|
|
||||||
@ -138,17 +139,31 @@ impl ConfigManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn rebuild_mappers(config: &mut LedStripConfigGroup) {
|
fn rebuild_mappers(config: &mut LedStripConfigGroup) {
|
||||||
let mut prev_end = 0;
|
let mut prev_pos_end = 0;
|
||||||
let mappers: Vec<SamplePointMapper> = config
|
let mappers: Vec<SamplePointMapper> = config
|
||||||
.strips
|
.strips
|
||||||
.iter()
|
.iter()
|
||||||
.map(|strip| {
|
.enumerate()
|
||||||
let mapper = SamplePointMapper {
|
.map(|(index, strip)| {
|
||||||
start: prev_end,
|
let mapper = &config.mappers[index];
|
||||||
end: prev_end + strip.len,
|
|
||||||
};
|
if mapper.start < mapper.end {
|
||||||
prev_end = mapper.end;
|
let mapper = SamplePointMapper {
|
||||||
mapper
|
start: mapper.start,
|
||||||
|
end: mapper.start + strip.len,
|
||||||
|
pos: prev_pos_end,
|
||||||
|
};
|
||||||
|
prev_pos_end = prev_pos_end + strip.len;
|
||||||
|
mapper
|
||||||
|
} else {
|
||||||
|
let mapper = SamplePointMapper {
|
||||||
|
end: mapper.end,
|
||||||
|
start: mapper.end + strip.len,
|
||||||
|
pos: prev_pos_end,
|
||||||
|
};
|
||||||
|
prev_pos_end = prev_pos_end + strip.len;
|
||||||
|
mapper
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
use std::{sync::Arc, time::Duration};
|
use std::{sync::Arc, time::Duration};
|
||||||
|
|
||||||
use paris::warn;
|
use paris::{info, warn};
|
||||||
use tauri::async_runtime::{Mutex, RwLock};
|
use tauri::async_runtime::{Mutex, RwLock};
|
||||||
use tokio::{sync::watch, time::sleep};
|
use tokio::{sync::watch, time::sleep};
|
||||||
|
|
||||||
@ -8,7 +8,7 @@ use crate::{
|
|||||||
ambient_light::{config, ConfigManager},
|
ambient_light::{config, ConfigManager},
|
||||||
rpc::MqttRpc,
|
rpc::MqttRpc,
|
||||||
screenshot::Screenshot,
|
screenshot::Screenshot,
|
||||||
screenshot_manager::ScreenshotManager,
|
screenshot_manager::ScreenshotManager, led_color::LedColor,
|
||||||
};
|
};
|
||||||
|
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
@ -16,8 +16,10 @@ use itertools::Itertools;
|
|||||||
use super::{LedStripConfigGroup, SamplePointConfig};
|
use super::{LedStripConfigGroup, SamplePointConfig};
|
||||||
|
|
||||||
pub struct LedColorsPublisher {
|
pub struct LedColorsPublisher {
|
||||||
rx: Arc<RwLock<watch::Receiver<Vec<u8>>>>,
|
sorted_colors_rx: Arc<RwLock<watch::Receiver<Vec<u8>>>>,
|
||||||
tx: Arc<RwLock<watch::Sender<Vec<u8>>>>,
|
sorted_colors_tx: Arc<RwLock<watch::Sender<Vec<u8>>>>,
|
||||||
|
colors_rx: Arc<RwLock<watch::Receiver<Vec<LedColor>>>>,
|
||||||
|
colors_tx: Arc<RwLock<watch::Sender<Vec<LedColor>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LedColorsPublisher {
|
impl LedColorsPublisher {
|
||||||
@ -25,26 +27,29 @@ impl LedColorsPublisher {
|
|||||||
static LED_COLORS_PUBLISHER_GLOBAL: tokio::sync::OnceCell<LedColorsPublisher> =
|
static LED_COLORS_PUBLISHER_GLOBAL: tokio::sync::OnceCell<LedColorsPublisher> =
|
||||||
tokio::sync::OnceCell::const_new();
|
tokio::sync::OnceCell::const_new();
|
||||||
|
|
||||||
|
let (sorted_tx, sorted_rx) = watch::channel(Vec::new());
|
||||||
let (tx, rx) = watch::channel(Vec::new());
|
let (tx, rx) = watch::channel(Vec::new());
|
||||||
|
|
||||||
LED_COLORS_PUBLISHER_GLOBAL
|
LED_COLORS_PUBLISHER_GLOBAL
|
||||||
.get_or_init(|| async {
|
.get_or_init(|| async {
|
||||||
LedColorsPublisher {
|
LedColorsPublisher {
|
||||||
rx: Arc::new(RwLock::new(rx)),
|
sorted_colors_rx: Arc::new(RwLock::new(sorted_rx)),
|
||||||
tx: Arc::new(RwLock::new(tx)),
|
sorted_colors_tx: Arc::new(RwLock::new(sorted_tx)),
|
||||||
|
colors_rx: Arc::new(RwLock::new(rx)),
|
||||||
|
colors_tx: Arc::new(RwLock::new(tx)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn start(&self) {
|
pub fn start(&self) {
|
||||||
let tx = self.tx.clone();
|
let sorted_colors_tx = self.sorted_colors_tx.clone();
|
||||||
|
let colors_tx = self.colors_tx.clone();
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
loop {
|
loop {
|
||||||
log::info!("colors update loop AAA");
|
let sorted_colors_tx = sorted_colors_tx.write().await;
|
||||||
|
let colors_tx = colors_tx.write().await;
|
||||||
let tx = tx.write().await;
|
|
||||||
let screenshot_manager = ScreenshotManager::global().await;
|
let screenshot_manager = ScreenshotManager::global().await;
|
||||||
|
|
||||||
let config_manager = ConfigManager::global().await;
|
let config_manager = ConfigManager::global().await;
|
||||||
@ -79,13 +84,13 @@ impl LedColorsPublisher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let colors = screenshot_manager
|
let colors = screenshot_manager
|
||||||
.get_all_colors(
|
.get_all_colors(&configs.sample_point_groups, &screenshots)
|
||||||
&configs.sample_point_groups,
|
|
||||||
&configs.mappers,
|
|
||||||
&screenshots,
|
|
||||||
)
|
|
||||||
.await;
|
.await;
|
||||||
match tx.send(colors) {
|
|
||||||
|
let sorted_colors =
|
||||||
|
ScreenshotManager::get_sorted_colors(&colors, &configs.mappers).await;
|
||||||
|
|
||||||
|
match colors_tx.send(colors) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
// log::info!("colors updated");
|
// log::info!("colors updated");
|
||||||
}
|
}
|
||||||
@ -94,17 +99,31 @@ impl LedColorsPublisher {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if some_screenshot_receiver_is_none
|
match sorted_colors_tx.send(sorted_colors) {
|
||||||
|| config_receiver.has_changed().unwrap_or(true)
|
Ok(_) => {
|
||||||
{
|
// log::info!("colors updated");
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
warn!("colors update failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if some_screenshot_receiver_is_none {
|
||||||
|
info!("some screenshot receiver is none. reload.");
|
||||||
sleep(Duration::from_millis(1000)).await;
|
sleep(Duration::from_millis(1000)).await;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if config_receiver.has_changed().unwrap_or(true) {
|
||||||
|
info!("config changed. reload.");
|
||||||
|
sleep(Duration::from_millis(100)).await;
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let rx = self.rx.clone();
|
let rx = self.sorted_colors_rx.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut rx = rx.read().await.clone();
|
let mut rx = rx.read().await.clone();
|
||||||
loop {
|
loop {
|
||||||
@ -136,8 +155,8 @@ impl LedColorsPublisher {
|
|||||||
mqtt.publish_led_sub_pixels(payload).await
|
mqtt.publish_led_sub_pixels(payload).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn clone_receiver(&self) -> watch::Receiver<Vec<u8>> {
|
pub async fn clone_sorted_colors_receiver(&self) -> watch::Receiver<Vec<u8>> {
|
||||||
self.rx.read().await.clone()
|
self.sorted_colors_rx.read().await.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_colors_configs(configs: &LedStripConfigGroup) -> AllColorConfig {
|
pub async fn get_colors_configs(configs: &LedStripConfigGroup) -> AllColorConfig {
|
||||||
@ -207,6 +226,10 @@ impl LedColorsPublisher {
|
|||||||
screenshot_receivers: local_rx_list,
|
screenshot_receivers: local_rx_list,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn clone_colors_receiver(&self) -> watch::Receiver<Vec<LedColor>> {
|
||||||
|
self.colors_rx.read().await.clone()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct AllColorConfig {
|
pub struct AllColorConfig {
|
||||||
|
@ -348,7 +348,24 @@ async fn main() {
|
|||||||
let app_handle = app.handle().clone();
|
let app_handle = app.handle().clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let publisher = ambient_light::LedColorsPublisher::global().await;
|
let publisher = ambient_light::LedColorsPublisher::global().await;
|
||||||
let mut publisher_update_receiver = publisher.clone_receiver().await;
|
let mut publisher_update_receiver = publisher.clone_sorted_colors_receiver().await;
|
||||||
|
loop {
|
||||||
|
if let Err(err) = publisher_update_receiver.changed().await {
|
||||||
|
error!("publisher update receiver changed error: {}", err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let publisher = publisher_update_receiver.borrow().clone();
|
||||||
|
|
||||||
|
app_handle
|
||||||
|
.emit_all("led_sorted_colors_changed", publisher)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let app_handle = app.handle().clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let publisher = ambient_light::LedColorsPublisher::global().await;
|
||||||
|
let mut publisher_update_receiver = publisher.clone_colors_receiver().await;
|
||||||
loop {
|
loop {
|
||||||
if let Err(err) = publisher_update_receiver.changed().await {
|
if let Err(err) = publisher_update_receiver.changed().await {
|
||||||
error!("publisher update receiver changed error: {}", err);
|
error!("publisher update receiver changed error: {}", err);
|
||||||
|
@ -10,7 +10,7 @@ use tokio::sync::{watch, OnceCell};
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
ambient_light::{SamplePointConfig, SamplePointMapper},
|
ambient_light::{SamplePointConfig, SamplePointMapper},
|
||||||
screenshot::{LedSamplePoints, ScreenSamplePoints, Screenshot, ScreenshotPayload},
|
screenshot::{LedSamplePoints, ScreenSamplePoints, Screenshot, ScreenshotPayload}, led_color::LedColor,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn take_screenshot(display_id: u32, scale_factor: f32) -> anyhow::Result<Screenshot> {
|
pub fn take_screenshot(display_id: u32, scale_factor: f32) -> anyhow::Result<Screenshot> {
|
||||||
@ -218,14 +218,9 @@ impl ScreenshotManager {
|
|||||||
pub async fn get_all_colors(
|
pub async fn get_all_colors(
|
||||||
&self,
|
&self,
|
||||||
configs: &Vec<SamplePointConfig>,
|
configs: &Vec<SamplePointConfig>,
|
||||||
mappers: &Vec<SamplePointMapper>,
|
|
||||||
screenshots: &Vec<Screenshot>,
|
screenshots: &Vec<Screenshot>,
|
||||||
) -> Vec<u8> {
|
) -> Vec<LedColor> {
|
||||||
let total_leds = configs
|
|
||||||
.iter()
|
|
||||||
.fold(0, |acc, config| acc + config.points.len());
|
|
||||||
|
|
||||||
let mut global_colors = vec![0u8; total_leds * 3];
|
|
||||||
let mut all_colors = vec![];
|
let mut all_colors = vec![];
|
||||||
|
|
||||||
for (index, screenshot) in screenshots.iter().enumerate() {
|
for (index, screenshot) in screenshots.iter().enumerate() {
|
||||||
@ -235,20 +230,42 @@ impl ScreenshotManager {
|
|||||||
all_colors.append(&mut colors);
|
all_colors.append(&mut colors);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
all_colors
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_sorted_colors(colors: &Vec<LedColor>, mappers: &Vec<SamplePointMapper>) -> Vec<u8> {
|
||||||
|
let total_leds = mappers
|
||||||
|
.iter()
|
||||||
|
.map(|mapper| usize::max(mapper.start, mapper.end))
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0) as usize;
|
||||||
|
let mut global_colors = vec![0u8; total_leds * 3];
|
||||||
|
|
||||||
let mut color_index = 0;
|
let mut color_index = 0;
|
||||||
mappers.iter().for_each(|group| {
|
mappers.iter().for_each(|group| {
|
||||||
if group.end > all_colors.len() || group.start > all_colors.len() {
|
if group.end > global_colors.len() || group.start > global_colors.len() {
|
||||||
warn!(
|
warn!(
|
||||||
"get_all_colors: group out of range. start: {}, end: {}, all_colors.len(): {}",
|
"get_sorted_colors: group out of range. start: {}, end: {}, global_colors.len(): {}",
|
||||||
group.start,
|
group.start,
|
||||||
group.end,
|
group.end,
|
||||||
all_colors.len()
|
global_colors.len()
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if color_index + group.start.abs_diff(group.end) > colors.len() {
|
||||||
|
warn!(
|
||||||
|
"get_sorted_colors: color_index out of range. color_index: {}, strip len: {}, colors.len(): {}",
|
||||||
|
color_index,
|
||||||
|
group.start.abs_diff(group.end),
|
||||||
|
colors.len()
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if group.end > group.start {
|
if group.end > group.start {
|
||||||
for i in group.start..group.end {
|
for i in group.start..group.end {
|
||||||
let rgb = all_colors[color_index].get_rgb();
|
let rgb = colors[color_index].get_rgb();
|
||||||
color_index += 1;
|
color_index += 1;
|
||||||
|
|
||||||
global_colors[i * 3] = rgb[0];
|
global_colors[i * 3] = rgb[0];
|
||||||
@ -257,7 +274,7 @@ impl ScreenshotManager {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for i in (group.end..group.start).rev() {
|
for i in (group.end..group.start).rev() {
|
||||||
let rgb = all_colors[color_index].get_rgb();
|
let rgb = colors[color_index].get_rgb();
|
||||||
color_index += 1;
|
color_index += 1;
|
||||||
|
|
||||||
global_colors[i * 3] = rgb[0];
|
global_colors[i * 3] = rgb[0];
|
||||||
|
17
src/App.tsx
17
src/App.tsx
@ -44,7 +44,7 @@ function App() {
|
|||||||
|
|
||||||
// listen to led_colors_changed event
|
// listen to led_colors_changed event
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
const unlisten = listen<Uint8ClampedArray>('led_colors_changed', (event) => {
|
const unlisten = listen<Array<string>>('led_colors_changed', (event) => {
|
||||||
const colors = event.payload;
|
const colors = event.payload;
|
||||||
|
|
||||||
setLedStripStore({
|
setLedStripStore({
|
||||||
@ -57,6 +57,21 @@ function App() {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// listen to led_sorted_colors_changed event
|
||||||
|
createEffect(() => {
|
||||||
|
const unlisten = listen<Uint8ClampedArray>('led_sorted_colors_changed', (event) => {
|
||||||
|
const sortedColors = event.payload;
|
||||||
|
|
||||||
|
setLedStripStore({
|
||||||
|
sortedColors,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
onCleanup(() => {
|
||||||
|
unlisten.then((unlisten) => unlisten());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const [ledStripConfiguration, setLedStripConfiguration] = createStore<
|
const [ledStripConfiguration, setLedStripConfiguration] = createStore<
|
||||||
LedStripConfigurationContextType[0]
|
LedStripConfigurationContextType[0]
|
||||||
>({
|
>({
|
||||||
|
@ -16,6 +16,7 @@ import { useTippy } from 'solid-tippy';
|
|||||||
import { followCursor } from 'tippy.js';
|
import { followCursor } from 'tippy.js';
|
||||||
import { LedStripConfig } from '../models/led-strip-config';
|
import { LedStripConfig } from '../models/led-strip-config';
|
||||||
import { LedStripConfigurationContext } from '../contexts/led-strip-configuration.context';
|
import { LedStripConfigurationContext } from '../contexts/led-strip-configuration.context';
|
||||||
|
import { ledStripStore } from '../stores/led-strip.store';
|
||||||
|
|
||||||
type LedStripPartProps = {
|
type LedStripPartProps = {
|
||||||
config?: LedStripConfig | null;
|
config?: LedStripConfig | null;
|
||||||
@ -55,44 +56,31 @@ export const LedStripPart: Component<LedStripPartProps> = (props) => {
|
|||||||
const [ledSamplePoints, setLedSamplePoints] = createSignal();
|
const [ledSamplePoints, setLedSamplePoints] = createSignal();
|
||||||
const [colors, setColors] = createSignal<string[]>([]);
|
const [colors, setColors] = createSignal<string[]>([]);
|
||||||
|
|
||||||
// get led strip colors when screenshot updated
|
// update led strip colors from global store
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
const samplePoints = ledSamplePoints();
|
if (!localProps.config) {
|
||||||
if (!localProps.config || !samplePoints) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let pendingCount = 0;
|
const index = ledStripStore.strips.findIndex(
|
||||||
const unlisten = listen<{
|
(s) =>
|
||||||
base64_image: string;
|
s.display_id === localProps.config!.display_id &&
|
||||||
display_id: number;
|
s.border === localProps.config!.border,
|
||||||
height: number;
|
);
|
||||||
width: number;
|
|
||||||
}>('encoded-screenshot-updated', (event) => {
|
|
||||||
if (event.payload.display_id !== localProps.config!.display_id) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (pendingCount >= 1) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
pendingCount++;
|
|
||||||
|
|
||||||
invoke<string[]>('get_one_edge_colors', {
|
if (index === -1) {
|
||||||
samplePoints,
|
return;
|
||||||
displayId: event.payload.display_id,
|
}
|
||||||
})
|
|
||||||
.then((colors) => {
|
|
||||||
setColors(colors);
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
pendingCount--;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
subscribeScreenshotUpdate(localProps.config.display_id);
|
|
||||||
|
|
||||||
onCleanup(() => {
|
const mapper = ledStripStore.mappers[index];
|
||||||
unlisten.then((unlisten) => unlisten());
|
if (!mapper) {
|
||||||
});
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const offset = mapper.pos;
|
||||||
|
|
||||||
|
const colors = ledStripStore.colors.slice(offset, offset + localProps.config.len);
|
||||||
|
setColors(colors);
|
||||||
});
|
});
|
||||||
|
|
||||||
// get led strip sample points
|
// get led strip sample points
|
||||||
|
@ -12,21 +12,18 @@ import { LedStripConfig, LedStripPixelMapper } from '../models/led-strip-config'
|
|||||||
import { ledStripStore } from '../stores/led-strip.store';
|
import { ledStripStore } from '../stores/led-strip.store';
|
||||||
import { invoke } from '@tauri-apps/api';
|
import { invoke } from '@tauri-apps/api';
|
||||||
import { LedStripConfigurationContext } from '../contexts/led-strip-configuration.context';
|
import { LedStripConfigurationContext } from '../contexts/led-strip-configuration.context';
|
||||||
|
import background from '../assets/transparent-grid-background.svg?url';
|
||||||
|
|
||||||
const SorterItem: Component<{ strip: LedStripConfig; mapper: LedStripPixelMapper }> = (
|
const SorterItem: Component<{ strip: LedStripConfig; mapper: LedStripPixelMapper }> = (
|
||||||
props,
|
props,
|
||||||
) => {
|
) => {
|
||||||
const [fullLeds, setFullLeds] = createSignal<string[]>([]);
|
const [fullLeds, setFullLeds] = createSignal<Array<string | null>>([]);
|
||||||
const [dragging, setDragging] = createSignal<boolean>(false);
|
const [dragging, setDragging] = createSignal<boolean>(false);
|
||||||
const [dragStart, setDragStart] = createSignal<{ x: number; y: number } | null>(null);
|
const [dragStart, setDragStart] = createSignal<{ x: number; y: number } | null>(null);
|
||||||
const [dragCurr, setDragCurr] = createSignal<{ x: number; y: number } | null>(null);
|
const [dragCurr, setDragCurr] = createSignal<{ x: number; y: number } | null>(null);
|
||||||
const [dragStartIndex, setDragStartIndex] = createSignal<number>(0);
|
const [dragStartIndex, setDragStartIndex] = createSignal<number>(0);
|
||||||
const [, { setSelectedStripPart }] = useContext(LedStripConfigurationContext);
|
const [, { setSelectedStripPart }] = useContext(LedStripConfigurationContext);
|
||||||
|
|
||||||
const totalLedCount = createMemo(() => {
|
|
||||||
return ledStripStore.strips.reduce((acc, strip) => acc + strip.len, 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
const move = (targetStart: number) => {
|
const move = (targetStart: number) => {
|
||||||
if (targetStart === props.mapper.start) {
|
if (targetStart === props.mapper.start) {
|
||||||
return;
|
return;
|
||||||
@ -70,7 +67,8 @@ const SorterItem: Component<{ strip: LedStripConfig; mapper: LedStripPixelMapper
|
|||||||
}
|
}
|
||||||
setDragCurr({ x: ev.clientX, y: ev.clientY });
|
setDragCurr({ x: ev.clientX, y: ev.clientY });
|
||||||
|
|
||||||
const cellWidth = (ev.currentTarget as HTMLDivElement).clientWidth / totalLedCount();
|
const cellWidth =
|
||||||
|
(ev.currentTarget as HTMLDivElement).clientWidth / ledStripStore.totalLedCount;
|
||||||
const diff = ev.clientX - dragStart()!.x;
|
const diff = ev.clientX - dragStart()!.x;
|
||||||
const moved = Math.round(diff / cellWidth);
|
const moved = Math.round(diff / cellWidth);
|
||||||
if (moved === 0) {
|
if (moved === 0) {
|
||||||
@ -85,12 +83,14 @@ const SorterItem: Component<{ strip: LedStripConfig; mapper: LedStripPixelMapper
|
|||||||
|
|
||||||
// update fullLeds
|
// update fullLeds
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
const fullLeds = new Array(totalLedCount()).fill('rgba(255,255,255,0.5)');
|
const fullLeds = new Array(ledStripStore.totalLedCount).fill(null);
|
||||||
|
|
||||||
for (let i = props.mapper.start, j = 0; i < props.mapper.end; i++, j++) {
|
for (
|
||||||
fullLeds[i] = `rgb(${ledStripStore.colors[i * 3]}, ${
|
let i = props.mapper.start, j = props.mapper.pos;
|
||||||
ledStripStore.colors[i * 3 + 1]
|
i < props.mapper.end;
|
||||||
}, ${ledStripStore.colors[i * 3 + 2]})`;
|
i++, j++
|
||||||
|
) {
|
||||||
|
fullLeds[i] = ledStripStore.colors[j];
|
||||||
}
|
}
|
||||||
setFullLeds(fullLeds);
|
setFullLeds(fullLeds);
|
||||||
});
|
});
|
||||||
@ -114,11 +114,12 @@ const SorterItem: Component<{ strip: LedStripConfig; mapper: LedStripPixelMapper
|
|||||||
{(it) => (
|
{(it) => (
|
||||||
<div
|
<div
|
||||||
class="flex-auto flex h-full w-full justify-center items-center relative"
|
class="flex-auto flex h-full w-full justify-center items-center relative"
|
||||||
title={it}
|
title={it ?? ''}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
class="absolute top-1/2 -translate-y-1/2 h-2.5 w-2.5 rounded-full ring-1 ring-stone-300"
|
class="absolute top-1/2 -translate-y-1/2 h-2.5 w-2.5 rounded-full ring-1 ring-stone-100"
|
||||||
style={{ background: it }}
|
classList={{ 'ring-stone-300/50': !it }}
|
||||||
|
style={{ background: it ?? 'transparent' }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@ -131,15 +132,13 @@ const SorterResult: Component = () => {
|
|||||||
const [fullLeds, setFullLeds] = createSignal<string[]>([]);
|
const [fullLeds, setFullLeds] = createSignal<string[]>([]);
|
||||||
|
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
const strips = ledStripStore.strips;
|
const fullLeds = new Array(ledStripStore.totalLedCount).fill('rgba(255,255,255,0.1)');
|
||||||
const totalLedCount = strips.reduce((acc, strip) => acc + strip.len, 0);
|
|
||||||
const fullLeds = new Array(totalLedCount).fill('rgba(255,255,255,0.5)');
|
|
||||||
|
|
||||||
ledStripStore.mappers.forEach((mapper) => {
|
ledStripStore.mappers.forEach((mapper) => {
|
||||||
for (let i = mapper.start, j = 0; i < mapper.end; i++, j++) {
|
for (let i = mapper.start, j = 0; i < mapper.end; i++, j++) {
|
||||||
fullLeds[i] = `rgb(${ledStripStore.colors[i * 3]}, ${
|
fullLeds[i] = `rgb(${ledStripStore.sortedColors[i * 3]}, ${
|
||||||
ledStripStore.colors[i * 3 + 1]
|
ledStripStore.sortedColors[i * 3 + 1]
|
||||||
}, ${ledStripStore.colors[i * 3 + 2]})`;
|
}, ${ledStripStore.sortedColors[i * 3 + 2]})`;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
setFullLeds(fullLeds);
|
setFullLeds(fullLeds);
|
||||||
@ -168,7 +167,12 @@ export const LedStripPartsSorter: Component = () => {
|
|||||||
const context = createContext();
|
const context = createContext();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div class="select-none overflow-hidden">
|
<div
|
||||||
|
class="select-none overflow-hidden"
|
||||||
|
style={{
|
||||||
|
'background-image': `url(${background})`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
<SorterResult />
|
<SorterResult />
|
||||||
<For each={ledStripStore.strips}>
|
<For each={ledStripStore.strips}>
|
||||||
{(strip, index) => (
|
{(strip, index) => (
|
||||||
|
@ -3,6 +3,7 @@ import { Borders } from '../constants/border';
|
|||||||
export type LedStripPixelMapper = {
|
export type LedStripPixelMapper = {
|
||||||
start: number;
|
start: number;
|
||||||
end: number;
|
end: number;
|
||||||
|
pos: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type LedStripConfigContainer = {
|
export type LedStripConfigContainer = {
|
||||||
|
@ -1,10 +1,12 @@
|
|||||||
import { createStore } from 'solid-js/store';
|
import { createStore } from 'solid-js/store';
|
||||||
import { DisplayConfig } from '../models/display-config';
|
|
||||||
import { LedStripConfig, LedStripPixelMapper } from '../models/led-strip-config';
|
import { LedStripConfig, LedStripPixelMapper } from '../models/led-strip-config';
|
||||||
|
|
||||||
export const [ledStripStore, setLedStripStore] = createStore({
|
export const [ledStripStore, setLedStripStore] = createStore({
|
||||||
displays: new Array<DisplayConfig>(),
|
|
||||||
strips: new Array<LedStripConfig>(),
|
strips: new Array<LedStripConfig>(),
|
||||||
mappers: new Array<LedStripPixelMapper>(),
|
mappers: new Array<LedStripPixelMapper>(),
|
||||||
colors: new Uint8ClampedArray(),
|
colors: new Array<string>(),
|
||||||
|
sortedColors: new Uint8ClampedArray(),
|
||||||
|
get totalLedCount() {
|
||||||
|
return Math.max(0, ...ledStripStore.mappers.map((m) => Math.max(m.start, m.end)));
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
Loading…
Reference in New Issue
Block a user