feat(gui, ambient_light): 鼠标滚轮修改 LED 灯条的灯珠数。

This commit is contained in:
Ivan Li 2023-03-26 22:39:47 +08:00
parent 3e54d30498
commit 58e8c30fe2
14 changed files with 452 additions and 127 deletions

35
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,35 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Tauri Development Debug",
"cargo": {
"args": [
"build",
"--manifest-path=./src-tauri/Cargo.toml",
"--no-default-features"
]
},
// task for the `beforeDevCommand` if used, must be configured in `.vscode/tasks.json`
"preLaunchTask": "ui:dev"
},
{
"type": "lldb",
"request": "launch",
"name": "Tauri Production Debug",
"cargo": {
"args": [
"build",
"--release",
"--manifest-path=./src-tauri/Cargo.toml"
]
},
// task for the `beforeBuildCommand` if used, must be configured in `.vscode/tasks.json`
"preLaunchTask": "ui:build"
}
]

29
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,29 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "ui:dev",
"type": "shell",
// `dev` keeps running in the background
// ideally you should also configure a `problemMatcher`
// see https://code.visualstudio.com/docs/editor/tasks#_can-a-background-task-be-used-as-a-prelaunchtask-in-launchjson
"isBackground": true,
// change this to your `beforeDevCommand`:
"command": "yarn",
"args": [
"dev"
]
},
{
"label": "ui:build",
"type": "shell",
// change this to your `beforeBuildCommand`:
"command": "yarn",
"args": [
"build"
]
}
]
}

View File

@ -3,8 +3,9 @@ use std::env::current_dir;
use paris::{error, info}; use paris::{error, info};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tauri::api::path::config_dir; use tauri::api::path::config_dir;
use tokio::sync::OnceCell;
#[derive(Clone, Copy, Serialize, Deserialize, Debug)] #[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq)]
pub enum Border { pub enum Border {
Top, Top,
Bottom, Bottom,
@ -29,7 +30,20 @@ pub struct LedStripConfig {
pub len: usize, pub len: usize,
} }
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct LedStripConfigGroup {
pub items: Vec<LedStripConfig>,
}
impl LedStripConfig { impl LedStripConfig {
pub async fn global() -> &'static Vec<LedStripConfig> {
static LED_STRIP_CONFIGS_GLOBAL: OnceCell<Vec<LedStripConfig>> = OnceCell::const_new();
LED_STRIP_CONFIGS_GLOBAL
.get_or_init(|| async { Self::read_config().await.unwrap() })
.await
}
pub async fn read_config() -> anyhow::Result<Vec<Self>> { pub async fn read_config() -> anyhow::Result<Vec<Self>> {
// config path // config path
let path = config_dir() let path = config_dir()
@ -43,10 +57,10 @@ impl LedStripConfig {
if exists { if exists {
let config = tokio::fs::read_to_string(path).await?; let config = tokio::fs::read_to_string(path).await?;
let config: Vec<Self> = toml::from_str(&config) let config: LedStripConfigGroup = toml::from_str(&config)
.map_err(|e| anyhow::anyhow!("Failed to parse config file: {}", e))?; .map_err(|e| anyhow::anyhow!("Failed to parse config file: {}", e))?;
Ok(config) Ok(config.items)
} else { } else {
info!("config file not exist, fallback to default config"); info!("config file not exist, fallback to default config");
Ok(Self::get_default_config().await?) Ok(Self::get_default_config().await?)
@ -58,12 +72,15 @@ impl LedStripConfig {
.unwrap_or(current_dir().unwrap()) .unwrap_or(current_dir().unwrap())
.join("led_strip_config.toml"); .join("led_strip_config.toml");
let config = toml::to_string(configs) let configs = LedStripConfigGroup { items: configs.clone() };
.map_err(|e| anyhow::anyhow!("Failed to parse config file: {}", e))?;
tokio::fs::write(path, config) let config = toml::to_string(&configs).map_err(|e| {
.await anyhow::anyhow!("Failed to parse config file: {}. configs: {:?}", e, configs)
.map_err(|e| anyhow::anyhow!("Failed to write config file: {}", e))?; })?;
tokio::fs::write(&path, config).await.map_err(|e| {
anyhow::anyhow!("Failed to write config file: {}. path: {:?}", e, &path)
})?;
Ok(()) Ok(())
} }
@ -99,13 +116,10 @@ impl LedStripConfig {
} }
#[derive(Clone, Copy, Serialize, Deserialize, Debug)] #[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct DisplayConfig { pub struct LedStripConfigOfDisplays {
pub id: u32, pub id: u32,
pub index_of_display: usize, pub index_of_display: usize,
pub display_width: usize,
pub display_height: usize,
pub led_strip_of_borders: LedStripConfigOfBorders, pub led_strip_of_borders: LedStripConfigOfBorders,
pub scale_factor: f32,
} }
impl LedStripConfigOfBorders { impl LedStripConfigOfBorders {
@ -119,21 +133,98 @@ impl LedStripConfigOfBorders {
} }
} }
impl DisplayConfig { impl LedStripConfigOfDisplays {
pub fn default( pub fn default(id: u32, index_of_display: usize) -> Self {
id: u32,
index_of_display: usize,
display_width: usize,
display_height: usize,
scale_factor: f32,
) -> Self {
Self { Self {
id, id,
index_of_display, index_of_display,
display_width,
display_height,
led_strip_of_borders: LedStripConfigOfBorders::default(), led_strip_of_borders: LedStripConfigOfBorders::default(),
scale_factor,
} }
} }
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])
}
} }

View File

@ -0,0 +1,88 @@
use std::{sync::Arc, borrow::Borrow};
use tauri::async_runtime::RwLock;
use tokio::sync::OnceCell;
use crate::ambient_light::{config, LedStripConfig};
use super::Border;
pub struct ConfigManager {
configs: Arc<RwLock<Vec<LedStripConfig>>>,
config_update_receiver: tokio::sync::watch::Receiver<Vec<LedStripConfig>>,
config_update_sender: tokio::sync::watch::Sender<Vec<LedStripConfig>>,
}
impl ConfigManager {
pub async fn global() -> &'static Self {
static CONFIG_MANAGER_GLOBAL: OnceCell<ConfigManager> = OnceCell::const_new();
CONFIG_MANAGER_GLOBAL
.get_or_init(|| async {
let configs = LedStripConfig::read_config().await.unwrap();
let (config_update_sender, config_update_receiver) =
tokio::sync::watch::channel(configs.clone());
ConfigManager {
configs: Arc::new(RwLock::new(configs)),
config_update_receiver,
config_update_sender,
}
})
.await
}
pub async fn reload(&self) -> anyhow::Result<()> {
let mut configs = self.configs.write().await;
*configs = LedStripConfig::read_config().await?;
Ok(())
}
pub async fn update(&self, configs: &Vec<LedStripConfig>) -> anyhow::Result<()> {
LedStripConfig::write_config(configs).await?;
self.reload().await?;
self.config_update_sender.send(configs.clone()).map_err(|e| {
anyhow::anyhow!("Failed to send config update: {}", e)
})?;
log::info!("config updated: {:?}", configs);
Ok(())
}
pub async fn configs(&self) -> Vec<LedStripConfig> {
self.configs.read().await.clone()
}
pub async fn patch_led_strip_len(&self, display_id: u32, border: Border, delta_len: i8) -> anyhow::Result<()> {
let mut configs = self.configs.write().await;
for config in configs.iter_mut() {
if config.display_id == display_id && config.border == border {
let target = config.len as i64 + delta_len as i64;
if target < 0 || target > 1000 {
return Err(anyhow::anyhow!("Overflow. range: 0-1000, current: {}", target));
}
config.len = target as usize;
}
}
let cloned_config = configs.clone();
drop(configs);
self.update(&cloned_config).await?;
self.config_update_sender
.send(cloned_config)
.map_err(|e| anyhow::anyhow!("Failed to send config update: {}", e))?;
Ok(())
}
pub fn clone_config_update_receiver(
&self,
) -> tokio::sync::watch::Receiver<Vec<LedStripConfig>> {
self.config_update_receiver.clone()
}
}

View File

@ -1,3 +1,5 @@
mod config; mod config;
mod config_manager;
pub use config::*; pub use config::*;
pub use config_manager::*;

View File

@ -7,7 +7,7 @@ mod led_color;
pub mod screenshot; pub mod screenshot;
mod screenshot_manager; mod screenshot_manager;
use ambient_light::LedStripConfig; use ambient_light::{Border, LedStripConfig};
use core_graphics::display::{ use core_graphics::display::{
kCGNullWindowID, kCGWindowImageDefault, kCGWindowListOptionOnScreenOnly, CGDisplay, kCGNullWindowID, kCGWindowImageDefault, kCGWindowListOptionOnScreenOnly, CGDisplay,
}; };
@ -17,7 +17,7 @@ use screenshot::Screenshot;
use screenshot_manager::ScreenshotManager; use screenshot_manager::ScreenshotManager;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::to_string; use serde_json::to_string;
use tauri::{http::ResponseBuilder, regex}; use tauri::{http::ResponseBuilder, regex, Manager};
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(remote = "DisplayInfo")] #[serde(remote = "DisplayInfo")]
@ -105,8 +105,7 @@ async fn get_led_strips_sample_points(
let screenshot = rx.borrow().clone(); let screenshot = rx.borrow().clone();
let width = screenshot.width; let width = screenshot.width;
let height = screenshot.height; let height = screenshot.height;
let sample_points = let sample_points = Screenshot::get_sample_point(&config, width as usize, height as usize);
Screenshot::get_sample_point(&config, width as usize, height as usize);
Ok(sample_points) Ok(sample_points)
} else { } else {
return Err(format!("display not found: {}", config.display_id)); return Err(format!("display not found: {}", config.display_id));
@ -132,6 +131,22 @@ async fn get_one_edge_colors(
} }
} }
#[tauri::command]
async fn patch_led_strip_len(display_id: u32, border: Border, delta_len: i8) -> Result<(), String> {
info!("patch_led_strip_len: {} {:?} {}", display_id, border, delta_len);
let config_manager = ambient_light::ConfigManager::global().await;
config_manager
.patch_led_strip_len(display_id, border, delta_len)
.await
.map_err(|e| {
error!("can not patch led strip len: {}", e);
e.to_string()
})?;
info!("patch_led_strip_len: ok");
Ok(())
}
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
env_logger::init(); env_logger::init();
@ -146,7 +161,8 @@ async fn main() {
read_led_strip_configs, read_led_strip_configs,
write_led_strip_configs, write_led_strip_configs,
get_led_strips_sample_points, get_led_strips_sample_points,
get_one_edge_colors get_one_edge_colors,
patch_led_strip_len
]) ])
.register_uri_scheme_protocol("ambient-light", move |_app, request| { .register_uri_scheme_protocol("ambient-light", move |_app, request| {
let response = ResponseBuilder::new().header("Access-Control-Allow-Origin", "*"); let response = ResponseBuilder::new().header("Access-Control-Allow-Origin", "*");
@ -275,6 +291,28 @@ async fn main() {
.status(500) .status(500)
.body(err.to_string().into_bytes()); .body(err.to_string().into_bytes());
}) })
.setup(move |app| {
let app_handle = app.handle().clone();
tokio::spawn(async move {
let config_manager = ambient_light::ConfigManager::global().await;
let config_update_receiver = config_manager.clone_config_update_receiver();
let mut config_update_receiver = config_update_receiver;
loop {
if let Err(err) = config_update_receiver.changed().await {
error!("config update receiver changed error: {}", err);
return;
}
log::info!("config changed. emit config_changed event.");
let config = config_update_receiver.borrow().clone();
app_handle.emit_all("config_changed", config).unwrap();
}
});
Ok(())
})
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");
} }

View File

@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
use tauri::async_runtime::RwLock; use tauri::async_runtime::RwLock;
use crate::{ use crate::{
ambient_light::{DisplayConfig, LedStripConfig}, ambient_light::{LedStripConfigOfDisplays, LedStripConfig},
led_color::LedColor, led_color::LedColor,
}; };
@ -80,92 +80,92 @@ impl Screenshot {
} }
} }
fn get_sample_points(config: DisplayConfig) -> ScreenSamplePoints { // fn get_sample_points(config: DisplayConfig) -> ScreenSamplePoints {
let top = match config.led_strip_of_borders.top { // let top = match config.led_strip_of_borders.top {
Some(led_strip_config) => Self::get_one_edge_sample_points( // Some(led_strip_config) => Self::get_one_edge_sample_points(
config.display_height / 8, // config.display_height / 8,
config.display_width, // config.display_width,
led_strip_config.len, // led_strip_config.len,
1, // 1,
), // ),
None => { // None => {
vec![] // vec![]
} // }
}; // };
let bottom: Vec<LedSamplePoints> = match config.led_strip_of_borders.bottom { // let bottom: Vec<LedSamplePoints> = match config.led_strip_of_borders.bottom {
Some(led_strip_config) => { // Some(led_strip_config) => {
let points = Self::get_one_edge_sample_points( // let points = Self::get_one_edge_sample_points(
config.display_height / 9, // config.display_height / 9,
config.display_width, // config.display_width,
led_strip_config.len, // led_strip_config.len,
5, // 5,
); // );
points // points
.into_iter() // .into_iter()
.map(|groups| -> Vec<Point> { // .map(|groups| -> Vec<Point> {
groups // groups
.into_iter() // .into_iter()
.map(|(x, y)| (x, config.display_height - y)) // .map(|(x, y)| (x, config.display_height - y))
.collect() // .collect()
}) // })
.collect() // .collect()
} // }
None => { // None => {
vec![] // vec![]
} // }
}; // };
let left: Vec<LedSamplePoints> = match config.led_strip_of_borders.left { // let left: Vec<LedSamplePoints> = match config.led_strip_of_borders.left {
Some(led_strip_config) => { // Some(led_strip_config) => {
let points = Self::get_one_edge_sample_points( // let points = Self::get_one_edge_sample_points(
config.display_width / 16, // config.display_width / 16,
config.display_height, // config.display_height,
led_strip_config.len, // led_strip_config.len,
5, // 5,
); // );
points // points
.into_iter() // .into_iter()
.map(|groups| -> Vec<Point> { // .map(|groups| -> Vec<Point> {
groups.into_iter().map(|(x, y)| (y, x)).collect() // groups.into_iter().map(|(x, y)| (y, x)).collect()
}) // })
.collect() // .collect()
} // }
None => { // None => {
vec![] // vec![]
} // }
}; // };
let right: Vec<LedSamplePoints> = match config.led_strip_of_borders.right { // let right: Vec<LedSamplePoints> = match config.led_strip_of_borders.right {
Some(led_strip_config) => { // Some(led_strip_config) => {
let points = Self::get_one_edge_sample_points( // let points = Self::get_one_edge_sample_points(
config.display_width / 16, // config.display_width / 16,
config.display_height, // config.display_height,
led_strip_config.len, // led_strip_config.len,
5, // 5,
); // );
points // points
.into_iter() // .into_iter()
.map(|groups| -> Vec<Point> { // .map(|groups| -> Vec<Point> {
groups // groups
.into_iter() // .into_iter()
.map(|(x, y)| (config.display_width - y, x)) // .map(|(x, y)| (config.display_width - y, x))
.collect() // .collect()
}) // })
.collect() // .collect()
} // }
None => { // None => {
vec![] // vec![]
} // }
}; // };
ScreenSamplePoints { // ScreenSamplePoints {
top, // top,
bottom, // bottom,
left, // left,
right, // right,
} // }
} // }
fn get_one_edge_sample_points( fn get_one_edge_sample_points(
width: usize, width: usize,

BIN
src/.DS_Store vendored Normal file

Binary file not shown.

View File

@ -1,11 +1,11 @@
import { createEffect } from 'solid-js'; import { createEffect, onCleanup } from 'solid-js';
import { convertFileSrc, invoke } from '@tauri-apps/api/tauri'; import { invoke } from '@tauri-apps/api/tauri';
import { DisplayView } from './components/display-view'; import { DisplayView } from './components/display-view';
import { DisplayListContainer } from './components/display-list-container'; import { DisplayListContainer } from './components/display-list-container';
import { displayStore, setDisplayStore } from './stores/display.store'; import { displayStore, setDisplayStore } from './stores/display.store';
import { path } from '@tauri-apps/api';
import { LedStripConfig } from './models/led-strip-config'; import { LedStripConfig } from './models/led-strip-config';
import { setLedStripStore } from './stores/led-strip.store'; import { setLedStripStore } from './stores/led-strip.store';
import { listen } from '@tauri-apps/api/event';
function App() { function App() {
createEffect(() => { createEffect(() => {
@ -15,14 +15,26 @@ function App() {
}); });
}); });
invoke<LedStripConfig[]>('read_led_strip_configs').then((strips) => { invoke<LedStripConfig[]>('read_led_strip_configs').then((strips) => {
console.log(strips);
setLedStripStore({ setLedStripStore({
strips, strips,
}); });
}); });
}); });
// register tauri event listeners
createEffect(() => {
const unlisten = listen('config_changed', (event) => {
const strips = event.payload as LedStripConfig[];
setLedStripStore({
strips,
});
});
onCleanup(() => {
unlisten.then((unlisten) => unlisten());
});
});
return ( return (
<div> <div>
<DisplayListContainer> <DisplayListContainer>

View File

@ -0,0 +1,16 @@
<!-- http://mike.eire.ca/2010/02/25/easy-svg-grid/ -->
<!-- "I needed a grid in the background while I was debugging an SVG image I was creating, something
like Photoshops transparency grid. Heres what I did." -->
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="200" height="400">
<defs>
<pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse">
<rect fill="black" x="0" y="0" width="5" height="5" opacity="0.3" />
<rect fill="white" x="5" y="0" width="5" height="5" />
<rect fill="black" x="5" y="5" width="5" height="5" opacity="0.3" />
<rect fill="white" x="0" y="5" width="5" height="5" />
</pattern>
</defs>
<rect fill="url(#grid)" x="0" y="0" width="100%" height="100%" />
</svg>

After

Width:  |  Height:  |  Size: 759 B

View File

@ -7,7 +7,7 @@ type DisplayInfoItemProps = {
export const DisplayInfoItem: ParentComponent<DisplayInfoItemProps> = (props) => { export const DisplayInfoItem: ParentComponent<DisplayInfoItemProps> = (props) => {
return ( return (
<dl class="px-3 py-1 flex hover:bg-gray-100/50 gap-2 text-black rounded"> <dl class="px-3 py-1 flex hover:bg-slate-900/50 gap-2 text-white drop-shadow-[0_2px_2px_rgba(0,0,0,0.8)] rounded">
<dt class="uppercase w-1/2 select-all whitespace-nowrap">{props.label}</dt> <dt class="uppercase w-1/2 select-all whitespace-nowrap">{props.label}</dt>
<dd class="select-all w-1/2 whitespace-nowrap">{props.children}</dd> <dd class="select-all w-1/2 whitespace-nowrap">{props.children}</dd>
</dl> </dl>

View File

@ -1,11 +1,13 @@
import { import {
createEffect, createEffect,
createSignal, createSignal,
JSX,
onCleanup, onCleanup,
onMount, onMount,
ParentComponent, ParentComponent,
} from 'solid-js'; } from 'solid-js';
import { displayStore, setDisplayStore } from '../stores/display.store'; import { displayStore, setDisplayStore } from '../stores/display.store';
import background from '../assets/transparent-grid-background.svg?url';
export const DisplayListContainer: ParentComponent = (props) => { export const DisplayListContainer: ParentComponent = (props) => {
let root: HTMLElement; let root: HTMLElement;
@ -13,8 +15,7 @@ export const DisplayListContainer: ParentComponent = (props) => {
top: '0px', top: '0px',
left: '0px', left: '0px',
}); });
const [rootStyle, setRootStyle] = createSignal({ const [rootStyle, setRootStyle] = createSignal<JSX.CSSProperties>({
// width: '100%',
height: '100%', height: '100%',
}); });
const [bound, setBound] = createSignal({ const [bound, setBound] = createSignal({
@ -38,6 +39,7 @@ export const DisplayListContainer: ParentComponent = (props) => {
setRootStyle({ setRootStyle({
height: `${(_bound.bottom - _bound.top) * displayStore.viewScale}px`, height: `${(_bound.bottom - _bound.top) * displayStore.viewScale}px`,
background: `url(${background})`,
}); });
}; };
@ -74,7 +76,7 @@ export const DisplayListContainer: ParentComponent = (props) => {
return ( return (
<section ref={root!} class="relative bg-gray-400/30" style={rootStyle()}> <section ref={root!} class="relative bg-gray-400/30" style={rootStyle()}>
<ol class="absolute bg-gray-700" style={olStyle()}> <ol class="absolute" style={olStyle()}>
{props.children} {props.children}
</ol> </ol>
</section> </section>

View File

@ -30,7 +30,7 @@ export const DisplayView: Component<DisplayViewProps> = (props) => {
return ( return (
<section <section
class="absolute bg-gray-300 grid grid-cols-[16px,auto,16px] grid-rows-[16px,auto,16px] overflow-hidden" class="absolute grid grid-cols-[16px,auto,16px] grid-rows-[16px,auto,16px] overflow-hidden group"
style={style()} style={style()}
> >
<ScreenView <ScreenView
@ -42,7 +42,7 @@ export const DisplayView: Component<DisplayViewProps> = (props) => {
/> />
<DisplayInfoPanel <DisplayInfoPanel
display={props.display} display={props.display}
class="absolute bg-slate-50/10 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded backdrop-blur w-1/3 min-w-[300px] text-black" class="absolute bg-slate-700/20 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded backdrop-blur w-1/3 min-w-[300px] text-black group-hover:opacity-100 opacity-0 transition-opacity"
/> />
<LedStripPart <LedStripPart
class="row-start-1 col-start-2 flex-row overflow-hidden" class="row-start-1 col-start-2 flex-row overflow-hidden"

View File

@ -7,11 +7,9 @@ import {
createSignal, createSignal,
For, For,
JSX, JSX,
on,
onCleanup, onCleanup,
splitProps, splitProps,
} from 'solid-js'; } from 'solid-js';
import { borders } from '../constants/border';
import { LedStripConfig } from '../models/led-strip-config'; import { LedStripConfig } from '../models/led-strip-config';
type LedStripPartProps = { type LedStripPartProps = {
@ -38,7 +36,7 @@ export const Pixel: Component<PixelProps> = (props) => {
title={props.color} title={props.color}
> >
<div <div
class="absolute top-px h-2 w-2 rounded-full shadow-2xl shadow-black" class="absolute top-1/2 -translate-y-1/2 h-2.5 w-2.5 rounded-full ring-1 ring-stone-300"
style={style()} style={style()}
/> />
</div> </div>
@ -101,6 +99,20 @@ export const LedStripPart: Component<LedStripPartProps> = (props) => {
} }
}); });
const onWheel = (e: WheelEvent) => {
if (localProps.config) {
invoke('patch_led_strip_len', {
displayId: localProps.config.display_id,
border: localProps.config.border,
deltaLen: e.deltaY > 0 ? 1 : -1,
})
.then(() => {})
.catch((e) => {
console.error(e);
});
}
};
const pixels = createMemo(() => { const pixels = createMemo(() => {
const _colors = colors(); const _colors = colors();
if (_colors) { if (_colors) {
@ -118,9 +130,9 @@ export const LedStripPart: Component<LedStripPartProps> = (props) => {
<section <section
{...rootProps} {...rootProps}
class={ class={
'bg-yellow-50 flex flex-nowrap justify-around items-center overflow-hidden' + 'flex flex-nowrap justify-around items-center overflow-hidden ' + rootProps.class
rootProps.class
} }
onWheel={onWheel}
> >
{pixels()} {pixels()}
</section> </section>