Files
plotter/adapters/qt6/qt_plot_widget.hpp
T
Martino Ferrari 38ef459897
CI / debug (tests + all adapters) (push) Canceled after 0s
CI / coverage (floor + measured table) (push) Canceled after 0s
CI / asan (AddressSanitizer) (push) Canceled after 0s
feat(plot)!: harden pipeline, XY series, dash/markers, touch, packaging
Breaking: Series::gather emits x relative to x0() and takes a GatherMode;
consumers reconstruct absolute x in f64 before mapping (series.hpp documents
the contract).

Bugs, each pinned by a fail-before regression test:
- render: f32 staging quantised epoch-time x into 128 px columns; every
  data-space draw now stages to_space(x) - to_space(origin) with the origin
  folded into the offset uniform in f64 (epoch/zero-origin twins rasterise
  identically)
- ticks: major test was ULP-fragile and blanked epoch axes; majors are an
  integer-index test and are never truncated by the minor cap
- gather: LOD envelope emitted buckets straddling [begin,end); ceil/floor
  bucket edges + raw lead/trail spans
- live follow: log x axes held a linear span and zoomed every frame; span and
  offset now live in axis space (plot + both figure link-group paths)
- input: a zero-notch wheel disarmed auto_scale on every axis; dy==0 pans x,
  factor == 1 / inf refused in wheel and drag zoom
- render: the single text flush painted legend names over the crosshair
  readout panel; two batches, under flushed before the panel
- data: NaN dropped from min/max unless it seeded the fold; non-finite
  samples are now excluded from every aggregate and from cached bounds

Robustness: viewport normalisation (no clamp UB), non-finite range refusal,
pyramid level cap at 57 (no shift/div UB through public gather), rounded ring
capacity documented + pre-sized, GL blend func and UNPACK_ALIGNMENT
save/restore, Renderer::release_gl() teardown, u64 buffer epochs, annotation
captions clamped, button-aware GLFW row capture, cached figure row rects (no
per-event layout), ruler-pair measurement refused, span-nonfinite guards in
axis_ends.

Features: XY series (sorted x, binary-search neighbours/snap, LOD over sample
index); StreamSeries::freeze(); ArraySeries::push(); per-trace dash and
markers (scatter at width 0) with auto or literal stride; GatherMode
Envelope/Nearest/Mean via bucket_sum/sumsq; Style::line_aa_px; per-glyph text
colour (readout values in trace colour); wheel-dx x pan; arrow-key pan;
Escape cancels a drag and restores captured ranges; modifier-masked box zoom
(Shift both, Ctrl x, Alt y); double-click reset via PointerEvent::time_s;
ImGui key repeat unified; pinch gestures on Qt and GTK; pixelDelta wheel path
and DevicePixelRatioChange handling; GNUInstallDirs, SOVERSION,
SameMinorVersion, generated plot/version.hpp, relocatable plot.pc, licence
install, FILES_MATCHING, GitHub Actions CI (debug/coverage/asan).

Suite 283 -> 350 cases, 0 failed; coverage 93.9% (3730/3971) over 24 files,
floor 80/90 held; ASAN preset suite green; all four demos run headless (the
GTK scripted-resize check needs a window manager and fails identically on the
parent commit); readme_main.cpp committed and compiles with the README
command; pkg-config and find_package consumption verified from a relocated
install prefix.
2026-09-30 17:32:06 +02:00

241 lines
12 KiB
C++

// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2026 Martino Ferrari
#pragma once
// The plot headers come first, and must. Qt's <QOpenGLWidget> reaches
// <QtGui/qopengl.h>, which on a desktop platform includes the system <GL/gl.h>;
// that header defines GL_TRUE, GL_COLOR_BUFFER_BIT, GL_TEXTURE_2D and the rest as
// preprocessor macros, and those are exactly the names plot/gl/api.hpp declares as
// enumerators -- a macro rewrite turns each definition into nonsense. Parsing
// api.hpp before the macros exist is what lets the two coexist (the GLFW adapter
// sidesteps the same clash with GLFW_INCLUDE_NONE, which Qt offers no equivalent
// of). A translation unit that uses this widget must keep the same order for
// anything it includes itself, and must not name a `plot::gl::GL_*` enumerator
// after a Qt header that reaches GL has been included: the macro rewrites that
// token wherever it appears, namespace and all.
#include <plot/core/rect.hpp>
#include <plot/core/status.hpp>
#include <plot/core/types.hpp>
#include <plot/input/controller.hpp>
#include <plot/math/vec2.hpp>
#include <plot/plot/plot.hpp>
#include <plot/render/renderer.hpp>
#include <qt6/qt_pointer.hpp>
#include <QOpenGLFunctions>
#include <QOpenGLWidget>
#include <functional>
#include <optional>
#include <utility>
class QKeyEvent;
class QMouseEvent;
class QPointF;
class QWheelEvent;
class QEvent;
class QGestureEvent;
class QPinchGesture;
namespace plot::qt {
/// Embeds a `Plot` in a Qt widget: a `QOpenGLWidget` whose framebuffer the plot
/// is rendered into, with Qt's own input events translated into `plot::input`
/// ones.
///
/// `QOpenGLWidget` renders into an FBO of its own, which it binds before calling
/// `paintGL()` -- exactly the "currently bound framebuffer" `Renderer` documents
/// it draws into. The widget therefore never creates a target of its own, and the
/// renderer's scissor-cleared viewport is the widget's whole rectangle. Nothing is
/// rendered to a texture or through a second pass: the plot is what Qt composes,
/// and the widget's other content (Qt draws none; a `QOpenGLWidget` is opaque)
/// would be drawn around it.
///
/// ## The surface format is a precondition, not a setting
///
/// This widget cannot ask for a context version: Qt hands a widget the
/// *application default* `QSurfaceFormat` at the moment its context is created,
/// and a context cannot be renegotiated afterwards. An embedding application must
/// therefore have done this before the widget exists:
///
/// QSurfaceFormat fmt;
/// fmt.setVersion(3, 3);
/// fmt.setProfile(QSurfaceFormat::CoreProfile);
/// fmt.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
/// fmt.setDepthBufferSize(0);
/// fmt.setStencilBufferSize(0);
/// QSurfaceFormat::setDefaultFormat(fmt);
/// QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL); // before QApplication
///
/// The last line matters as much as the rest: an ES or ANGLE backend has no 3.3
/// core profile to give, and this library's loader resolves desktop entry points.
/// `initializeGL()` reports the failure through `init_status()` rather than
/// asserting, but it cannot repair a format that was already decided.
///
/// ## The coordinate convention: device pixels, both sides
///
/// Two pixel spaces meet here, exactly as they do in the GLFW and ImGui adapters.
/// Qt reports widget geometry and mouse positions in **logical** pixels
/// (`width()`, `QMouseEvent::position()`), while the widget's framebuffer -- what
/// `Renderer::begin_frame()` takes and what every `Rect` in this library speaks --
/// is in **device** pixels, `devicePixelRatioF()` times as large on a scaled
/// display.
///
/// This widget converts everything into device pixels and keeps it there:
///
/// * the viewport handed to the plot is `round(width() * dpr)` x
/// `round(height() * dpr)` (rounded, not truncated, so the last column of the
/// FBO is inside the plot), and
/// * every pointer and wheel position is multiplied by the same
/// `devicePixelRatioF()` before it reaches the controller.
///
/// `device_viewport()` and `to_device()` are the only two places that mapping
/// exists, so the viewport and the input cannot disagree -- and they must not: a
/// mismatch renders correctly but pans by the wrong amount, which is invisible on
/// an unscaled display and wrong on every other one.
///
/// The *anchor* a move's delta is measured from is the one thing kept in logical
/// pixels: `devicePixelRatioF()` can change between two move events, and the delta
/// is then a logical difference scaled by the ratio in effect now, never the
/// difference of two device positions taken at different ratios (see
/// `PointerAnchor`). A drag that crosses onto a display with another scale factor
/// therefore pans by the distance the pointer moved, not by a cross-scale jump.
///
/// ## Input
///
/// Qt reports levels and edges directly (`QMouseEvent` press/release are edges,
/// `buttons()` is the state after the event), so the translation is a
/// reinterpretation rather than the edge synthesis the ImGui adapter needs.
/// Wheel input is the one unit conversion: Qt's `angleDelta()` is in eighths of a
/// degree, 120 to a notch, while `Controller::on_wheel()` takes notches, positive
/// = zoom in -- which is Qt's positive `angleDelta().y()` too. A wheel event whose
/// deltas both vanish -- no angle and no pixels -- is refused before it reaches the
/// controller, because a zero-notch, zero-pan event changes nothing and must not
/// clear auto scale; anything with a vertical *or* horizontal component is
/// forwarded, and the controller decides what each does (zoom on `dy`, pan on
/// `dx`). The widget is also a pinch source: `Qt::PinchGesture` is grabbed in the
/// constructor and folded into `input::GestureEvent`s by `PinchTracker`
/// (`qt_pointer.hpp`), so a two-finger zoom-about-focal-point and a two-finger pan
/// reach the controller like the equivalent wheel + drag pair would.
///
/// ## Threading
///
/// Qt widgets live on the GUI thread, and so does everything here: `initializeGL`,
/// `paintGL` and the event handlers all run there, which is the thread that owns
/// the context. A host that feeds the plot from a producer thread acquires its
/// data on this thread (see the frame callback).
class PlotWidget : public QOpenGLWidget, protected QOpenGLFunctions {
Q_OBJECT
public:
/// One frame of host code, run by `paintGL()` after the viewport is set and
/// before the frame is staged. It is where data is refreshed -- acquiring a
/// `data::StreamSeries`, re-fitting a live axis, moving cursors -- and `dt` is
/// the wall time since the previous call, in seconds. Optional; a widget with
/// no callback just re-draws the plot as it stands.
using FrameFn = std::function<void(Plot&, f64)>;
/// Renders and drives `plot`, which must outlive this widget.
explicit PlotWidget(Plot& plot, QWidget* parent = nullptr);
~PlotWidget() override;
PlotWidget(const PlotWidget&) = delete;
PlotWidget& operator=(const PlotWidget&) = delete;
void set_frame_callback(FrameFn frame) { frame_ = std::move(frame); }
/// The plot this widget renders. Valid for the widget's whole life.
Plot& plot() noexcept { return *plot_; }
const Plot& plot() const noexcept { return *plot_; }
/// The controller the widget feeds, bound to `plot()`.
input::Controller& controller() noexcept { return controller_; }
const input::Controller& controller() const noexcept { return controller_; }
/// The renderer, or null until a successful `initializeGL()`. Valid from the
/// corresponding `paintGL()` onwards, and after the widget's context exists.
Renderer* renderer() noexcept { return renderer_ ? &*renderer_ : nullptr; }
const Renderer* renderer() const noexcept { return renderer_ ? &*renderer_ : nullptr; }
/// What `initializeGL()` made of the context: `Ok`, or the failure that left
/// the widget drawing nothing. A `QOpenGLWidget` virtual cannot return a
/// `Status`, and a widget must not throw across Qt's callback, so the outcome
/// is recorded here instead.
const Status& init_status() const noexcept { return init_status_; }
/// Frames actually staged, and the frame time of the last one (ms). The mean is
/// an exponential moving average seeded by the first frame, of the same
/// render-only span: the frame callback, `begin_frame`, `draw` and `end_frame`.
u64 frames_painted() const noexcept { return frames_; }
f32 last_frame_ms() const noexcept { return last_frame_ms_; }
f32 mean_frame_ms() const noexcept { return mean_frame_ms_; }
/// The region the last frame was drawn into, in device pixels -- the rect
/// `begin_frame()` was handed. Zero-sized before the first frame.
Rect last_device_viewport() const noexcept { return last_viewport_; }
protected:
void initializeGL() override;
void resizeGL(int w, int h) override;
void paintGL() override;
/// The one virtual that sees what no dedicated handler does: the device pixel
/// ratio change (`QEvent::DevicePixelRatioChange`) and the grabbed pinch
/// (`QEvent::Gesture`). Both refresh or feed the controller before the next
/// paint, so a gesture arriving between the change and the frame maps against
/// the geometry the ratio now implies.
bool event(QEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override;
void mouseReleaseEvent(QMouseEvent* event) override;
/// Qt reports the second press of a double click as this event and not as a
/// press, so without it a drag that began with a double click would have no
/// press to start from. Forwarded as one.
void mouseDoubleClickEvent(QMouseEvent* event) override;
void wheelEvent(QWheelEvent* event) override;
void keyPressEvent(QKeyEvent* event) override;
private:
/// The widget's rectangle in device pixels: the plot's viewport, and the size
/// of the framebuffer the frame is drawn into.
Rect device_viewport() const noexcept;
/// A Qt position (logical widget pixels) in device pixels. The one place a
/// pointer position is mapped, so everything the controller sees is scaled by
/// the same factor the viewport is -- a move's *delta*, whose ratio can change
/// between two events, is scaled by `PointerAnchor` instead.
Vec2 to_device(const QPointF& p) const noexcept;
/// Translates one mouse event and hands it to the controller. `pressed` and
/// `released` are the transitions Qt reports on the event itself.
void forward_pointer(QMouseEvent* event, bool pressed, bool released);
/// Sets the plot's viewport to the current device rect (through the controller,
/// which refreshes the layout with it).
void refresh_viewport();
/// Folds one pinch update into a `GestureEvent` through `PinchTracker` and hands
/// it to the controller. `event` is accepted for the pinch gesture, so Qt does
/// not offer it to parents too.
void forward_pinch(QPinchGesture* gesture, QGestureEvent* event);
Plot* plot_ = nullptr; ///< declared first: the controller is built over it
input::Controller controller_;
std::optional<Renderer> renderer_;
FrameFn frame_;
Status init_status_;
/// The position a move's delta is measured from, in **logical** pixels: Qt
/// reports no delta of its own, and the ratio can change between two events
/// (see `PointerAnchor` for why the anchor must not be device pixels).
PointerAnchor anchor_;
/// The pinch gesture's folding state (see `PinchTracker`): one per widget, alive
/// between `Qt::GestureStarted` and `Finished`/`Canceled`.
PinchTracker pinch_;
u64 frames_ = 0;
f32 last_frame_ms_ = 0.0f;
f32 mean_frame_ms_ = 0.0f;
/// Wall clock at the last `paintGL()` start, or negative before the first one.
f64 last_paint_s_ = -1.0;
Rect last_viewport_{};
};
} // namespace plot::qt