diff --git a/server/src/wled_controller/api/routes/color_strip_sources.py b/server/src/wled_controller/api/routes/color_strip_sources.py index 6c2aace..be74882 100644 --- a/server/src/wled_controller/api/routes/color_strip_sources.py +++ b/server/src/wled_controller/api/routes/color_strip_sources.py @@ -1,8 +1,11 @@ """Color strip source routes: CRUD, calibration test, preview, and API input push.""" import asyncio +import io as _io import json as _json import secrets +import time as _time +import uuid as _uuid import numpy as np from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect @@ -706,7 +709,6 @@ async def test_color_strip_ws( return # Acquire stream – unique consumer ID per WS to avoid release races - import uuid as _uuid manager: ProcessorManager = get_processor_manager() csm = manager.color_strip_stream_manager consumer_id = f"__test_{_uuid.uuid4().hex[:8]}__" @@ -733,6 +735,7 @@ async def test_color_strip_ws( meta: dict = { "type": "meta", "source_type": source.source_type, + "source_name": source.name, "led_count": stream.led_count, } if is_picture and stream.calibration: @@ -752,9 +755,10 @@ async def test_color_strip_ws( if is_composite and hasattr(source, "layers"): # Send layer info for composite preview enabled_layers = [l for l in source.layers if l.get("enabled", True)] - layer_infos = [] # [{name, id, is_notification}, ...] + layer_infos = [] # [{name, id, is_notification, has_brightness}, ...] for layer in enabled_layers: - info = {"id": layer["source_id"], "name": layer.get("source_id", "?"), "is_notification": False} + info = {"id": layer["source_id"], "name": layer.get("source_id", "?"), + "is_notification": False, "has_brightness": bool(layer.get("brightness_source_id"))} try: layer_src = store.get_source(layer["source_id"]) info["name"] = layer_src.name @@ -766,6 +770,13 @@ async def test_color_strip_ws( meta["layer_infos"] = layer_infos await websocket.send_text(_json.dumps(meta)) + # For picture sources, grab the live stream for frame preview + _frame_live = None + if is_picture and hasattr(stream, '_live_stream'): + _frame_live = stream._live_stream + _last_aux_time = 0.0 + _AUX_INTERVAL = 0.5 # send JPEG preview / brightness updates every 0.5s + # Stream binary RGB frames at ~20 Hz while True: # For composite sources, send per-layer data like target preview does @@ -791,6 +802,50 @@ async def test_color_strip_ws( colors = stream.get_latest_colors() if colors is not None: await websocket.send_bytes(colors.tobytes()) + + # Periodically send auxiliary data (frame preview, brightness) + now = _time.monotonic() + if now - _last_aux_time >= _AUX_INTERVAL: + _last_aux_time = now + + # Send brightness values for composite layers + if is_composite and isinstance(stream, CompositeColorStripStream): + try: + bri_values = stream.get_layer_brightness() + if any(v is not None for v in bri_values): + bri_msg = {"type": "brightness", "values": [ + round(v * 100) if v is not None else None for v in bri_values + ]} + await websocket.send_text(_json.dumps(bri_msg)) + except Exception: + pass + + # Send JPEG frame preview for picture sources + if _frame_live: + try: + frame = _frame_live.get_latest_frame() + if frame is not None and frame.image is not None: + from PIL import Image as _PIL_Image + img = frame.image + # Ensure 3-channel RGB (some engines may produce BGRA) + if img.ndim == 3 and img.shape[2] == 4: + img = img[:, :, :3] + # Downscale for bandwidth + h, w = img.shape[:2] + scale = min(480 / w, 360 / h, 1.0) + if scale < 1.0: + new_w = max(1, int(w * scale)) + new_h = max(1, int(h * scale)) + pil = _PIL_Image.fromarray(img).resize((new_w, new_h), _PIL_Image.LANCZOS) + else: + pil = _PIL_Image.fromarray(img) + buf = _io.BytesIO() + pil.save(buf, format='JPEG', quality=70) + # Wire format: [0xFD] [jpeg_bytes] + await websocket.send_bytes(b'\xfd' + buf.getvalue()) + except Exception as e: + logger.warning(f"JPEG frame preview error: {e}") + await asyncio.sleep(0.05) except WebSocketDisconnect: pass diff --git a/server/src/wled_controller/core/processing/composite_stream.py b/server/src/wled_controller/core/processing/composite_stream.py index 9fa5402..6106d8f 100644 --- a/server/src/wled_controller/core/processing/composite_stream.py +++ b/server/src/wled_controller/core/processing/composite_stream.py @@ -110,6 +110,22 @@ class CompositeColorStripStream(ColorStripStream): with self._colors_lock: return self._latest_layer_colors + def get_layer_brightness(self) -> List[Optional[float]]: + """Return per-layer brightness values (0.0-1.0) from value sources, or None if no source.""" + enabled = [l for l in self._layers if l.get("enabled", True)] + result: List[Optional[float]] = [] + with self._sub_lock: + for i in range(len(enabled)): + if i in self._brightness_streams: + _vs_id, vs = self._brightness_streams[i] + try: + result.append(vs.get_value()) + except Exception: + result.append(None) + else: + result.append(None) + return result + def configure(self, device_led_count: int) -> None: if self._auto_size and device_led_count > 0 and device_led_count != self._led_count: self._led_count = device_led_count diff --git a/server/src/wled_controller/static/css/dashboard.css b/server/src/wled_controller/static/css/dashboard.css index bf404bd..f97afa2 100644 --- a/server/src/wled_controller/static/css/dashboard.css +++ b/server/src/wled_controller/static/css/dashboard.css @@ -354,14 +354,14 @@ background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 6px; - padding: 10px 12px; + padding: 10px 0 0; min-width: 0; - overflow: hidden; } .perf-chart-wrap { position: relative; height: 100px; + overflow: hidden; } .perf-chart-header { @@ -369,6 +369,7 @@ justify-content: space-between; align-items: center; margin-bottom: 0; + padding: 0 12px; } .perf-chart-label { @@ -382,7 +383,7 @@ .perf-chart-subtitle { position: absolute; top: 0; - left: 0; + left: 12px; font-size: 0.6rem; font-weight: 400; color: var(--text-muted); diff --git a/server/src/wled_controller/static/css/modal.css b/server/src/wled_controller/static/css/modal.css index 1b22e3b..5df34be 100644 --- a/server/src/wled_controller/static/css/modal.css +++ b/server/src/wled_controller/static/css/modal.css @@ -156,6 +156,20 @@ background: rgba(255, 255, 255, 0.25); } +.css-test-rect-outer { + position: relative; + padding: 22px 30px; +} + +.css-test-rect-ticks { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + pointer-events: none; + z-index: 2; +} + .css-test-rect { display: grid; grid-template-columns: 14px 1fr 14px; @@ -170,8 +184,36 @@ } .css-test-rect-screen { - background: #111; + background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + background-size: cover; + background-position: center; border-radius: 2px; + outline: 1px solid rgba(255, 255, 255, 0.15); + outline-offset: -1px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 4px; + overflow: hidden; +} + +.css-test-rect-label { + color: rgba(255, 255, 255, 0.85); + font-size: 0.8rem; + font-weight: 600; + text-align: center; + text-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 90%; +} + +.css-test-rect-leds { + font-size: 0.7rem; + font-weight: 400; + opacity: 0.75; } .css-test-edge-wrap { @@ -190,15 +232,6 @@ display: block; } -.css-test-info { - display: flex; - gap: 16px; - padding: 8px 0 0; - font-family: monospace; - font-size: 0.85em; - color: var(--text-muted, #888); -} - .css-test-status { text-align: center; padding: 8px 0; @@ -245,6 +278,23 @@ opacity: 1; } +.css-test-layer-brightness { + position: absolute; + right: 6px; + top: 50%; + transform: translateY(-50%); + font-size: 0.6rem; + font-family: var(--font-mono, monospace); + color: #fff; + text-shadow: 0 0 3px rgba(0,0,0,0.9), 0 0 6px rgba(0,0,0,0.6); + pointer-events: none; + white-space: nowrap; + display: flex; + align-items: center; + gap: 2px; +} +.css-test-layer-brightness svg { width: 12px; height: 12px; } + /* LED count control */ .css-test-led-control { display: flex; diff --git a/server/src/wled_controller/static/js/core/ui.js b/server/src/wled_controller/static/js/core/ui.js index 20e8822..759d160 100644 --- a/server/src/wled_controller/static/js/core/ui.js +++ b/server/src/wled_controller/static/js/core/ui.js @@ -6,6 +6,16 @@ import { kcTestAutoRefresh, setKcTestAutoRefresh, setKcTestTargetId, confirmReso import { t } from './i18n.js'; import { ICON_PAUSE, ICON_START } from './icons.js'; +/** Returns true on touch devices where auto-focus would pop up the virtual keyboard */ +export function isTouchDevice() { + return 'ontouchstart' in window || navigator.maxTouchPoints > 0; +} + +/** Focus element only on non-touch devices (avoids virtual keyboard popup on mobile) */ +export function desktopFocus(el) { + if (el && !isTouchDevice()) el.focus(); +} + export function toggleHint(btn) { const hint = btn.closest('.label-row').nextElementSibling; if (hint && hint.classList.contains('input-hint')) { diff --git a/server/src/wled_controller/static/js/features/color-strips.js b/server/src/wled_controller/static/js/features/color-strips.js index 0a51a85..e707ed9 100644 --- a/server/src/wled_controller/static/js/features/color-strips.js +++ b/server/src/wled_controller/static/js/features/color-strips.js @@ -5,7 +5,7 @@ import { fetchWithAuth, escapeHtml } from '../core/api.js'; import { _cachedSyncClocks, _cachedValueSources, audioSourcesCache, streamsCache, colorStripSourcesCache, valueSourcesCache } from '../core/state.js'; import { t } from '../core/i18n.js'; -import { showToast, showConfirm } from '../core/ui.js'; +import { showToast, showConfirm, desktopFocus } from '../core/ui.js'; import { Modal } from '../core/modal.js'; import { getColorStripIcon, getPictureSourceIcon, getAudioSourceIcon, getValueSourceIcon, @@ -13,6 +13,7 @@ import { ICON_LED, ICON_PALETTE, ICON_FPS, ICON_MAP_PIN, ICON_MUSIC, ICON_AUDIO_LOOPBACK, ICON_TIMER, ICON_LINK_SOURCE, ICON_FILM, ICON_LINK, ICON_SPARKLES, ICON_ACTIVITY, ICON_CLOCK, ICON_BELL, ICON_EYE, + ICON_SUN_DIM, } from '../core/icons.js'; import * as P from '../core/icon-paths.js'; import { wrapCard } from '../core/card-colors.js'; @@ -1553,7 +1554,7 @@ export async function showCSSEditor(cssId = null, cloneData = null) { cssEditorModal.snapshot(); cssEditorModal.open(); - setTimeout(() => document.getElementById('css-editor-name').focus(), 100); + setTimeout(() => desktopFocus(document.getElementById('css-editor-name')), 100); } catch (error) { if (error.isAuth) return; console.error('Failed to open CSS editor:', error); @@ -1924,7 +1925,6 @@ export function testColorStrip(sourceId) { if (layersContainer) layersContainer.innerHTML = ''; document.getElementById('css-test-status').style.display = ''; document.getElementById('css-test-status').textContent = t('color_strip.test.connecting'); - document.getElementById('css-test-led-count').textContent = ''; // Restore LED count + Enter key handler const ledCount = _getCssTestLedCount(); @@ -1954,8 +1954,16 @@ function _cssTestConnect(sourceId, ledCount) { if (gen !== _cssTestGeneration) return; if (typeof event.data === 'string') { - // JSON metadata - _cssTestMeta = JSON.parse(event.data); + const msg = JSON.parse(event.data); + + // Handle brightness updates for composite layers + if (msg.type === 'brightness') { + _cssTestUpdateBrightness(msg.values); + return; + } + + // Initial metadata + _cssTestMeta = msg; const isPicture = _cssTestMeta.edges && _cssTestMeta.edges.length > 0; _cssTestIsComposite = _cssTestMeta.layers && _cssTestMeta.layers.length > 0; @@ -1977,7 +1985,15 @@ function _cssTestConnect(sourceId, ledCount) { const fireBtn = document.getElementById('css-test-fire-btn'); if (fireBtn) fireBtn.style.display = (isNotify && !_cssTestIsComposite) ? '' : 'none'; - document.getElementById('css-test-led-count').textContent = `${_cssTestMeta.led_count} LEDs`; + // Populate rect screen labels for picture sources + if (isPicture) { + const nameEl = document.getElementById('css-test-rect-name'); + const ledsEl = document.getElementById('css-test-rect-leds'); + if (nameEl) nameEl.textContent = _cssTestMeta.source_name || ''; + if (ledsEl) ledsEl.textContent = `${_cssTestMeta.led_count} LEDs`; + // Render tick marks after layout settles + requestAnimationFrame(() => _cssTestRenderTicks(_cssTestMeta.edges)); + } // Build composite layer canvases if (_cssTestIsComposite) { @@ -1985,6 +2001,27 @@ function _cssTestConnect(sourceId, ledCount) { } } else { const raw = new Uint8Array(event.data); + // Check JPEG frame preview: [0xFD] [jpeg_bytes] + if (raw.length > 1 && raw[0] === 0xFD) { + const jpegBlob = new Blob([raw.subarray(1)], { type: 'image/jpeg' }); + const url = URL.createObjectURL(jpegBlob); + const screen = document.getElementById('css-test-rect-screen'); + if (screen) { + // Preload image to avoid flicker on swap + const img = new Image(); + img.onload = () => { + const oldUrl = screen._blobUrl; + screen._blobUrl = url; + screen.style.backgroundImage = `url(${url})`; + screen.style.backgroundSize = 'cover'; + screen.style.backgroundPosition = 'center'; + if (oldUrl) URL.revokeObjectURL(oldUrl); + }; + img.onerror = () => URL.revokeObjectURL(url); + img.src = url; + } + return; + } // Check composite wire format: [0xFE] [layer_count] [led_count_hi] [led_count_lo] [layers...] [composite...] if (raw.length > 3 && raw[0] === 0xFE && _cssTestIsComposite) { const layerCount = raw[1]; @@ -2032,18 +2069,40 @@ function _cssTestBuildLayers(layerNames, sourceType, layerInfos) { for (let i = 0; i < layerNames.length; i++) { const info = layerInfos && layerInfos[i]; const isNotify = info && info.is_notification; + const hasBri = info && info.has_brightness; const fireBtn = isNotify ? `` : ''; + const briLabel = hasBri + ? `` + : ''; html += `