Files
plotter/adapters/qt6/qt_plot_widget.hpp
T
Martino Ferrari ed3a8ce645 licence: MIT LICENSE and SPDX identifiers in every first-party file
The repository had no licence at all, so every source was all-rights-reserved
by default. Add the verbatim MIT text at LICENSE (Copyright (c) 2026 Martino
Ferrari) and a two-line SPDX header to each of the 113 first-party sources --
48 include/plot, 26 src, 10 adapters, 5 examples, 21 tests, 3 tools -- so the
grant travels with each file rather than relying on the root document alone.

Scripts keep their shebang on line 1; the SPDX lines follow it. Genuinely
vendored code is untouched: third_party/stb_truetype.h carries no header of
ours. src/render/embedded_mono_font.cpp is generated, so tools/fonts/gen_atlas.py
emit() now writes the two lines into its header comment and the file was
regenerated -- gen_atlas.py --check passes and the regeneration adds only those
comment lines to the previously committed file.

README's provenance section now states MIT and links LICENSE.

No code, test or public API change.
2026-09-28 22:13:40 +02:00

220 lines
10 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;
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 with
/// no vertical component is refused before it reaches the controller, because a
/// zero-notch zoom changes no range but still runs the range setters, which clear
/// auto scale: a horizontal scroll must not silently stop a live axis following.
///
/// ## 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;
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();
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_;
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