Initial commit

This commit is contained in:
Seth Hillbrand
2026-02-15 12:50:49 -08:00
commit c17ab8607c
61 changed files with 11607 additions and 0 deletions
@@ -0,0 +1,30 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .collapsible_section import CollapsibleSection
from .param_slider import ParamSlider
from .toggle_switch import ToggleSwitch
from .segment_button import SegmentButton
from .preset_bar import PresetBar
from .color_wheel import ColorWheel
__all__ = [
"CollapsibleSection",
"ParamSlider",
"ToggleSwitch",
"SegmentButton",
"PresetBar",
"ColorWheel",
]
@@ -0,0 +1,162 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Collapsible section widget with animated expand/collapse."""
from PySide6.QtCore import Qt, QPropertyAnimation, QEasingCurve, Property, QPointF
from PySide6.QtWidgets import (
QWidget, QVBoxLayout, QHBoxLayout, QLabel, QFrame, QSizePolicy,
)
from PySide6.QtGui import QPainter, QColor, QFont
from ..theme import COLOR_BG_SECTION_HEADER, COLOR_TEXT_PRIMARY, COLOR_BORDER
class _HeaderBar(QWidget):
"""Clickable header bar with triangle arrow and title."""
def __init__(self, title: str, parent=None):
super().__init__(parent)
self.title = title
self._expanded = True
self.setFixedHeight(32)
self.setCursor(Qt.CursorShape.PointingHandCursor)
@property
def expanded(self) -> bool:
return self._expanded
@expanded.setter
def expanded(self, value: bool):
self._expanded = value
self.update()
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.fillRect(self.rect(), QColor(COLOR_BG_SECTION_HEADER))
arrow_x = 12
arrow_y = self.height() // 2
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor(COLOR_TEXT_PRIMARY))
if self._expanded:
p.drawPolygon([
QPointF(arrow_x - 4, arrow_y - 2),
QPointF(arrow_x + 4, arrow_y - 2),
QPointF(arrow_x, arrow_y + 3),
])
else:
p.drawPolygon([
QPointF(arrow_x - 2, arrow_y - 4),
QPointF(arrow_x + 3, arrow_y),
QPointF(arrow_x - 2, arrow_y + 4),
])
p.setPen(QColor(COLOR_TEXT_PRIMARY))
font = QFont()
font.setBold(True)
font.setPointSize(10)
p.setFont(font)
p.drawText(
28, 0, self.width() - 32, self.height(),
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
self.title,
)
p.end()
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.parent().toggle()
class CollapsibleSection(QWidget):
"""A section with a clickable header that expands and collapses its content area."""
def __init__(self, title: str, parent=None, expanded: bool = False):
super().__init__(parent)
self._expanded = expanded
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self._header = _HeaderBar(title, self)
layout.addWidget(self._header)
self._content = QWidget()
self._content.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
self._content_layout = QVBoxLayout(self._content)
self._content_layout.setContentsMargins(8, 6, 8, 6)
self._content_layout.setSpacing(6)
layout.addWidget(self._content)
self._animation = QPropertyAnimation(self, b"content_height")
self._animation.setDuration(200)
self._animation.setEasingCurve(QEasingCurve.Type.InOutQuad)
if not expanded:
self._content.setMaximumHeight(0)
self._header.expanded = False
@property
def content_layout(self) -> QVBoxLayout:
return self._content_layout
def add_widget(self, widget: QWidget):
self._content_layout.addWidget(widget)
def add_layout(self, layout):
self._content_layout.addLayout(layout)
def _get_content_height(self) -> int:
return self._content.maximumHeight()
def _set_content_height(self, h: int):
self._content.setMaximumHeight(h)
content_height = Property(int, _get_content_height, _set_content_height)
def toggle(self):
self._expanded = not self._expanded
self._header.expanded = self._expanded
target_height = self._content.sizeHint().height() if self._expanded else 0
self._animation.stop()
self._animation.setStartValue(self._content.maximumHeight())
self._animation.setEndValue(target_height)
if self._expanded:
self._animation.finished.connect(self._unlock_height)
self._animation.start()
def _unlock_height(self):
"""Remove height cap after expansion so content can resize freely."""
if self._expanded:
self._content.setMaximumHeight(16777215)
try:
self._animation.finished.disconnect(self._unlock_height)
except TypeError:
pass
def is_expanded(self) -> bool:
return self._expanded
@@ -0,0 +1,798 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""HSV color wheel widget with Fast and Professional modes.
Fast mode provides a two-point color remapping interface: the user clicks to
select a source color region, then drags to a destination. The shift is
propagated across the internal polar grid with linear falloff and sent as a
CLUT to the camera.
Professional mode overlays a polar grid of draggable control points for
per-region color grading adjustments.
"""
import copy
import math
from PySide6.QtCore import Qt, Signal, QPointF, QRectF
from PySide6.QtWidgets import QWidget
from PySide6.QtGui import (
QPainter, QColor, QImage, QPen, QBrush,
QConicalGradient, QRadialGradient, QPixmap,
)
from ..theme import COLOR_BG_PANEL, COLOR_ACCENT
from yolocam.clut import (
HUE_SECTORS, SAT_COLUMNS, FULL_R_VALUE, INTERVAL_THETA, INTERVAL_R_NORM,
init_fast_grid, init_luma_grid, calc_rows_data,
)
_TWO_PI = 2.0 * math.pi
_SAT_RINGS = SAT_COLUMNS
_HUE_STEP_DEG = INTERVAL_THETA
_GRID_POINT_RADIUS = 3.5
_GRID_HIT_RADIUS = 8.0
_GRID_LINE_COLOR = QColor(255, 255, 255, 64)
_ACCENT_COLOR = QColor(COLOR_ACCENT)
_HOME_LINE_COLOR = QColor(255, 255, 255, 40)
_SOURCE_COLOR = QColor(255, 0, 67, 200)
_DEST_COLOR = QColor(255, 255, 255, 200)
_ARROW_COLOR = QColor(255, 255, 255, 160)
def _polar_to_xy(center_x, center_y, radius, angle_rad):
"""Convert polar coordinates to pixel position (math convention, y-up)."""
return (
center_x + radius * math.cos(angle_rad),
center_y - radius * math.sin(angle_rad),
)
def _xy_to_polar(cx, cy, px, py):
"""Convert pixel position to (angle_rad, distance) from center."""
dx = px - cx
dy = py - cy
dist = math.sqrt(dx * dx + dy * dy)
angle = math.atan2(-dy, dx)
if angle < 0:
angle += _TWO_PI
return angle, dist
class ColorWheel(QWidget):
"""Circular HSV color wheel with click/drag selection.
Supports two modes:
- "fast" (default): two-point color remapping via CLUT
- "professional": polar grid of draggable control points for
per-region color grading
Hue maps to angle around the circumference, saturation maps to
distance from center. Brightness (value) is controlled externally.
"""
hue_changed = Signal(int)
saturation_changed = Signal(int)
brightness_changed = Signal(int)
color_changed = Signal(int, int, int)
grid_changed = Signal(object)
WHEEL_SIZE = 280
INDICATOR_RADIUS = 6
def __init__(self, parent=None):
super().__init__(parent)
self._hue = 0
self._saturation = 0
self._brightness = 100
self._dragging = False
self._mode = "fast"
self._wheel_pixmap = None
self._wheel_center = QPointF(self.WHEEL_SIZE / 2.0, self.WHEEL_SIZE / 2.0)
self._wheel_radius = self.WHEEL_SIZE / 2.0 - 2.0
# Professional mode state: displacement (dx, dy) per grid point
self._grid_disp = [[(0.0, 0.0) for _ in range(_SAT_RINGS)] for _ in range(HUE_SECTORS)]
self._grid_drag_idx = None
self._grid_hover_idx = None
# Fast mode state
self._fast_grid = init_fast_grid()
self._fast_luma = init_luma_grid()
self._fast_drags = [] # persistent drag ops: [{"line","col","dest_theta","dest_r"}, ...]
self._fast_active_idx = None # index of drag being edited, or None
self._fast_new_source = None # (line, col) for new drag being created
self._fast_dest_px = None # pixel coords during drag
self._fast_hover_idx = None # index of hovered drag source, or None
self.setFixedSize(self.WHEEL_SIZE, self.WHEEL_SIZE)
self.setMouseTracking(True)
self._rebuild_wheel()
# -- Public API --
def hue(self) -> int:
return self._hue
def saturation(self) -> int:
return self._saturation
def brightness(self) -> int:
return self._brightness
def set_hue(self, value: int):
value = max(0, min(360, value))
if self._hue == value:
return
self._hue = value
self.update()
def set_saturation(self, value: int):
value = max(0, min(100, value))
if self._saturation == value:
return
self._saturation = value
self.update()
def set_brightness(self, value: int):
value = max(0, min(100, value))
if self._brightness == value:
return
self._brightness = value
self.brightness_changed.emit(self._brightness)
self.color_changed.emit(self._hue, self._saturation, self._brightness)
self.update()
def mode(self) -> str:
return self._mode
def set_mode(self, mode: str):
if mode not in ("fast", "professional"):
return
if self._mode == mode:
return
old_mode = self._mode
self._mode = mode
self._grid_drag_idx = None
self._grid_hover_idx = None
self._fast_active_idx = None
self._fast_new_source = None
self._fast_dest_px = None
self._dragging = False
if old_mode == "fast" and mode == "professional":
self._sync_fast_to_professional()
self.grid_changed.emit(self.grid_data())
self.update()
def grid_data(self) -> dict:
"""Return the current grid displacement state as HSV adjustment dicts.
Format: {"hue": 25x12, "sat": 25x12, "luma": 25x12}
Row 24 wraps to row 0 for interpolation continuity.
"""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
hue_grid = []
sat_grid = []
luma_grid = []
for h in range(HUE_SECTORS + 1):
h_idx = h % HUE_SECTORS
hue_row = []
sat_row = []
luma_row = []
for s in range(_SAT_RINGS):
dx, dy = self._grid_disp[h_idx][s]
hx, hy = self._grid_home_pos(h_idx, s)
if abs(dx) < 0.01 and abs(dy) < 0.01:
hue_row.append(0.0)
sat_row.append(0.0)
else:
home_angle, home_dist = _xy_to_polar(cx, cy, hx, hy)
cur_angle, cur_dist = _xy_to_polar(cx, cy, hx + dx, hy + dy)
angle_delta = math.degrees(cur_angle - home_angle)
if angle_delta > 180:
angle_delta -= 360
if angle_delta < -180:
angle_delta += 360
sat_delta = ((cur_dist - home_dist) / self._wheel_radius) * 100.0
hue_row.append(round(angle_delta, 2))
sat_row.append(round(sat_delta, 2))
luma_row.append(0.0)
hue_grid.append(hue_row)
sat_grid.append(sat_row)
luma_grid.append(luma_row)
return {"hue": hue_grid, "sat": sat_grid, "luma": luma_grid}
def fast_grid_data(self) -> dict:
"""Return the Fast mode grid state for CLUT computation."""
return {
"mode": "fast",
"grid": copy.deepcopy(self._fast_grid),
"luma": copy.deepcopy(self._fast_luma),
}
def set_grid_data(self, data: dict):
"""Load grid state from a dict (inverse of grid_data)."""
hue_grid = data.get("hue", [])
sat_grid = data.get("sat", [])
cx = self._wheel_center.x()
cy = self._wheel_center.y()
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
hue_delta = 0.0
sat_delta = 0.0
if h < len(hue_grid) and s < len(hue_grid[h]):
hue_delta = hue_grid[h][s]
if h < len(sat_grid) and s < len(sat_grid[h]):
sat_delta = sat_grid[h][s]
if abs(hue_delta) < 0.01 and abs(sat_delta) < 0.01:
self._grid_disp[h][s] = (0.0, 0.0)
continue
hx, hy = self._grid_home_pos(h, s)
home_angle, home_dist = _xy_to_polar(cx, cy, hx, hy)
new_angle = home_angle + math.radians(hue_delta)
new_dist = home_dist + (sat_delta / 100.0) * self._wheel_radius
new_dist = max(0, min(self._wheel_radius, new_dist))
nx, ny = _polar_to_xy(cx, cy, new_dist, new_angle)
self._grid_disp[h][s] = (nx - hx, ny - hy)
self.update()
def reset_grid(self):
"""Reset all grid points to home positions (both modes)."""
self._grid_disp = [[(0.0, 0.0) for _ in range(_SAT_RINGS)] for _ in range(HUE_SECTORS)]
self._grid_drag_idx = None
self._fast_grid = init_fast_grid()
self._fast_luma = init_luma_grid()
self._fast_drags = []
self._fast_active_idx = None
self._fast_new_source = None
self._fast_dest_px = None
if self._mode == "fast":
self.grid_changed.emit(self.fast_grid_data())
else:
self.grid_changed.emit(self.grid_data())
self.update()
# -- Painting --
def _rebuild_wheel(self):
"""Pre-render the HSV wheel as a QPixmap.
Always renders at full brightness so the color spectrum is visible regardless
of the camera's brightness parameter value.
"""
size = self.WHEEL_SIZE
pixmap = QPixmap(size, size)
pixmap.fill(Qt.GlobalColor.transparent)
p = QPainter(pixmap)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
cx = size / 2.0
cy = size / 2.0
radius = self._wheel_radius
hue_gradient = QConicalGradient(cx, cy, 0)
num_stops = 12
for i in range(num_stops + 1):
frac = i / num_stops
hue_val = frac * 360.0
if hue_val >= 360.0:
hue_val = 0.0
color = QColor.fromHsvF(hue_val / 360.0, 1.0, 1.0)
hue_gradient.setColorAt(frac, color)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QBrush(hue_gradient))
p.drawEllipse(QPointF(cx, cy), radius, radius)
sat_gradient = QRadialGradient(cx, cy, radius)
center_color = QColor(255, 255, 255, 255)
edge_color = QColor(255, 255, 255, 0)
sat_gradient.setColorAt(0.0, center_color)
sat_gradient.setColorAt(1.0, edge_color)
p.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceOver)
p.setBrush(QBrush(sat_gradient))
p.drawEllipse(QPointF(cx, cy), radius, radius)
p.end()
self._wheel_pixmap = pixmap
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor(COLOR_BG_PANEL))
p.drawEllipse(self._wheel_center, self._wheel_radius + 2, self._wheel_radius + 2)
if self._wheel_pixmap:
p.drawPixmap(0, 0, self._wheel_pixmap)
if self._mode == "fast":
self._paint_fast_mode(p)
else:
self._paint_grid(p)
p.end()
def _paint_fast_mode(self, p: QPainter):
"""Draw Fast mode persistent drag arrows and active drag."""
half = 5.0
for i, drag in enumerate(self._fast_drags):
sx, sy = self._grid_pos_to_pixel(drag["line"], drag["col"])
dx, dy = self._polar_norm_to_pixel(drag["dest_theta"], drag["dest_r"])
active = (i == self._fast_active_idx)
hovered = (i == self._fast_hover_idx) and not self._dragging
alpha = 220 if (active or hovered) else 140
src_half = half + 2.0 if hovered else half
p.setPen(QPen(QColor(255, 0, 67, alpha), 2.5 if hovered else 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawRect(QRectF(sx - src_half, sy - src_half, src_half * 2, src_half * 2))
p.setPen(QPen(QColor(255, 255, 255, alpha), 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawEllipse(QPointF(dx, dy), self.INDICATOR_RADIUS, self.INDICATOR_RADIUS)
self._paint_arrow(p, sx, sy, dx, dy, alpha)
if self._fast_dest_px is not None:
source = self._fast_new_source
if self._fast_active_idx is not None and self._fast_active_idx < len(self._fast_drags):
d = self._fast_drags[self._fast_active_idx]
source = (d["line"], d["col"])
if source is not None:
sx, sy = self._grid_pos_to_pixel(*source)
dx, dy = self._fast_dest_px
p.setPen(QPen(_SOURCE_COLOR, 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawRect(QRectF(sx - half, sy - half, half * 2, half * 2))
p.setPen(QPen(_DEST_COLOR, 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawEllipse(QPointF(dx, dy), self.INDICATOR_RADIUS, self.INDICATOR_RADIUS)
self._paint_arrow(p, sx, sy, dx, dy)
def _paint_arrow(self, p: QPainter, x1, y1, x2, y2, alpha=160):
"""Draw an arrow from (x1,y1) to (x2,y2)."""
dx = x2 - x1
dy = y2 - y1
length = math.sqrt(dx * dx + dy * dy)
if length < 5:
return
p.setPen(QPen(QColor(255, 255, 255, alpha), 1.5))
# Shaft
p.drawLine(QPointF(x1, y1), QPointF(x2, y2))
# Arrowhead
angle = math.atan2(dy, dx)
head_len = 8.0
spread = math.pi / 6.0
p.drawLine(
QPointF(x2, y2),
QPointF(x2 - head_len * math.cos(angle - spread), y2 - head_len * math.sin(angle - spread)),
)
p.drawLine(
QPointF(x2, y2),
QPointF(x2 - head_len * math.cos(angle + spread), y2 - head_len * math.sin(angle + spread)),
)
def _paint_grid(self, p: QPainter):
"""Draw the polar grid mesh and control points over the wheel."""
grid_pen = QPen(_GRID_LINE_COLOR, 0.75)
p.setPen(grid_pen)
p.setBrush(Qt.BrushStyle.NoBrush)
for s in range(_SAT_RINGS):
points = []
for h in range(HUE_SECTORS):
hx, hy = self._grid_home_pos(h, s)
dx, dy = self._grid_disp[h][s]
points.append(QPointF(hx + dx, hy + dy))
for i in range(HUE_SECTORS):
next_i = (i + 1) % HUE_SECTORS
p.drawLine(points[i], points[next_i])
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS - 1):
hx1, hy1 = self._grid_home_pos(h, s)
dx1, dy1 = self._grid_disp[h][s]
hx2, hy2 = self._grid_home_pos(h, s + 1)
dx2, dy2 = self._grid_disp[h][s + 1]
p.drawLine(QPointF(hx1 + dx1, hy1 + dy1), QPointF(hx2 + dx2, hy2 + dy2))
home_pen = QPen(_HOME_LINE_COLOR, 0.5, Qt.PenStyle.DotLine)
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
dx, dy = self._grid_disp[h][s]
if abs(dx) < 0.5 and abs(dy) < 0.5:
continue
hx, hy = self._grid_home_pos(h, s)
p.setPen(home_pen)
p.drawLine(QPointF(hx, hy), QPointF(hx + dx, hy + dy))
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
hx, hy = self._grid_home_pos(h, s)
dx, dy = self._grid_disp[h][s]
px, py = hx + dx, hy + dy
displaced = abs(dx) > 0.5 or abs(dy) > 0.5
hovered = self._grid_hover_idx == (h, s)
r = _GRID_POINT_RADIUS + (1.0 if hovered else 0.0)
if displaced:
p.setPen(QPen(QColor(40, 40, 40), 1.0))
p.setBrush(QBrush(_ACCENT_COLOR))
elif hovered:
p.setPen(QPen(QColor(40, 40, 40), 1.0))
p.setBrush(QBrush(QColor(255, 255, 255)))
else:
p.setPen(QPen(QColor(60, 60, 60), 0.75))
p.setBrush(QBrush(QColor(255, 255, 255, 200)))
p.drawEllipse(QPointF(px, py), r, r)
def _grid_home_pos(self, h_idx: int, s_idx: int) -> tuple:
"""Compute the undisplaced pixel position for grid point (h_idx, s_idx).
s_idx 0 is nearest center, s_idx (_SAT_RINGS-1) is at wheel edge.
"""
angle_rad = (h_idx / HUE_SECTORS) * _TWO_PI
frac = (s_idx + 1) / _SAT_RINGS
dist = frac * self._wheel_radius
return _polar_to_xy(self._wheel_center.x(), self._wheel_center.y(), dist, angle_rad)
def _grid_pos_to_pixel(self, line_num: int, col_num: int) -> tuple:
"""Convert a Fast mode grid position to pixel coordinates.
Uses the mathematical grid positions (same coordinate system as the algo).
col_num 0 is center, col_num 11 is outermost.
"""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
theta_deg = line_num * INTERVAL_THETA
r_norm = col_num * INTERVAL_R_NORM
pixel_r = r_norm / FULL_R_VALUE * self._wheel_radius
angle_rad = math.radians(theta_deg)
return (cx + pixel_r * math.cos(angle_rad), cy - pixel_r * math.sin(angle_rad))
def _polar_norm_to_pixel(self, theta_deg: float, r_norm: float) -> tuple:
"""Convert absolute polar coordinates to pixel position."""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
pixel_r = r_norm / FULL_R_VALUE * self._wheel_radius
angle_rad = math.radians(theta_deg)
return (cx + pixel_r * math.cos(angle_rad), cy - pixel_r * math.sin(angle_rad))
def _pixel_to_polar_norm(self, px: float, py: float) -> tuple:
"""Convert pixel position to (theta_degrees, r_normalized)."""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
dx = px - cx
dy = cy - py
r_pixels = math.sqrt(dx * dx + dy * dy)
theta_deg = math.degrees(math.atan2(dy, dx))
if theta_deg < 0:
theta_deg += 360.0
r_norm = r_pixels / self._wheel_radius * FULL_R_VALUE
return theta_deg, r_norm
def _find_nearest_fast_point(self, px: float, py: float) -> tuple:
"""Find the nearest Fast grid point to a pixel position.
Returns (line_num, col_num). Skips center column (col 0).
"""
theta_deg, r_norm = self._pixel_to_polar_norm(px, py)
line = round(theta_deg / INTERVAL_THETA) % HUE_SECTORS
col = round(r_norm / INTERVAL_R_NORM)
col = max(1, min(SAT_COLUMNS - 1, col))
return line, col
def _find_nearest_drag_source(self, px: float, py: float):
"""Find the index of the nearest committed drag source within hit radius, or None."""
best_idx = None
best_dist = _GRID_HIT_RADIUS * 1.5
for i, drag in enumerate(self._fast_drags):
sx, sy = self._grid_pos_to_pixel(drag["line"], drag["col"])
d = math.sqrt((px - sx) ** 2 + (py - sy) ** 2)
if d < best_dist:
best_dist = d
best_idx = i
return best_idx
def _rebuild_fast_grid(self):
"""Recompute fast grid from scratch by replaying all committed drags."""
self._fast_grid = init_fast_grid()
self._fast_luma = init_luma_grid()
for drag in self._fast_drags:
calc_rows_data(
drag["line"], drag["col"],
drag["dest_theta"], drag["dest_r"],
self._fast_grid,
)
def _sync_fast_to_professional(self):
"""Update professional grid displacements to reflect fast grid changes."""
identity = init_fast_grid()
cx = self._wheel_center.x()
cy = self._wheel_center.y()
for h in range(HUE_SECTORS):
for s in range(SAT_COLUMNS):
id_theta, id_r = identity[h][s]
cur_theta, cur_r = self._fast_grid[h][s]
theta_delta = cur_theta - id_theta
if theta_delta > 180:
theta_delta -= 360
if theta_delta < -180:
theta_delta += 360
r_delta = cur_r - id_r
if abs(theta_delta) < 0.01 and abs(r_delta) < 0.001:
self._grid_disp[h][s] = (0.0, 0.0)
continue
hx, hy = self._grid_home_pos(h, s)
home_angle, home_dist = _xy_to_polar(cx, cy, hx, hy)
new_angle = home_angle + math.radians(theta_delta)
r_delta_px = (r_delta / FULL_R_VALUE) * self._wheel_radius
new_dist = max(0, min(self._wheel_radius, home_dist + r_delta_px))
nx, ny = _polar_to_xy(cx, cy, new_dist, new_angle)
self._grid_disp[h][s] = (nx - hx, ny - hy)
def _indicator_pos(self) -> tuple:
"""Compute pixel position of the current hue/saturation indicator."""
angle_rad = (self._hue / 360.0) * _TWO_PI
dist = (self._saturation / 100.0) * self._wheel_radius
x = self._wheel_center.x() + dist * math.cos(angle_rad)
y = self._wheel_center.y() - dist * math.sin(angle_rad)
return x, y
# -- Mouse interaction --
def mousePressEvent(self, event):
if self._mode == "fast":
pos = event.position()
if event.button() == Qt.MouseButton.LeftButton:
idx = self._find_nearest_drag_source(pos.x(), pos.y())
if idx is not None:
self._fast_active_idx = idx
self._fast_new_source = None
else:
line, col = self._find_nearest_fast_point(pos.x(), pos.y())
self._fast_new_source = (line, col)
self._fast_active_idx = None
self._fast_dest_px = None
self._fast_hover_idx = None
self._dragging = True
self.setCursor(Qt.CursorShape.ClosedHandCursor)
self.update()
elif event.button() == Qt.MouseButton.RightButton:
idx = self._find_nearest_drag_source(pos.x(), pos.y())
if idx is not None:
del self._fast_drags[idx]
self._rebuild_fast_grid()
self.grid_changed.emit(self.fast_grid_data())
self.update()
return
pos = event.position()
if event.button() == Qt.MouseButton.RightButton:
hit = self._hit_test_grid(pos)
if hit is not None:
self._grid_disp[hit[0]][hit[1]] = (0.0, 0.0)
else:
self.reset_grid()
return
self.grid_changed.emit(self.grid_data())
self.update()
return
if event.button() == Qt.MouseButton.LeftButton:
hit = self._hit_test_grid(pos)
if hit is not None:
self._grid_drag_idx = hit
self._dragging = True
def mouseMoveEvent(self, event):
pos = event.position()
if self._mode == "fast":
if self._dragging and (self._fast_new_source is not None or self._fast_active_idx is not None):
cx = self._wheel_center.x()
cy = self._wheel_center.y()
dx = pos.x() - cx
dy = pos.y() - cy
dist = math.sqrt(dx * dx + dy * dy)
if dist > self._wheel_radius:
scale = self._wheel_radius / dist
px = cx + dx * scale
py = cy + dy * scale
else:
px, py = pos.x(), pos.y()
self._fast_dest_px = (px, py)
self.update()
else:
hover = self._find_nearest_drag_source(pos.x(), pos.y())
if hover != self._fast_hover_idx:
self._fast_hover_idx = hover
self.setCursor(
Qt.CursorShape.OpenHandCursor if hover is not None
else Qt.CursorShape.CrossCursor
)
self.update()
return
if self._dragging and self._grid_drag_idx is not None:
self._drag_grid_point(pos)
return
hit = self._hit_test_grid(pos)
if hit != self._grid_hover_idx:
self._grid_hover_idx = hit
self.update()
def mouseReleaseEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
if self._mode == "fast" and self._fast_dest_px is not None:
dest_theta, dest_r = self._pixel_to_polar_norm(*self._fast_dest_px)
if self._fast_active_idx is not None and self._fast_active_idx < len(self._fast_drags):
d = self._fast_drags[self._fast_active_idx]
d["dest_theta"] = dest_theta
d["dest_r"] = dest_r
elif self._fast_new_source is not None:
line, col = self._fast_new_source
self._fast_drags.append({
"line": line, "col": col,
"dest_theta": dest_theta, "dest_r": dest_r,
})
self._rebuild_fast_grid()
self._fast_active_idx = None
self._fast_new_source = None
self._fast_dest_px = None
self.grid_changed.emit(self.fast_grid_data())
self.update()
elif self._mode == "professional" and self._grid_drag_idx is not None:
self.grid_changed.emit(self.grid_data())
self._dragging = False
self._grid_drag_idx = None
self.setCursor(Qt.CursorShape.CrossCursor)
def _hit_test_grid(self, pos: QPointF):
"""Find the nearest grid point within hit radius, or None."""
px, py = pos.x(), pos.y()
best = None
best_dist = _GRID_HIT_RADIUS
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
hx, hy = self._grid_home_pos(h, s)
dx, dy = self._grid_disp[h][s]
gx, gy = hx + dx, hy + dy
d = math.sqrt((px - gx) ** 2 + (py - gy) ** 2)
if d < best_dist:
best_dist = d
best = (h, s)
return best
def _drag_grid_point(self, pos: QPointF):
"""Update the displacement of the currently dragged grid point."""
h, s = self._grid_drag_idx
hx, hy = self._grid_home_pos(h, s)
px, py = pos.x(), pos.y()
cx = self._wheel_center.x()
cy = self._wheel_center.y()
dx = px - cx
dy = py - cy
dist = math.sqrt(dx * dx + dy * dy)
if dist > self._wheel_radius:
scale = self._wheel_radius / dist
px = cx + dx * scale
py = cy + dy * scale
self._grid_disp[h][s] = (px - hx, py - hy)
self.update()
@@ -0,0 +1,140 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Parameter slider widget with label, slider, and spinbox."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QWidget, QHBoxLayout, QLabel, QSlider, QSpinBox, QDoubleSpinBox, QSizePolicy,
)
class ParamSlider(QWidget):
"""Row layout with label, slider, and spinbox for adjusting a parameter."""
value_changed = Signal(float)
def __init__(self, label: str, min_val: float = 0, max_val: float = 100,
default: float = 50, step: float = 1, decimals: int = 0,
suffix: str = "", parent=None):
super().__init__(parent)
self._min = min_val
self._max = max_val
self._step = step
self._decimals = decimals
self._block_signals = False
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
self._label = QLabel(label)
self._label.setFixedWidth(110)
self._label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
layout.addWidget(self._label)
self._slider = QSlider(Qt.Orientation.Horizontal)
self._slider.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
if decimals > 0:
self._scale = 10 ** decimals
self._slider.setMinimum(int(min_val * self._scale))
self._slider.setMaximum(int(max_val * self._scale))
self._slider.setSingleStep(int(step * self._scale))
self._slider.setValue(int(default * self._scale))
self._spin = QDoubleSpinBox()
self._spin.setDecimals(decimals)
self._spin.setMinimum(min_val)
self._spin.setMaximum(max_val)
self._spin.setSingleStep(step)
self._spin.setValue(default)
if suffix:
self._spin.setSuffix(suffix)
self._slider.valueChanged.connect(self._slider_moved_float)
self._spin.valueChanged.connect(self._spin_changed_float)
else:
self._scale = 1
self._slider.setMinimum(int(min_val))
self._slider.setMaximum(int(max_val))
self._slider.setSingleStep(int(step))
self._slider.setValue(int(default))
self._spin = QSpinBox()
self._spin.setMinimum(int(min_val))
self._spin.setMaximum(int(max_val))
self._spin.setSingleStep(int(step))
self._spin.setValue(int(default))
if suffix:
self._spin.setSuffix(suffix)
self._slider.valueChanged.connect(self._slider_moved_int)
self._spin.valueChanged.connect(self._spin_changed_int)
layout.addWidget(self._slider, 1)
self._spin.setFixedWidth(70)
self._spin.setAlignment(Qt.AlignmentFlag.AlignRight)
layout.addWidget(self._spin)
def _slider_moved_int(self, val: int):
if self._block_signals:
return
self._block_signals = True
self._spin.setValue(val)
self._block_signals = False
self.value_changed.emit(float(val))
def _spin_changed_int(self, val: int):
if self._block_signals:
return
self._block_signals = True
self._slider.setValue(val)
self._block_signals = False
self.value_changed.emit(float(val))
def _slider_moved_float(self, val: int):
if self._block_signals:
return
fval = val / self._scale
self._block_signals = True
self._spin.setValue(fval)
self._block_signals = False
self.value_changed.emit(fval)
def _spin_changed_float(self, val: float):
if self._block_signals:
return
self._block_signals = True
self._slider.setValue(int(val * self._scale))
self._block_signals = False
self.value_changed.emit(val)
def value(self) -> float:
if self._decimals > 0:
return self._spin.value()
return float(self._spin.value())
def set_value(self, val: float, emit: bool = True):
self._block_signals = True
if self._decimals > 0:
self._spin.setValue(val)
self._slider.setValue(int(val * self._scale))
else:
self._spin.setValue(int(val))
self._slider.setValue(int(val))
self._block_signals = False
if emit:
self.value_changed.emit(val)
def set_enabled(self, enabled: bool):
self._slider.setEnabled(enabled)
self._spin.setEnabled(enabled)
@@ -0,0 +1,109 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Preset bar for quick scene switching."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QWidget, QHBoxLayout, QPushButton, QSizePolicy, QMenu, QInputDialog,
)
from ..theme import COLOR_ACCENT, COLOR_BG_INPUT, COLOR_BORDER, COLOR_TEXT_PRIMARY, COLOR_TEXT_SECONDARY
class PresetBar(QWidget):
"""Horizontal bar with preset buttons and an add button."""
preset_selected = Signal(str)
save_requested = Signal()
preset_deleted = Signal(str)
preset_renamed = Signal(str, str)
def __init__(self, parent=None):
super().__init__(parent)
self._presets: list[str] = []
self._active: str | None = None
self._buttons: dict[str, QPushButton] = {}
self._layout = QHBoxLayout(self)
self._layout.setContentsMargins(0, 4, 0, 4)
self._layout.setSpacing(4)
self._add_btn = QPushButton("+")
self._add_btn.setFixedSize(28, 28)
self._add_btn.setCursor(Qt.CursorShape.PointingHandCursor)
self._add_btn.setToolTip("Save new preset")
self._add_btn.setStyleSheet(f"""
QPushButton {{ background-color: {COLOR_BG_INPUT}; color: {COLOR_TEXT_SECONDARY};
border: 1px solid {COLOR_BORDER}; border-radius: 4px; font-size: 16px; font-weight: bold; }}
QPushButton:hover {{ color: {COLOR_TEXT_PRIMARY}; border-color: {COLOR_ACCENT}; }}
""")
self._add_btn.clicked.connect(self.save_requested.emit)
self._layout.addStretch()
self._layout.addWidget(self._add_btn)
def set_presets(self, names: list[str], active: str | None = None):
for btn in self._buttons.values():
self._layout.removeWidget(btn)
btn.deleteLater()
self._buttons.clear()
self._presets = list(names)
self._active = active
insert_pos = 0
for name in names:
btn = self._make_button(name)
self._layout.insertWidget(insert_pos, btn)
self._buttons[name] = btn
insert_pos += 1
self._apply_styles()
def _make_button(self, name: str) -> QPushButton:
btn = QPushButton(name)
btn.setFixedHeight(28)
btn.setCursor(Qt.CursorShape.PointingHandCursor)
btn.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
btn.clicked.connect(lambda: self._select(name))
btn.customContextMenuRequested.connect(lambda pos, n=name: self._context_menu(n, pos))
return btn
def _select(self, name: str):
self._active = name
self._apply_styles()
self.preset_selected.emit(name)
def _context_menu(self, name: str, pos):
menu = QMenu(self)
rename_action = menu.addAction("Rename")
delete_action = menu.addAction("Delete")
action = menu.exec(self._buttons[name].mapToGlobal(pos))
if action == rename_action:
new_name, ok = QInputDialog.getText(self, "Rename Preset", "New name:", text=name)
if ok and new_name and new_name != name:
self.preset_renamed.emit(name, new_name)
elif action == delete_action:
self.preset_deleted.emit(name)
def _apply_styles(self):
for name, btn in self._buttons.items():
active = (name == self._active)
if active:
btn.setStyleSheet(f"""
QPushButton {{ background-color: {COLOR_ACCENT}; color: {COLOR_TEXT_PRIMARY};
border: none; border-radius: 4px; font-weight: bold; padding: 2px 10px; }}
""")
else:
btn.setStyleSheet(f"""
QPushButton {{ background-color: {COLOR_BG_INPUT}; color: {COLOR_TEXT_SECONDARY};
border: 1px solid {COLOR_BORDER}; border-radius: 4px; padding: 2px 10px; }}
QPushButton:hover {{ color: {COLOR_TEXT_PRIMARY}; border-color: {COLOR_ACCENT}; }}
""")
@@ -0,0 +1,126 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Segmented button control for mutually exclusive options."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QWidget, QHBoxLayout, QPushButton, QSizePolicy
from PySide6.QtGui import QFont
from ..theme import COLOR_ACCENT, COLOR_BG_INPUT, COLOR_BORDER, COLOR_TEXT_PRIMARY, COLOR_TEXT_SECONDARY
class SegmentButton(QWidget):
"""Row of exclusive buttons styled as a segmented control."""
selection_changed = Signal(int)
selection_changed_text = Signal(str)
def __init__(self, options: list[str], parent=None):
super().__init__(parent)
self._options = options
self._buttons: list[QPushButton] = []
self._selected = 0
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.setStyleSheet(f"""
SegmentButton {{
background: {COLOR_BG_INPUT};
border: 1px solid {COLOR_BORDER};
border-radius: 6px;
}}
""")
for i, label in enumerate(options):
btn = QPushButton(label)
btn.setCheckable(True)
btn.setCursor(Qt.CursorShape.PointingHandCursor)
btn.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
btn.setFixedHeight(28)
btn.clicked.connect(lambda checked, idx=i: self._on_click(idx))
self._buttons.append(btn)
layout.addWidget(btn)
self._apply_styles()
def _apply_styles(self):
for i, btn in enumerate(self._buttons):
active = (i == self._selected)
radius_left = "6px" if i == 0 else "0px"
radius_right = "6px" if i == len(self._buttons) - 1 else "0px"
if active:
btn.setStyleSheet(f"""
QPushButton {{
background-color: {COLOR_ACCENT};
color: {COLOR_TEXT_PRIMARY};
border: none;
border-radius: 0px;
border-top-left-radius: {radius_left};
border-bottom-left-radius: {radius_left};
border-top-right-radius: {radius_right};
border-bottom-right-radius: {radius_right};
font-weight: bold;
font-size: 12px;
padding: 2px 8px;
}}
""")
else:
btn.setStyleSheet(f"""
QPushButton {{
background-color: transparent;
color: {COLOR_TEXT_SECONDARY};
border: none;
border-radius: 0px;
border-top-left-radius: {radius_left};
border-bottom-left-radius: {radius_left};
border-top-right-radius: {radius_right};
border-bottom-right-radius: {radius_right};
font-size: 12px;
padding: 2px 8px;
}}
QPushButton:hover {{
color: {COLOR_TEXT_PRIMARY};
background-color: rgba(255,255,255,0.05);
}}
""")
btn.setChecked(active)
def _on_click(self, index: int):
if index == self._selected:
return
self._selected = index
self._apply_styles()
self.selection_changed.emit(index)
self.selection_changed_text.emit(self._options[index])
def selected_index(self) -> int:
return self._selected
def selected_text(self) -> str:
return self._options[self._selected]
def set_selected(self, index: int, emit: bool = True):
if index < 0 or index >= len(self._options):
return
if index == self._selected:
return
self._selected = index
self._apply_styles()
if emit:
self.selection_changed.emit(index)
self.selection_changed_text.emit(self._options[index])
@@ -0,0 +1,95 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""iOS-style toggle switch widget."""
from PySide6.QtCore import Qt, Signal, QPropertyAnimation, QEasingCurve, Property, QRectF
from PySide6.QtWidgets import QWidget
from PySide6.QtGui import QPainter, QColor
from ..theme import COLOR_ACCENT, COLOR_TOGGLE_OFF
class ToggleSwitch(QWidget):
"""Custom painted toggle switch. Pink when on, gray when off."""
toggled = Signal(bool)
TRACK_W = 44
TRACK_H = 22
THUMB_RADIUS = 8
THUMB_MARGIN = 3
def __init__(self, checked: bool = False, parent=None):
super().__init__(parent)
self._checked = checked
self._thumb_pos = float(self.TRACK_W - self.THUMB_MARGIN - self.THUMB_RADIUS
if checked
else self.THUMB_MARGIN + self.THUMB_RADIUS)
self.setFixedSize(self.TRACK_W, self.TRACK_H)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self._anim = QPropertyAnimation(self, b"thumb_pos")
self._anim.setDuration(150)
self._anim.setEasingCurve(QEasingCurve.Type.InOutQuad)
def _get_thumb_pos(self) -> float:
return self._thumb_pos
def _set_thumb_pos(self, val: float):
self._thumb_pos = val
self.update()
thumb_pos = Property(float, _get_thumb_pos, _set_thumb_pos)
def is_checked(self) -> bool:
return self._checked
def set_checked(self, checked: bool, emit: bool = True):
if self._checked == checked:
return
self._checked = checked
target = (self.TRACK_W - self.THUMB_MARGIN - self.THUMB_RADIUS
if checked
else self.THUMB_MARGIN + self.THUMB_RADIUS)
self._anim.stop()
self._anim.setStartValue(self._thumb_pos)
self._anim.setEndValue(float(target))
self._anim.start()
if emit:
self.toggled.emit(checked)
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.set_checked(not self._checked)
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
track_color = QColor(COLOR_ACCENT) if self._checked else QColor(COLOR_TOGGLE_OFF)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(track_color)
p.drawRoundedRect(QRectF(0, 0, self.TRACK_W, self.TRACK_H),
self.TRACK_H / 2, self.TRACK_H / 2)
p.setBrush(QColor("#ffffff"))
p.drawEllipse(QRectF(self._thumb_pos - self.THUMB_RADIUS,
(self.TRACK_H - 2 * self.THUMB_RADIUS) / 2,
2 * self.THUMB_RADIUS, 2 * self.THUMB_RADIUS))
p.end()