Skip to main content

Data Viewer Widget Roadmap

DataViewer Widget Development Roadmap

This document tracks remaining development tasks for the Data Viewer Widget. For documentation of completed features and current architecture, see the main developer documentation.

For the mixed-lane ordering refactor that precedes interactive lane drag-and-drop, see ordering abstractions implementation roadmap.

NotePre-Architecture Widget

The Data Viewer Widget was the first plot widget developed, before the unified Plots/ directory structure and common axis/interaction infrastructure. Several refactoring items below extract DataViewer-specific code into shared components or adopt existing shared components from Plots/Common/. These refactoring tasks are ordered by priority and can be interleaved with feature work.

TipRelated GitHub Issues

Open issues tracking remaining feature work:

  • #223 — Extract reusable temporal X-axis (CenteredTimeAxis widget)
  • #227 — Mouse-wheel modifiers for Y scaling (global, per-lane, viewport zoom)
  • #247 — Y-axis scalebars and lane labels

Closed issues:

  • #248 — Viewport culling and configurable lane sizing (completed in Phases 1 + 2)

Completed Work Summary

The following features are complete and documented in index.qmd:

  • EditorState pattern: DataViewerState with DataViewerStateData serialization via reflect-cpp
  • SeriesOptionsRegistry: Generic type-safe per-series options for analog, event, and interval types
  • Rendering pipeline: SceneBuildingHelpers → RenderableBatch → PlottingOpenGL::SceneRenderer
  • Layout system: CorePlotting::LayoutEngine with StackedLayoutStrategy; spike sorter configuration for custom channel ordering; FitToViewport lane sizing with configurable margin_factor
  • Y-axis transform pipeline: TransformComposers composing data normalization, user adjustments, layout positioning, global scaling
  • Interaction system: DataViewerInteractionManager state machine (Normal, CreateInterval, ModifyInterval, CreateLine modes)
  • Interval editing: Click-to-select, edge dragging, collision prevention, multi-timeframe support
  • Entity selection: Multi-select via Ctrl+click in DataViewerSelectionManager
  • Coordinate transforms: Unified DataViewerCoordinates class for canvas ↔︎ world ↔︎ time ↔︎ data conversions
  • Analog vertex cache: Ring buffer for 26–130x faster scrolling rendering
  • SVG export: Publication-quality export using the same scene building as OpenGL rendering
  • Time frame synchronization: Cross-sampling-rate display (e.g., 30 kHz electrophysiology + 500 Hz video)
  • Grouped data: Group loading with auto-calculated scaling and event spacing
  • Theme and grid: Dark/Light themes, configurable grid overlay
  • DataManager observer: Combo box population, stale key cleanup
  • Developer Debug Panel: Real-time diagnostics for lane layout, scales, coordinate transforms, and viewport state

Not yet implemented: Common axis integration, Y pan/zoom for channel navigation, enhanced per-type visual options, viewport culling, and shared component extraction described below.


Phase 1: Layout Foundation

Status: Complete. Issues: #248, #227

Goal: Establish the lane sizing model that all subsequent Y-axis features depend on.

1.1 Y-Scale State Audit

Merged global_zoom and global_vertical_scale into a single global_y_scale field. Exposed as “Global Y Scale” in the UI and used consistently in all TransformComposers functions.

1.2 Configurable Lane Sizing

StackedLayoutStrategy uses FitToViewport (equal division of viewport among stackable lanes). Layout config persisted in DataViewerLayoutConfig via reflect-cpp with a user-configurable margin_factor (fraction of allocated lane height used for data rendering, default 0.8). State API: setMarginFactor(), marginFactor(), layoutConfigChanged() signal.

Note

The former FixedHeight lane sizing policy (with lane_height and lane_gap parameters) was removed because Y viewport zoom (y_zoom + y_pan in ViewStateData) provides the same functionality — users zoom into the viewport to see a subset of channels at larger resolution, rather than setting a fixed pixel height per lane.

Key files: StackedLayoutStrategy.hpp/.cpp, DataViewerStateData.hpp, DataViewerState.hpp/.cpp

1.3 Lane Sizing UI Controls

“Layout Settings” group in DataViewerPropertiesWidget: margin factor spinbox (0.1–1.0). Bidirectional sync via layoutConfigChanged().

1.4 Verification

32+ channels in FitToViewport all visible. Y viewport zoom shows subset with panning. Workspace save/restore roundtrips layout config.


Phase 1B: Rendering Pipeline Modernization

Status: Complete. Depends on: Phase 1.

Goal: Migrate from TimeSeriesViewState to shared ViewStateData zoom/pan model. Eliminate the performance bottleneck where Y-axis panning triggered full scene rebuild + GPU re-upload every frame.

Summary of Changes

ViewStateData adoption (1B.1): DataViewerStateData::view is now CorePlotting::ViewStateData (x_min/x_max as double, y_min/y_max, y_pan, y_zoom). global_y_scale remains a separate field in DataViewerStateData (data amplitude gain, not a view transform). DataViewer defaults: x_min=0, x_max=1000, y_min=-1, y_max=1. Convenience methods on DataViewerState: timeStart(), timeEnd(), timeWidth(), timeCenter().

Scene dirty guard (1B.3, 1B.6): OpenGLWidget uses separate signal handlers:

  • timeWindowChanged → scene_dirty = true (scene rebuild needed)
  • viewStateChanged → matrix update only (Y pan/zoom is instant)
  • layoutConfigChanged → scene_dirty = true (layout transforms baked into vertices)
  • global_y_scale changes detected via cached comparison → scene_dirty = true

Scene rebuilds (rebuildScene()) only occur when _cache_state.scene_dirty is set. Y-axis panning updates only the projection/view matrices.

Caller migration (1B.7): All files across DataViewer_Widget/ updated to use ViewStateData field names (x_min/x_max/y_pan with appropriate casts). DataViewerCoordinates, DataViewerInputHandler, DataViewerInteractionManager, DataViewerDebugPanel, DataViewerPropertiesWidget, SVGExporter, and all test files migrated.

Key architectural decisions:

  • x_zoom fixed at 1.0, x_pan at 0.0 (DataViewer X-axis controlled externally via time bar)
  • Lane sizing policy changes reset y_pan to 0 to prevent stranded viewport on mode switch
  • double precision for time bounds sufficient for indices up to ~9×10¹⁵

Phase 2: Y-Axis Navigation

Status: In progress (Phase 2.1 completed). Issues: #227 (wheel modifiers, per-lane scaling), #248 (viewport culling), #247 (axis synchronization) Depends on: Phase 1 (layout foundation must exist), Phase 1B (pan/zoom must be performant before adding more interaction modes).

Goal: Allow users to pan and zoom the Y-axis so they can view a subset of channels at readable resolution, inspired by EventPlotWidget’s trial Y navigation.

2.1 MultiLaneVerticalAxisWidget (Minimal Version)

Create a new MultiLaneVerticalAxisWidget in Plots/Common/ and integrate it into DataViewer. This is a standalone widget — not a subclass of the existing single-range VerticalAxisWidget, which continues to serve ScatterPlotWidget and EventPlotWidget unchanged.

The existing VerticalAxisWidget manages a single y_min/y_max range with uniform tick marks. DataViewer lanes have independent amplitude scales (each series has its own user_scale_factor, data range, and normalization), so a single-range axis cannot meaningfully represent per-lane amplitudes. Building the multi-lane widget from the start avoids a throwaway integration cycle.

New files:

Plots/Common/MultiLaneVerticalAxisWidget/
├── Core/
│   ├── MultiLaneVerticalAxisStateData.hpp   # LaneAxisDescriptor + vector, serializable
│   └── MultiLaneVerticalAxisState.hpp       # QObject with lane update signals
├── MultiLaneVerticalAxisWidget.hpp/.cpp     # QPainter rendering: labels + separators
└── CMakeLists.txt

The widget follows the standard four-layer pattern (StateData → State → Widget → optional WithControls) and is driven by a std::vector<LaneAxisDescriptor>:

struct LaneAxisDescriptor {
    std::string lane_id;        ///< Series key in DataManager
    std::string label;          ///< Display name (channel name or series key)
    float y_center;             ///< Center Y position in world coordinates
    float y_half_height;        ///< Half-height of the lane in world coordinates
};

Minimal rendering scope (Phase 2 only):

  • Channel name labels painted at each lane’s center Y position
  • Lane boundary separators (horizontal lines between lanes)
  • Viewport-aware: only renders labels for lanes visible in the current Y viewport
  • Fixed 50px width (matching existing VerticalAxisWidget sizeHint)

Scalebars, visibility toggles, and per-lane range annotations are deferred to Phase 3, which adds them incrementally to this same widget.

Layout: Place MultiLaneVerticalAxisWidget in a QHBoxLayout to the left of OpenGLWidget:

DataViewer_Widget (QWidget)
├── QVBoxLayout
│   ├── QHBoxLayout [stretch 1]
│   │   ├── MultiLaneVerticalAxisWidget (50px fixed width)
│   │   └── OpenGLWidget [stretch 1]
│   └── (future: CenteredTimeAxisWidget — Phase 4)

State integration:

// In DataViewerState
_multi_lane_axis_state = std::make_unique<MultiLaneVerticalAxisState>(this);

Data flow (one-directional — labels are read-only display):

  • After each layout computation, DataViewer extracts LaneAxisDescriptor entries from LayoutResponse and pushes them to MultiLaneVerticalAxisState
  • DataViewerState::viewStateChanged → widget repaint (for Y pan/zoom tracking)
  • No bidirectional range sync is needed (Y pan/zoom originates from wheel events on OpenGLWidget, not from the axis widget)

Files: src/WhiskerToolbox/Plots/Common/MultiLaneVerticalAxisWidget/ (new), src/WhiskerToolbox/DataViewer_Widget/Core/DataViewerState.hpp, src/WhiskerToolbox/DataViewer_Widget/Core/DataViewerState.cpp, src/WhiskerToolbox/DataViewer_Widget/Core/DataViewerStateData.hpp, src/WhiskerToolbox/DataViewer_Widget/UI/DataViewer_Widget.cpp

2.3 Viewport Visibility Culling

When many channels are loaded but only a few are visible (e.g., viewing 4 of 32 channels), non-visible series are culled from the rendering pipeline using additive culling:

  1. Layout query: LayoutResponse::isSeriesVisible() and visibleSeriesIds() determine which lanes overlap the effective Y viewport (accounting for y_pan).
  2. Additive tracking: SceneCacheState::series_in_scene tracks which series have been built into the current scene. The set accumulates across pan-triggered rebuilds and is only cleared on full data changes (time window, layout config, global Y scale).
  3. Pan-triggered rebuild: hasNewVisibleSeries() checks if any enabled, viewport-visible series is not yet in series_in_scene. If so, an additive rebuild is triggered that builds the new series plus all previously-built series.
  4. Additive batch building: add*BatchesToBuilder methods skip a series only if it is both off-screen AND not in series_in_scene. This ensures panning never removes already-rendered series from the scene.

Non-stackable series (full-canvas intervals, full-canvas events) always pass the visibility check because their layout spans the entire viewport.

Key files: src/CorePlotting/Layout/LayoutEngine.hpp (isSeriesVisible, visibleSeriesIds), src/CorePlotting/Layout/LayoutEngine.cpp, src/WhiskerToolbox/DataViewer_Widget/Rendering/OpenGLWidget.hpp (SceneCacheState::series_in_scene, hasNewVisibleSeries), src/WhiskerToolbox/DataViewer_Widget/Rendering/OpenGLWidget.cpp

2.4 Wheel Modifier Chords for Y Interaction

ImportantPreserving Existing Behavior

The current default mouse wheel behavior (time-axis zoom) must be preserved. Users who do not use modifiers should see no change. Y-axis panning is already handled by left-click drag (via DataViewerInputHandler) and does not need a wheel chord.

WarningKnown Limitation — Y Viewport Zoom Not Yet Rendered

The Alt+Ctrl+Scroll chord correctly updates y_zoom and y_pan in ViewStateData, but the DataViewer rendering pipeline does not yet incorporate y_zoom into the projection or view matrices. As a result, the gesture currently appears as a pan rather than a zoom. See Phase 2.7 for the rendering refactoring plan.

Current behavior (unchanged):

Modifier Action
None Time-axis zoom (normal sensitivity)
Shift Time-axis zoom (fine sensitivity)
Ctrl Time-axis zoom (coarse sensitivity)
Left-drag Y-axis pan

New chords — all Y-axis wheel actions share Alt as the common prefix, distinguishing them from X-axis zoom (no Alt):

Modifier Action Scope State Field
Alt+Scroll Global Y scale All lanes global_y_scale
Alt+Shift+Scroll Per-lane Y scale Hovered lane user_scale_factor in AnalogSeriesOptionsData
Alt+Ctrl+Scroll Y viewport zoom (cursor-anchored) View matrix y_zoom in ViewStateData

Global Y scale (Alt+Scroll): Adjusts global_y_scale, which amplifies all series uniformly within their lanes. This is a data gain factor baked into vertices, so it triggers a scene rebuild.

Per-lane Y scale (Alt+Shift+Scroll): Adjusts the user_scale_factor for the analog series under the cursor. Uses OpenGLWidget::findSeriesAtPosition() for hit testing. No-op if the cursor is not over an analog lane. The per-series scale is already serialized and shown in the properties panel, so this provides a mouse-driven shortcut for an existing feature. Shift narrows the scope from global to local.

Y viewport zoom (Alt+Ctrl+Scroll): Adjusts y_zoom in ViewStateData, which scales the view matrix — making lane heights appear larger or smaller without changing the data gain. This is a cheap matrix-only update (no scene rebuild). Cursor-anchored: the focal point under the mouse remains stable during zoom. Define min/max span clamps so projection and hit testing never degenerate.

Implementation notes:

  • Alt+click is window-move on some Linux WMs, but Alt+Scroll is generally safe
  • Respect OpenGLWidget::isInteractionActive() (no zoom while creating/editing intervals)
  • When multiple modifiers match (e.g., Alt+Ctrl+Shift), the most specific chord wins: per-lane (Alt+Shift) > viewport zoom (Alt+Ctrl) > global scale (Alt)
  • Document chords in a user-facing summary (tooltip, status bar, or User Guide stub)

Spinbox synchronization: The properties panel already has spinboxes for global_y_scale and per-series user_scale_factor. Wheel-driven changes update these spinboxes without triggering feedback loops by leveraging the existing _updating_from_state guard in DataViewerPropertiesWidget::_connectStateSignals():

  • Global Y scale: _handleGlobalYScaleWheel() calls setGlobalYScale() on the state, which emits viewStateChanged. The properties widget’s viewStateChanged handler sets _updating_from_state = true, updates the spinbox value, then clears the guard — preventing the spinbox’s valueChanged signal from re-entering the state setter.
  • Per-lane Y scale: _handlePerLaneYScaleWheel() uses the same getMutable() + update() pattern as AnalogViewer_Widget::_setAnalogScaleFactor(). No spinbox sync is needed because the AnalogViewer_Widget sub-panel only shows when the user explicitly selects a series in the feature tree, and the spinbox value is set when setActiveKey() is called.

Key implementation details:

  • Three new private helper methods in DataViewer_Widget: _handleGlobalYScaleWheel(), _handlePerLaneYScaleWheel(), _handleYViewportZoomWheel()
  • OpenGLWidget::findSeriesAtPosition() moved from private to public for hit testing
  • All wheel handlers use multiplicative 5% steps with std::clamp for bounds
  • Y viewport zoom is cursor-anchored: computes world-Y under cursor before zoom, then adjusts y_pan so the same world-Y maps back to the same screen position after zoom

Files: src/WhiskerToolbox/DataViewer_Widget/UI/DataViewer_Widget.cpp (wheelEvent), src/WhiskerToolbox/DataViewer_Widget/Core/DataViewerState.cpp, src/WhiskerToolbox/DataViewer_Widget/Core/SeriesOptionsRegistry.cpp, src/WhiskerToolbox/DataViewer_Widget/UI/DataViewerPropertiesWidget.cpp

2.5 Visible Lane Indicator in Properties Panel

A read-only “Visible lanes: N of M” label in DataViewerPropertiesWidget updates whenever the viewport or lane count changes. Added to the Layout Settings group in the properties panel UI. The update is driven by two signal connections wired in DataViewerWidgetRegistration::create_editor_custom:

  • OpenGLWidget::sceneRebuilt → recomputes visible/total from layout response
  • DataViewerState::viewStateChanged → recomputes when Y pan/zoom changes

The effective viewport is computed as [y_min + y_pan, y_max + y_pan] and passed to LayoutResponse::visibleSeriesIds() to count visible lanes.

Files: src/WhiskerToolbox/DataViewer_Widget/UI/DataViewerPropertiesWidget.cpp, src/WhiskerToolbox/DataViewer_Widget/UI/DataViewerPropertiesWidget.hpp, src/WhiskerToolbox/DataViewer_Widget/UI/DataViewerPropertiesWidget.ui, src/WhiskerToolbox/DataViewer_Widget/DataViewerWidgetRegistration.cpp

2.6 Verification

  • Load 32+ channels.
  • Y pan scrolls through lanes; Y zoom narrows the visible range.
  • Viewport culling skips off-screen series (verify via Developer Debug Panel rendering stats).
  • Per-lane hover scaling adjusts the hovered series only.
  • Channel name labels appear on the MultiLaneVerticalAxisWidget at correct Y positions.
  • Labels scroll correctly during Y pan and recompute when series are added/removed.
  • “Visible lanes: N of M” indicator updates correctly.
  • Workspace save/restore roundtrips all new state.
  • Existing DataViewer_Widget tests that assert time window changes after wheel remain green.
  • Existing VerticalAxisWidget consumers (ScatterPlot, EventPlot) are unaffected.

2.7 Y Viewport Zoom Rendering Support

Status: Complete.

Summary

y_zoom in ViewStateData now affects rendered output in DataViewer so that Alt+Ctrl+Scroll produces true cursor-anchored Y viewport zoom.

The implementation folds both y_zoom and y_pan into the projection matrix via a new computeEffectiveYViewport() helper in ViewStateData.hpp. The view matrix is now identity — all vertical camera state lives in the projection. Every location that previously computed effective_y_min = y_min + y_pan now calls the helper instead.

Changes Made

File Changes
ViewStateData.hpp (CorePlotting) Added EffectiveYViewport struct and computeEffectiveYViewport() inline helper
OpenGLWidget.cpp updateMatrices(), rebuildScene(), hasNewVisibleSeries(), all add*BatchesToBuilder(), getDiagnostics(), drawLaneBoundaries(), drawOriginMarkers(), findSeriesAtPosition() — all use effective viewport, view matrix is identity
SVGExporter.cpp buildScene() uses effective viewport, view matrix is identity
DataViewerCoordinates.cpp Constructor uses effective viewport for YAxisParams
DataViewerInputHandler.cpp Pan delta scales inversely with y_zoom
DataViewerDebugPanel.cpp Coordinate inspector and Y bounds display use effective viewport
DataViewerWidgetRegistration.cpp Visible lane indicator uses effective viewport
DataViewer_Widget.cpp _handleYViewportZoomWheel() rewritten with correct cursor-anchoring math; MultiLaneVerticalAxisWidget uses setViewportGetter()
MultiLaneVerticalAxisWidget.hpp/.cpp New ViewportGetter type returning {y_min, y_max} effective bounds; deprecated setPanGetter(); ndcToPixelY() and isLaneVisible() use viewport getter

Phase 3: Y-Axis Scalebars and Enhanced Lane Annotations

Status: Not started. Issues: #247 Depends on: Phase 2 (MultiLaneVerticalAxisWidget exists with minimal label + separator rendering)

Goal: Extend the MultiLaneVerticalAxisWidget created in Phase 2.1 with per-lane scalebars, visibility toggles, and smart label positioning so users can interpret amplitudes and identify individual traces at a glance.

NoteIncremental Enhancement — No Widget Replacement

Phase 2.1 creates the MultiLaneVerticalAxisWidget with channel name labels and lane separators. All Phase 3 work is additive to that same widget — extending LaneAxisDescriptor with amplitude range fields, adding scalebar rendering to paintEvent(), and wiring new toggle controls. No widget is replaced or discarded.

3.1 Extend LaneAxisDescriptor with Amplitude Information

Add per-lane amplitude fields to LaneAxisDescriptor so the widget can render scalebars:

struct LaneAxisDescriptor {
    std::string lane_id;        ///< Series key in DataManager
    std::string label;          ///< Display name (channel name or series key)
    float y_center;             ///< Center Y position in world coordinates
    float y_half_height;        ///< Half-height of the lane in world coordinates
    double amplitude_min;       ///< Data-space minimum (after user_scale_factor)
    double amplitude_max;       ///< Data-space maximum (after user_scale_factor)
    std::string unit;           ///< Amplitude unit label (e.g., "µV", "mV")
    bool show_scalebar = true;  ///< Per-lane scalebar visibility
};

DataViewer populates the new fields from per-series statistics, user_scale_factor, and group scaling normalization during layout computation.

Files: src/WhiskerToolbox/Plots/Common/MultiLaneVerticalAxisWidget/Core/MultiLaneVerticalAxisStateData.hpp

3.2 Per-Lane Y-Axis Scalebars

Within each lane’s Y band in the axis widget, draw a small scalebar indicating the amplitude range:

  • A vertical bar with two endpoints and a magnitude label (e.g., “100 µV”)
  • The scale is computed from the lane’s amplitude range: user_scale_factor, data statistics, and any group scaling normalization
  • Scalebars provide absolute scale context that uniform tick marks cannot (since each lane has its own amplitude mapping)

3.3 Visibility Toggles

Add options to DataViewerStateData and the properties UI:

  • Toggle lane labels on/off
  • Toggle scalebars on/off
  • These should be serialized for workspace restore

3.4 Group Scaling Verification

Verify that scalebars update correctly when switching between individual and unified group scaling modes (GroupScalingState), and that labels remain aligned during Y pan/zoom.

3.5 Smart Label Positioning

Labels and scalebars must be viewport-aware (#248):

  • When panning in Y, labels for visible lanes must adjust accordingly
  • Labels for off-screen lanes should not be rendered
  • Labels should not overlap when lanes are very short (many channels or high Y zoom)

3.6 Verification

  • Each data lane can render an optional Y-axis scalebar indicating its magnitude/units.
  • Each data lane displays its assigned name/identifier (e.g., channel name or series key).
  • Scalebars and labels toggle on/off via properties UI.
  • Correct behavior when switching between individual and unified group scaling modes.
  • Labels remain aligned and visible during vertical panning.

Phase 4: CenteredTimeAxis Widget

Status: Not started. Issues: #223 Parallel with: Phase 3 (no dependency between X and Y axis work)

Goal: Extract the DataViewer’s temporal X-axis behavior into a reusable CenteredTimeAxisWidget in Plots/Common/, following the established four-layer axis widget pattern (StateData → State → Widget → WithRangeControls). The SpectrogramWidget (currently a stub with time-axis state defined but no axis widget) is the primary second consumer.

4.1 CenteredTimeAxis — New Horizontal Axis Variant

The DataViewer’s X-axis behavior is unique among the plot widgets: it is always centered on the global time position with zoom but no independent X panning. Neither the existing RelativeTimeAxis (event-relative, symmetric window) nor HorizontalAxis (arbitrary range with pan) match this pattern exactly.

A new CenteredTimeAxis variant should be added to Plots/Common/:

Plots/Common/CenteredTimeAxisWidget/
├── Core/
│   ├── CenteredTimeAxisStateData.hpp   # half_window (zoom level), serializable
│   └── CenteredTimeAxisState.hpp       # QObject with zoom math + signals
├── CenteredTimeAxisWidget.hpp          # Axis display (tick marks, labels) via QPainter
└── CenteredTimeAxisWithRangeControls.hpp  # Factory with zoom spinbox

State fields:

struct CenteredTimeAxisStateData {
    double time_start = 0.0;   ///< Visible window start in time units
    double time_end = 10000.0; ///< Visible window end in time units
};

The state uses time_start/time_end rather than half_window for consistency with the existing TimeSeriesViewState representation. The State class provides convenience accessors for halfWindow() and center() computed from these fields.

Key behavior differences from existing axes:

Aspect CenteredTimeAxis RelativeTimeAxis HorizontalAxis
Center Global time position (external) 0 (alignment event) User-adjustable
Pan None — follows time bar User-adjustable User-adjustable
Zoom Adjusts window width symmetrically around center Adjusts min/max symmetrically Adjusts x_min/x_max
Labels Absolute time values Relative offsets (±N) Arbitrary values

Signals: rangeChanged (user action), rangeUpdated (silent sync — matches bidirectional sync pattern used by all axis widgets)

The axis widget receives the current time position from an external source (the application’s global time bar emits timeChanged). On each time change, the parent widget recenters the window: time_start = current_time - half_window; time_end = current_time + half_window.

Sharing potential: This axis variant could also be useful for any future widget that needs a time-following view (e.g., a real-time signal monitor).

4.2 Zoom Math Extraction

The wheel-zoom math currently lives in DataViewer_Widget::wheelEvent and DataViewerState::adjustTimeWidth. This logic should be extracted into CenteredTimeAxisState as reusable methods:

  • applyWheelZoom(int angle_delta, ZoomScalingMode mode, Qt::KeyboardModifiers mods, int64_t total_frames)
  • Supports both Adaptive and Fixed scaling modes with Shift (fine) / Ctrl (coarse) modifiers
  • Optional clamp policy hooks
  • Pure logic that can be unit-tested without QWidget

This addresses the core goal of #223: making the zoom behavior reusable without duplicating the logic in each consumer widget.

4.3 DataViewer Migration

Migrate DataViewer_Widget to use CenteredTimeAxisWidget:

  1. Add CenteredTimeAxisState member to DataViewerState
  2. Place CenteredTimeAxisWidget below the OpenGL canvas in the QVBoxLayout
  3. Replace DataViewerState::setTimeWindow() / adjustTimeWindowWidth() with CenteredTimeAxisState methods
  4. Wire state sync: CenteredTimeAxisState → DataViewerState time window updates
  5. Update DataViewerStateData serialization to include CenteredTimeAxisStateData

Existing tests that assert time window changes after wheel events must remain green.

4.4 SpectrogramWidget Adoption

Adopt the same CenteredTimeAxisWidget for SpectrogramWidget’s time axis. The SpectrogramWidget currently defines SpectrogramViewState with x_min/x_max/x_zoom/x_pan but has no axis widget — it is essentially a stub GUI. This provides:

  • Tick marks and time labels via QPainter (matching other plot widgets)
  • Zoom controls via CenteredTimeAxisWithRangeControls
  • Consistent wheel-zoom behavior shared with DataViewer

4.5 Tests and Documentation

  • Port/add unit tests for zoom math (adaptive vs fixed scaling, modifiers) independent of QWidget
  • Update TimeRange.hpp / TimeSeriesViewState comments to point to the new module
  • Developer documentation entry for the shared temporal axis
  • Link from DataViewer and Spectrogram developer docs

4.6 Verification

  • DataViewer time-axis behavior unchanged (behavioral parity with pre-migration)
  • CenteredTimeAxisWidget renders absolute time tick marks and labels below the OpenGL canvas
  • SpectrogramWidget can use the same axis widget for its time dimension
  • Wheel zoom tests pass for both consumers
  • Workspace save/restore roundtrips CenteredTimeAxisStateData

Phase 5: Enhanced Event Glyph Options

Status: Not started. Events are currently rendered as simple ticks with configurable color and spacing but no glyph type selection.

Goal: Full control over event glyph appearance, using the shared CorePlotting::GlyphStyleData infrastructure that is now implemented and integrated into TemporalProjectionViewWidget, OnionSkinViewWidget, and EventPlotWidget.

5.1 Shared GlyphStyleData (Complete)

The shared glyph infrastructure is now available:

Component Location Status
CorePlotting::GlyphType enum CorePlotting/DataTypes/GlyphStyleData.hpp Complete
CorePlotting::GlyphStyleData struct CorePlotting/DataTypes/GlyphStyleData.hpp Complete
CorePlotting::toRenderableGlyphType() CorePlotting/DataTypes/GlyphStyleConversion.hpp Complete
CorePlotting::hexColorToVec4() CorePlotting/DataTypes/GlyphStyleConversion.hpp Complete
GlyphStyleState Plots/Common/GlyphStyleWidget/Core/GlyphStyleState.hpp Complete
GlyphStyleControls Plots/Common/GlyphStyleWidget/GlyphStyleControls.hpp Complete

Already integrated into: TemporalProjectionViewWidget, OnionSkinViewWidget, EventPlotWidget.

5.2 State and Options Update

Extend DigitalEventSeriesOptionsData to include glyph options using the shared struct:

#include "CorePlotting/DataTypes/GlyphStyleData.hpp"

struct DigitalEventSeriesOptionsData {
    rfl::Flatten<CorePlotting::SeriesStyle> style;
    
    // Event-specific settings (existing)
    EventPlottingModeData plotting_mode;
    float vertical_spacing;
    float event_height;
    float margin_factor;

    // Glyph options (using shared infrastructure)
    CorePlotting::GlyphStyleData glyph_style{
        CorePlotting::GlyphType::Tick, 5.0f, "#FFFFFF", 1.0f};
};

5.3 Properties Panel Controls

Embed GlyphStyleControls from Plots/Common/GlyphStyleWidget/ for per-event-key glyph customization, following the same pattern used by TemporalProjectionViewWidget and OnionSkinViewWidget:

#include "Plots/Common/GlyphStyleWidget/GlyphStyleControls.hpp"

auto * controls = new GlyphStyleControls(glyph_style_state, parent);

5.4 Scene Building Update

Update SceneBuildingHelpers::buildEventSeriesBatch() to use CorePlotting::toRenderableGlyphType() and CorePlotting::hexColorToVec4() from GlyphStyleConversion.hpp, replacing the hardcoded tick rendering.


Phase 6: Enhanced Interval Rendering

Status: Not started. Intervals are currently rendered as filled rectangles with configurable color and alpha but no border or pattern options.

Goal: Rich interval visualization with adjustable border, alpha, and hatching patterns.

6.1 IntervalRenderingOptions

Extend DigitalIntervalSeriesOptionsData:

struct DigitalIntervalSeriesOptionsData {
    rfl::Flatten<CorePlotting::SeriesStyle> style;
    
    // Existing
    bool extend_full_canvas = true;
    float margin_factor = 0.95f;
    float interval_height = 1.0f;

    // New border options
    float border_thickness = 1.0f;        ///< Border line width in pixels (0 = no border)
    std::string border_color = "#FFFFFF"; ///< Border color in hex
    float border_alpha = 1.0f;            ///< Border alpha (separate from fill alpha)

    // New fill options
    float fill_alpha = 0.5f;             ///< Fill alpha (replaces general alpha for fill)

    // New hatching options
    IntervalHatchPattern hatch_pattern = IntervalHatchPattern::None;
    float hatch_spacing = 8.0f;          ///< Spacing between hatch lines in pixels
    float hatch_angle = 45.0f;           ///< Angle of hatch lines in degrees
    std::string hatch_color = "#FFFFFF"; ///< Hatch line color
};

6.2 Hatching Patterns

enum class IntervalHatchPattern {
    None,              ///< Solid fill only (default)
    ForwardDiagonal,   ///< Lines from bottom-left to top-right
    BackwardDiagonal,  ///< Lines from top-left to bottom-right
    CrossHatch,        ///< Both diagonal directions
    Horizontal,        ///< Horizontal lines
    Vertical           ///< Vertical lines
};

Hatching can be implemented via:

  1. Fragment shader approach: A shader that discards fragments based on position modulo hatch spacing and angle. This is efficient but requires a new shader variant.
  2. Additional geometry approach: Generate hatch lines as RenderablePolyLineBatch clipped to the interval rectangle. Simpler but generates more geometry.

The fragment shader approach is preferred for performance with many intervals.

6.3 SVG Export Update

Update SVGExporter to support border and hatching in SVG output. SVG natively supports stroke, stroke-width, and <pattern> elements for hatching, making this straightforward.

6.4 Properties Panel Controls

Add to the interval section of DataViewerPropertiesWidget:

  • Fill alpha slider (0.0–1.0)
  • Border thickness spinbox
  • Border color button
  • Hatch pattern combo box
  • Hatch spacing spinbox (enabled when pattern ≠ None)

Phase 7: Analog Line Style Enhancements

Status: Partially implemented. Color, alpha, and line thickness exist in AnalogSeriesOptionsData via CorePlotting::SeriesStyle. Gap handling modes exist but are basic.

Goal: Additional line rendering options for publication-quality analog traces.

7.1 Planned Options

struct AnalogSeriesOptionsData {
    // Existing via SeriesStyle
    // hex_color, alpha, line_thickness, is_visible

    // Existing analog-specific
    // user_scale_factor, y_offset, gap_handling, enable_gap_detection, gap_threshold

    // New options
    LineStyle line_style = LineStyle::Solid;  ///< Solid, Dashed, Dotted
    bool show_data_points = false;            ///< Overlay point markers on the line
    PointGlyphType data_point_glyph = PointGlyphType::Circle;
    float data_point_size = 3.0f;
};

enum class LineStyle {
    Solid,    ///< Continuous line (default)
    Dashed,   ///< Dashed segments
    Dotted    ///< Dotted segments
};

7.2 Rendering

Dashed/dotted styles can be implemented via fragment shader stipple patterns or by breaking the polyline into segments during scene building. The shader approach is preferred for consistency with interval hatching (Phase 6).


Phase 8: Shared Component Extraction

Status: Not started. Design exploration — depends on Phases 1–6 establishing which patterns are truly shared.

Goal: Extract DataViewer-specific implementations that have general utility into shared locations, and adopt shared components that are currently duplicated.

8.1 Components to Extract from DataViewer

Component Current Location Target Location Also Used By
SeriesOptionsRegistry DataViewer_Widget/Core/ Plots/Common/ or CorePlotting/ Any multi-series plot widget
TransformComposers DataViewer_Widget/Rendering/ CorePlotting/Layout/ Any widget with stacked lane layout
AnalogVertexCache DataViewer_Widget/Rendering/ CorePlotting/ or PlottingOpenGL/ LinePlotWidget (dense time series)
DataViewerCoordinates DataViewer_Widget/Interaction/ Pattern generalizable via Plots/Common/ Layout+coordinate queries shared
SpikeSorterConfigLoader DataViewer_Widget/Core/ DataManager/ or CorePlotting/ Any widget displaying multi-channel data

8.2 Components to Adopt from Plots/Common/

Shared Component Current DataViewer Equivalent Adoption Notes
VerticalAxisState + VerticalAxisWidget Direct y_min/y_max in state Phase 2.1
CenteredTimeAxis (new) Direct time window in state Phase 4.1
PlotInteractionHelpers Custom zoom/pan in DataViewerInputHandler Adopt shared zoom/pan concepts

8.3 Shared Visual Options Infrastructure

The point glyph options infrastructure is now implemented and centralized:

CorePlotting/DataTypes/
├── GlyphStyleData.hpp         # COMPLETE: GlyphType enum + GlyphStyleData struct
├── GlyphStyleConversion.hpp   # COMPLETE: toRenderableGlyphType(), hexColorToVec4()
├── SeriesStyle.hpp            # Already exists: hex_color, alpha, line_thickness, is_visible
├── LineRenderingOptions.hpp   # Planned: line_style (solid/dashed/dotted), data_point overlay
├── IntervalRenderingOptions.hpp # Planned: border, fill_alpha, hatch pattern

Plots/Common/GlyphStyleWidget/
├── Core/GlyphStyleState.hpp   # COMPLETE: QObject wrapper with styleChanged/styleUpdated signals
├── GlyphStyleControls.hpp     # COMPLETE: Widget with shape combo, size spinbox, color button, alpha
├── CMakeLists.txt             # COMPLETE: Static library linking Qt6::Widgets + CorePlotting

Already integrated into: TemporalProjectionViewWidget, OnionSkinViewWidget, EventPlotWidget.

Remaining shared visual option structs to implement:


Phase 9: Directory Relocation

Status: Not started. Low priority — functional correctness is unaffected.

Goal: Move src/WhiskerToolbox/DataViewer_Widget/ to src/WhiskerToolbox/Plots/DataViewerWidget/ for consistency with other plot widgets.

9.1 Steps

  1. Move directory DataViewer_Widget/ → Plots/DataViewerWidget/
  2. Update CMakeLists.txt references in src/WhiskerToolbox/ and the widget’s own CMakeLists.txt
  3. Update #include paths across the codebase
  4. Update registration module type ID if it references the path
  5. Update test directory structure in tests/ if mirrored

This is a purely mechanical refactor with no behavioral change. It should be done after the major feature phases to avoid merge conflicts.


Implementation Priority

Completed Prerequisites

  • Developer Debug Panel — Diagnostic infrastructure providing real-time visibility into lane layout, scales, coordinate transforms, and viewport state. Complete — accelerates development of Phases 1–3.

Completed (Y-Axis Track)

  1. Phase 1: Layout foundation — lane sizing model with configurable margin_factor (#248 ✓, #227)
  2. Phase 1B: Rendering pipeline modernization — ViewStateData, scene dirty guard, shared interaction helpers for fast pan/zoom
  3. Phase 2: Y-axis navigation — pan/zoom, viewport culling, wheel modifiers (#227, #248 ✓)

Next Up

  1. Phase 3: Y-axis scalebars and lane labels (#247)

Parallel Track (X-Axis Extraction)

  1. Phase 4: CenteredTimeAxis widget — can proceed in parallel with Phase 3 (#223)

Following (Visual Enhancements)

  1. Phase 5: Enhanced event glyph options — shared infrastructure milestone
  2. Phase 6: Enhanced interval rendering — border, alpha, hatching
  3. Phase 7: Analog line style enhancements

Deferred

  1. Phase 8: Shared component extraction — house-cleaning across widgets
  2. Phase 9: Directory relocation — mechanical cleanup

Open Questions

  1. CenteredTimeAxis scope: Should the new axis variant handle the time-following logic itself (receiving timeChanged signals), or should it remain a pure zoom widget with the center set externally? The external approach is more flexible but requires the parent widget to manually update the center on every time change.

  2. Lane height policy: Should lane height be fixed across all series types, or should analog channels get taller lanes than event/interval channels by default? A configurable policy (uniform vs. type-weighted) could address both preferences.

  3. Viewport culling granularity: Should culling operate at the series level (skip entire series) or could it operate at the sample level (skip analog samples outside the viewport)? Sample-level culling is already partially handled by the AnalogVertexCache time range queries.

  4. Hatching renderer: Fragment shader stipple vs. additional geometry — the shader approach is more performant but adds shader complexity. Is the interval count high enough to warrant shader-based hatching, or would geometry-based hatching suffice?

  5. SeriesOptionsRegistry scope: If extracted to Plots/Common/, should it remain specific to the three DataViewer series types (analog, event, interval), or should it be generalized to support arbitrary option types via a compile-time type list?

  6. Y-axis wheel modifier chords: Which modifier combinations should be used for Y-axis operations? Alt+Scroll is a natural candidate but may conflict with Linux window manager defaults (Alt+click is often window move). Alternatives include right-click+scroll or other combinations.

Resolved Questions

  • Multi-lane VerticalAxisWidget design (was Q6): Decision — new separate widget. MultiLaneVerticalAxisWidget will be a standalone widget in Plots/Common/, not a subclass or extension of the existing VerticalAxisWidget. The single-range widget remains unchanged for consumers that need a uniform Y range.

  • CenteredTimeAxis state representation (was Q8): Decision — time_start/time_end. Consistent with TimeSeriesViewState. The State class provides halfWindow() and center() convenience accessors computed from time_start/time_end.


See Also