Port slsDetectorGui to Qt6 and replace qwt with custom Qt-only plots

Build system and integration: find_package(Qt6) with Widgets/Gui/Core/Concurrent, qt6_wrap_ui/qt6_add_resources, Qt6::* links; drop bundled qwt from the build and tree; Qt6 API fixes in the non-plot GUI sources (QtConcurrent run, QButtonGroup::idClicked, QFontMetrics::horizontalAdvance, title()/setLegendVisible call sites).

Plotting: replace QwtPlot/QwtPlotCurve/QwtRasterData with self-contained Qt Widgets painting: shared palette/ticks/theme helpers, fast cached-QImage 2D image view with axes/clip/zoom/overlays/ROI, thin histogram + scale panel with the marker freeze rule, custom 1D plot (axes/grid/legend/log/zoom/pan/ROI) and a 2D wrapper preserving the old API (interpolation, marching-squares contours, gain palette, ScalePanel sync).

Docs/CPack/CI/conda updated for Qt6 and qwt/expat removal.
This commit is contained in:
Qt6 Port committed 2026-11-12 15:25:45 +01:00
1 parent 8d23326aae
commit 91497579a9
31 files changed
+6138 -1914

No files matched your search

+2 -2
View File
@@ -25,8 +25,8 @@ jobs:
- name: Install build dependencies
run: |
dnf -y install rpm-build qt5-qtbase-devel qt5-qtsvg-devel \
libpng-devel zlib-devel expat-devel libtiff-devel
dnf -y install rpm-build qt6-qtbase-devel \
libpng-devel zlib-devel libtiff-devel
- name: Build with versioned binaries
run: |
+2 -2
View File
@@ -21,8 +21,8 @@ jobs:
- name: Install build dependencies
run: |
dnf -y install rpm-build qt5-qtbase-devel qt5-qtsvg-devel \
libpng-devel zlib-devel expat-devel libtiff-devel
dnf -y install rpm-build qt6-qtbase-devel \
libpng-devel zlib-devel libtiff-devel
- name: Build with versioned binaries
run: |
+1 -1
View File
@@ -23,7 +23,7 @@ jobs:
- uses: awalsh128/cache-apt-pkgs-action@v1.6.1
with:
packages: libhdf5-dev qtbase5-dev qt5-qmake libqt5svg5-dev libpng-dev libtiff-dev
packages: libhdf5-dev qt6-base-dev libpng-dev libtiff-dev
version: 1.0
- name: Configure CMake
+2 -5
View File
@@ -183,8 +183,6 @@ endif()
#Maybe have an option guarding this?
set(SLS_INTERNAL_RAPIDJSON_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libs/rapidjson)
set(SLS_INTERNAL_QWT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libs/qwt-6.1.5)
set(ClangFormat_EXCLUDE_PATTERNS "build/"
"libs/"
"slsDetectorCalibration/"
@@ -320,8 +318,7 @@ if (SLS_USE_RECEIVER)
add_subdirectory(slsReceiverSoftware)
endif (SLS_USE_RECEIVER)
if (SLS_USE_GUI)
add_subdirectory(libs/qwt)
if (SLS_USE_GUI)
add_subdirectory(slsDetectorGui)
endif (SLS_USE_GUI)
@@ -420,7 +417,7 @@ set(CPACK_RPM_COMPONENT_INSTALL ON)
set(CPACK_RPM_GUI_PACKAGE_REQUIRES
"qt5-qtbase, qt5-qtbase-gui"
"qt6-qtbase, qt6-qtbase-gui"
)
#control which RPMs are generated
+18 -20
View File
@@ -99,9 +99,13 @@ To use the basic building blocks, meaning sls_detector_get/put and the shared li
#### GUI
* Qt 5.9
* Qt 6 (>= 6.2, components Widgets, Gui, Core and Concurrent)
* Qwt 6.1.5 (packaged in libs)
* libpng and zlib
The GUI plotting (1D/2D plots, colour maps, scale panel) is implemented with
plain Qt Widgets painting; Qwt, ROOT and OpenGL are no longer dependencies and
the bundled Qwt copy has been removed.
#### Moench executables
@@ -125,8 +129,6 @@ The documentation is built with
* pybind11 (python bindings)
* qwt (gui plotting)
* libzmq (streaming to/from receiver)
### 3.2. Download Source Code from github
@@ -246,7 +248,11 @@ make -j12
> **Note:** For v7.x.x of slsDetectorPackage and older, refer [zeromq notes for dependencies for conda](#4-pybind-and-zeromq).
### 3.5. Build slsDetectorGui (Qt5)
### 3.5. Build slsDetectorGui (Qt6)
The GUI needs Qt 6 (>= 6.2) with the Widgets, Gui, Core and Concurrent modules.
Qwt, Qt5, expat and Qt6Svg are no longer needed; the plotting is done with
plain Qt Widgets painting.
1. Using pre-built binary on conda
```
@@ -254,17 +260,14 @@ conda create -n myenv slsdetgui=7.0.0
conda activate myenv
```
2. Using system installation on RHEL7
2. Using system installation on RHEL8/RHEL9/Fedora
```
yum install qt5-qtbase-devel.x86_64
yum install qt5-qtsvg-devel.x86_64
dnf install qt6-qtbase-devel
```
3. Using system installation on RHEL8
3. Using system installation on Debian/Ubuntu
```
yum install qt5-qtbase-devel.x86_64
yum install qt5-qtsvg-devel.x86_64
yum install expat-devel.x86_64
apt install qt6-base-dev
```
4. Using conda
@@ -274,20 +277,15 @@ conda config --add channels conda-forge
conda config --add channels slsdetectorgroup
conda config --set channel_priority strict
# create environment to compile
# on rhel7
conda create -n slsgui zeromq gxx_linux-64 gxx_linux-64 mesa-libgl-devel-cos6-x86_64 qt
# on fedora or newer systems
conda create -n slsgui zeromq qt
# when using conda compilers, would also need libgl, but no need for it on fedora unless maybe using it with ROOT
# create environment to compile (qt6-main is the Qt6 base package on conda-forge)
conda create -n slsgui zeromq gxx_linux-64 qt6-main
# activate environment
conda activate slsgui
# compile with cmake outside slsDetecorPackage folder
mkdir build && cd build
cmake ../slsDetectorPackage -DSLS_USE_GUI=ON
cmake ../slsDetectorPackage -DSLS_USE_GUI=ON -DCMAKE_PREFIX_PATH=$CONDA_PREFIX
make -j12
# or compile with cmk.sh
+2 -3
View File
@@ -20,7 +20,7 @@ requirements:
- git
- cmake
- ninja
- qt 5.*
- qt6-main
host:
- libstdcxx-ng
@@ -28,7 +28,6 @@ requirements:
- libgl-devel # [linux]
- libtiff
- zlib
- expat
run:
- libstdcxx-ng
@@ -62,7 +61,7 @@ outputs:
run:
- {{ pin_subpackage('slsdetlib', exact=True) }}
- qt 5.*
- qt6-main
- name: moenchzmq
+6 -3
View File
@@ -46,8 +46,12 @@ ZeroMQ
GUI
-----------------------
* Qt 5.9
* Qwt 6.1.5 (packaged in libs)
* Qt 6 (>= 6.2, components Widgets, Gui, Core and Concurrent)
* libpng and zlib
The GUI plotting (1D/2D plots, colour maps, scale panel) is implemented with
plain Qt Widgets painting. Qwt, ROOT and OpenGL are not required and the
bundled Qwt copy has been removed from the sources.
-----------------------
Moench executables
@@ -72,5 +76,4 @@ Packaged in libs/
* catch2 (unit testing)
* rapidjson (streaming from receiver)
* pybind11 (python bindings)
* qwt (gui plotting)
* libzmq (streaming to/from receiver)
+12 -16
View File
@@ -311,9 +311,13 @@ using this compiler
3.4. Build slsDetectorGui (Qt5)
3.4. Build slsDetectorGui (Qt6)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The GUI needs Qt 6 (>= 6.2) with the Widgets, Gui, Core and Concurrent modules.
Qwt, Qt5, expat and Qt6Svg are no longer needed; plotting is done with plain
Qt Widgets painting.
1. Using pre-built binary on conda
.. code-block:: bash
@@ -322,20 +326,17 @@ using this compiler
conda activate myenv
2. Using system installation on RHEL7
2. Using system installation on RHEL8/RHEL9/Fedora
.. code-block:: bash
yum install qt5-qtbase-devel.x86_64
yum install qt5-qtsvg-devel.x86_64
dnf install qt6-qtbase-devel
3. Using system installation on RHEL8
3. Using system installation on Debian/Ubuntu
.. code-block:: bash
yum install qt5-qtbase-devel.x86_64
yum install qt5-qtsvg-devel.x86_64
yum install expat-devel.x86_64
apt install qt6-base-dev
4. Using conda
@@ -346,20 +347,15 @@ using this compiler
conda config --add channels slsdetectorgroup
conda config --set channel_priority strict
# create environment to compile
# on rhel7
conda create -n slsgui gxx_linux-64 gxx_linux-64 mesa-libgl-devel-cos6-x86_64 qt
# on fedora or newer systems
conda create -n slsgui qt
# when using conda compilers, would also need libgl, but no need for it on fedora unless maybe using it with ROOT
# create environment to compile (qt6-main is the Qt6 base package on conda-forge)
conda create -n slsgui zeromq gxx_linux-64 qt6-main
# activate environment
conda activate slsgui
# compile with cmake outside slsDetecorPackage folder
mkdir build && cd build
cmake ../slsDetectorPackage -DSLS_USE_GUI=ON
cmake ../slsDetectorPackage -DSLS_USE_GUI=ON -DCMAKE_PREFIX_PATH=$CONDA_PREFIX
make -j12
# or compile with cmk.sh
-57
View File
@@ -1,57 +0,0 @@
#inspired by: https://github.com/ericriff/qwt/blob/master/CMakeLists.txt
# Build a static version of qwt from tar file
cmake_minimum_required(VERSION 3.12)
project(qwt)
set(PROJECT_VERSION 6.1.5)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
# Extract qwt sources from the supplied source file
set(INTERNALQWTDIR "qwt-source/")
set(QWTBASE ${CMAKE_CURRENT_BINARY_DIR}/${INTERNALQWTDIR})
file(MAKE_DIRECTORY ${QWTBASE})
execute_process(
COMMAND tar -xf ${CMAKE_CURRENT_SOURCE_DIR}/qwt-6.1.5.tar.bz2 -C ${QWTBASE} --strip-components=1
RESULT_VARIABLE ret
)
if(ret AND NOT ret EQUAL 0)
message( FATAL_ERROR "Could not unpack qwt")
endif()
# Without this define moc files are not included and linking of examples fails.
add_definitions(-DQWT_MOC_INCLUDE)
find_package(Qt5 REQUIRED
COMPONENTS
Core
Gui
Widgets
OpenGL
Concurrent
PrintSupport
Svg
)
file(GLOB QWT_SOURCES ${QWTBASE}src/*.cpp)
file(GLOB QWT_HEADERS ${QWTBASE}src/*.h)
add_library(qwt STATIC ${QWT_SOURCES} ${QWT_HEADERS} )
target_include_directories(qwt PUBLIC
$<BUILD_INTERFACE:${QWTBASE}/src>
)
target_link_libraries(qwt PUBLIC
Qt5::Core
Qt5::Gui
Qt5::Widgets
Qt5::OpenGL
Qt5::Concurrent
Qt5::PrintSupport
Qt5::Svg
)
# Disable all warnings in QWT since we don’t want to patch the library
target_compile_options(qwt PRIVATE -w)
Binary file not shown.
+65 -22
View File
@@ -5,17 +5,60 @@ set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
find_package(Qt5 5.9 COMPONENTS Widgets Core Gui REQUIRED)
# Qt6 only (Widgets/Gui/Core). Concurrent is needed for the acquisition
# thread in qDrawPlot.cpp. No Qwt, no Qt5 compatibility modules.
find_package(Qt6 6.2 REQUIRED COMPONENTS Widgets Gui Core Concurrent)
find_package(PNG REQUIRED)
find_package(ZLIB REQUIRED)
set(SOURCES
# The Qt-only plotting stack is built once as a static library and linked by
# the GUI executable as well as by the plotting demo and the QtTest suite.
set(PLOTTING_SOURCES
slsDetectorPlotting/src/SlsQtPlotCommon.cpp
slsDetectorPlotting/src/SlsQtFastImage.cpp
slsDetectorPlotting/src/SlsQtScalePanel.cpp
slsDetectorPlotting/src/SlsQt1DPlot.cpp
slsDetectorPlotting/src/SlsQt1DZoomer.cpp
slsDetectorPlotting/src/SlsQt2DHist.cpp
slsDetectorPlotting/src/SlsQt2DPlot.cpp
)
set(PLOTTING_HEADERS
slsDetectorPlotting/include/SlsQtPlotCommon.h
slsDetectorPlotting/include/SlsQtFastImage.h
slsDetectorPlotting/include/SlsQtScalePanel.h
slsDetectorPlotting/include/SlsQt1DPlot.h
slsDetectorPlotting/include/SlsQt2DHist.h
slsDetectorPlotting/include/SlsQt2DPlot.h
)
add_library(slsDetectorPlotting STATIC
${PLOTTING_SOURCES}
${PLOTTING_HEADERS}
)
set_target_properties(slsDetectorPlotting PROPERTIES
# plotting widgets are Q_OBJECT classes; moc them in the library
AUTOMOC ON
AUTOUIC OFF
)
target_include_directories(slsDetectorPlotting PUBLIC
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/slsDetectorPlotting/include>"
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
)
target_link_libraries(slsDetectorPlotting
PUBLIC
slsProjectOptions
# sls/ansi.h, sls/sls_detector_defs.h and the logger symbols
slsSupportStatic
Qt6::Widgets
Qt6::Gui
Qt6::Core
PRIVATE
slsProjectWarnings
)
set(SOURCES
src/qDetectorMain.cpp
src/qDrawPlot.cpp
src/qCloneWidget.cpp
@@ -46,14 +89,9 @@ set(FORMS
forms/form_cloneplot.ui
)
qt5_wrap_ui(FORMS_H ${FORMS})
qt6_wrap_ui(FORMS_H ${FORMS})
set(HEADERS
slsDetectorPlotting/include/SlsQt1DPlot.h
slsDetectorPlotting/include/SlsQt1DZoomer.h
slsDetectorPlotting/include/SlsQt2DHist.h
slsDetectorPlotting/include/SlsQt2DPlot.h
slsDetectorPlotting/include/SlsQt2DZoomer.h
include/qDefs.h
include/qDetectorMain.h
include/qDrawPlot.h
@@ -72,13 +110,9 @@ set(HEADERS
set(RESOURCES
include/icons.qrc
)
qt5_add_resources(RESOURCES_SRCS ${RESOURCES})
qt6_add_resources(RESOURCES_SRCS ${RESOURCES})
add_definitions(
${Qt5Widgets_DEFINITIONS} -DPRINT_LOG #-DVERBOSE
)
add_executable(slsDetectorGui
${SOURCES}
${HEADERS}
@@ -86,28 +120,27 @@ add_executable(slsDetectorGui
${RESOURCES_SRCS}
)
target_compile_definitions(slsDetectorGui PRIVATE PRINT_LOG)
target_include_directories(slsDetectorGui PUBLIC
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/slsDetectorPlotting/include>"
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
"$<BUILD_INTERFACE:${QT5Widgets_INCLUDE_DIRS}>"
"$<BUILD_INTERFACE:${SLS_INTERNAL_QWT_DIR}/include>"
"$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>"
)
target_link_libraries(slsDetectorGui PUBLIC
slsProjectOptions
slsDetectorStatic
slsDetectorPlotting
PNG::PNG
ZLIB::ZLIB
Qt5::Widgets
Qt5::Gui
Qt5::Core
expat
Qt6::Widgets
Qt6::Gui
Qt6::Core
Qt6::Concurrent
PRIVATE
slsProjectWarnings
qwt
)
set_target_properties(slsDetectorGui PROPERTIES
@@ -119,4 +152,14 @@ if((CMAKE_BUILD_TYPE STREQUAL "Release") AND SLS_LTO_AVAILABLE)
set_property(TARGET slsDetectorGui PROPERTY INTERPROCEDURAL_OPTIMIZATION True)
endif()
# Demo application and QtTest based tests for the plotting widgets.
# These are provided by the verification task; wire them in when present so
# they do not have to touch this file. Both link slsDetectorPlotting.
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt")
add_subdirectory(tests)
endif()
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/demo/CMakeLists.txt")
add_subdirectory(demo)
endif()
sls_install_executable(slsDetectorGui COMPONENT gui)
@@ -1,192 +1,285 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#ifndef SLSQT1DPLOT_H
#define SLSQT1DPLOT_H
#include "SlsQt1DZoomer.h"
#include "sls/ansi.h"
#include "sls/sls_detector_defs.h"
#include <array>
#include <qwt_plot.h>
#include <qwt_plot_curve.h>
#include <qwt_plot_marker.h>
#include <qwt_plot_shapeitem.h>
#include <qwt_scale_div.h>
class QPen;
class QwtSymbol;
namespace sls {
class SlsQt1DPlot;
class SlsQtH1D : public QwtPlotCurve {
public:
SlsQtH1D(QString title, int n, double xmin, double xmax, double *data = 0);
SlsQtH1D(QString title, int n, double *data_x, double *data_y);
~SlsQtH1D();
void Attach(SlsQt1DPlot *p);
void Detach(SlsQt1DPlot *p);
int SetLineColor(int c = -1);
int SetLineWidth(int w = 1);
void SetLineStyle(int s = 0);
void setStyleLinesorDots(bool isLines);
void setSymbolMarkers(bool isMarker);
void SetData(int n, double xmin, double xmax, double *d = 0);
void SetData(int n, double *dx, double *dy);
double *GetX() { return x; }
double *GetY() { return y; }
int GetNBinsX() { return ndata; }
double FillBin(int bx, double v = 1);
double Fill(double x, double v = 1);
double SetBinContent(int bx, double v);
double SetContent(double x, double v);
int FindBinIndex(double px);
double GetXMin() { return x[0]; }
double GetFirstXgtZero() { return firstXgt0; }
double GetXMax() { return x[ndata - 1]; }
double GetYMin() { return ymin; }
double GetFirstYgtZero() { return firstYgt0; }
double GetYMax() { return ymax; }
SlsQtH1D *Add(double v);
private:
int ndata;
int n_array;
double dx;
double *x{nullptr}, *y{nullptr};
double ymin, ymax;
double firstXgt0, firstYgt0;
void Initailize();
int SetUpArrays(int n);
int CheckIndex(int bx);
QPen *pen_ptr{nullptr};
};
class SlsQtH1DList {
public:
SlsQtH1DList(SlsQtH1D *hist = 0);
~SlsQtH1DList();
SlsQtH1D *Add(SlsQtH1D *h);
void Remove(SlsQtH1D *h);
void Print();
SlsQtH1D *Hist() { return the_hist; } // if no hist returns 0
SlsQtH1DList *Next() { return the_next; }
private:
SlsQtH1DList *the_next;
SlsQtH1D *the_hist;
};
class SlsQt1DPlot : public QwtPlot {
Q_OBJECT
public:
SlsQt1DPlot(QWidget * = NULL, bool gain = false);
~SlsQt1DPlot();
void SetTitle(QString title);
void SetXTitle(QString title);
void SetYTitle(QString title);
void SetTitleFont(const QFont &f);
void SetXFont(const QFont &f);
void SetYFont(const QFont &f);
void InsertHLine(double y);
void RemoveHLine();
void InsertVLine(double v);
void RemoveVLine();
/** This group of functions have been added by Dhanya on 19.06.2012 to be
able to use zooming functionality without mouse control*/
void DisableZoom(bool disable);
void EnableXAutoScaling() {
setAxisAutoScale(QwtPlot::xBottom, true);
Update();
};
void EnableYAutoScaling() {
setAxisAutoScale(QwtPlot::yLeft, true);
Update();
};
void SetYStep(int step) { ystep = step; };
void SetXMinMax(double min, double max) {
setAxisScale(QwtPlot::xBottom, min, max);
};
void SetYMinMax(double min, double max) {
setAxisScale(QwtPlot::yLeft, min, max);
};
double GetXMinimum() { return hist_list->Hist()->GetXMin(); };
double GetXMaximum() { return hist_list->Hist()->GetXMax(); };
double GetYMinimum() { return hist_list->Hist()->GetYMin(); };
double GetYMaximum() { return hist_list->Hist()->GetYMax(); };
/**---*/
void SetZoom(double xmin, double ymin, double x_width, double y_width);
void SetZoomBase(double xmin, double ymin, double x_width, double y_width) {
zoomer->SetZoomBase(xmin, ymin, x_width, y_width);
}
void alignScales();
void SetLogX(bool yes = 1);
void SetLogY(bool yes = 1);
void EnableRoiBoxes(std::vector<slsDetectorDefs::ROI> roi, int ymin,
int ymax);
void DisableRoiBoxes();
private:
bool gainPlot{false};
SlsQtH1DList *hist_list{nullptr};
SlsQt1DZoomer *zoomer{nullptr};
QwtPlotPanner *panner{nullptr};
QwtPlotMarker *hline{nullptr};
QwtPlotMarker *vline{nullptr};
bool disableZoom{false};
int ystep{0};
void SetupZoom();
void UnknownStuff();
// void alignScales();
void CalculateNResetZoomBase();
void NewHistogramAttached(SlsQtH1D *h);
void HistogramDetached(SlsQtH1D *h);
void SetLog(int axisId, bool yes);
friend void SlsQtH1D::Attach(SlsQt1DPlot *p);
friend void SlsQtH1D::Detach(SlsQt1DPlot *p);
std::vector<std::unique_ptr<QwtPlotShapeItem>> roiBoxes{};
QwtPlotShapeItem *roiBox{nullptr};
signals:
void PlotZoomedSignal(const QRectF &);
public slots:
void SetZoomX(const QRectF &rect);
void UnZoom();
void Update();
private slots:
void GetPannedCoord(int, int);
};
} // namespace sls
#endif
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2026 Contributors to the SLS Detector Package
#ifndef SLSQT1DPLOT_H
#define SLSQT1DPLOT_H
// Qt6-only 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.
#include "SlsQtPlotCommon.h"
#include "sls/sls_detector_defs.h"
#include <QColor>
#include <QFont>
#include <QPen>
#include <QPointF>
#include <QRectF>
#include <QString>
#include <QWidget>
#include <vector>
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()).
class SlsQtH1D {
public:
SlsQtH1D(QString title, int n, double xmin, double xmax,
double *data = nullptr);
SlsQtH1D(QString title, int n, double *data_x, double *data_y);
~SlsQtH1D();
void Attach(SlsQt1DPlot *p);
void Detach(SlsQt1DPlot *p);
int SetLineColor(int c = -1);
int SetLineWidth(int w = 1);
void SetLineStyle(int s = 0);
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).
void setLegendVisible(bool visible) { m_legendVisible = visible; }
bool legendVisible() const { return m_legendVisible; }
void SetData(int n, double xmin, double xmax, double *d = nullptr);
void SetData(int n, double *dx, double *dy);
double *GetX() { return m_x.data(); }
double *GetY() { return m_y.data(); }
int GetNBinsX() const { return m_ndata; }
double FillBin(int bx, double v = 1);
double Fill(double x, double v = 1);
double SetBinContent(int bx, double v);
double SetContent(double x, double v);
int FindBinIndex(double px);
double GetXMin() const { return m_ndata > 0 ? m_x.front() : 0.0; }
double GetFirstXgtZero() const { return m_firstXgt0; }
double GetXMax() const {
return m_ndata > 0 ? m_x[static_cast<size_t>(m_ndata - 1)] : 0.0;
}
double GetYMin() const { return m_ymin; }
double GetFirstYgtZero() const { return m_firstYgt0; }
double GetYMax() const { return m_ymax; }
SlsQtH1D *Add(double v);
QString title() const { return m_title; }
void setTitle(const QString &title) { m_title = title; }
// Read access for the painter only.
const QPen &pen() const { return m_pen; }
bool isLines() const { return m_linesMode; }
bool isMarkers() const { return m_markerMode; }
private:
friend class SlsQt1DPlot;
void initialize();
void setUpArrays(int n);
int checkIndex(int bx);
QString m_title;
int m_ndata{0};
double m_dx{0.0};
std::vector<double> m_x;
std::vector<double> m_y;
double m_ymin{0.0};
double m_ymax{0.0};
double m_firstXgt0{-1.0};
double m_firstYgt0{-1.0};
bool m_linesMode{true};
bool m_markerMode{false};
bool m_legendVisible{true};
QPen m_pen;
SlsQt1DPlot *m_plot{nullptr};
};
// Custom painted 1D plot (replaces QwtPlot + QwtPlotZoomer + QwtPlotPanner).
class SlsQt1DPlot : public QWidget {
Q_OBJECT
public:
explicit SlsQt1DPlot(QWidget *parent = nullptr, bool gain = false);
~SlsQt1DPlot() override;
void SetTitle(QString title);
void SetXTitle(QString title);
void SetYTitle(QString title);
void SetTitleFont(const QFont &f);
void SetXFont(const QFont &f);
void SetYFont(const QFont &f);
void InsertHLine(double y);
void RemoveHLine();
void InsertVLine(double v);
void RemoveVLine();
// Disables every zoom/pan interaction (rubber band, wheel zoom, middle
// drag panning and the right-click zoom out), like the old zoomer/panner
// based implementation did.
void DisableZoom(bool disable);
void EnableXAutoScaling();
void EnableYAutoScaling();
void SetYStep(int step) { m_yStep = step; }
void SetXMinMax(double min, double max);
void SetYMinMax(double min, double max);
double GetXMinimum() const;
double GetXMaximum() const;
double GetYMinimum() const;
double GetYMaximum() const;
bool isGainPlot() const { return m_gainPlot; }
bool isZoomDisabled() const { return m_disableZoom; }
// Currently visible data range (x=left, y=bottom, width/height > 0).
QRectF viewRect() const;
int zoomLevel() const { return m_zoomIndex; }
void SetZoom(double xmin, double ymin, double x_width, double y_width);
void SetZoomBase(double xmin, double ymin, double x_width,
double y_width);
void alignScales();
void SetLogX(bool yes = true);
void SetLogY(bool yes = true);
void EnableRoiBoxes(std::vector<slsDetectorDefs::ROI> roi, int ymin,
int ymax);
void DisableRoiBoxes();
signals:
void PlotZoomedSignal(const QRectF &rect);
public slots:
void SetZoomX(const QRectF &rect);
void UnZoom();
void Update();
protected:
void paintEvent(QPaintEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
void leaveEvent(QEvent *event) override;
private:
friend class SlsQtH1D;
struct Geometry {
QRect plot; // plot rectangle in widget pixels
std::vector<double> xTicks;
std::vector<double> yTicks;
std::vector<QString> xLabels;
std::vector<QString> yLabels;
int titleH{0};
int xTitleH{0};
int yTitleW{0};
int legendH{0};
};
// histogram list
void addHistogram(SlsQtH1D *h);
void removeHistogram(SlsQtH1D *h);
// ranges / zoom
void recomputeBase();
void clampView();
void setView(double xLo, double xHi, double yLo, double yHi);
QRectF baseRect() const;
QRectF currentRect() const;
void resetZoom(bool emitSignal);
void zoomOutOneLevel();
void applyZoomRect(const QRectF &rect);
void pushZoomRect(const QRectF &rect, bool emitSignal);
void zoomAbout(const QPointF &pos, double factor, bool push);
bool zoomAllowed() const { return !m_disableZoom && !m_gainPlot; }
void emitZoomed();
// coordinate transforms
double tx(double v) const;
double ty(double v) const;
double itx(double t) const;
double ity(double t) const;
QPointF toWidget(double x, double y, const Geometry &g) const;
QPointF toData(const QPointF &pos, const Geometry &g) const;
// painting helpers
Geometry computeGeometry() const;
std::vector<double> tickValues(double lo, double hi, bool log,
int maxTicks) const;
std::vector<QString> tickLabels(const std::vector<double> &ticks,
double lo, double hi, bool log) const;
void paintGrid(QPainter &p, const Geometry &g) const;
void paintCurves(QPainter &p, const Geometry &g) const;
void paintDecorations(QPainter &p, const Geometry &g) const;
void paintFrame(QPainter &p, const Geometry &g) const;
void paintLegend(QPainter &p, const Geometry &g) const;
void paintTracker(QPainter &p, const Geometry &g) const;
void paintRubberBand(QPainter &p, const Geometry &g) const;
// state
bool m_gainPlot{false};
std::vector<SlsQtH1D *> m_hists;
QString m_title;
QString m_xTitle;
QString m_yTitle;
QFont m_titleFont;
QFont m_xTitleFont;
QFont m_yTitleFont;
QFont m_tickFont;
sls::plot::PlotTheme m_theme;
bool m_logX{false};
bool m_logY{false};
bool m_xAuto{true};
bool m_yAuto{true};
bool m_disableZoom{false};
int m_yStep{0};
double m_xLo{0.0}, m_xHi{1.0}, m_yLo{0.0}, m_yHi{1.0};
double m_bxLo{0.0}, m_bxHi{1.0}, m_byLo{0.0}, m_byHi{1.0};
std::vector<QRectF> m_zoomStack;
int m_zoomIndex{0};
bool m_rubberBand{false};
QPointF m_rubberStart;
QPointF m_rubberCur;
bool m_panning{false};
QPointF m_panStart;
double m_panXnLo{0.0}, m_panXnHi{1.0}, m_panYnLo{0.0}, m_panYnHi{1.0};
bool m_trackValid{false};
QPointF m_trackPos;
bool m_hasHLine{false};
double m_hLine{0.0};
bool m_hasVLine{false};
double m_vLine{0.0};
bool m_roiOn{false};
std::vector<slsDetectorDefs::ROI> m_rois;
int m_roiYMin{0};
int m_roiYMax{0};
};
} // namespace sls
#endif
@@ -1,58 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#ifndef SLSQT1DZOOMER_H
#define SLSQT1DZOOMER_H
#include <qwt_global.h>
#include <qwt_plot_panner.h>
#include <qwt_plot_zoomer.h>
namespace sls {
class SlsQtH1D;
class SlsQt1DZoomer : public QwtPlotZoomer {
private:
double x0, x1, y0, y1;
double firstXgt0, firstYgt0;
bool xIsLog, yIsLog;
public:
SlsQt1DZoomer(QWidget *canvas) : QwtPlotZoomer(canvas) {
setTrackerMode(AlwaysOn);
xIsLog = yIsLog = 0;
}
double x() { return x0; }
double x_firstGreaterThan0() { return firstXgt0; }
double w() { return x1 - x0; }
double y() { return y0; }
double y_firstGreaterThan0() { return firstYgt0; }
double h() { return y1 - y0; }
void SetZoomBase(double xmin, double ymin, double x_width, double y_width);
void SetZoomBase(SlsQtH1D *h);
void ExtendZoomBase(SlsQtH1D *h);
void ResetZoomBase();
bool IsLogX() { return xIsLog; }
bool IsLogY() { return yIsLog; }
bool SetLogX(bool yes) { return xIsLog = yes; }
bool SetLogY(bool yes) { return yIsLog = yes; }
using QwtPlotPicker::trackerText;
virtual QwtText trackerText(const QPoint &pos) const {
QColor bg(Qt::white);
bg.setAlpha(200);
QwtText text = QwtPlotPicker::trackerText(pos);
text.setBackgroundBrush(QBrush(bg));
return text;
}
};
} // namespace sls
#endif
@@ -1,132 +1,96 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
// Copyright (C) 2026 Contributors to the SLS Detector Package
#pragma once
#ifndef SLSQT2DHIST_H
#define SLSQT2DHIST_H
// 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.
//
// 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).
//
// 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.
#include <qwt_color_map.h>
#include <qwt_plot_spectrogram.h>
#include <qwt_scale_draw.h>
#include <qwt_scale_widget.h>
#include <vector>
namespace sls {
class SlsQt2DHist : public QwtRasterData {
private:
double x_min, x_max, y_min, y_max;
double x_width, y_width;
int nx, ny, nb;
double *data{nullptr};
double z_min, z_mean, z_max;
bool z_mean_has_been_calculated;
int nx_array, ny_array;
bool interp;
static double value_between_points(double p1, double v1, double p2,
double v2, double p) { // linear extrap
return (v2 - v1) / (p2 - p1) * (p - p1) + v1;
}
class SlsQt2DHist {
public:
SlsQt2DHist(int nbinsx = 10, double xmin = 0, double xmax = 10,
int nbinsy = 10, double ymin = 0, double ymax = 10,
double *d = 0, double zmin = 0, double zmax = -1);
virtual ~SlsQt2DHist();
double *d = nullptr, double zmin = 0, double zmax = -1);
~SlsQt2DHist() = default;
double GetXMin() { return x_min; }
double GetXMax() { return x_max; }
double GetXBinWidth() { return x_width; }
double GetYMin() { return y_min; }
double GetYMax() { return y_max; }
double GetYBinWidth() { return y_width; }
double GetMinimum() { return z_min; }
double GetMaximum() { return z_max; }
// ---- bin geometry (data coordinates) ---------------------------------
double GetXMin() const { return x_min; }
double GetXMax() const { return x_max; }
double GetXBinWidth() const { return x_width; }
double GetYMin() const { return y_min; }
double GetYMax() const { return y_max; }
double GetYBinWidth() const { return y_width; }
int GetNBinsX() const { return nx; }
int GetNBinsY() const { return ny; }
// ---- z range ----------------------------------------------------------
double GetMinimum() const { return z_min; }
double GetMaximum() const { return z_max; }
// Mean of all bins (lazily computed; invalidated by the setters).
double GetMean();
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.
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
// (larger than z_max) fallback so the log mapping stays valid.
double SetMinimumToFirstGreaterThanZero();
int GetNBinsX() { return nx; }
int GetNBinsY() { return ny; }
double GetBinValue(int bx, int by);
int GetBinIndex(int bx, int by);
double *GetDataPtr() { return data; }
void Interpolate(bool on = 1) { interp = on; }
// ---- data access ------------------------------------------------------
int GetBinIndex(int bx, int by) const;
int FindBinIndex(double x, double y) const;
double GetBinValue(int bx, int by) const;
void SetBinValue(int bx, int by, double v);
double *GetDataPtr() { return data.data(); }
const double *GetDataPtr() const { return data.data(); }
// ---- sampling ---------------------------------------------------------
void Interpolate(bool on = true) { interp = on; }
bool IsInterpolated() const { return interp; }
// Box sampling (containing bin) or, when Interpolate(true) is set,
// bilinear interpolation between the four surrounding bin centres.
// Points outside the data sample the under/overflow bin (which SetData
// keeps at 0).
double value(double x, double y) const;
// ---- bulk input -------------------------------------------------------
// Copies nbinsx*nbinsy values from d (x fastest). d may be nullptr: the
// call then only re-allocates the buffer when the geometry changed, and a
// new allocation is zeroed; with an unchanged geometry the previous values
// 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 SetMinimumToFirstGreaterThanZero();
void SetMinimum(double zmin) { z_min = zmin; }
void SetMaximum(double zmax) { z_max = zmax; }
void SetMinMax(double zmin = 0, double zmax = -1);
int FindBinIndex(double x, double y);
virtual QwtRasterData *copy() const {
// this function does not create a new SlsQt2DHistData instance,
// just passes a pointer so that data is common to both the copy and the
// original instance
return (QwtRasterData *)this;
}
virtual QwtInterval range() const { return QwtInterval(z_min, z_max); }
virtual QwtInterval interval(Qt::Axis axis) const {
switch (axis) {
case Qt::ZAxis:
return QwtInterval(z_min, z_max);
case Qt::XAxis:
return QwtInterval(x_min, x_max);
case Qt::YAxis:
return QwtInterval(y_min, y_max);
default:
return QwtInterval(z_min, z_max);
};
};
virtual double value(double x, double y) const {
// if(!interp){ //default is box like plot
int index =
int((x - x_min) / x_width) + int((y - y_min) / y_width) * nx;
if (index < 0 || index > nb)
index = nb;
if (!interp)
return data[index];
//}
int x_int = int((x - x_min) / x_width - 0.5);
if (x_int < 0)
x_int = 0;
else if (x_int > nx - 2)
x_int = nx - 2;
int y_int = int((y - y_min) / y_width - 0.5);
if (y_int < 0)
y_int = 0;
else if (y_int > ny - 2)
y_int = ny - 2;
int b00 = x_int * ny + y_int;
int b01 = x_int * ny + y_int + 1;
int b10 = (x_int + 1) * ny + y_int;
int b11 = (x_int + 1) * ny + y_int + 1;
// vertical extrap
double y0 = y_min + (y_int + 0.5) * y_width;
double y1 = y_min + (y_int + 1.5) * y_width;
double left_v = value_between_points(y0, data[b00], y1, data[b01], y);
double right_v = value_between_points(y0, data[b10], y1, data[b11], y);
// horazontal extrap
return 0.5;
return value_between_points(x_min + (x_int + 0.5) * x_width, left_v,
x_min + (x_int + 1.5) * x_width, right_v,
x);
}
private:
double x_min{0.0}, x_max{0.0}, y_min{0.0}, y_max{0.0};
double x_width{1.0}, y_width{1.0};
int nx{0}, ny{0}, nb{0};
// nb + 1 values: the last entry is the under/overflow bin (kept at 0), so
// an out-of-range GetBinIndex() still returns a valid index.
std::vector<double> data;
double z_min{0.0}, z_mean{0.0}, z_max{0.0};
bool z_mean_has_been_calculated{false};
bool interp{false};
};
} // namespace sls
#endif
} // namespace sls
@@ -1,109 +1,191 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#pragma once
#include "SlsQt2DHist.h"
#include "SlsQt2DZoomer.h"
#include "sls/sls_detector_defs.h"
#include <array>
#include <qlist.h>
#include <qwt_plot.h>
#include <qwt_plot_shapeitem.h>
#include <qwt_plot_spectrogram.h>
class QwtPlotPanner;
class QwtScaleWidget;
class QwtLinearColorMap;
namespace sls {
class SlsQt2DPlot : public QwtPlot {
Q_OBJECT
public:
SlsQt2DPlot(QWidget * = NULL, bool gain = false);
~SlsQt2DPlot();
void SetTitle(QString title);
void SetXTitle(QString title);
void SetYTitle(QString title);
void SetZTitle(QString title);
void SetTitleFont(const QFont &f);
void SetXFont(const QFont &f);
void SetYFont(const QFont &f);
void SetZFont(const QFont &f);
void UnZoom(bool replot = true);
void SetZoom(double xmin, double ymin, double x_width, double y_width);
void DisableZoom(bool disable);
void EnableXAutoScaling() { setAxisAutoScale(QwtPlot::xBottom, true); };
void EnableYAutoScaling() { setAxisAutoScale(QwtPlot::yLeft, true); };
void SetXMinMax(double min, double max) {
setAxisScale(QwtPlot::xBottom, min, max);
};
void SetYMinMax(double min, double max) {
setAxisScale(QwtPlot::yLeft, min, max);
};
double GetXMinimum() { return hist->GetXMin(); };
double GetXMaximum() { return hist->GetXMax(); };
double GetYMinimum() { return hist->GetYMin(); };
double GetYMaximum() { return hist->GetYMax(); };
double GetZMinimum() { return hist->GetMinimum(); }
double GetZMaximum() { return hist->GetMaximum(); }
void SetZMinMax(double zmin = 0, double zmax = -1);
void SetZMinimumToFirstGreaterThanZero() {
hist->SetMinimumToFirstGreaterThanZero();
}
double GetZMean() { return hist->GetMean(); }
void SetData(int nbinsx, double xmin, double xmax, int nbinsy, double ymin,
double ymax, double *d, double zmin = 0, double zmax = -1) {
hist->SetData(nbinsx, xmin, xmax, nbinsy, ymin, ymax, d, zmin, zmax);
}
double *GetDataPtr() { return hist->GetDataPtr(); }
int GetBinIndex(int bx, int by) { return hist->GetBinIndex(bx, by); }
int FindBinIndex(double x, double y) { return hist->FindBinIndex(x, y); }
void SetBinValue(int bx, int by, double v) { hist->SetBinValue(bx, by, v); }
double GetBinValue(int bx, int by) { return hist->GetBinValue(bx, by); }
void FillTestPlot(int i = 0);
void Update();
void SetInterpolate(bool enable);
void SetContour(bool enable);
void SetLogz(bool enable, bool isMin, bool isMax, double min, double max);
void SetZRange(bool isMin, bool isMax, double min, double max);
void LogZ(bool on = 1);
void EnableRoiBoxes(std::vector<slsDetectorDefs::ROI> roi);
void DisableRoiBoxes();
public slots:
void showSpectrogram(bool on);
void SetZoom(const QRectF &rect);
private slots:
void GetPannedCoord(int, int);
signals:
void PlotZoomedSignal(const QRectF &);
private:
void SetupZoom();
void SetupColorMap();
bool gainPlot{false};
QwtLinearColorMap *myColourMap(QVector<double> colourStops);
QwtLinearColorMap *myColourMap(int log = 0);
QwtPlotSpectrogram *d_spectrogram{nullptr};
SlsQt2DHist *hist{nullptr};
SlsQt2DZoomer *zoomer{nullptr};
QwtPlotPanner *panner{nullptr};
QwtScaleWidget *rightAxis{nullptr};
QList<double> contourLevelsLinear;
QList<double> contourLevelsLog;
bool disableZoom{false};
int isLog;
std::vector<std::unique_ptr<QwtPlotShapeItem>> roiBoxes{};
};
} // namespace sls
// SPDX-License-Identifier: LGPL-3.0-or-other
// 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;
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);
QString title() const;
void SetTitleFont(const QFont &f);
void SetXFont(const QFont &f);
void SetYFont(const QFont &f);
void SetZFont(const QFont &f);
// ---- 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);
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 DisableRoiBoxes();
// Extra accessors used by the integration/verification code.
SlsQtFastImage *imageView() const { return m_view; }
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:
void PlotZoomedSignal(const QRectF &);
private:
void setupUi();
void pushImage();
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};
SlsQtFastImage *m_view{nullptr};
SlsQtScalePanel *m_panel{nullptr};
bool m_logZ{false};
bool m_interp{false};
bool m_contourOn{false};
bool m_showImage{true};
bool m_zoomDisabled{false};
// Pending programmatic viewport (Enable*AutoScaling/SetXMinMax/...).
bool m_autoX{true};
bool m_autoY{true};
bool m_applyViewPending{false};
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};
};
} // namespace sls
@@ -1,47 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#ifndef SLSQT2DZOOMER_H
#define SLSQT2DZOOMER_H
#include "SlsQt2DHist.h"
#include <cstdio>
#include <qwt_plot_panner.h>
#include <qwt_plot_zoomer.h>
namespace sls {
class SlsQt2DZoomer : public QwtPlotZoomer {
private:
SlsQt2DHist *hist;
public:
SlsQt2DZoomer(QWidget *canvas) : QwtPlotZoomer(canvas) {
setTrackerMode(AlwaysOn);
}
void SetHist(SlsQt2DHist *h) { hist = h; }
virtual QwtText trackerTextF(const QPointF &pos) const {
QColor bg(Qt::white);
bg.setAlpha(200);
// QwtText text = QwtPlotZoomer::trackerText(pos);
static QwtText text;
if (hist) {
static char t[200];
sprintf(t, "%3.2f, %3.2f, %3.2f", pos.x(), pos.y(),
hist->value(pos.x(), pos.y()));
text.setText(t);
} else {
QPoint p = pos.toPoint();
QwtText text = QwtPlotZoomer::trackerText(p);
}
text.setBackgroundBrush(QBrush(bg));
return text;
}
};
} // namespace sls
#endif
@@ -0,0 +1,245 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// 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 <QFont>
#include <QImage>
#include <QPointF>
#include <QRectF>
#include <QString>
#include <QTransform>
#include <QWidget>
#include <functional>
#include <vector>
class QPainter;
namespace sls {
class SlsQtFastImage : public QWidget {
Q_OBJECT
public:
// Smallest data width/height the viewport may have, in image pixels.
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();
bool hasImage() const;
int imageWidth() const;
int imageHeight() const;
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;
// ---- title and axis titles -------------------------------------------
void setTitle(const QString &title);
QString title() const;
void setXAxisTitle(const QString &title);
QString xAxisTitle() const;
void setYAxisTitle(const QString &title);
QString yAxisTitle() const;
void setTitleFont(const QFont &f);
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;
protected:
void paintEvent(QPaintEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void mouseDoubleClickEvent(QMouseEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
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;
};
void renderImage();
Fit computeFit() const;
QRect imageRect() const;
QRect scaleRect() 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;
double vpW() const { return (m_vpW < 0) ? m_nx : m_vpW; }
double vpH() const { return (m_vpH < 0) ? m_ny : m_vpH; }
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;
bool m_logScale = false;
bool m_integerValues = false;
bool m_zeroWhite = false;
bool m_showBar = false;
bool m_axesVisible = true;
bool m_zoomEnabled = true;
std::vector<int> m_hist;
double m_histLo = 0.0, m_histHi = 1.0;
qint64 m_histMs = 0;
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;
};
} // namespace sls
@@ -0,0 +1,103 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2026 Contributors to the SLS Detector Package
#pragma once
// Shared plotting primitives for the Qt6-only 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.
#include <QColor>
#include <QFont>
#include <QRect>
#include <QRgb>
#include <QSize>
#include <QString>
#include <cmath>
#include <vector>
namespace sls {
namespace plot {
// Palettes offered by the image scale panel. Color / BW1 / BW2 are the
// original three and stay first (the b / B / c shortcuts use those indices).
// Gain4 is the fixed, muted palette for the 0..3 gain bits and is *not* in the
// chooser (see paletteCount()).
enum class Palette {
Color,
BW1,
BW2,
Turbo,
Viridis,
Plasma,
Inferno,
Magma,
Cividis,
Hot,
Gray,
Gray_r,
Coolwarm,
Bwr,
Seismic,
RdBu,
YlGnBu,
Sunset,
Gain4
};
// 256-entry RGB lookup table for one palette. All tables are built once, the
// first time they are needed, and are safe to use from any thread afterwards.
const QRgb *paletteLut(Palette p);
// Human-readable name (label of the scale panel's palette chooser).
const char *paletteName(Palette p);
// Number of palettes offered in the chooser: everything except Gain4.
int paletteCount();
// Log10 mapping that clamps values <= 0 to 1e-2, so that empty pixels (or
// negative pedestal-corrected values) stay visible instead of becoming -inf.
inline double logClamp(double v) {
return std::log10(v > 1e-2 ? v : 1e-2);
}
// Nice axis step: 1, 2 or 5 times a power of ten, at most maxTicks intervals
// across span. Returns 1.0 for a degenerate span.
double niceStep(double span, int maxTicks = 8);
// All nice ticks in [lo, hi] (multiples of niceStep()). Empty when the range
// is degenerate. At most maxTicks + 1 values are returned.
std::vector<double> computeLinearTicks(double lo, double hi, int maxTicks = 8);
// Formats one tick with the precision implied by the step: no trailing zeros,
// no "-0", scientific notation only for very large / very small values.
QString formatTick(double v, double step);
// The dark plot style shared by the 1D plot, the 2D plot and the histogram
// strip of the scale panel. The image view keeps its own margins because it
// also has axis titles, but uses the same colours and font size.
struct PlotTheme {
PlotTheme();
QColor background{28, 28, 28};
QColor frame{225, 225, 225};
QColor grid{95, 95, 95};
QColor tick{215, 215, 215};
QColor text{230, 230, 230};
QFont tickFont;
int leftMargin = 52;
int bottomMargin = 26;
int topMargin = 6;
int rightMargin = 6;
};
// Inner plot rectangle of a widget, after the theme margins have been
// subtracted. Never smaller than 10x10 so a tiny widget still paints.
QRect plotRectFor(const QSize &widgetSize, const PlotTheme &theme);
} // namespace plot
} // namespace sls
@@ -0,0 +1,169 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2026 Contributors to the SLS Detector Package
#pragma once
// Thin histogram strip + scale panel of the Qt6 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, the image/histogram lin-log switches and the min/max spin
// boxes. See AGENT_INSTRUCTIONS.md: "the three-way freeze rule".
#include "SlsQtPlotCommon.h"
#include <QMetaObject>
#include <QPointer>
#include <QWidget>
#include <functional>
#include <vector>
class QComboBox;
class QDoubleSpinBox;
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.
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 ---------------------------------------------------
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;
protected:
void paintEvent(QPaintEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
private:
void windowFor(double clo, double chi, double &wlo, double &whi) const;
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;
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;
};
// Histogram strip + palette combo + image lin/log + histogram lin/log + min/max
// spin boxes. 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.
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);
SlsQtScaleHisto *histogramWidget() const;
bool isDragging() const; // strip drag in progress
// ---- test / programmatic hooks ---------------------------------------
// The values currently shown in the min/max spin boxes (1-decimal
// rounded). Stays frozen while the strip marker is dragged (R1).
void controlRange(double &lo, double &hi) const;
// Sets both spin boxes as if the user had typed them: this is the only
// path that pushes the colour range from the controls, so a test can
// trigger a "user edit" without synthesising spin-box events.
void setControlRange(double lo, double hi);
// Range last pushed to the view by a spin-box edit; false if no edit was
// pushed yet. Palette/log changes never update this (R2).
bool lastPushedRange(double &lo, double &hi) const;
private:
void attachView(SlsQtFastImage *view);
void detachView();
void updateHisto();
QPointer<SlsQtFastImage> m_view;
SlsQtScaleHisto *m_histo = nullptr;
QComboBox *m_paletteCombo = nullptr;
QComboBox *m_imageLogCombo = nullptr;
QComboBox *m_histoLogCombo = nullptr;
QDoubleSpinBox *m_loSpin = nullptr;
QDoubleSpinBox *m_hiSpin = nullptr;
int m_suppress = 0;
// R2: only a real edit of the min/max spin boxes 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;
};
} // namespace sls
File diff suppressed because it is too large. Load diff
@@ -1,99 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
/* TODO! short description */
#include "SlsQt1DZoomer.h"
#include "SlsQt1DPlot.h"
#include <iostream>
#include <qwt_plot.h>
#include <qwt_scale_div.h>
namespace sls {
void SlsQt1DZoomer::ResetZoomBase() {
SetZoomBase(x0, y0, x1 - x0,
y1 - y0); // for going between log and nonlog plots
}
void SlsQt1DZoomer::SetZoomBase(double xmin, double ymin, double x_width,
double y_width) {
if (xIsLog && xmin <= 0) {
double xmax = xmin + x_width;
xmin = firstXgt0 * 0.98;
if (xmax <= xmin)
x_width = firstXgt0;
else
x_width = xmax - xmin;
}
if (yIsLog && ymin <= 0) {
double ymax = ymin + y_width;
ymin = firstYgt0 * 0.98;
if (ymax <= ymin)
y_width = firstYgt0;
else
y_width = ymax - ymin;
}
if (plot()) {
if (xIsLog) {
double xmin_curr =
plot()->axisScaleDiv(QwtPlot::xBottom).lowerBound();
double xmax_curr =
plot()->axisScaleDiv(QwtPlot::xBottom).upperBound();
if (xmin_curr < xmin)
xmin_curr = xmin;
if (xmax_curr > xmin + x_width)
xmax_curr = xmin + x_width;
plot()->setAxisScale(QwtPlot::xBottom, xmin_curr, xmax_curr);
}
if (yIsLog) {
double ymin_curr =
plot()->axisScaleDiv(QwtPlot::yLeft).lowerBound();
double ymax_curr =
plot()->axisScaleDiv(QwtPlot::yLeft).upperBound();
if (ymin_curr < ymin)
ymin_curr = ymin;
if (ymax_curr > ymin + y_width)
ymax_curr = ymin + y_width;
plot()->setAxisScale(QwtPlot::yLeft, ymin_curr, ymax_curr);
}
plot()->replot();
}
setZoomBase(QRectF(xmin, ymin, x_width, y_width));
}
void SlsQt1DZoomer::SetZoomBase(SlsQtH1D *h) {
x0 = h->GetXMin() < 0 ? h->GetXMin() * 1.02 : h->GetXMin() / 1.02;
x1 = h->GetXMax() < 0 ? h->GetXMax() / 1.02 : h->GetXMax() * 1.02;
y0 = h->GetYMin() < 0 ? h->GetYMin() * 1.02 : h->GetYMin() / 1.02;
y1 = h->GetYMax() < 0 ? h->GetYMax() / 1.02 : h->GetYMax() * 1.02;
firstXgt0 = h->GetFirstXgtZero(); // for log plots
firstYgt0 = h->GetFirstYgtZero(); // for log plots
ResetZoomBase();
}
void SlsQt1DZoomer::ExtendZoomBase(SlsQtH1D *h) {
double h_x0 = h->GetXMin() < 0 ? h->GetXMin() * 1.02 : h->GetXMin() / 1.02;
double h_x1 = h->GetXMax() < 0 ? h->GetXMax() / 1.02 : h->GetXMax() * 1.02;
double h_y0 = h->GetYMin() < 0 ? h->GetYMin() * 1.02 : h->GetYMin() / 1.02;
double h_y1 = h->GetYMax() < 0 ? h->GetYMax() / 1.02 : h->GetYMax() * 1.02;
if (h_x0 < x0)
x0 = h_x0;
if (h_x1 > x1)
x1 = h_x1;
if (h_y0 < y0)
y0 = h_y0;
if (h_y1 > y1)
y1 = h_y1;
if (h->GetFirstXgtZero() < firstXgt0)
firstXgt0 = h->GetFirstXgtZero();
if (h->GetFirstYgtZero() < firstYgt0)
firstYgt0 = h->GetFirstYgtZero();
ResetZoomBase();
}
} // namespace sls
@@ -1,149 +1,230 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
/* TODO! short description */
// Copyright (C) 2026 Contributors to the SLS Detector Package
#include "SlsQt2DHist.h"
#include "sls/ansi.h"
#include <cmath>
#include <iostream>
using std::cout;
using std::endl;
#include <algorithm>
#include <cmath>
#include <cstring>
namespace sls {
SlsQt2DHist::SlsQt2DHist(int nbinsx, double xmin, double xmax, int nbinsy,
double ymin, double ymax, double *d, double zmin,
double zmax)
: QwtRasterData() {
x_min = 0;
x_max = 0;
y_min = 0;
y_max = 0;
interp = 0;
nx_array = ny_array = 0;
data = nullptr;
double zmax) {
SetData(nbinsx, xmin, xmax, nbinsy, ymin, ymax, d, zmin, zmax);
}
SlsQt2DHist::~SlsQt2DHist() { delete[] data; }
int SlsQt2DHist::GetBinIndex(int bx, int by) {
int b = bx * ny + by;
if (b < 0 || b >= nb) {
cout << "GetBinIndex:: Incorrect indicies bx and by returning overflow "
"bin;"
<< endl;
return nb;
}
return b;
}
int SlsQt2DHist::FindBinIndex(double x, double y) {
return GetBinIndex(int((x - x_min) / x_width), int((y - y_min) / y_width));
}
double SlsQt2DHist::GetBinValue(int bx, int by) {
return data[GetBinIndex(bx, by)];
}
void SlsQt2DHist::SetBinValue(int bx, int by, double v) {
z_mean_has_been_calculated = 0;
data[GetBinIndex(bx, by)] = v;
namespace {
// Bins are addressed with their lower edge; the ranges are descending/invalid
// only if a caller passes nonsense - fall back to a unit width so the
// conversions below never divide by zero.
double safeBinWidth(int nbins, double lo, double hi) {
if (nbins <= 0)
return 1.0;
const double w = (hi - lo) / nbins;
if (!std::isfinite(w) || w <= 0.0)
return 1.0;
return w;
}
} // namespace
void SlsQt2DHist::SetData(int nbinsx, double xmin, double xmax, int nbinsy,
double ymin, double ymax, double *d, double zmin,
double zmax) {
z_mean_has_been_calculated = 0;
if (xmax < xmin || ymax < ymin)
cout << "Warning input range invalid." << endl;
if (nbinsx < 1 || nbinsy < 1)
return; // invalid geometry: keep the previous data
x_width = (xmax - xmin) / nbinsx;
y_width = (ymax - ymin) / nbinsy;
z_mean_has_been_calculated = false;
if (x_min != xmin || x_max != xmax || y_min != ymin || y_max != ymax) {
x_min = xmin;
x_max = xmax;
y_min = ymin;
y_max = ymax;
setInterval(Qt::XAxis, QwtInterval(xmin, xmax));
setInterval(Qt::YAxis, QwtInterval(ymin, ymax));
}
x_min = xmin;
x_max = xmax;
y_min = ymin;
y_max = ymax;
x_width = safeBinWidth(nbinsx, xmin, xmax);
y_width = safeBinWidth(nbinsy, ymin, ymax);
if (nbinsx * nbinsy < 1) {
cout << "Exitting: SlsQt2DHist::SetData() number of bins must be "
"greater than zero."
<< endl;
exit(1);
}
if (nbinsx * nbinsy > nx_array * ny_array) {
delete[] data;
data = new double[nbinsx * nbinsy + 1]; // one for under/overflow bin
nx_array = nbinsx;
ny_array = nbinsy;
}
nx = nbinsx;
ny = nbinsy;
nb = nx * ny;
data[nb] = 0; // set over flow to zero
// one extra entry for the under/overflow bin; keep the previous allocation
// when the frame geometry is unchanged (the GUI feeds a frame every few ms)
const size_t needed = static_cast<size_t>(nb) + 1;
if (data.size() != needed)
data.assign(needed, 0.0);
data[static_cast<size_t>(nb)] = 0.0;
if (d) {
memcpy(data, d, nb * sizeof(double));
std::memcpy(data.data(), d, static_cast<size_t>(nb) * sizeof(double));
SetMinMax(zmin, zmax);
}
}
int SlsQt2DHist::GetBinIndex(int bx, int by) const {
if (bx < 0 || bx >= nx || by < 0 || by >= ny)
return nb; // under/overflow bin
return bx + by * nx; // x fastest, the layout of the image copy
}
int SlsQt2DHist::FindBinIndex(double x, double y) const {
if (!std::isfinite(x) || !std::isfinite(y))
return nb;
const int bx = static_cast<int>(std::floor((x - x_min) / x_width));
const int by = static_cast<int>(std::floor((y - y_min) / y_width));
return GetBinIndex(bx, by);
}
double SlsQt2DHist::GetBinValue(int bx, int by) const {
return data[static_cast<size_t>(GetBinIndex(bx, by))];
}
void SlsQt2DHist::SetBinValue(int bx, int by, double v) {
const int index = GetBinIndex(bx, by);
if (index >= nb)
return; // never modify the under/overflow bin through this API
z_mean_has_been_calculated = false;
data[static_cast<size_t>(index)] = v;
}
void SlsQt2DHist::SetMinMax(double zmin, double zmax) {
/* if(zmin<zmax){ edited out to test*/
if (zmax != -1) {
if (zmax != -1.0) {
z_min = zmin;
z_max = zmax;
} else {
z_mean_has_been_calculated = 1;
z_min = data[0];
z_mean = 0;
z_max = data[0];
for (int i = 0; i < nb; i++) {
if (data[i] < z_min)
z_min = data[i];
if (data[i] > z_max)
z_max = data[i];
z_mean += data[i];
}
z_mean /= nb;
if (z_min > 0)
z_min /= 1.02;
else
z_min *= 1.02;
if (z_max > 0)
z_max *= 1.02;
else
z_max /= 1.02;
z_mean_has_been_calculated = false;
return;
}
setInterval(Qt::ZAxis, QwtInterval(z_min, z_max));
z_mean_has_been_calculated = true;
z_min = 0.0;
z_max = 1.0;
z_mean = 0.0;
if (nb < 1 || data.empty())
return;
// Skip non-finite bins: a single NaN used to poison the whole auto range
// (min/max became NaN, the colour LUT index degenerated) and an Inf made
// it unbounded. The mean is taken over the finite bins only.
bool haveFinite = false;
double sum = 0.0;
int finiteCount = 0;
for (int i = 0; i < nb; i++) {
const double v = data[static_cast<size_t>(i)];
if (!std::isfinite(v))
continue;
if (!haveFinite) {
z_min = v;
z_max = v;
haveFinite = true;
} else {
if (v < z_min)
z_min = v;
if (v > z_max)
z_max = v;
}
sum += v;
finiteCount++;
}
if (!haveFinite) {
// No usable value at all: keep a valid, harmless range so the colour
// mapping and the scale-panel spin boxes stay finite.
z_min = 0.0;
z_max = 1.0;
z_mean = 0.0;
return;
}
z_mean = sum / finiteCount;
// Keep a tiny margin so the extreme bins are not clipped by rounding.
// The padding must always be OUTWARD:
// - low end: divide a positive value / multiply a negative one;
// - 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).
if (z_min > 0)
z_min /= 1.02;
else
z_min -= 0.02 * std::abs(z_min);
if (z_max > 0)
z_max *= 1.02;
else
z_max += 0.02 * std::abs(z_max);
}
double SlsQt2DHist::GetMean() {
if (!z_mean_has_been_calculated) {
z_mean_has_been_calculated = 1;
z_mean = 0;
for (int i = 0; i < nb; i++)
z_mean += data[i];
z_mean /= nb;
z_mean_has_been_calculated = true;
z_mean = 0.0;
double sum = 0.0;
int finiteCount = 0;
for (int i = 0; i < nb; i++) {
const double v = data[static_cast<size_t>(i)];
if (!std::isfinite(v))
continue;
sum += v;
finiteCount++;
}
z_mean = (finiteCount > 0) ? sum / finiteCount : 0.0;
}
return z_mean;
}
double SlsQt2DHist::SetMinimumToFirstGreaterThanZero() {
z_min = fabs(z_max) + 1;
double first = std::fabs(z_max) + 1.0;
if (!std::isfinite(first) || first <= 0.0)
first = 1.0;
for (int i = 0; i < nb; i++) {
if (data[i] > 0 && data[i] < z_min)
z_min = data[i];
const double v = data[static_cast<size_t>(i)];
if (v > 0.0 && v < first)
first = v;
}
setInterval(Qt::ZAxis, QwtInterval(z_min, z_max));
z_min = first;
return z_min;
}
} // namespace sls
double SlsQt2DHist::value(double x, double y) const {
if (nb < 1 || data.empty())
return 0.0;
if (!std::isfinite(x) || !std::isfinite(y))
return data[static_cast<size_t>(nb)];
if (interp && nx >= 2 && ny >= 2) {
// Continuous bin-centre coordinates: bin centre i is at i.
const double cu = (x - x_min) / x_width - 0.5;
const double cv = (y - y_min) / y_width - 0.5;
if (!std::isfinite(cu) || !std::isfinite(cv))
return data[static_cast<size_t>(nb)];
// Outside the grid the border value is extended (no extrapolation).
const double u = std::min(std::max(cu, 0.0), double(nx - 1));
const double v = std::min(std::max(cv, 0.0), double(ny - 1));
int i0 = static_cast<int>(std::floor(u));
int j0 = static_cast<int>(std::floor(v));
i0 = std::min(std::max(i0, 0), nx - 2);
j0 = std::min(std::max(j0, 0), ny - 2);
const double fx = u - i0;
const double fy = v - j0;
const size_t i1 = static_cast<size_t>(i0 + 1);
const size_t j1 = static_cast<size_t>(j0 + 1);
const size_t i0s = static_cast<size_t>(i0);
const size_t j0s = static_cast<size_t>(j0);
const double v00 = data[i0s + j0s * nx];
const double v10 = data[i1 + j0s * nx];
const double v01 = data[i0s + j1 * nx];
const double v11 = data[i1 + j1 * nx];
return (1.0 - fx) * (1.0 - fy) * v00 + fx * (1.0 - fy) * v10 +
(1.0 - fx) * fy * v01 + fx * fy * v11;
}
// Box sampling: the value of the bin containing (x, y).
const double bx = (x - x_min) / x_width;
const double by = (y - y_min) / y_width;
if (!std::isfinite(bx) || !std::isfinite(by))
return data[static_cast<size_t>(nb)];
const int ix = static_cast<int>(std::floor(bx));
const int iy = static_cast<int>(std::floor(by));
if (ix < 0 || ix >= nx || iy < 0 || iy >= ny)
return data[static_cast<size_t>(nb)];
return data[static_cast<size_t>(ix + iy * nx)];
}
} // namespace sls
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,500 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2026 Contributors to the SLS Detector Package
#include "SlsQtPlotCommon.h"
#include <algorithm>
namespace sls {
namespace plot {
namespace {
// Piecewise-linear colour definition: up to 24 anchor stops plus an optional
// gamma for the grey ramps (nstops == 0).
struct PaletteDef {
int nstops = 0;
double stops[24] = {0, 0, 0, 0, 0};
double r[24] = {0, 0, 0, 0, 0};
double g[24] = {0, 0, 0, 0, 0};
double b[24] = {0, 0, 0, 0, 0};
double gamma = 1.0;
};
const PaletteDef &paletteDef(Palette p) {
// "False" colour table, as used by the original display.
static const PaletteDef color = [] {
PaletteDef d;
d.nstops = 5;
d.stops[0] = 0.00; d.stops[1] = 0.34; d.stops[2] = 0.61;
d.stops[3] = 0.84; d.stops[4] = 1.00;
d.r[0] = 0.00; d.r[1] = 0.00; d.r[2] = 0.87; d.r[3] = 1.00;
d.r[4] = 0.51;
d.g[0] = 0.00; d.g[1] = 0.81; d.g[2] = 1.00; d.g[3] = 0.20;
d.g[4] = 0.00;
d.b[0] = 0.51; d.b[1] = 1.00; d.b[2] = 0.12; d.b[3] = 0.00;
d.b[4] = 0.00;
return d;
}();
static const PaletteDef bw1 = [] {
PaletteDef d;
d.gamma = 1.1111; // same exponent the original 'b' button used
return d;
}();
static const PaletteDef bw2 = [] {
PaletteDef d;
d.gamma = 0.9; // same exponent the original 'B' button used
return d;
}();
static const PaletteDef turbo = [] {
PaletteDef d;
d.nstops = 15;
for (int i = 0; i < 15; i++)
d.stops[i] = i / 14.0;
const double r[15] = {0.1882, 0.2549, 0.2745, 0.2235, 0.1059,
0.1412, 0.3804, 0.6431, 0.8196, 0.9529,
0.9961, 0.9529, 0.8510, 0.6941, 0.4784};
const double g[15] = {0.0706, 0.2706, 0.4588, 0.6353, 0.8118,
0.9255, 0.9882, 0.9882, 0.9098, 0.7765,
0.6078, 0.3882, 0.2196, 0.0980, 0.0157};
const double b[15] = {0.2314, 0.6706, 0.9294, 0.9882, 0.8314,
0.6510, 0.4235, 0.2314, 0.2039, 0.2275,
0.1765, 0.0824, 0.0235, 0.0039, 0.0078};
for (int i = 0; i < 15; i++) {
d.r[i] = r[i];
d.g[i] = g[i];
d.b[i] = b[i];
}
return d;
}();
static const PaletteDef viridis = [] {
PaletteDef d;
d.nstops = 10;
for (int i = 0; i < 10; i++)
d.stops[i] = i / 9.0;
const double r[10] = {0.2667, 0.2824, 0.2431, 0.1922, 0.1490,
0.1216, 0.2078, 0.4314, 0.7098, 0.9922};
const double g[10] = {0.0039, 0.1569, 0.2863, 0.4078, 0.5098,
0.6196, 0.7176, 0.8078, 0.8706, 0.9059};
const double b[10] = {0.3294, 0.4706, 0.5373, 0.5569, 0.5569,
0.5373, 0.4745, 0.3451, 0.1686, 0.1451};
for (int i = 0; i < 10; i++) {
d.r[i] = r[i];
d.g[i] = g[i];
d.b[i] = b[i];
}
return d;
}();
static const PaletteDef plasma = [] {
PaletteDef d;
d.nstops = 10;
for (int i = 0; i < 10; i++)
d.stops[i] = i / 9.0;
const double r[10] = {0.0510, 0.2745, 0.4471, 0.6118, 0.7412,
0.8471, 0.9294, 0.9843, 0.9922, 0.9412};
const double g[10] = {0.0314, 0.0118, 0.0039, 0.0902, 0.2157,
0.3412, 0.4745, 0.6235, 0.7922, 0.9765};
const double b[10] = {0.5294, 0.6235, 0.6588, 0.6196, 0.5255,
0.4196, 0.3255, 0.2275, 0.1490, 0.1294};
for (int i = 0; i < 10; i++) {
d.r[i] = r[i];
d.g[i] = g[i];
d.b[i] = b[i];
}
return d;
}();
static const PaletteDef inferno = [] {
PaletteDef d;
d.nstops = 10;
for (int i = 0; i < 10; i++)
d.stops[i] = i / 9.0;
const double r[10] = {0.0000, 0.1059, 0.2902, 0.4706, 0.6471,
0.8118, 0.9294, 0.9843, 0.9686, 0.9882};
const double g[10] = {0.0000, 0.0471, 0.0471, 0.1098, 0.1725,
0.2667, 0.4118, 0.6078, 0.8196, 1.0000};
const double b[10] = {0.0157, 0.2549, 0.4196, 0.4275, 0.3765,
0.2745, 0.1451, 0.0235, 0.2392, 0.6431};
for (int i = 0; i < 10; i++) {
d.r[i] = r[i];
d.g[i] = g[i];
d.b[i] = b[i];
}
return d;
}();
static const PaletteDef magma = [] {
PaletteDef d;
d.nstops = 10;
for (int i = 0; i < 10; i++)
d.stops[i] = i / 9.0;
const double r[10] = {0.0000, 0.0941, 0.2667, 0.4471, 0.6196,
0.8039, 0.9451, 0.9922, 0.9961, 0.9882};
const double g[10] = {0.0000, 0.0588, 0.0588, 0.1216, 0.1843,
0.2510, 0.3765, 0.5882, 0.7922, 0.9922};
const double b[10] = {0.0157, 0.2392, 0.4627, 0.5059, 0.4980,
0.4431, 0.3647, 0.4078, 0.5529, 0.7490};
for (int i = 0; i < 10; i++) {
d.r[i] = r[i];
d.g[i] = g[i];
d.b[i] = b[i];
}
return d;
}();
static const PaletteDef cividis = [] {
PaletteDef d;
d.nstops = 10;
for (int i = 0; i < 10; i++)
d.stops[i] = i / 9.0;
const double r[10] = {0.0000, 0.0706, 0.2314, 0.3412, 0.4392,
0.5412, 0.6471, 0.7647, 0.8824, 0.9961};
const double g[10] = {0.1333, 0.2078, 0.2863, 0.3647, 0.4431,
0.5255, 0.6118, 0.7020, 0.8000, 0.9098};
const double b[10] = {0.3059, 0.4392, 0.4235, 0.4275, 0.4510,
0.4706, 0.4549, 0.4118, 0.3333, 0.2196};
for (int i = 0; i < 10; i++) {
d.r[i] = r[i];
d.g[i] = g[i];
d.b[i] = b[i];
}
return d;
}();
static const PaletteDef hot = [] {
PaletteDef d;
d.nstops = 4;
d.stops[0] = 0.0000; d.stops[1] = 0.3650; d.stops[2] = 0.7460;
d.stops[3] = 1.0000;
d.r[0] = 0.0000; d.r[1] = 1.0000; d.r[2] = 1.0000; d.r[3] = 1.0000;
d.g[0] = 0.0000; d.g[1] = 0.0000; d.g[2] = 1.0000; d.g[3] = 1.0000;
d.b[0] = 0.0000; d.b[1] = 0.0000; d.b[2] = 0.0000; d.b[3] = 1.0000;
return d;
}();
static const PaletteDef gray = [] {
PaletteDef d;
d.nstops = 2;
d.stops[0] = 0.0000;
d.stops[1] = 1.0000;
d.r[0] = 0.0000; d.r[1] = 1.0000;
d.g[0] = 0.0000; d.g[1] = 1.0000;
d.b[0] = 0.0000; d.b[1] = 1.0000;
return d;
}();
static const PaletteDef gray_r = [] {
PaletteDef d;
d.nstops = 2;
d.stops[0] = 0.0000;
d.stops[1] = 1.0000;
d.r[0] = 1.0000; d.r[1] = 0.0000;
d.g[0] = 1.0000; d.g[1] = 0.0000;
d.b[0] = 1.0000; d.b[1] = 0.0000;
return d;
}();
static const PaletteDef coolwarm = [] {
PaletteDef d;
d.nstops = 3;
d.stops[0] = 0.0000; d.stops[1] = 0.5000; d.stops[2] = 1.0000;
d.r[0] = 0.2314; d.r[1] = 0.8667; d.r[2] = 0.7059;
d.g[0] = 0.2980; d.g[1] = 0.8667; d.g[2] = 0.0157;
d.b[0] = 0.7529; d.b[1] = 0.8667; d.b[2] = 0.1490;
return d;
}();
static const PaletteDef bwr = [] {
PaletteDef d;
d.nstops = 3;
d.stops[0] = 0.0000; d.stops[1] = 0.5000; d.stops[2] = 1.0000;
d.r[0] = 0.0000; d.r[1] = 1.0000; d.r[2] = 1.0000;
d.g[0] = 0.0000; d.g[1] = 1.0000; d.g[2] = 0.0000;
d.b[0] = 1.0000; d.b[1] = 1.0000; d.b[2] = 0.0000;
return d;
}();
static const PaletteDef seismic = [] {
PaletteDef d;
d.nstops = 5;
d.stops[0] = 0.0000; d.stops[1] = 0.2500; d.stops[2] = 0.5000;
d.stops[3] = 0.7500; d.stops[4] = 1.0000;
d.r[0] = 0.0000; d.r[1] = 0.0000; d.r[2] = 1.0000; d.r[3] = 1.0000;
d.r[4] = 0.5020;
d.g[0] = 0.0000; d.g[1] = 0.0000; d.g[2] = 1.0000; d.g[3] = 0.0000;
d.g[4] = 0.0000;
d.b[0] = 0.3020; d.b[1] = 1.0000; d.b[2] = 1.0000; d.b[3] = 0.0000;
d.b[4] = 0.0000;
return d;
}();
static const PaletteDef rdbu = [] {
PaletteDef d;
d.nstops = 9;
for (int i = 0; i < 9; i++)
d.stops[i] = i / 8.0;
const double r[9] = {0.6980, 0.8392, 0.9569, 0.9922, 0.9686,
0.8196, 0.5725, 0.2627, 0.1294};
const double g[9] = {0.0941, 0.3765, 0.6471, 0.8588, 0.9686,
0.8980, 0.7725, 0.5765, 0.4000};
const double b[9] = {0.1686, 0.3020, 0.5098, 0.7804, 0.9686,
0.9412, 0.8706, 0.7647, 0.6745};
for (int i = 0; i < 9; i++) {
d.r[i] = r[i];
d.g[i] = g[i];
d.b[i] = b[i];
}
return d;
}();
static const PaletteDef ylgnbu = [] {
PaletteDef d;
d.nstops = 9;
for (int i = 0; i < 9; i++)
d.stops[i] = i / 8.0;
const double r[9] = {0.0314, 0.1451, 0.1333, 0.1137, 0.2549,
0.4980, 0.7804, 0.9294, 1.0000};
const double g[9] = {0.1137, 0.2039, 0.3686, 0.5686, 0.7137,
0.8039, 0.9137, 0.9725, 1.0000};
const double b[9] = {0.3451, 0.5804, 0.6588, 0.7529, 0.7686,
0.7333, 0.7059, 0.6941, 0.8510};
for (int i = 0; i < 9; i++) {
d.r[i] = r[i];
d.g[i] = g[i];
d.b[i] = b[i];
}
return d;
}();
static const PaletteDef sunset = [] {
PaletteDef d;
d.nstops = 11;
for (int i = 0; i < 11; i++)
d.stops[i] = i / 10.0;
const double r[11] = {0.2118, 0.2902, 0.4314, 0.5961, 0.7608, 0.9176,
0.9961, 0.9922, 0.9647, 0.8667, 0.6471};
const double g[11] = {0.2941, 0.4824, 0.6510, 0.7922, 0.8941, 0.9255,
0.8549, 0.7020, 0.4941, 0.2392, 0.0000};
const double b[11] = {0.6039, 0.7176, 0.8039, 0.8824, 0.9373, 0.8000,
0.5451, 0.4000, 0.2941, 0.1765, 0.1490};
for (int i = 0; i < 11; i++) {
d.r[i] = r[i];
d.g[i] = g[i];
d.b[i] = b[i];
}
return d;
}();
// The gain image holds one of four numbers (the Jungfrau gain bits). These
// are deliberately desaturated so a large flat map does not glare.
static const PaletteDef gain4 = [] {
PaletteDef d;
d.nstops = 4;
d.stops[0] = 0.0000; d.stops[1] = 0.3333; d.stops[2] = 0.6667;
d.stops[3] = 1.0000;
d.r[0] = 0.3725; d.r[1] = 0.4353; d.r[2] = 0.7961; d.r[3] = 0.6902;
d.g[0] = 0.5020; d.g[1] = 0.6275; d.g[2] = 0.7412; d.g[3] = 0.4157;
d.b[0] = 0.6588; d.b[1] = 0.4353; d.b[2] = 0.4157; d.b[3] = 0.3882;
return d;
}();
switch (p) {
case Palette::BW1:
return bw1;
case Palette::BW2:
return bw2;
case Palette::Turbo:
return turbo;
case Palette::Viridis:
return viridis;
case Palette::Plasma:
return plasma;
case Palette::Inferno:
return inferno;
case Palette::Magma:
return magma;
case Palette::Cividis:
return cividis;
case Palette::Hot:
return hot;
case Palette::Gray:
return gray;
case Palette::Gray_r:
return gray_r;
case Palette::Coolwarm:
return coolwarm;
case Palette::Bwr:
return bwr;
case Palette::Seismic:
return seismic;
case Palette::RdBu:
return rdbu;
case Palette::YlGnBu:
return ylgnbu;
case Palette::Sunset:
return sunset;
case Palette::Gain4:
return gain4;
case Palette::Color:
default:
return color;
}
}
// 256-entry lookup table sampled from exactly the same definition.
void buildLut(const PaletteDef &d, QRgb *out) {
for (int i = 0; i < 256; i++) {
const double v = i / 255.0;
double rr, gg, bb;
if (d.nstops <= 0) {
const double c = std::pow(v, d.gamma);
rr = gg = bb = c;
} else {
int k = 0;
while (k < d.nstops - 2 && v > d.stops[k + 1])
k++;
const double span = d.stops[k + 1] - d.stops[k];
const double t = (span > 0) ? (v - d.stops[k]) / span : 0.0;
const double tc = (t < 0) ? 0.0 : (t > 1 ? 1.0 : t);
rr = d.r[k] + (d.r[k + 1] - d.r[k]) * tc;
gg = d.g[k] + (d.g[k + 1] - d.g[k]) * tc;
bb = d.b[k] + (d.b[k + 1] - d.b[k]) * tc;
}
out[i] = qRgb(static_cast<int>(rr * 255.0 + 0.5),
static_cast<int>(gg * 255.0 + 0.5),
static_cast<int>(bb * 255.0 + 0.5));
}
}
constexpr int kNumPalettes = int(Palette::Gain4) + 1;
// Built once, on first use; const afterwards, so safe from any thread.
const QRgb *paletteTables() {
static const auto tables = [] {
auto *t = new QRgb[kNumPalettes][256];
for (int i = 0; i < kNumPalettes; i++)
buildLut(paletteDef(static_cast<Palette>(i)), t[i]);
return t;
}();
return &tables[0][0];
}
} // namespace
const QRgb *paletteLut(Palette p) {
const int i = int(p);
if (i < 0 || i >= kNumPalettes)
return paletteTables();
return paletteTables() + size_t(i) * 256;
}
const char *paletteName(Palette p) {
switch (p) {
case Palette::Gain4:
return "gain 0..3 (fixed)";
case Palette::Color:
return "Col (jet)";
case Palette::BW1:
return "BW grey 1";
case Palette::BW2:
return "BW grey 2";
case Palette::Turbo:
return "Turbo";
case Palette::Viridis:
return "Viridis";
case Palette::Plasma:
return "Plasma";
case Palette::Inferno:
return "Inferno";
case Palette::Magma:
return "Magma";
case Palette::Cividis:
return "Cividis (colorblind)";
case Palette::Hot:
return "Hot";
case Palette::Gray:
return "Grey (linear)";
case Palette::Gray_r:
return "Grey reversed";
case Palette::Coolwarm:
return "Coolwarm (diverging)";
case Palette::Bwr:
return "BWR (diverging)";
case Palette::Seismic:
return "Seismic (diverging)";
case Palette::RdBu:
return "RdBu (diverging)";
case Palette::YlGnBu:
return "YlGnBu (Brewer)";
case Palette::Sunset:
return "Sunset (Tol)";
}
return "?";
}
int paletteCount() { return int(Palette::Gain4); }
double niceStep(double span, int maxTicks) {
if (!(span > 0.0) || !std::isfinite(span))
return 1.0;
if (maxTicks < 1)
maxTicks = 1;
const double raw = span / double(maxTicks);
const double mag = std::pow(10.0, std::floor(std::log10(raw)));
const double norm = raw / mag;
double mult = 10.0;
if (norm <= 1.0)
mult = 1.0;
else if (norm <= 2.0)
mult = 2.0;
else if (norm <= 5.0)
mult = 5.0;
return mult * mag;
}
std::vector<double> computeLinearTicks(double lo, double hi, int maxTicks) {
std::vector<double> out;
if (!std::isfinite(lo) || !std::isfinite(hi) || !(hi > lo))
return out;
if (maxTicks < 1)
maxTicks = 1;
const double step = niceStep(hi - lo, maxTicks);
const double first = std::ceil(lo / step - 1e-9);
for (long long k = static_cast<long long>(first);; ++k) {
const double v = double(k) * step;
if (v > hi + step * 1e-9)
break;
out.push_back(std::abs(v) < step * 1e-9 ? 0.0 : v);
if (static_cast<int>(out.size()) > maxTicks + 1)
break;
}
return out;
}
QString formatTick(double v, double step) {
if (!std::isfinite(v))
return QStringLiteral("?");
if (!(step > 0.0) || !std::isfinite(step))
step = 1.0;
if (std::abs(v) < step * 1e-9)
v = 0.0; // avoid "-0"
const double a = std::abs(v);
if (a >= 1e6 || (a > 0.0 && a < 1e-3)) {
QString s = QString::number(v, 'g', 4);
return s;
}
const int dec =
std::max(0, static_cast<int>(std::ceil(-std::log10(step) - 1e-9)));
QString s = QString::number(v, 'f', dec);
if (s.contains(QLatin1Char('.'))) {
while (s.endsWith(QLatin1Char('0')))
s.chop(1);
if (s.endsWith(QLatin1Char('.')))
s.chop(1);
}
return s;
}
PlotTheme::PlotTheme() { tickFont.setPixelSize(10); }
QRect plotRectFor(const QSize &widgetSize, const PlotTheme &theme) {
int x0 = theme.leftMargin;
int y0 = theme.topMargin;
int x1 = widgetSize.width() - theme.rightMargin;
int y1 = widgetSize.height() - theme.bottomMargin;
if (x1 - x0 < 10)
x1 = x0 + 10;
if (y1 - y0 < 10)
y1 = y0 + 10;
return QRect(x0, y0, x1 - x0, y1 - y0);
}
} // namespace plot
} // namespace sls
@@ -0,0 +1,552 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2026 Contributors to the SLS Detector Package
#include "SlsQtScalePanel.h"
#include "SlsQtFastImage.h"
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QMouseEvent>
#include <QObject>
#include <QPainter>
#include <QVBoxLayout>
#include <algorithm>
#include <cmath>
namespace sls {
namespace {
constexpr int kHistoHeight = 38;
constexpr int kPanelHeight = kHistoHeight + 40; // strip + one compact row
} // namespace
// ---------------------------------------------------------------------------
// SlsQtScaleHisto
// ---------------------------------------------------------------------------
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."));
}
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)
return;
m_hist = h;
m_dlo = dlo;
m_dhi = dhi;
m_clo = clo;
m_chi = chi;
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_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;
}
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;
}
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 *) {
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; };
// 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());
p.setPen(Qt::NoPen);
p.setBrush(QColor(120, 190, 255));
for (size_t i = 0; i < hv->size(); i++) {
if ((*hv)[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))));
}
}
// 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));
}
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();
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));
}
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
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);
}
void SlsQtScaleHisto::mouseMoveEvent(QMouseEvent *e) {
if (m_dragMin < 0)
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
}
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;
}
// ---------------------------------------------------------------------------
// SlsQtScalePanel
// ---------------------------------------------------------------------------
SlsQtScalePanel::SlsQtScalePanel(SlsQtFastImage *view, QWidget *parent)
: QWidget(parent) {
auto *col = new QVBoxLayout(this);
col->setContentsMargins(4, 2, 4, 4);
col->setSpacing(3);
m_histo = new SlsQtScaleHisto(this);
col->addWidget(m_histo);
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_loSpin = new QDoubleSpinBox(this);
m_hiSpin = new QDoubleSpinBox(this);
for (QDoubleSpinBox *b : {m_loSpin, m_hiSpin}) {
b->setRange(-1e9, 1e9);
b->setDecimals(1);
b->setSingleStep(1.0);
b->setKeyboardTracking(false);
b->setFixedWidth(84);
}
m_paletteCombo->setMinimumContentsLength(12);
row->addWidget(new QLabel(QStringLiteral("palette:"), this));
row->addWidget(m_paletteCombo);
row->addWidget(new QLabel(QStringLiteral("image"), this));
row->addWidget(m_imageLogCombo);
row->addWidget(new QLabel(QStringLiteral("histo"), this));
row->addWidget(m_histoLogCombo);
row->addWidget(new QLabel(QStringLiteral("min"), this));
row->addWidget(m_loSpin);
row->addWidget(new QLabel(QStringLiteral("max"), this));
row->addWidget(m_hiSpin);
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(); });
// Only a real edit of the spin boxes may push the colour range; values set
// by refresh() happen under m_suppress and never mark an edit (R2).
connect(m_loSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
[this](double) {
if (!m_suppress)
m_rangeEdited = true;
push();
});
connect(m_hiSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
[this](double) {
if (!m_suppress)
m_rangeEdited = true;
push();
});
m_histo->onRangeChanged = [this](double a, double b) {
if (m_suppress || !m_view)
return;
m_view->setColorRange(a, b);
m_suppress++;
m_loSpin->setValue(a);
m_hiSpin->setValue(b);
m_suppress--;
refresh();
};
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);
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 min/max spin boxes (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);
if (m_loSpin)
m_loSpin->setValue(a);
if (m_hiSpin)
m_hiSpin->setValue(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 when the min/max spin boxes were really
// edited. The spins show 1-decimal values, while the automatic z range
// computed by SlsQt2DPlot is not rounded; pushing the spins on a palette or
// log change would perturb that range and (via onColorRangeChanged) pin
// the 2D panel override forever. A strip-marker drag applies its range
// directly in the onRangeChanged handler, not here.
if (m_rangeEdited) {
m_rangeEdited = false;
double a = m_loSpin ? m_loSpin->value() : 0.0;
double b = m_hiSpin ? m_hiSpin->value() : 1.0;
if (!(b > a)) {
b = a + 1.0;
m_suppress++;
if (m_hiSpin)
m_hiSpin->setValue(b);
m_suppress--;
}
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_loSpin ? m_loSpin->value() : 0.0;
hi = m_hiSpin ? m_hiSpin->value() : 1.0;
}
void SlsQtScalePanel::setControlRange(double lo, double hi) {
// Mimic the operator typing both ends: programmatic setValue() calls are
// suppressed (so they do not push individually), then one edit is pushed.
m_suppress++;
if (m_loSpin)
m_loSpin->setValue(lo);
if (m_hiSpin)
m_hiSpin->setValue(hi);
m_suppress--;
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();
}
} // namespace sls
-1
View File
@@ -9,7 +9,6 @@
#include <QFileDialog>
#include <QImage>
#include <QPainter>
#include <qwt_text.h>
namespace sls {
+1 -1
View File
@@ -19,7 +19,7 @@ void qDacWidget::SetupWidgetWindow(std::string name) {
if (isDac) {
spinDac->setDecimals(0);
} else {
spinDac->setSuffix(0x00b0 + QString("C"));
spinDac->setSuffix(QString(QChar(0x00B0)) + QString("C"));
spinDac->setReadOnly(true);
lblDacmV->setMinimumWidth(0);
lblDacmV->setMaximumWidth(0);
+16 -16
View File
@@ -13,7 +13,6 @@
#include <QPainter>
#include <QResizeEvent>
#include <QtConcurrent/QtConcurrentRun>
#include <qwt_scale_engine.h>
namespace sls {
@@ -150,13 +149,13 @@ void qDrawPlot::SetupPlots() {
gainhist1d->SetLineColor(0);
gainhist1d->setStyleLinesorDots(isLines);
gainhist1d->setSymbolMarkers(isMarkers);
gainhist1d->setItemAttribute(QwtPlotItem::Legend, false);
gainhist1d->setLegendVisible(false);
// setup 1d gain plot
gainplot1d = new SlsQt1DPlot(boxPlot, true);
gainhist1d->Attach(gainplot1d);
gainplot1d->hide();
connect(plot1d, SIGNAL(PlotZoomedSignal(const QRectF &)), this,
SLOT(Zoom1DGainPlot(const QRectF &)));
connect(plot1d, &SlsQt1DPlot::PlotZoomedSignal, this,
&qDrawPlot::Zoom1DGainPlot);
// setup 2d data
@@ -193,8 +192,8 @@ void qDrawPlot::SetupPlots() {
nPixelsY - 0.5, gainData);
gainplot2d->Update();
gainplot2d->hide();
connect(plot2d, SIGNAL(PlotZoomedSignal(const QRectF &)), this,
SLOT(Zoom2DGainPlot(const QRectF &)));
connect(plot2d, &SlsQt2DPlot::PlotZoomedSignal, this,
&qDrawPlot::Zoom2DGainPlot);
// layout of plots
int ratio = qDefs::DATA_GAIN_PLOT_RATIO - 1;
@@ -486,7 +485,7 @@ void qDrawPlot::ClonePlot() {
if (is1d) {
LOG(logDEBUG) << "Cloning 1D Image";
cloneplot1D = new SlsQt1DPlot();
cloneplot1D->SetTitle(plot1d->title().text());
cloneplot1D->SetTitle(indexTitle);
cloneplot1D->SetXTitle(xTitle1d);
cloneplot1D->SetYTitle(yTitle1d);
QVector<SlsQtH1D *> cloneplotHists1D;
@@ -495,7 +494,7 @@ void qDrawPlot::ClonePlot() {
h->SetLineColor(iHist);
h->setStyleLinesorDots(isLines);
h->setSymbolMarkers(isMarkers);
h->setItemAttribute(QwtPlotItem::Legend, false);
h->setLegendVisible(false);
cloneplotHists1D.append(h);
h->Attach(cloneplot1D);
}
@@ -504,16 +503,16 @@ void qDrawPlot::ClonePlot() {
h->SetLineColor(0);
h->setStyleLinesorDots(isLines);
h->setSymbolMarkers(isMarkers);
h->setItemAttribute(QwtPlotItem::Legend, false);
h->setLegendVisible(false);
clonegainplot1D = new SlsQt1DPlot(NULL, true);
h->Attach(clonegainplot1D);
connect(cloneplot1D, SIGNAL(PlotZoomedSignal(const QRectF &)),
clonegainplot1D, SLOT(SetZoomX(const QRectF &)));
connect(cloneplot1D, &SlsQt1DPlot::PlotZoomedSignal,
clonegainplot1D, &SlsQt1DPlot::SetZoomX);
}
} else {
LOG(logDEBUG) << "Cloning 2D Image";
cloneplot2D = new SlsQt2DPlot();
cloneplot2D->setTitle(plot2d->title().text());
cloneplot2D->setTitle(plot2d->title());
cloneplot2D->SetXTitle(xTitle2d);
cloneplot2D->SetYTitle(yTitle2d);
cloneplot2D->SetZTitle(zTitle2d);
@@ -525,8 +524,9 @@ void qDrawPlot::ClonePlot() {
clonegainplot2D = new SlsQt2DPlot(NULL, true);
clonegainplot2D->SetData(nPixelsX, -0.5, nPixelsX - 0.5, nPixelsY,
-0.5, nPixelsY - 0.5, gainData);
connect(cloneplot2D, SIGNAL(PlotZoomedSignal(const QRectF &)),
clonegainplot2D, SLOT(SetZoom(const QRectF &)));
connect(cloneplot2D, &SlsQt2DPlot::PlotZoomedSignal,
clonegainplot2D,
qOverload<const QRectF &>(&SlsQt2DPlot::SetZoom));
}
}
@@ -545,7 +545,7 @@ void qDrawPlot::SavePlot() {
render(&painter);
QString fName = fileSavePath + QString('/') + fileSaveName + QString('_') +
(is1d ? plot1d->title().text() : plot2d->title().text()) +
(is1d ? indexTitle : plot2d->title()) +
QString('_') + QString("%1").arg(currentAcqIndex) +
QString(".png");
@@ -626,7 +626,7 @@ void qDrawPlot::StartAcquisition() {
xyRangeChanged = true;
}
QtConcurrent::run(this, &qDrawPlot::AcquireThread);
(void)QtConcurrent::run([this] { AcquireThread(); });
LOG(logDEBUG) << "End of Starting Acquisition in qDrawPlot";
}
+6 -6
View File
@@ -79,8 +79,8 @@ void qTabDataOutput::Initialization() {
if (chkRate->isEnabled()) {
connect(chkRate, SIGNAL(toggled(bool)), this,
SLOT(EnableRateCorrection()));
connect(btnGroupRate, SIGNAL(buttonClicked(int)), this,
SLOT(SetRateCorrection()));
connect(btnGroupRate, &QButtonGroup::idClicked, this,
&qTabDataOutput::SetRateCorrection);
connect(spinCustomDeadTime, SIGNAL(valueChanged(int)), this,
SLOT(SetRateCorrection()));
}
@@ -309,8 +309,8 @@ void qTabDataOutput::GetRateCorrection() {
LOG(logDEBUG) << "Getting Rate Correction";
disconnect(chkRate, SIGNAL(toggled(bool)), this,
SLOT(EnableRateCorrection()));
disconnect(btnGroupRate, SIGNAL(buttonClicked(int)), this,
SLOT(SetRateCorrection()));
disconnect(btnGroupRate, &QButtonGroup::idClicked, this,
&qTabDataOutput::SetRateCorrection);
disconnect(spinCustomDeadTime, SIGNAL(valueChanged(int)), this,
SLOT(SetRateCorrection()));
try {
@@ -326,8 +326,8 @@ void qTabDataOutput::GetRateCorrection() {
CATCH_DISPLAY("Could not get rate correction.",
"qTabDataOutput::GetRateCorrection")
connect(chkRate, SIGNAL(toggled(bool)), this, SLOT(EnableRateCorrection()));
connect(btnGroupRate, SIGNAL(buttonClicked(int)), this,
SLOT(SetRateCorrection()));
connect(btnGroupRate, &QButtonGroup::idClicked, this,
&qTabDataOutput::SetRateCorrection);
connect(spinCustomDeadTime, SIGNAL(valueChanged(int)), this,
SLOT(SetRateCorrection()));
}
+1 -6
View File
@@ -1,17 +1,12 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#include "qVersionResolve.h"
#include <iostream>
namespace sls {
int qResolve_GetQFontWidth(const QFontMetrics fm, const QString &text,
int len) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
return fm.horizontalAdvance(text, len);
#else
return fm.width(text, len);
#endif
};
}
} // namespace sls