"""Coordinate conversion and isolated gaze buffering for screenshot POC.""" from collections import deque from dataclasses import dataclass from threading import Lock from typing import Optional @dataclass(frozen=True) class PageGeometry: viewport_width: float viewport_height: float page_width: float page_height: float screenshot_width: int screenshot_height: int device_pixel_ratio: float page_origin_x: float = 0 page_origin_y: float = 0 @property def scale_x(self) -> float: return self.screenshot_width / self.page_width @property def scale_y(self) -> float: return self.screenshot_height / self.page_height def map_point(self, gaze_x: float, gaze_y: float, scroll_x: float = 0, scroll_y: float = 0) -> tuple[float, float]: """Viewport CSS -> full-page CSS -> actual screenshot pixel coordinates.""" page_x = gaze_x + scroll_x - self.page_origin_x page_y = gaze_y + scroll_y - self.page_origin_y return page_x * self.scale_x, page_y * self.scale_y @dataclass(frozen=True) class GazeSample: timestamp: float viewport_x: float viewport_y: float scroll_x: float scroll_y: float viewport_width: float | None = None viewport_height: float | None = None device_pixel_ratio: float | None = None page_width: float | None = None page_height: float | None = None runtime_identity: str | None = None class GazeBuffer: """Opt-in side buffer. Never controls or blocks the source gaze producer.""" def __init__(self, every_n_frames: int = 3, movement_threshold: float = 25, max_samples: int | None = None): if every_n_frames < 1: raise ValueError("every_n_frames must be positive") self.every_n_frames = every_n_frames self.movement_threshold = movement_threshold self._samples = deque(maxlen=max_samples) self._previous: Optional[GazeSample] = None self._frame = 0 self._lock = Lock() def add(self, timestamp: float, x: float, y: float, scroll_x: float, scroll_y: float, *, viewport_width: float | None = None, viewport_height: float | None = None, device_pixel_ratio: float | None = None, page_width: float | None = None, page_height: float | None = None, runtime_identity: str | None = None) -> bool: sample = GazeSample(timestamp, x, y, scroll_x, scroll_y, viewport_width, viewport_height, device_pixel_ratio, page_width, page_height, runtime_identity) with self._lock: self._frame += 1 moved = self._previous is not None and ( (x - self._previous.viewport_x) ** 2 + (y - self._previous.viewport_y) ** 2 ) ** 0.5 > self.movement_threshold if self._frame % self.every_n_frames and not moved: return False self._samples.append(sample) self._previous = sample return True def snapshot(self) -> tuple[GazeSample, ...]: with self._lock: return tuple(self._samples) def drain(self) -> tuple[GazeSample, ...]: """Atomically transfer pending samples without interrupting producers.""" with self._lock: samples = tuple(self._samples) self._samples.clear() return samples