Simplify the 2D plotting code

SlsQtFastImage
- Remove what the gui never used: the colour bar inside the view, the
  ROI editor, the extra ROI rectangles, pixel aspect and zero-white.
- Report changes with signals instead of std::function callbacks.
- Keep the image as double so that pixel values are shown exactly.
- Draw interpolated images and contour lines itself, which removes the
  second colour mapped image and the paint hook from SlsQt2DPlot.
- One Mapping struct for the image to widget transformation.

SlsQtScalePanel
- Connect to the signals of the view instead of chaining callbacks.
- The histogram strip keeps its own copy of the 256 bins, so there is
  no pointer into the view to guard and no snapshot during a drag.
- Remove the hooks that only the tests used.
- Histogram bins now have the same width as the bars drawn for them.

SlsQt2DPlot
- Remove the pass-through methods the gui does not call and the
  duplicated state (log scale, palette, ROI rectangles).

Tests and demo rewritten for the new interfaces. The demo now shows the
2D and the 1D plot of the gui with synthetic frames.
This commit is contained in:
Erik Fröjdh committed 2026-11-13 10:01:01 +01:00
1 parent bb18813808
commit 356423fadf
14 files changed
+1891 -4225

No files matched your search

+100 -451
View File
@@ -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 <QApplication>
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QMouseEvent>
#include <QPixmap>
#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <memory>
#include <vector>
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<sls::SlsQtH1D>(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<double> frame(static_cast<size_t>(kNx) * kNy);
std::vector<double> 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<size_t>(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<sls::SlsQtH1D> 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<float> m_frame;
std::vector<double> m_frameD;
std::vector<double> m_gainData;
std::vector<double> m_c1, m_c2, m_c3;
std::vector<SlsQtH1D *> 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 <file> and exit."),
QStringLiteral("file")},
{QStringLiteral("frames"),
QStringLiteral("Exit after <n> 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();
}
@@ -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);
@@ -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 <vector>
@@ -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};
@@ -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 <QFont>
#include <QImage>
#include <QPointF>
#include <QRectF>
#include <QRgb>
#include <QString>
#include <QWidget>
#include <vector>
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<slsDetectorDefs::ROI> roi);
void EnableRoiBoxes(const std::vector<slsDetectorDefs::ROI> &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<ContourSegment> 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<QRectF> m_roiRects;
std::vector<double> 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
} // namespace sls
@@ -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 <QElapsedTimer>
#include <QFont>
#include <QImage>
#include <QLineF>
#include <QPointF>
#include <QRectF>
#include <QString>
#include <QTransform>
#include <QWidget>
#include <functional>
#include <vector>
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<int> &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<int> &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<QRectF> &rects);
void clearOverlayRects();
const std::vector<QRectF> &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<QRectF> &rects);
const std::vector<QRectF> &overlayRects() const;
/** White line segments, e.g. contour lines */
void setOverlayLines(const std::vector<QLineF> &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<void()> onImageChanged;
// reported in data coordinates (x1, y1, x2, y2), y up
std::function<void(double, double, double, double)> onZoomChanged;
std::function<void(double, double)> onColorRangeChanged;
std::function<void(const QRgb *)> onPaletteChanged;
// x0, y0, x1, y1 in data coordinates (integers, ROI list convention)
std::function<void(int, int, int, int)> onRoiEdited;
// one histogram/scale refresh, after an in-view colour bar drag
std::function<void()> 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<void(QPainter &, const QTransform &)> 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<double> 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<float> 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<int> 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<int> m_hist;
double m_histLo = 0.0, m_histHi = 1.0;
qint64 m_histMs = 0;
std::vector<QRectF> m_overlayRects;
std::vector<QLineF> 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<QRectF> 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
@@ -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 <QColor>
#include <QFont>
#include <QFontMetrics>
#include <QMouseEvent>
#include <QRect>
#include <QRgb>
#include <QSize>
#include <QString>
#include <QWheelEvent>
#include <QtGlobal>
#include <cmath>
#include <vector>
@@ -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 <QMetaObject>
#include <QPointer>
#include <QWidget>
#include <functional>
#include <vector>
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<int> *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<void(double, double)> 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<int> &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<int> *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<int> *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<int> m_snap; // bars snapshot at press
int m_previewX = 0;
std::vector<int> 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<SlsQtFastImage> 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<void()> m_prevImageChanged;
std::function<void()> 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
@@ -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")};
@@ -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
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -3,13 +3,14 @@
#include "SlsQtScalePanel.h"
#include "SlsQtFastImage.h"
#include "SlsQtPlotCommon.h"
#include <QComboBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QMouseEvent>
#include <QObject>
#include <QPainter>
#include <QSignalBlocker>
#include <QVBoxLayout>
#include <algorithm>
@@ -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<int> *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<int> &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<int> *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<int> *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<plot::Palette>(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<sls::plot::Palette>(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<int>::of(&QComboBox::currentIndexChanged),
this, [this](int) { push(); });
connect(m_imageLogCombo,
QOverload<int>::of(&QComboBox::currentIndexChanged), this,
[this](int i) {
if (m_suppress || !m_view)
return;
m_view->setLogScale(i == 1);
refresh();
});
connect(m_histoLogCombo,
QOverload<int>::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<plot::Palette>(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<sls::plot::Palette>(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<int>(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
+2 -2
View File
@@ -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);
File diff suppressed because it is too large. Load diff