Port qwt-free GUI plotting from 1010/qt6-port-ai-experimental

Straight port of the GUI work on 1010/qt6-port-ai-experimental
(91497579a..fdc457fee) onto dev/mac-build, without further changes:

- Qt-only plotting stack replacing qwt: SlsQtPlotCommon, SlsQtFastImage,
  SlsQtScalePanel and rewritten SlsQt1DPlot / SlsQt2DPlot / SlsQt2DHist.
  The 2D view zooms with the wheel, pans by dragging and shows pixel
  outlines and values when zoomed in.
- slsDetectorPlotting static library, QtTest suite and plot_demo.
- Detachable Plot settings dock.
- Bundled qwt removed, SLS_GUI_QT_MAJOR and cmk.sh -g/-G added.

Not ported: this_build_bin_path.sh, CI workflows, conda recipe, README,
installation.rst and dependencies.rst.

The conflict in qDrawPlot::StartAcquisition keeps the developer
behaviour of not resetting the zoom at the start of an acquisition.
This commit is contained in:
Erik Fröjdh committed 2026-11-13 09:41:02 +01:00
1 parent da4f41c117
commit 7b7d2e49bd
33 files changed
+8846 -1875

No files matched your search

+14 -7
View File
@@ -227,6 +227,10 @@ option(SLS_USE_DETECTOR "Detector libs" ON)
option(SLS_USE_RECEIVER "Receiver" ON)
option(SLS_USE_RECEIVER_BINARIES "Receiver binaries" ON)
option(SLS_USE_GUI "GUI" OFF)
# Qt major version used by slsDetectorGui when SLS_USE_GUI=ON. Qt 5 is kept
# for older distributions (e.g. RHEL 7); Qt 6 is the default.
set(SLS_GUI_QT_MAJOR "6" CACHE STRING "Qt major version for slsDetectorGui (5 or 6)")
set_property(CACHE SLS_GUI_QT_MAJOR PROPERTY STRINGS 5 6)
option(SLS_USE_SIMULATOR "Simulator" OFF)
option(SLS_USE_TESTS "TESTS" OFF)
option(SLS_USE_SANITIZER "Sanitizers for debugging" OFF)
@@ -293,8 +297,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/"
@@ -446,8 +448,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)
@@ -541,9 +542,15 @@ set(CPACK_RPM_PACKAGE_RELEASE_DIST ON)
set(CPACK_RPM_COMPONENT_INSTALL ON)
set(CPACK_RPM_GUI_PACKAGE_REQUIRES
"qt5-qtbase, qt5-qtbase-gui"
)
if(SLS_GUI_QT_MAJOR STREQUAL "5")
set(CPACK_RPM_GUI_PACKAGE_REQUIRES
"qt5-qtbase, qt5-qtbase-gui"
)
else()
set(CPACK_RPM_GUI_PACKAGE_REQUIRES
"qt6-qtbase, qt6-qtbase-gui"
)
endif()
#control which RPMs are generated
set(CPACK_COMPONENTS_ALL cli receiver zmq gui)
+70 -10
View File
@@ -1,7 +1,16 @@
#!/bin/bash
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
CMAKE="cmake3"
# Stop at the first failing configure/build step so a failed GUI build is not
# reported as success by the final (possibly skipped) install step.
set -e
# Prefer cmake3 when the distribution provides it (RHEL/CentOS), otherwise
# use the default cmake. -k <cmd> still overrides this.
if command -v cmake3 >/dev/null 2>&1; then
CMAKE="cmake3"
else
CMAKE="cmake"
fi
BUILDDIR="build"
INSTALLDIR=""
HDF5DIR="/opt/hdf5v1.10.0"
@@ -10,6 +19,8 @@ COMPILERTHREADS=0
TEXTCLIENT=0
RECEIVER=0
GUI=0
QT5=0
QT6=0
DEBUG=0
PYTHON=0
TESTS=0
@@ -26,13 +37,14 @@ CMAKE_PRE=""
CMAKE_POST=""
usage() { echo -e "
Usage: $0 [-b] [-c] [-d <HDF5 directory>] [-e] [-g] [-h] [-i] [-j <Number of threads>] [-k <CMake command>] [-l <Install directory>] [-m] [-n] [-p] [-r] [-s] [-t] [-u] [-z]
Usage: $0 [-b] [-c] [-d <HDF5 directory>] [-e] [-g] [-G] [-h] [-i] [-j <Number of threads>] [-k <CMake command>] [-l <Install directory>] [-m] [-n] [-p] [-r] [-s] [-t] [-u] [-z]
-[no option]: only make
-b: Builds/Rebuilds CMake files normal mode
-c: Clean
-d: HDF5 Custom Directory
-e: Debug mode
-g: Build/Rebuilds gui
-g: Build/Rebuilds gui with Qt5
-G: Build/Rebuilds gui with Qt6
-h: Builds/Rebuilds Cmake files with HDF5 package
-i: Builds tests
-j: Number of threads to compile through
@@ -76,12 +88,16 @@ For using multiple cores to compile faster:
./cmk.sh -j9 -h #with hdf
For rebuilding only certain sections
./cmk.sh -tg #only text client and gui
./cmk.sh -tg #text client and Qt5 gui
./cmk.sh -tG #text client and Qt6 gui
./cmk.sh -r #only receiver
Switching between -g and -G removes the build tree automatically
(no extra -c needed).
" ; exit 1; }
while getopts ":bcd:eghij:k:l:mnpq:rstuz" opt ; do
while getopts ":bcd:eghij:k:l:mnpGq:rstuz" opt ; do
case $opt in
b)
echo "Building of CMake files Required"
@@ -100,8 +116,15 @@ while getopts ":bcd:eghij:k:l:mnpq:rstuz" opt ; do
DEBUG=1
;;
g)
echo "Compiling Options: GUI"
echo "Compiling Options: GUI (Qt5)"
GUI=1
QT5=1
REBUILD=1
;;
G)
echo "Compiling Options: GUI (Qt6)"
GUI=1
QT6=1
REBUILD=1
;;
h)
@@ -174,6 +197,11 @@ while getopts ":bcd:eghij:k:l:mnpq:rstuz" opt ; do
done
if [ $QT5 -eq 1 ] && [ $QT6 -eq 1 ]; then
echo "Invalid options: -g (Qt5 GUI) and -G (Qt6 GUI) are mutually exclusive" >&2
exit 1
fi
#python
if [ $PYTHON -eq 1 ]; then
CMAKE_POST+=" -DSLS_USE_PYTHON=ON "
@@ -182,9 +210,8 @@ fi
if [ $TEXTCLIENT -eq 0 ] && [ $RECEIVER -eq 0 ] && [ $GUI -eq 0 ]; then
#CMAKE_POST+=" -DSLS_USE_TEXTCLIENT=ON -DSLS_USE_RECEIVER=ON -DSLS_USE_GUI=ON "
CMAKE_POST+=" -DSLS_USE_TEXTCLIENT=ON -DSLS_USE_RECEIVER=ON -DSLS_USE_GUI=OFF "
echo "Enabling Compile Option: TextClient, Receiver and GUI"
echo "Enabling Compile Option: TextClient and Receiver (GUI off; use -g)"
else
if [ $TEXTCLIENT -eq 1 ]; then
CMAKE_POST+=" -DSLS_USE_TEXTCLIENT=ON -DSLS_USE_RECEIVER=OFF "
@@ -195,8 +222,13 @@ else
echo "Enabling Compile Option: Receiver"
fi
if [ $GUI -eq 1 ]; then
CMAKE_POST+=" -DSLS_USE_GUI=ON "
echo "Enabling Compile Option: GUI"
if [ $QT6 -eq 1 ]; then
CMAKE_POST+=" -DSLS_USE_GUI=ON -DSLS_GUI_QT_MAJOR=6 "
echo "Enabling Compile Option: GUI (Qt6)"
else
CMAKE_POST+=" -DSLS_USE_GUI=ON -DSLS_GUI_QT_MAJOR=5 "
echo "Enabling Compile Option: GUI (Qt5)"
fi
fi
fi
@@ -204,6 +236,26 @@ fi
# Switching the GUI between Qt5 and Qt6 in an existing build tree leaves
# generated Qt/moc/ui files and objects from the other major behind; even
# make clean after a reconfigure can race with stale targets, so remove the
# whole build tree. Read the cache before -b removes it.
if [ $GUI -eq 1 ] && [ -f "$BUILDDIR/CMakeCache.txt" ]; then
requested_qt=5
[ $QT6 -eq 1 ] && requested_qt=6
cached_gui=$(grep -E '^SLS_USE_GUI:BOOL=' "$BUILDDIR/CMakeCache.txt" | head -1 | cut -d= -f2 || true)
cached_qt=$(grep -E '^SLS_GUI_QT_MAJOR:STRING=' "$BUILDDIR/CMakeCache.txt" | head -1 | cut -d= -f2 || true)
# Cache from before SLS_GUI_QT_MAJOR existed: that build was Qt6.
if [ "$cached_gui" = "ON" ] && [ -z "$cached_qt" ]; then
cached_qt=6
fi
if [ "$cached_gui" = "ON" ] && [ -n "$cached_qt" ] && [ "$cached_qt" != "$requested_qt" ]; then
echo "Qt major changed from $cached_qt to $requested_qt: removing the build directory"
rm -rf -- "$BUILDDIR"
CLEAN=0
fi
fi
#build dir doesnt exist
if [ ! -d "$BUILDDIR" ] ; then
echo "No Build Directory. Building of Cmake files required"
@@ -265,6 +317,14 @@ else
fi
# Qt from conda-forge: cmake does not search $CONDA_PREFIX by itself when
# the environment does not export CMAKE_PREFIX_PATH. Only add the hint for
# the GUI build so a plain `./cmk.sh -cbgjN` / `-cbGjN` works in a conda env.
if [ $GUI -eq 1 ] && [ -n "${CONDA_PREFIX:-}" ] && [ -z "${CMAKE_PREFIX_PATH:-}" ]; then
CMAKE_POST+=" -DCMAKE_PREFIX_PATH=$CONDA_PREFIX"
echo "Using CMAKE_PREFIX_PATH from CONDA_PREFIX: $CONDA_PREFIX"
fi
#install
if [ -n "$INSTALLDIR" ]; then
CMAKE_POST+=" -DCMAKE_INSTALL_PREFIX=$INSTALLDIR"
+138
View File
@@ -0,0 +1,138 @@
Plotting in slsDetectorGui (Qt 5 / Qt 6)
=======================================
The detector GUI used to draw every plot with the bundled **Qwt 6.1.5**
library. That dependency has been removed together with its build rules and
sources. All plots in `slsDetectorGui` are now painted by a small,
self-contained stack that needs only **Qt Widgets / Gui / Core** (plus the
Qt `Concurrent` module for the acquisition thread). It builds against **Qt 5
(>= 5.9) or Qt 6 (>= 6.2)**; Qt 6 is the default, while Qt 5 keeps older
distributions such as RHEL 7 usable. There is no ROOT, Qwt, Qt Charts or
OpenGL dependency.
The stack lives in `slsDetectorGui/slsDetectorPlotting` and is compiled once
into the static library `slsDetectorPlotting`, which is linked by the GUI
executable, by the QtTest suite and by the demo application.
Components
----------
.. list-table::
:header-rows: 1
:widths: 30 70
* - Component
- Responsibility
* - `sls::plot` (SlsQtPlotCommon)
- Shared data: the 256-entry colour lookup tables of all palettes, the
1/2/5 tick and label formatting helpers, `logClamp()` and the dark
`PlotTheme` used by the 1D, 2D and histogram painting.
* - `SlsQtFastImage`
- Fast 2D image view with its own axes, grid, tick labels, pixel outlines
and value labels, ROI overlays and wheel/pan zoom. Also the canvas of
`SlsQt2DPlot`.
* - `SlsQtScaleHisto`
- Thin 256-bin histogram strip with two draggable range markers.
* - `SlsQtScalePanel`
- The strip plus palette chooser and image/histogram lin-log switches.
The colour min/max are edited in the Plot tab; the panel synchronises
its range with the image view in both directions.
* - `SlsQt2DPlot` / `SlsQt2DHist`
- The GUI 2D detector plot and its plain data container: z range, lin/log
z, bilinear interpolation, contour lines and ROI boxes. The z-axis
(colour scale) title is shown as a compact caption row directly above the
scale panel, where the old qwt colour bar used to have it.
* - `SlsQt1DPlot` / `SlsQtH1D`
- The GUI 1D plot widget and histogram/curve data class: auto range,
lin/log axes, zoom/pan, legend, ROI boxes and gain plots.
Rendering rules
---------------
These rules are what make the image look like the old detector display while
staying fast enough for online frames:
* Data coordinates are **image pixel edge coordinates**: `x` to the right,
`y` up, row 0 at the bottom, pixel `(ix, iy)` covering
`[ix, ix+1) x [iy, iy+1)`. The frame is flipped exactly once when the
`QImage` is composed, never anywhere else.
* One cached `Format_RGB32` image is composed per update by writing whole
scanlines through the 256-entry palette LUT; there is no `setPixel` in the
hot loop and the image is only reallocated when the frame geometry changes.
Repaints of the same frame reuse the cache.
* Log palettes clamp values `<= 0` to `1e-2` before `log10`, so empty or
negative (pedestal corrected) pixels stay visible instead of becoming
`-inf`.
* The histogram of the scale panel is binned over the window the strip
actually displays - the colour range widened by half a range on either side,
in log space when the image is logarithmic - and values outside that window
are skipped instead of piling up in the edge bins. It is recomputed at most
every ~300 ms.
* The image, the overlays and the contours are clipped to the plot rectangle,
so a zoomed frame never paints over the axes or the margins.
* Axis ticks are 1/2/5 x 10^n steps chosen for at most ~8 grid lines; labels
drop trailing zeros and adapt their decimals to the step. Pixel outlines
appear when one data pixel is at least ~16 screen pixels wide, in-pixel
values only when they fit (~50 screen pixels) and use the integer format for
photon/gain maps.
* Wheel zoom keeps the data point under the cursor fixed (factor 1.18) and the
viewport is clamped to the frame and to a minimum size.
* Overlays (gate ROI, receiver ROIs, contour lines) are specified in data
coordinates and follow zoom and pan.
Scale panel freeze rule
-----------------------
Dragging one of the two range markers of the histogram strip must not change
anything except the dashed preview line: the axis window is the one captured
when the button went down, the painted bars are a snapshot taken at the same
moment (the producer keeps feeding new frames), and the cursor-to-value mapping
uses the pressed-time window so the marker cannot chase itself. The new range
is applied once, on release, and the strip is refreshed afterwards.
Detachable Plot settings
------------------------
The Plot settings tab can be detached into a movable/floating dock with
**View -> Detach Plot Settings**. The tab contents are reparented between two
``QScrollArea`` widgets (the tab and the dock), so the same ``qTabPlot``
instance keeps working while the rest of the main window is busy starting or
stopping an acquisition. Selecting the action again reattaches the tab.
Demo and tests
--------------
The demo application and the QtTest suite are built automatically by the GUI
CMake file (they are enabled by the presence of `slsDetectorGui/demo` and
`slsDetectorGui/tests`)::
cmake -S slsDetectorPackage -B build -DSLS_USE_GUI=ON \
-DSLS_GUI_QT_MAJOR=6 -DCMAKE_BUILD_TYPE=Release
cmake --build build --target plot_demo plotting_test -j
# standalone demo / offline benchmark (1024x512 synthetic frame, 20 Hz)
QT_QPA_PLATFORM=offscreen ./build/bin/plot_demo --frames 100
QT_QPA_PLATFORM=offscreen ./build/bin/plot_demo --shot 2d-zoom-roi --png shot.png
# QtTest suite (also registered with CTest when -DSLS_USE_TESTS=ON)
QT_QPA_PLATFORM=offscreen ./build/bin/plotting_test
`plot_demo` prints the unthrottled render throughput and the measured timer
frame rate; `plotting_test` covers the palettes and LUTs, tick/label helpers,
the FastImageView histogram window, log clamping, zero-white, cursor-fixed
zoom, viewport clamping, clipping (checked on rendered pixels), buffer
ownership, ROI overlays, the three-way histogram freeze rule, the scale panel
re-entrancy, 1D and 2D behaviour and the 1024x512 >= 20 Hz acceptance
benchmark.
Removing Qwt
------------
`libs/qwt` is gone from the source tree and the build; `slsDetectorGui` no
longer finds or links Qwt, and no source under `slsDetectorPlotting` includes
a `qwt_*` header. The package metadata and documentation refer to the Qt
runtime packages instead (`qt6-qtbase`/`qt5-qtbase` on RPM based systems,
`qt6-base-dev`/`qtbase5-dev` on Debian/Ubuntu, `qt6-main`/`qt-main` in
conda), selected by `SLS_GUI_QT_MAJOR` (or `cmk.sh -G` for Qt 6 and `-g` for
Qt 5). Switching between the two cmk flags removes the build tree
automatically, so no extra `-c` is needed.
+6
View File
@@ -62,6 +62,12 @@ slsDetectorPackage
commandline
.. toctree::
:caption: GUI
:maxdepth: 2
gui_plotting
.. toctree::
:caption: Developer
-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 SYSTEM 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.
+80 -22
View File
@@ -5,17 +5,69 @@ set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
find_package(Qt5 5.9 COMPONENTS Widgets Core Gui REQUIRED)
# Qt 5 or 6 (Widgets/Gui/Core). Concurrent is needed for the acquisition
# thread in qDrawPlot.cpp. No Qwt. SLS_GUI_QT_MAJOR selects the Qt major
# version; Qt 5 is needed on older distributions such as RHEL 7.
if(SLS_GUI_QT_MAJOR STREQUAL "6")
find_package(Qt6 6.2 REQUIRED COMPONENTS Widgets Gui Core Concurrent)
set(SLS_QT_LIBS Qt6::Widgets Qt6::Gui Qt6::Core)
set(SLS_QT_CONCURRENT Qt6::Concurrent)
elseif(SLS_GUI_QT_MAJOR STREQUAL "5")
find_package(Qt5 5.9 REQUIRED COMPONENTS Widgets Gui Core Concurrent)
set(SLS_QT_LIBS Qt5::Widgets Qt5::Gui Qt5::Core)
set(SLS_QT_CONCURRENT Qt5::Concurrent)
else()
message(FATAL_ERROR "SLS_GUI_QT_MAJOR must be 5 or 6 (got ${SLS_GUI_QT_MAJOR})")
endif()
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
${SLS_QT_LIBS}
PRIVATE
slsProjectWarnings
)
set(SOURCES
src/qDetectorMain.cpp
src/qDrawPlot.cpp
src/qCloneWidget.cpp
@@ -46,14 +98,13 @@ set(FORMS
forms/form_cloneplot.ui
)
qt5_wrap_ui(FORMS_H ${FORMS})
if(SLS_GUI_QT_MAJOR STREQUAL "6")
qt6_wrap_ui(FORMS_H ${FORMS})
else()
qt5_wrap_ui(FORMS_H ${FORMS})
endif()
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 +123,13 @@ set(HEADERS
set(RESOURCES
include/icons.qrc
)
qt5_add_resources(RESOURCES_SRCS ${RESOURCES})
if(SLS_GUI_QT_MAJOR STREQUAL "6")
qt6_add_resources(RESOURCES_SRCS ${RESOURCES})
else()
qt5_add_resources(RESOURCES_SRCS ${RESOURCES})
endif()
add_definitions(
${Qt5Widgets_DEFINITIONS} -DPRINT_LOG #-DVERBOSE
)
add_executable(slsDetectorGui
${SOURCES}
${HEADERS}
@@ -86,28 +137,25 @@ 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
${SLS_QT_LIBS}
${SLS_QT_CONCURRENT}
PRIVATE
slsProjectWarnings
qwt
)
set_target_properties(slsDetectorGui PROPERTIES
@@ -119,4 +167,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)
+29
View File
@@ -0,0 +1,29 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2026 Contributors to the SLS Detector Package
#
# Standalone Qt Widgets demo / benchmark for the Qt5/Qt6 plotting stack.
# Wired in from slsDetectorGui/CMakeLists.txt by an EXISTS guard; links the
# shared slsDetectorPlotting static library built by the GUI CMake file.
#
# Build: cmake --build <build> --target plot_demo
# Run: QT_QPA_PLATFORM=offscreen <build>/bin/plot_demo --frames 120
if(SLS_GUI_QT_MAJOR STREQUAL "5")
find_package(Qt5 5.9 REQUIRED COMPONENTS Widgets Gui Core)
else()
find_package(Qt6 6.2 REQUIRED COMPONENTS Widgets Gui Core)
endif()
if(NOT TARGET slsDetectorPlotting)
message(FATAL_ERROR
"plot_demo needs the slsDetectorPlotting target defined in "
"slsDetectorGui/CMakeLists.txt")
endif()
add_executable(plot_demo
plot_demo.cpp
)
target_link_libraries(plot_demo PRIVATE slsDetectorPlotting)
set_target_properties(plot_demo PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
+486
View File
@@ -0,0 +1,486 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2026 Contributors to the SLS Detector Package
//
// Standalone offscreen demo / benchmark for the Qt5/Qt6 plotting stack.
//
// It builds a synthetic 1024x512 float frame (sin(x/40)+cos(y/30) plus a moving
// hotspot) at ~20 Hz, feeds it to SlsQtFastImage, keeps SlsQtScalePanel in sync
// and shows a 1D plot with three live curves below it. It prints the
// measured timer rate plus the unthrottled render throughput. --png saves a
// screenshot; --shot prepares one of the acceptance views:
//
// 2d-default 2D image + scale panel
// 2d-zoom-roi 64x30 pixel zoom with gate/overlay/receiver ROIs
// scale-drag mid-drag ScaleHisto strip (frozen bars, dashed preview)
// 1d-log the real SlsQt1DPlot with three curves on a log y axis
// gain the real SlsQt2DPlot gain-mode widget (Gain4, 0..3)
//
// QT_QPA_PLATFORM=offscreen ./bin/plot_demo --frames 120
// QT_QPA_PLATFORM=offscreen ./bin/plot_demo --shot 1d-log \
// --png ../artifacts/1d-log.png
//
// CLI: --frames N (0 = run until closed), --png PATH, --shot MODE.
#include "SlsQt1DPlot.h"
#include "SlsQt2DPlot.h"
#include "SlsQtFastImage.h"
#include "SlsQtPlotCommon.h"
#include "SlsQtScalePanel.h"
#include <QApplication>
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QMouseEvent>
#include <QPixmap>
#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <vector>
using sls::SlsQt1DPlot;
using sls::SlsQt2DPlot;
using sls::SlsQtFastImage;
using sls::SlsQtH1D;
using sls::SlsQtScalePanel;
namespace {
constexpr int kNx = 1024;
constexpr int kNy = 512;
constexpr int kTimerMs = 50; // ~20 Hz
constexpr int kShotFrames = 8;
constexpr int kCurveBins = 256;
void sendMouse(QWidget &w, QEvent::Type type, const QPointF &pos,
Qt::MouseButton button, Qt::MouseButtons buttons) {
QMouseEvent e(type, pos, QPointF(w.mapToGlobal(pos.toPoint())), button,
buttons, Qt::NoModifier);
QCoreApplication::sendEvent(&w, &e);
}
struct Options {
int frames = 120;
QString png;
QString shot;
};
} // namespace
class PlotDemo : public QWidget {
public:
explicit PlotDemo(const Options &opt) : QWidget(nullptr), m_opt(opt) {
m_frame.resize(size_t(kNx) * size_t(kNy));
m_frameD.resize(size_t(kNx) * size_t(kNy));
m_c1.resize(kCurveBins);
m_c2.resize(kCurveBins);
m_c3.resize(kCurveBins);
buildUi();
}
~PlotDemo() override {
// The curves must go before the QWidget base class destroys the plot
// they are attached to.
for (SlsQtH1D *c : m_curves)
delete c;
m_curves.clear();
}
int run() {
resize(1100, 900);
setWindowTitle(QStringLiteral("slsDetectorPlotting Qt6 demo"));
show();
m_targetFrames = m_opt.frames;
connect(&m_timer, &QTimer::timeout, this, [this] { tick(); });
connect(qApp, &QCoreApplication::aboutToQuit, this,
[this] { printStats(); });
m_timer.start(kTimerMs);
return QApplication::exec();
}
private:
void buildUi() {
auto *root = new QVBoxLayout(this);
root->setContentsMargins(0, 0, 0, 0);
root->setSpacing(0);
// 2D image + scale panel (the acceptance demo path).
m_2dRow = new QWidget(this);
auto *row = new QVBoxLayout(m_2dRow);
row->setContentsMargins(0, 0, 0, 0);
row->setSpacing(0);
m_view = new SlsQtFastImage(m_2dRow);
m_panel = new SlsQtScalePanel(m_view, m_2dRow);
row->addWidget(m_view, 1);
row->addWidget(m_panel);
// 1D plot with three curves (the real widget).
m_1d = new SlsQt1DPlot(this);
m_1d->SetTitle(QStringLiteral("1D histograms"));
m_1d->SetXTitle(QStringLiteral("bin"));
m_1d->SetYTitle(QStringLiteral("counts"));
for (int i = 0; i < 3; i++) {
auto *h = new SlsQtH1D(QStringLiteral("curve %1").arg(i + 1),
kCurveBins, 0.0, double(kCurveBins),
nullptr);
h->Attach(m_1d);
h->SetLineColor(i);
h->SetLineWidth(2);
m_curves.push_back(h);
}
// Real SlsQt2DPlot used for the 2D acceptance screenshots (title,
// axis titles, z-axis caption, scale panel): hidden in the live demo.
m_2d = new SlsQt2DPlot(this);
m_2d->hide();
// Real SlsQt2DPlot gain-mode widget (hidden until --shot gain).
m_gain = new SlsQt2DPlot(this, true);
m_gain->hide();
m_gainData.resize(size_t(kNx) * size_t(kNy));
root->addWidget(m_2dRow, 2);
root->addWidget(m_1d, 1);
root->addWidget(m_2d, 2);
root->addWidget(m_gain, 2);
}
void tick() {
const bool first = !m_started;
if (first) {
// Benchmark while the 2D view is visible and laid out.
(void)benchmark();
m_started = true;
setupShot();
}
m_phase += 0.08;
buildFrame();
if (m_2dRow->isVisible()) {
m_view->setImageCopy(m_frame.data(), kNx, kNy);
m_view->repaint(); // compose + paint, like the GUI acquisition loop
}
if (m_2d->isVisible()) {
// Real SlsQt2DPlot path: the GUI feeds double frames.
for (size_t i = 0; i < m_frame.size(); i++)
m_frameD[i] = double(m_frame[i]);
m_2d->SetData(kNx, -0.5, kNx - 0.5, kNy, -0.5, kNy - 0.5,
m_frameD.data());
m_2d->imageView()->repaint(); // sync compose: histogram/panel too
}
if (m_1d->isVisible())
update1d();
if (first) {
applyShotGeometry();
m_clock.start();
m_frames = 0; // measure the timer rate from here on
}
m_frames++;
if (m_opt.shot == QLatin1String("scale-drag") && !m_shotPrepared &&
m_frames >= 4) {
startStripDrag();
m_shotPrepared = true;
}
if (m_targetFrames > 0 && m_frames >= m_targetFrames)
finish();
}
// One-shot unthrottled measurement: copy + compose + paint per frame.
double benchmark() {
const int frames = 40;
QElapsedTimer t;
t.start();
for (int i = 0; i < frames; i++) {
m_frame[0] = float(i);
m_view->setImageCopy(m_frame.data(), kNx, kNy);
m_view->repaint();
}
const double seconds = double(t.nsecsElapsed()) / 1e9;
const double fps = double(frames) / seconds;
std::printf(
"plot_demo: render throughput %.1f fps (%.2f ms/frame, %d frames, "
"%dx%d)\n",
fps, 1000.0 * seconds / double(frames), frames, kNx, kNy);
std::fflush(stdout);
return fps;
}
void setupShot() {
m_view->setTitle(QStringLiteral("sin(x/40) + cos(y/30) | 1024x512"));
m_view->setXAxisTitle(QStringLiteral("x [px]"));
m_view->setYAxisTitle(QStringLiteral("y [px]"));
m_view->setColorRange(-2.0, 2.0);
if (m_opt.shot == QLatin1String("1d-log")) {
m_2dRow->hide();
m_gain->hide();
m_1d->show();
resize(1100, 640);
m_1d->SetTitle(QStringLiteral("1D histograms | log y"));
m_1d->SetLogY(true);
m_1d->SetLogX(false);
} else if (m_opt.shot == QLatin1String("gain")) {
m_2dRow->hide();
m_1d->hide();
m_gain->show();
resize(kNx, kNy);
} else if (m_opt.shot == QLatin1String("2d-default") ||
m_opt.shot == QLatin1String("2d-zoom-roi") ||
m_opt.shot == QLatin1String("scale-drag")) {
// Real SlsQt2DPlot: canvas + scale panel + z-axis caption row.
m_2dRow->hide();
m_1d->hide();
m_gain->hide();
m_2d->show();
resize(1100, 660);
m_2d->SetTitle(
QStringLiteral("sin(x/40) + cos(y/30) | 1024x512"));
m_2d->SetXTitle(QStringLiteral("x [px]"));
m_2d->SetYTitle(QStringLiteral("y [px]"));
m_2d->SetZTitle(QStringLiteral("z (colour scale)"));
} else {
m_2dRow->show();
m_1d->hide();
m_2d->hide();
m_gain->hide();
resize(1100, 640);
if (!m_opt.shot.isEmpty()) {
std::fprintf(stderr, "plot_demo: unknown --shot '%s'\n",
qPrintable(m_opt.shot));
}
}
}
// Applied after the first frame: setImageCopy() of a new image resets the
// viewport, so zoom/ROI/gain data must be set once an image exists.
void applyShotGeometry() {
if (m_opt.shot == QLatin1String("2d-zoom-roi")) {
// Data coords of SlsQt2DPlot are bin centres: -0.5..nx-0.5 with
// unit bins, i.e. image pixel edges 400..460 / 200..230.
m_2d->SetZoom(QRectF(399.5, 199.5, 60.0, 30.0));
m_2d->EnableRoiBoxes({slsDetectorDefs::ROI(410, 429, 210, 224),
slsDetectorDefs::ROI(446, 451, 218, 225)});
m_2d->imageView()->repaint();
} else if (m_opt.shot == QLatin1String("gain")) {
// Real gain widget: 0..3 gain bits in four quadrants plus a
// gain-switching block (as on a Jungfrau chip).
for (int y = 0; y < kNy; y++) {
for (int x = 0; x < kNx; x++) {
int g = (x < kNx / 2 ? 0 : 1) + (y < kNy / 2 ? 2 : 0);
if (x > 3 * kNx / 4 && y > 7 * kNy / 8)
g = (g + 1) % 4;
m_gainData[size_t(y) * kNx + x] = double(g);
}
}
m_gain->SetData(kNx, -0.5, kNx - 0.5, kNy, -0.5, kNy - 0.5,
m_gainData.data());
m_gain->UnZoom();
m_gain->Update();
}
}
void update1d() {
const double centre1 =
kCurveBins / 2.0 + 40.0 * std::sin(m_phase * 0.6);
const double centre2 =
kCurveBins / 2.0 - 40.0 * std::sin(m_phase * 0.6);
for (int i = 0; i < kCurveBins; i++) {
const double x = i;
m_c1[size_t(i)] =
800.0 * std::exp(-std::pow(x - centre1, 2.0) / (2 * 18 * 18)) +
5.0;
m_c2[size_t(i)] =
500.0 * std::exp(-std::pow(x - centre2, 2.0) / (2 * 28 * 28)) +
15.0;
m_c3[size_t(i)] = 20.0 + 8.0 * std::sin(x / 7.0 + m_phase) + 1.0;
}
m_curves[0]->SetData(kCurveBins, 0.0, double(kCurveBins), m_c1.data());
m_curves[1]->SetData(kCurveBins, 0.0, double(kCurveBins), m_c2.data());
m_curves[2]->SetData(kCurveBins, 0.0, double(kCurveBins), m_c3.data());
m_1d->Update();
}
void buildFrame() {
const double cx = 512.0 + 220.0 * std::sin(m_phase);
const double cy = 256.0 + 120.0 * std::cos(m_phase * 0.7);
for (int y = 0; y < kNy; y++) {
for (int x = 0; x < kNx; x++) {
const double base = std::sin(x / 40.0) + std::cos(y / 30.0);
const double dx = x - cx, dy = y - cy;
const double hotspot =
1.2 * std::exp(-(dx * dx + dy * dy) / (2.0 * 70.0 * 70.0));
m_frame[size_t(y) * kNx + x] = float(base + hotspot);
}
}
}
SlsQtScalePanel *scalePanel() const {
return m_2d && m_2d->isVisible() ? m_2d->scalePanel() : m_panel;
}
void startStripDrag() {
SlsQtScalePanel *panel = scalePanel();
if (!panel)
return;
auto *strip = panel->histogramWidget();
if (!strip || strip->width() <= 0)
return;
const double w = strip->width();
const QPointF press(w * 0.25, strip->height() * 0.5);
const QPointF move(w * 0.42, strip->height() * 0.5);
sendMouse(*strip, QEvent::MouseButtonPress, press, Qt::LeftButton,
Qt::LeftButton);
sendMouse(*strip, QEvent::MouseMove, move, Qt::NoButton,
Qt::LeftButton);
m_stripDragging = strip->isDragging();
std::printf("plot_demo: ScaleHisto drag prepared (dragging=%d, "
"previewX=%d)\n",
m_stripDragging ? 1 : 0, strip->previewX());
}
void endStripDrag() {
if (!m_stripDragging)
return;
SlsQtScalePanel *panel = scalePanel();
if (!panel)
return;
auto *strip = panel->histogramWidget();
if (!strip)
return;
const double w = strip->width();
sendMouse(*strip, QEvent::MouseButtonRelease,
QPointF(w * 0.42, strip->height() * 0.5), Qt::LeftButton,
Qt::NoButton);
m_stripDragging = false;
}
void finish() {
// The drag screenshot must be taken before the release applies it.
if (!m_opt.png.isEmpty())
savePng();
endStripDrag();
printStats();
m_timer.stop();
QApplication::quit();
}
void savePng() {
const QPixmap shot = grab();
if (shot.isNull()) {
std::fprintf(stderr, "plot_demo: could not grab the window\n");
return;
}
if (!shot.save(m_opt.png, "PNG")) {
std::fprintf(stderr, "plot_demo: failed to save %s\n",
qPrintable(m_opt.png));
return;
}
std::printf("plot_demo: saved %s (%dx%d)\n", qPrintable(m_opt.png),
shot.width(), shot.height());
std::fflush(stdout);
m_pngSaved = true;
}
void printStats() {
if (m_statsPrinted)
return;
m_statsPrinted = true;
if (!m_started || m_frames <= 0) {
std::printf("plot_demo: no frames rendered\n");
return;
}
// m_clock starts after the first frame, so (m_frames - 1) intervals
// were measured.
const double seconds = double(m_clock.nsecsElapsed()) / 1e9;
const double fps =
(m_frames > 1 && seconds > 0.0) ? double(m_frames - 1) / seconds : 0.0;
std::printf("plot_demo: %d timer frames, %.3f s between first/last = "
"%.1f fps (QTimer target %d ms)\n",
m_frames, seconds, fps, kTimerMs);
std::fflush(stdout);
}
Options m_opt;
QWidget *m_2dRow = nullptr;
SlsQtFastImage *m_view = nullptr;
SlsQtScalePanel *m_panel = nullptr;
SlsQt1DPlot *m_1d = nullptr;
SlsQt2DPlot *m_2d = nullptr;
SlsQt2DPlot *m_gain = nullptr;
QTimer m_timer;
QElapsedTimer m_clock;
std::vector<float> m_frame;
std::vector<double> m_frameD;
std::vector<double> m_gainData;
std::vector<double> m_c1, m_c2, m_c3;
std::vector<SlsQtH1D *> m_curves;
double m_phase = 0.0;
int m_frames = 0;
int m_targetFrames = 120;
bool m_started = false;
bool m_shotPrepared = false;
bool m_stripDragging = false;
bool m_statsPrinted = false;
bool m_pngSaved = false;
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
QCoreApplication::setApplicationName(QStringLiteral("plot_demo"));
QCoreApplication::setApplicationVersion(QStringLiteral("1.0"));
QCommandLineParser parser;
parser.setApplicationDescription(
QStringLiteral("Qt5/Qt6 plotting stack demo / offline benchmark"));
parser.addHelpOption();
parser.addVersionOption();
const QCommandLineOption framesOpt(
QStringList{QStringLiteral("f"), QStringLiteral("frames")},
QStringLiteral("number of timer frames before exiting (0 = run until "
"the window is closed)"),
QStringLiteral("N"), QStringLiteral("120"));
const QCommandLineOption pngOpt(
QStringLiteral("png"),
QStringLiteral("save a screenshot to PATH when the run finishes"),
QStringLiteral("PATH"));
const QCommandLineOption shotOpt(
QStringLiteral("shot"),
QStringLiteral("prepare an acceptance view: 2d-default, 2d-zoom-roi, "
"scale-drag, 1d-log, gain"),
QStringLiteral("MODE"));
parser.addOption(framesOpt);
parser.addOption(pngOpt);
parser.addOption(shotOpt);
parser.process(app);
Options opt;
opt.frames = parser.value(framesOpt).toInt();
opt.png = parser.value(pngOpt);
opt.shot = parser.value(shotOpt);
if (opt.frames < 0)
opt.frames = 0;
// A shot needs a few frames for the histogram/panel to settle.
if (!opt.shot.isEmpty() && opt.frames > 0 && !parser.isSet(framesOpt))
opt.frames = kShotFrames;
if (opt.frames == 0 && !opt.png.isEmpty()) {
std::fprintf(stderr,
"plot_demo: --png needs a finite --frames value\n");
return 2;
}
std::printf("plot_demo: Qt %s, platform '%s', frame %dx%d\n",
qVersion(), qPrintable(QGuiApplication::platformName()), kNx,
kNy);
std::fflush(stdout);
PlotDemo demo(opt);
const int rc = demo.run();
return rc;
}
+7
View File
@@ -5,6 +5,9 @@
#include "sls/Detector.h"
#include "ui_form_detectormain.h"
class QResizeEvent;
class QAction;
class QDockWidget;
class QScrollArea;
namespace sls {
@@ -38,6 +41,7 @@ class qDetectorMain : public QMainWindow, private Ui::DetectorMainObject {
void ResizeMainWindow(bool b);
void EnableTabs(bool enable);
void SetZoomToolTip(bool disable);
void SetPlotSettingsDetached(bool detached);
protected:
void resizeEvent(QResizeEvent *event);
@@ -71,6 +75,9 @@ class qDetectorMain : public QMainWindow, private Ui::DetectorMainObject {
qTabDebugging *tabDebugging;
qTabDeveloper *tabDeveloper;
qTabMessages *tabMessages;
QDockWidget *dockWidgetPlotSettings{nullptr};
QScrollArea *dockScrollPlotSettings{nullptr};
QAction *actionDetachPlotSettings{nullptr};
int isDeveloper{false};
QString zoomToolTip;
QColor defaultTabColor;
@@ -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
// Qt5/Qt6 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,140 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2026 Contributors to the SLS Detector Package
#pragma once
// Shared plotting primitives for the Qt5/Qt6 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 <QFontMetrics>
#include <QMouseEvent>
#include <QRect>
#include <QRgb>
#include <QSize>
#include <QString>
#include <QWheelEvent>
#include <QtGlobal>
#include <cmath>
#include <vector>
namespace sls {
namespace plot {
// Qt5/Qt6 compatibility helpers. The GUI and the plotting stack are built
// against whichever Qt major version the distribution provides (see the
// SLS_GUI_QT_MAJOR CMake option); keep the version-specific calls in one place.
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
inline QPointF eventPosition(const QMouseEvent *event) {
return event->position();
}
inline QPointF eventPosition(const QWheelEvent *event) {
return event->position();
}
#else
inline QPointF eventPosition(const QMouseEvent *event) {
return event->localPos();
}
inline QPointF eventPosition(const QWheelEvent *event) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
return event->position();
#else
return event->posF();
#endif
}
#endif
// QFontMetrics::horizontalAdvance() arrived in Qt 5.11; Qt 5.9 (RHEL 7)
// still needs width().
inline int textWidth(const QFontMetrics &metrics, const QString &text) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
return metrics.horizontalAdvance(text);
#else
return metrics.width(text);
#endif
}
// 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,170 @@
// 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 Qt5/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 and the image/histogram lin-log switches. The
// colour min/max live in the Plot tab, not here. See AGENT_INSTRUCTIONS.md:
// "the three-way freeze rule".
#include "SlsQtPlotCommon.h"
#include <QMetaObject>
#include <QPointer>
#include <QWidget>
#include <functional>
#include <vector>
class QComboBox;
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.
// push() = controls -> view, refresh() = view -> controls, with a
// re-entrancy guard; refresh() is skipped while the strip is being dragged and
// the range is applied on release. The z min/max are edited in the Plot tab.
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 colour range last read from / written to the view. Stays frozen
// while the strip marker is dragged (R1).
void controlRange(double &lo, double &hi) const;
// Applies a colour range as a user edit would: this is the only path that
// pushes the colour range from the panel controls, so a test can trigger
// one without synthesising events.
void setControlRange(double lo, double hi);
// Range last pushed to the view by a control edit; false if no edit was
// pushed yet. Palette/log changes never update this (R2).
bool lastPushedRange(double &lo, double &hi) const;
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;
// The colour range last read from the view (kept for the R1 freeze rule
// and for programmatic/test edits; there are no min/max spin boxes here).
double m_controlLo = 0.0;
double m_controlHi = 1.0;
int m_suppress = 0;
// R2: only an explicit control edit may push the colour range. Refreshes
// (automatic z range) and palette/log changes only update the controls.
bool m_rangeEdited = false;
bool m_lastPushedValid = false;
double m_lastPushedLo = 0.0;
double m_lastPushedHi = 1.0;
std::function<void()> m_prevImageChanged;
std::function<void()> m_prevScaleReleased;
bool m_installed = false;
QMetaObject::Connection m_destroyedConn;
};
} // 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 control range 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,510 @@
// 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 <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(sls::plot::eventPosition(e).x() - xa);
const double d2 = std::abs(sls::plot::eventPosition(e).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 = sls::plot::eventPosition(e).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(sls::plot::eventPosition(e).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 = sls::plot::eventPosition(e).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_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->addStretch(1);
col->addLayout(row);
connect(m_paletteCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, [this](int) { push(); });
connect(m_imageLogCombo,
QOverload<int>::of(&QComboBox::currentIndexChanged), this,
[this](int i) {
if (m_suppress || !m_view)
return;
m_view->setLogScale(i == 1);
refresh();
});
connect(m_histoLogCombo,
QOverload<int>::of(&QComboBox::currentIndexChanged), this,
[this](int) { updateHisto(); });
m_histo->onRangeChanged = [this](double a, double b) {
if (m_suppress || !m_view)
return;
m_view->setColorRange(a, b);
m_controlLo = a;
m_controlHi = b;
refresh();
};
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 control range (and the
// strip labels) under the frozen marker.
if (m_view->isScaleDragging() ||
(m_histo && m_histo->isDragging()))
return;
m_suppress++;
double a = 0.0, b = 1.0;
m_view->colorRange(a, b);
m_controlLo = a;
m_controlHi = b;
if (m_imageLogCombo)
m_imageLogCombo->setCurrentIndex(m_view->logScale() ? 1 : 0);
const int pi = m_view->paletteIndex();
if (m_paletteCombo && pi >= 0 && pi < m_paletteCombo->count())
m_paletteCombo->setCurrentIndex(pi);
updateHisto();
m_suppress--;
}
void SlsQtScalePanel::syncFromView() { refresh(); }
void SlsQtScalePanel::push() { // controls -> view
if (m_suppress || !m_view)
return;
// Palette changes are always applied (cheap and lossless).
const int pi = m_paletteCombo ? m_paletteCombo->currentIndex() : 0;
if (pi >= 0)
m_view->setPaletteLut(
sls::plot::paletteLut(static_cast<sls::plot::Palette>(pi)));
// R2: only push the colour range on an explicit control edit (the Plot
// tab owns min/max; the panel only synchronises it). Palette/log changes
// must not perturb the automatic z range. A strip-marker drag applies its
// range directly in the onRangeChanged handler, not here.
if (m_rangeEdited) {
m_rangeEdited = false;
double a = m_controlLo;
double b = m_controlHi;
if (!(b > a)) {
b = a + 1.0;
m_controlHi = b;
}
m_lastPushedValid = true;
m_lastPushedLo = a;
m_lastPushedHi = b;
m_view->setColorRange(a, b);
}
refresh();
}
void SlsQtScalePanel::controlRange(double &lo, double &hi) const {
lo = m_controlLo;
hi = m_controlHi;
}
void SlsQtScalePanel::setControlRange(double lo, double hi) {
// Mimic the operator applying both ends from the Plot tab.
m_controlLo = lo;
m_controlHi = hi;
m_rangeEdited = true;
push();
}
bool SlsQtScalePanel::lastPushedRange(double &lo, double &hi) const {
lo = m_lastPushedLo;
hi = m_lastPushedHi;
return m_lastPushedValid;
}
void SlsQtScalePanel::setPalette(sls::plot::Palette p) {
const int idx = int(p);
if (m_paletteCombo && idx >= 0 && idx < m_paletteCombo->count())
setPaletteChoice(idx);
else if (m_view)
m_view->setPaletteLut(sls::plot::paletteLut(p));
refresh();
}
void SlsQtScalePanel::setPaletteChoice(int index) {
if (!m_paletteCombo || index < 0 || index >= m_paletteCombo->count())
return;
if (m_paletteCombo->currentIndex() == index)
push();
else
m_paletteCombo->setCurrentIndex(index); // triggers push()
}
int SlsQtScalePanel::paletteChoice() const {
return m_paletteCombo ? m_paletteCombo->currentIndex() : -1;
}
void SlsQtScalePanel::setImageLog(bool on) {
if (m_view)
m_view->setLogScale(on);
refresh();
}
void SlsQtScalePanel::setColorRange(double lo, double hi) {
if (m_view)
m_view->setColorRange(lo, hi);
refresh();
}
void SlsQtScalePanel::setHistoLog(bool on) {
if (m_histoLogCombo)
m_histoLogCombo->setCurrentIndex(on ? 1 : 0);
}
bool SlsQtScalePanel::histoLog() const {
return m_histoLogCombo && m_histoLogCombo->currentIndex() == 1;
}
void SlsQtScalePanel::setPaletteEnabled(bool on) {
if (m_paletteCombo)
m_paletteCombo->setEnabled(on);
}
SlsQtScaleHisto *SlsQtScalePanel::histogramWidget() const { return m_histo; }
bool SlsQtScalePanel::isDragging() const {
return m_histo && m_histo->isDragging();
}
} // 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);
+53
View File
@@ -15,8 +15,12 @@
#include "sls/ToString.h"
#include "sls/versionAPI.h"
#include <QAction>
#include <QDockWidget>
#include <QFileDialog>
#include <QMenu>
#include <QResizeEvent>
#include <QScrollArea>
#include <QSizePolicy>
#include <QStyleFactory>
@@ -155,6 +159,25 @@ void qDetectorMain::SetUpWidgetWindow() {
scrollMeasurement->setWidget(tabMeasurement);
scrollDataOutput->setWidget(tabDataOutput);
scrollPlot->setWidget(tabPlot);
// The Plot settings can be detached into a dock (or floated) so the
// operator can change them while an acquisition is being started/stopped
// without switching tabs in the main window.
dockWidgetPlotSettings = new QDockWidget(tr("Plot Settings"), this);
dockWidgetPlotSettings->setObjectName(
QStringLiteral("dockWidgetPlotSettings"));
dockWidgetPlotSettings->setAllowedAreas(Qt::LeftDockWidgetArea |
Qt::RightDockWidgetArea |
Qt::BottomDockWidgetArea);
dockWidgetPlotSettings->setFeatures(QDockWidget::DockWidgetMovable |
QDockWidget::DockWidgetFloatable);
dockScrollPlotSettings = new QScrollArea(dockWidgetPlotSettings);
dockScrollPlotSettings->setWidgetResizable(true);
dockScrollPlotSettings->setFrameShape(QFrame::NoFrame);
dockWidgetPlotSettings->setWidget(dockScrollPlotSettings);
addDockWidget(Qt::RightDockWidgetArea, dockWidgetPlotSettings);
dockWidgetPlotSettings->hide();
scrollSettings->setWidget(tabSettings);
scrollAdvanced->setWidget(tabAdvanced);
scrollDebugging->setWidget(tabDebugging);
@@ -251,6 +274,15 @@ void qDetectorMain::Initialization() {
// Help Menu
connect(menuHelp, SIGNAL(triggered(QAction *)), this,
SLOT(ExecuteHelp(QAction *)));
// View Menu: detach the Plot settings so they stay usable while the
// acquisition is starting/stopping.
QMenu *menuView = menuBar()->addMenu(tr("&View"));
actionDetachPlotSettings = new QAction(tr("Detach Plot Settings"), this);
actionDetachPlotSettings->setCheckable(true);
menuView->addAction(actionDetachPlotSettings);
connect(actionDetachPlotSettings, &QAction::toggled, this,
&qDetectorMain::SetPlotSettingsDetached);
}
void qDetectorMain::LoadConfigFile(const std::string &config_file) {
@@ -556,6 +588,27 @@ void qDetectorMain::EnableTabs(bool enable) {
}
}
void qDetectorMain::SetPlotSettingsDetached(bool detached) {
if (!dockWidgetPlotSettings || !dockScrollPlotSettings || !scrollPlot ||
!tabPlot)
return;
if (detached) {
QWidget *page = scrollPlot->takeWidget();
if (!page)
return;
dockScrollPlotSettings->setWidget(page);
dockWidgetPlotSettings->show();
dockWidgetPlotSettings->raise();
tabs->setTabText(PLOT, tr("Plot (detached)"));
} else {
QWidget *page = dockScrollPlotSettings->takeWidget();
if (page)
scrollPlot->setWidget(page);
dockWidgetPlotSettings->hide();
tabs->setTabText(PLOT, tr("Plot"));
}
}
void qDetectorMain::SetZoomToolTip(bool disable) {
if (disable)
dockWidgetPlot->setToolTip(
+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");
@@ -620,7 +620,7 @@ void qDrawPlot::StartAcquisition() {
"qDrawPlot::StartAcquisition");
}
QtConcurrent::run(this, &qDrawPlot::AcquireThread);
(void)QtConcurrent::run([this] { AcquireThread(); });
LOG(logDEBUG) << "End of Starting Acquisition in qDrawPlot";
}
+15 -6
View File
@@ -3,6 +3,15 @@
#include "qTabDataOutput.h"
#include "qDefs.h"
// QButtonGroup::idClicked arrived in Qt 5.15; older Qt5 releases (RHEL 7 has
// Qt 5.9) only provide the deprecated buttonClicked(int) overload, and Qt6
// removed that overload. Keep the three connect/disconnect sites in sync.
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
#define SLS_RATE_GROUP_SIGNAL &QButtonGroup::idClicked
#else
#define SLS_RATE_GROUP_SIGNAL QOverload<int>::of(&QButtonGroup::buttonClicked)
#endif
#include <QButtonGroup>
#include <QFileDialog>
#include <QStandardItemModel>
@@ -79,8 +88,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, SLS_RATE_GROUP_SIGNAL, this,
&qTabDataOutput::SetRateCorrection);
connect(spinCustomDeadTime, SIGNAL(valueChanged(int)), this,
SLOT(SetRateCorrection()));
}
@@ -309,8 +318,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, SLS_RATE_GROUP_SIGNAL, this,
&qTabDataOutput::SetRateCorrection);
disconnect(spinCustomDeadTime, SIGNAL(valueChanged(int)), this,
SLOT(SetRateCorrection()));
try {
@@ -326,8 +335,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, SLS_RATE_GROUP_SIGNAL, this,
&qTabDataOutput::SetRateCorrection);
connect(spinCustomDeadTime, SIGNAL(valueChanged(int)), this,
SLOT(SetRateCorrection()));
}
+3 -2
View File
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#include "qVersionResolve.h"
#include <iostream>
namespace sls {
@@ -10,8 +9,10 @@ int qResolve_GetQFontWidth(const QFontMetrics fm, const QString &text,
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
return fm.horizontalAdvance(text, len);
#else
// RHEL 7 still ships Qt 5.9, where QFontMetrics::width() is the only
// available overload for this.
return fm.width(text, len);
#endif
};
}
} // namespace sls
+46
View File
@@ -0,0 +1,46 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2026 Contributors to the SLS Detector Package
#
# QtTest suite for the Qt5/Qt6 plotting stack.
#
# Wired in from slsDetectorGui/CMakeLists.txt by an EXISTS guard; the plotting
# sources are compiled once into the slsDetectorPlotting static library there
# and shared by the GUI executable, this suite and the demo.
#
# Build: cmake --build <build> --target plotting_test
# Run: QT_QPA_PLATFORM=offscreen <build>/bin/plotting_test
# (or "ctest -R plotting" when the project is configured with
# -DSLS_USE_TESTS=ON)
if(SLS_GUI_QT_MAJOR STREQUAL "5")
find_package(Qt5 5.9 REQUIRED COMPONENTS Test)
set(SLS_QT_TEST Qt5::Test)
else()
find_package(Qt6 6.2 REQUIRED COMPONENTS Test)
set(SLS_QT_TEST Qt6::Test)
endif()
if(NOT TARGET slsDetectorPlotting)
message(FATAL_ERROR
"plotting_test needs the slsDetectorPlotting target defined in "
"slsDetectorGui/CMakeLists.txt")
endif()
add_executable(plotting_test
plotting_test.cpp
)
target_link_libraries(plotting_test PRIVATE
slsDetectorPlotting
${SLS_QT_TEST}
)
set_target_properties(plotting_test PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
if(SLS_USE_TESTS)
add_test(NAME plotting_test COMMAND plotting_test)
set_tests_properties(plotting_test PROPERTIES
ENVIRONMENT "QT_QPA_PLATFORM=offscreen"
TIMEOUT 300
)
endif()
File diff suppressed because it is too large. Load diff