Add Pattern Templates for Key Colors targets with visual canvas editor
Introduce Pattern Template entity as a reusable rectangle layout that Key Colors targets reference via pattern_template_id. This replaces inline rectangle storage with a shared template system. Backend: - New PatternTemplate data model, store (JSON persistence), CRUD API - KC targets now reference pattern_template_id instead of inline rectangles - ProcessorManager resolves pattern template at KC processing start - Picture source test endpoint supports capture_duration=0 for single frame - Delete protection: 409 when template is referenced by a KC target Frontend: - Pattern Templates section in Key Colors sub-tab with card UI - Visual canvas editor with drag-to-move, 8-point resize handles - Background capture from any picture source for visual alignment - Precise coordinate list synced bidirectionally with canvas - Resizable editor container, viewport-constrained modal - KC target editor uses pattern template dropdown instead of inline rects - Localization (en/ru) for all new UI elements Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
147
server/src/wled_controller/api/routes/pattern_templates.py
Normal file
147
server/src/wled_controller/api/routes/pattern_templates.py
Normal file
@@ -0,0 +1,147 @@
|
||||
"""Pattern template routes: CRUD for rectangle layout templates."""
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
|
||||
from wled_controller.api.auth import AuthRequired
|
||||
from wled_controller.api.dependencies import (
|
||||
get_pattern_template_store,
|
||||
get_picture_target_store,
|
||||
)
|
||||
from wled_controller.api.schemas.pattern_templates import (
|
||||
PatternTemplateCreate,
|
||||
PatternTemplateListResponse,
|
||||
PatternTemplateResponse,
|
||||
PatternTemplateUpdate,
|
||||
)
|
||||
from wled_controller.api.schemas.picture_targets import KeyColorRectangleSchema
|
||||
from wled_controller.storage.key_colors_picture_target import KeyColorRectangle
|
||||
from wled_controller.storage.pattern_template_store import PatternTemplateStore
|
||||
from wled_controller.storage.picture_target_store import PictureTargetStore
|
||||
from wled_controller.utils import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _pat_template_to_response(t) -> PatternTemplateResponse:
|
||||
"""Convert a PatternTemplate to its API response."""
|
||||
return PatternTemplateResponse(
|
||||
id=t.id,
|
||||
name=t.name,
|
||||
rectangles=[
|
||||
KeyColorRectangleSchema(name=r.name, x=r.x, y=r.y, width=r.width, height=r.height)
|
||||
for r in t.rectangles
|
||||
],
|
||||
created_at=t.created_at,
|
||||
updated_at=t.updated_at,
|
||||
description=t.description,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/pattern-templates", response_model=PatternTemplateListResponse, tags=["Pattern Templates"])
|
||||
async def list_pattern_templates(
|
||||
_auth: AuthRequired,
|
||||
store: PatternTemplateStore = Depends(get_pattern_template_store),
|
||||
):
|
||||
"""List all pattern templates."""
|
||||
try:
|
||||
templates = store.get_all_templates()
|
||||
responses = [_pat_template_to_response(t) for t in templates]
|
||||
return PatternTemplateListResponse(templates=responses, count=len(responses))
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to list pattern templates: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/api/v1/pattern-templates", response_model=PatternTemplateResponse, tags=["Pattern Templates"], status_code=201)
|
||||
async def create_pattern_template(
|
||||
data: PatternTemplateCreate,
|
||||
_auth: AuthRequired,
|
||||
store: PatternTemplateStore = Depends(get_pattern_template_store),
|
||||
):
|
||||
"""Create a new pattern template."""
|
||||
try:
|
||||
rectangles = [
|
||||
KeyColorRectangle(name=r.name, x=r.x, y=r.y, width=r.width, height=r.height)
|
||||
for r in data.rectangles
|
||||
]
|
||||
template = store.create_template(
|
||||
name=data.name,
|
||||
rectangles=rectangles,
|
||||
description=data.description,
|
||||
)
|
||||
return _pat_template_to_response(template)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create pattern template: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/api/v1/pattern-templates/{template_id}", response_model=PatternTemplateResponse, tags=["Pattern Templates"])
|
||||
async def get_pattern_template(
|
||||
template_id: str,
|
||||
_auth: AuthRequired,
|
||||
store: PatternTemplateStore = Depends(get_pattern_template_store),
|
||||
):
|
||||
"""Get pattern template by ID."""
|
||||
try:
|
||||
template = store.get_template(template_id)
|
||||
return _pat_template_to_response(template)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=404, detail=f"Pattern template {template_id} not found")
|
||||
|
||||
|
||||
@router.put("/api/v1/pattern-templates/{template_id}", response_model=PatternTemplateResponse, tags=["Pattern Templates"])
|
||||
async def update_pattern_template(
|
||||
template_id: str,
|
||||
data: PatternTemplateUpdate,
|
||||
_auth: AuthRequired,
|
||||
store: PatternTemplateStore = Depends(get_pattern_template_store),
|
||||
):
|
||||
"""Update a pattern template."""
|
||||
try:
|
||||
rectangles = None
|
||||
if data.rectangles is not None:
|
||||
rectangles = [
|
||||
KeyColorRectangle(name=r.name, x=r.x, y=r.y, width=r.width, height=r.height)
|
||||
for r in data.rectangles
|
||||
]
|
||||
template = store.update_template(
|
||||
template_id=template_id,
|
||||
name=data.name,
|
||||
rectangles=rectangles,
|
||||
description=data.description,
|
||||
)
|
||||
return _pat_template_to_response(template)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update pattern template: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/api/v1/pattern-templates/{template_id}", status_code=204, tags=["Pattern Templates"])
|
||||
async def delete_pattern_template(
|
||||
template_id: str,
|
||||
_auth: AuthRequired,
|
||||
store: PatternTemplateStore = Depends(get_pattern_template_store),
|
||||
target_store: PictureTargetStore = Depends(get_picture_target_store),
|
||||
):
|
||||
"""Delete a pattern template."""
|
||||
try:
|
||||
if store.is_referenced_by(template_id, target_store):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Cannot delete pattern template: it is referenced by one or more key colors targets. "
|
||||
"Please reassign those targets before deleting.",
|
||||
)
|
||||
store.delete_template(template_id)
|
||||
except HTTPException:
|
||||
raise
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to delete pattern template: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@@ -365,26 +365,33 @@ async def test_picture_source(
|
||||
)
|
||||
stream.initialize()
|
||||
|
||||
logger.info(f"Starting {test_request.capture_duration}s stream test for {stream_id}")
|
||||
|
||||
frame_count = 0
|
||||
total_capture_time = 0.0
|
||||
last_frame = None
|
||||
|
||||
start_time = time.perf_counter()
|
||||
end_time = start_time + test_request.capture_duration
|
||||
|
||||
while time.perf_counter() < end_time:
|
||||
if test_request.capture_duration == 0:
|
||||
# Single frame capture
|
||||
logger.info(f"Capturing single frame for {stream_id}")
|
||||
capture_start = time.perf_counter()
|
||||
screen_capture = stream.capture_frame()
|
||||
capture_elapsed = time.perf_counter() - capture_start
|
||||
|
||||
if screen_capture is None:
|
||||
continue
|
||||
|
||||
total_capture_time += capture_elapsed
|
||||
frame_count += 1
|
||||
last_frame = screen_capture
|
||||
if screen_capture is not None:
|
||||
total_capture_time = capture_elapsed
|
||||
frame_count = 1
|
||||
last_frame = screen_capture
|
||||
else:
|
||||
logger.info(f"Starting {test_request.capture_duration}s stream test for {stream_id}")
|
||||
end_time = start_time + test_request.capture_duration
|
||||
while time.perf_counter() < end_time:
|
||||
capture_start = time.perf_counter()
|
||||
screen_capture = stream.capture_frame()
|
||||
capture_elapsed = time.perf_counter() - capture_start
|
||||
if screen_capture is None:
|
||||
continue
|
||||
total_capture_time += capture_elapsed
|
||||
frame_count += 1
|
||||
last_frame = screen_capture
|
||||
|
||||
actual_duration = time.perf_counter() - start_time
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ from wled_controller.api.dependencies import (
|
||||
)
|
||||
from wled_controller.api.schemas.picture_targets import (
|
||||
ExtractedColorResponse,
|
||||
KeyColorRectangleSchema,
|
||||
KeyColorsResponse,
|
||||
KeyColorsSettingsSchema,
|
||||
PictureTargetCreate,
|
||||
@@ -28,7 +27,6 @@ from wled_controller.core.processor_manager import ProcessorManager, ProcessingS
|
||||
from wled_controller.storage import DeviceStore
|
||||
from wled_controller.storage.wled_picture_target import WledPictureTarget
|
||||
from wled_controller.storage.key_colors_picture_target import (
|
||||
KeyColorRectangle,
|
||||
KeyColorsSettings,
|
||||
KeyColorsPictureTarget,
|
||||
)
|
||||
@@ -84,10 +82,7 @@ def _kc_settings_to_schema(settings: KeyColorsSettings) -> KeyColorsSettingsSche
|
||||
fps=settings.fps,
|
||||
interpolation_mode=settings.interpolation_mode,
|
||||
smoothing=settings.smoothing,
|
||||
rectangles=[
|
||||
KeyColorRectangleSchema(name=r.name, x=r.x, y=r.y, width=r.width, height=r.height)
|
||||
for r in settings.rectangles
|
||||
],
|
||||
pattern_template_id=settings.pattern_template_id,
|
||||
)
|
||||
|
||||
|
||||
@@ -97,10 +92,7 @@ def _kc_schema_to_settings(schema: KeyColorsSettingsSchema) -> KeyColorsSettings
|
||||
fps=schema.fps,
|
||||
interpolation_mode=schema.interpolation_mode,
|
||||
smoothing=schema.smoothing,
|
||||
rectangles=[
|
||||
KeyColorRectangle(name=r.name, x=r.x, y=r.y, width=r.width, height=r.height)
|
||||
for r in schema.rectangles
|
||||
],
|
||||
pattern_template_id=schema.pattern_template_id,
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user