feat: 拖拽排序。

This commit is contained in:
Ivan Li 2023-04-01 23:32:31 +08:00
parent 5893c4344c
commit 0d47911355
11 changed files with 252 additions and 64 deletions

View File

@ -1,6 +1,7 @@
{
"files.autoSave": "onWindowChange",
"cSpell.words": [
"Itertools"
"Itertools",
"Leds"
]
}

View File

@ -1,5 +1,6 @@
use std::{env::current_dir, fmt::format};
use std::env::current_dir;
use display_info::DisplayInfo;
use paris::{error, info};
use serde::{Deserialize, Serialize};
use tauri::api::path::config_dir;
@ -41,6 +42,8 @@ pub struct LedStripConfigGroup {
impl LedStripConfigGroup {
pub async fn read_config() -> anyhow::Result<Self> {
let displays = DisplayInfo::all()?;
// config path
let path = config_dir()
.unwrap_or(current_dir().unwrap())
@ -53,10 +56,14 @@ impl LedStripConfigGroup {
if exists {
let config = tokio::fs::read_to_string(path).await?;
let config: LedStripConfigGroup = toml::from_str(&config)
let mut config: LedStripConfigGroup = toml::from_str(&config)
.map_err(|e| anyhow::anyhow!("Failed to parse config file: {}", e))?;
log::info!("config loaded: {:?}", config.strips.iter().map(|c| format!("{}#{}", c.index, c.display_id)).collect::<Vec<_>>());
for strip in config.strips.iter_mut() {
strip.display_id = displays[strip.index / 4].id;
}
// log::info!("config loaded: {:?}", config);
Ok(config)
} else {
@ -76,7 +83,7 @@ impl LedStripConfigGroup {
anyhow::anyhow!("Failed to parse config file: {}. configs: {:?}", e, configs)
})?;
tokio::fs::write (&path, config_text).await.map_err(|e| {
tokio::fs::write(&path, config_text).await.map_err(|e| {
anyhow::anyhow!("Failed to write config file: {}. path: {:?}", e, &path)
})?;

View File

@ -1,4 +1,4 @@
use std::sync::Arc;
use std::{borrow::BorrowMut, sync::Arc};
use tauri::async_runtime::RwLock;
use tokio::sync::OnceCell;
@ -45,7 +45,7 @@ impl ConfigManager {
.send(configs.clone())
.map_err(|e| anyhow::anyhow!("Failed to send config update: {}", e))?;
log::info!("config updated: {:?}", configs);
// log::info!("config updated: {:?}", configs);
Ok(())
}
@ -90,6 +90,53 @@ impl ConfigManager {
Ok(())
}
pub async fn move_strip_part(
&self,
display_id: u32,
border: Border,
target_start: usize,
) -> anyhow::Result<()> {
let mut config = self.config.write().await;
for (index, strip) in config.clone().strips.iter().enumerate() {
if strip.display_id == display_id && strip.border == border {
let mut mapper = config.mappers[index].borrow_mut();
if target_start == mapper.start {
return Ok(());
}
let target_end = mapper.end + target_start - mapper.start;
if target_start > 1000 || target_end > 1000 {
return Err(anyhow::anyhow!(
"Overflow. range: 0-1000, current: {}-{}",
target_start,
target_end
));
}
mapper.start = target_start as usize;
mapper.end = target_end as usize;
log::info!("mapper: {:?}", mapper);
}
}
log::info!("mapper: {:?}", config.mappers[4]);
let cloned_config = config.clone();
drop(config);
self.update(&cloned_config).await?;
self.config_update_sender
.send(cloned_config)
.map_err(|e| anyhow::anyhow!("Failed to send config update: {}", e))?;
Ok(())
}
fn rebuild_mappers(config: &mut LedStripConfigGroup) {
let mut prev_end = 0;
let mappers: Vec<SamplePointMapper> = config

View File

@ -1,8 +1,8 @@
use std::sync::Arc;
use std::{sync::Arc, time::Duration};
use paris::warn;
use tauri::async_runtime::{Mutex, RwLock};
use tokio::sync::watch;
use tokio::{sync::watch, time::sleep};
use crate::{
ambient_light::{config, ConfigManager},
@ -71,7 +71,7 @@ impl LedColorsPublisher {
warn!("rx changed error: {}", err);
continue;
}
log::info!("screenshot updated");
// log::info!("screenshot updated");
let screenshot = rx.borrow().clone();
@ -97,30 +97,12 @@ impl LedColorsPublisher {
if some_screenshot_receiver_is_none
|| config_receiver.has_changed().unwrap_or(true)
{
sleep(Duration::from_millis(1000)).await;
break;
}
}
}
});
tokio::spawn(async move {
let config_manager = ConfigManager::global().await;
let mut config_receiver = config_manager.clone_config_update_receiver();
loop {
if let Err(err) = config_receiver.changed().await {
warn!("config receiver changed error: {}", err);
continue;
}
let configs = config_receiver.borrow().clone();
let configs = Self::get_colors_configs(&configs).await;
handler.abort();
break;
}
});
Ok(())
}

View File

@ -159,6 +159,22 @@ async fn send_colors(buffer: Vec<u8>) -> Result<(), String> {
})
}
#[tauri::command]
async fn move_strip_part(display_id: u32, border: Border, target_start: usize) -> Result<(), String> {
let config_manager = ambient_light::ConfigManager::global().await;
config_manager
.move_strip_part(
display_id,
border,
target_start,
)
.await
.map_err(|e| {
error!("can not move strip part: {}", e);
e.to_string()
})
}
#[tokio::main]
async fn main() {
env_logger::init();
@ -180,6 +196,7 @@ async fn main() {
get_one_edge_colors,
patch_led_strip_len,
send_colors,
move_strip_part,
])
.register_uri_scheme_protocol("ambient-light", move |_app, request| {
let response = ResponseBuilder::new().header("Access-Control-Allow-Origin", "*");

View File

@ -113,7 +113,7 @@ impl ScreenshotManager {
) -> anyhow::Result<()> {
let channels = self.channels.to_owned();
let encode_listeners = self.encode_listeners.to_owned();
log::info!("subscribe_encoded_screenshot_updated. {}", display_id);
// log::info!("subscribe_encoded_screenshot_updated. {}", display_id);
{
let encode_listeners = encode_listeners.read().await;
@ -209,7 +209,7 @@ impl ScreenshotManager {
let screenshot = take_screenshot(display_id, scale_factor);
if let Ok(screenshot) = screenshot {
tx.send(screenshot).unwrap();
log::info!("take_screenshot_loop: send success. display#{}", display_id)
// log::info!("take_screenshot_loop: send success. display#{}", display_id)
} else {
warn!("take_screenshot_loop: {}", screenshot.err().unwrap());
}

View File

@ -1,4 +1,4 @@
import { createEffect, onCleanup } from 'solid-js';
import { createContext, createEffect, onCleanup } from 'solid-js';
import { invoke } from '@tauri-apps/api/tauri';
import { DisplayView } from './components/display-view';
import { DisplayListContainer } from './components/display-list-container';
@ -7,6 +7,11 @@ import { LedStripConfigContainer } from './models/led-strip-config';
import { setLedStripStore } from './stores/led-strip.store';
import { listen } from '@tauri-apps/api/event';
import { LedStripPartsSorter } from './components/led-strip-parts-sorter';
import { createStore } from 'solid-js/store';
import {
LedStripConfigurationContext,
LedStripConfigurationContextType,
} from './contexts/led-strip-configuration.context';
function App() {
createEffect(() => {
@ -52,14 +57,33 @@ function App() {
});
});
const [ledStripConfiguration, setLedStripConfiguration] = createStore<
LedStripConfigurationContextType[0]
>({
selectedStripPart: null,
});
const ledStripConfigurationContextValue: LedStripConfigurationContextType = [
ledStripConfiguration,
{
setSelectedStripPart: (v) => {
setLedStripConfiguration({
selectedStripPart: v,
});
},
},
];
return (
<div>
<LedStripPartsSorter />
<DisplayListContainer>
{displayStore.displays.map((display) => {
return <DisplayView display={display} />;
})}
</DisplayListContainer>
<LedStripConfigurationContext.Provider value={ledStripConfigurationContextValue}>
<LedStripPartsSorter />
<DisplayListContainer>
{displayStore.displays.map((display) => {
return <DisplayView display={display} />;
})}
</DisplayListContainer>
</LedStripConfigurationContext.Provider>
</div>
);
}

View File

@ -10,10 +10,12 @@ import {
JSX,
onCleanup,
splitProps,
useContext,
} from 'solid-js';
import { useTippy } from 'solid-tippy';
import { followCursor } from 'tippy.js';
import { LedStripConfig } from '../models/led-strip-config';
import { LedStripConfigurationContext } from '../contexts/led-strip-configuration.context';
type LedStripPartProps = {
config?: LedStripConfig | null;
@ -48,6 +50,7 @@ export const Pixel: Component<PixelProps> = (props) => {
export const LedStripPart: Component<LedStripPartProps> = (props) => {
const [localProps, rootProps] = splitProps(props, ['config']);
const [stripConfiguration] = useContext(LedStripConfigurationContext);
const [ledSamplePoints, setLedSamplePoints] = createSignal();
const [colors, setColors] = createSignal<string[]>([]);
@ -143,8 +146,15 @@ export const LedStripPart: Component<LedStripPartProps> = (props) => {
{...rootProps}
ref={setAnchor}
class={
'flex flex-nowrap justify-around items-center overflow-hidden ' + rootProps.class
'flex rounded-full flex-nowrap justify-around items-center overflow-hidden ' +
rootProps.class
}
classList={{
'ring ring-inset bg-yellow-400/50 ring-orange-400 animate-pulse':
stripConfiguration.selectedStripPart?.border === localProps.config?.border &&
stripConfiguration.selectedStripPart?.displayId ===
localProps.config?.display_id,
}}
onWheel={onWheel}
>
<For each={colors()}>{(item) => <Pixel color={item} />}</For>

View File

@ -1,14 +1,91 @@
import { Component, createContext, createEffect, createSignal, For } from 'solid-js';
import {
Component,
createContext,
createEffect,
createMemo,
createSignal,
For,
JSX,
useContext,
} from 'solid-js';
import { LedStripConfig, LedStripPixelMapper } from '../models/led-strip-config';
import { ledStripStore } from '../stores/led-strip.store';
import { invoke } from '@tauri-apps/api';
import { LedStripConfigurationContext } from '../contexts/led-strip-configuration.context';
const SorterItem: Component<{ mapper: LedStripPixelMapper }> = (props) => {
const SorterItem: Component<{ strip: LedStripConfig; mapper: LedStripPixelMapper }> = (
props,
) => {
const [fullLeds, setFullLeds] = createSignal<string[]>([]);
const [dragging, setDragging] = createSignal<boolean>(false);
const [dragStart, setDragStart] = createSignal<{ x: number; y: number } | null>(null);
const [dragCurr, setDragCurr] = createSignal<{ x: number; y: number } | null>(null);
const [dragStartIndex, setDragStartIndex] = createSignal<number>(0);
const [, { setSelectedStripPart }] = useContext(LedStripConfigurationContext);
const totalLedCount = createMemo(() => {
return ledStripStore.strips.reduce((acc, strip) => acc + strip.len, 0);
});
const move = (targetStart: number) => {
if (targetStart === props.mapper.start) {
return;
}
console.log(`target_start ${targetStart}`);
invoke('move_strip_part', {
displayId: props.strip.display_id,
border: props.strip.border,
targetStart,
}).catch((err) => console.error(err));
};
const onPointerDown = (ev: PointerEvent) => {
if (ev.button !== 0) {
return;
}
setDragging(true);
setDragStart({ x: ev.clientX, y: ev.clientY });
setDragCurr({ x: ev.clientX, y: ev.clientY });
setDragStartIndex(props.mapper.start);
};
const onPointerUp = () => (ev: PointerEvent) => {
if (ev.button !== 0) {
return;
}
setDragging(false);
};
const onPointerMove = (ev: PointerEvent) => {
setSelectedStripPart({
displayId: props.strip.display_id,
border: props.strip.border,
});
if (!(ev.buttons & 1)) {
return;
}
const draggingInfo = dragging();
if (!draggingInfo) {
return;
}
setDragCurr({ x: ev.clientX, y: ev.clientY });
const cellWidth = (ev.currentTarget as HTMLDivElement).clientWidth / totalLedCount();
const diff = ev.clientX - dragStart()!.x;
const moved = Math.round(diff / cellWidth);
if (moved === 0) {
return;
}
move(props.mapper.start + moved);
};
const onPointerLeave = () => {
setSelectedStripPart(null);
};
// update fullLeds
createEffect(() => {
const strips = ledStripStore.strips;
const totalLedCount = strips.reduce((acc, strip) => acc + strip.len, 0);
const fullLeds = new Array(totalLedCount).fill('rgba(255,255,255,0.5)');
const fullLeds = new Array(totalLedCount()).fill('rgba(255,255,255,0.5)');
for (let i = props.mapper.start, j = 0; i < props.mapper.end; i++, j++) {
fullLeds[i] = `rgb(${ledStripStore.colors[i * 3]}, ${
@ -18,8 +95,21 @@ const SorterItem: Component<{ mapper: LedStripPixelMapper }> = (props) => {
setFullLeds(fullLeds);
});
const style = createMemo<JSX.CSSProperties>(() => {
return {
transform: `translateX(${(dragCurr()?.x ?? 0) - (dragStart()?.x ?? 0)}px)`,
};
});
return (
<div class="flex h-2 m-2">
<div
class="flex h-2 m-2 select-none cursor-ew-resize focus:cursor-ew-resize"
style={style()}
onPointerMove={onPointerMove}
onPointerDown={onPointerDown}
onPointerUp={onPointerUp}
onPointerLeave={onPointerLeave}
>
<For each={fullLeds()}>
{(it) => (
<div
@ -78,11 +168,13 @@ export const LedStripPartsSorter: Component = () => {
const context = createContext();
return (
<div>
<div class="select-none overflow-hidden">
<SorterResult />
<For each={ledStripStore.strips}>
{(strip, index) => <SorterItem mapper={ledStripStore.mappers[index()]} />}
{(strip, index) => (
<SorterItem strip={strip} mapper={ledStripStore.mappers[index()]} />
)}
</For>
</div>
);
};
};

View File

@ -0,0 +1,24 @@
import { createContext } from 'solid-js';
import { Borders } from '../constants/border';
export type LedStripConfigurationContextType = [
{
selectedStripPart: {
displayId: number;
border: Borders;
} | null;
},
{
setSelectedStripPart: (v: { displayId: number; border: Borders } | null) => void;
},
];
export const LedStripConfigurationContext =
createContext<LedStripConfigurationContextType>([
{
selectedStripPart: null,
},
{
setSelectedStripPart: () => {},
},
]);

View File

@ -1,16 +0,0 @@
import { Borders } from '../constants/border';
import { LedStripConfig } from './led-strip-config';
export class LedStripConfigOfBorders implements Record<Borders, LedStripConfig | null> {
constructor(
public top: LedStripConfig | null = null,
public bottom: LedStripConfig | null = null,
public left: LedStripConfig | null = null,
public right: LedStripConfig | null = null,
) {}
}
export class DisplayConfig {
led_strip_of_borders = new LedStripConfigOfBorders();
constructor(public id: number) {}
}