diff --git a/slsDetectorGui/demo/plot_demo.cpp b/slsDetectorGui/demo/plot_demo.cpp index 019750f70..896b54568 100644 --- a/slsDetectorGui/demo/plot_demo.cpp +++ b/slsDetectorGui/demo/plot_demo.cpp @@ -1,486 +1,135 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2026 Contributors to the SLS Detector Package + +// Shows the plots of the gui with synthetic frames, no detector needed. // -// Standalone offscreen demo / benchmark for the plotting stack. -// -// It builds a synthetic 1024x512 float frame (sin(x/40)+cos(y/30) plus a moving -// hotspot) at ~20 Hz, feeds it to SlsQtFastImage, keeps SlsQtScalePanel in sync -// and shows a 1D plot with three live curves below it. It prints the -// measured timer rate plus the unthrottled render throughput. --png saves a -// screenshot; --shot prepares one of the acceptance views: -// -// 2d-default 2D image + scale panel -// 2d-zoom-roi 64x30 pixel zoom with gate/overlay/receiver ROIs -// scale-drag mid-drag ScaleHisto strip (frozen bars, dashed preview) -// 1d-log the real SlsQt1DPlot with three curves on a log y axis -// gain the real SlsQt2DPlot gain-mode widget (Gain4, 0..3) -// -// QT_QPA_PLATFORM=offscreen ./bin/plot_demo --frames 120 -// QT_QPA_PLATFORM=offscreen ./bin/plot_demo --shot 1d-log \ -// --png ../artifacts/1d-log.png -// -// CLI: --frames N (0 = run until closed), --png PATH, --shot MODE. +// plot_demo until the window is closed +// plot_demo --zoom 500,250,12,8 start with these pixels x,y,width,height +// QT_QPA_PLATFORM=offscreen plot_demo --png demo.png #include "SlsQt1DPlot.h" #include "SlsQt2DPlot.h" -#include "SlsQtFastImage.h" -#include "SlsQtPlotCommon.h" -#include "SlsQtScalePanel.h" #include -#include #include -#include -#include -#include -#include #include #include -#include -#include #include -#include +#include #include -using sls::SlsQt1DPlot; -using sls::SlsQt2DPlot; -using sls::SlsQtFastImage; -using sls::SlsQtH1D; -using sls::SlsQtScalePanel; - namespace { constexpr int kNx = 1024; constexpr int kNy = 512; -constexpr int kTimerMs = 50; // ~20 Hz -constexpr int kShotFrames = 8; -constexpr int kCurveBins = 256; +constexpr int kFrameIntervalMs = 50; -void sendMouse(QWidget &w, QEvent::Type type, const QPointF &pos, - Qt::MouseButton button, Qt::MouseButtons buttons) { - QMouseEvent e(type, pos, QPointF(w.mapToGlobal(pos.toPoint())), button, - buttons, Qt::NoModifier); - QCoreApplication::sendEvent(&w, &e); -} +class PlotDemo : public QWidget { + public: + PlotDemo() { + m_plot2d = new sls::SlsQt2DPlot(this); + m_plot2d->SetTitle(QStringLiteral("Synthetic frames")); + m_plot2d->SetXTitle(QStringLiteral("x [pixel]")); + m_plot2d->SetYTitle(QStringLiteral("y [pixel]")); + m_plot2d->SetZTitle(QStringLiteral("counts")); -struct Options { - int frames = 120; - QString png; - QString shot; + m_plot1d = new sls::SlsQt1DPlot(this); + m_plot1d->SetTitle(QStringLiteral("Mean of the columns")); + m_plot1d->SetXTitle(QStringLiteral("x [pixel]")); + m_plot1d->SetYTitle(QStringLiteral("counts")); + m_columns = + std::make_unique(QString(), kNx, -0.5, kNx - 0.5); + m_columns->setLegendVisible(false); + m_columns->Attach(m_plot1d); + + auto *layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(m_plot2d, 2); + layout->addWidget(m_plot1d, 1); + nextFrame(); + } + + sls::SlsQt2DPlot *plot2d() const { return m_plot2d; } + + // Counts like from a photon counting detector, with a spot moving around + void nextFrame() { + m_phase += 0.08; + const double spotX = kNx / 2 + 220 * std::sin(m_phase); + const double spotY = kNy / 2 + 120 * std::cos(0.7 * m_phase); + std::vector frame(static_cast(kNx) * kNy); + std::vector columns(kNx, 0.0); + for (int y = 0; y < kNy; ++y) { + for (int x = 0; x < kNx; ++x) { + const double waves = + 2 + std::sin(x / 40.0) + std::cos(y / 30.0); + const double r2 = + std::pow(x - spotX, 2) + std::pow(y - spotY, 2); + const double counts = std::floor( + 40 * waves + 300 * std::exp(-r2 / (2 * 70.0 * 70.0))); + frame[static_cast(y) * kNx + x] = counts; + columns[x] += counts / kNy; + } + } + m_plot2d->SetData(kNx, -0.5, kNx - 0.5, kNy, -0.5, kNy - 0.5, + frame.data()); + m_columns->SetData(kNx, -0.5, kNx - 0.5, columns.data()); + m_plot1d->Update(); + } + + private: + sls::SlsQt2DPlot *m_plot2d; + sls::SlsQt1DPlot *m_plot1d; + std::unique_ptr m_columns; + double m_phase = 0.0; }; } // namespace -class PlotDemo : public QWidget { - public: - explicit PlotDemo(const Options &opt) : QWidget(nullptr), m_opt(opt) { - m_frame.resize(size_t(kNx) * size_t(kNy)); - m_frameD.resize(size_t(kNx) * size_t(kNy)); - m_c1.resize(kCurveBins); - m_c2.resize(kCurveBins); - m_c3.resize(kCurveBins); - buildUi(); - } - - ~PlotDemo() override { - // The curves must go before the QWidget base class destroys the plot - // they are attached to. - for (SlsQtH1D *c : m_curves) - delete c; - m_curves.clear(); - } - - int run() { - resize(1100, 900); - setWindowTitle(QStringLiteral("slsDetectorPlotting Qt6 demo")); - show(); - - m_targetFrames = m_opt.frames; - connect(&m_timer, &QTimer::timeout, this, [this] { tick(); }); - connect(qApp, &QCoreApplication::aboutToQuit, this, - [this] { printStats(); }); - m_timer.start(kTimerMs); - return QApplication::exec(); - } - - private: - void buildUi() { - auto *root = new QVBoxLayout(this); - root->setContentsMargins(0, 0, 0, 0); - root->setSpacing(0); - - // 2D image + scale panel (the acceptance demo path). - m_2dRow = new QWidget(this); - auto *row = new QVBoxLayout(m_2dRow); - row->setContentsMargins(0, 0, 0, 0); - row->setSpacing(0); - m_view = new SlsQtFastImage(m_2dRow); - m_panel = new SlsQtScalePanel(m_view, m_2dRow); - row->addWidget(m_view, 1); - row->addWidget(m_panel); - - // 1D plot with three curves (the real widget). - m_1d = new SlsQt1DPlot(this); - m_1d->SetTitle(QStringLiteral("1D histograms")); - m_1d->SetXTitle(QStringLiteral("bin")); - m_1d->SetYTitle(QStringLiteral("counts")); - for (int i = 0; i < 3; i++) { - auto *h = new SlsQtH1D(QStringLiteral("curve %1").arg(i + 1), - kCurveBins, 0.0, double(kCurveBins), - nullptr); - h->Attach(m_1d); - h->SetLineColor(i); - h->SetLineWidth(2); - m_curves.push_back(h); - } - - // Real SlsQt2DPlot used for the 2D acceptance screenshots (title, - // axis titles, z-axis caption, scale panel): hidden in the live demo. - m_2d = new SlsQt2DPlot(this); - m_2d->hide(); - - // Real SlsQt2DPlot gain-mode widget (hidden until --shot gain). - m_gain = new SlsQt2DPlot(this, true); - m_gain->hide(); - m_gainData.resize(size_t(kNx) * size_t(kNy)); - - root->addWidget(m_2dRow, 2); - root->addWidget(m_1d, 1); - root->addWidget(m_2d, 2); - root->addWidget(m_gain, 2); - } - - void tick() { - const bool first = !m_started; - if (first) { - // Benchmark while the 2D view is visible and laid out. - (void)benchmark(); - m_started = true; - setupShot(); - } - m_phase += 0.08; - buildFrame(); - if (m_2dRow->isVisible()) { - m_view->setImageCopy(m_frame.data(), kNx, kNy); - m_view->repaint(); // compose + paint, like the GUI acquisition loop - } - if (m_2d->isVisible()) { - // Real SlsQt2DPlot path: the GUI feeds double frames. - for (size_t i = 0; i < m_frame.size(); i++) - m_frameD[i] = double(m_frame[i]); - m_2d->SetData(kNx, -0.5, kNx - 0.5, kNy, -0.5, kNy - 0.5, - m_frameD.data()); - m_2d->imageView()->repaint(); // sync compose: histogram/panel too - } - if (m_1d->isVisible()) - update1d(); - if (first) { - applyShotGeometry(); - m_clock.start(); - m_frames = 0; // measure the timer rate from here on - } - m_frames++; - - if (m_opt.shot == QLatin1String("scale-drag") && !m_shotPrepared && - m_frames >= 4) { - startStripDrag(); - m_shotPrepared = true; - } - if (m_targetFrames > 0 && m_frames >= m_targetFrames) - finish(); - } - - // One-shot unthrottled measurement: copy + compose + paint per frame. - double benchmark() { - const int frames = 40; - QElapsedTimer t; - t.start(); - for (int i = 0; i < frames; i++) { - m_frame[0] = float(i); - m_view->setImageCopy(m_frame.data(), kNx, kNy); - m_view->repaint(); - } - const double seconds = double(t.nsecsElapsed()) / 1e9; - const double fps = double(frames) / seconds; - std::printf( - "plot_demo: render throughput %.1f fps (%.2f ms/frame, %d frames, " - "%dx%d)\n", - fps, 1000.0 * seconds / double(frames), frames, kNx, kNy); - std::fflush(stdout); - return fps; - } - - void setupShot() { - m_view->setTitle(QStringLiteral("sin(x/40) + cos(y/30) | 1024x512")); - m_view->setXAxisTitle(QStringLiteral("x [px]")); - m_view->setYAxisTitle(QStringLiteral("y [px]")); - m_view->setColorRange(-2.0, 2.0); - - if (m_opt.shot == QLatin1String("1d-log")) { - m_2dRow->hide(); - m_gain->hide(); - m_1d->show(); - resize(1100, 640); - m_1d->SetTitle(QStringLiteral("1D histograms | log y")); - m_1d->SetLogY(true); - m_1d->SetLogX(false); - } else if (m_opt.shot == QLatin1String("gain")) { - m_2dRow->hide(); - m_1d->hide(); - m_gain->show(); - resize(kNx, kNy); - } else if (m_opt.shot == QLatin1String("2d-default") || - m_opt.shot == QLatin1String("2d-zoom-roi") || - m_opt.shot == QLatin1String("scale-drag")) { - // Real SlsQt2DPlot: canvas + scale panel + z-axis caption row. - m_2dRow->hide(); - m_1d->hide(); - m_gain->hide(); - m_2d->show(); - resize(1100, 660); - m_2d->SetTitle( - QStringLiteral("sin(x/40) + cos(y/30) | 1024x512")); - m_2d->SetXTitle(QStringLiteral("x [px]")); - m_2d->SetYTitle(QStringLiteral("y [px]")); - m_2d->SetZTitle(QStringLiteral("z (colour scale)")); - } else { - m_2dRow->show(); - m_1d->hide(); - m_2d->hide(); - m_gain->hide(); - resize(1100, 640); - if (!m_opt.shot.isEmpty()) { - std::fprintf(stderr, "plot_demo: unknown --shot '%s'\n", - qPrintable(m_opt.shot)); - } - } - } - - // Applied after the first frame: setImageCopy() of a new image resets the - // viewport, so zoom/ROI/gain data must be set once an image exists. - void applyShotGeometry() { - if (m_opt.shot == QLatin1String("2d-zoom-roi")) { - // Data coords of SlsQt2DPlot are bin centres: -0.5..nx-0.5 with - // unit bins, i.e. image pixel edges 400..460 / 200..230. - m_2d->SetZoom(QRectF(399.5, 199.5, 60.0, 30.0)); - m_2d->EnableRoiBoxes({slsDetectorDefs::ROI(410, 429, 210, 224), - slsDetectorDefs::ROI(446, 451, 218, 225)}); - m_2d->imageView()->repaint(); - } else if (m_opt.shot == QLatin1String("gain")) { - // Real gain widget: 0..3 gain bits in four quadrants plus a - // gain-switching block (as on a Jungfrau chip). - for (int y = 0; y < kNy; y++) { - for (int x = 0; x < kNx; x++) { - int g = (x < kNx / 2 ? 0 : 1) + (y < kNy / 2 ? 2 : 0); - if (x > 3 * kNx / 4 && y > 7 * kNy / 8) - g = (g + 1) % 4; - m_gainData[size_t(y) * kNx + x] = double(g); - } - } - m_gain->SetData(kNx, -0.5, kNx - 0.5, kNy, -0.5, kNy - 0.5, - m_gainData.data()); - m_gain->UnZoom(); - m_gain->Update(); - } - } - - void update1d() { - const double centre1 = - kCurveBins / 2.0 + 40.0 * std::sin(m_phase * 0.6); - const double centre2 = - kCurveBins / 2.0 - 40.0 * std::sin(m_phase * 0.6); - for (int i = 0; i < kCurveBins; i++) { - const double x = i; - m_c1[size_t(i)] = - 800.0 * std::exp(-std::pow(x - centre1, 2.0) / (2 * 18 * 18)) + - 5.0; - m_c2[size_t(i)] = - 500.0 * std::exp(-std::pow(x - centre2, 2.0) / (2 * 28 * 28)) + - 15.0; - m_c3[size_t(i)] = 20.0 + 8.0 * std::sin(x / 7.0 + m_phase) + 1.0; - } - m_curves[0]->SetData(kCurveBins, 0.0, double(kCurveBins), m_c1.data()); - m_curves[1]->SetData(kCurveBins, 0.0, double(kCurveBins), m_c2.data()); - m_curves[2]->SetData(kCurveBins, 0.0, double(kCurveBins), m_c3.data()); - m_1d->Update(); - } - - void buildFrame() { - const double cx = 512.0 + 220.0 * std::sin(m_phase); - const double cy = 256.0 + 120.0 * std::cos(m_phase * 0.7); - for (int y = 0; y < kNy; y++) { - for (int x = 0; x < kNx; x++) { - const double base = std::sin(x / 40.0) + std::cos(y / 30.0); - const double dx = x - cx, dy = y - cy; - const double hotspot = - 1.2 * std::exp(-(dx * dx + dy * dy) / (2.0 * 70.0 * 70.0)); - m_frame[size_t(y) * kNx + x] = float(base + hotspot); - } - } - } - - SlsQtScalePanel *scalePanel() const { - return m_2d && m_2d->isVisible() ? m_2d->scalePanel() : m_panel; - } - - void startStripDrag() { - SlsQtScalePanel *panel = scalePanel(); - if (!panel) - return; - auto *strip = panel->histogramWidget(); - if (!strip || strip->width() <= 0) - return; - const double w = strip->width(); - const QPointF press(w * 0.25, strip->height() * 0.5); - const QPointF move(w * 0.42, strip->height() * 0.5); - sendMouse(*strip, QEvent::MouseButtonPress, press, Qt::LeftButton, - Qt::LeftButton); - sendMouse(*strip, QEvent::MouseMove, move, Qt::NoButton, - Qt::LeftButton); - m_stripDragging = strip->isDragging(); - std::printf("plot_demo: ScaleHisto drag prepared (dragging=%d, " - "previewX=%d)\n", - m_stripDragging ? 1 : 0, strip->previewX()); - } - - void endStripDrag() { - if (!m_stripDragging) - return; - SlsQtScalePanel *panel = scalePanel(); - if (!panel) - return; - auto *strip = panel->histogramWidget(); - if (!strip) - return; - const double w = strip->width(); - sendMouse(*strip, QEvent::MouseButtonRelease, - QPointF(w * 0.42, strip->height() * 0.5), Qt::LeftButton, - Qt::NoButton); - m_stripDragging = false; - } - - void finish() { - // The drag screenshot must be taken before the release applies it. - if (!m_opt.png.isEmpty()) - savePng(); - endStripDrag(); - printStats(); - m_timer.stop(); - QApplication::quit(); - } - - void savePng() { - const QPixmap shot = grab(); - if (shot.isNull()) { - std::fprintf(stderr, "plot_demo: could not grab the window\n"); - return; - } - if (!shot.save(m_opt.png, "PNG")) { - std::fprintf(stderr, "plot_demo: failed to save %s\n", - qPrintable(m_opt.png)); - return; - } - std::printf("plot_demo: saved %s (%dx%d)\n", qPrintable(m_opt.png), - shot.width(), shot.height()); - std::fflush(stdout); - m_pngSaved = true; - } - - void printStats() { - if (m_statsPrinted) - return; - m_statsPrinted = true; - if (!m_started || m_frames <= 0) { - std::printf("plot_demo: no frames rendered\n"); - return; - } - // m_clock starts after the first frame, so (m_frames - 1) intervals - // were measured. - const double seconds = double(m_clock.nsecsElapsed()) / 1e9; - const double fps = - (m_frames > 1 && seconds > 0.0) ? double(m_frames - 1) / seconds : 0.0; - std::printf("plot_demo: %d timer frames, %.3f s between first/last = " - "%.1f fps (QTimer target %d ms)\n", - m_frames, seconds, fps, kTimerMs); - std::fflush(stdout); - } - - Options m_opt; - QWidget *m_2dRow = nullptr; - SlsQtFastImage *m_view = nullptr; - SlsQtScalePanel *m_panel = nullptr; - SlsQt1DPlot *m_1d = nullptr; - SlsQt2DPlot *m_2d = nullptr; - SlsQt2DPlot *m_gain = nullptr; - QTimer m_timer; - - QElapsedTimer m_clock; - std::vector m_frame; - std::vector m_frameD; - std::vector m_gainData; - std::vector m_c1, m_c2, m_c3; - std::vector m_curves; - double m_phase = 0.0; - int m_frames = 0; - int m_targetFrames = 120; - bool m_started = false; - bool m_shotPrepared = false; - bool m_stripDragging = false; - bool m_statsPrinted = false; - bool m_pngSaved = false; -}; - int main(int argc, char **argv) { QApplication app(argc, argv); - QCoreApplication::setApplicationName(QStringLiteral("plot_demo")); - QCoreApplication::setApplicationVersion(QStringLiteral("1.0")); - QCommandLineParser parser; parser.setApplicationDescription( - QStringLiteral("Plotting stack demo / offline benchmark")); + QStringLiteral("Shows the plots of the gui with synthetic frames.")); parser.addHelpOption(); - parser.addVersionOption(); - const QCommandLineOption framesOpt( - QStringList{QStringLiteral("f"), QStringLiteral("frames")}, - QStringLiteral("number of timer frames before exiting (0 = run until " - "the window is closed)"), - QStringLiteral("N"), QStringLiteral("120")); - const QCommandLineOption pngOpt( - QStringLiteral("png"), - QStringLiteral("save a screenshot to PATH when the run finishes"), - QStringLiteral("PATH")); - const QCommandLineOption shotOpt( - QStringLiteral("shot"), - QStringLiteral("prepare an acceptance view: 2d-default, 2d-zoom-roi, " - "scale-drag, 1d-log, gain"), - QStringLiteral("MODE")); - parser.addOption(framesOpt); - parser.addOption(pngOpt); - parser.addOption(shotOpt); + parser.addOptions({ + {QStringLiteral("zoom"), + QStringLiteral("Start with these pixels of the image."), + QStringLiteral("x,y,width,height")}, + {QStringLiteral("png"), + QStringLiteral("Save the window to and exit."), + QStringLiteral("file")}, + {QStringLiteral("frames"), + QStringLiteral("Exit after frames, 5 with --png."), + QStringLiteral("n")}, + }); parser.process(app); + const QString png = parser.value(QStringLiteral("png")); + int framesLeft = parser.value(QStringLiteral("frames")).toInt(); + if (framesLeft <= 0 && !png.isEmpty()) + framesLeft = 5; - Options opt; - opt.frames = parser.value(framesOpt).toInt(); - opt.png = parser.value(pngOpt); - opt.shot = parser.value(shotOpt); - if (opt.frames < 0) - opt.frames = 0; - // A shot needs a few frames for the histogram/panel to settle. - if (!opt.shot.isEmpty() && opt.frames > 0 && !parser.isSet(framesOpt)) - opt.frames = kShotFrames; - if (opt.frames == 0 && !opt.png.isEmpty()) { - std::fprintf(stderr, - "plot_demo: --png needs a finite --frames value\n"); - return 2; + PlotDemo demo; + demo.resize(1100, 900); + demo.show(); + const QStringList zoom = parser.value(QStringLiteral("zoom")) + .split(QLatin1Char(','), Qt::SkipEmptyParts); + if (zoom.size() == 4) { + // pixel ix covers ix - 0.5 to ix + 0.5 on the axes + demo.plot2d()->SetZoom(QRectF(zoom[0].toDouble() - 0.5, + zoom[1].toDouble() - 0.5, + zoom[2].toDouble(), zoom[3].toDouble())); } - std::printf("plot_demo: Qt %s, platform '%s', frame %dx%d\n", - qVersion(), qPrintable(QGuiApplication::platformName()), kNx, - kNy); - std::fflush(stdout); - - PlotDemo demo(opt); - const int rc = demo.run(); - return rc; + QTimer timer; + QObject::connect(&timer, &QTimer::timeout, &demo, [&] { + demo.nextFrame(); + if (framesLeft > 0 && --framesLeft == 0) { + if (!png.isEmpty()) + demo.grab().save(png); + app.quit(); + } + }); + timer.start(kFrameIntervalMs); + return app.exec(); } diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h index be5b9e22a..3d50e9a63 100644 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h @@ -3,13 +3,10 @@ #ifndef SLSQT1DPLOT_H #define SLSQT1DPLOT_H -// Replacement for the qwt based 1D plotting layer of slsDetectorGui. -// -// SlsQt1DPlot is a plain QWidget that paints its own frame, ticks, grid, -// clipped curves, legend, ROI boxes and tracker and implements the zoom / pan -// interaction (rubber-band zoom, wheel zoom, middle-drag pan, right click zoom -// out one level, Ctrl+right reset). SlsQtH1D is a plain data container plus -// curve description (no QwtPlotCurve base). No qwt, ROOT or OpenGL. +// SlsQt1DPlot paints its own frame, ticks, grid, curves, legend, ROI boxes +// and tracker and implements the zoom / pan interaction (rubber-band zoom, +// wheel zoom, middle-drag pan, right click zoom out one level, Ctrl+right +// reset). SlsQtH1D holds the data and the look of one curve. #include "SlsQtPlotCommon.h" #include "sls/sls_detector_defs.h" @@ -28,9 +25,7 @@ namespace sls { class SlsQt1DPlot; -// One 1D histogram/curve. The public data API is the one the old -// QwtPlotCurve derived class exposed, so qDrawPlot/qCloneWidget do not need -// changes apart from the legend attribute (now setLegendVisible()). +// One 1D histogram/curve. class SlsQtH1D { public: SlsQtH1D(QString title, int n, double xmin, double xmax, @@ -47,8 +42,8 @@ class SlsQtH1D { void setStyleLinesorDots(bool isLines); void setSymbolMarkers(bool isMarker); - // Replaces the old QwtPlotItem::Legend attribute: while false the plot - // draws no legend entry for this curve (used by the gain plots). + // While false the plot draws no legend entry for this curve (used by the + // gain plots). void setLegendVisible(bool visible) { m_legendVisible = visible; } bool legendVisible() const { return m_legendVisible; } @@ -107,7 +102,7 @@ class SlsQtH1D { SlsQt1DPlot *m_plot{nullptr}; }; -// Custom painted 1D plot (replaces QwtPlot + QwtPlotZoomer + QwtPlotPanner). +// 1D plot of any number of SlsQtH1D curves. class SlsQt1DPlot : public QWidget { Q_OBJECT @@ -152,7 +147,6 @@ class SlsQt1DPlot : public QWidget { void SetZoomBase(double xmin, double ymin, double x_width, double y_width); - void alignScales(); void SetLogX(bool yes = true); void SetLogY(bool yes = true); diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h index 232d8e6b8..d13bf1ad5 100644 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h @@ -2,21 +2,18 @@ // Copyright (C) 2026 Contributors to the SLS Detector Package #pragma once -// Plain 2D data container used by SlsQt2DPlot. Unlike the previous -// QwtRasterData-derived class it has no qwt (or any other plotting) base: the -// widget composites the image itself through sls::SlsQtFastImage, so all it -// needs from here is the bin geometry, the data, the z range and box/bilinear -// sampling. +// 2D data container used by SlsQt2DPlot: the bin geometry, the data, the z +// range and box/bilinear sampling. // // Data layout: the values are stored x fastest (index = bx + by * nbinsx), // which is the layout qDrawPlot fills (data2d[py * nPixelsX + px]) and the one -// SlsQtFastImage::setImageCopy() expects (image data[x + y*nx], row 0 = y 0). +// SlsQtFastImage::setImage() expects. // // Data coordinates: bin (bx, by) covers // [xmin + bx*xwidth, xmin + (bx+1)*xwidth) x // [ymin + by*ywidth, ymin + (by+1)*ywidth) // and its centre is at (xmin + (bx+0.5)*xwidth, ...). y is up (row 0 is the -// bottom row), matching the FastImageView and the ROI list convention. +// bottom row), like in SlsQtFastImage and in the ROI list. #include @@ -26,7 +23,7 @@ class SlsQt2DHist { public: SlsQt2DHist(int nbinsx = 10, double xmin = 0, double xmax = 10, int nbinsy = 10, double ymin = 0, double ymax = 10, - double *d = nullptr, double zmin = 0, double zmax = -1); + const double *d = nullptr, double zmin = 0, double zmax = -1); ~SlsQt2DHist() = default; // ---- bin geometry (data coordinates) --------------------------------- @@ -47,7 +44,7 @@ class SlsQt2DHist { void SetMinimum(double zmin) { z_min = zmin; } void SetMaximum(double zmax) { z_max = zmax; } // zmax < 0: compute the auto range from the data (+/-2% padding); a zmin - // is ignored in that case, exactly like the previous implementation. + // is ignored in that case. void SetMinMax(double zmin = 0, double zmax = -1); // Smallest positive value, used as the lower end of a log z scale. // Returns z_min; when there is no positive bin it keeps the previous @@ -79,7 +76,7 @@ class SlsQt2DHist { // are kept (nullptr does not clear the frame). Invalid (non-positive) bin // counts are ignored and the previous data is kept. void SetData(int nbinsx, double xmin, double xmax, int nbinsy, double ymin, - double ymax, double *d, double zmin = 0, double zmax = -1); + double ymax, const double *d, double zmin = 0, double zmax = -1); private: double x_min{0.0}, x_max{0.0}, y_min{0.0}, y_max{0.0}; diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h index 4c4d5b8a0..1b58591b9 100644 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h @@ -2,190 +2,109 @@ // Copyright (C) 2026 Contributors to the SLS Detector Package #pragma once -// Qt Widgets-only 2D plot: a sls::SlsQtFastImage canvas (image + axes + zoom / -// pan / ROI overlays) plus the sls::SlsQtScalePanel (histogram strip, palette, -// lin/log and colour range). It replaces the previous QwtPlot-based class and -// keeps the public API qDrawPlot/qTabPlot/qCloneWidget use; the only call-site -// change is title()/setTitle() instead of the QwtPlot title text. -// -// No qwt/ROOT/OpenGL: painting lives in SlsQtFastImage, contours and the -// bilinear overlay are painted through its clipped onPaintOverlay() hook. - #include "SlsQt2DHist.h" #include "sls/sls_detector_defs.h" -#include -#include -#include #include -#include #include #include #include class QLabel; -class QPainter; -class QTransform; namespace sls { class SlsQtFastImage; class SlsQtScalePanel; +/** + * 2D detector image: an SlsQtFastImage with an SlsQtScalePanel below it. + * + * Positions and ranges are in the coordinates given to SetData(), while the + * image view itself works in pixels. + * + * With gain = true the plot shows the gain bits (0..3) in a fixed palette, + * without axes, zoom and scale panel. + */ class SlsQt2DPlot : public QWidget { Q_OBJECT public: explicit SlsQt2DPlot(QWidget *parent = nullptr, bool gain = false); - ~SlsQt2DPlot() override; - // ---- title / axis titles --------------------------------------------- - void SetTitle(QString title); - void SetXTitle(QString title); - void SetYTitle(QString title); - void SetZTitle(QString title); - // qDrawPlot/qCloneWidget use these instead of QwtPlot::title()/setTitle(). - void setTitle(const QString &title); + void SetTitle(const QString &title); QString title() const; - void SetTitleFont(const QFont &f); - void SetXFont(const QFont &f); - void SetYFont(const QFont &f); - void SetZFont(const QFont &f); + void SetXTitle(const QString &title); + void SetYTitle(const QString &title); + void SetZTitle(const QString &title); + + /** Copies nbinsx * nbinsy values from d, x fastest */ + void SetData(int nbinsx, double xmin, double xmax, int nbinsy, double ymin, + double ymax, const double *d); + /** Applies pending axis and z ranges and repaints */ + void Update(); + + /** Range of the data, not of the visible part */ + double GetXMinimum() const { return m_hist.GetXMin(); } + double GetXMaximum() const { return m_hist.GetXMax(); } + double GetYMinimum() const { return m_hist.GetYMin(); } + double GetYMaximum() const { return m_hist.GetYMax(); } - // ---- interaction / viewport ------------------------------------------ - void UnZoom(bool replot = true); - // x_width/y_width are the viewport size in data coordinates. - void SetZoom(double xmin, double ymin, double x_width, double y_width); void DisableZoom(bool disable); void EnableXAutoScaling(); void EnableYAutoScaling(); void SetXMinMax(double min, double max); void SetYMinMax(double min, double max); - // ---- full data ranges (NOT the current viewport: qTabPlot uses these to - // compute the aspect ratio) --------------------------------------------- - double GetXMinimum() { return m_hist->GetXMin(); } - double GetXMaximum() { return m_hist->GetXMax(); } - double GetYMinimum() { return m_hist->GetYMin(); } - double GetYMaximum() { return m_hist->GetYMax(); } - double GetZMinimum() { return m_hist->GetMinimum(); } - double GetZMaximum() { return m_hist->GetMaximum(); } - double GetZMean() { return m_hist->GetMean(); } - - // ---- z (colour) range ------------------------------------------------- - void SetZMinMax(double zmin = 0, double zmax = -1); - void SetZMinimumToFirstGreaterThanZero(); - - // ---- data ------------------------------------------------------------- - void SetData(int nbinsx, double xmin, double xmax, int nbinsy, double ymin, - double ymax, double *d, double zmin = 0, double zmax = -1); - double *GetDataPtr() { return m_hist->GetDataPtr(); } - int GetBinIndex(int bx, int by) { return m_hist->GetBinIndex(bx, by); } - int FindBinIndex(double x, double y) { - return m_hist->FindBinIndex(x, y); - } - void SetBinValue(int bx, int by, double v); - double GetBinValue(int bx, int by) { return m_hist->GetBinValue(bx, by); } - void FillTestPlot(int i = 0); - // Re-applies the pending view/z state and repaints. - void Update(); - - // ---- rendering options ------------------------------------------------ void SetInterpolate(bool enable); void SetContour(bool enable); void SetLogz(bool enable, bool isMin, bool isMax, double min, double max); + /** Fixes the enabled ends of the z range, the other ends follow the + * data. A range picked on the scale panel is kept until an end is + * fixed here or the image size changes. */ void SetZRange(bool isMin, bool isMax, double min, double max); - void LogZ(bool on = 1); - // ---- ROI boxes (all receiver ROIs, yellow overlays) ------------------- - void EnableRoiBoxes(std::vector roi); + void EnableRoiBoxes(const std::vector &roi); void DisableRoiBoxes(); - // Extra accessors used by the integration/verification code. SlsQtFastImage *imageView() const { return m_view; } + /** nullptr for a gain plot */ SlsQtScalePanel *scalePanel() const { return m_panel; } - bool isGainPlot() const { return m_gain; } - // Compact z-axis (colour scale) title shown above the scale panel; nullptr - // in gain mode. Kept as a plain QLabel so the integration tests can check - // it without touching the foundation ScalePanel. - QLabel *zTitleLabel() const { return m_zTitleLabel; } public slots: - void showSpectrogram(bool on); void SetZoom(const QRectF &rect); signals: + /** The user zoomed or panned */ void PlotZoomedSignal(const QRectF &); private: - void setupUi(); - void pushImage(); + void fillTestPlot(); void applyPendingView(); - void applyZRange(double lo, double hi); - void onViewZoomed(double x1, double y1, double x2, double y2); - void rebuildSmoothImage(); void updateContours(); - void paintOverlay(QPainter &p, const QTransform &t); - void drawRois(QPainter &p, const QTransform &t) const; - // Data (ROOT/qwt bin-centre) coordinates <-> SlsQtFastImage pixel-edge - // coordinates (pixel ix covers [ix, ix+1), so the conversion is +0.5 for - // the usual -0.5..nx-0.5 / unit-width bin geometry of qDrawPlot). double dataXToImage(double x) const; double dataYToImage(double y) const; - double imageXToData(double u) const; - double imageYToData(double v) const; - struct ContourSegment { - QPointF a; - QPointF b; - }; - - bool m_gain{false}; - SlsQt2DHist *m_hist{nullptr}; + const bool m_gain; + SlsQt2DHist m_hist; SlsQtFastImage *m_view{nullptr}; SlsQtScalePanel *m_panel{nullptr}; + QLabel *m_zTitleLabel{nullptr}; - bool m_logZ{false}; - bool m_interp{false}; bool m_contourOn{false}; - bool m_showImage{true}; - bool m_zoomDisabled{false}; + bool m_contourDirty{false}; - // Pending programmatic viewport (Enable*AutoScaling/SetXMinMax/...). + // axis ranges requested through SetXMinMax() etc. bool m_autoX{true}; bool m_autoY{true}; - bool m_applyViewPending{false}; + bool m_applyViewPending{true}; double m_reqX0{0.0}, m_reqX1{1.0}, m_reqY0{0.0}, m_reqY1{1.0}; - // True after the scale panel changed the colour range: the per-frame - // auto z range must not overwrite the user's choice. - bool m_panelZOverride{false}; - // True while SetZRange()/SetLogz()/SetZMinMax() pinned an explicit range: - // Update() must not re-derive the auto range (not even the log minimum) - // until SetZRange(false, false, ...) clears it. - bool m_userZOverride{false}; - // Guards the onColorRangeChanged() callback while the plot sets the range. - bool m_syncingZ{false}; - - QRgb m_palette[256]; - QImage m_smooth; // bilinear ("interpolate") overlay, data resolution - bool m_smoothDirty{true}; - - std::vector m_contourSegments; - bool m_contourDirty{true}; - - // Yellow ROI boxes in image pixel-edge coordinates; kept so they can be - // redrawn above the smooth overlay. - std::vector m_roiRects; - - std::vector m_testData; // storage for FillTestPlot() - QFont m_zFont; - QString m_zTitle; - QLabel *m_zTitleLabel{nullptr}; - int m_lastNx{0}; - int m_lastNy{0}; + // who decides the z range, if not the data + bool m_panelZOverride{false}; // picked on the scale panel + bool m_userZOverride{false}; // fixed with SetZRange() }; -} // namespace sls \ No newline at end of file +} // namespace sls diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQtFastImage.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQtFastImage.h index a66e68953..5364d500f 100644 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQtFastImage.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQtFastImage.h @@ -2,130 +2,88 @@ // Copyright (C) 2026 Contributors to the SLS Detector Package #pragma once -// Qt6 port of the fast 2D image view: one cached Format_RGB32 image composed -// from a 256-entry palette LUT, painted with its own axes, grid, tick labels, -// overlays and an optional in-view colour bar. No qwt, ROOT or OpenGL. -// -// Data coordinates are IMAGE PIXEL EDGE coordinates: -// x in [0, nx], y in [0, ny], y is UP and row 0 is at the BOTTOM. -// Pixel (ix, iy) covers [ix, ix+1) x [iy, iy+1). The QImage is composed with -// exactly one flip (QImage row = ny - 1 - dataRow); nothing else flips rows. -// -// Viewport: setViewport()/viewport() and the onZoomChanged callback use the -// same data coordinates (x1,y1,x2,y2 with y1 < y2, y up). widgetToData() maps -// a widget position to that space. Programmatic setViewport() does NOT emit -// onZoomChanged (that keeps master/slave view synchronisation free of feedback -// loops); user pan/wheel zoom, resetView() and resizeEvent() do. - #include "SlsQtPlotCommon.h" +#include #include #include +#include #include #include #include -#include #include -#include #include class QPainter; namespace sls { +/** + * Colour mapped 2D image with axes, zoom and pan. + * + * All coordinates are in image pixels: pixel (ix, iy) covers + * [ix, ix+1) x [iy, iy+1), y points up and row 0 is at the bottom. The + * viewport, the overlays and the signals use these coordinates. + * + * The wheel zooms around the cursor, dragging pans and a double click shows + * the whole image again. Once the pixels are large enough they are outlined + * and labelled with their value. + */ class SlsQtFastImage : public QWidget { Q_OBJECT public: - // Smallest data width/height the viewport may have, in image pixels. + /** Smallest width and height of the viewport */ static constexpr double kMinimumViewport = 2.0; explicit SlsQtFastImage(QWidget *parent = nullptr); - ~SlsQtFastImage() override; - // ---- image input (always copied; GUI thread only) --------------------- - void setImageCopy(const float *data, int nx, int ny); - void setImageCopy(const double *data, int nx, int ny); - - // ---- colour mapping --------------------------------------------------- - // Replaces the 256-entry colour table (GUI thread only). The LUTs returned - // by sls::plot::paletteLut() are recognised, so the ScalePanel can keep its - // chooser in sync; a custom table reports paletteIndex() == -1. - void setPaletteLut(const QRgb *lut); - int paletteIndex() const; // index into sls::plot::Palette, -1 if custom - - void setLogScale(bool on); - bool logScale() const; - void setIntegerValues(bool on); - bool integerValues() const; - void setZeroWhite(bool on); - bool zeroWhite() const; - - void setColorRange(double lo, double hi); - void colorRange(double &lo, double &hi) const; - - // ---- histogram of the last composed frame ----------------------------- - // 256 bins over the window the scale strip displays: the colour range - // widened by half a range on either side (log space when log is on). - // Values outside that window are skipped, not piled into edge bins. - // Recomputed at most every ~300 ms. - const std::vector &histogram() const; - void histogramRange(double &lo, double &hi) const; - void invalidateHistogram(); - - // ---- geometry / zoom -------------------------------------------------- - void setPixelAspectX(double a); - double pixelAspectX() const; - void setViewport(double x1, double y1, double x2, double y2); - void viewport(double &x, double &y, double &w, double &h) const; - void resetView(); + /** Copies the data, which is stored x fastest: data[ix + iy * nx] */ + void setImage(const double *data, int nx, int ny); bool hasImage() const; int imageWidth() const; int imageHeight() const; + void setPalette(plot::Palette palette); + plot::Palette palette() const; + /** Map log10 of the values, see plot::logClamp() for values <= 0 */ + void setLogScale(bool on); + bool logScale() const; + void setColorRange(double lo, double hi); + void colorRange(double &lo, double &hi) const; + /** Blend neighbouring pixels. Ignored once the pixels are outlined. */ + void setInterpolate(bool on); + bool interpolate() const; + + /** + * 256 bins over histogramRange(): the colour range widened by half its + * width on both sides, in log10 of the values with a log scale. Values + * outside that range are not counted. Updated while painting, at most a + * few times per second. + */ + const std::vector &histogram() const; + void histogramRange(double &lo, double &hi) const; + + /** Does not emit viewportChanged() */ + void setViewport(double x1, double y1, double x2, double y2); + void viewport(double &x, double &y, double &w, double &h) const; + void resetView(); QPointF widgetToData(const QPointF &widgetPos) const; QPointF dataToWidget(const QPointF &dataPos) const; - // ---- overlays (data coordinates, see above) --------------------------- - // Editable yellow ROI (gate ROI), as in the reference view. - void setRoiRect(double x0, double y0, double x1, double y1, bool on = true); - void setRoiRectVisible(bool on); - bool roiRect(double &x0, double &y0, double &x1, double &y1) const; - - // Additional yellow rectangles (e.g. every receiver ROI): each QRectF is - // (x0, y0, width, height) with (x0,y0) the LOWER-LEFT corner in data - // coordinates. Replaces the previous list. - void setOverlayRects(const std::vector &rects); - void clearOverlayRects(); - const std::vector &overlayRects() const; - - // Red receiver-ROI rectangle, same data coordinates. - void setReceiverRoiRect(double x0, double y0, double x1, double y1, - bool on = true); - void clearReceiverRoiRect(); - - // ---- ROI editor ------------------------------------------------------- - // While active the yellow ROI is edited with the mouse (inside = move, - // edges/corners = resize, outside = draw a new one) instead of panning. - // onRoiEdited() reports (x0,y0,x1,y1) in data coordinates on release. - void beginRoiEdit(bool on); - bool roiEditActive() const; - - // ---- optional in-view colour bar (the ScalePanel replaces it) --------- - void setColorBarVisible(bool on); - bool colorBarVisible() const; - bool isScaleDragging() const; - - // Axes can be turned off for the gain map, which is a plain 0..3 mosaic - // without ticks (the plot then fills the whole widget). - void setAxesVisible(bool on); - bool axesVisible() const; - // Zoom/pan interaction can be turned off (gain map: fixed range). void setZoomEnabled(bool on); bool zoomEnabled() const; + void setAxesVisible(bool on); + bool axesVisible() const; + + /** Yellow rectangles, QRectF(x, y, width, height) with (x, y) the lower + * left corner */ + void setOverlayRects(const std::vector &rects); + const std::vector &overlayRects() const; + /** White line segments, e.g. contour lines */ + void setOverlayLines(const std::vector &lines); - // ---- title and axis titles ------------------------------------------- void setTitle(const QString &title); QString title() const; void setXAxisTitle(const QString &title); @@ -136,24 +94,14 @@ class SlsQtFastImage : public QWidget { QFont titleFont() const; void setAxisTitleFont(const QFont &f); QFont axisTitleFont() const; - void setTickFont(const QFont &f); - QFont tickFont() const; - // ---- callbacks (GUI thread) ------------------------------------------ - std::function onImageChanged; - // reported in data coordinates (x1, y1, x2, y2), y up - std::function onZoomChanged; - std::function onColorRangeChanged; - std::function onPaletteChanged; - // x0, y0, x1, y1 in data coordinates (integers, ROI list convention) - std::function onRoiEdited; - // one histogram/scale refresh, after an in-view colour bar drag - std::function onScaleReleased; - // Called at the end of paintEvent, clipped to the plot rectangle. The - // painter is in widget coordinates and `dataToWidget` maps data - // coordinates (x right, y up) to widget coordinates - use it for contour - // lines, polygons, markers, ... - std::function onPaintOverlay; + signals: + /** The user zoomed or panned, or a resize changed the visible area. + * QRectF(x, y, width, height) with (x, y) the lower left corner. */ + void viewportChanged(const QRectF &viewport); + /** Palette, log scale or colour range changed */ + void colorMapChanged(); + void histogramChanged(); protected: void paintEvent(QPaintEvent *event) override; @@ -165,81 +113,67 @@ class SlsQtFastImage : public QWidget { void resizeEvent(QResizeEvent *event) override; private: - struct Fit { - QRect ir; // plot rectangle in widget pixels - double sx = 1.0; // screen pixels per data x unit - double sy = 1.0; // screen pixels per data y unit - double ox = 0.0; // centering offset inside ir, widget pixels - double oy = 0.0; + /** Where the viewport ends up in the widget */ + struct Mapping { + QRect plot; // widget area the image is drawn in + double scale = 1.0; // widget pixels per image pixel + QPointF origin; // widget position of image coordinate (0, 0) + + QPointF toWidget(double x, double y) const { + return {origin.x() + x * scale, origin.y() - y * scale}; + } + QPointF toData(const QPointF &w) const { + return {(w.x() - origin.x()) / scale, (origin.y() - w.y()) / scale}; + } }; - void renderImage(); - Fit computeFit() const; - QRect imageRect() const; - QRect scaleRect() const; + QRect plotRect() const; + Mapping mapping() const; void clampViewport(); void matchViewportToWindow(); - void drawImage(QPainter &p, const Fit &fit); - void drawOverlays(QPainter &p, const Fit &fit); - void drawAxes(QPainter &p, const Fit &fit); - void drawTitles(QPainter &p, const Fit &fit); - void drawColorBar(QPainter &p); - void drawPixelDetail(QPainter &p, const Fit &fit); - double valueAt(const QPoint &pos) const; + void zoomAt(const QPointF &widgetPos, double factor); + void renderImage(); + void updateHistogram(); + void drawImage(QPainter &p, const Mapping &m) const; + void drawAxes(QPainter &p, const Mapping &m) const; + void drawPixelDetail(QPainter &p, const Mapping &m) const; + void drawOverlays(QPainter &p, const Mapping &m) const; + void drawTitles(QPainter &p, const Mapping &m) const; + double value(int ix, int iy) const; - double vpW() const { return (m_vpW < 0) ? m_nx : m_vpW; } - double vpH() const { return (m_vpH < 0) ? m_ny : m_vpH; } + std::vector m_data; + int m_nx = 0; + int m_ny = 0; + QImage m_image; // m_data through the colour map, row 0 at the top + bool m_imageDirty = true; - std::vector m_owned; // widget-owned copy of the last frame - const float *m_data = nullptr; - int m_nx = 0, m_ny = 0; - QImage m_image; - bool m_dirty = true; - QRgb m_palette[256]; - int m_paletteIndex = int(plot::Palette::Color); - - double m_clo = 0.0, m_chi = 4000.0; - double m_defClo = 0.0, m_defChi = 4000.0; + plot::Palette m_palette = plot::Palette::Color; + double m_colorLo = 0.0; + double m_colorHi = 1.0; bool m_logScale = false; - bool m_integerValues = false; - bool m_zeroWhite = false; - bool m_showBar = false; - bool m_axesVisible = true; + bool m_interpolate = false; + + std::vector m_histogram; + double m_histogramLo = 0.0; + double m_histogramHi = 1.0; + QElapsedTimer m_histogramAge; + + QRectF m_viewport; // (x, y) is the lower left corner bool m_zoomEnabled = true; + bool m_axesVisible = true; + bool m_panning = false; + QPointF m_panStart; // widget position of the press + QPointF m_panStartViewport; // lower left corner at the press - std::vector m_hist; - double m_histLo = 0.0, m_histHi = 1.0; - qint64 m_histMs = 0; + std::vector m_overlayRects; + std::vector m_overlayLines; - double m_pixelAspectX = 1.0; - double m_vpX = 0.0, m_vpY = 0.0; - double m_vpW = -1.0, m_vpH = -1.0; - double m_sx = 1.0; // last painted screen pixels per data x unit - - bool m_roiOn = false; - double m_roiX0 = 0.0, m_roiY0 = 0.0, m_roiX1 = 0.0, m_roiY1 = 0.0; - std::vector m_overlays; - bool m_rxOn = false; - double m_rxX0 = 0.0, m_rxY0 = 0.0, m_rxX1 = 0.0, m_rxY1 = 0.0; - - bool m_roiEdit = false; - int m_roiGrab = 0; // 0 none, 1 move, 2 left, 3 right, 4 bottom, 5 top, - // 6 bl, 7 br, 8 tl, 9 tr, 10 new rectangle - QPointF m_roiPress{0, 0}; - double m_roiStart[4] = {0, 0, 0, 0}; - - bool m_dragging = false; - QPointF m_lastPos; - double m_dragVpX = 0.0, m_dragVpY = 0.0; - - bool m_dragScale = false; // in-view colour bar drag - bool m_dragMax = false; - int m_dragScaleY = 0; - double m_dragClo = 0.0, m_dragChi = 0.0; - - sls::plot::PlotTheme m_theme; - QString m_title, m_xTitle, m_yTitle; - QFont m_titleFont, m_axisTitleFont, m_tickFont; + plot::PlotTheme m_theme; + QString m_title; + QString m_xTitle; + QString m_yTitle; + QFont m_titleFont; + QFont m_axisTitleFont; }; } // namespace sls diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQtPlotCommon.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQtPlotCommon.h index c1ec8ae23..0c4b65630 100644 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQtPlotCommon.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQtPlotCommon.h @@ -2,24 +2,15 @@ // Copyright (C) 2026 Contributors to the SLS Detector Package #pragma once -// Shared plotting primitives for the plotting stack used by -// slsDetectorGui. Nothing here depends on qwt, ROOT or OpenGL. -// -// The palettes and the 1/2/5 tick rules are the ones the previous -// FastImageView/ScalePanel implementation used (see notes/plot-foundation.md); -// keeping them in one place guarantees that the 1D plot, the 2D plot and the -// scale panel draw the same axes with the same colours. +// Palettes, axis ticks and colours shared by the 1D plot, the 2D plot and the +// scale panel, so that they all draw the same axes with the same colours. #include #include -#include -#include #include #include #include #include -#include -#include #include #include diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQtScalePanel.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQtScalePanel.h index c236685c7..0c605dcda 100644 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQtScalePanel.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQtScalePanel.h @@ -2,20 +2,8 @@ // Copyright (C) 2026 Contributors to the SLS Detector Package #pragma once -// Thin histogram strip + scale panel of the plotting stack: the -// strip shows the distribution of the last frame over the window the colour -// mapping currently shows and carries the two draggable range ends; the panel -// owns the palette chooser and the image/histogram lin-log switches. The -// colour min/max live in the Plot tab, not here. See AGENT_INSTRUCTIONS.md: -// "the three-way freeze rule". - -#include "SlsQtPlotCommon.h" - -#include -#include #include -#include #include class QComboBox; @@ -24,51 +12,40 @@ namespace sls { class SlsQtFastImage; -// The histogram strip (fixed height ~38 px). The two markers sit at 1/4 and -// 3/4 of the width and the value axis rescales under them: the window shown is -// the mapped range widened by half a range on either side (in log space when -// logX is on). -// -// FREEZE RULE: while a marker is dragged the strip does not change at all. -// * the axis window is the one captured at press (see displayedWindow()), -// * the painted bars are a snapshot of the histogram taken at press -// (see displayedHistogram()), -// * the cursor->value mapping goes through that pressed-time window, so the -// marker cannot chase itself. -// Only the dashed preview line moves. The new range is applied once, on -// release (onRangeChanged), and the strip is refreshed afterwards. +/** + * Histogram of the image with the two ends of the colour range as markers. + * + * The markers stay at 1/4 and 3/4 of the width and the value axis rescales + * under them, so the strip shows the colour range plus half a range on either + * side. Dragging a marker moves that end of the range. + * + * Only a preview line follows the cursor during a drag and the new range is + * reported on release. Rescaling the axis under a dragged marker would make + * the marker run away from the cursor. + */ class SlsQtScaleHisto : public QWidget { Q_OBJECT public: explicit SlsQtScaleHisto(QWidget *parent = nullptr); - // h: live 256-bin histogram (owned by the image view); dlo/dhi: bounds of - // those bins in their own binning space (log10 space when logX); clo/chi: - // colour range in value space; logX: the value axis is log; logY: the bar - // heights are log10(count + 1). - void setData(const std::vector *h, double dlo, double dhi, double clo, - double chi, bool logX, bool logY); - - // Drops the raw pointer to the view's histogram vector (and any frozen - // snapshot). Called when the panel detaches from a view or when the view - // is destroyed, so a later repaint cannot read freed memory. - void clearData(); - - // Reports the new mapped range (value space) once, when the button is - // released. - std::function onRangeChanged; - - // ---- test accessors --------------------------------------------------- + /** + * Ignored while a marker is dragged. + * @param counts histogram of the image + * @param binLo lower edge of the first bin + * @param binHi upper edge of the last bin + * @param colorLo lower end of the colour range + * @param colorHi upper end of the colour range + * @param logX the colour scale is logarithmic, the bins are in log10 + * @param logY draw log10(count + 1) + */ + void setData(const std::vector &counts, double binLo, double binHi, + double colorLo, double colorHi, bool logX, bool logY); bool isDragging() const; - // The live mapped colour range (value space). - void currentWindow(double &lo, double &hi) const; - // The axis window currently shown/painted, in bin space. Frozen while - // dragging. - void displayedWindow(double &lo, double &hi) const; - // The bars currently painted: the press-time snapshot while dragging. - const std::vector *displayedHistogram() const; - int previewX() const; + + signals: + /** A marker was dragged and released */ + void rangeChanged(double lo, double hi); protected: void paintEvent(QPaintEvent *event) override; @@ -77,94 +54,46 @@ class SlsQtScaleHisto : public QWidget { void mouseReleaseEvent(QMouseEvent *event) override; private: - void windowFor(double clo, double chi, double &wlo, double &whi) const; + enum class Marker { None, Lo, Hi }; - const std::vector *m_hist = nullptr; - double m_dlo = 0.0, m_dhi = 1.0; - double m_clo = 0.0, m_chi = 1.0; - bool m_logX = false, m_logY = false; + void axisRange(double &lo, double &hi) const; - int m_dragMin = -1; // -1 none, 1 min, 0 max - bool m_dragging = false; - double m_preClo = 0.0, m_preChi = 1.0; // axis basis at press - std::vector m_snap; // bars snapshot at press - int m_previewX = 0; + std::vector m_counts; + double m_binLo = 0.0; + double m_binHi = 1.0; + double m_colorLo = 0.0; + double m_colorHi = 1.0; + bool m_logX = false; + bool m_logY = false; + + Marker m_dragged = Marker::None; + double m_dragX = 0.0; // widget x of the cursor }; -// Histogram strip + palette combo + image lin/log + histogram lin/log. -// push() = controls -> view, refresh() = view -> controls, with a -// re-entrancy guard; refresh() is skipped while the strip is being dragged and -// the range is applied on release. The z min/max are edited in the Plot tab. +/** + * Colour controls of an image view: the histogram strip, the palette and + * lin/log switches for the image and for the histogram. + */ class SlsQtScalePanel : public QWidget { Q_OBJECT public: - explicit SlsQtScalePanel(SlsQtFastImage *view = nullptr, - QWidget *parent = nullptr); - ~SlsQtScalePanel() override; - - // Attaches to a view; preserves callbacks that were already installed on - // it (the panel chains onImageChanged / onScaleReleased). - void setView(SlsQtFastImage *view); - SlsQtFastImage *view() const; - - void refresh(); // view -> controls - void syncFromView(); // alias of refresh() - void push(); // controls -> view - - // Convenience API for the 2D plot: keep the controls in sync while the - // plot changes the view programmatically. - void setPalette(plot::Palette p); // also handles Gain4 (not in the chooser) - void setPaletteChoice(int index); - int paletteChoice() const; - void setImageLog(bool on); - void setColorRange(double lo, double hi); - void setHistoLog(bool on); - bool histoLog() const; - void setPaletteEnabled(bool on); + explicit SlsQtScalePanel(SlsQtFastImage *view, QWidget *parent = nullptr); SlsQtScaleHisto *histogramWidget() const; - bool isDragging() const; // strip drag in progress - // ---- test / programmatic hooks --------------------------------------- - // The colour range last read from / written to the view. Stays frozen - // while the strip marker is dragged (R1). - void controlRange(double &lo, double &hi) const; - // Applies a colour range as a user edit would: this is the only path that - // pushes the colour range from the panel controls, so a test can trigger - // one without synthesising events. - void setControlRange(double lo, double hi); - // Range last pushed to the view by a control edit; false if no edit was - // pushed yet. Palette/log changes never update this (R2). - bool lastPushedRange(double &lo, double &hi) const; + signals: + /** The user dragged a marker of the histogram strip */ + void colorRangeEdited(double lo, double hi); private: - void attachView(SlsQtFastImage *view); - void detachView(); - void updateHisto(); + void refresh(); - QPointer m_view; - SlsQtScaleHisto *m_histo = nullptr; - QComboBox *m_paletteCombo = nullptr; - QComboBox *m_imageLogCombo = nullptr; - QComboBox *m_histoLogCombo = nullptr; - // The colour range last read from the view (kept for the R1 freeze rule - // and for programmatic/test edits; there are no min/max spin boxes here). - double m_controlLo = 0.0; - double m_controlHi = 1.0; - int m_suppress = 0; - - // R2: only an explicit control edit may push the colour range. Refreshes - // (automatic z range) and palette/log changes only update the controls. - bool m_rangeEdited = false; - bool m_lastPushedValid = false; - double m_lastPushedLo = 0.0; - double m_lastPushedHi = 1.0; - - std::function m_prevImageChanged; - std::function m_prevScaleReleased; - bool m_installed = false; - QMetaObject::Connection m_destroyedConn; + SlsQtFastImage *m_view; + SlsQtScaleHisto *m_histo; + QComboBox *m_paletteCombo; + QComboBox *m_imageLogCombo; + QComboBox *m_histoLogCombo; }; } // namespace sls diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cpp index eaf5f703e..bded994fa 100644 --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cpp +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cpp @@ -24,10 +24,8 @@ constexpr int kTickLen = 4; constexpr double kMinSpan = 1e-9; constexpr double kPixelClamp = 1.0e6; -// Colours of SlsQtH1D::SetLineColor(). The original qwt plot had a white -// canvas; the new plotting stack uses the shared dark theme, so the first -// colour (black in the qwt version) and the dark variants are mapped to -// bright equivalents so that a curve is never invisible on the background. +// Colours of SlsQtH1D::SetLineColor(), bright enough for the dark +// background. QColor lineColorForIndex(int c) { switch (c) { case 0: @@ -159,8 +157,8 @@ void SlsQtH1D::SetData(int n, double xmin, double xmax, double *data) { m_ndata = n; if (xmin > xmax) std::swap(xmin, xmax); - // Deliberately divided by n (not n-1): the old qwt code defined the bins - // this way and the GUI/ROI mapping depends on it. + // Deliberately divided by n (not n-1): the GUI/ROI mapping depends on + // the bins being defined this way. m_dx = (xmax - xmin) / n; m_ymin = m_ymax = data ? data[0] : 0.0; m_firstXgt0 = -1.0; @@ -422,7 +420,7 @@ void SlsQt1DPlot::recomputeBase() { } clampView(); // Keep the bottom of the zoom stack (the "full view") in sync with the - // data range; qwt's zoomer did this through setZoomBase() as well. + // data range. if (!m_zoomStack.empty()) m_zoomStack.front() = baseRect(); } @@ -731,11 +729,6 @@ void SlsQt1DPlot::SetZoomBase(double xmin, double ymin, double x_width, update(); } -void SlsQt1DPlot::alignScales() { - // Kept for API compatibility. The custom painter aligns the frame and the - // tick labels itself; there are no qwt scale widgets to align. -} - void SlsQt1DPlot::SetLogX(bool yes) { if (m_logX == yes) return; @@ -1004,9 +997,8 @@ SlsQt1DPlot::Geometry SlsQt1DPlot::computeGeometry() const { } if (m_gainPlot) { - // The old qwt gain plot forced divideScale(0, 3, 3, 0, 1): exactly the - // ticks 0, 1, 2, 3 regardless of the widget height. The generic 1/2/5 - // chooser would yield 0, 0.5, 1, ... in a taller window. + // Exactly the ticks 0, 1, 2, 3 regardless of the widget height. The + // generic 1/2/5 chooser would yield 0, 0.5, 1, ... in a taller window. g.yTicks = {0.0, 1.0, 2.0, 3.0}; g.yLabels = {QStringLiteral("0"), QStringLiteral("1"), QStringLiteral("2"), QStringLiteral("3")}; diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DHist.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DHist.cpp index 100b48655..885dd496f 100644 --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DHist.cpp +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DHist.cpp @@ -9,7 +9,7 @@ namespace sls { SlsQt2DHist::SlsQt2DHist(int nbinsx, double xmin, double xmax, int nbinsy, - double ymin, double ymax, double *d, double zmin, + double ymin, double ymax, const double *d, double zmin, double zmax) { SetData(nbinsx, xmin, xmax, nbinsy, ymin, ymax, d, zmin, zmax); } @@ -29,7 +29,7 @@ double safeBinWidth(int nbins, double lo, double hi) { } // namespace void SlsQt2DHist::SetData(int nbinsx, double xmin, double xmax, int nbinsy, - double ymin, double ymax, double *d, double zmin, + double ymin, double ymax, const double *d, double zmin, double zmax) { if (nbinsx < 1 || nbinsy < 1) return; // invalid geometry: keep the previous data @@ -139,8 +139,7 @@ void SlsQt2DHist::SetMinMax(double zmin, double zmax) { // - high end: multiply a positive value / add 2% of the magnitude to a // negative one, i.e. move it up towards zero. (Multiplying a negative // z_max by 1.02 would move it BELOW the data maximum and clip the - // brightest bin - that was the direction bug reported as R5.) - // Positive-value padding is unchanged (the old qwt formulas). + // brightest bin.) if (z_min > 0) z_min /= 1.02; else diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlot.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlot.cpp index 3ecadc422..bd6870cea 100644 --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlot.cpp +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlot.cpp @@ -7,871 +7,398 @@ #include "SlsQtScalePanel.h" #include -#include -#include -#include -#include +#include #include #include #include -#include namespace sls { namespace { -constexpr int kLowResGrid = 256; // marching-squares grid is subsampled to this -constexpr size_t kMaxContourSegs = 120000; + +constexpr int kContourLevels = 9; +// the contours are computed on a grid of at most this many cells per axis +constexpr int kContourGrid = 256; +constexpr size_t kMaxContourLines = 120000; + } // namespace SlsQt2DPlot::SlsQt2DPlot(QWidget *parent, bool gain) : QWidget(parent), m_gain(gain) { - m_hist = new SlsQt2DHist(); - std::memcpy(m_palette, plot::paletteLut(plot::Palette::Color), - sizeof(m_palette)); - setupUi(); - - m_view->onZoomChanged = [this](double x1, double y1, double x2, double y2) { - onViewZoomed(x1, y1, x2, y2); - }; - m_view->onColorRangeChanged = [this](double, double) { - if (m_syncingZ) - return; - // The user dragged the scale/histogram markers or edited the spin - // boxes: that range is now authoritative until the Plot tab forces a - // new one through SetZRange()/SetZMinMax(). - m_panelZOverride = true; - m_smoothDirty = true; - m_contourDirty = true; - if (m_interp) - rebuildSmoothImage(); - if (m_contourOn) - updateContours(); - if (m_view) - m_view->update(); - }; - m_view->onPaletteChanged = [this](const QRgb *lut) { - std::memcpy(m_palette, lut, sizeof(m_palette)); - m_smoothDirty = true; - if (m_interp) - rebuildSmoothImage(); - if (m_view) - m_view->update(); - }; - m_view->onPaintOverlay = [this](QPainter &p, const QTransform &t) { - paintOverlay(p, t); - }; - - if (m_gain) { - // Plain 0..3 gain map: fixed palette/range, no axes, no zoom. The - // scale panel is not created for it (the parent plot keeps the - // colour controls). - m_view->setAxesVisible(false); - m_view->setZoomEnabled(false); - m_view->setIntegerValues(true); - m_view->setPaletteLut(plot::paletteLut(plot::Palette::Gain4)); - std::memcpy(m_palette, plot::paletteLut(plot::Palette::Gain4), - sizeof(m_palette)); - m_view->setTitle(QStringLiteral("Gain")); - applyZRange(0.0, 3.0); - } - - FillTestPlot(); - Update(); -} - -SlsQt2DPlot::~SlsQt2DPlot() { - // The child widgets are destroyed after this body: drop the callbacks that - // capture this (and m_hist) so nothing can call into a half-destroyed - // plot while the QWidget children are torn down. - if (m_view) { - m_view->onZoomChanged = nullptr; - m_view->onColorRangeChanged = nullptr; - m_view->onPaletteChanged = nullptr; - m_view->onPaintOverlay = nullptr; - } - delete m_hist; -} - -void SlsQt2DPlot::setupUi() { auto *layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); m_view = new SlsQtFastImage(this); layout->addWidget(m_view, 1); + connect(m_view, &SlsQtFastImage::viewportChanged, this, + [this](const QRectF &v) { + emit PlotZoomedSignal( + QRectF(m_hist.GetXMin() + v.x() * m_hist.GetXBinWidth(), + m_hist.GetYMin() + v.y() * m_hist.GetYBinWidth(), + v.width() * m_hist.GetXBinWidth(), + v.height() * m_hist.GetYBinWidth())); + }); - if (!m_gain) { - // One compact caption row for the z-axis (colour scale) title: the old - // qwt plot showed it next to the colour bar, the ScalePanel replaces - // the bar, so it lives directly above the panel (same dark style as - // the histogram strip, no extra heavy widget). + if (m_gain) { + m_view->setAxesVisible(false); + m_view->setZoomEnabled(false); + m_view->setPalette(plot::Palette::Gain4); + m_view->setColorRange(0.0, 3.0); + m_view->setTitle(QStringLiteral("Gain")); + } else { + const plot::PlotTheme theme; m_zTitleLabel = new QLabel(this); - m_zFont = m_view->axisTitleFont(); - m_zTitleLabel->setFont(m_zFont); m_zTitleLabel->setAlignment(Qt::AlignCenter); - m_zTitleLabel->setContentsMargins(0, 1, 0, 1); - m_zTitleLabel->setSizePolicy(QSizePolicy::Preferred, - QSizePolicy::Fixed); - m_zTitleLabel->setStyleSheet(QStringLiteral( - "QLabel { background-color: rgb(28, 28, 28);" - " color: rgb(230, 230, 230); }")); - m_zTitleLabel->hide(); // shown by SetZTitle() once a title is set - layout->addWidget(m_zTitleLabel, 0); + m_zTitleLabel->setStyleSheet( + QStringLiteral("background-color: %1; color: %2;") + .arg(theme.background.name(), theme.text.name())); + m_zTitleLabel->hide(); + layout->addWidget(m_zTitleLabel); - // Fixed 78 px histogram strip + palette/log/min-max controls. m_panel = new SlsQtScalePanel(m_view, this); - layout->addWidget(m_panel, 0); + layout->addWidget(m_panel); + connect(m_panel, &SlsQtScalePanel::colorRangeEdited, this, + [this] { m_panelZOverride = true; }); + // the contour levels follow the colour range + connect(m_view, &SlsQtFastImage::colorMapChanged, this, [this] { + if (m_contourOn) + updateContours(); + }); } + + fillTestPlot(); } // --------------------------------------------------------------------------- // titles // --------------------------------------------------------------------------- -void SlsQt2DPlot::SetTitle(QString title) { setTitle(title); } +void SlsQt2DPlot::SetTitle(const QString &title) { m_view->setTitle(title); } -void SlsQt2DPlot::setTitle(const QString &title) { - if (m_view) - m_view->setTitle(title); +QString SlsQt2DPlot::title() const { return m_view->title(); } + +void SlsQt2DPlot::SetXTitle(const QString &title) { + m_view->setXAxisTitle(title); } -QString SlsQt2DPlot::title() const { return m_view ? m_view->title() : QString(); } - -void SlsQt2DPlot::SetXTitle(QString title) { - if (m_view) - m_view->setXAxisTitle(title); +void SlsQt2DPlot::SetYTitle(const QString &title) { + m_view->setYAxisTitle(title); } -void SlsQt2DPlot::SetYTitle(QString title) { - if (m_view) - m_view->setYAxisTitle(title); -} - -void SlsQt2DPlot::SetZTitle(QString title) { - m_zTitle = title; - if (!m_zTitleLabel || m_gain) +void SlsQt2DPlot::SetZTitle(const QString &title) { + if (!m_zTitleLabel) return; m_zTitleLabel->setText(title); - // No empty caption row: the panel keeps its exact 78 px height/look when - // no z title is configured. m_zTitleLabel->setVisible(!title.isEmpty()); } -void SlsQt2DPlot::SetTitleFont(const QFont &f) { - if (m_view) - m_view->setTitleFont(f); -} - -void SlsQt2DPlot::SetXFont(const QFont &f) { - if (m_view) - m_view->setAxisTitleFont(f); -} - -void SlsQt2DPlot::SetYFont(const QFont &f) { - if (m_view) - m_view->setAxisTitleFont(f); -} - -void SlsQt2DPlot::SetZFont(const QFont &f) { - m_zFont = f; - if (m_zTitleLabel) - m_zTitleLabel->setFont(f); -} - -// --------------------------------------------------------------------------- -// viewport / zoom -// --------------------------------------------------------------------------- -void SlsQt2DPlot::UnZoom(bool replot) { - m_applyViewPending = false; - if (m_view && m_view->hasImage()) - m_view->resetView(); - if (replot) { - if (m_view) - m_view->update(); - if (m_panel) - m_panel->refresh(); - } -} - -void SlsQt2DPlot::SetZoom(double xmin, double ymin, double x_width, - double y_width) { - SetZoom(QRectF(xmin, ymin, x_width, y_width)); -} - -void SlsQt2DPlot::SetZoom(const QRectF &rect) { - if (!m_view || !m_hist) - return; - const QRectF r = rect.normalized(); - if (!(r.width() > 0.0) || !(r.height() > 0.0)) - return; - m_applyViewPending = false; - m_view->setViewport(dataXToImage(r.left()), dataYToImage(r.top()), - dataXToImage(r.right()), dataYToImage(r.bottom())); - m_view->update(); -} - -void SlsQt2DPlot::DisableZoom(bool disable) { - m_zoomDisabled = disable; - if (m_view && !m_gain) - m_view->setZoomEnabled(!disable); -} - -void SlsQt2DPlot::EnableXAutoScaling() { - if (m_gain) - return; - m_autoX = true; - m_applyViewPending = true; - applyPendingView(); -} - -void SlsQt2DPlot::EnableYAutoScaling() { - if (m_gain) - return; - m_autoY = true; - m_applyViewPending = true; - applyPendingView(); -} - -void SlsQt2DPlot::SetXMinMax(double min, double max) { - if (m_gain) - return; - m_autoX = false; - m_reqX0 = min; - m_reqX1 = max; - m_applyViewPending = true; - applyPendingView(); -} - -void SlsQt2DPlot::SetYMinMax(double min, double max) { - if (m_gain) - return; - m_autoY = false; - m_reqY0 = min; - m_reqY1 = max; - m_applyViewPending = true; - applyPendingView(); -} - -void SlsQt2DPlot::applyPendingView() { - m_applyViewPending = false; - if (m_gain || !m_view || !m_hist) - return; - const int nx = m_hist->GetNBinsX(); - const int ny = m_hist->GetNBinsY(); - if (nx < 1 || ny < 1) - return; - - double u0 = 0.0, u1 = double(nx); - double v0 = 0.0, v1 = double(ny); - if (!m_autoX) { - u0 = dataXToImage(m_reqX0); - u1 = dataXToImage(m_reqX1); - } - if (!m_autoY) { - v0 = dataYToImage(m_reqY0); - v1 = dataYToImage(m_reqY1); - } - if (u1 < u0) - std::swap(u0, u1); - if (v1 < v0) - std::swap(v0, v1); - - // FastImageView refuses viewports smaller than kMinimumViewport; expand - // instead of silently ignoring the request. - const double kMin = SlsQtFastImage::kMinimumViewport; - if (!(u1 - u0 >= kMin)) { - const double c = 0.5 * (u0 + u1); - u0 = c - 0.5 * kMin; - u1 = c + 0.5 * kMin; - } - if (!(v1 - v0 >= kMin)) { - const double c = 0.5 * (v0 + v1); - v0 = c - 0.5 * kMin; - v1 = c + 0.5 * kMin; - } - m_view->setViewport(u0, v0, u1, v1); -} - -void SlsQt2DPlot::onViewZoomed(double x1, double y1, double x2, double y2) { - if (!m_hist) - return; - double dx1 = imageXToData(x1), dx2 = imageXToData(x2); - double dy1 = imageYToData(y1), dy2 = imageYToData(y2); - if (dx2 < dx1) - std::swap(dx1, dx2); - if (dy2 < dy1) - std::swap(dy1, dy2); - emit PlotZoomedSignal(QRectF(dx1, dy1, dx2 - dx1, dy2 - dy1)); -} - -// --------------------------------------------------------------------------- -// z range / colour mapping -// --------------------------------------------------------------------------- -void SlsQt2DPlot::applyZRange(double lo, double hi) { - if (!m_view) - return; - if (m_gain) { - double a = 0.0, b = 0.0; - m_view->colorRange(a, b); - if (a == 0.0 && b == 3.0) - return; - m_syncingZ = true; - m_view->setColorRange(0.0, 3.0); - m_syncingZ = false; - return; - } - double curLo = 0.0, curHi = 0.0; - m_view->colorRange(curLo, curHi); - if (curLo == lo && curHi == hi) - return; - m_syncingZ = true; - m_view->setColorRange(lo, hi); - m_syncingZ = false; - m_smoothDirty = true; - m_contourDirty = true; - if (m_interp) - rebuildSmoothImage(); - if (m_contourOn) - updateContours(); - if (m_panel) - m_panel->refresh(); -} - -void SlsQt2DPlot::SetZMinMax(double zmin, double zmax) { - if (m_gain) - return; - m_hist->SetMinMax(zmin, zmax); - // An explicitly requested range is authoritative: keep it across the - // per-frame Update() calls until SetZRange(false, false, ...) clears it. - m_userZOverride = true; - m_panelZOverride = false; - applyZRange(m_hist->GetMinimum(), m_hist->GetMaximum()); - if (m_view) - m_view->update(); - if (m_panel) - m_panel->refresh(); -} - -void SlsQt2DPlot::SetZMinimumToFirstGreaterThanZero() { - if (m_gain) - return; - m_hist->SetMinimumToFirstGreaterThanZero(); - // This is the automatic log minimum, so it releases both overrides. - m_userZOverride = false; - m_panelZOverride = false; - Update(); -} - -void SlsQt2DPlot::SetLogz(bool enable, bool isMin, bool isMax, double min, - double max) { - LogZ(enable); - SetZRange(isMin, isMax, min, max); -} - -void SlsQt2DPlot::SetZRange(bool isMin, bool isMax, double min, double max) { - if (m_gain) - return; - if (m_logZ) - m_hist->SetMinimumToFirstGreaterThanZero(); - if (isMin || isMax) { - double zmin = isMin ? min : m_hist->GetMinimum(); - double zmax = isMax ? max : m_hist->GetMaximum(); - if (!(zmax > zmin)) - zmax = zmin + 1.0; - m_hist->SetMinMax(zmin, zmax); - // An explicit range from the Plot tab (qTabPlot's min/max z controls) - // wins over both the panel and the auto range, and must survive the - // Update() that follows (in particular the log-min re-derivation). - m_userZOverride = true; - m_panelZOverride = false; - applyZRange(zmin, zmax); - } else { - // Neither end is pinned: fall back to the automatic range on the next - // Update() (the scale-panel override, if any, still takes precedence - // there). qDrawPlot calls this every frame while the z-range check - // boxes are off. - m_userZOverride = false; - } - Update(); -} - -void SlsQt2DPlot::LogZ(bool on) { - if (m_gain) - return; - m_logZ = (on != 0); - if (m_view) - m_view->setLogScale(m_logZ); - m_smoothDirty = true; - m_contourDirty = true; - if (m_panel) - m_panel->setImageLog(m_logZ); // keeps the panel's lin/log chooser in sync - Update(); -} - // --------------------------------------------------------------------------- // data // --------------------------------------------------------------------------- void SlsQt2DPlot::SetData(int nbinsx, double xmin, double xmax, int nbinsy, - double ymin, double ymax, double *d, double zmin, - double zmax) { - m_hist->SetData(nbinsx, xmin, xmax, nbinsy, ymin, ymax, d, zmin, zmax); - const bool newGeometry = (m_hist->GetNBinsX() != m_lastNx || - m_hist->GetNBinsY() != m_lastNy); - m_lastNx = m_hist->GetNBinsX(); - m_lastNy = m_hist->GetNBinsY(); - if (newGeometry) { - // New frame geometry: drop the scale-panel override and fit the whole - // frame (zoom is preserved across frames of the same size). An - // explicit Plot-tab range (m_userZOverride) survives: qDrawPlot still - // has those min/max values and re-applies them every frame. + double ymin, double ymax, const double *d) { + const int oldNx = m_hist.GetNBinsX(); + const int oldNy = m_hist.GetNBinsY(); + m_hist.SetData(nbinsx, xmin, xmax, nbinsy, ymin, ymax, d); + if (m_hist.GetNBinsX() != oldNx || m_hist.GetNBinsY() != oldNy) { + // a zoom or a range picked on the scale panel belonged to the old + // image, a range fixed with SetZRange() is still wanted m_panelZOverride = false; m_applyViewPending = true; } - if (zmax != -1.0) { - // The frame itself carries an explicit z range: it takes over from any - // previous user/panel range (and Update() must apply it, not skip). - m_userZOverride = false; - m_panelZOverride = false; - } - pushImage(); - m_smoothDirty = true; + m_view->setImage(m_hist.GetDataPtr(), m_hist.GetNBinsX(), + m_hist.GetNBinsY()); m_contourDirty = true; Update(); } -void SlsQt2DPlot::pushImage() { - if (!m_view || !m_hist) - return; - const int nx = m_hist->GetNBinsX(); - const int ny = m_hist->GetNBinsY(); - if (nx < 1 || ny < 1) - return; - m_view->setImageCopy(m_hist->GetDataPtr(), nx, ny); -} - -void SlsQt2DPlot::SetBinValue(int bx, int by, double v) { - m_hist->SetBinValue(bx, by, v); - if (m_view && m_hist->GetNBinsX() > 0 && m_hist->GetNBinsY() > 0) { - pushImage(); - m_smoothDirty = true; - m_contourDirty = true; - Update(); - } -} - -void SlsQt2DPlot::FillTestPlot(int mode) { - const int nx = 50; - const int ny = 50; - m_testData.assign(static_cast(nx) * static_cast(ny), 0.0); - const double dmax = - std::sqrt(std::pow(nx / 2.0 - 0.5, 2) + std::pow(ny / 2.0 - 0.5, 2)); - for (int i = 0; i < nx; i++) { - for (int j = 0; j < ny; j++) { - const double d = std::sqrt(std::pow(nx / 2.0 - (i + 0.5), 2) + - std::pow(ny / 2.0 - (j + 0.5), 2)); - m_testData[static_cast(i) + - static_cast(j) * static_cast(nx)] = - (mode % 3) ? 10 * d / dmax : 10 * (1 - d / dmax); +// Shown until the first image arrives +void SlsQt2DPlot::fillTestPlot() { + const int n = 50; + const double center = n / 2.0; + const double maxDistance = std::hypot(center - 0.5, center - 0.5); + std::vector data(static_cast(n) * n); + for (int iy = 0; iy < n; ++iy) { + for (int ix = 0; ix < n; ++ix) { + const double distance = + std::hypot(center - (ix + 0.5), center - (iy + 0.5)); + data[static_cast(iy) * n + ix] = + 10 * (1 - distance / maxDistance); } } - SetData(nx, 200, 822, ny, -0.5, ny - 0.5, m_testData.data()); + SetData(n, 200, 822, n, -0.5, n - 0.5, data.data()); } void SlsQt2DPlot::Update() { - if (!m_view) - return; - if (m_gain) { - m_view->update(); - return; + if (!m_gain) { + if (m_applyViewPending) + applyPendingView(); + if (!m_panelZOverride && !m_userZOverride) { + if (m_view->logScale()) + m_hist.SetMinimumToFirstGreaterThanZero(); + m_view->setColorRange(m_hist.GetMinimum(), m_hist.GetMaximum()); + } + if (m_contourOn && m_contourDirty) + updateContours(); } - if (m_applyViewPending) - applyPendingView(); - if (!m_panelZOverride && !m_userZOverride && m_hist) { - if (m_logZ) - m_hist->SetMinimumToFirstGreaterThanZero(); - applyZRange(m_hist->GetMinimum(), m_hist->GetMaximum()); - } - if (m_interp && m_smoothDirty) - rebuildSmoothImage(); - if (m_contourOn && m_contourDirty) - updateContours(); m_view->update(); - if (m_panel) - m_panel->refresh(); } // --------------------------------------------------------------------------- -// rendering options +// axis ranges and zoom +// --------------------------------------------------------------------------- +double SlsQt2DPlot::dataXToImage(double x) const { + return (x - m_hist.GetXMin()) / m_hist.GetXBinWidth(); +} + +double SlsQt2DPlot::dataYToImage(double y) const { + return (y - m_hist.GetYMin()) / m_hist.GetYBinWidth(); +} + +void SlsQt2DPlot::SetZoom(const QRectF &rect) { + const QRectF r = rect.normalized(); + if (r.isEmpty()) + return; + m_applyViewPending = false; + m_view->setViewport(dataXToImage(r.left()), dataYToImage(r.top()), + dataXToImage(r.right()), dataYToImage(r.bottom())); +} + +void SlsQt2DPlot::DisableZoom(bool disable) { + if (!m_gain) + m_view->setZoomEnabled(!disable); +} + +void SlsQt2DPlot::EnableXAutoScaling() { + m_autoX = true; + applyPendingView(); +} + +void SlsQt2DPlot::EnableYAutoScaling() { + m_autoY = true; + applyPendingView(); +} + +void SlsQt2DPlot::SetXMinMax(double min, double max) { + m_autoX = false; + m_reqX0 = min; + m_reqX1 = max; + applyPendingView(); +} + +void SlsQt2DPlot::SetYMinMax(double min, double max) { + m_autoY = false; + m_reqY0 = min; + m_reqY1 = max; + applyPendingView(); +} + +void SlsQt2DPlot::applyPendingView() { + m_applyViewPending = false; + if (m_gain) + return; + double x0 = 0.0, x1 = m_hist.GetNBinsX(); + double y0 = 0.0, y1 = m_hist.GetNBinsY(); + if (!m_autoX) { + x0 = dataXToImage(std::min(m_reqX0, m_reqX1)); + x1 = dataXToImage(std::max(m_reqX0, m_reqX1)); + } + if (!m_autoY) { + y0 = dataYToImage(std::min(m_reqY0, m_reqY1)); + y1 = dataYToImage(std::max(m_reqY0, m_reqY1)); + } + // the view ignores a viewport below its minimum size, so widen the + // request around its centre instead + const auto widen = [](double &lo, double &hi) { + const double missing = SlsQtFastImage::kMinimumViewport - (hi - lo); + if (missing > 0) { + lo -= missing / 2; + hi += missing / 2; + } + }; + widen(x0, x1); + widen(y0, y1); + m_view->setViewport(x0, y0, x1, y1); +} + +// --------------------------------------------------------------------------- +// z range +// --------------------------------------------------------------------------- +void SlsQt2DPlot::SetLogz(bool enable, bool isMin, bool isMax, double min, + double max) { + if (m_gain) + return; + m_view->setLogScale(enable); + SetZRange(isMin, isMax, min, max); +} + +void SlsQt2DPlot::SetZRange(bool isMin, bool isMax, double min, double max) { + if (m_gain) + return; + m_userZOverride = isMin || isMax; + if (m_userZOverride) { + if (m_view->logScale()) + m_hist.SetMinimumToFirstGreaterThanZero(); + const double zmin = isMin ? min : m_hist.GetMinimum(); + double zmax = isMax ? max : m_hist.GetMaximum(); + if (!(zmax > zmin)) + zmax = zmin + 1.0; + m_panelZOverride = false; + m_view->setColorRange(zmin, zmax); + } + Update(); +} + +// --------------------------------------------------------------------------- +// drawing options // --------------------------------------------------------------------------- void SlsQt2DPlot::SetInterpolate(bool enable) { - m_interp = enable; - m_smoothDirty = true; - if (m_interp) - rebuildSmoothImage(); - else { - m_smooth = QImage(); - m_smoothDirty = false; - } - if (m_view) - m_view->update(); + m_view->setInterpolate(enable); } void SlsQt2DPlot::SetContour(bool enable) { m_contourOn = enable; - m_contourDirty = true; - if (m_contourOn) - updateContours(); - else - m_contourSegments.clear(); - if (m_view) - m_view->update(); + updateContours(); } -void SlsQt2DPlot::showSpectrogram(bool on) { - m_showImage = on; - if (m_view) - m_view->update(); -} - -// --------------------------------------------------------------------------- -// ROI overlays: the ROI list is in bin indices; pixel (ix,iy) covers -// [ix,ix+1)x[iy,iy+1) in FastImageView coordinates, so the conversion is the -// identity on the index (not on the data coordinate). -// --------------------------------------------------------------------------- -void SlsQt2DPlot::EnableRoiBoxes(std::vector roi) { - m_roiRects.clear(); - m_roiRects.reserve(roi.size()); +// The ROIs are in pixels with inclusive limits +void SlsQt2DPlot::EnableRoiBoxes(const std::vector &roi) { + std::vector rects; + rects.reserve(roi.size()); for (const auto &r : roi) { - if (r.xmax < r.xmin || r.ymax < r.ymin) - continue; - m_roiRects.emplace_back(QRectF(double(r.xmin), double(r.ymin), - double(r.xmax - r.xmin + 1), - double(r.ymax - r.ymin + 1))); - } - if (m_view) { - m_view->setOverlayRects(m_roiRects); - m_view->update(); + if (r.xmax >= r.xmin && r.ymax >= r.ymin) + rects.emplace_back(r.xmin, r.ymin, r.xmax - r.xmin + 1, + r.ymax - r.ymin + 1); } + m_view->setOverlayRects(rects); } -void SlsQt2DPlot::DisableRoiBoxes() { - m_roiRects.clear(); - if (m_view) { - m_view->clearOverlayRects(); - m_view->update(); - } -} +void SlsQt2DPlot::DisableRoiBoxes() { m_view->setOverlayRects({}); } -// --------------------------------------------------------------------------- -// coordinate conversions: data (bin-centre) <-> image (pixel-edge) -// --------------------------------------------------------------------------- -double SlsQt2DPlot::dataXToImage(double x) const { - const double w = m_hist->GetXBinWidth(); - return (w > 0.0) ? (x - m_hist->GetXMin()) / w : 0.0; -} - -double SlsQt2DPlot::dataYToImage(double y) const { - const double w = m_hist->GetYBinWidth(); - return (w > 0.0) ? (y - m_hist->GetYMin()) / w : 0.0; -} - -double SlsQt2DPlot::imageXToData(double u) const { - return m_hist->GetXMin() + u * m_hist->GetXBinWidth(); -} - -double SlsQt2DPlot::imageYToData(double v) const { - return m_hist->GetYMin() + v * m_hist->GetYBinWidth(); -} - -// --------------------------------------------------------------------------- -// bilinear interpolation overlay -// -// SlsQtFastImage always displays one colour per data pixel. When the user -// enables "interpolate" we compose the same colour-mapped image at data -// resolution and let QPainter resample it bilinearly on top of the (opaque) -// pixel image; pixel detail / deep zoom keeps the crisp pixel view. The ROI -// boxes are redrawn above it so they stay visible. -// --------------------------------------------------------------------------- -void SlsQt2DPlot::rebuildSmoothImage() { - m_smoothDirty = false; - if (!m_interp || !m_view || !m_hist) { - m_smooth = QImage(); - return; - } - const int nx = m_hist->GetNBinsX(); - const int ny = m_hist->GetNBinsY(); - const double *src = m_hist->GetDataPtr(); - if (nx < 1 || ny < 1 || !src) { - m_smooth = QImage(); - return; - } - if (m_smooth.size() != QSize(nx, ny) || - m_smooth.format() != QImage::Format_RGB32) - m_smooth = QImage(nx, ny, QImage::Format_RGB32); - - double lo = 0.0, hi = 1.0; - m_view->colorRange(lo, hi); - const bool log = m_view->logScale(); - const double loD = log ? plot::logClamp(lo) : lo; - const double hiD = log ? plot::logClamp(hi) : hi; - double range = hiD - loD; - if (!std::isfinite(range) || !(range > 0.0)) - range = 1.0; - const double scale = 255.0 / range; - const bool zeroWhite = m_view->zeroWhite(); - const QRgb *pal = m_palette; - - for (int y = 0; y < ny; y++) { - // Exactly one flip, like SlsQtFastImage: QImage row = ny-1-dataRow. - QRgb *line = reinterpret_cast(m_smooth.scanLine(ny - 1 - y)); - const double *s = src + static_cast(y) * static_cast(nx); - for (int x = 0; x < nx; x++) { - const double v = s[x]; - if (!std::isfinite(v)) { - line[x] = pal[0]; - continue; - } - if (zeroWhite && !(v > 0.0)) { - line[x] = qRgb(255, 255, 255); - continue; - } - int idx = - static_cast(((log ? plot::logClamp(v) : v) - loD) * scale); - if (idx < 0) - idx = 0; - else if (idx > 255) - idx = 255; - line[x] = pal[idx]; - } - } -} - -// --------------------------------------------------------------------------- -// marching squares: ~9 levels over the visible colour range, on a subsampled -// grid (the full 1024x512 grid at 9 levels is unnecessary and slow), in -// FastImageView pixel-edge coordinates. The segments are stored in data -// coordinates and clipped to the plot rect by the FastImageView paint hook. -// --------------------------------------------------------------------------- +// Marching squares for kContourLevels levels spread evenly over the colour +// range. Lines are in pixel coordinates, the value of a pixel sits at its +// centre. void SlsQt2DPlot::updateContours() { - m_contourSegments.clear(); m_contourDirty = false; - if (!m_contourOn || m_gain || !m_hist || !m_view) - return; - const int nx = m_hist->GetNBinsX(); - const int ny = m_hist->GetNBinsY(); - const double *d = m_hist->GetDataPtr(); - if (!d || nx < 2 || ny < 2) - return; - + std::vector lines; + const int nx = m_hist.GetNBinsX(); + const int ny = m_hist.GetNBinsY(); + const bool log = m_view->logScale(); double lo = 0.0, hi = 1.0; m_view->colorRange(lo, hi); - std::vector levels; - levels.reserve(9); - if (m_logZ) { - double a = (lo > 0.0 && std::isfinite(lo)) ? std::log10(lo) : 0.0; - double b = (hi > 0.0 && std::isfinite(hi)) ? std::log10(hi) : a + 1.0; - if (!(b > a)) - b = a + 1.0; - for (int k = 1; k <= 9; k++) - levels.push_back(std::pow(10.0, a + (b - a) * k / 10.0)); - } else { - if (!std::isfinite(lo) || !std::isfinite(hi) || !(hi > lo)) - return; - for (int k = 1; k <= 9; k++) - levels.push_back(lo + (hi - lo) * k / 10.0); + if (log) { + lo = plot::logClamp(lo); + hi = plot::logClamp(hi); + } + if (!m_contourOn || nx < 2 || ny < 2 || !std::isfinite(lo) || + !std::isfinite(hi) || !(hi > lo)) { + m_view->setOverlayLines(lines); + return; } - const int step = - std::max(1, static_cast(std::ceil( - double(std::max(nx, ny)) / double(kLowResGrid)))); + std::vector levels; + for (int k = 1; k <= kContourLevels; ++k) { + const double level = lo + (hi - lo) * k / (kContourLevels + 1); + levels.push_back(log ? std::pow(10.0, level) : level); + } - auto intersect = [](double pu, double pv, double qu, double qv, double pval, - double qval, double L) { - const double dv = qval - pval; - double t = (std::abs(dv) > 1e-12) ? (L - pval) / dv : 0.5; - t = std::min(1.0, std::max(0.0, t)); - return QPointF(pu + (qu - pu) * t, pv + (qv - pv) * t); + // every step-th pixel, and always the last one so that the contours + // reach the edge of the image + const int step = (std::max(nx, ny) + kContourGrid - 1) / kContourGrid; + const auto gridPoints = [step](int n) { + std::vector points; + for (int i = 0; i < n; i += step) + points.push_back(i); + if (points.back() != n - 1) + points.push_back(n - 1); + return points; + }; + const std::vector gridX = gridPoints(nx); + const std::vector gridY = gridPoints(ny); + + // where the level is crossed between p and q + const auto crossing = [](QPointF p, QPointF q, double pValue, double qValue, + double level) { + const double diff = qValue - pValue; + const double t = std::abs(diff) > 1e-12 + ? std::clamp((level - pValue) / diff, 0.0, 1.0) + : 0.5; + return p + (q - p) * t; }; - // Subsample the grid, but always include the last row/column: a plain - // "i + step < nx" loop left the outermost (up to step-1 pixels wide) band - // without contour segments (R8). Clamping the last sample to nx-1/ny-1 - // makes the contours cover the full frame. - std::vector gridX; - gridX.reserve(static_cast(nx) / static_cast(step) + 2); - for (int i = 0; i < nx; i += step) - gridX.push_back(i); - if (gridX.back() != nx - 1) - gridX.push_back(nx - 1); - std::vector gridY; - gridY.reserve(static_cast(ny) / static_cast(step) + 2); - for (int j = 0; j < ny; j += step) - gridY.push_back(j); - if (gridY.back() != ny - 1) - gridY.push_back(ny - 1); - - for (size_t gy = 0; gy + 1 < gridY.size(); gy++) { - const int j = gridY[gy]; - const int jNext = gridY[gy + 1]; - for (size_t gx = 0; gx + 1 < gridX.size(); gx++) { - const int i = gridX[gx]; - const int iNext = gridX[gx + 1]; - const size_t i0 = static_cast(i); - const size_t i1 = static_cast(iNext); - const size_t j0 = static_cast(j); - const size_t j1 = static_cast(jNext); - const double va = d[i0 + j0 * nx]; - const double vb = d[i1 + j0 * nx]; - const double vc = d[i1 + j1 * nx]; - const double vd = d[i0 + j1 * nx]; + for (size_t gy = 0; gy + 1 < gridY.size(); ++gy) { + for (size_t gx = 0; gx + 1 < gridX.size(); ++gx) { + // corners of the cell: a b on the lower edge, d c on the upper + const int i0 = gridX[gx], i1 = gridX[gx + 1]; + const int j0 = gridY[gy], j1 = gridY[gy + 1]; + const double va = m_hist.GetBinValue(i0, j0); + const double vb = m_hist.GetBinValue(i1, j0); + const double vc = m_hist.GetBinValue(i1, j1); + const double vd = m_hist.GetBinValue(i0, j1); if (!std::isfinite(va) || !std::isfinite(vb) || !std::isfinite(vc) || !std::isfinite(vd)) continue; - const double u0 = i + 0.5; - const double u1 = iNext + 0.5; - const double v0 = j + 0.5; - const double v1 = jNext + 0.5; - for (double L : levels) { - const int code = (va > L ? 1 : 0) | (vb > L ? 2 : 0) | - (vc > L ? 4 : 0) | (vd > L ? 8 : 0); - if (code == 0 || code == 15) + const QPointF a(i0 + 0.5, j0 + 0.5), b(i1 + 0.5, j0 + 0.5); + const QPointF c(i1 + 0.5, j1 + 0.5), d(i0 + 0.5, j1 + 0.5); + + for (const double level : levels) { + const int corners = (va > level ? 1 : 0) | + (vb > level ? 2 : 0) | + (vc > level ? 4 : 0) | (vd > level ? 8 : 0); + if (corners == 0 || corners == 15) continue; - const QPointF e0 = - intersect(u0, v0, u1, v0, va, vb, L); // bottom - const QPointF e1 = - intersect(u1, v0, u1, v1, vb, vc, L); // right - const QPointF e2 = - intersect(u0, v1, u1, v1, vd, vc, L); // top - const QPointF e3 = - intersect(u0, v0, u0, v1, va, vd, L); // left - const bool centerHigh = (va + vb + vc + vd) * 0.25 > L; - auto add = [this](const QPointF &a, const QPointF &b) { - m_contourSegments.push_back({a, b}); - }; - switch (code) { + const QPointF bottom = crossing(a, b, va, vb, level); + const QPointF right = crossing(b, c, vb, vc, level); + const QPointF top = crossing(d, c, vd, vc, level); + const QPointF left = crossing(a, d, va, vd, level); + // two opposite corners above the level: the centre decides + // which pairs of edges are connected + const bool centerAbove = (va + vb + vc + vd) / 4 > level; + switch (corners) { case 1: - add(e3, e0); + case 14: + lines.emplace_back(left, bottom); break; case 2: - add(e0, e1); + case 13: + lines.emplace_back(bottom, right); break; case 3: - add(e3, e1); + case 12: + lines.emplace_back(left, right); break; case 4: - add(e1, e2); - break; - case 5: - if (centerHigh) { - add(e0, e1); - add(e2, e3); - } else { - add(e3, e0); - add(e1, e2); - } + case 11: + lines.emplace_back(right, top); break; case 6: - add(e0, e2); + case 9: + lines.emplace_back(bottom, top); break; case 7: - add(e2, e3); - break; case 8: - add(e2, e3); - break; - case 9: - add(e0, e2); + lines.emplace_back(top, left); break; + case 5: case 10: - if (centerHigh) { - add(e3, e0); - add(e1, e2); + if (centerAbove == (corners == 5)) { + lines.emplace_back(bottom, right); + lines.emplace_back(top, left); } else { - add(e0, e1); - add(e2, e3); + lines.emplace_back(left, bottom); + lines.emplace_back(right, top); } break; - case 11: - add(e1, e2); - break; - case 12: - add(e1, e3); - break; - case 13: - add(e0, e1); - break; - case 14: - add(e3, e0); - break; - default: - break; } - if (m_contourSegments.size() >= kMaxContourSegs) + if (lines.size() >= kMaxContourLines) { + m_view->setOverlayLines(lines); return; + } } } } + m_view->setOverlayLines(lines); } -// --------------------------------------------------------------------------- -// clipped paint hook -// --------------------------------------------------------------------------- -void SlsQt2DPlot::drawRois(QPainter &p, const QTransform &t) const { - if (m_roiRects.empty()) - return; - QPen pen(Qt::yellow); - pen.setWidth(1); - pen.setCosmetic(true); - p.save(); - p.setPen(pen); - p.setBrush(Qt::NoBrush); - for (const QRectF &r : m_roiRects) { - const QRectF wr = - QRectF(t.map(r.topLeft()), t.map(r.bottomRight())).normalized(); - p.drawRect(wr); - } - p.restore(); -} - -void SlsQt2DPlot::paintOverlay(QPainter &p, const QTransform &t) { - if (!m_view) - return; - - bool smoothDrawn = false; - if (!m_showImage) { - // WqtPlotSpectrogram image-mode equivalent: hide the image (contours - // and ROI boxes keep painting on the dark background). - p.fillRect(p.viewport(), plot::PlotTheme().background); - } else if (m_interp && !m_smooth.isNull()) { - // Deep zoom keeps the crisp pixel view (grid + values must stay - // readable); otherwise the bilinear image replaces the blocky one. - const double sx = std::abs(t.m11()); - if (sx > 0.0 && sx < 16.0) { - const QRectF target = - QRectF(t.map(QPointF(0.0, 0.0)), - t.map(QPointF(double(m_hist->GetNBinsX()), - double(m_hist->GetNBinsY())))) - .normalized(); - p.save(); - p.setRenderHint(QPainter::SmoothPixmapTransform, true); - p.drawImage(target, m_smooth); - p.restore(); - smoothDrawn = true; - } - } - if (!m_showImage || smoothDrawn) - drawRois(p, t); - - if (m_contourOn && !m_contourSegments.empty()) { - QPen pen(QColor(255, 255, 255, 190)); - pen.setWidth(1); - p.save(); - p.setPen(pen); - p.setBrush(Qt::NoBrush); - for (const ContourSegment &s : m_contourSegments) - p.drawLine(t.map(s.a), t.map(s.b)); - p.restore(); - } -} - -} // namespace sls \ No newline at end of file +} // namespace sls diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQtFastImage.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQtFastImage.cpp index fc35992ed..12a033290 100644 --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQtFastImage.cpp +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQtFastImage.cpp @@ -2,7 +2,6 @@ // Copyright (C) 2026 Contributors to the SLS Detector Package #include "SlsQtFastImage.h" -#include #include #include #include @@ -10,14 +9,23 @@ #include #include -#include namespace sls { namespace { -constexpr int kScaleBarWidth = 50; // optional in-view colour bar, widget px -constexpr QRgb kWhite = qRgb(255, 255, 255); +constexpr int kHistogramBins = 256; +constexpr int kHistogramIntervalMs = 300; +constexpr int kMaxTicks = 8; +constexpr double kWheelZoomFactor = 1.18; +// widget pixels per image pixel from which the pixels are outlined / labelled +constexpr double kOutlineMinScale = 16.0; +constexpr double kLabelMinScale = 50.0; + +QString formatValue(double v) { + const bool integer = (v == std::round(v)); + return QString::number(v, 'f', integer ? 0 : 1); +} } // namespace @@ -26,196 +34,25 @@ SlsQtFastImage::SlsQtFastImage(QWidget *parent) : QWidget(parent) { setFocusPolicy(Qt::StrongFocus); setMinimumSize(200, 200); setAttribute(Qt::WA_OpaquePaintEvent, true); - setAttribute(Qt::WA_NoSystemBackground, true); - const QFont base = font(); - m_titleFont = base; + m_titleFont = font(); m_titleFont.setPixelSize(13); m_titleFont.setBold(true); - m_axisTitleFont = base; + m_axisTitleFont = font(); m_axisTitleFont.setPixelSize(11); - m_tickFont = base; - m_tickFont.setPixelSize(10); - - setPaletteLut(plot::paletteLut(plot::Palette::Color)); } -SlsQtFastImage::~SlsQtFastImage() = default; - -// --------------------------------------------------------------------------- -// image input -// --------------------------------------------------------------------------- -void SlsQtFastImage::setImageCopy(const float *data, int nx, int ny) { +void SlsQtFastImage::setImage(const double *data, int nx, int ny) { if (!data || nx <= 0 || ny <= 0) return; - const size_t n = static_cast(nx) * static_cast(ny); - if (m_owned.size() != n) - m_owned.resize(n); - std::memcpy(m_owned.data(), data, n * sizeof(float)); - const bool newSize = (nx != m_nx || ny != m_ny); - m_data = m_owned.data(); - m_nx = nx; - m_ny = ny; - m_dirty = true; - if (newSize) { - m_hist.clear(); - m_histMs = 0; - m_vpW = -1.0; - m_vpH = -1.0; + m_data.assign(data, data + static_cast(nx) * ny); + if (nx != m_nx || ny != m_ny) { + m_nx = nx; + m_ny = ny; + m_viewport = QRectF(0, 0, nx, ny); + m_histogramAge.invalidate(); } - if (m_vpW < 0) - m_vpW = nx; - if (m_vpH < 0) - m_vpH = ny; - clampViewport(); - update(); -} - -void SlsQtFastImage::setImageCopy(const double *data, int nx, int ny) { - if (!data || nx <= 0 || ny <= 0) - return; - const size_t n = static_cast(nx) * static_cast(ny); - if (m_owned.size() != n) - m_owned.resize(n); - for (size_t i = 0; i < n; i++) - m_owned[i] = static_cast(data[i]); - const bool newSize = (nx != m_nx || ny != m_ny); - m_data = m_owned.data(); - m_nx = nx; - m_ny = ny; - m_dirty = true; - if (newSize) { - m_hist.clear(); - m_histMs = 0; - m_vpW = -1.0; - m_vpH = -1.0; - } - if (m_vpW < 0) - m_vpW = nx; - if (m_vpH < 0) - m_vpH = ny; - clampViewport(); - update(); -} - -// --------------------------------------------------------------------------- -// colour mapping -// --------------------------------------------------------------------------- -void SlsQtFastImage::setPaletteLut(const QRgb *lut) { - if (!lut) - return; - if (onPaletteChanged) - onPaletteChanged(lut); - std::memcpy(m_palette, lut, sizeof(m_palette)); - m_paletteIndex = -1; - for (int i = 0; i <= int(plot::Palette::Gain4); i++) { - if (lut == plot::paletteLut(static_cast(i))) { - m_paletteIndex = i; - break; - } - } - m_dirty = true; - update(); -} - -int SlsQtFastImage::paletteIndex() const { return m_paletteIndex; } - -void SlsQtFastImage::setLogScale(bool on) { - if (m_logScale == on) - return; - m_logScale = on; - m_histMs = 0; // bins follow the mapping - m_dirty = true; - update(); -} - -bool SlsQtFastImage::logScale() const { return m_logScale; } - -void SlsQtFastImage::setIntegerValues(bool on) { - m_integerValues = on; - update(); -} - -bool SlsQtFastImage::integerValues() const { return m_integerValues; } - -void SlsQtFastImage::setZeroWhite(bool on) { - m_zeroWhite = on; - m_dirty = true; - update(); -} - -bool SlsQtFastImage::zeroWhite() const { return m_zeroWhite; } - -void SlsQtFastImage::setColorRange(double lo, double hi) { - m_clo = lo; - m_chi = hi; - m_defClo = lo; - m_defChi = hi; - m_histMs = 0; // the bins follow the window: recompute on the next render - m_dirty = true; - if (onColorRangeChanged) - onColorRangeChanged(lo, hi); - update(); -} - -void SlsQtFastImage::colorRange(double &lo, double &hi) const { - lo = m_clo; - hi = m_chi; -} - -const std::vector &SlsQtFastImage::histogram() const { return m_hist; } - -void SlsQtFastImage::histogramRange(double &lo, double &hi) const { - lo = m_histLo; - hi = m_histHi; -} - -void SlsQtFastImage::invalidateHistogram() { - m_hist.clear(); - m_histMs = 0; -} - -// --------------------------------------------------------------------------- -// geometry / zoom -// --------------------------------------------------------------------------- -void SlsQtFastImage::setPixelAspectX(double a) { - m_pixelAspectX = (a > 0.0 && std::isfinite(a)) ? a : 1.0; - update(); -} - -double SlsQtFastImage::pixelAspectX() const { return m_pixelAspectX; } - -void SlsQtFastImage::setViewport(double x1, double y1, double x2, double y2) { - if (!std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(x2) || - !std::isfinite(y2)) - return; - if (x2 - x1 < kMinimumViewport || y2 - y1 < kMinimumViewport) - return; - m_vpX = x1; - m_vpY = y1; - m_vpW = x2 - x1; - m_vpH = y2 - y1; - clampViewport(); - update(); -} - -void SlsQtFastImage::viewport(double &x, double &y, double &w, - double &h) const { - x = m_vpX; - y = m_vpY; - w = vpW(); - h = vpH(); -} - -void SlsQtFastImage::resetView() { - if (!hasImage()) - return; // nothing to reset yet (and 0,0,0,0 would collapse the map) - m_vpX = 0.0; - m_vpY = 0.0; - m_vpW = m_nx; - m_vpH = m_ny; - if (onZoomChanged) - onZoomChanged(0.0, 0.0, double(m_nx), double(m_ny)); + m_imageDirty = true; update(); } @@ -225,102 +62,269 @@ int SlsQtFastImage::imageWidth() const { return m_nx; } int SlsQtFastImage::imageHeight() const { return m_ny; } -QPointF SlsQtFastImage::widgetToData(const QPointF &widgetPos) const { +double SlsQtFastImage::value(int ix, int iy) const { + return m_data[static_cast(iy) * m_nx + ix]; +} + +// --------------------------------------------------------------------------- +// colour mapping +// --------------------------------------------------------------------------- +void SlsQtFastImage::setPalette(plot::Palette palette) { + if (palette == m_palette) + return; + m_palette = palette; + m_imageDirty = true; + update(); + emit colorMapChanged(); +} + +plot::Palette SlsQtFastImage::palette() const { return m_palette; } + +void SlsQtFastImage::setLogScale(bool on) { + if (on == m_logScale) + return; + m_logScale = on; + m_histogramAge.invalidate(); + m_imageDirty = true; + update(); + emit colorMapChanged(); +} + +bool SlsQtFastImage::logScale() const { return m_logScale; } + +void SlsQtFastImage::setColorRange(double lo, double hi) { + if (lo == m_colorLo && hi == m_colorHi) + return; + m_colorLo = lo; + m_colorHi = hi; + m_histogramAge.invalidate(); + m_imageDirty = true; + update(); + emit colorMapChanged(); +} + +void SlsQtFastImage::colorRange(double &lo, double &hi) const { + lo = m_colorLo; + hi = m_colorHi; +} + +void SlsQtFastImage::setInterpolate(bool on) { + m_interpolate = on; + update(); +} + +bool SlsQtFastImage::interpolate() const { return m_interpolate; } + +const std::vector &SlsQtFastImage::histogram() const { + return m_histogram; +} + +void SlsQtFastImage::histogramRange(double &lo, double &hi) const { + lo = m_histogramLo; + hi = m_histogramHi; +} + +void SlsQtFastImage::renderImage() { + m_imageDirty = false; + if (m_image.size() != QSize(m_nx, m_ny)) + m_image = QImage(m_nx, m_ny, QImage::Format_RGB32); + + const QRgb *lut = plot::paletteLut(m_palette); + const bool log = m_logScale; + const double lo = log ? plot::logClamp(m_colorLo) : m_colorLo; + const double hi = log ? plot::logClamp(m_colorHi) : m_colorHi; + const double toIndex = 255.0 / (hi > lo ? hi - lo : 1.0); + + for (int y = 0; y < m_ny; ++y) { + // QImage rows run top down: this is the only place that flips y + auto *line = reinterpret_cast(m_image.scanLine(m_ny - 1 - y)); + const double *row = m_data.data() + static_cast(y) * m_nx; + for (int x = 0; x < m_nx; ++x) { + const double v = row[x]; + if (!std::isfinite(v)) { + line[x] = lut[0]; + continue; + } + const double index = ((log ? plot::logClamp(v) : v) - lo) * toIndex; + line[x] = lut[static_cast(std::clamp(index, 0.0, 255.0))]; + } + } + + // Walking the frame a second time is cheap, but the histogram is only + // looked at by a person, so a few times per second is enough. + if (!m_histogramAge.isValid() || + m_histogramAge.elapsed() > kHistogramIntervalMs) + updateHistogram(); +} + +void SlsQtFastImage::updateHistogram() { + m_histogramAge.start(); + const bool log = m_logScale; + double lo = log ? plot::logClamp(m_colorLo) : m_colorLo; + double hi = log ? plot::logClamp(m_colorHi) : m_colorHi; + if (!std::isfinite(lo) || !std::isfinite(hi)) { + lo = 0.0; + hi = 1.0; + } + if (!(hi > lo)) + hi = lo + 1.0; + const double margin = 0.5 * (hi - lo); + m_histogramLo = lo - margin; + m_histogramHi = hi + margin; + + m_histogram.assign(kHistogramBins, 0); + const double toBin = kHistogramBins / (m_histogramHi - m_histogramLo); + for (const double raw : m_data) { + if (!std::isfinite(raw)) + continue; + const double v = log ? plot::logClamp(raw) : raw; + if (v < m_histogramLo || v > m_histogramHi) + continue; + const int bin = static_cast((v - m_histogramLo) * toBin); + ++m_histogram[std::min(bin, kHistogramBins - 1)]; + } + emit histogramChanged(); +} + +// --------------------------------------------------------------------------- +// viewport +// --------------------------------------------------------------------------- +void SlsQtFastImage::setViewport(double x1, double y1, double x2, double y2) { + if (!std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(x2) || + !std::isfinite(y2)) + return; + if (x2 - x1 < kMinimumViewport || y2 - y1 < kMinimumViewport) + return; + m_viewport = QRectF(x1, y1, x2 - x1, y2 - y1); + clampViewport(); + update(); +} + +void SlsQtFastImage::viewport(double &x, double &y, double &w, + double &h) const { + x = m_viewport.x(); + y = m_viewport.y(); + w = m_viewport.width(); + h = m_viewport.height(); +} + +void SlsQtFastImage::resetView() { if (!hasImage()) - return QPointF(0.0, 0.0); - const Fit fit = computeFit(); - if (!(fit.sx > 0.0) || !(fit.sy > 0.0)) - return QPointF(0.0, 0.0); - const double x = - m_vpX + (widgetPos.x() - fit.ir.left() - fit.ox) / fit.sx; - const double y = (m_vpY + vpH()) - - (widgetPos.y() - fit.ir.top() - fit.oy) / fit.sy; - return QPointF(x, y); + return; + m_viewport = QRectF(0, 0, m_nx, m_ny); + update(); + emit viewportChanged(m_viewport); +} + +void SlsQtFastImage::clampViewport() { + if (!hasImage()) + return; + const double nx = m_nx; + const double ny = m_ny; + const double w = + std::clamp(m_viewport.width(), std::min(kMinimumViewport, nx), nx); + const double h = + std::clamp(m_viewport.height(), std::min(kMinimumViewport, ny), ny); + const double x = std::clamp(m_viewport.x(), 0.0, nx - w); + const double y = std::clamp(m_viewport.y(), 0.0, ny - h); + m_viewport = QRectF(x, y, w, h); +} + +// A zoomed viewport takes the shape of the plot area so the image fills it; +// the whole image is shown with empty borders instead. +void SlsQtFastImage::matchViewportToWindow() { + if (!hasImage()) + return; + double w = m_viewport.width(); + double h = m_viewport.height(); + if (w >= m_nx - 0.5 && h >= m_ny - 0.5) + return; + const QRect plot = plotRect(); + const double aspect = double(plot.width()) / plot.height(); + if (w / h > aspect) + h = w / aspect; + else + w = h * aspect; + if (w > m_nx) { + h *= m_nx / w; + w = m_nx; + } + if (h > m_ny) { + w *= m_ny / h; + h = m_ny; + } + const QPointF center = m_viewport.center(); + m_viewport = QRectF(center.x() - w / 2, center.y() - h / 2, w, h); + clampViewport(); + emit viewportChanged(m_viewport); +} + +void SlsQtFastImage::zoomAt(const QPointF &widgetPos, double factor) { + const QPointF anchor = mapping().toData(widgetPos); + const double fx = (anchor.x() - m_viewport.x()) / m_viewport.width(); + const double fy = (anchor.y() - m_viewport.y()) / m_viewport.height(); + m_viewport.setSize(m_viewport.size() * factor); + clampViewport(); + // keep the point under the cursor where it is + m_viewport.moveTo(anchor.x() - fx * m_viewport.width(), + anchor.y() - fy * m_viewport.height()); + clampViewport(); + update(); + emit viewportChanged(m_viewport); +} + +QRect SlsQtFastImage::plotRect() const { + int left = 0, top = 0, right = 0, bottom = 0; + if (m_axesVisible) { + left = m_theme.leftMargin; + top = m_theme.topMargin; + right = m_theme.rightMargin; + bottom = m_theme.bottomMargin; + } + if (!m_title.isEmpty()) + top += QFontMetrics(m_titleFont).height() + 4; + const int axisTitleHeight = QFontMetrics(m_axisTitleFont).height(); + if (!m_xTitle.isEmpty()) + bottom += axisTitleHeight + 4; + if (!m_yTitle.isEmpty()) + left += axisTitleHeight + 6; + return QRect(left, top, std::max(10, width() - left - right), + std::max(10, height() - top - bottom)); +} + +SlsQtFastImage::Mapping SlsQtFastImage::mapping() const { + Mapping m; + m.plot = plotRect(); + if (!hasImage()) + return m; + m.scale = std::min(m.plot.width() / m_viewport.width(), + m.plot.height() / m_viewport.height()); + // the viewport is centred in the plot area + const double left = + m.plot.left() + (m.plot.width() - m_viewport.width() * m.scale) / 2; + const double top = + m.plot.top() + (m.plot.height() - m_viewport.height() * m.scale) / 2; + m.origin = QPointF(left - m_viewport.x() * m.scale, + top + (m_viewport.y() + m_viewport.height()) * m.scale); + return m; +} + +QPointF SlsQtFastImage::widgetToData(const QPointF &widgetPos) const { + return hasImage() ? mapping().toData(widgetPos) : QPointF(); } QPointF SlsQtFastImage::dataToWidget(const QPointF &dataPos) const { - if (!hasImage()) - return QPointF(0.0, 0.0); - const Fit fit = computeFit(); - const double wx = fit.ir.left() + fit.ox + (dataPos.x() - m_vpX) * fit.sx; - const double wy = fit.ir.top() + fit.oy + - ((m_vpY + vpH()) - dataPos.y()) * fit.sy; - return QPointF(wx, wy); + return hasImage() ? mapping().toWidget(dataPos.x(), dataPos.y()) + : QPointF(); } -// --------------------------------------------------------------------------- -// overlays / ROI editor -// --------------------------------------------------------------------------- -void SlsQtFastImage::setRoiRect(double x0, double y0, double x1, double y1, - bool on) { - m_roiX0 = x0; - m_roiY0 = y0; - m_roiX1 = x1; - m_roiY1 = y1; - m_roiOn = on; - update(); +void SlsQtFastImage::setZoomEnabled(bool on) { + m_zoomEnabled = on; + if (!on) + m_panning = false; } -void SlsQtFastImage::setRoiRectVisible(bool on) { - m_roiOn = on; - update(); -} - -bool SlsQtFastImage::roiRect(double &x0, double &y0, double &x1, - double &y1) const { - x0 = m_roiX0; - y0 = m_roiY0; - x1 = m_roiX1; - y1 = m_roiY1; - return m_roiOn; -} - -void SlsQtFastImage::setOverlayRects(const std::vector &rects) { - m_overlays = rects; - update(); -} - -void SlsQtFastImage::clearOverlayRects() { - m_overlays.clear(); - update(); -} - -const std::vector &SlsQtFastImage::overlayRects() const { - return m_overlays; -} - -void SlsQtFastImage::setReceiverRoiRect(double x0, double y0, double x1, - double y1, bool on) { - m_rxX0 = x0; - m_rxY0 = y0; - m_rxX1 = x1; - m_rxY1 = y1; - m_rxOn = on; - update(); -} - -void SlsQtFastImage::clearReceiverRoiRect() { - m_rxOn = false; - update(); -} - -void SlsQtFastImage::beginRoiEdit(bool on) { - m_roiEdit = on; - m_roiGrab = 0; - setCursor(on ? Qt::CrossCursor : Qt::ArrowCursor); - update(); -} - -bool SlsQtFastImage::roiEditActive() const { return m_roiEdit; } - -void SlsQtFastImage::setColorBarVisible(bool on) { - m_showBar = on; - update(); -} - -bool SlsQtFastImage::colorBarVisible() const { return m_showBar; } - -bool SlsQtFastImage::isScaleDragging() const { return m_dragScale; } +bool SlsQtFastImage::zoomEnabled() const { return m_zoomEnabled; } void SlsQtFastImage::setAxesVisible(bool on) { m_axesVisible = on; @@ -329,20 +333,23 @@ void SlsQtFastImage::setAxesVisible(bool on) { bool SlsQtFastImage::axesVisible() const { return m_axesVisible; } -void SlsQtFastImage::setZoomEnabled(bool on) { - m_zoomEnabled = on; - if (!on) { - m_dragging = false; - m_dragScale = false; - } +// --------------------------------------------------------------------------- +// overlays and titles +// --------------------------------------------------------------------------- +void SlsQtFastImage::setOverlayRects(const std::vector &rects) { + m_overlayRects = rects; update(); } -bool SlsQtFastImage::zoomEnabled() const { return m_zoomEnabled; } +const std::vector &SlsQtFastImage::overlayRects() const { + return m_overlayRects; +} + +void SlsQtFastImage::setOverlayLines(const std::vector &lines) { + m_overlayLines = lines; + update(); +} -// --------------------------------------------------------------------------- -// titles -// --------------------------------------------------------------------------- void SlsQtFastImage::setTitle(const QString &title) { m_title = title; update(); @@ -378,835 +385,230 @@ void SlsQtFastImage::setAxisTitleFont(const QFont &f) { QFont SlsQtFastImage::axisTitleFont() const { return m_axisTitleFont; } -void SlsQtFastImage::setTickFont(const QFont &f) { - m_tickFont = f; - update(); -} - -QFont SlsQtFastImage::tickFont() const { return m_tickFont; } - -// --------------------------------------------------------------------------- -// layout helpers -// --------------------------------------------------------------------------- -QRect SlsQtFastImage::imageRect() const { - const QFontMetrics titleFm(m_titleFont); - const QFontMetrics axisFm(m_axisTitleFont); - int top = m_axesVisible ? m_theme.topMargin : 0; - int bottom = m_axesVisible ? m_theme.bottomMargin : 0; - int left = m_axesVisible ? m_theme.leftMargin : 0; - int right = m_axesVisible ? m_theme.rightMargin : 0; - if (!m_title.isEmpty()) - top += titleFm.height() + 4; - if (!m_xTitle.isEmpty()) - bottom += axisFm.height() + 4; - if (!m_yTitle.isEmpty()) - left += axisFm.height() + 6; - if (m_showBar) - right += kScaleBarWidth; - int x0 = left, y0 = top; - int x1 = width() - right, y1 = height() - bottom; - if (x1 - x0 < 10) - x1 = x0 + 10; - if (y1 - y0 < 10) - y1 = y0 + 10; - return QRect(x0, y0, x1 - x0, y1 - y0); -} - -QRect SlsQtFastImage::scaleRect() const { - if (!m_showBar) - return QRect(); - const QRect ir = imageRect(); - return QRect(ir.right() + 4, ir.top(), kScaleBarWidth - 4, ir.height()); -} - -SlsQtFastImage::Fit SlsQtFastImage::computeFit() const { - Fit f; - f.ir = imageRect(); - if (!hasImage() || !(vpW() > 0.0) || !(vpH() > 0.0)) - return f; - if (m_pixelAspectX != 1.0) { - const double fitY = double(f.ir.height()) / vpH(); - const double fitX = double(f.ir.width()) / (vpW() * m_pixelAspectX); - f.sy = std::min(fitY, fitX); - f.sx = f.sy * m_pixelAspectX; - } else { - const double fitX = double(f.ir.width()) / vpW(); - const double fitY = double(f.ir.height()) / vpH(); - f.sx = f.sy = std::min(fitX, fitY); - } - f.ox = (f.ir.width() - vpW() * f.sx) * 0.5; - f.oy = (f.ir.height() - vpH() * f.sy) * 0.5; - return f; -} - -// Keeps the viewport inside the image and no smaller than the minimum. -void SlsQtFastImage::clampViewport() { - if (!hasImage()) - return; - if (m_vpW > m_nx) - m_vpW = m_nx; - if (m_vpH > m_ny) - m_vpH = m_ny; - if (m_vpW < std::min(kMinimumViewport, double(m_nx))) - m_vpW = std::min(kMinimumViewport, double(m_nx)); - if (m_vpH < std::min(kMinimumViewport, double(m_ny))) - m_vpH = std::min(kMinimumViewport, double(m_ny)); - if (m_vpX < 0.0) - m_vpX = 0.0; - if (m_vpX + vpW() > m_nx) - m_vpX = m_nx - vpW(); - if (m_vpY < 0.0) - m_vpY = 0.0; - if (m_vpY + vpH() > m_ny) - m_vpY = m_ny - vpH(); -} - -// The whole-frame view is letterboxed on purpose; any other view keeps the -// shape of the plot area so the image always fills it (used on resize and -// when the viewport is initialised for zoom, not during wheel zoom). -void SlsQtFastImage::matchViewportToWindow() { - if (!hasImage()) - return; - if (vpW() >= m_nx - 0.5 && vpH() >= m_ny - 0.5) - return; - const QRect ir = imageRect(); - if (ir.width() <= 0 || ir.height() <= 0) - return; - const double ar = double(ir.width()) / double(ir.height()) / m_pixelAspectX; - double w = vpW(), h = vpH(); - if (w / h > ar) - h = w / ar; // too wide -> grow vertically - else - w = h * ar; // too tall -> grow horizontally - if (w > m_nx) { // grown past the sensor: shrink both, keep the shape - h *= m_nx / w; - w = m_nx; - } - if (h > m_ny) { - w *= m_ny / h; - h = m_ny; - } - const double cx = m_vpX + vpW() / 2.0, cy = m_vpY + vpH() / 2.0; - m_vpW = w; - m_vpH = h; - m_vpX = cx - w / 2.0; - m_vpY = cy - h / 2.0; - clampViewport(); - if (onZoomChanged) - onZoomChanged(m_vpX, m_vpY, m_vpX + vpW(), m_vpY + vpH()); -} - -void SlsQtFastImage::resizeEvent(QResizeEvent *) { - matchViewportToWindow(); - update(); -} - -// --------------------------------------------------------------------------- -// composition: one scanline write per image row, exactly one flip -// --------------------------------------------------------------------------- -void SlsQtFastImage::renderImage() { - m_dirty = false; - if (!m_data || m_nx <= 0 || m_ny <= 0) - return; - if (m_image.size() != QSize(m_nx, m_ny) || - m_image.format() != QImage::Format_RGB32) - m_image = QImage(m_nx, m_ny, QImage::Format_RGB32); - - // log: values <= 0 are capped at 1e-2 (log10 = -2), so an empty pixel is - // still distinguishable instead of becoming -inf - const double loD = m_logScale ? sls::plot::logClamp(m_clo) : m_clo; - const double hiD = m_logScale ? sls::plot::logClamp(m_chi) : m_chi; - const double range = (hiD > loD) ? (hiD - loD) : 1.0; - const double scale = 255.0 / range; - const bool logScale = m_logScale; - const bool zeroWhite = m_zeroWhite; - const QRgb *palette = m_palette; - - for (int y = 0; y < m_ny; y++) { - // QImage row 0 is the top, data row 0 is the bottom: the flip happens - // here, once, and nowhere else. - QRgb *line = reinterpret_cast(m_image.scanLine(m_ny - 1 - y)); - const float *src = m_data + static_cast(y) * size_t(m_nx); - if (logScale) { - for (int x = 0; x < m_nx; x++) { - const double v = src[x]; - if (!std::isfinite(v)) { - line[x] = palette[0]; - continue; - } - if (zeroWhite && !(v > 0.0)) { - line[x] = kWhite; - continue; - } - int idx = int((sls::plot::logClamp(v) - loD) * scale); - if (idx < 0) - idx = 0; - else if (idx > 255) - idx = 255; - line[x] = palette[idx]; - } - } else { - for (int x = 0; x < m_nx; x++) { - const double v = src[x]; - if (!std::isfinite(v)) { - line[x] = palette[0]; - continue; - } - if (zeroWhite && !(v > 0.0)) { - line[x] = kWhite; - continue; - } - int idx = int((v - loD) * scale); - if (idx < 0) - idx = 0; - else if (idx > 255) - idx = 255; - line[x] = palette[idx]; - } - } - } - - // Histogram for the scale panel: walking the whole frame is cheap enough at - // the image cadence, but the panel only needs the shape, so a few times a - // second is plenty. Bin over the window the strip displays (the colour - // range widened by half a range; log space when log), skip values outside - // it - a photon map accumulates to thousands of counts while its scale - // shows 0..12, so full-range binning would put the whole window in one bin. - const qint64 now = QDateTime::currentMSecsSinceEpoch(); - if (m_hist.empty() || m_hist.size() != 256 || now - m_histMs > 300) { - m_histMs = now; - double dlo, dhi; - if (m_logScale) { - const double a = sls::plot::logClamp(m_clo); - const double b = sls::plot::logClamp(m_chi); - dlo = a; - dhi = b; - } else { - dlo = m_clo; - dhi = m_chi; - } - if (!std::isfinite(dlo) || !std::isfinite(dhi)) - dlo = 0.0, dhi = 1.0; - if (!(dhi > dlo)) - dhi = dlo + 1.0; - const double span = dhi - dlo; - double hlo = dlo - 0.5 * span; - double hhi = dhi + 0.5 * span; - if (!(hhi > hlo)) - hhi = hlo + 1.0; - m_histLo = hlo; - m_histHi = hhi; - m_hist.assign(256, 0); - const double sc = 255.0 / (hhi - hlo); - const size_t n = size_t(m_nx) * size_t(m_ny); - for (size_t p = 0; p < n; p++) { - const double raw = m_data[p]; - if (!std::isfinite(raw)) - continue; - const double v = logScale ? sls::plot::logClamp(raw) : raw; - if (v < hlo || v > hhi) - continue; // outside the visible window - int b = int((v - hlo) * sc); - if (b < 0) - b = 0; - else if (b > 255) - b = 255; - m_hist[b]++; - } - if (onImageChanged) - onImageChanged(); - } -} - // --------------------------------------------------------------------------- // painting // --------------------------------------------------------------------------- void SlsQtFastImage::paintEvent(QPaintEvent *) { - if (m_dirty) - renderImage(); QPainter p(this); p.fillRect(rect(), m_theme.background); if (!hasImage()) return; + if (m_imageDirty) + renderImage(); - const Fit fit = computeFit(); - m_sx = fit.sx; - drawImage(p, fit); - drawAxes(p, fit); - drawPixelDetail(p, fit); - // Overlays last (before titles) so a ROI edge that lies on a pixel - // boundary is not hidden by the pixel grid. - drawOverlays(p, fit); - if (onPaintOverlay) { - // Data-space overlay hook (contour lines etc.), clipped like the image. - p.save(); - p.setClipRect(fit.ir); - const QTransform dataToWidget( - fit.sx, 0.0, 0.0, -fit.sy, - fit.ir.left() + fit.ox - m_vpX * fit.sx, - fit.ir.top() + fit.oy + (m_vpY + vpH()) * fit.sy); - onPaintOverlay(p, dataToWidget); - p.restore(); - } - drawTitles(p, fit); - if (m_showBar) - drawColorBar(p); + const Mapping m = mapping(); + drawImage(p, m); + drawAxes(p, m); + drawPixelDetail(p, m); + drawOverlays(p, m); + drawTitles(p, m); } -void SlsQtFastImage::drawImage(QPainter &p, const Fit &fit) { - const QRect ir = fit.ir; +void SlsQtFastImage::drawImage(QPainter &p, const Mapping &m) const { p.save(); - // Zoomed in, the scaled image is larger than the plot area: without this - // clip it spills over the frame and the tick labels. - p.setClipRect(ir); - p.translate(ir.left() + fit.ox, ir.top() + fit.oy); - p.scale(fit.sx, fit.sy); - // Display row of the top edge of the viewport (QImage rows are top-down). - const double topRow = double(m_ny) - (m_vpY + vpH()); - p.translate(-m_vpX, -topRow); - p.drawImage(QPoint(0, 0), m_image); + p.setClipRect(m.plot); + p.setRenderHint(QPainter::SmoothPixmapTransform, + m_interpolate && m.scale < kOutlineMinScale); + const QRectF target(m.toWidget(0, m_ny), + QSizeF(m_nx * m.scale, m_ny * m.scale)); + p.drawImage(target, m_image); p.restore(); } -void SlsQtFastImage::drawOverlays(QPainter &p, const Fit &fit) { - const QRect ir = fit.ir; - auto toWidget = [&](double x, double y) { - return QPointF(ir.left() + fit.ox + (x - m_vpX) * fit.sx, - ir.top() + fit.oy + ((m_vpY + vpH()) - y) * fit.sy); - }; - auto rectWidget = [&](double x0, double y0, double x1, double y1) { - const QRectF r(toWidget(x0, y0), toWidget(x1, y1)); - return r.normalized(); - }; - - // Overlays live in the same plot area: clip them as well. - p.save(); - p.setClipRect(ir); - - // Editable yellow ROI (gate ROI), drawn in data coordinates. - if (m_roiOn && m_roiX1 > m_roiX0 && m_roiY1 > m_roiY0) { - const QRectF r = rectWidget(m_roiX0, m_roiY0, m_roiX1, m_roiY1); - QPen pen(Qt::yellow); - pen.setWidth(m_roiEdit ? 2 : 1); - pen.setCosmetic(true); - p.setPen(pen); - p.setBrush(Qt::NoBrush); - p.drawRect(r); - if (m_roiEdit) { // corner and edge handles: what can be grabbed - const double hw = 3.0; // half handle size, in widget pixels - const double xs[3] = {r.left(), r.center().x(), r.right()}; - const double ys[3] = {r.top(), r.center().y(), r.bottom()}; - p.setBrush(QColor(255, 255, 80)); - for (int iy = 0; iy < 3; iy++) { - for (int ix = 0; ix < 3; ix++) { - if (ix == 1 && iy == 1) - continue; // centre handle would only be confusing - p.drawRect( - QRectF(xs[ix] - hw, ys[iy] - hw, 2 * hw, 2 * hw)); - } - } - } - } - - // Additional yellow rectangles (e.g. all receiver ROIs). - if (!m_overlays.empty()) { - QPen pen(Qt::yellow); - pen.setWidth(1); - pen.setCosmetic(true); - p.setPen(pen); - p.setBrush(Qt::NoBrush); - for (const QRectF &o : m_overlays) { - if (!(o.width() > 0.0) || !(o.height() > 0.0)) - continue; - p.drawRect(rectWidget(o.left(), o.top(), o.left() + o.width(), - o.top() + o.height())); - } - } - - // Red receiver-ROI box, same data coordinates. - if (m_rxOn && m_rxX1 > m_rxX0 && m_rxY1 > m_rxY0) { - QPen pen(Qt::red); - pen.setWidth(1); - pen.setCosmetic(true); - p.setPen(pen); - p.setBrush(Qt::NoBrush); - p.drawRect(rectWidget(m_rxX0, m_rxY0, m_rxX1, m_rxY1)); - } - p.restore(); // back to the full widget for the axes -} - -void SlsQtFastImage::drawAxes(QPainter &p, const Fit &fit) { +void SlsQtFastImage::drawAxes(QPainter &p, const Mapping &m) const { if (!m_axesVisible) return; - const QRect ir = fit.ir; - p.setFont(m_tickFont); - const double x0 = m_vpX, x1 = m_vpX + vpW(); - const double y0 = m_vpY, y1 = m_vpY + vpH(); - const double stepX = sls::plot::niceStep(x1 - x0, 8); - const double stepY = sls::plot::niceStep(y1 - y0, 8); - const std::vector ticksX = sls::plot::computeLinearTicks(x0, x1, 8); - const std::vector ticksY = sls::plot::computeLinearTicks(y0, y1, 8); + const QRect plot = m.plot; + const double x0 = m_viewport.x(); + const double x1 = x0 + m_viewport.width(); + const double y0 = m_viewport.y(); + const double y1 = y0 + m_viewport.height(); + const auto ticksX = plot::computeLinearTicks(x0, x1, kMaxTicks); + const auto ticksY = plot::computeLinearTicks(y0, y1, kMaxTicks); + const double stepX = plot::niceStep(x1 - x0, kMaxTicks); + const double stepY = plot::niceStep(y1 - y0, kMaxTicks); p.save(); - p.setClipRect(ir); - QPen grid(m_theme.grid); - grid.setStyle(Qt::DotLine); - QPen tick(m_theme.tick); - tick.setWidth(1); - for (double gx : ticksX) { - const double wx = fit.ir.left() + fit.ox + (gx - m_vpX) * fit.sx; - p.setPen(grid); - p.drawLine(QPointF(wx, ir.top()), QPointF(wx, ir.bottom())); - } - for (double gy : ticksY) { - const double wy = - fit.ir.top() + fit.oy + ((m_vpY + vpH()) - gy) * fit.sy; - p.setPen(grid); - p.drawLine(QPointF(ir.left(), wy), QPointF(ir.right(), wy)); - } - p.restore(); + p.setFont(m_theme.tickFont); - // ticks and labels outside the frame - p.save(); - p.setPen(tick); - for (double gx : ticksX) { - const double wx = fit.ir.left() + fit.ox + (gx - m_vpX) * fit.sx; - p.drawLine(QPointF(wx, ir.bottom() + 1), QPointF(wx, ir.bottom() + 4)); - p.setPen(m_theme.tick); - p.drawText(QRectF(wx - 30, ir.bottom() + 5, 60, 14), - Qt::AlignHCenter | Qt::AlignTop, - sls::plot::formatTick(gx, stepX)); - p.setPen(tick); + p.setClipRect(plot); + p.setPen(QPen(m_theme.grid, 1, Qt::DotLine)); + for (const double x : ticksX) { + const double wx = m.toWidget(x, 0).x(); + p.drawLine(QPointF(wx, plot.top()), QPointF(wx, plot.bottom())); } - for (double gy : ticksY) { - const double wy = - fit.ir.top() + fit.oy + ((m_vpY + vpH()) - gy) * fit.sy; - p.drawLine(QPointF(ir.left() - 4, wy), QPointF(ir.left() - 1, wy)); - p.drawText(QRectF(ir.left() - 50, wy - 7, 44, 14), + for (const double y : ticksY) { + const double wy = m.toWidget(0, y).y(); + p.drawLine(QPointF(plot.left(), wy), QPointF(plot.right(), wy)); + } + p.setClipping(false); + + p.setPen(m_theme.tick); + for (const double x : ticksX) { + const double wx = m.toWidget(x, 0).x(); + p.drawLine(QPointF(wx, plot.bottom() + 1), + QPointF(wx, plot.bottom() + 4)); + p.drawText(QRectF(wx - 30, plot.bottom() + 5, 60, 14), + Qt::AlignHCenter | Qt::AlignTop, plot::formatTick(x, stepX)); + } + for (const double y : ticksY) { + const double wy = m.toWidget(0, y).y(); + p.drawLine(QPointF(plot.left() - 4, wy), QPointF(plot.left() - 1, wy)); + p.drawText(QRectF(plot.left() - 50, wy - 7, 44, 14), Qt::AlignRight | Qt::AlignVCenter, - sls::plot::formatTick(gy, stepY)); + plot::formatTick(y, stepY)); } - p.setPen(QPen(m_theme.frame)); - p.setBrush(Qt::NoBrush); - p.drawRect(ir.adjusted(0, 0, -1, -1)); + p.setPen(m_theme.frame); + p.drawRect(plot.adjusted(0, 0, -1, -1)); p.restore(); } -void SlsQtFastImage::drawPixelDetail(QPainter &p, const Fit &fit) { - // Pixel outlines and in-pixel values, once one pixel is big enough. The - // thresholds are computed from the fit scale, not from a fixed zoom level. - if (m_sx < 16.0) +void SlsQtFastImage::drawPixelDetail(QPainter &p, const Mapping &m) const { + if (m.scale < kOutlineMinScale) return; - const QRect ir = fit.ir; - const double x0 = m_vpX, x1 = m_vpX + vpW(); - const double y0 = m_vpY, y1 = m_vpY + vpH(); + const QRect plot = m.plot; + const double right = m_viewport.x() + m_viewport.width(); + const double top = m_viewport.y() + m_viewport.height(); + const int ix0 = std::max(0, static_cast(std::floor(m_viewport.x()))); + const int iy0 = std::max(0, static_cast(std::floor(m_viewport.y()))); + const int ix1 = std::min(m_nx, static_cast(std::ceil(right))); + const int iy1 = std::min(m_ny, static_cast(std::ceil(top))); + p.save(); - p.setClipRect(ir); - // thin outline around every pixel (only when a sane number is visible) - if (vpW() <= 256 && vpH() <= 256) { - QPen px(QColor(55, 55, 55)); - px.setCosmetic(true); - p.setPen(px); - for (int gx = int(std::floor(x0)); gx <= int(std::ceil(x1)); gx++) { - const double wx = ir.left() + fit.ox + (gx - m_vpX) * fit.sx; - if (wx < ir.left() - 0.5 || wx > ir.right() + 0.5) - continue; - p.drawLine(QPointF(wx, ir.top()), QPointF(wx, ir.bottom())); - } - for (int gy = int(std::floor(y0)); gy <= int(std::ceil(y1)); gy++) { - const double wy = - ir.top() + fit.oy + ((m_vpY + vpH()) - gy) * fit.sy; - if (wy < ir.top() - 0.5 || wy > ir.bottom() + 0.5) - continue; - p.drawLine(QPointF(ir.left(), wy), QPointF(ir.right(), wy)); - } + p.setClipRect(plot); + p.setPen(QColor(55, 55, 55)); + for (int ix = ix0; ix <= ix1; ++ix) { + const double wx = m.toWidget(ix, 0).x(); + p.drawLine(QPointF(wx, plot.top()), QPointF(wx, plot.bottom())); } - if (m_sx >= 50.0 && vpW() <= 64 && vpH() <= 64) { - const int maxChars = m_integerValues ? 5 : 6; - const double cell = std::min(fit.sx, fit.sy); - const double bySize = cell * 0.30; - const double byWidth = fit.sx * 0.92 / (0.62 * maxChars); - QFont f = m_tickFont; - f.setPixelSize(std::max( - 7, std::min(20, int(std::min(bySize, byWidth))))); + for (int iy = iy0; iy <= iy1; ++iy) { + const double wy = m.toWidget(0, iy).y(); + p.drawLine(QPointF(plot.left(), wy), QPointF(plot.right(), wy)); + } + + if (m.scale >= kLabelMinScale) { + QFont f = m_theme.tickFont; + f.setPixelSize(std::clamp(static_cast(m.scale * 0.25), 7, 20)); p.setFont(f); - for (int gy = int(std::floor(y0)); gy <= int(std::ceil(y1)); gy++) { - if (gy < 0 || gy >= m_ny) - continue; - for (int gx = int(std::floor(x0)); gx <= int(std::ceil(x1)); gx++) { - if (gx < 0 || gx >= m_nx) - continue; - const double v = m_data[gx + gy * m_nx]; + for (int iy = iy0; iy < iy1; ++iy) { + for (int ix = ix0; ix < ix1; ++ix) { + const double v = value(ix, iy); if (!std::isfinite(v)) continue; - // text colour from the pixel that was actually painted - const QRgb c = m_image.pixel(gx, m_ny - 1 - gy); - const int lum = - (qRed(c) * 299 + qGreen(c) * 587 + qBlue(c) * 114) / 1000; - p.setPen(lum > 140 ? QColor(15, 15, 15) - : QColor(245, 245, 245)); - const QString txt = - m_integerValues - ? QString::number(qint64(std::llround(v))) - : QString::number(v, 'f', 1); - const QPointF ctr = - QPointF(ir.left() + fit.ox + (gx + 0.5 - m_vpX) * fit.sx, - ir.top() + fit.oy + - ((m_vpY + vpH()) - (gy + 0.5)) * fit.sy); - p.drawText(QRectF(ctr.x() - fit.sx * 0.5, - ctr.y() - fit.sy * 0.5, fit.sx, fit.sy), - Qt::AlignCenter, txt); + // dark text on bright pixels and the other way round + const QRgb c = m_image.pixel(ix, m_ny - 1 - iy); + p.setPen(qGray(c) > 140 ? QColor(15, 15, 15) + : QColor(245, 245, 245)); + const QRectF cell(m.toWidget(ix, iy + 1), + QSizeF(m.scale, m.scale)); + p.drawText(cell, Qt::AlignCenter, formatValue(v)); } } } p.restore(); } -void SlsQtFastImage::drawTitles(QPainter &p, const Fit &fit) { - const QRect ir = fit.ir; +void SlsQtFastImage::drawOverlays(QPainter &p, const Mapping &m) const { + p.save(); + p.setClipRect(m.plot); + p.setBrush(Qt::NoBrush); + + p.setPen(QColor(255, 255, 255, 190)); + for (const QLineF &l : m_overlayLines) + p.drawLine(m.toWidget(l.x1(), l.y1()), m.toWidget(l.x2(), l.y2())); + + p.setPen(Qt::yellow); + for (const QRectF &r : m_overlayRects) { + if (r.width() > 0.0 && r.height() > 0.0) + p.drawRect(QRectF(m.toWidget(r.x(), r.y() + r.height()), + r.size() * m.scale)); + } + p.restore(); +} + +void SlsQtFastImage::drawTitles(QPainter &p, const Mapping &m) const { + const QRect plot = m.plot; + p.save(); + p.setPen(m_theme.text); if (!m_title.isEmpty()) { p.setFont(m_titleFont); - p.setPen(m_theme.text); - p.drawText(QRectF(0, 1, width(), ir.top() - 2), - Qt::AlignHCenter | Qt::AlignVCenter, m_title); - } - if (!m_yTitle.isEmpty()) { - const QFontMetrics fm(m_axisTitleFont); - p.save(); - p.setFont(m_axisTitleFont); - p.setPen(m_theme.text); - p.translate(fm.height() / 2.0 + 4.0, ir.center().y()); - p.rotate(-90.0); - p.drawText(QRectF(-ir.height() / 2.0, -fm.height() / 2.0, - ir.height(), fm.height()), - Qt::AlignCenter, m_yTitle); - p.restore(); + p.drawText(QRectF(0, 1, width(), plot.top() - 2), Qt::AlignCenter, + m_title); } + p.setFont(m_axisTitleFont); if (!m_xTitle.isEmpty()) { - p.setFont(m_axisTitleFont); - p.setPen(m_theme.text); - p.drawText(QRectF(ir.left(), ir.bottom() + m_theme.bottomMargin, - ir.width(), - height() - ir.bottom() - m_theme.bottomMargin), + const int y = plot.bottom() + m_theme.bottomMargin; + p.drawText(QRectF(plot.left(), y, plot.width(), height() - y), Qt::AlignHCenter | Qt::AlignTop, m_xTitle); } -} - -void SlsQtFastImage::drawColorBar(QPainter &p) { - const QRect sr = scaleRect(); - if (sr.height() <= 0) - return; - for (int yy = sr.top(); yy <= sr.bottom(); yy++) { - const double frac = 1.0 - double(yy - sr.top()) / sr.height(); - int idx = int(frac * 255.0); - if (idx < 0) - idx = 0; - else if (idx > 255) - idx = 255; - p.setPen(m_palette[idx]); - p.drawLine(sr.left(), yy, sr.right(), yy); + if (!m_yTitle.isEmpty()) { + const double h = p.fontMetrics().height(); + p.translate(h / 2 + 4, plot.center().y()); + p.rotate(-90); + p.drawText(QRectF(-plot.height() / 2.0, -h / 2, plot.height(), h), + Qt::AlignCenter, m_yTitle); } - p.setPen(m_theme.frame); - p.drawRect(sr.adjusted(-1, -1, 1, 1)); - p.setFont(m_tickFont); - p.setPen(m_theme.text); - p.drawText(sr.left(), sr.top() + 1, sr.width(), 12, Qt::AlignCenter, - QString::number(m_chi, 'g', 4)); - p.drawText(sr.left(), sr.bottom() - 11, sr.width(), 12, Qt::AlignCenter, - QString::number(m_clo, 'g', 4)); -} - -double SlsQtFastImage::valueAt(const QPoint &pos) const { - const QRect sr = scaleRect(); - if (sr.height() <= 0 || !sr.contains(pos)) - return m_clo - 1.0; - const double frac = 1.0 - double(pos.y() - sr.top()) / sr.height(); - return m_clo + frac * (m_chi - m_clo); + p.restore(); } // --------------------------------------------------------------------------- // interaction // --------------------------------------------------------------------------- void SlsQtFastImage::mousePressEvent(QMouseEvent *e) { - if (e->button() != Qt::LeftButton) + if (e->button() != Qt::LeftButton || !m_zoomEnabled || !hasImage()) return; - const QPoint ip = e->position().toPoint(); - if (m_roiEdit && hasImage()) { - // which part of the yellow rectangle was grabbed? - const QPointF d = widgetToData(QPointF(ip)); - const QPointF d2 = widgetToData(QPointF(ip + QPoint(8, 0))); - const double tol = std::max(1e-9, std::abs(d2.x() - d.x())); - const bool nearL = std::abs(d.x() - m_roiX0) <= tol; - const bool nearR = std::abs(d.x() - m_roiX1) <= tol; - const bool nearB = std::abs(d.y() - m_roiY0) <= tol; - const bool nearT = std::abs(d.y() - m_roiY1) <= tol; - const bool inX = d.x() >= m_roiX0 - tol && d.x() <= m_roiX1 + tol; - const bool inY = d.y() >= m_roiY0 - tol && d.y() <= m_roiY1 + tol; - m_roiGrab = 0; - if (nearL && nearB) - m_roiGrab = 6; - else if (nearR && nearB) - m_roiGrab = 7; - else if (nearL && nearT) - m_roiGrab = 8; - else if (nearR && nearT) - m_roiGrab = 9; - else if (nearL && inY) - m_roiGrab = 2; - else if (nearR && inY) - m_roiGrab = 3; - else if (nearB && inX) - m_roiGrab = 4; - else if (nearT && inX) - m_roiGrab = 5; - else if (inX && inY) - m_roiGrab = 1; - else - m_roiGrab = 10; // start a new rectangle at the cursor - m_roiPress = d; - m_roiStart[0] = m_roiX0; - m_roiStart[1] = m_roiY0; - m_roiStart[2] = m_roiX1; - m_roiStart[3] = m_roiY1; - if (m_roiGrab == 10) { - m_roiX0 = m_roiX1 = std::max(0.0, std::min(double(m_nx), d.x())); - m_roiY0 = m_roiY1 = std::max(0.0, std::min(double(m_ny), d.y())); - m_roiOn = true; - } - update(); - return; - } - const QRect sr = scaleRect(); - if (sr.height() > 0 && sr.contains(ip)) { - m_dragScale = true; - m_dragScaleY = ip.y(); - m_dragClo = m_clo; - m_dragChi = m_chi; - m_dragMax = (ip.y() < sr.top() + sr.height() / 2); - setCursor(Qt::SizeVerCursor); - return; - } - if (!m_zoomEnabled) - return; // fixed view (gain map): no panning - m_dragging = true; - m_lastPos = QPointF(ip); - m_dragVpX = m_vpX; - m_dragVpY = m_vpY; + m_panning = true; + m_panStart = e->position(); + m_panStartViewport = m_viewport.topLeft(); setCursor(Qt::ClosedHandCursor); } void SlsQtFastImage::mouseMoveEvent(QMouseEvent *e) { - const QPointF pos = e->position(); - if (m_roiEdit && hasImage()) { - const QPointF d = widgetToData(pos); - const double x = std::max(0.0, std::min(double(m_nx), d.x())); - const double y = std::max(0.0, std::min(double(m_ny), d.y())); - constexpr double kMin = 2.0; // a ROI smaller than this is unusable - if (m_roiGrab == 10) { // dragging out a new rectangle - m_roiX0 = std::min(m_roiPress.x(), x); - m_roiX1 = std::max(m_roiPress.x(), x); - m_roiY0 = std::min(m_roiPress.y(), y); - m_roiY1 = std::max(m_roiPress.y(), y); - m_roiOn = true; - } else if (m_roiGrab == 1) { // move the whole rectangle - const double dx = x - m_roiPress.x(); - const double dy = y - m_roiPress.y(); - double x0 = m_roiStart[0] + dx, x1 = m_roiStart[2] + dx; - double y0 = m_roiStart[1] + dy, y1 = m_roiStart[3] + dy; - if (x0 < 0.0) { - x1 -= x0; - x0 = 0.0; - } - if (x1 > m_nx) { - x0 -= (x1 - m_nx); - x1 = m_nx; - } - if (y0 < 0.0) { - y1 -= y0; - y0 = 0.0; - } - if (y1 > m_ny) { - y0 -= (y1 - m_ny); - y1 = m_ny; - } - m_roiX0 = x0; - m_roiX1 = x1; - m_roiY0 = y0; - m_roiY1 = y1; - } else if (m_roiGrab != 0) { // one edge or one corner - double x0 = m_roiStart[0], y0 = m_roiStart[1]; - double x1 = m_roiStart[2], y1 = m_roiStart[3]; - const bool left = (m_roiGrab == 2 || m_roiGrab == 6 || - m_roiGrab == 8); - const bool right = (m_roiGrab == 3 || m_roiGrab == 7 || - m_roiGrab == 9); - const bool bottom = (m_roiGrab == 4 || m_roiGrab == 6 || - m_roiGrab == 7); - const bool top = (m_roiGrab == 5 || m_roiGrab == 8 || - m_roiGrab == 9); - if (left && x <= x1 - kMin) - x0 = x; - if (right && x >= x0 + kMin) - x1 = x; - if (bottom && y <= y1 - kMin) - y0 = y; - if (top && y >= y0 + kMin) - y1 = y; - m_roiX0 = x0; - m_roiY0 = y0; - m_roiX1 = x1; - m_roiY1 = y1; - } + if (!hasImage()) + return; + const Mapping m = mapping(); + if (m_panning) { + const QPointF delta = (e->position() - m_panStart) / m.scale; + m_viewport.moveTo(m_panStartViewport.x() - delta.x(), + m_panStartViewport.y() + delta.y()); + clampViewport(); update(); - if (m_roiGrab == 0) { // hovering: show what grabbing here would do - const QPointF dd = widgetToData(pos); - const QPointF dd2 = widgetToData(pos + QPointF(8, 0)); - const double tol = std::max(1e-9, std::abs(dd2.x() - dd.x())); - const bool nearL = std::abs(dd.x() - m_roiX0) <= tol; - const bool nearR = std::abs(dd.x() - m_roiX1) <= tol; - const bool nearB = std::abs(dd.y() - m_roiY0) <= tol; - const bool nearT = std::abs(dd.y() - m_roiY1) <= tol; - const bool inside = dd.x() >= m_roiX0 - tol && - dd.x() <= m_roiX1 + tol && - dd.y() >= m_roiY0 - tol && - dd.y() <= m_roiY1 + tol; - if ((nearL && nearT) || (nearR && nearB)) - setCursor(Qt::SizeFDiagCursor); - else if ((nearL && nearB) || (nearR && nearT)) - setCursor(Qt::SizeBDiagCursor); - else if (nearL || nearR) - setCursor(Qt::SizeHorCursor); - else if (nearT || nearB) - setCursor(Qt::SizeVerCursor); - else - setCursor(inside ? Qt::OpenHandCursor : Qt::CrossCursor); - } + emit viewportChanged(m_viewport); return; } - if (m_dragScale) { - const QRect sr = scaleRect(); - if (sr.height() <= 0) - return; - const double delta = double(e->position().toPoint().y() - m_dragScaleY) / - double(sr.height()) * (m_dragChi - m_dragClo); - if (m_dragMax) { - m_chi = m_dragChi - delta; - if (m_chi < m_clo + 1.0) - m_chi = m_clo + 1.0; - } else { - m_clo = m_dragClo - delta; - if (m_clo > m_chi - 1.0) - m_clo = m_chi - 1.0; - } - m_dirty = true; - update(); - return; - } - if (!m_dragging) { - const QPoint hp = pos.toPoint(); - const QRect ir2 = imageRect(); - const QRect sr = scaleRect(); - if (sr.height() > 0 && sr.contains(hp)) { - setCursor(Qt::SizeVerCursor); - setToolTip(QStringLiteral("Scale: %1") - .arg(valueAt(hp), 0, 'f', 0)); - } else if (ir2.contains(hp) && hasImage()) { - setCursor(Qt::OpenHandCursor); - // widgetToData() returns data rows (row 0 = bottom), matching the - // ROOT plots and the ROI list: (0,0) is the bottom-left pixel. - const QPointF d = widgetToData(pos); - const int ix = int(std::floor(d.x())); - const int iy = int(std::floor(d.y())); - if (ix >= 0 && ix < m_nx && iy >= 0 && iy < m_ny) - setToolTip(QStringLiteral("(x=%1, y=%2) = %3") - .arg(ix) - .arg(iy) - .arg(double(m_data[ix + iy * m_nx]), 0, 'f', 1)); - } else { - setCursor(Qt::ArrowCursor); - setToolTip(QString()); - } - return; - } - const QPointF now = widgetToData(pos); - const QPointF then = widgetToData(m_lastPos); - m_vpX = m_dragVpX - (now.x() - then.x()); - m_vpY = m_dragVpY - (now.y() - then.y()); - clampViewport(); - update(); - if (onZoomChanged) - onZoomChanged(m_vpX, m_vpY, m_vpX + vpW(), m_vpY + vpH()); + + const QPointF d = m.toData(e->position()); + const int ix = static_cast(std::floor(d.x())); + const int iy = static_cast(std::floor(d.y())); + const bool onImage = m.plot.contains(e->position().toPoint()) && ix >= 0 && + ix < m_nx && iy >= 0 && iy < m_ny; + setCursor(onImage && m_zoomEnabled ? Qt::OpenHandCursor : Qt::ArrowCursor); + setToolTip(onImage ? QStringLiteral("(x=%1, y=%2) = %3") + .arg(ix) + .arg(iy) + .arg(formatValue(value(ix, iy))) + : QString()); } void SlsQtFastImage::mouseReleaseEvent(QMouseEvent *e) { - if (e->button() == Qt::LeftButton && m_roiGrab != 0) { - m_roiGrab = 0; - if (onRoiEdited && m_roiX1 - m_roiX0 >= 2.0 && - m_roiY1 - m_roiY0 >= 2.0) { - onRoiEdited(int(std::lround(m_roiX0)), - int(std::lround(m_roiY0)), - int(std::lround(m_roiX1)), - int(std::lround(m_roiY1))); - } + if (e->button() != Qt::LeftButton || !m_panning) return; - } - if (e->button() == Qt::LeftButton) { - if (m_dragging && onZoomChanged) - onZoomChanged(m_vpX, m_vpY, m_vpX + vpW(), m_vpY + vpH()); - m_dragging = false; - const bool wasScale = m_dragScale; - m_dragScale = false; - setCursor(Qt::ArrowCursor); - if (wasScale && onScaleReleased) - onScaleReleased(); // one histogram/scale refresh, after the drag - } + m_panning = false; + setCursor(Qt::OpenHandCursor); +} + +void SlsQtFastImage::mouseDoubleClickEvent(QMouseEvent *) { + if (m_zoomEnabled) + resetView(); } void SlsQtFastImage::wheelEvent(QWheelEvent *e) { - if (!hasImage() || !m_zoomEnabled) + if (!hasImage() || !m_zoomEnabled || e->angleDelta().y() == 0) return; - const QPointF imgPt = widgetToData(e->position()); - const double mx = imgPt.x(), my = imgPt.y(); - - const double factor = (e->angleDelta().y() > 0) ? 1.0 / 1.18 : 1.18; - double nw = vpW() * factor, nh = vpH() * factor; - if (nw < std::min(kMinimumViewport, double(m_nx))) - nw = std::min(kMinimumViewport, double(m_nx)); - if (nh < std::min(kMinimumViewport, double(m_ny))) - nh = std::min(kMinimumViewport, double(m_ny)); - if (nw > m_nx) - nw = m_nx; - if (nh > m_ny) - nh = m_ny; - - // Keep the data point under the cursor fixed. (The reference reshaped the - // viewport to the window while zooming in; that moves the cursor point and - // breaks the "zoom keeps the cursor point fixed" invariant.) - const double fracX = (mx - m_vpX) / vpW(); - const double fracY = (my - m_vpY) / vpH(); - m_vpX = mx - fracX * nw; - m_vpY = my - fracY * nh; - m_vpW = nw; - m_vpH = nh; - clampViewport(); - - if (onZoomChanged) - onZoomChanged(m_vpX, m_vpY, m_vpX + vpW(), m_vpY + vpH()); - setToolTip(QStringLiteral("Zoom: %1%").arg(int(100.0 * m_nx / vpW()))); - update(); + zoomAt(e->position(), + e->angleDelta().y() > 0 ? 1 / kWheelZoomFactor : kWheelZoomFactor); } -void SlsQtFastImage::mouseDoubleClickEvent(QMouseEvent *e) { - const QRect sr = scaleRect(); - if (sr.height() > 0 && sr.contains(e->position().toPoint())) { - m_clo = m_defClo; - m_chi = m_defChi; - m_histMs = 0; - m_dirty = true; - update(); - } else if (m_zoomEnabled) { - resetView(); - } -} +void SlsQtFastImage::resizeEvent(QResizeEvent *) { matchViewportToWindow(); } } // namespace sls diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQtScalePanel.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQtScalePanel.cpp index 875e02302..a14f3279c 100644 --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQtScalePanel.cpp +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQtScalePanel.cpp @@ -3,13 +3,14 @@ #include "SlsQtScalePanel.h" #include "SlsQtFastImage.h" +#include "SlsQtPlotCommon.h" #include #include #include #include -#include #include +#include #include #include @@ -18,8 +19,16 @@ namespace sls { namespace { + constexpr int kHistoHeight = 38; -constexpr int kPanelHeight = kHistoHeight + 40; // strip + one compact row +// fraction of the width where the markers sit +constexpr double kLoMarker = 0.25; +constexpr double kHiMarker = 0.75; +// how close to a marker a click has to be, in widget pixels +constexpr double kGrabDistance = 10.0; +// smallest colour range a drag can produce +constexpr double kMinRange = 1e-9; + } // namespace // --------------------------------------------------------------------------- @@ -27,484 +36,214 @@ constexpr int kPanelHeight = kHistoHeight + 40; // strip + one compact row // --------------------------------------------------------------------------- SlsQtScaleHisto::SlsQtScaleHisto(QWidget *parent) : QWidget(parent) { setFixedHeight(kHistoHeight); - setMouseTracking(true); - setToolTip(QStringLiteral( - "Distribution of the last image (its own value range); the band " - "between the two markers is the range mapped to the palette. " - "Markers sit at 1/4 and 3/4 and the axis rescales under them - " - "drag either one to change that end.")); + setToolTip(tr("Histogram of the image. The band between the two markers " + "is the colour range, drag a marker to change it.")); } -void SlsQtScaleHisto::setData(const std::vector *h, double dlo, - double dhi, double clo, double chi, bool logX, - bool logY) { - // Frozen while a marker is being dragged: re-filling the bars from the - // live image mid-drag fed the drag back into the histogram (the bars - // moved, which moved the marker, which moved the bars...). The strip is - // refreshed once, when the button comes back up. - if (m_dragging) +void SlsQtScaleHisto::setData(const std::vector &counts, double binLo, + double binHi, double colorLo, double colorHi, + bool logX, bool logY) { + if (isDragging()) return; - m_hist = h; - m_dlo = dlo; - m_dhi = dhi; - m_clo = clo; - m_chi = chi; + m_counts = counts; + m_binLo = binLo; + m_binHi = binHi; + m_colorLo = colorLo; + m_colorHi = colorHi; m_logX = logX; m_logY = logY; update(); } -void SlsQtScaleHisto::clearData() { - // The view that owned the histogram vector is gone (or detached): never - // touch m_hist again. A pending marker drag is abandoned as well. - m_hist = nullptr; - m_snap.clear(); - m_dragging = false; - m_dragMin = -1; - update(); -} +bool SlsQtScaleHisto::isDragging() const { return m_dragged != Marker::None; } -bool SlsQtScaleHisto::isDragging() const { return m_dragging; } - -void SlsQtScaleHisto::currentWindow(double &lo, double &hi) const { - lo = m_clo; - hi = m_chi; -} - -void SlsQtScaleHisto::windowFor(double clo, double chi, double &wlo, - double &whi) const { - double dclo = m_logX ? sls::plot::logClamp(clo) : clo; - double dchi = m_logX ? sls::plot::logClamp(chi) : chi; - if (!std::isfinite(dclo) || !std::isfinite(dchi)) { - dclo = 0.0; - dchi = 1.0; +// Value axis shown by the strip, in log10 of the values if m_logX +void SlsQtScaleHisto::axisRange(double &lo, double &hi) const { + double a = m_logX ? plot::logClamp(m_colorLo) : m_colorLo; + double b = m_logX ? plot::logClamp(m_colorHi) : m_colorHi; + if (!std::isfinite(a) || !std::isfinite(b)) { + a = 0.0; + b = 1.0; } - if (!(dchi > dclo)) - dchi = dclo + 1.0; - const double span = dchi - dclo; - wlo = dclo - 0.5 * span; - whi = dchi + 0.5 * span; - if (!(whi > wlo)) - whi = wlo + 1.0; + if (!(b > a)) + b = a + 1.0; + // puts a at kLoMarker and b at kHiMarker + const double perWidth = (b - a) / (kHiMarker - kLoMarker); + lo = a - kLoMarker * perWidth; + hi = lo + perWidth; } -void SlsQtScaleHisto::displayedWindow(double &lo, double &hi) const { - // Work in the histogram's own binning space (log10 values when logX). - if (m_dragging) - windowFor(m_preClo, m_preChi, lo, hi); - else - windowFor(m_clo, m_chi, lo, hi); -} - -const std::vector *SlsQtScaleHisto::displayedHistogram() const { - if (m_dragging && !m_snap.empty()) - return &m_snap; - return m_hist; -} - -int SlsQtScaleHisto::previewX() const { return m_previewX; } - void SlsQtScaleHisto::paintEvent(QPaintEvent *) { + const plot::PlotTheme theme; QPainter p(this); - p.fillRect(rect(), QColor(28, 28, 28)); - const int W = width(), H = height(); - if (W <= 0 || H <= 0) - return; - // While a marker is dragged the axis stays exactly as it was when the - // drag started: the bars (and the two numbers) must not move with the - // cursor, only the dragged end is previewed as a dashed line. - const double dclo = m_dragging ? m_preClo : m_clo; - const double dchi = m_dragging ? m_preChi : m_chi; - double wlo = 0.0, whi = 1.0; - windowFor(dclo, dchi, wlo, whi); - auto xof = [&](double vBin) { return (vBin - wlo) / (whi - wlo) * W; }; + p.fillRect(rect(), theme.background); + const double w = width(); + const double h = height(); - // The image keeps arriving while the marker is dragged, so paint from the - // snapshot taken when the button went down. - const std::vector *hv = displayedHistogram(); - if (hv && !hv->empty() && m_dhi > m_dlo) { - int mx = 1; - for (int v : *hv) - if (v > mx) - mx = v; - const double lmx = std::log10(double(mx) + 1.0); - const double binW = (m_dhi - m_dlo) / double(hv->size()); + double axisLo = 0.0, axisHi = 1.0; + axisRange(axisLo, axisHi); + const auto toX = [&](double v) { + return (v - axisLo) / (axisHi - axisLo) * w; + }; + + const int maxCount = + m_counts.empty() ? 0 + : *std::max_element(m_counts.begin(), m_counts.end()); + if (maxCount > 0 && m_binHi > m_binLo) { + const double binWidth = (m_binHi - m_binLo) / m_counts.size(); + const double full = m_logY ? std::log10(maxCount + 1.0) : maxCount; p.setPen(Qt::NoPen); p.setBrush(QColor(120, 190, 255)); - for (size_t i = 0; i < hv->size(); i++) { - if ((*hv)[i] <= 0) + for (size_t i = 0; i < m_counts.size(); ++i) { + if (m_counts[i] <= 0) continue; - // solid: the bar is as wide as the bin spacing on screen - const double x0 = xof(m_dlo + double(i) * binW); - const double x1 = xof(m_dlo + double(i + 1) * binW); - const double bh = - m_logY ? (std::log10(double((*hv)[i]) + 1.0) / lmx) - : (double((*hv)[i]) / double(mx)); - const double w = std::max(1.0, x1 - x0); - if (x0 > W || x0 + w < 0) - continue; - p.drawRect(QRectF(x0, H - 3 - bh * (H - 6), w, - std::max(1.0, bh * (H - 6)))); + const double x0 = toX(m_binLo + i * binWidth); + const double x1 = toX(m_binLo + (i + 1) * binWidth); + const double count = + m_logY ? std::log10(m_counts[i] + 1.0) : m_counts[i]; + const double barHeight = std::max(1.0, count / full * (h - 6)); + p.drawRect(QRectF(x0, h - 3 - barHeight, std::max(1.0, x1 - x0), + barHeight)); } } - // the two markers at their fixed places (they are what the axis follows) - const double xa = 0.25 * W, xb = 0.75 * W; - if (m_dragging) { // the dragged end, previewed only - QPen pv(QColor(255, 205, 110, 180)); - pv.setWidth(1); - pv.setStyle(Qt::DashLine); - p.setPen(pv); - const double x = - std::max(0.0, std::min(double(W - 1), double(m_previewX))); - p.drawLine(QPointF(x, 0), QPointF(x, H)); + if (isDragging()) { + p.setPen(QPen(QColor(255, 205, 110, 180), 1, Qt::DashLine)); + p.drawLine(QPointF(m_dragX, 0), QPointF(m_dragX, h)); } - p.fillRect(QRectF(xa, 0, xb - xa, H), QColor(255, 255, 255, 26)); - QPen mk(QColor(255, 205, 110)); - mk.setWidth(2); - p.setPen(mk); - p.setBrush(Qt::NoBrush); - p.drawLine(QPointF(xa, 0), QPointF(xa, H)); - p.drawLine(QPointF(xb, 0), QPointF(xb, H)); - QFont f = p.font(); + + const double xLo = kLoMarker * w; + const double xHi = kHiMarker * w; + p.fillRect(QRectF(xLo, 0, xHi - xLo, h), QColor(255, 255, 255, 26)); + p.setPen(QPen(QColor(255, 205, 110), 2)); + p.drawLine(QPointF(xLo, 0), QPointF(xLo, h)); + p.drawLine(QPointF(xHi, 0), QPointF(xHi, h)); + + QFont f = font(); f.setPixelSize(9); p.setFont(f); p.setPen(QColor(255, 225, 160)); - p.drawText(QRectF(xa + 3, 1, std::max(0.0, W - xa - 6), 11), - Qt::AlignLeft | Qt::AlignTop, - QString::number(dclo, 'g', 4)); - p.drawText(QRectF(3, 1, std::max(0.0, xb - 3), 11), - Qt::AlignRight | Qt::AlignTop, - QString::number(dchi, 'g', 4)); + p.drawText(QRectF(xLo + 3, 1, w, 11), Qt::AlignLeft | Qt::AlignTop, + QString::number(m_colorLo, 'g', 4)); + p.drawText(QRectF(0, 1, xHi - 3, 11), Qt::AlignRight | Qt::AlignTop, + QString::number(m_colorHi, 'g', 4)); } void SlsQtScaleHisto::mousePressEvent(QMouseEvent *e) { - const double xa = 0.25 * width(), xb = 0.75 * width(); - const double d = std::abs(e->position().x() - xa); - const double d2 = std::abs(e->position().x() - xb); - if (std::min(d, d2) > 10) { - m_dragMin = -1; // too far from either marker: ignore + if (e->button() != Qt::LeftButton) return; - } - m_dragMin = (d <= d2) ? 1 : 0; - // Dragging only moves this strip: re-rendering a megapixel image on every - // mouse move is what made it crawl, so the new range is applied when the - // button comes back up (see mouseReleaseEvent). - m_dragging = true; - m_snap.clear(); - if (m_hist) - m_snap = *m_hist; // the bars: frozen as well (the image keeps updating) - m_preClo = m_clo; // the axis basis: frozen until the button is released - m_preChi = m_chi; - m_previewX = e->position().toPoint().x(); - mouseMoveEvent(e); + const double x = e->position().x(); + const double toLo = std::abs(x - kLoMarker * width()); + const double toHi = std::abs(x - kHiMarker * width()); + if (std::min(toLo, toHi) > kGrabDistance) + return; + m_dragged = (toLo <= toHi) ? Marker::Lo : Marker::Hi; + m_dragX = x; + update(); } void SlsQtScaleHisto::mouseMoveEvent(QMouseEvent *e) { - if (m_dragMin < 0) + if (!isDragging()) return; - const int W = width(); - if (W <= 0) - return; - // The cursor -> value mapping uses the axis FROZEN at press time. Using - // the live clo_/chi_ here was the positive feedback: the move changed the - // range, the range changed the window, and the same cursor position then - // mapped to a different value, so the marker chased itself. - double wlo = 0.0, whi = 1.0; - windowFor(m_preClo, m_preChi, wlo, whi); - const double t = std::max(0.0, std::min(1.0, double(e->position().x()) / W)); - const double vBin = wlo + t * (whi - wlo); - const double v = m_logX ? std::pow(10.0, vBin) : vBin; - if (m_dragMin == 1) - m_clo = std::min(v, m_chi - 1e-9); - else - m_chi = std::max(v, m_clo + 1e-9); - m_previewX = e->position().toPoint().x(); - update(); // only the preview line moves; bars and axis stay frozen + m_dragX = std::clamp(e->position().x(), 0.0, double(width())); + update(); } -void SlsQtScaleHisto::mouseReleaseEvent(QMouseEvent *) { - if (m_dragMin >= 0 && m_dragging) { - m_dragging = false; // unfreeze first, so the refresh is applied - m_snap.clear(); // back to the live histogram - if (onRangeChanged) - onRangeChanged(m_clo, m_chi); // one update, as soon as released - update(); - } - m_dragMin = -1; +void SlsQtScaleHisto::mouseReleaseEvent(QMouseEvent *e) { + if (e->button() != Qt::LeftButton || !isDragging()) + return; + double axisLo = 0.0, axisHi = 1.0; + axisRange(axisLo, axisHi); + const double onAxis = axisLo + m_dragX / width() * (axisHi - axisLo); + const double v = m_logX ? std::pow(10.0, onAxis) : onAxis; + + double lo = m_colorLo; + double hi = m_colorHi; + if (m_dragged == Marker::Lo) + lo = std::min(v, hi - kMinRange); + else + hi = std::max(v, lo + kMinRange); + m_dragged = Marker::None; + update(); + emit rangeChanged(lo, hi); } // --------------------------------------------------------------------------- // SlsQtScalePanel // --------------------------------------------------------------------------- SlsQtScalePanel::SlsQtScalePanel(SlsQtFastImage *view, QWidget *parent) - : QWidget(parent) { - auto *col = new QVBoxLayout(this); - col->setContentsMargins(4, 2, 4, 4); - col->setSpacing(3); - + : QWidget(parent), m_view(view) { m_histo = new SlsQtScaleHisto(this); - col->addWidget(m_histo); + + m_paletteCombo = new QComboBox(this); + for (int i = 0; i < plot::paletteCount(); ++i) + m_paletteCombo->addItem( + plot::paletteName(static_cast(i))); + m_paletteCombo->setMinimumContentsLength(12); + + m_imageLogCombo = new QComboBox(this); + m_imageLogCombo->addItems({tr("lin"), tr("log")}); + m_imageLogCombo->setToolTip( + tr("Colour scale of the image. With log, values <= 0 are shown as " + "1e-2 so that empty pixels stay visible.")); + + m_histoLogCombo = new QComboBox(this); + m_histoLogCombo->addItems({tr("lin"), tr("log")}); + m_histoLogCombo->setToolTip( + tr("Height of the histogram bars: counts or log10(counts + 1).")); auto *row = new QHBoxLayout(); row->setSpacing(4); - m_paletteCombo = new QComboBox(this); - for (int i = 0; i < sls::plot::paletteCount(); i++) - m_paletteCombo->addItem( - sls::plot::paletteName(static_cast(i))); - m_imageLogCombo = new QComboBox(this); - m_imageLogCombo->addItem(QStringLiteral("lin")); - m_imageLogCombo->addItem(QStringLiteral("log")); - m_imageLogCombo->setToolTip( - QStringLiteral("image: log10(value), values <= 0 are capped at\n" - "1e-2 so empty pixels stay visible")); - m_histoLogCombo = new QComboBox(this); - m_histoLogCombo->addItem(QStringLiteral("lin")); - m_histoLogCombo->addItem(QStringLiteral("log")); - m_histoLogCombo->setToolTip( - QStringLiteral("histogram bars: linear counts, or log10(count+1).\n" - "The histogram's value axis always follows the image\n" - "mapping above.")); - m_paletteCombo->setMinimumContentsLength(12); - - row->addWidget(new QLabel(QStringLiteral("palette:"), this)); + row->addWidget(new QLabel(tr("palette:"), this)); row->addWidget(m_paletteCombo); - row->addWidget(new QLabel(QStringLiteral("image"), this)); + row->addWidget(new QLabel(tr("image"), this)); row->addWidget(m_imageLogCombo); - row->addWidget(new QLabel(QStringLiteral("histo"), this)); + row->addWidget(new QLabel(tr("histo"), this)); row->addWidget(m_histoLogCombo); row->addStretch(1); - col->addLayout(row); - - connect(m_paletteCombo, QOverload::of(&QComboBox::currentIndexChanged), - this, [this](int) { push(); }); - connect(m_imageLogCombo, - QOverload::of(&QComboBox::currentIndexChanged), this, - [this](int i) { - if (m_suppress || !m_view) - return; - m_view->setLogScale(i == 1); - refresh(); - }); - connect(m_histoLogCombo, - QOverload::of(&QComboBox::currentIndexChanged), this, - [this](int) { updateHisto(); }); - m_histo->onRangeChanged = [this](double a, double b) { - if (m_suppress || !m_view) - return; - m_view->setColorRange(a, b); - m_controlLo = a; - m_controlHi = b; - refresh(); - }; + auto *layout = new QVBoxLayout(this); + layout->setContentsMargins(4, 2, 4, 4); + layout->setSpacing(3); + layout->addWidget(m_histo); + layout->addLayout(row); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - setFixedHeight(kPanelHeight); - setView(view); -} -SlsQtScalePanel::~SlsQtScalePanel() { detachView(); } - -void SlsQtScalePanel::attachView(SlsQtFastImage *view) { - if (!view) - return; - m_prevImageChanged = view->onImageChanged; - m_prevScaleReleased = view->onScaleReleased; - view->onImageChanged = [this]() { - if (m_prevImageChanged) - m_prevImageChanged(); - refresh(); - }; - view->onScaleReleased = [this]() { - if (m_prevScaleReleased) - m_prevScaleReleased(); - refresh(); - }; - m_installed = true; - // R6 lifetime: the strip holds a raw pointer to view->histogram(). When - // the view is destroyed, drop it before any repaint can read freed memory. - m_destroyedConn = QObject::connect( - view, &QObject::destroyed, this, [this]() { - m_installed = false; - m_prevImageChanged = nullptr; - m_prevScaleReleased = nullptr; - if (m_histo) - m_histo->clearData(); - }); -} - -void SlsQtScalePanel::detachView() { - if (m_destroyedConn) { - QObject::disconnect(m_destroyedConn); - m_destroyedConn = QMetaObject::Connection(); - } - if (m_view && m_installed) { - m_view->onImageChanged = m_prevImageChanged; - m_view->onScaleReleased = m_prevScaleReleased; - } - m_installed = false; - m_prevImageChanged = nullptr; - m_prevScaleReleased = nullptr; - m_rangeEdited = false; // a pending edit belongs to the old view - // R6: the strip must not keep pointing at the old view's histogram. - if (m_histo) - m_histo->clearData(); -} - -void SlsQtScalePanel::setView(SlsQtFastImage *view) { - if (m_view == view) { - refresh(); - return; - } - detachView(); - m_view = view; - attachView(view); + connect( + m_paletteCombo, &QComboBox::currentIndexChanged, this, + [this](int i) { m_view->setPalette(static_cast(i)); }); + connect(m_imageLogCombo, &QComboBox::currentIndexChanged, this, + [this](int i) { m_view->setLogScale(i == 1); }); + connect(m_histoLogCombo, &QComboBox::currentIndexChanged, this, + &SlsQtScalePanel::refresh); + connect(m_histo, &SlsQtScaleHisto::rangeChanged, this, + [this](double lo, double hi) { + m_view->setColorRange(lo, hi); + emit colorRangeEdited(lo, hi); + }); + connect(m_view, &SlsQtFastImage::colorMapChanged, this, + &SlsQtScalePanel::refresh); + connect(m_view, &SlsQtFastImage::histogramChanged, this, + &SlsQtScalePanel::refresh); refresh(); } -SlsQtFastImage *SlsQtScalePanel::view() const { return m_view; } - -void SlsQtScalePanel::updateHisto() { - if (!m_view || !m_histo) - return; - double a = 0.0, b = 1.0; - m_view->colorRange(a, b); - double hlo = 0.0, hhi = 1.0; - m_view->histogramRange(hlo, hhi); - m_histo->setData(&m_view->histogram(), hlo, hhi, a, b, - m_view->logScale(), - m_histoLogCombo && - m_histoLogCombo->currentIndex() == 1); -} - -void SlsQtScalePanel::refresh() { - if (!m_view) - return; - // Dragging the Z scale on the image changes the range on every mouse - // move; re-filling the histogram from the image with that half-applied - // range fed the drag back into the bars. Frozen until release, when - // onScaleReleased() calls this again. - // R1: the same holds while one of the strip's own markers is dragged - - // otherwise the incoming frames keep moving the control range (and the - // strip labels) under the frozen marker. - if (m_view->isScaleDragging() || - (m_histo && m_histo->isDragging())) - return; - m_suppress++; - double a = 0.0, b = 1.0; - m_view->colorRange(a, b); - m_controlLo = a; - m_controlHi = b; - if (m_imageLogCombo) - m_imageLogCombo->setCurrentIndex(m_view->logScale() ? 1 : 0); - const int pi = m_view->paletteIndex(); - if (m_paletteCombo && pi >= 0 && pi < m_paletteCombo->count()) - m_paletteCombo->setCurrentIndex(pi); - updateHisto(); - m_suppress--; -} - -void SlsQtScalePanel::syncFromView() { refresh(); } - -void SlsQtScalePanel::push() { // controls -> view - if (m_suppress || !m_view) - return; - // Palette changes are always applied (cheap and lossless). - const int pi = m_paletteCombo ? m_paletteCombo->currentIndex() : 0; - if (pi >= 0) - m_view->setPaletteLut( - sls::plot::paletteLut(static_cast(pi))); - // R2: only push the colour range on an explicit control edit (the Plot - // tab owns min/max; the panel only synchronises it). Palette/log changes - // must not perturb the automatic z range. A strip-marker drag applies its - // range directly in the onRangeChanged handler, not here. - if (m_rangeEdited) { - m_rangeEdited = false; - double a = m_controlLo; - double b = m_controlHi; - if (!(b > a)) { - b = a + 1.0; - m_controlHi = b; - } - m_lastPushedValid = true; - m_lastPushedLo = a; - m_lastPushedHi = b; - m_view->setColorRange(a, b); - } - refresh(); -} - -void SlsQtScalePanel::controlRange(double &lo, double &hi) const { - lo = m_controlLo; - hi = m_controlHi; -} - -void SlsQtScalePanel::setControlRange(double lo, double hi) { - // Mimic the operator applying both ends from the Plot tab. - m_controlLo = lo; - m_controlHi = hi; - m_rangeEdited = true; - push(); -} - -bool SlsQtScalePanel::lastPushedRange(double &lo, double &hi) const { - lo = m_lastPushedLo; - hi = m_lastPushedHi; - return m_lastPushedValid; -} - -void SlsQtScalePanel::setPalette(sls::plot::Palette p) { - const int idx = int(p); - if (m_paletteCombo && idx >= 0 && idx < m_paletteCombo->count()) - setPaletteChoice(idx); - else if (m_view) - m_view->setPaletteLut(sls::plot::paletteLut(p)); - refresh(); -} - -void SlsQtScalePanel::setPaletteChoice(int index) { - if (!m_paletteCombo || index < 0 || index >= m_paletteCombo->count()) - return; - if (m_paletteCombo->currentIndex() == index) - push(); - else - m_paletteCombo->setCurrentIndex(index); // triggers push() -} - -int SlsQtScalePanel::paletteChoice() const { - return m_paletteCombo ? m_paletteCombo->currentIndex() : -1; -} - -void SlsQtScalePanel::setImageLog(bool on) { - if (m_view) - m_view->setLogScale(on); - refresh(); -} - -void SlsQtScalePanel::setColorRange(double lo, double hi) { - if (m_view) - m_view->setColorRange(lo, hi); - refresh(); -} - -void SlsQtScalePanel::setHistoLog(bool on) { - if (m_histoLogCombo) - m_histoLogCombo->setCurrentIndex(on ? 1 : 0); -} - -bool SlsQtScalePanel::histoLog() const { - return m_histoLogCombo && m_histoLogCombo->currentIndex() == 1; -} - -void SlsQtScalePanel::setPaletteEnabled(bool on) { - if (m_paletteCombo) - m_paletteCombo->setEnabled(on); -} - SlsQtScaleHisto *SlsQtScalePanel::histogramWidget() const { return m_histo; } -bool SlsQtScalePanel::isDragging() const { - return m_histo && m_histo->isDragging(); +// Shows the state of the view +void SlsQtScalePanel::refresh() { + { + const QSignalBlocker blockPalette(m_paletteCombo); + const QSignalBlocker blockLog(m_imageLogCombo); + m_paletteCombo->setCurrentIndex(static_cast(m_view->palette())); + m_imageLogCombo->setCurrentIndex(m_view->logScale() ? 1 : 0); + } + double colorLo = 0.0, colorHi = 1.0; + m_view->colorRange(colorLo, colorHi); + double binLo = 0.0, binHi = 1.0; + m_view->histogramRange(binLo, binHi); + m_histo->setData(m_view->histogram(), binLo, binHi, colorLo, colorHi, + m_view->logScale(), m_histoLogCombo->currentIndex() == 1); } } // namespace sls diff --git a/slsDetectorGui/src/qDrawPlot.cpp b/slsDetectorGui/src/qDrawPlot.cpp index c0709c904..2254163a6 100644 --- a/slsDetectorGui/src/qDrawPlot.cpp +++ b/slsDetectorGui/src/qDrawPlot.cpp @@ -182,7 +182,7 @@ void qDrawPlot::SetupPlots() { plot2d = new SlsQt2DPlot(boxPlot); plot2d->SetData(nPixelsX, -0.5, nPixelsX - 0.5, nPixelsY, -0.5, nPixelsY - 0.5, data2d); - plot2d->setTitle(""); + plot2d->SetTitle(""); plot2d->SetXTitle(xTitle2d); plot2d->SetYTitle(yTitle2d); plot2d->SetZTitle(zTitle2d); @@ -512,7 +512,7 @@ void qDrawPlot::ClonePlot() { } else { LOG(logDEBUG) << "Cloning 2D Image"; cloneplot2D = new SlsQt2DPlot(); - cloneplot2D->setTitle(plot2d->title()); + cloneplot2D->SetTitle(plot2d->title()); cloneplot2D->SetXTitle(xTitle2d); cloneplot2D->SetYTitle(yTitle2d); cloneplot2D->SetZTitle(zTitle2d); diff --git a/slsDetectorGui/tests/plotting_test.cpp b/slsDetectorGui/tests/plotting_test.cpp index 0eb88ea75..c237aa725 100644 --- a/slsDetectorGui/tests/plotting_test.cpp +++ b/slsDetectorGui/tests/plotting_test.cpp @@ -1,12 +1,8 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2026 Contributors to the SLS Detector Package -// -// QtTest suite for the plotting stack (verification task). -// -// Everything is checked through the public API or through rendered pixels; the -// widgets are shown on the offscreen QPA platform and rendered synchronously -// with QWidget::grab(), so the assertions exercise the same paint path the GUI -// uses. The performance slot is the acceptance benchmark for 1024x512 frames. + +// Tests of the plotting widgets, through their public interface and through +// the pixels they paint. Run with QT_QPA_PLATFORM=offscreen. #include "SlsQt1DPlot.h" #include "SlsQt2DHist.h" @@ -17,24 +13,29 @@ #include "sls/sls_detector_defs.h" #include +#include #include #include #include -#include #include #include #include +#include #include #include +#include #include #include #include #include #include +#include #include #include +using sls::plot::Palette; + namespace { constexpr QRgb kBackground = qRgb(28, 28, 28); @@ -49,8 +50,7 @@ QImage render(QWidget &w) { return w.grab().toImage(); } -QPointF widgetPos(const sls::SlsQtFastImage &view, double dataX, - double dataY) { +QPointF widgetPos(const sls::SlsQtFastImage &view, double dataX, double dataY) { return view.dataToWidget(QPointF(dataX, dataY)); } @@ -141,16 +141,55 @@ bool is125Step(double step) { near(norm, 5.0, 1e-6); } -// A 1024x512 acceptance frame: sin(x/40) + cos(y/30). -std::vector acceptanceFrame(double phase = 0.0) { - std::vector f(size_t(1024) * 512); - for (int y = 0; y < 512; y++) { - for (int x = 0; x < 1024; x++) { - f[size_t(y) * 1024 + x] = - float(std::sin(x / 40.0 + phase) + std::cos(y / 30.0)); +// 1024 x 512 pixels of sin(x/40) + cos(y/30) +std::vector testFrame() { + std::vector f(size_t(1024) * 512); + for (int y = 0; y < 512; y++) + for (int x = 0; x < 1024; x++) + f[size_t(y) * 1024 + x] = std::sin(x / 40.0) + std::cos(y / 30.0); + return f; +} + +// Every pixel has the value of its x index +std::vector xRamp(int nx, int ny) { + std::vector f(size_t(nx) * ny); + for (int y = 0; y < ny; y++) + for (int x = 0; x < nx; x++) + f[size_t(y) * nx + x] = x; + return f; +} + +int sum(const std::vector &v) { + return std::accumulate(v.begin(), v.end(), 0); +} + +// Plot area of an image view without titles +QRect plotArea(const sls::SlsQtFastImage &view) { + return sls::plot::plotRectFor(view.size(), sls::plot::PlotTheme()); +} + +// Number of matching pixels above and to the right of the plot area +int countOutside(const QImage &img, const QRect &plot, bool (*pred)(QRgb)) { + int n = 0; + for (int y = 0; y < img.height(); y++) { + for (int x = 0; x < img.width(); x++) { + if ((x > plot.right() || y < plot.top()) && pred(img.pixel(x, y))) + n++; } } - return f; + return n; +} + +// Bounding box of the pixels that differ +QRect differingArea(const QImage &a, const QImage &b) { + QRect area; + for (int y = 0; y < a.height(); y++) { + for (int x = 0; x < a.width(); x++) { + if (a.pixel(x, y) != b.pixel(x, y)) + area |= QRect(x, y, 1, 1); + } + } + return area; } } // namespace @@ -159,45 +198,39 @@ class PlottingTest : public QObject { Q_OBJECT private slots: - // ---- foundation: palettes / ticks / formatting ------------------------ void palettesAndLuts(); void paletteLogClamp(); void tickMath(); void tickFormatting(); - // ---- FastImageView ---------------------------------------------------- - void fastImageOwnsFrame(); - void fastImageYUp(); - void fastImageHistogramWindow(); - void fastImageHistogramLogWindow(); - void fastImageLogClamp(); - void fastImageZeroWhite(); - void fastImageZoomCursorInvariance(); - void fastImageViewportClamping(); - void fastImageClipsToPlotRect(); - void fastImageOverlaysInDataCoordinates(); - void fastImageTitlesAndAspect(); + void imageIsCopied(); + void imageYUp(); + void imageLogScale(); + void imageHistogram(); + void imageViewport(); + void imageWheelZoom(); + void imagePan(); + void imageIsClippedToPlotArea(); + void imageOverlays(); + void imageInterpolation(); + void imageTitles(); - // ---- ScaleHisto / ScalePanel ----------------------------------------- - void scaleHistoThreeWayFreeze(); - void scaleHistoMaxMarker(); - void scalePanelReentrancy(); - void scalePanelFreezeAndPushRules(); - void scalePanelDetachLifetime(); + void scaleHistoDrag(); + void scaleHistoLogAxis(); + void scalePanel(); - // ---- 1D plot ---------------------------------------------------------- void h1dDataApi(); void oneDimensionalRangeZoomLogAndGain(); void oneDimensionalRoiBoxes(); - // ---- 2D plot ---------------------------------------------------------- void twoDHistogramContainer(); - void twoDimensionalDataZRangeAndPanel(); - void twoDimensionalLogInterpolateAndContour(); - void twoDimensionalRoiAndClipping(); - void twoDimensionalGainMode(); + void plot2dTitles(); + void plot2dZRange(); + void plot2dLogZ(); + void plot2dContours(); + void plot2dRoiAndZoom(); + void plot2dGain(); - // ---- acceptance benchmark -------------------------------------------- void performance1024x512(); }; @@ -254,8 +287,8 @@ void PlottingTest::palettesAndLuts() { const QRgb *gain = sls::plot::paletteLut(sls::plot::Palette::Gain4); QVERIFY(gain != nullptr); QVERIFY(gain[0] != sls::plot::paletteLut(sls::plot::Palette::Color)[0]); - QString gainName = QString::fromLatin1( - sls::plot::paletteName(sls::plot::Palette::Gain4)); + QString gainName = + QString::fromLatin1(sls::plot::paletteName(sls::plot::Palette::Gain4)); QVERIFY(gainName.contains(QStringLiteral("gain"), Qt::CaseInsensitive)); } @@ -280,8 +313,8 @@ void PlottingTest::tickMath() { } QCOMPARE(sls::plot::niceStep(1000.0, 8), 200.0); QVERIFY(near(sls::plot::niceStep(0.9, 8), 0.2)); - QCOMPARE(sls::plot::niceStep(0.0, 8), 1.0); // degenerate - QCOMPARE(sls::plot::niceStep(-5.0, 8), 1.0); // degenerate + QCOMPARE(sls::plot::niceStep(0.0, 8), 1.0); // degenerate + QCOMPARE(sls::plot::niceStep(-5.0, 8), 1.0); // degenerate // Ticks cover the visible range, never exceed the requested density and // are uniformly spaced. @@ -332,9 +365,9 @@ void PlottingTest::tickFormatting() { QCOMPARE(sls::plot::formatTick(-0.0, 0.5), QStringLiteral("0")); QCOMPARE(sls::plot::formatTick(-200.0, 200.0), QStringLiteral("-200")); QVERIFY(sls::plot::formatTick(2.5e7, 1e7).contains(QLatin1Char('e'))); - QCOMPARE(sls::plot::formatTick( - std::numeric_limits::infinity(), 1.0), - QStringLiteral("?")); + QCOMPARE( + sls::plot::formatTick(std::numeric_limits::infinity(), 1.0), + QStringLiteral("?")); // No trailing zeros anywhere, and labels stay short. for (double v : {0.0, 1.0, 2.0, 5.0, 10.0, 100.0, -100.0, 0.5, 2.5}) { const QString s = sls::plot::formatTick(v, 1.0); @@ -344,809 +377,466 @@ void PlottingTest::tickFormatting() { } // --------------------------------------------------------------------------- -// FastImageView: buffer ownership, orientation, histogram, colour mapping +// SlsQtFastImage: data and colour mapping // --------------------------------------------------------------------------- -void PlottingTest::fastImageOwnsFrame() { +void PlottingTest::imageIsCopied() { sls::SlsQtFastImage view; - view.resize(200, 200); // sx ~ 35 px => no in-pixel text over cell centres + view.resize(200, 200); // pixels are outlined but not labelled view.show(); - QTest::qWait(5); - - view.setPaletteLut(sls::plot::paletteLut(sls::plot::Palette::Color)); view.setColorRange(0.0, 2.0); - std::vector src(16, 1.0f); - view.setImageCopy(src.data(), 4, 4); - const QRgb expected = sls::plot::paletteLut(sls::plot::Palette::Color)[127]; - QCOMPARE(dominantPixelAtData(view, render(view), 0.5, 0.5), expected); + std::vector src(16, 1.0); + view.setImage(src.data(), 4, 4); + QCOMPARE(dominantPixelAtData(view, render(view), 0.5, 0.5), + sls::plot::paletteLut(Palette::Color)[127]); - // The producer owns and recycles its buffer: the view must have copied it. - std::fill(src.begin(), src.end(), 2.0f); - // Force a recomposition from the widget-owned data (no new frame pushed). - view.setColorRange(0.0, 2.0); - const QImage after = render(view); - QCOMPARE(dominantPixelAtData(view, after, 0.5, 0.5), expected); + // the caller may reuse its buffer: a new palette still shows 1.0 + std::fill(src.begin(), src.end(), 2.0); + view.setPalette(Palette::Gray); + QCOMPARE(dominantPixelAtData(view, render(view), 0.5, 0.5), + sls::plot::paletteLut(Palette::Gray)[127]); - // Same for the double overload (the GUI feeds double frames). - std::vector dsrc(16, 1.0); - view.setImageCopy(dsrc.data(), 4, 4); - QCOMPARE(dominantPixelAtData(view, render(view), 1.5, 1.5), expected); - std::fill(dsrc.begin(), dsrc.end(), 2.0); - view.setColorRange(0.0, 2.0); - QCOMPARE(dominantPixelAtData(view, render(view), 1.5, 1.5), expected); - - // Invalid input is ignored, the previous frame stays valid. - view.setImageCopy(static_cast(nullptr), 4, 4); - view.setImageCopy(src.data(), 0, 4); + // invalid input is ignored + view.setImage(nullptr, 4, 4); + view.setImage(src.data(), 0, 4); QCOMPARE(view.imageWidth(), 4); QCOMPARE(view.imageHeight(), 4); } -void PlottingTest::fastImageYUp() { +void PlottingTest::imageYUp() { sls::SlsQtFastImage view; view.resize(200, 200); view.show(); - QTest::qWait(5); - view.setPaletteLut(sls::plot::paletteLut(sls::plot::Palette::Gray)); + view.setPalette(Palette::Gray); view.setColorRange(0.0, 4.0); - // row 0 = bottom = 0, row 1 = top = 3 - std::vector f{0, 0, 0, 0, 3, 3, 3, 3}; - view.setImageCopy(f.data(), 4, 2); + // row 0 is the bottom row + const std::vector f{0, 0, 0, 0, 3, 3, 3, 3}; + view.setImage(f.data(), 4, 2); const QImage img = render(view); - // Data y is up: y=0.5 (bottom row) is drawn below y=1.5 (top row). QVERIFY(widgetPos(view, 0.5, 0.5).y() > widgetPos(view, 0.5, 1.5).y()); - const QRgb *lut = sls::plot::paletteLut(sls::plot::Palette::Gray); + const QRgb *lut = sls::plot::paletteLut(Palette::Gray); QCOMPARE(dominantPixelAtData(view, img, 0.5, 0.5), lut[0]); - QCOMPARE(dominantPixelAtData(view, img, 0.5, 1.5), - lut[int((3.0 - 0.0) * 255.0 / 4.0)]); - // Exactly one flip: both quarters of the top row match, no mirrored mix. - QCOMPARE(dominantPixelAtData(view, img, 2.5, 1.5), - dominantPixelAtData(view, img, 0.5, 1.5)); + QCOMPARE(dominantPixelAtData(view, img, 0.5, 1.5), lut[3 * 255 / 4]); + QCOMPARE(dominantPixelAtData(view, img, 2.5, 1.5), lut[3 * 255 / 4]); } -void PlottingTest::fastImageHistogramWindow() { +void PlottingTest::imageLogScale() { sls::SlsQtFastImage view; view.resize(200, 200); view.show(); - QTest::qWait(5); - view.setLogScale(false); + view.setLogScale(true); + view.setColorRange(0.01, 100.0); + const double nan = std::numeric_limits::quiet_NaN(); + const std::vector f{-100.0, 0.0, 0.01, 0.02, 1000.0, nan, 1.0, 1.0}; + view.setImage(f.data(), 4, 2); + const QImage img = render(view); + const QRgb *lut = sls::plot::paletteLut(Palette::Color); - // 64x32 ramp, value == x: only x in [0,4] is inside the 1..3 window. + // everything <= 0 is shown like 1e-2, the lower end of this range + QCOMPARE(dominantPixelAtData(view, img, 0.5, 0.5), lut[0]); + QCOMPARE(dominantPixelAtData(view, img, 1.5, 0.5), lut[0]); + QCOMPARE(dominantPixelAtData(view, img, 2.5, 0.5), lut[0]); + QVERIFY(dominantPixelAtData(view, img, 3.5, 0.5) != lut[0]); + // above the range and not finite + QCOMPARE(dominantPixelAtData(view, img, 0.5, 1.5), lut[255]); + QCOMPARE(dominantPixelAtData(view, img, 1.5, 1.5), lut[0]); + // 1 is halfway between 1e-2 and 1e2 + QCOMPARE(dominantPixelAtData(view, img, 2.5, 1.5), lut[127]); +} + +void PlottingTest::imageHistogram() { + sls::SlsQtFastImage view; + view.resize(200, 200); + view.show(); const int nx = 64, ny = 32; - std::vector ramp(size_t(nx) * ny); - for (int y = 0; y < ny; y++) - for (int x = 0; x < nx; x++) - ramp[size_t(y) * nx + x] = float(x); + const std::vector ramp = xRamp(nx, ny); view.setColorRange(1.0, 3.0); - view.setImageCopy(ramp.data(), nx, ny); + view.setImage(ramp.data(), nx, ny); + QSignalSpy spy(&view, &sls::SlsQtFastImage::histogramChanged); render(view); + QCOMPARE(spy.count(), 1); + // the colour range widened by half its width on both sides double lo = 0.0, hi = 0.0; view.histogramRange(lo, hi); QVERIFY(near(lo, 0.0) && near(hi, 4.0)); QCOMPARE(int(view.histogram().size()), 256); - long long sum = 0; - for (int v : view.histogram()) - sum += v; - QCOMPARE(sum, 5LL * ny); // 0,1,2,3,4 in-window; 5..63 skipped + QCOMPARE(sum(view.histogram()), 5 * ny); // x = 0..4 - // The histogram follows a colour-range change (invalidated, not stale). - // Range 10.2..19.8 -> window 5.1..24.9 (not aligned with the integer ramp). + // follows the colour range, values outside are not counted view.setColorRange(10.2, 19.8); render(view); view.histogramRange(lo, hi); QVERIFY(near(lo, 5.4) && near(hi, 24.6)); - sum = 0; - for (int v : view.histogram()) - sum += v; - QCOMPARE(sum, 19LL * ny); // x = 6..24 - - // Outside values are skipped instead of piling into the edge bins. + QCOMPARE(sum(view.histogram()), 19 * ny); // x = 6..24 QCOMPARE(view.histogram().front(), 0); QCOMPARE(view.histogram().back(), 0); -} - -void PlottingTest::fastImageHistogramLogWindow() { - sls::SlsQtFastImage view; - view.resize(200, 200); - view.show(); - QTest::qWait(5); - const int nx = 64, ny = 32; - std::vector ramp(size_t(nx) * ny); - for (int y = 0; y < ny; y++) - for (int x = 0; x < nx; x++) - ramp[size_t(y) * nx + x] = float(x); + // in log10 of the values with a log scale view.setLogScale(true); - QVERIFY(view.logScale()); view.setColorRange(1.0, 100.0); - view.setImageCopy(ramp.data(), nx, ny); render(view); - - double lo = 0.0, hi = 0.0; view.histogramRange(lo, hi); - // log10(1) - 1 .. log10(100) + 1 QVERIFY(near(lo, -1.0) && near(hi, 3.0)); - long long sum = 0; - for (int v : view.histogram()) - sum += v; - // x=0 is clamped to 1e-2 (log -2) and is outside; x=1..63 are inside. - QCOMPARE(sum, 63LL * ny); -} - -void PlottingTest::fastImageLogClamp() { - sls::SlsQtFastImage view; - view.resize(200, 200); - view.show(); - QTest::qWait(5); - view.setPaletteLut(sls::plot::paletteLut(sls::plot::Palette::Color)); - view.setLogScale(true); - // Lower end is exactly the 1e-2 log clamp, so everything <= 0 maps to the - // first LUT entry while 0.02 (just above the clamp) does not. - view.setColorRange(0.01, 100.0); - std::vector f{-100.0f, 0.0f, 0.01f, 0.02f, 1000.0f, 1000.0f, 1.0f, - 1.0f}; - view.setImageCopy(f.data(), 4, 2); - const QImage img = render(view); - const QRgb *lut = sls::plot::paletteLut(sls::plot::Palette::Color); - - const QRgb clamped0 = dominantPixelAtData(view, img, 0.5, 0.5); - QCOMPARE(clamped0, lut[0]); - QCOMPARE(dominantPixelAtData(view, img, 1.5, 0.5), clamped0); - QCOMPARE(dominantPixelAtData(view, img, 2.5, 0.5), clamped0); - // 0.02 is > 1e-2, so it is not clamped to the bottom colour. - QVERIFY(dominantPixelAtData(view, img, 3.5, 0.5) != clamped0); - // Above the range: top colour, no wraparound. - QCOMPARE(dominantPixelAtData(view, img, 0.5, 1.5), lut[255]); -} - -void PlottingTest::fastImageZeroWhite() { - sls::SlsQtFastImage view; - view.resize(200, 200); - view.show(); - QTest::qWait(5); - view.setPaletteLut(sls::plot::paletteLut(sls::plot::Palette::Color)); - view.setColorRange(0.0, 2.0); - - std::vector f(16, 1.0f); - f[0] = 0.0f; // data pixel (0,0), bottom-left - view.setImageCopy(f.data(), 4, 4); - const QRgb *lut = sls::plot::paletteLut(sls::plot::Palette::Color); - - QVERIFY(!view.zeroWhite()); - QCOMPARE(dominantPixelAtData(view, render(view), 0.5, 0.5), lut[0]); - - view.setZeroWhite(true); - QVERIFY(view.zeroWhite()); - QCOMPARE(dominantPixelAtData(view, render(view), 0.5, 0.5), qRgb(255, 255, 255)); - // A real value is not affected. - QCOMPARE(dominantPixelAtData(view, render(view), 1.5, 1.5), lut[127]); - - // Non-finite pixels use the lowest colour, even with zero-white on. - f[0] = std::numeric_limits::quiet_NaN(); - view.setImageCopy(f.data(), 4, 4); - QCOMPARE(dominantPixelAtData(view, render(view), 0.5, 0.5), lut[0]); - - view.setIntegerValues(true); - QVERIFY(view.integerValues()); - view.setIntegerValues(false); - QVERIFY(!view.integerValues()); + QCOMPARE(sum(view.histogram()), 63 * ny); // x = 0 counts as 1e-2 } // --------------------------------------------------------------------------- -// FastImageView: zoom / viewport / clipping +// SlsQtFastImage: viewport, zoom and pan // --------------------------------------------------------------------------- -void PlottingTest::fastImageZoomCursorInvariance() { +void PlottingTest::imageViewport() { sls::SlsQtFastImage view; view.resize(400, 300); view.show(); - QTest::qWait(5); - // Square image: the whole-image fit is height-limited with a constant - // horizontal letterbox, so the cursor-fixed rule can hold exactly even when - // the viewport is clamped at the minimum size during deep zoom. - const int nx = 64, ny = 64; - std::vector ramp(size_t(nx) * ny, 1.0f); - view.setColorRange(0.0, 2.0); - view.setImageCopy(ramp.data(), nx, ny); - view.resetView(); - - int zoomCalls = 0; - view.onZoomChanged = [&](double, double, double, double) { zoomCalls++; }; - view.setViewport(10.0, 5.0, 30.0, 15.0); // programmatic: no callback - QCOMPARE(zoomCalls, 0); - view.resetView(); - QCOMPARE(zoomCalls, 1); - - const QPointF cursor(200.0, 150.0); - for (int i = 0; i < 5; i++) { - const QPointF before = view.widgetToData(cursor); - sendWheel(view, cursor, 120); // zoom in, factor 1/1.18 - const QPointF after = view.widgetToData(cursor); - QVERIFY2(near(before.x(), after.x(), 1e-6), - "wheel zoom must keep the cursor x fixed"); - QVERIFY2(near(before.y(), after.y(), 1e-6), - "wheel zoom must keep the cursor y fixed"); - } - double vx, vy, vw, vh; - view.viewport(vx, vy, vw, vh); - QVERIFY(vw < nx && vh < ny); - QVERIFY(zoomCalls >= 6); // 1 reset + 5 wheels - - // Deep zoom clamps to the minimum viewport instead of collapsing. - for (int i = 0; i < 40; i++) - sendWheel(view, cursor, 120); - view.viewport(vx, vy, vw, vh); - QVERIFY2(vw >= sls::SlsQtFastImage::kMinimumViewport - 1e-9, - "viewport clamps to the minimum width"); - QVERIFY2(vh >= sls::SlsQtFastImage::kMinimumViewport - 1e-9, - "viewport clamps to the minimum height"); - - // Zooming back out stops at the full frame and keeps the cursor point. - for (int i = 0; i < 60; i++) { - const QPointF before = view.widgetToData(cursor); - sendWheel(view, cursor, -120); - const QPointF after = view.widgetToData(cursor); - QVERIFY(near(before.x(), after.x(), 1e-6)); - QVERIFY(near(before.y(), after.y(), 1e-6)); - } - view.viewport(vx, vy, vw, vh); - QVERIFY(near(vw, nx) && near(vh, ny)); - QVERIFY(near(vx, 0.0) && near(vy, 0.0)); -} - -void PlottingTest::fastImageViewportClamping() { - sls::SlsQtFastImage view; - view.resize(400, 300); - view.show(); - QTest::qWait(5); const int nx = 64, ny = 32; - std::vector ramp(size_t(nx) * ny, 1.0f); - view.setImageCopy(ramp.data(), nx, ny); - view.resetView(); + const std::vector ramp = xRamp(nx, ny); + view.setImage(ramp.data(), nx, ny); + QSignalSpy spy(&view, &sls::SlsQtFastImage::viewportChanged); double x, y, w, h; - // Requested viewports are clamped to the image bounds. - view.setViewport(-100.0, -100.0, 5000.0, 5000.0); - view.viewport(x, y, w, h); - QVERIFY(near(x, 0.0) && near(y, 0.0)); - QVERIFY(near(w, nx) && near(h, ny)); - - // A viewport smaller than the minimum is rejected (state unchanged). - view.setViewport(10.0, 10.0, 10.5, 10.5); - view.viewport(x, y, w, h); - QVERIFY(near(w, nx) && near(h, ny)); - - // A viewport that would stick out on the right/top is slid back inside. - view.setViewport(60.0, 28.0, 70.0, 38.0); - view.viewport(x, y, w, h); - QVERIFY(near(w, 10.0) && near(h, 10.0)); - QVERIFY(x >= 0.0 && x + w <= nx + 1e-9); - QVERIFY(y >= 0.0 && y + h <= ny + 1e-9); - - // Non-finite values are ignored. - const double nan = std::numeric_limits::quiet_NaN(); - view.setViewport(nan, 0.0, 10.0, 10.0); - view.viewport(x, y, w, h); - QVERIFY(near(w, 10.0) && near(h, 10.0)); - - view.resetView(); + // the whole image to start with view.viewport(x, y, w, h); QVERIFY(near(x, 0.0) && near(y, 0.0) && near(w, nx) && near(h, ny)); - // Pixel aspect stretches x only and is validated. - view.setPixelAspectX(2.0); - QCOMPARE(view.pixelAspectX(), 2.0); - view.setPixelAspectX(-1.0); - QCOMPARE(view.pixelAspectX(), 1.0); + // clamped to the image + view.setViewport(-100.0, -100.0, 5000.0, 5000.0); + view.viewport(x, y, w, h); + QVERIFY(near(x, 0.0) && near(y, 0.0) && near(w, nx) && near(h, ny)); + + // moved back inside + view.setViewport(60.0, 28.0, 70.0, 38.0); + view.viewport(x, y, w, h); + QVERIFY(near(x, 54.0) && near(y, 22.0) && near(w, 10.0) && near(h, 10.0)); + + // too small or not finite: ignored + view.setViewport(10.0, 10.0, 10.5, 10.5); + view.setViewport(std::numeric_limits::quiet_NaN(), 0.0, 9.0, 9.0); + view.viewport(x, y, w, h); + QVERIFY(near(x, 54.0) && near(y, 22.0) && near(w, 10.0) && near(h, 10.0)); + + // only the user and resetView() are reported + QCOMPARE(spy.count(), 0); + view.resetView(); + QCOMPARE(spy.count(), 1); + QCOMPARE(spy.at(0).at(0).toRectF(), QRectF(0, 0, nx, ny)); + + // a new image size shows the whole image again + view.setViewport(10.0, 10.0, 20.0, 20.0); + view.setImage(ramp.data(), ny, nx); + view.viewport(x, y, w, h); + QVERIFY(near(x, 0.0) && near(y, 0.0) && near(w, ny) && near(h, nx)); } -void PlottingTest::fastImageClipsToPlotRect() { +void PlottingTest::imageWheelZoom() { sls::SlsQtFastImage view; view.resize(400, 300); view.show(); - QTest::qWait(5); - const int nx = 1024, ny = 512; - std::vector frame = acceptanceFrame(); + const int n = 64; + const std::vector ramp = xRamp(n, n); + view.setImage(ramp.data(), n, n); + QSignalSpy spy(&view, &sls::SlsQtFastImage::viewportChanged); + + // zooming in keeps the point under the cursor + const QPointF cursor(200.0, 150.0); + for (int i = 0; i < 5; i++) { + const QPointF before = view.widgetToData(cursor); + sendWheel(view, cursor, 120); + const QPointF after = view.widgetToData(cursor); + QVERIFY(near(before.x(), after.x()) && near(before.y(), after.y())); + } + QCOMPARE(spy.count(), 5); + double x, y, w, h; + view.viewport(x, y, w, h); + QVERIFY(w < n && h < n); + + // down to the minimum viewport + for (int i = 0; i < 40; i++) + sendWheel(view, cursor, 120); + view.viewport(x, y, w, h); + QVERIFY(near(w, sls::SlsQtFastImage::kMinimumViewport)); + QVERIFY(near(h, sls::SlsQtFastImage::kMinimumViewport)); + + // and back out to the whole image + for (int i = 0; i < 60; i++) + sendWheel(view, cursor, -120); + view.viewport(x, y, w, h); + QVERIFY(near(x, 0.0) && near(y, 0.0) && near(w, n) && near(h, n)); + + // not when zooming is disabled + view.setZoomEnabled(false); + sendWheel(view, cursor, 120); + view.viewport(x, y, w, h); + QVERIFY(near(w, n) && near(h, n)); +} + +void PlottingTest::imagePan() { + sls::SlsQtFastImage view; + view.resize(400, 300); + view.show(); + const int n = 64; + const std::vector ramp = xRamp(n, n); + view.setImage(ramp.data(), n, n); + view.setViewport(20.0, 20.0, 40.0, 40.0); + QSignalSpy spy(&view, &sls::SlsQtFastImage::viewportChanged); + + // the grabbed point follows the cursor + const QPointF from(200.0, 150.0), to(230.0, 130.0); + const QPointF grabbed = view.widgetToData(from); + sendMouse(view, QEvent::MouseButtonPress, from, Qt::LeftButton, + Qt::LeftButton); + sendMouse(view, QEvent::MouseMove, to, Qt::NoButton, Qt::LeftButton); + sendMouse(view, QEvent::MouseButtonRelease, to, Qt::LeftButton, + Qt::NoButton); + const QPointF dropped = view.widgetToData(to); + QVERIFY(near(grabbed.x(), dropped.x()) && near(grabbed.y(), dropped.y())); + QVERIFY(spy.count() >= 1); + double x, y, w, h; + view.viewport(x, y, w, h); + QVERIFY(x < 20.0 && y < 20.0 && near(w, 20.0) && near(h, 20.0)); + + // a double click shows the whole image + sendMouse(view, QEvent::MouseButtonDblClick, to, Qt::LeftButton, + Qt::LeftButton); + view.viewport(x, y, w, h); + QVERIFY(near(x, 0.0) && near(y, 0.0) && near(w, n) && near(h, n)); +} + +// --------------------------------------------------------------------------- +// SlsQtFastImage: painting +// --------------------------------------------------------------------------- +void PlottingTest::imageIsClippedToPlotArea() { + sls::SlsQtFastImage view; + view.resize(400, 300); + view.show(); + const std::vector frame = testFrame(); view.setColorRange(-2.0, 2.0); - view.setImageCopy(frame.data(), nx, ny); - view.resetView(); + view.setImage(frame.data(), 1024, 512); - // Margins of the widget: the plot rect is QRect(52, 6, w-58, h-32). - const QRect ir = sls::plot::plotRectFor(view.size(), sls::plot::PlotTheme()); - QCOMPARE(ir, QRect(52, 6, 400 - 58, 300 - 32)); - - // Zoom so the scaled image is much larger than the plot area; without the - // clip it would paint over the right/top margins. + // zoomed in, the scaled image is much larger than the plot area view.setViewport(100.0, 100.0, 164.0, 132.0); const QImage img = render(view); - QVERIFY(img.width() == 400 && img.height() == 300); - - for (int y = ir.top(); y <= ir.bottom(); y++) { - for (int x = ir.right() + 1; x < img.width(); x++) { - QVERIFY2(img.pixel(x, y) == kBackground, - "zoomed image must be clipped to the plot rect (right " - "margin)"); - } - } - for (int x = ir.left(); x <= img.width() - 1; x++) { - for (int y = 0; y < ir.top(); y++) { - QVERIFY2(img.pixel(x, y) == kBackground, - "zoomed image must be clipped to the plot rect (top " - "margin)"); - } - } - // ... while the image itself is definitely painted inside. - QVERIFY(img.pixel(ir.center()) != kBackground); + const QRect plot = plotArea(view); + QCOMPARE(plot, QRect(52, 6, 400 - 58, 300 - 32)); + QVERIFY(img.pixel(plot.center()) != kBackground); + QCOMPARE(countOutside(img, plot, [](QRgb c) { return c != kBackground; }), + 0); } -void PlottingTest::fastImageOverlaysInDataCoordinates() { +void PlottingTest::imageOverlays() { sls::SlsQtFastImage view; view.resize(400, 300); view.show(); - QTest::qWait(5); - const int nx = 1024, ny = 512; - std::vector frame = acceptanceFrame(); + const std::vector frame = testFrame(); view.setColorRange(-2.0, 2.0); - view.setImageCopy(frame.data(), nx, ny); - view.resetView(); + view.setImage(frame.data(), 1024, 512); + const QImage plain = render(view); - // (120,110) lower-left + 20x10, entirely inside the view. + // lower left corner (120, 110), 20 x 10 pixels view.setOverlayRects({QRectF(120.0, 110.0, 20.0, 10.0)}); QCOMPARE(int(view.overlayRects().size()), 1); QImage img = render(view); - const QPointF topLeft = view.dataToWidget(QPointF(120.0, 120.0)); - QVERIFY2(yellowNear(img, topLeft.toPoint(), 2), - "overlay must be drawn at its data coordinates (yellow)"); - const QPointF bottomRight = view.dataToWidget(QPointF(140.0, 110.0)); - QVERIFY(yellowNear(img, bottomRight.toPoint(), 2)); + QVERIFY(yellowNear(img, widgetPos(view, 120.0, 120.0).toPoint())); + QVERIFY(yellowNear(img, widgetPos(view, 140.0, 110.0).toPoint())); + QVERIFY(!yellowNear(img, widgetPos(view, 130.0, 115.0).toPoint(), 0)); - // A rectangle crossing the plot edge is clipped: no yellow outside. + // sticking out of the image: clipped view.setOverlayRects({QRectF(1000.0, 400.0, 400.0, 400.0)}); img = render(view); - const QRect ir = sls::plot::plotRectFor(view.size(), sls::plot::PlotTheme()); - for (int x = ir.right() + 1; x < img.width(); x++) { - for (int y = 0; y < img.height(); y++) { - const QRgb c = img.pixel(x, y); - QVERIFY2(!(qRed(c) > 180 && qGreen(c) > 180 && qBlue(c) < 90), - "overlays must be clipped to the plot rect"); - } - } - view.clearOverlayRects(); - QVERIFY(view.overlayRects().empty()); + QVERIFY(countPixels(img, isYellow) > 0); + QCOMPARE(countOutside(img, plotArea(view), isYellow), 0); + view.setOverlayRects({}); + QCOMPARE(render(view), plain); - // Editable gate ROI and receiver ROI are reported back in data coords. - view.setRoiRect(10.0, 20.0, 110.0, 220.0); - double x0, y0, x1, y1; - QVERIFY(view.roiRect(x0, y0, x1, y1)); - QVERIFY(near(x0, 10.0) && near(y1, 220.0)); - view.setRoiRectVisible(false); - QVERIFY(!view.roiRect(x0, y0, x1, y1)); - view.setReceiverRoiRect(5.0, 6.0, 7.0, 8.0); - view.clearReceiverRoiRect(); + // from corner to corner and beyond + view.setOverlayLines({QLineF(0.0, 0.0, 2048.0, 1024.0)}); + img = render(view); + QVERIFY(isBright(img.pixel(widgetPos(view, 512.0, 256.0).toPoint()))); + const QRect changed = differingArea(plain, img); + QVERIFY(changed.width() > 300 && plotArea(view).contains(changed)); + view.setOverlayLines({}); + QCOMPARE(render(view), plain); } -void PlottingTest::fastImageTitlesAndAspect() { +void PlottingTest::imageInterpolation() { sls::SlsQtFastImage view; view.resize(400, 300); view.show(); - QTest::qWait(5); - std::vector ramp(64 * 32, 1.0f); - view.setImageCopy(ramp.data(), 64, 32); + // one bright pixel, shown at about 8 widget pixels per image pixel + std::vector f(32 * 32, 0.0); + f[16 * 32 + 16] = 1.0; + view.setPalette(Palette::Gray); + view.setColorRange(0.0, 1.0); + view.setImage(f.data(), 32, 32); + const QPoint neighbour = widgetPos(view, 15.9, 16.5).toPoint(); + + QCOMPARE(render(view).pixel(neighbour), qRgb(0, 0, 0)); + view.setInterpolate(true); + QVERIFY(qGray(render(view).pixel(neighbour)) > 0); + + // not once the pixels are outlined + view.setViewport(12.0, 12.0, 20.0, 20.0); + QCOMPARE(dominantPixelAtData(view, render(view), 15.5, 16.5), + qRgb(0, 0, 0)); +} + +void PlottingTest::imageTitles() { + sls::SlsQtFastImage view; + view.resize(400, 300); + view.show(); + const std::vector ramp = xRamp(64, 32); + view.setImage(ramp.data(), 64, 32); + const QPointF before = widgetPos(view, 0.0, 32.0); - QVERIFY(view.title().isEmpty()); view.setTitle(QStringLiteral("Detector 0")); view.setXAxisTitle(QStringLiteral("x [px]")); view.setYAxisTitle(QStringLiteral("y [px]")); QCOMPARE(view.title(), QStringLiteral("Detector 0")); QCOMPARE(view.xAxisTitle(), QStringLiteral("x [px]")); QCOMPARE(view.yAxisTitle(), QStringLiteral("y [px]")); - // A title consumes a row at the top; the image must still render. - const QImage img = render(view); - const QRect ir = sls::plot::plotRectFor(view.size(), sls::plot::PlotTheme()); - QVERIFY(img.pixel(ir.center()) != kBackground); - QFont f; - f.setPixelSize(17); - view.setTitleFont(f); - QCOMPARE(view.titleFont().pixelSize(), 17); - view.setAxisTitleFont(f); - QCOMPARE(view.axisTitleFont().pixelSize(), 17); - view.setTickFont(f); - QCOMPARE(view.tickFont().pixelSize(), 17); + // the titles take their space from the image + const QPointF after = widgetPos(view, 0.0, 32.0); + QVERIFY(after.x() > before.x() && after.y() > before.y()); + render(view); + + // nothing but the image without axes + view.setTitle(QString()); + view.setXAxisTitle(QString()); + view.setYAxisTitle(QString()); + view.setAxesVisible(false); + QVERIFY(!view.axesVisible()); + QCOMPARE(widgetPos(view, 0.0, 0.0).x(), 0.0); } // --------------------------------------------------------------------------- -// ScaleHisto: three-way freeze rule +// SlsQtScaleHisto and SlsQtScalePanel // --------------------------------------------------------------------------- -void PlottingTest::scaleHistoThreeWayFreeze() { +void PlottingTest::scaleHistoDrag() { sls::SlsQtScaleHisto histo; histo.resize(400, 38); histo.show(); - QTest::qWait(5); + // colour range 10..20: the axis shows 5..25, markers at x = 100 and 300 + histo.setData(std::vector(256, 5), 5.0, 25.0, 10.0, 20.0, false, + false); + QSignalSpy spy(&histo, &sls::SlsQtScaleHisto::rangeChanged); + const QImage before = render(histo); - std::vector bins(256, 0); - bins[100] = 10; - bins[200] = 300; - histo.setData(&bins, 0.0, 1.0, 0.2, 0.8, false, false); - double dw0 = 0.0, dw1 = 0.0; - histo.displayedWindow(dw0, dw1); - QVERIFY(near(dw0, -0.1, 1e-9) && near(dw1, 1.1, 1e-9)); - double cw0 = 0.0, cw1 = 0.0; - histo.currentWindow(cw0, cw1); - QVERIFY(near(cw0, 0.2) && near(cw1, 0.8)); - - int rangeCalls = 0; - double newLo = 0.0, newHi = 0.0; - histo.onRangeChanged = [&](double a, double b) { - rangeCalls++; - newLo = a; - newHi = b; - }; - - const int W = histo.width(); - const QPointF marker(W * 0.25, 19.0); - sendMouse(histo, QEvent::MouseButtonPress, marker, Qt::LeftButton, + sendMouse(histo, QEvent::MouseButtonPress, QPointF(100, 19), Qt::LeftButton, Qt::LeftButton); QVERIFY(histo.isDragging()); + sendMouse(histo, QEvent::MouseMove, QPointF(160, 19), Qt::NoButton, + Qt::LeftButton); - // Freeze #1 (bars): a live histogram update must be ignored. - const std::vector *frozen = histo.displayedHistogram(); - QVERIFY(frozen != nullptr); - QVERIFY(frozen != &bins); - QCOMPARE(int(frozen->size()), 256); - QCOMPARE((*frozen)[100], 10); - std::vector live2(256, 0); - live2[50] = 999; - histo.setData(&live2, 0.0, 1.0, 0.0, 1.0, false, false); - QVERIFY2(histo.displayedHistogram() == frozen, - "histogram bars must be frozen while dragging"); - QCOMPARE((*histo.displayedHistogram())[100], 10); - QCOMPARE((*histo.displayedHistogram())[200], 300); + // only a preview line moves and new data has to wait + std::vector other(256, 1); + other[60] = 100; + histo.setData(other, 0.0, 100.0, 50.0, 60.0, false, false); + const QImage during = render(histo); + QCOMPARE(spy.count(), 0); + QVERIFY(during != before); + for (const int x : {50, 100, 250, 300, 350}) + QCOMPARE(during.copy(x, 0, 1, 38), before.copy(x, 0, 1, 38)); - // Freeze #2 (axis window): still the press-time window after a move. - const int previewAtPress = histo.previewX(); - sendMouse(histo, QEvent::MouseMove, QPointF(W * 0.40, 19.0), - Qt::NoButton, Qt::LeftButton); - QVERIFY(histo.isDragging()); - double fw0 = 0.0, fw1 = 0.0; - histo.displayedWindow(fw0, fw1); - QVERIFY2(near(fw0, dw0) && near(fw1, dw1), - "axis window must stay frozen while dragging"); - - // Freeze #3 (cursor mapping): the pre-move range is used, so these must be - // stable no matter how often the mouse moves. - double l0 = 0.0, l1 = 0.0; - histo.currentWindow(l0, l1); - QVERIFY(l0 > 0.2); // preview moved the low end - for (int i = 0; i < 3; i++) - sendMouse(histo, QEvent::MouseMove, QPointF(W * 0.40, 19.0), - Qt::NoButton, Qt::LeftButton); - double l2 = 0.0, l3 = 0.0; - histo.currentWindow(l2, l3); - QVERIFY(near(l0, l2) && near(l1, l3)); - QVERIFY2(histo.previewX() != previewAtPress, - "only the dashed preview line moves"); - QCOMPARE(rangeCalls, 0); // nothing applied before release - - // Painting mid-drag must not mutate the frozen state either. - (void)histo.grab(); - histo.displayedWindow(fw0, fw1); - QVERIFY(near(fw0, dw0) && near(fw1, dw1)); - QVERIFY(histo.displayedHistogram() == frozen); - - sendMouse(histo, QEvent::MouseButtonRelease, QPointF(W * 0.40, 19.0), + // x = 160 is at 40% of the axis 5..25 + sendMouse(histo, QEvent::MouseButtonRelease, QPointF(160, 19), Qt::LeftButton, Qt::NoButton); QVERIFY(!histo.isDragging()); - QCOMPARE(rangeCalls, 1); // applied exactly once, on release - QVERIFY(near(newLo, l2) && near(newHi, l3)); - QVERIFY2(histo.displayedHistogram() == &bins, - "live histogram is restored after release"); - double nw0 = 0.0, nw1 = 0.0; - histo.displayedWindow(nw0, nw1); - QVERIFY2(!near(nw0, dw0) || !near(nw1, dw1), - "the axis rebuilds from the new range after release"); + QCOMPARE(spy.count(), 1); + QVERIFY(near(spy.at(0).at(0).toDouble(), 13.0)); + QVERIFY(near(spy.at(0).at(1).toDouble(), 20.0)); - // A press far away from both markers is ignored. - sendMouse(histo, QEvent::MouseButtonPress, QPointF(W * 0.5, 19.0), - Qt::LeftButton, Qt::LeftButton); + // a click away from the markers does nothing + sendMouse(histo, QEvent::MouseButtonPress, QPointF(200, 19), Qt::LeftButton, + Qt::LeftButton); QVERIFY(!histo.isDragging()); - sendMouse(histo, QEvent::MouseButtonRelease, QPointF(W * 0.5, 19.0), + sendMouse(histo, QEvent::MouseButtonRelease, QPointF(200, 19), Qt::LeftButton, Qt::NoButton); - QCOMPARE(rangeCalls, 1); + QCOMPARE(spy.count(), 1); } -void PlottingTest::scaleHistoMaxMarker() { +void PlottingTest::scaleHistoLogAxis() { sls::SlsQtScaleHisto histo; histo.resize(400, 38); histo.show(); - QTest::qWait(5); - std::vector bins(256, 1); - histo.setData(&bins, 0.0, 1.0, 0.2, 0.8, false, false); - - int rangeCalls = 0; - double newLo = 0.0, newHi = 0.0; - histo.onRangeChanged = [&](double a, double b) { - rangeCalls++; - newLo = a; - newHi = b; + // colour range 1..100: the axis shows 1e-1..1e3 + histo.setData(std::vector(256, 5), -1.0, 3.0, 1.0, 100.0, true, true); + QSignalSpy spy(&histo, &sls::SlsQtScaleHisto::rangeChanged); + const auto drag = [&histo](double from, double to) { + sendMouse(histo, QEvent::MouseButtonPress, QPointF(from, 19), + Qt::LeftButton, Qt::LeftButton); + sendMouse(histo, QEvent::MouseMove, QPointF(to, 19), Qt::NoButton, + Qt::LeftButton); + sendMouse(histo, QEvent::MouseButtonRelease, QPointF(to, 19), + Qt::LeftButton, Qt::NoButton); }; - const int W = histo.width(); - sendMouse(histo, QEvent::MouseButtonPress, QPointF(W * 0.75, 19.0), - Qt::LeftButton, Qt::LeftButton); - QVERIFY(histo.isDragging()); - sendMouse(histo, QEvent::MouseMove, QPointF(W * 0.60, 19.0), - Qt::NoButton, Qt::LeftButton); - sendMouse(histo, QEvent::MouseButtonRelease, QPointF(W * 0.60, 19.0), - Qt::LeftButton, Qt::NoButton); - QCOMPARE(rangeCalls, 1); - QVERIFY(newLo < newHi); - QVERIFY(newHi < 0.8); // max marker dragged down + + // upper marker to the middle of the axis + drag(300, 200); + QCOMPARE(spy.count(), 1); + QVERIFY(near(spy.at(0).at(0).toDouble(), 1.0)); + QVERIFY(near(spy.at(0).at(1).toDouble(), 10.0)); + + // the lower marker cannot pass the upper one + drag(100, 390); + QCOMPARE(spy.count(), 2); + QVERIFY(spy.at(1).at(0).toDouble() < 100.0); + QVERIFY(near(spy.at(1).at(0).toDouble(), 100.0)); + QVERIFY(near(spy.at(1).at(1).toDouble(), 100.0)); } -// --------------------------------------------------------------------------- -// ScalePanel: re-entrancy, control synchronisation, strip freeze -// --------------------------------------------------------------------------- -void PlottingTest::scalePanelReentrancy() { - sls::SlsQtFastImage view; - view.resize(300, 300); - view.show(); - QTest::qWait(5); - std::vector ramp(64 * 32); - for (int i = 0; i < 64 * 32; i++) - ramp[i] = float(i % 100) / 10.0f; - view.setColorRange(0.0, 10.0); - view.setImageCopy(ramp.data(), 64, 32); - view.repaint(); +void PlottingTest::scalePanel() { + QWidget window; + auto *view = new sls::SlsQtFastImage(&window); + auto *panel = new sls::SlsQtScalePanel(view, &window); + auto *layout = new QVBoxLayout(&window); + layout->addWidget(view); + layout->addWidget(panel); + window.resize(500, 500); + window.show(); + std::vector ramp = xRamp(64, 32); + std::fill_n(ramp.begin(), 64 * 8, 12.0); // not the same count per bin + view->setColorRange(10.0, 20.0); + view->setImage(ramp.data(), 64, 32); + render(window); - sls::SlsQtScalePanel panel(&view); - panel.resize(760, 78); - panel.show(); - QTest::qWait(5); - QVERIFY(panel.histogramWidget() != nullptr); - QVERIFY(panel.view() == &view); - QVERIFY(!panel.isDragging()); + // in the order they are created: palette, image lin/log, histogram lin/log + const QList combos = panel->findChildren(); + QCOMPARE(combos.size(), 3); + QCOMPARE(combos[0]->count(), sls::plot::paletteCount()); - // view -> controls -> view must not recurse (sympass guard): one change, - // one control update, no push-back loop. The min/max spin boxes were - // removed from the plot window; the range is owned by the Plot tab, so - // the panel only keeps the last range it read from/wrote to the view - // (controlRange(), not spin-box widgets). - int rangeCalls = 0; - view.onColorRangeChanged = [&](double, double) { rangeCalls++; }; - panel.setColorRange(1.0, 5.0); - QCOMPARE(rangeCalls, 1); - double a = 0.0, b = 0.0; - view.colorRange(a, b); - QVERIFY(near(a, 1.0) && near(b, 5.0)); - panel.controlRange(a, b); - QVERIFY(near(a, 1.0) && near(b, 5.0)); + // the controls show the view + view->setPalette(Palette::Viridis); + view->setLogScale(true); + QCOMPARE(combos[0]->currentIndex(), int(Palette::Viridis)); + QCOMPARE(combos[1]->currentIndex(), 1); - // refresh()/push() round trip is stable (idempotent, no re-entrancy). - panel.refresh(); - panel.push(); - view.colorRange(a, b); - QVERIFY(near(a, 1.0) && near(b, 5.0)); - panel.refresh(); - panel.refresh(); - view.colorRange(a, b); - QVERIFY(near(a, 1.0) && near(b, 5.0)); + // and change it + combos[0]->setCurrentIndex(int(Palette::Gray)); + combos[1]->setCurrentIndex(0); + QCOMPARE(view->palette(), Palette::Gray); + QVERIFY(!view->logScale()); - // Palette and image-log controls stay in sync with the view. - panel.setPaletteChoice(3); - QCOMPARE(view.paletteIndex(), 3); - QCOMPARE(view.paletteIndex(), int(sls::plot::Palette::Turbo)); - QCOMPARE(panel.paletteChoice(), 3); - panel.setImageLog(true); - QVERIFY(view.logScale()); - QVERIFY(!view.isScaleDragging()); - panel.setImageLog(false); - QVERIFY(!view.logScale()); - panel.setHistoLog(true); - QVERIFY(panel.histoLog()); - - // A strip drag freezes the strip; refresh() during the drag (the image - // keeps arriving in the real GUI) must not feed back into it. - sls::SlsQtScaleHisto *strip = panel.histogramWidget(); - double sw0 = 0.0, sw1 = 0.0; - strip->displayedWindow(sw0, sw1); - const std::vector *live = strip->displayedHistogram(); - QVERIFY(live != nullptr); - const int W = strip->width(); - sendMouse(*strip, QEvent::MouseButtonPress, QPointF(W * 0.25, 10.0), - Qt::LeftButton, Qt::LeftButton); - QVERIFY(strip->isDragging()); - QVERIFY(panel.isDragging()); - const std::vector *frozen = strip->displayedHistogram(); - QVERIFY2(frozen != live, "drag paints a snapshot, not the live bars"); - panel.refresh(); - sendMouse(*strip, QEvent::MouseMove, QPointF(W * 0.40, 10.0), - Qt::NoButton, Qt::LeftButton); - panel.refresh(); - double dw0 = 0.0, dw1 = 0.0; - strip->displayedWindow(dw0, dw1); - QVERIFY2(near(dw0, sw0) && near(dw1, sw1), - "panel refresh must not move the frozen strip"); - QVERIFY2(strip->displayedHistogram() == frozen, - "panel refresh must not replace the frozen bars"); - - sendMouse(*strip, QEvent::MouseButtonRelease, QPointF(W * 0.40, 10.0), - Qt::LeftButton, Qt::NoButton); - QVERIFY(!strip->isDragging()); - QVERIFY(!panel.isDragging()); - // Release applied the previewed range to the view. - view.colorRange(a, b); - QVERIFY(b > a); - QVERIFY(!near(a, 1.0) || !near(b, 5.0)); - - // Detach/reattach keeps working and preserves the view callbacks. - panel.setView(nullptr); - QVERIFY(panel.view() == nullptr); - panel.setView(&view); - QVERIFY(panel.view() == &view); - panel.refresh(); // must not crash with a fresh attachment -} - -// --------------------------------------------------------------------------- -// ScalePanel R1/R2 (task-11): strip freeze and the controls->view push rules -// --------------------------------------------------------------------------- -void PlottingTest::scalePanelFreezeAndPushRules() { - sls::SlsQtFastImage view; - view.resize(400, 400); - view.show(); - QTest::qWait(5); - std::vector data(64 * 64); - for (int i = 0; i < 64 * 64; i++) - data[size_t(i)] = float(i % 100) / 10.0f; - view.setColorRange(1.0, 5.0); - view.setImageCopy(data.data(), 64, 64); - view.repaint(); - - sls::SlsQtScalePanel panel(&view); - panel.resize(760, 78); - panel.show(); - QTest::qWait(5); + const QImage linear = render(*panel->histogramWidget()); + combos[2]->setCurrentIndex(1); + QVERIFY(render(*panel->histogramWidget()) != linear); + // dragging the lower marker from 25% to 40% of the strip + QSignalSpy spy(panel, &sls::SlsQtScalePanel::colorRangeEdited); + sls::SlsQtScaleHisto *histo = panel->histogramWidget(); + const QPointF from(0.25 * histo->width(), 19), to(0.4 * histo->width(), 19); + sendMouse(*histo, QEvent::MouseButtonPress, from, Qt::LeftButton, + Qt::LeftButton); + sendMouse(*histo, QEvent::MouseMove, to, Qt::NoButton, Qt::LeftButton); + sendMouse(*histo, QEvent::MouseButtonRelease, to, Qt::LeftButton, + Qt::NoButton); double lo = 0.0, hi = 0.0; - panel.controlRange(lo, hi); - QVERIFY(near(lo, 1.0) && near(hi, 5.0)); - int rangeCalls = 0; - view.onColorRangeChanged = [&](double, double) { rangeCalls++; }; + view->colorRange(lo, hi); + QVERIFY(near(lo, 13.0) && near(hi, 20.0)); + QCOMPARE(spy.count(), 1); - // R1: while a strip marker is dragged, incoming frames may change the - // view's colour range, but refresh() must keep the controls frozen at the - // press-time values (and the strip axis/bars frozen as well). - auto *strip = panel.histogramWidget(); - double frozenW0 = 0.0, frozenW1 = 0.0; - strip->displayedWindow(frozenW0, frozenW1); - const std::vector *liveBars = strip->displayedHistogram(); - sendMouse(*strip, QEvent::MouseButtonPress, - QPointF(strip->width() * 0.25, strip->height() / 2.0), - Qt::LeftButton, Qt::LeftButton); - QVERIFY(strip->isDragging()); - const std::vector *frozenBars = strip->displayedHistogram(); - QVERIFY2(frozenBars != nullptr && frozenBars != liveBars, - "drag paints a press-time histogram snapshot"); - view.setColorRange(2.0, 7.0); - panel.refresh(); - panel.controlRange(lo, hi); - QVERIFY2(near(lo, 1.0) && near(hi, 5.0), - "control range frozen while the strip marker is dragged (R1)"); - view.setColorRange(3.0, 9.0); - panel.refresh(); - panel.controlRange(lo, hi); - QVERIFY2(near(lo, 1.0) && near(hi, 5.0), - "control range still frozen after a second live range change (R1)"); - double dw0 = 0.0, dw1 = 0.0; - strip->displayedWindow(dw0, dw1); - QVERIFY(near(dw0, frozenW0) && near(dw1, frozenW1)); - QVERIFY(strip->displayedHistogram() == frozenBars); - // Move the low marker from its 1/4 place towards 2/5 (the preview value). - sendMouse(*strip, QEvent::MouseMove, - QPointF(strip->width() * 0.40, strip->height() / 2.0), - Qt::NoButton, Qt::LeftButton); - double cw0 = 0.0, cw1 = 0.0; - strip->currentWindow(cw0, cw1); - QVERIFY(cw0 > 2.0); - sendMouse(*strip, QEvent::MouseButtonRelease, - QPointF(strip->width() * 0.40, strip->height() / 2.0), - Qt::LeftButton, Qt::NoButton); - QVERIFY(!strip->isDragging()); - // On release the strip range is applied and the controls follow it. - double vlo = 0.0, vhi = 0.0; - view.colorRange(vlo, vhi); - QVERIFY2(near(vlo, cw0) && near(vhi, cw1), - "strip range applied to the view on release (R1)"); - panel.controlRange(lo, hi); - QVERIFY(std::abs(lo - vlo) <= 0.051); - QVERIFY(std::abs(hi - vhi) <= 0.051); - - // R2: palette/log changes must NOT push the control range into the view - // (that would fire onColorRangeChanged and pin the 2D panel override). - // Only an explicit control-range edit may change the range. - view.setColorRange(0.408939, 40.8); // e.g. SlsQt2DPlot's auto z range - view.repaint(); - const int callsBefore = rangeCalls; - panel.setPaletteChoice(3); - QCOMPARE(rangeCalls, callsBefore); - double a = 0.0, b = 0.0; - view.colorRange(a, b); - QVERIFY2(near(a, 0.408939) && near(b, 40.8), - "palette change leaves the auto z range bit-exact (R2)"); - double plo = 0.0, phi = 0.0; - QVERIFY(!panel.lastPushedRange(plo, phi)); - panel.setImageLog(true); - panel.setImageLog(false); - QCOMPARE(rangeCalls, callsBefore); - view.colorRange(a, b); - QVERIFY(near(a, 0.408939) && near(b, 40.8)); - QVERIFY(!panel.lastPushedRange(plo, phi)); - panel.controlRange(lo, hi); - QVERIFY(near(lo, 0.4, 0.051) && near(hi, 40.8, 0.051)); - - // A real operator edit is the only path that pushes a range, exactly once. - panel.setControlRange(2.5, 8.0); - QCOMPARE(rangeCalls, callsBefore + 1); - view.colorRange(a, b); - QVERIFY(near(a, 2.5) && near(b, 8.0)); - QVERIFY(panel.lastPushedRange(plo, phi)); - QVERIFY(near(plo, 2.5) && near(phi, 8.0)); - // A later palette change still does not push the (now edited) range. - panel.setPaletteChoice(5); - QCOMPARE(rangeCalls, callsBefore + 1); - view.colorRange(a, b); - QVERIFY(near(a, 2.5) && near(b, 8.0)); -} - -// --------------------------------------------------------------------------- -// ScalePanel R6 (task-11): the strip never keeps a pointer to a dead histogram -// --------------------------------------------------------------------------- -void PlottingTest::scalePanelDetachLifetime() { - std::vector ramp(64 * 32, 1.0f); - - // Detaching the panel clears the strip's raw histogram pointer, and the - // orphaned strip can still be repainted/grab'ed safely. - auto *view = new sls::SlsQtFastImage; - view->resize(300, 300); - view->show(); - QTest::qWait(5); - view->setImageCopy(ramp.data(), 64, 32); - view->repaint(); - auto *panel = new sls::SlsQtScalePanel(view); - panel->resize(600, 78); - panel->show(); - QTest::qWait(5); - panel->histogramWidget()->repaint(); - QVERIFY(panel->histogramWidget()->displayedHistogram() != nullptr); - panel->setView(nullptr); - QVERIFY(panel->view() == nullptr); - QVERIFY2(panel->histogramWidget()->displayedHistogram() == nullptr, - "detach drops the live histogram pointer (R6)"); - (void)panel->histogramWidget()->grab(); // must not read freed memory - panel->refresh(); - delete panel; - - // Destroying the view clears the strip through the destroyed connection; - // repainting the orphaned panel afterwards is safe. - auto *view2 = new sls::SlsQtFastImage; - view2->resize(300, 300); - view2->show(); - QTest::qWait(5); - view2->setImageCopy(ramp.data(), 64, 32); - view2->repaint(); - auto *panel2 = new sls::SlsQtScalePanel(view2); - panel2->resize(600, 78); - panel2->show(); - QTest::qWait(5); - panel2->histogramWidget()->repaint(); - QVERIFY(panel2->histogramWidget()->displayedHistogram() != nullptr); - delete view2; - QVERIFY(panel2->view() == nullptr); - QVERIFY2(panel2->histogramWidget()->displayedHistogram() == nullptr, - "destroyed view drops the live histogram pointer (R6)"); - (void)panel2->histogramWidget()->grab(); - panel2->refresh(); - delete panel2; - delete view; + // a range set by the program is not an edit + view->setColorRange(0.0, 5.0); + QCOMPARE(spy.count(), 1); } // --------------------------------------------------------------------------- @@ -1167,7 +857,6 @@ void PlottingTest::h1dDataApi() { QCOMPARE(h.GetFirstXgtZero(), 1.0); QCOMPARE(h.GetFirstYgtZero(), 1.0); - // Fill/FillBin/SetContent/SetBinContent follow the old qwt data contract. QCOMPARE(h.FillBin(0, 5.0), 6.0); QCOMPARE(h.GetY()[0], 6.0); QCOMPARE(h.Fill(5.0, 2.0), 8.0); // y[5] was 6, FindBinIndex(5) == 5 @@ -1292,12 +981,11 @@ void PlottingTest::oneDimensionalRangeZoomLogAndGain() { plot.EnableXAutoScaling(); QVERIFY(plot.viewRect().width() > 15.0); - // G/H marker lines, SetYStep and alignScales (API compatibility). + // G/H marker lines and SetYStep. plot.SetYMinMax(0.0, 300.0); plot.InsertHLine(150.0); plot.InsertVLine(50.0); plot.SetYStep(2); - plot.alignScales(); img = render(plot); QVERIFY2(countPixels(img, isYellow) > 20, "H/V marker lines are painted in the plot"); @@ -1305,7 +993,7 @@ void PlottingTest::oneDimensionalRangeZoomLogAndGain() { plot.RemoveVLine(); plot.EnableYAutoScaling(); - // O1 (task-10): on a log-y axis the auto-range padding is applied in + // On a log-y axis the auto-range padding is applied in // log10 space (2 % of the decade span on each side), not to the linear // value, so the top point is not glued to the frame. plot.SetLogY(true); @@ -1339,7 +1027,7 @@ void PlottingTest::oneDimensionalRangeZoomLogAndGain() { QVERIFY(near(gain.viewRect().bottom(), 3.0)); const QImage gshort = render(gain); QVERIFY(countPixels(gshort, [](QRgb c) { return c != kBackground; }) > 100); - // O2/task-14: the topmost gain tick label ("3") must be fully inside the + // The topmost gain tick label ("3") must be fully inside the // widget in both a short and a tall gain plot. The top-left label area // (x < plot.left) contains no frame/grid pixels, so it isolates the label. auto topLabelVisible = [](const QImage &img) { @@ -1377,7 +1065,7 @@ void PlottingTest::oneDimensionalRoiBoxes() { plot.Update(); std::vector rois{slsDetectorDefs::ROI(10, 30), - slsDetectorDefs::ROI(50, 70)}; + slsDetectorDefs::ROI(50, 70)}; plot.EnableRoiBoxes(rois, 0, 100); QVERIFY(countPixels(render(plot), isYellow) > 100); @@ -1454,13 +1142,13 @@ void PlottingTest::twoDHistogramContainer() { hist.SetData(0, 0.0, 4.0, 3, 0.0, 3.0, nullptr); QCOMPARE(hist.GetNBinsX(), 5); // invalid geometry ignored - // R3 (task-12): NaN/Inf bins are skipped by the automatic z range/mean. + // NaN/Inf bins are skipped by the automatic z range/mean. std::vector nf(12); for (int i = 0; i < 12; i++) - nf[size_t(i)] = double(i + 1); // 1..12 - nf[0] = std::numeric_limits::quiet_NaN(); // 1 - nf[5] = std::numeric_limits::infinity(); // 6 - nf[7] = -std::numeric_limits::infinity(); // 8 + nf[size_t(i)] = double(i + 1); // 1..12 + nf[0] = std::numeric_limits::quiet_NaN(); // 1 + nf[5] = std::numeric_limits::infinity(); // 6 + nf[7] = -std::numeric_limits::infinity(); // 8 hist.SetData(4, 0.0, 4.0, 3, 0.0, 3.0, nf.data()); QVERIFY(std::isfinite(hist.GetMinimum())); QVERIFY(std::isfinite(hist.GetMaximum())); @@ -1476,7 +1164,7 @@ void PlottingTest::twoDHistogramContainer() { QCOMPARE(hist.GetMaximum(), 1.0); QCOMPARE(hist.GetMean(), 0.0); - // R5 (task-12): all-negative data is padded OUTWARD on both ends; the + // All-negative data is padded OUTWARD on both ends; the // high end must stay above the data maximum (the brightest bin must not be // clipped - multiplying a negative max by 1.02 would move it below). std::vector neg(12); @@ -1490,385 +1178,291 @@ void PlottingTest::twoDHistogramContainer() { } // --------------------------------------------------------------------------- -// 2D: SetData / z range / scale panel integration +// SlsQt2DPlot // --------------------------------------------------------------------------- -void PlottingTest::twoDimensionalDataZRangeAndPanel() { +void PlottingTest::plot2dTitles() { sls::SlsQt2DPlot plot; plot.resize(700, 600); plot.show(); - QTest::qWait(5); - QVERIFY(!plot.isGainPlot()); - QVERIFY(plot.imageView() != nullptr); - QVERIFY(plot.scalePanel() != nullptr); - plot.SetTitle(QStringLiteral("2D detector")); - QCOMPARE(plot.title(), QStringLiteral("2D detector")); - plot.SetXTitle(QStringLiteral("x")); - plot.SetYTitle(QStringLiteral("y")); - // The colour-scale title is a compact caption row above the scale panel. - plot.SetZTitle(QStringLiteral("counts [a.u.]")); - QVERIFY(plot.zTitleLabel() != nullptr); - QTest::qWait(5); - QVERIFY2(plot.zTitleLabel()->isVisible(), - "SetZTitle() shows the z-axis caption"); - QCOMPARE(plot.zTitleLabel()->text(), QStringLiteral("counts [a.u.]")); - plot.SetZTitle(QString()); - QTest::qWait(5); - QVERIFY2(!plot.zTitleLabel()->isVisible(), - "an empty z title hides the caption row again"); - - plot.FillTestPlot(); + // a test image is shown until the first data arrives QCOMPARE(plot.GetXMinimum(), 200.0); QCOMPARE(plot.GetXMaximum(), 822.0); QCOMPARE(plot.GetYMinimum(), -0.5); QCOMPARE(plot.GetYMaximum(), 49.5); - QVERIFY(plot.GetZMaximum() > plot.GetZMinimum()); - QVERIFY(plot.imageView()->hasImage()); QCOMPARE(plot.imageView()->imageWidth(), 50); QCOMPARE(plot.imageView()->imageHeight(), 50); - QVERIFY(plot.imageView()->hasImage()); - // Z range is pushed to the canvas and the scale panel stays in sync. - plot.SetZMinMax(2.0, 8.0); - QCOMPARE(plot.GetZMinimum(), 2.0); - QCOMPARE(plot.GetZMaximum(), 8.0); - double lo = 0.0, hi = 0.0; - plot.imageView()->colorRange(lo, hi); - QVERIFY(near(lo, 2.0) && near(hi, 8.0)); - QVERIFY(plot.scalePanel()->view() == plot.imageView()); + plot.SetTitle(QStringLiteral("2D detector")); + plot.SetXTitle(QStringLiteral("x")); + plot.SetYTitle(QStringLiteral("y")); + QCOMPARE(plot.title(), QStringLiteral("2D detector")); + QCOMPARE(plot.imageView()->xAxisTitle(), QStringLiteral("x")); + QCOMPARE(plot.imageView()->yAxisTitle(), QStringLiteral("y")); - // Panel -> plot direction. - plot.scalePanel()->setColorRange(3.0, 6.0); - plot.imageView()->colorRange(lo, hi); - QVERIFY(near(lo, 3.0) && near(hi, 6.0)); - - // Fresh data with an explicit z range. - std::vector d(4 * 3); - for (int i = 0; i < 12; i++) - d[size_t(i)] = double(i); - plot.SetData(4, 0.0, 4.0, 3, 0.0, 3.0, d.data(), 1.0, 9.0); - QCOMPARE(plot.imageView()->imageWidth(), 4); - QCOMPARE(plot.imageView()->imageHeight(), 3); - QCOMPARE(plot.GetZMinimum(), 1.0); - QCOMPARE(plot.GetZMaximum(), 9.0); - QCOMPARE(plot.GetBinValue(1, 1), 5.0); - QCOMPARE(plot.GetBinIndex(1, 1), 5); - QCOMPARE(plot.FindBinIndex(0.5, 0.5), 0); - - plot.SetBinValue(1, 1, 42.0); - QCOMPARE(plot.GetBinValue(1, 1), 42.0); - QCOMPARE(*(plot.GetDataPtr() + 1 + 1 * 4), 42.0); - - // Whole-image fit: no paint outside the plot rectangle of the canvas. - plot.UnZoom(); - QImage img = render(*plot.imageView()); - const QRect ir = - sls::plot::plotRectFor(plot.imageView()->size(), sls::plot::PlotTheme()); - for (int x = ir.right() + 1; x < img.width(); x++) { - for (int y = 0; y < img.height(); y++) { - QVERIFY2(img.pixel(x, y) == kBackground, - "2D canvas must not paint in the right margin"); - } - } - QVERIFY(img.pixel(ir.center()) != kBackground); - - plot.EnableXAutoScaling(); - plot.EnableYAutoScaling(); - plot.SetXMinMax(1.0, 3.0); - plot.SetYMinMax(0.5, 2.5); - QVERIFY(plot.imageView()->hasImage()); - plot.UnZoom(false); + // the z title has its own row above the scale panel + const QList labels = + plot.findChildren(Qt::FindDirectChildrenOnly); + QCOMPARE(labels.size(), 1); + QVERIFY(!labels[0]->isVisible()); + plot.SetZTitle(QStringLiteral("counts")); + QVERIFY(labels[0]->isVisible()); + QCOMPARE(labels[0]->text(), QStringLiteral("counts")); + plot.SetZTitle(QString()); + QVERIFY(!labels[0]->isVisible()); } -// --------------------------------------------------------------------------- -// 2D: log z, interpolation, contours -// --------------------------------------------------------------------------- -void PlottingTest::twoDimensionalLogInterpolateAndContour() { - sls::SlsQt2DPlot plot; - plot.resize(800, 600); - plot.show(); - QTest::qWait(5); - plot.FillTestPlot(); - plot.UnZoom(); - - // Log z reaches the canvas and the panel chooser. - plot.LogZ(true); - QVERIFY(plot.imageView()->logScale()); - plot.LogZ(false); - QVERIFY(!plot.imageView()->logScale()); - - // SetLogz(enable, isMin, isMax, min, max) sets the range and the scale. - // An explicit Plot-tab / SetLogz() range is honoured in log mode too (the - // old qwt behaviour): the requested zmin/zmax reach the data and the - // canvas. - plot.SetLogz(true, true, true, 0.1, 9.0); - QVERIFY(plot.imageView()->logScale()); - QVERIFY(near(plot.GetZMinimum(), 0.1)); - QVERIFY(near(plot.GetZMaximum(), 9.0)); - double zlo = 0.0, zhi = 0.0; - plot.imageView()->colorRange(zlo, zhi); - QVERIFY(near(zlo, 0.1) && near(zhi, 9.0)); - - // The explicit range survives the Update() calls of streaming frames ... - plot.Update(); - QVERIFY(near(plot.GetZMinimum(), 0.1)); - QVERIFY(near(plot.GetZMaximum(), 9.0)); - plot.imageView()->colorRange(zlo, zhi); - QVERIFY(near(zlo, 0.1) && near(zhi, 9.0)); - - // ... while SetZRange(false, false) (qDrawPlot's per-frame call while the - // z-range check boxes are off) drops the explicit pin and returns to the - // automatic log range. - plot.SetZRange(false, false, 0.0, 0.0); - QVERIFY(plot.GetZMinimum() > 0.0); - QVERIFY(!(near(plot.GetZMinimum(), 0.1) && near(plot.GetZMaximum(), 9.0))); - plot.imageView()->colorRange(zlo, zhi); - QVERIFY(near(zlo, plot.GetZMinimum()) && near(zhi, plot.GetZMaximum())); - - // Contours are painted through the clipped overlay hook. - const QImage blocky = render(*plot.imageView()); - plot.SetContour(true); - const QImage contours = render(*plot.imageView()); - QVERIFY2(blocky != contours, "SetContour(true) changes the rendered image"); - const QRect ir = - sls::plot::plotRectFor(plot.imageView()->size(), sls::plot::PlotTheme()); - for (int x = ir.right() + 1; x < contours.width(); x++) { - for (int y = 0; y < contours.height(); y++) { - QVERIFY2(contours.pixel(x, y) == kBackground, - "contours must be clipped to the plot rect"); - } - } - plot.SetContour(false); - QVERIFY(render(*plot.imageView()) == blocky); - - // Bilinear interpolation overlay. - plot.SetInterpolate(true); - const QImage smooth = render(*plot.imageView()); - QVERIFY2(smooth != blocky, "SetInterpolate(true) changes the rendered image"); - plot.SetInterpolate(false); - QVERIFY(render(*plot.imageView()) == blocky); - - // Spectrogram image can be hidden without losing contours/ROI paint. - plot.showSpectrogram(false); - QVERIFY(render(*plot.imageView()) != blocky); - plot.showSpectrogram(true); - QVERIFY(render(*plot.imageView()) == blocky); - - // R8 (task-12): on a >256-wide frame the marching-squares grid is - // subsampled; the last row/column must be included so the contours reach - // the image edges (pre-fix an outer band up to step-1 bins wide was empty). - plot.LogZ(false); - { - std::vector big(size_t(1024) * 1024); - for (int y = 0; y < 1024; y++) - for (int x = 0; x < 1024; x++) - big[size_t(y) * 1024 + size_t(x)] = double(x + y); - plot.SetData(1024, -0.5, 1023.5, 1024, -0.5, 1023.5, big.data()); - plot.UnZoom(); - plot.SetContour(true); - plot.showSpectrogram(false); // contour-only render on the dark canvas - const QImage edgeImg = render(*plot.imageView()); - const QPointF imgRight = - plot.imageView()->dataToWidget(QPointF(1024.0, 0.0)); - const QPointF imgTop = - plot.imageView()->dataToWidget(QPointF(0.0, 1024.0)); - int maxX = -1; - int minY = std::numeric_limits::max(); - for (int y = ir.top(); y <= ir.bottom(); y++) { - for (int x = ir.left(); x <= ir.right(); x++) { - if (!isBright(edgeImg.pixel(x, y))) - continue; - maxX = std::max(maxX, x); - minY = std::min(minY, y); - } - } - QVERIFY2(maxX >= int(std::lround(imgRight.x())) - 1, - "contours reach the image right edge (R8)"); - QVERIFY2(minY <= int(std::lround(imgTop.y())) + 1, - "contours reach the image top edge (R8)"); - plot.showSpectrogram(true); - plot.SetContour(false); - plot.FillTestPlot(); // restore the small test frame - } - - // R3 (task-12): a frame with NaN/Inf bins keeps the z range and the canvas - // colour range finite (auto range skips the non-finite bins). - plot.SetZRange(false, false, 0.0, 0.0); - { - std::vector nf(50 * 50); - for (int i = 0; i < 50 * 50; i++) - nf[size_t(i)] = double(i % 100); - nf[0] = std::numeric_limits::quiet_NaN(); - nf[1] = std::numeric_limits::infinity(); - nf[2] = -std::numeric_limits::infinity(); - plot.SetData(50, -0.5, 49.5, 50, -0.5, 49.5, nf.data()); - double qlo = 0.0, qhi = 0.0; - plot.imageView()->colorRange(qlo, qhi); - QVERIFY(std::isfinite(qlo) && std::isfinite(qhi)); - QVERIFY(qhi > qlo); - QVERIFY(std::isfinite(plot.GetZMinimum())); - QVERIFY(std::isfinite(plot.GetZMaximum())); - QVERIFY(std::isfinite(plot.GetZMean())); - (void)render(*plot.imageView()); - - std::vector allnf(50 * 50, - std::numeric_limits::quiet_NaN()); - plot.SetData(50, -0.5, 49.5, 50, -0.5, 49.5, allnf.data()); - plot.imageView()->colorRange(qlo, qhi); - QVERIFY(near(qlo, 0.0) && near(qhi, 1.0)); - } - - plot.LogZ(false); -} - -// --------------------------------------------------------------------------- -// 2D: ROI boxes, viewport/zoom, no paint outside the plot rect -// --------------------------------------------------------------------------- -void PlottingTest::twoDimensionalRoiAndClipping() { +void PlottingTest::plot2dZRange() { sls::SlsQt2DPlot plot; plot.resize(700, 600); plot.show(); - QTest::qWait(5); - std::vector d(100 * 80); - for (int y = 0; y < 80; y++) - for (int x = 0; x < 100; x++) - d[size_t(y) * 100 + x] = double(x + y); - plot.SetData(100, 0.0, 100.0, 80, 0.0, 80.0, d.data()); - plot.UnZoom(); + sls::SlsQtFastImage *view = plot.imageView(); + std::vector d(64 * 32); + for (size_t i = 0; i < d.size(); i++) + d[i] = double(i % 12); + double lo = 0.0, hi = 0.0; - std::vector rois{slsDetectorDefs::ROI(10, 29, 20, 39)}; - plot.EnableRoiBoxes(rois); - const std::vector &ov = plot.imageView()->overlayRects(); - QCOMPARE(int(ov.size()), 1); - QVERIFY(near(ov[0].left(), 10.0) && near(ov[0].top(), 20.0)); - QVERIFY(near(ov[0].width(), 20.0) && near(ov[0].height(), 20.0)); - QImage img = render(*plot.imageView()); - const QPointF roiCorner = plot.imageView()->dataToWidget(QPointF(10.0, 20.0)); - QVERIFY2(yellowNear(img, roiCorner.toPoint(), 3), - "ROI box is painted in data coordinates"); - plot.DisableRoiBoxes(); - QVERIFY(plot.imageView()->overlayRects().empty()); + // follows the data + plot.SetData(64, 0.0, 64.0, 32, 0.0, 32.0, d.data()); + view->colorRange(lo, hi); + QVERIFY(lo <= 0.0 && lo > -1.0 && hi >= 11.0 && hi < 12.0); - // Programmatic zoom: data rect -> image pixel-edge viewport. - plot.SetZoom(QRectF(20.0, 20.0, 20.0, 20.0)); - double x = 0.0, y = 0.0, w = 0.0, h = 0.0; - plot.imageView()->viewport(x, y, w, h); - QVERIFY(near(x, 20.0) && near(y, 20.0)); - QVERIFY(near(w, 20.0) && near(h, 20.0)); - QVERIFY(plot.imageView()->hasImage()); + // fixed ends stay for the following frames + plot.SetZRange(true, true, 2.0, 8.0); + plot.SetData(64, 0.0, 64.0, 32, 0.0, 32.0, d.data()); + view->colorRange(lo, hi); + QVERIFY(near(lo, 2.0) && near(hi, 8.0)); - // Deep zoom: the canvas must still be clipped to its plot rect. - img = render(*plot.imageView()); - const QRect ir = - sls::plot::plotRectFor(plot.imageView()->size(), sls::plot::PlotTheme()); - for (int xx = ir.right() + 1; xx < img.width(); xx++) { - for (int yy = 0; yy < img.height(); yy++) { - QVERIFY2(img.pixel(xx, yy) == kBackground, - "zoomed 2D image must be clipped to the plot rect"); - } - } + // one end fixed, the other from the data + plot.SetZRange(true, false, 2.0, 0.0); + view->colorRange(lo, hi); + QVERIFY(near(lo, 2.0) && hi >= 11.0 && hi < 12.0); - // User zoom emits the data-coordinate viewport for the gain-plot sync. - QSignalSpy spy(&plot, &sls::SlsQt2DPlot::PlotZoomedSignal); - sendWheel(*plot.imageView(), - QPointF(plot.imageView()->width() / 2.0, - plot.imageView()->height() / 2.0), - 120); - QVERIFY(spy.count() >= 1); - const QRectF zr = spy.takeLast().at(0).toRectF(); - QVERIFY(zr.width() > 0.0 && zr.height() > 0.0); - QVERIFY(zr.width() <= 100.0 && zr.height() <= 80.0); - plot.UnZoom(); + plot.SetZRange(false, false, 0.0, 0.0); + view->colorRange(lo, hi); + QVERIFY(lo <= 0.0 && hi >= 11.0); + + // a range picked on the scale panel stays as well, qDrawPlot calls + // SetZRange() without fixed ends for every frame + sls::SlsQtScaleHisto *histo = plot.scalePanel()->histogramWidget(); + const QPointF from(0.75 * histo->width(), 19), to(0.5 * histo->width(), 19); + sendMouse(*histo, QEvent::MouseButtonPress, from, Qt::LeftButton, + Qt::LeftButton); + sendMouse(*histo, QEvent::MouseMove, to, Qt::NoButton, Qt::LeftButton); + sendMouse(*histo, QEvent::MouseButtonRelease, to, Qt::LeftButton, + Qt::NoButton); + double pickedLo = 0.0, pickedHi = 0.0; + view->colorRange(pickedLo, pickedHi); + QVERIFY(near(pickedLo, lo) && pickedHi < hi - 1.0); + plot.SetData(64, 0.0, 64.0, 32, 0.0, 32.0, d.data()); + plot.SetZRange(false, false, 0.0, 0.0); + view->colorRange(lo, hi); + QVERIFY(near(lo, pickedLo) && near(hi, pickedHi)); + + // until an end is fixed + plot.SetZRange(false, true, 0.0, 5.0); + view->colorRange(lo, hi); + QVERIFY(lo <= 0.0 && near(hi, 5.0)); + plot.SetZRange(false, false, 0.0, 0.0); + view->colorRange(lo, hi); + QVERIFY(lo <= 0.0 && hi >= 11.0); + + // or the image size changes + sendMouse(*histo, QEvent::MouseButtonPress, from, Qt::LeftButton, + Qt::LeftButton); + sendMouse(*histo, QEvent::MouseButtonRelease, to, Qt::LeftButton, + Qt::NoButton); + plot.SetData(32, 0.0, 32.0, 64, 0.0, 64.0, d.data()); + view->colorRange(lo, hi); + QVERIFY(lo <= 0.0 && hi >= 11.0); } -// --------------------------------------------------------------------------- -// 2D: gain mode -// --------------------------------------------------------------------------- -void PlottingTest::twoDimensionalGainMode() { +void PlottingTest::plot2dLogZ() { + sls::SlsQt2DPlot plot; + plot.resize(700, 600); + plot.show(); + sls::SlsQtFastImage *view = plot.imageView(); + std::vector d(64 * 32); + for (size_t i = 0; i < d.size(); i++) + d[i] = double(i % 12) * 0.5; + plot.SetData(64, 0.0, 64.0, 32, 0.0, 32.0, d.data()); + double lo = 0.0, hi = 0.0; + + // starts at the smallest value above zero + plot.SetLogz(true, false, false, 0.0, 0.0); + QVERIFY(view->logScale()); + view->colorRange(lo, hi); + QVERIFY(near(lo, 0.5) && hi >= 5.5); + + plot.SetLogz(true, true, true, 0.1, 9.0); + view->colorRange(lo, hi); + QVERIFY(near(lo, 0.1) && near(hi, 9.0)); + + plot.SetLogz(false, false, false, 0.0, 0.0); + QVERIFY(!view->logScale()); + + // values that are not finite do not end up in the range + d[0] = std::numeric_limits::quiet_NaN(); + d[1] = std::numeric_limits::infinity(); + d[2] = -std::numeric_limits::infinity(); + plot.SetData(64, 0.0, 64.0, 32, 0.0, 32.0, d.data()); + view->colorRange(lo, hi); + QVERIFY(lo <= 0.0 && lo > -1.0 && hi >= 5.5 && hi < 6.5); + std::fill(d.begin(), d.end(), std::numeric_limits::quiet_NaN()); + plot.SetData(64, 0.0, 64.0, 32, 0.0, 32.0, d.data()); + view->colorRange(lo, hi); + QVERIFY(near(lo, 0.0) && near(hi, 1.0)); + render(plot); +} + +void PlottingTest::plot2dContours() { + sls::SlsQt2DPlot plot; + plot.resize(800, 600); + plot.show(); + sls::SlsQtFastImage *view = plot.imageView(); + const int n = 1024; // more pixels than the contour grid has cells + std::vector d(size_t(n) * n); + for (int y = 0; y < n; y++) + for (int x = 0; x < n; x++) + d[size_t(y) * n + x] = double(x + y); + plot.SetData(n, -0.5, n - 0.5, n, -0.5, n - 0.5, d.data()); + const QImage plain = render(*view); + + // the diagonal lines reach the right and the upper edge of the image + plot.SetContour(true); + const QRect changed = differingArea(plain, render(*view)); + QVERIFY(plotArea(*view).contains(changed)); + QVERIFY(changed.right() >= int(widgetPos(*view, n, 0).x()) - 2); + QVERIFY(changed.top() <= int(widgetPos(*view, 0, n).y()) + 2); + plot.SetContour(false); + QCOMPARE(render(*view), plain); + + // the levels follow the colour range: x + y stays below 500 + plot.SetZRange(true, true, 0.0, 500.0); + const QImage plainLow = render(*view); + plot.SetContour(true); + const QRect low = differingArea(plainLow, render(*view)); + QVERIFY(low.right() < int(widgetPos(*view, 500, 0).x())); + QVERIFY(low.top() > int(widgetPos(*view, 0, 500).y())); + plot.SetContour(false); + + plot.SetInterpolate(true); + QVERIFY(view->interpolate()); + plot.SetInterpolate(false); + QVERIFY(!view->interpolate()); +} + +void PlottingTest::plot2dRoiAndZoom() { + sls::SlsQt2DPlot plot; + plot.resize(700, 600); + plot.show(); + sls::SlsQtFastImage *view = plot.imageView(); + const std::vector d = xRamp(100, 80); + // the data coordinates are the pixels shifted by 1000 and 2000 + plot.SetData(100, 1000.0, 1100.0, 80, 2000.0, 2080.0, d.data()); + double x = 0.0, y = 0.0, w = 0.0, h = 0.0; + + // pixels 10..29 x 20..39 + plot.EnableRoiBoxes({slsDetectorDefs::ROI(10, 29, 20, 39)}); + QCOMPARE(int(view->overlayRects().size()), 1); + QCOMPARE(view->overlayRects()[0], QRectF(10.0, 20.0, 20.0, 20.0)); + QVERIFY(yellowNear(render(*view), widgetPos(*view, 10.0, 20.0).toPoint())); + plot.DisableRoiBoxes(); + QVERIFY(view->overlayRects().empty()); + + plot.SetZoom(QRectF(1020.0, 2020.0, 20.0, 20.0)); + view->viewport(x, y, w, h); + QVERIFY(near(x, 20.0) && near(y, 20.0) && near(w, 20.0) && near(h, 20.0)); + + // the user zooming is reported in data coordinates + QSignalSpy spy(&plot, &sls::SlsQt2DPlot::PlotZoomedSignal); + sendWheel(*view, widgetPos(*view, 30.0, 30.0), 120); + QCOMPARE(spy.count(), 1); + const QRectF zoomed = spy.at(0).at(0).toRectF(); + QVERIFY(zoomed.width() < 20.0 && zoomed.height() < 20.0); + QVERIFY(QRectF(1020.0, 2020.0, 20.0, 20.0).contains(zoomed)); + + // axis ranges from the plot tab + plot.SetXMinMax(1040.0, 1060.0); + view->viewport(x, y, w, h); + QVERIFY(near(x, 40.0) && near(w, 20.0) && near(y, 0.0) && near(h, 80.0)); + plot.SetYMinMax(2030.0, 2010.0); + view->viewport(x, y, w, h); + QVERIFY(near(x, 40.0) && near(w, 20.0) && near(y, 10.0) && near(h, 20.0)); + plot.EnableXAutoScaling(); + plot.EnableYAutoScaling(); + view->viewport(x, y, w, h); + QVERIFY(near(x, 0.0) && near(y, 0.0) && near(w, 100.0) && near(h, 80.0)); + + plot.DisableZoom(true); + QVERIFY(!view->zoomEnabled()); + plot.DisableZoom(false); + QVERIFY(view->zoomEnabled()); +} + +void PlottingTest::plot2dGain() { sls::SlsQt2DPlot gain(nullptr, true); gain.resize(200, 200); gain.show(); - QTest::qWait(5); - QVERIFY(gain.isGainPlot()); + sls::SlsQtFastImage *view = gain.imageView(); QVERIFY(gain.scalePanel() == nullptr); - QVERIFY(gain.zTitleLabel() == nullptr); - QVERIFY(!gain.imageView()->axesVisible()); - QVERIFY(!gain.imageView()->zoomEnabled()); - QCOMPARE(gain.imageView()->paletteIndex(), - int(sls::plot::Palette::Gain4)); - double lo = 0.0, hi = 0.0; - gain.imageView()->colorRange(lo, hi); - QVERIFY(near(lo, 0.0) && near(hi, 3.0)); + QVERIFY(!view->axesVisible()); + QVERIFY(!view->zoomEnabled()); + QCOMPARE(view->palette(), Palette::Gain4); - // Four quadrants, one per gain bit (data layout: x fastest, y up). + // one quadrant per gain: 0 1 above 2 3 std::vector d(8 * 8); - for (int by = 0; by < 8; by++) - for (int bx = 0; bx < 8; bx++) { - const int g = (bx < 4 ? 0 : 1) + (by < 4 ? 2 : 0); - d[size_t(bx) + size_t(by) * 8] = double(g); - } + for (int y = 0; y < 8; y++) + for (int x = 0; x < 8; x++) + d[size_t(y) * 8 + x] = (x < 4 ? 0 : 1) + (y < 4 ? 2 : 0); gain.SetData(8, 0.0, 8.0, 8, 0.0, 8.0, d.data()); - QCOMPARE(gain.imageView()->imageWidth(), 8); - QCOMPARE(gain.imageView()->imageHeight(), 8); - const QImage img = render(*gain.imageView()); - const QRgb c0 = img.pixel(int(gain.imageView()->dataToWidget(QPointF(1.5, 1.5)).x()), - int(gain.imageView()->dataToWidget(QPointF(1.5, 1.5)).y())); - const QRgb c1 = img.pixel(int(gain.imageView()->dataToWidget(QPointF(5.5, 1.5)).x()), - int(gain.imageView()->dataToWidget(QPointF(5.5, 1.5)).y())); - const QRgb c2 = img.pixel(int(gain.imageView()->dataToWidget(QPointF(1.5, 5.5)).x()), - int(gain.imageView()->dataToWidget(QPointF(1.5, 5.5)).y())); - const QRgb c3 = img.pixel(int(gain.imageView()->dataToWidget(QPointF(5.5, 5.5)).x()), - int(gain.imageView()->dataToWidget(QPointF(5.5, 5.5)).y())); - // Data value = (x>=4 ? 1 : 0) + (y>=4 ? 2 : 0); the bottom half (small y) - // adds 2, so the bottom-left cell is gain bit 2. - const QRgb *gainLut = sls::plot::paletteLut(sls::plot::Palette::Gain4); - QCOMPARE(c0, gainLut[170]); // value 2 - QCOMPARE(c1, gainLut[255]); // value 3 - QCOMPARE(c2, gainLut[0]); // value 0 - QCOMPARE(c3, gainLut[85]); // value 1 - // All four categorical colours are actually painted somewhere. - QSet present; - for (int yy = 0; yy < img.height(); yy++) - for (int xx = 0; xx < img.width(); xx++) - present.insert(img.pixel(xx, yy)); - for (int k : {0, 85, 170, 255}) - QVERIFY2(present.contains(gainLut[k]), - "all four gain categories are painted"); + const QImage img = render(*view); + const QRgb *lut = sls::plot::paletteLut(Palette::Gain4); + QCOMPARE(dominantPixelAtData(*view, img, 2.0, 6.0), lut[0]); + QCOMPARE(dominantPixelAtData(*view, img, 6.0, 6.0), lut[85]); + QCOMPARE(dominantPixelAtData(*view, img, 2.0, 2.0), lut[170]); + QCOMPARE(dominantPixelAtData(*view, img, 6.0, 2.0), lut[255]); + + // the range is fixed and the plot only follows the zoom of the data plot + gain.SetZRange(true, true, 0.0, 100.0); + gain.SetLogz(true, false, false, 0.0, 0.0); + double lo = 0.0, hi = 0.0; + view->colorRange(lo, hi); + QVERIFY(near(lo, 0.0) && near(hi, 3.0)); + QVERIFY(!view->logScale()); + gain.SetZoom(QRectF(2.0, 2.0, 4.0, 4.0)); + double x = 0.0, y = 0.0, w = 0.0, h = 0.0; + view->viewport(x, y, w, h); + QVERIFY(near(x, 2.0) && near(y, 2.0) && near(w, 4.0) && near(h, 4.0)); } // --------------------------------------------------------------------------- -// acceptance benchmark: 1024x512 float frames at >= 20 Hz +// the gui has to keep up with 1024 x 512 pixels at 20 Hz // --------------------------------------------------------------------------- void PlottingTest::performance1024x512() { sls::SlsQtFastImage view; view.resize(1100, 600); view.show(); - QTest::qWait(20); - std::vector frame = acceptanceFrame(); + QVERIFY(QTest::qWaitForWindowExposed(&view)); // or repaint() does nothing + std::vector frame = testFrame(); view.setColorRange(-2.0, 2.0); - view.setImageCopy(frame.data(), 1024, 512); - view.repaint(); - - // Warm up: first paints allocate the cached QImage and font paths. - for (int i = 0; i < 5; i++) { - frame[0] = float(i); - view.setImageCopy(frame.data(), 1024, 512); + const auto showFrame = [&](int i) { + frame[0] = i; + view.setImage(frame.data(), 1024, 512); view.repaint(); - } + }; + for (int i = 0; i < 5; i++) + showFrame(i); const int frames = 60; QElapsedTimer timer; timer.start(); - for (int i = 0; i < frames; i++) { - frame[0] = float(i); - view.setImageCopy(frame.data(), 1024, 512); - view.repaint(); // synchronous: copy + compose + paint - } - const double seconds = double(timer.nsecsElapsed()) / 1e9; - const double fps = double(frames) / seconds; - qInfo("1024x512 benchmark: %.1f fps (%.2f ms/frame)", fps, + for (int i = 0; i < frames; i++) + showFrame(i); + const double seconds = timer.nsecsElapsed() / 1e9; + qInfo("1024x512: %.1f fps (%.2f ms/frame)", frames / seconds, 1000.0 * seconds / frames); - QVERIFY2(fps >= 20.0, "1024x512 frames must render at >= 20 fps"); + QVERIFY(frames / seconds >= 20.0); } QTEST_MAIN(PlottingTest)