# Technical Specification: Playhead-Centering Zoom Algorithm

This document specifies the playhead drifting phenomenon during zoom operations and provides the architectural solutions, mathematical formulations, and source code prototypes required to lock the playback cursor as a static physical anchor point on the screen throughout timeline magnification updates.

---

## 1. Visual Symptom & Playhead Drifting Analysis

In standard digital audio workstation (DAW) graphical user interfaces, when an operator executes a mouse wheel zoom gesture (Zoom In/Out), the layout layout engine defaults to treating the leftmost physical pixel coordinate ($0$) of the timeline as the boundary axis for scaling.

### 1.1. Visual Failure Manifestations:

* **During Zoom In:** The red playback cursor (Playhead) positioned at a specific timestamp (e.g., $4.00\text{ s}$) is rapidly shifted toward the right perimeter of the viewport until it flies completely out of view.
* **During Zoom Out:** The playhead is abruptly snapped back toward the left perimeter of the screen viewport.
* **Consequence:** The sound engineer is forced to continuously adjust the horizontal scrollbar (`scrollLeft`) to find the playhead location, severely breaking the workflow during detail editing blocks.

### 1.2. Target Layout State (Playhead-Centering Zoom):

Throughout mouse-driven zoom updates at any scale:

* The playback cursor (Playhead) must act as a static physical anchor point locked to its exact pixel position relative to the visible browser window viewport.
* The multi-channel waveform graphics must stretch or compress symmetrically around the vertical axis of the playback cursor.

---

## 2. Mathematical Modeling for Playhead Anchoring

To guarantee that the on-screen placement of the cursor maps identically before and after a modification to the viewport magnification ratio, we establish a system of equations conserving the pixel coordinates of the playhead.

### 2.1. Operational Variables Mapping:

* $t_{\text{playhead}}$ (seconds): The instantaneous runtime clock position of the playhead (e.g., $4.00\text{ s}$).
* $Z_{\text{current}}$ (px/s): The initial timeline horizontal scaling zoom factor before resizing.
* $Z_{\text{new}}$ (px/s): The target timeline horizontal scaling zoom factor after resizing.
* $S_{\text{current}}$ (pixels): The current initial horizontal scroll offset (`scrollLeft`) of the timeline view.
* $S_{\text{new}}$ (pixels): The target adjusted horizontal scroll offset calculated to overwrite the container state.
* $X_{\text{viewport}}$ (pixels): The physical offset tracking the distance from the left edge of the screen viewport container to the playhead rendering path line.

### 2.2. Coordinate Conservation Formula

The absolute spatial coordinate of the playhead on the global arrangement timeline maps to:


$$X_{\text{absolute}} = t_{\text{playhead}} \times Z$$

The actual visible screen viewport placement of the cursor before executing the zoom factor modification evaluates to:


$$X_{\text{viewport}} = (t_{\text{playhead}} \times Z_{\text{current}}) - S_{\text{current}}$$

To lock the playhead directly to its coordinate position post-zoom ($Z_{\text{new}}$), the variable value $X_{\text{viewport}}$ must remain strictly unchanged:


$$X_{\text{viewport}} = (t_{\text{playhead}} \times Z_{\text{new}}) - S_{\text{new}}$$

Solving the equation systems to calculate the target adjusted scroll offset parameter $S_{\text{new}}$:


$$S_{\text{new}} = (t_{\text{playhead}} \times Z_{\text{new}}) - X_{\text{viewport}}$$

Substituting the initial definition statement of $X_{\text{viewport}}$ back into the calculation loop:


$$S_{\text{new}} = (t_{\text{playhead}} \times Z_{\text{new}}) - \left( (t_{\text{playhead}} \times Z_{\text{current}}) - S_{\text{current}} \right)$$

Compiling the final optimized mathematical reduction model:


$$S_{\text{new}} = S_{\text{current}} + t_{\text{playhead}} \times (Z_{\text{new}} - Z_{\text{current}})$$

*Physical Property Significance:* The calculated target scrollbar position equals the current scroll offset augmented by the absolute coordinate displacement of the playhead triggered by the variance across magnification scales.

---

## 3. Frontend Client Integration Blueprint (React / HTML5)

This mathematical alignment routine is tied directly into the primary mouse `wheel` event handler capturing timeline zoom interactions inside the main `index.html` structure:

```javascript
// Timeline wheel interaction handling segment capturing Playhead-anchored Zoom
const handleTimelineZoom = (e) => {
    // Restrict zoom loops exclusively to situations where Ctrl (or Cmd) modifiers are engaged
    if (!e.ctrlKey) return; 
    e.preventDefault();

    const timelineWrapper = timelineWrapperRef.current;
    if (!timelineWrapper) return;

    // 1. Capture absolute layout dimensions before updating state variables
    const scrollLeftCurrent = timelineWrapper.scrollLeft;
    const zoomCurrent = zoom; // Maps to Z_current
    const playheadTime = currentTime; // Maps to t_playhead

    // 2. Evaluate target zoom ratio step updates (Enforces fluid scaling profiles)
    const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1;
    let zoomNew = zoomCurrent * zoomFactor;

    // Rigidly clamp calculation bounds within safe operating limits
    const minZoomLimit = viewportWidth / maxDuration;
    const maxZoomLimit = 2000; // Mitigates graphical memory canvas texture crashes
    zoomNew = Math.max(minZoomLimit, Math.min(maxZoomLimit, zoomNew));

    // 3. Apply the conservation formula to calculate S_new scroll offsets
    const scrollLeftNew = scrollLeftCurrent + playheadTime * (zoomNew - zoomCurrent);

    // 4. Propagate updated values synchronously down to State queues and the DOM
    setZoom(zoomNew);
    
    // Defer scroll alignment to requestAnimationFrame to execute right as Canvas buffers redraw
    requestAnimationFrame(() => {
        timelineWrapper.scrollLeft = scrollLeftNew;
    });
};

```

---

## 4. Desktop Application Integration Manual (Python PyQt6 / PySide6)

When porting this layout algorithm to a containerized Python desktop context, capture the native `wheelEvent` tracking loop of the underlying `QGraphicsView` or `QScrollArea` layout wrapper:

```python
# [PYTHON PORTING BLUEPRINT] - Lock-step Playhead Zoom tracking over PyQt6 QGraphicsView
from PyQt6.QtWidgets import QGraphicsView, QScrollBar
from PyQt6.QtCore import Qt

class ProAudioTimelineView(QGraphicsView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.playhead_time_seconds = 4.0  # Maps to t_playhead parameter
        self.zoom_level = 100.0           # Maps to Z_current constant (pixels/second)
        
    def wheelEvent(self, event):
        # Inspect for active hardware keyboard ControlModifier keys
        if event.modifiers() & Qt.KeyboardModifier.ControlModifier:
            event.accept()
            
            # 1. Capture absolute workspace metrics before calculating adjustments
            h_scrollbar = self.horizontalScrollBar()
            scroll_current = h_scrollbar.value() # Maps to S_current
            zoom_current = self.zoom_level
            t_playhead = self.playhead_time_seconds
            
            # 2. Evaluate target scaling ratio increments
            angle_delta = event.angleDelta().y()
            zoom_factor = 1.1 if angle_delta > 0 else 0.9
            zoom_new = max(10.0, min(2000.0, zoom_current * zoom_factor))
            
            # 3. Apply the coordinate conservation model to isolate scroll_new offsets
            scroll_new = scroll_current + t_playhead * (zoom_new - zoom_current)
            
            # 4. Overwrite parameters and prompt vector updates on the QPainter surface
            self.zoom_level = zoom_new
            self.update_timeline_graphics() # Invokes the multi-channel waveform redraw routines
            
            # Commit updated scroll values immediately to lock playhead layout tracking
            h_scrollbar.setValue(int(scroll_new))
        else:
            # Drop down to default native vertical/horizontal scroll handling patterns
            super().wheelEvent(event)

```

---

## 5. UI Operational State Comparison

Based on the verified structural architecture of the system layout:

* **Baseline Initial State:** Audio waveform paths render at standard macro scaling bounds (evaluating approximately to a few hundred pixel columns per second of timeline data). The distinct vertical red playback cursor path line tracking the $4.00\text{ s}$ clock milestone renders centered in the visible workspace view.
* **Post Maximum Zoom-In State:** Symmetrical audio waveform data lines stretch horizontally to their maximum viewport scaling boundaries (exposing granular peak structures explicitly). By executing the conservation equations defined in Section 2.2, the horizontal scroll container shifts rightward, keeping the red cursor line locked to its absolute pixel column coordinate on the screen instead of letting it slip past the viewport limits.

This technical spec document establishes the supreme design token rules for compiling and verifying zooming workflows on the arrangement canvas.