diff --git a/CMakeLists.txt b/CMakeLists.txt index 41ee30021..c02a1a7a1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) diff --git a/cmk.sh b/cmk.sh index 498d590bd..472609b44 100755 --- a/cmk.sh +++ b/cmk.sh @@ -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 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 ] [-e] [-g] [-h] [-i] [-j ] [-k ] [-l ] [-m] [-n] [-p] [-r] [-s] [-t] [-u] [-z] +Usage: $0 [-b] [-c] [-d ] [-e] [-g] [-G] [-h] [-i] [-j ] [-k ] [-l ] [-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" diff --git a/docs/src/gui_plotting.rst b/docs/src/gui_plotting.rst new file mode 100644 index 000000000..92c65c50f --- /dev/null +++ b/docs/src/gui_plotting.rst @@ -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. diff --git a/docs/src/index.rst b/docs/src/index.rst index 8a5044cea..41b65e4c4 100644 --- a/docs/src/index.rst +++ b/docs/src/index.rst @@ -62,6 +62,12 @@ slsDetectorPackage commandline +.. toctree:: + :caption: GUI + :maxdepth: 2 + + gui_plotting + .. toctree:: :caption: Developer diff --git a/libs/qwt/CMakeLists.txt b/libs/qwt/CMakeLists.txt deleted file mode 100644 index be7986822..000000000 --- a/libs/qwt/CMakeLists.txt +++ /dev/null @@ -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 - $ -) - -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) diff --git a/libs/qwt/qwt-6.1.5.tar.bz2 b/libs/qwt/qwt-6.1.5.tar.bz2 deleted file mode 100644 index 9317162a9..000000000 Binary files a/libs/qwt/qwt-6.1.5.tar.bz2 and /dev/null differ diff --git a/slsDetectorGui/CMakeLists.txt b/slsDetectorGui/CMakeLists.txt index b78ccdd95..04ac38b0e 100755 --- a/slsDetectorGui/CMakeLists.txt +++ b/slsDetectorGui/CMakeLists.txt @@ -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 + "$" + "$" +) +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 "$" - "$" "$" - "$" - "$" "$" ) 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) diff --git a/slsDetectorGui/demo/CMakeLists.txt b/slsDetectorGui/demo/CMakeLists.txt new file mode 100644 index 000000000..a6544c9ee --- /dev/null +++ b/slsDetectorGui/demo/CMakeLists.txt @@ -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 --target plot_demo +# Run: QT_QPA_PLATFORM=offscreen /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" +) diff --git a/slsDetectorGui/demo/plot_demo.cpp b/slsDetectorGui/demo/plot_demo.cpp new file mode 100644 index 000000000..a7aafdcda --- /dev/null +++ b/slsDetectorGui/demo/plot_demo.cpp @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using sls::SlsQt1DPlot; +using sls::SlsQt2DPlot; +using sls::SlsQtFastImage; +using sls::SlsQtH1D; +using sls::SlsQtScalePanel; + +namespace { + +constexpr int kNx = 1024; +constexpr int kNy = 512; +constexpr int kTimerMs = 50; // ~20 Hz +constexpr int kShotFrames = 8; +constexpr int kCurveBins = 256; + +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 m_frame; + std::vector m_frameD; + std::vector m_gainData; + std::vector m_c1, m_c2, m_c3; + std::vector m_curves; + double m_phase = 0.0; + int m_frames = 0; + int m_targetFrames = 120; + bool m_started = false; + bool m_shotPrepared = false; + bool m_stripDragging = false; + bool m_statsPrinted = false; + bool m_pngSaved = false; +}; + +int main(int argc, char **argv) { + QApplication app(argc, argv); + QCoreApplication::setApplicationName(QStringLiteral("plot_demo")); + QCoreApplication::setApplicationVersion(QStringLiteral("1.0")); + + QCommandLineParser parser; + parser.setApplicationDescription( + QStringLiteral("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; +} diff --git a/slsDetectorGui/include/qDetectorMain.h b/slsDetectorGui/include/qDetectorMain.h index aa8d2d235..46373abab 100644 --- a/slsDetectorGui/include/qDetectorMain.h +++ b/slsDetectorGui/include/qDetectorMain.h @@ -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; diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h index 878a43b81..66ed168e1 100644 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h @@ -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 -#include -#include -#include -#include -#include - -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 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> 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 +#include +#include +#include +#include +#include +#include + +#include + +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(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 m_x; + std::vector 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 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 xTicks; + std::vector yTicks; + std::vector xLabels; + std::vector 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 tickValues(double lo, double hi, bool log, + int maxTicks) const; + std::vector tickLabels(const std::vector &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 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 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 m_rois; + int m_roiYMin{0}; + int m_roiYMax{0}; +}; + +} // namespace sls + +#endif diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DZoomer.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DZoomer.h deleted file mode 100644 index 19715c92d..000000000 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DZoomer.h +++ /dev/null @@ -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 -#include -#include - -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 diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h index 9baacbef6..232d8e6b8 100644 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h @@ -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 -#include -#include -#include +#include 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 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 \ No newline at end of file diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h index f7142b6eb..4c4d5b8a0 100644 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h @@ -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 -#include -#include -#include -#include - -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 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 colourStops); - QwtLinearColorMap *myColourMap(int log = 0); - - QwtPlotSpectrogram *d_spectrogram{nullptr}; - SlsQt2DHist *hist{nullptr}; - SlsQt2DZoomer *zoomer{nullptr}; - QwtPlotPanner *panner{nullptr}; - QwtScaleWidget *rightAxis{nullptr}; - QList contourLevelsLinear; - QList contourLevelsLog; - bool disableZoom{false}; - int isLog; - std::vector> 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 +#include +#include +#include +#include +#include +#include + +#include + +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 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 m_contourSegments; + bool m_contourDirty{true}; + + // Yellow ROI boxes in image pixel-edge coordinates; kept so they can be + // redrawn above the smooth overlay. + std::vector m_roiRects; + + std::vector m_testData; // storage for FillTestPlot() + QFont m_zFont; + QString m_zTitle; + QLabel *m_zTitleLabel{nullptr}; + int m_lastNx{0}; + int m_lastNy{0}; +}; + +} // namespace sls \ No newline at end of file diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DZoomer.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DZoomer.h deleted file mode 100644 index e7b72445d..000000000 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DZoomer.h +++ /dev/null @@ -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 -#include -#include - -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 diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQtFastImage.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQtFastImage.h new file mode 100644 index 000000000..a66e68953 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQtFastImage.h @@ -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 +#include +#include +#include +#include +#include +#include + +#include +#include + +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 &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 &rects); + void clearOverlayRects(); + const std::vector &overlayRects() const; + + // Red receiver-ROI rectangle, same data coordinates. + void setReceiverRoiRect(double x0, double y0, double x1, double y1, + bool on = true); + void clearReceiverRoiRect(); + + // ---- ROI editor ------------------------------------------------------- + // While active the yellow ROI is edited with the mouse (inside = move, + // edges/corners = resize, outside = draw a new one) instead of panning. + // onRoiEdited() reports (x0,y0,x1,y1) in data coordinates on release. + void beginRoiEdit(bool on); + bool roiEditActive() const; + + // ---- optional in-view colour bar (the ScalePanel replaces it) --------- + void setColorBarVisible(bool on); + bool colorBarVisible() const; + bool isScaleDragging() const; + + // Axes can be turned off for the gain map, which is a plain 0..3 mosaic + // without ticks (the plot then fills the whole widget). + void setAxesVisible(bool on); + bool axesVisible() const; + // Zoom/pan interaction can be turned off (gain map: fixed range). + void setZoomEnabled(bool on); + bool zoomEnabled() const; + + // ---- 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 onImageChanged; + // reported in data coordinates (x1, y1, x2, y2), y up + std::function onZoomChanged; + std::function onColorRangeChanged; + std::function onPaletteChanged; + // x0, y0, x1, y1 in data coordinates (integers, ROI list convention) + std::function onRoiEdited; + // one histogram/scale refresh, after an in-view colour bar drag + std::function onScaleReleased; + // Called at the end of paintEvent, clipped to the plot rectangle. The + // painter is in widget coordinates and `dataToWidget` maps data + // coordinates (x right, y up) to widget coordinates - use it for contour + // lines, polygons, markers, ... + std::function onPaintOverlay; + + 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 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 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 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 diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQtPlotCommon.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQtPlotCommon.h new file mode 100644 index 000000000..bb66458d2 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQtPlotCommon.h @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +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 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 diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQtScalePanel.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQtScalePanel.h new file mode 100644 index 000000000..616fc5918 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQtScalePanel.h @@ -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 +#include +#include + +#include +#include + +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 *h, double dlo, double dhi, double clo, + double chi, bool logX, bool logY); + + // Drops the raw pointer to the view's histogram vector (and any frozen + // snapshot). Called when the panel detaches from a view or when the view + // is destroyed, so a later repaint cannot read freed memory. + void clearData(); + + // Reports the new mapped range (value space) once, when the button is + // released. + std::function onRangeChanged; + + // ---- test accessors --------------------------------------------------- + bool isDragging() const; + // The live mapped colour range (value space). + void currentWindow(double &lo, double &hi) const; + // The axis window currently shown/painted, in bin space. Frozen while + // dragging. + void displayedWindow(double &lo, double &hi) const; + // The bars currently painted: the press-time snapshot while dragging. + const std::vector *displayedHistogram() const; + int previewX() const; + + 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 *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 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 m_view; + SlsQtScaleHisto *m_histo = nullptr; + QComboBox *m_paletteCombo = nullptr; + QComboBox *m_imageLogCombo = nullptr; + QComboBox *m_histoLogCombo = nullptr; + // The colour range last read from the view (kept for the R1 freeze rule + // and for programmatic/test edits; there are no min/max spin boxes here). + double m_controlLo = 0.0; + double m_controlHi = 1.0; + int m_suppress = 0; + + // R2: only an explicit control edit may push the colour range. Refreshes + // (automatic z range) and palette/log changes only update the controls. + bool m_rangeEdited = false; + bool m_lastPushedValid = false; + double m_lastPushedLo = 0.0; + double m_lastPushedHi = 1.0; + + std::function m_prevImageChanged; + std::function m_prevScaleReleased; + bool m_installed = false; + QMetaObject::Connection m_destroyedConn; +}; + +} // namespace sls diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cpp index 8ae58d4b2..c164b59a7 100644 --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cpp +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cpp @@ -1,656 +1,1607 @@ -// SPDX-License-Identifier: LGPL-3.0-or-other -// Copyright (C) 2021 Contributors to the SLS Detector Package - -/* TODO! short description */ -#include "SlsQt1DPlot.h" -#include "qDefs.h" -#include "qVersionResolve.h" -#include "sls/logger.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace sls { - -#define QwtLog10ScaleEngine QwtLogScaleEngine // hmm - -SlsQtH1D::SlsQtH1D(QString title, int n, double min, double max, double *data) - : QwtPlotCurve(title), x(nullptr), y(nullptr), pen_ptr(nullptr) { - Initailize(); - SetData(n, min, max, data); -} - -SlsQtH1D::SlsQtH1D(QString title, int n, double *data_x, double *data_y) - : QwtPlotCurve(title) { - Initailize(); - SetData(n, data_x, data_y); -} - -void SlsQtH1D::Initailize() { - ndata = n_array = 0; - x = y = nullptr; - pen_ptr = new QPen(); - SetLineColor(); -} - -SlsQtH1D::~SlsQtH1D() { - - delete[] x; - - delete[] y; - - delete pen_ptr; -} - -void SlsQtH1D::Attach(SlsQt1DPlot *p) { - attach((QwtPlot *)p); - p->NewHistogramAttached(this); -} - -void SlsQtH1D::Detach(SlsQt1DPlot *p) { - detach(); - p->HistogramDetached(this); -} - -int SlsQtH1D::SetLineColor(int c) { - static int last_color = 1; - if (c < 0) - c = (last_color + 1) % 3; - - switch (c) { - case 0: - pen_ptr->setColor(Qt::black); - break; - case 1: - pen_ptr->setColor(Qt::red); - break; - case 2: - pen_ptr->setColor(Qt::blue); - break; - case 3: - pen_ptr->setColor(Qt::green); - break; - case 4: - pen_ptr->setColor(Qt::magenta); - break; - case 5: - pen_ptr->setColor(Qt::cyan); - break; - case 6: - pen_ptr->setColor(Qt::darkYellow); - break; - case 7: - pen_ptr->setColor(Qt::gray); - break; - case 8: - pen_ptr->setColor(Qt::darkBlue); - break; - case 9: - pen_ptr->setColor(Qt::darkGreen); - break; - case 10: - pen_ptr->setColor(Qt::darkMagenta); - break; - } - /* if(c==0) pen_ptr->setColor(Qt::black); - else if(c==1) pen_ptr->setColor(Qt::red); - else pen_ptr->setColor(Qt::blue);*/ - - setPen(*pen_ptr); - - return last_color = c; -} - -int SlsQtH1D::SetLineWidth(int w) { - pen_ptr->setWidth(w); - setPen(*pen_ptr); - return w; -} - -void SlsQtH1D::SetLineStyle(int s) { - if (s == 1) - pen_ptr->setStyle(Qt::DashLine); - else if (s == 2) - pen_ptr->setStyle(Qt::DotLine); - else if (s == 3) - pen_ptr->setStyle(Qt::DashDotLine); - else if (s == 4) - pen_ptr->setStyle(Qt::DashDotDotLine); - else if (s == 5) - pen_ptr->setStyle(Qt::CustomDashLine); - else - pen_ptr->setStyle(Qt::SolidLine); - setPen(*pen_ptr); -} - -void SlsQtH1D::setStyleLinesorDots(bool isLines) { - setStyle(isLines ? QwtPlotCurve::Lines : QwtPlotCurve::Dots); -} - -void SlsQtH1D::setSymbolMarkers(bool isMarker) { - QwtSymbol *marker = new QwtSymbol(); - if (isMarker) { - marker->setStyle(QwtSymbol::Cross); - marker->setSize(5, 5); - } - setSymbol(marker); -} - -void SlsQtH1D::SetData(int n, double xmin, double xmax, double *data) { - n = SetUpArrays(n); - - ndata = n; - if (xmin > xmax) { - double t = xmin; - xmin = xmax; - xmax = t; - } - - dx = (xmax - xmin) / n; - ymin = ymax = data ? data[0] : 0; - firstXgt0 = -1; - firstYgt0 = -1; - - for (int i = 0; i < ndata; i++) { - x[i] = i ? x[i - 1] + dx : xmin; - y[i] = data ? data[i] : 0; - if (data && ymin > y[i]) - ymin = y[i]; - if (data && ymax < y[i]) - ymax = y[i]; - if (x[i] > 0 && (firstXgt0 < 0 || firstXgt0 > x[i])) - firstXgt0 = x[i]; - if (y[i] > 0 && (firstYgt0 < 0 || firstYgt0 > y[i])) - firstYgt0 = y[i]; - } - - setRawSamples(x, y, ndata); -} - -void SlsQtH1D::SetData(int n, double *data_x, double *data_y) { - - int reverse = (data_x && n > 0 && data_x[0] > data_x[n - 1]) ? 1 : 0; - n = SetUpArrays(n); - - ndata = n; - dx = -1; // signifies not regular intervals - - ymin = ymax = data_y ? data_y[0] : 0; - - firstXgt0 = -1; - firstYgt0 = -1; - - for (int i = 0; i < ndata; i++) { - int b = reverse ? n - i - 1 : i; - x[b] = data_x ? data_x[i] : 0; - y[b] = data_y ? data_y[i] : 0; - if (data_y && ymin > y[b]) - ymin = y[b]; - if (data_y && ymax < y[b]) - ymax = y[b]; - if (x[b] > 0 && (firstXgt0 < 0 || firstXgt0 > x[b])) - firstXgt0 = x[b]; - if (y[b] > 0 && (firstYgt0 < 0 || firstYgt0 > y[b])) - firstYgt0 = y[b]; - } - setRawSamples(x, y, ndata); -} - -int SlsQtH1D::SetUpArrays(int n) { - n = n < 1 ? 1 : n; // overflow bin - - if (n + 1 > n_array) { - n_array = n + 1; - - delete x; - - delete y; - x = new double[n_array]; - y = new double[n_array]; - } - - return n; -} - -double SlsQtH1D::FillBin(int bx, double v) { - bx = CheckIndex(bx); - return SetBinContent(bx, y[bx] + v); -} -double SlsQtH1D::Fill(double x, double v) { - return FillBin(FindBinIndex(x), v); -} - -double SlsQtH1D::SetBinContent(int bx, double v) { - bx = CheckIndex(bx); - y[bx] = v; - if (bx < ndata) { - if (y[bx] < ymin) - ymin = y[bx]; - if (y[bx] > 0 && (firstYgt0 <= 0 || y[bx] < firstYgt0)) - firstYgt0 = y[bx]; - if (y[bx] > ymax) - ymax = y[bx]; - } - return y[bx]; -} - -double SlsQtH1D::SetContent(double x, double v) { - return SetBinContent(FindBinIndex(x), v); -} - -int SlsQtH1D::FindBinIndex(double px) { - if (dx > 0) - CheckIndex(int((px - x[0]) / dx)); - - // find closest bin - int b = 0; - for (; b < ndata; b++) - if (x[b] > px) - break; - - if (b == 0) - return 0; - else if (fabs(px - x[b - 1]) < fabs(px - x[b])) - return b - 1; - - return b; -} - -int SlsQtH1D::CheckIndex(int bx) { - return (bx < 0 || bx > ndata) ? ndata : bx; -} // ndata is the overflow bin - -SlsQtH1D *SlsQtH1D::Add(double v) { - for (int bx = 0; bx < ndata; bx++) - FillBin(bx, v); - return this; -} - -// 1d hist list stuff -SlsQtH1DList::SlsQtH1DList(SlsQtH1D *hist) { - the_hist = hist; - the_next = nullptr; -} - -SlsQtH1DList::~SlsQtH1DList() { delete the_next; } - -SlsQtH1D *SlsQtH1DList::Add(SlsQtH1D *hist) { - SlsQtH1DList *hl = this; - - while (hl) { - if (hist == hl->the_hist) - return hist; // already added - if (!hl->the_next) - break; - hl = hl->the_next; - } - if (hl->the_hist) - hl->the_next = new SlsQtH1DList(hist); - else - hl->the_hist = hist; - - // Print(); - - return hist; -} - -void SlsQtH1DList::Print() { - SlsQtH1DList *hl = this; - int i = 0; - while (hl) { - std::cout << " " << i++ << ") " << hl << " " << hl->the_hist << " " - << hl->the_next << '\n'; - hl = hl->the_next; - if (i > 10) - break; - } -} - -void SlsQtH1DList::Remove(SlsQtH1D *hist) { - SlsQtH1DList *hl = this; - while (hl) { // every match will be removed - if (hl->the_hist != hist) - hl = hl->the_next; - else { // match - if (!hl->the_next) - hl->the_hist = - nullptr; // first the_hist is zero when there's no next - else { - SlsQtH1DList *t = hl->the_next; - hl->the_hist = t->the_hist; - hl->the_next = t->the_next; - t->the_next = nullptr; - delete t; - } - } - } -} - -// 1d plot stuff -SlsQt1DPlot::SlsQt1DPlot(QWidget *parent, bool gain) - : QwtPlot(parent), gainPlot(gain) { - // n_histograms_attached=0; - hline = vline = nullptr; - hist_list = new SlsQtH1DList(); - - UnknownStuff(); - alignScales(); - SetupZoom(); - - // Assign a title -#ifndef IAN - insertLegend(new QwtLegend(), QwtPlot::BottomLegend); -#else - insertLegend(new QwtLegend(), QwtPlot::RightLegend); -#endif - - axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); - axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); - setFont(qDefs::GetDefaultFont()); - SetTitleFont(qDefs::GetDefaultFont()); - SetXFont(qDefs::GetDefaultFont()); - SetYFont(qDefs::GetDefaultFont()); - - if (gainPlot) { - SetTitle(""); - SetYTitle("Gain"); - DisableZoom(true); - // set only major ticks from 0 to 3 - auto div = axisScaleEngine(QwtPlot::yLeft)->divideScale(0, 3, 3, 0, 1); - setAxisScaleDiv(QwtPlot::yLeft, div); - } -} - -SlsQt1DPlot::~SlsQt1DPlot() { - - delete hist_list; - - delete hline; - - delete vline; - - delete zoomer; - - delete panner; -} - -void SlsQt1DPlot::CalculateNResetZoomBase() { - if (hist_list->Hist()) - zoomer->SetZoomBase(hist_list->Hist()); - SlsQtH1DList *hl = hist_list->Next(); - while (hl) { - if (hl->Hist()) - zoomer->ExtendZoomBase(hl->Hist()); - hl = hl->Next(); - } -} - -void SlsQt1DPlot::NewHistogramAttached(SlsQtH1D *h) { - hist_list->Add(h); - CalculateNResetZoomBase(); - // commented out by dhanya to take off zooming every hist in 1d plots - // if(!hist_list->Next()) UnZoom(); - Update(); -} - -void SlsQt1DPlot::HistogramDetached(SlsQtH1D *h) { - hist_list->Remove(h); - CalculateNResetZoomBase(); - Update(); -} - -void SlsQt1DPlot::Update() { replot(); } - -void SlsQt1DPlot::SetTitle(QString title) { setTitle(title); } - -void SlsQt1DPlot::SetXTitle(QString title) { - setAxisTitle(QwtPlot::xBottom, title); -} - -void SlsQt1DPlot::SetYTitle(QString title) { - setAxisTitle(QwtPlot::yLeft, title); -} - -void SlsQt1DPlot::SetTitleFont(const QFont &f) { - QwtText t(""); - t.setFont(f); - t.setRenderFlags(Qt::AlignLeft | Qt::AlignVCenter); - setTitle(t); -} - -void SlsQt1DPlot::SetXFont(const QFont &f) { - QwtText t(""); - t.setFont(f); - setAxisTitle(QwtPlot::xBottom, t); -} - -void SlsQt1DPlot::SetYFont(const QFont &f) { - QwtText t(""); - t.setFont(f); - setAxisTitle(QwtPlot::yLeft, t); -} - -void SlsQt1DPlot::SetLogX(bool yes) { SetLog(QwtPlot::xBottom, yes); } -void SlsQt1DPlot::SetLogY(bool yes) { SetLog(QwtPlot::yLeft, yes); } -void SlsQt1DPlot::SetLog(int axisId, bool yes) { - if (axisId == QwtPlot::xBottom) - zoomer->SetLogX(yes); - if (axisId == QwtPlot::yLeft) - zoomer->SetLogY(yes); - - zoomer->ResetZoomBase(); // needs to be done before setting Engine - - // the old ones are deleted by in the setAxisScaleFunction() function see: - // 128 of file qwt_plot_axis.cpp - if (yes) - setAxisScaleEngine(axisId, new QwtLog10ScaleEngine()); - else - setAxisScaleEngine(axisId, new QwtLinearScaleEngine()); - - axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); - axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); - - Update(); -} - -void SlsQt1DPlot::EnableRoiBoxes(std::vector roi, - int ymin, int ymax) { - roiBoxes.clear(); - for (auto &r : roi) { - auto box = std::make_unique(); - box->setPen(QColor(Qt::yellow), 2.0, Qt::SolidLine); - // TopLeft - BottomRight (max points are +1 on graph) - QRectF myRect(QPointF(r.xmin, ymin), QPointF(r.xmax - 1, ymax - 1)); - box->setRect(myRect); - box->attach(this); - roiBoxes.push_back(std::move(box)); - } - replot(); -} - -void SlsQt1DPlot::DisableRoiBoxes() { - for (auto &r : roiBoxes) { - r->detach(); - } - replot(); -} - -void SlsQt1DPlot::SetZoomX(const QRectF &rect) { - double xmin = 0, xmax = 0, ymin = 0, ymax = 0; - rect.getCoords(&xmin, &ymin, &xmax, &ymax); - LOG(logDEBUG1) << "Zoomed in at " << xmin << "\t" << xmax << "\t" << ymin - << "\t" << ymax; - SetXMinMax(xmin, xmax); - // SetYMinMax(ymin, ymax); - replot(); -} - -void SlsQt1DPlot::UnZoom() { - setAxisScale(QwtPlot::xBottom, zoomer->x(), zoomer->x() + zoomer->w()); - setAxisScale(QwtPlot::yLeft, zoomer->y(), zoomer->y() + zoomer->h()); - - zoomer->setZoomBase(); // Call replot for the attached plot before - // initializing the zoomer with its scales. - Update(); -} - -void SlsQt1DPlot::SetZoom(double xmin, double ymin, double x_width, - double y_width) { - setAxisScale(QwtPlot::xBottom, xmin, xmin + x_width); - setAxisScale(QwtPlot::yLeft, ymin, ymin + y_width); - Update(); -} - -void SlsQt1DPlot::GetPannedCoord(int, int) { - double xmin = invTransform(QwtPlot::xBottom, 0); - double xmax = invTransform(QwtPlot::xBottom, canvas()->rect().width()); - double ymax = invTransform(QwtPlot::yLeft, 0); - double ymin = invTransform(QwtPlot::yLeft, canvas()->rect().height()); - LOG(logDEBUG1) << "Rect1 " << xmin << "\t" << xmax << "\t" << ymin << "\t" - << ymax; - QPointF topLeft = QPointF(xmin, ymin); - QPointF bottomRight = QPointF(xmax, ymax); - const QRectF rectf = QRectF(topLeft, bottomRight); - rectf.getCoords(&xmin, &ymin, &xmax, &ymax); - LOG(logDEBUG1) << "RectF " << xmin << "\t" << xmax << "\t" << ymin << "\t" - << ymax; - emit PlotZoomedSignal(rectf); -} - -void SlsQt1DPlot::RemoveHLine() { - if (hline) - hline->detach(); - delete hline; - hline = nullptr; -} - -void SlsQt1DPlot::InsertHLine(double y) { - if (!hline) { - hline = new QwtPlotMarker(); - hline->setLabelAlignment(Qt::AlignRight | Qt::AlignTop); - hline->setLineStyle(QwtPlotMarker::HLine); - hline->attach(this); - } - hline->setYValue(y); -} - -void SlsQt1DPlot::RemoveVLine() { - if (vline) - vline->detach(); - delete vline; - vline = nullptr; -} - -void SlsQt1DPlot::InsertVLine(double x) { - if (!vline) { - vline = new QwtPlotMarker(); - vline->setLabelAlignment(Qt::AlignRight | Qt::AlignTop); - vline->setLineStyle(QwtPlotMarker::VLine); - vline->attach(this); - } - vline->setXValue(x); -} - -void SlsQt1DPlot::SetupZoom() { - // LeftButton for the zooming - // MiddleButton for the panning - // RightButton: zoom out by 1 - // Ctrl+RighButton: zoom out to full size - - zoomer = new SlsQt1DZoomer(canvas()); - zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, - Qt::ControlModifier); - - zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); - - panner = new QwtPlotPanner((QwtPlotCanvas *)canvas()); - panner->setAxisEnabled(QwtPlot::yRight, false); - panner->setMouseButton(Qt::MiddleButton); - - // Avoid jumping when labels with more/less digits - // appear/disappear when scrolling vertically - - const QFontMetrics fm(axisWidget(QwtPlot::yLeft)->font()); - QwtScaleDraw *sd = axisScaleDraw(QwtPlot::yLeft); - sd->setMinimumExtent(qResolve_GetQFontWidth(fm, "100.00")); - const QColor c(Qt::darkBlue); - zoomer->setRubberBandPen(c); - zoomer->setTrackerPen(c); - - connect(zoomer, SIGNAL(zoomed(const QRectF &)), this, - SIGNAL(PlotZoomedSignal(const QRectF &))); - connect(panner, SIGNAL(panned(int, int)), this, - SLOT(GetPannedCoord(int, int))); -} - -// Set a plain canvas frame and align the scales to it -void SlsQt1DPlot::alignScales() { - // The code below shows how to align the scales to - // the canvas frame, but is also a good example demonstrating - // why the spreaded API needs polishing. - - ((QwtPlotCanvas *)canvas())->setFrameStyle(QFrame::Box | QFrame::Plain); - ((QwtPlotCanvas *)canvas())->setLineWidth(1); - - for (int i = 0; i < QwtPlot::axisCnt; i++) { - QwtScaleWidget *scaleWidget = (QwtScaleWidget *)axisWidget(i); - if (scaleWidget) - scaleWidget->setMargin(0); - QwtScaleDraw *scaleDraw = (QwtScaleDraw *)axisScaleDraw(i); - if (scaleDraw) - scaleDraw->enableComponent(QwtAbstractScaleDraw::Backbone, false); - } -} - -void SlsQt1DPlot::UnknownStuff() { - // We don't need the cache here - ((QwtPlotCanvas *)canvas()) - ->setPaintAttribute(QwtPlotCanvas::BackingStore, false); -#ifdef Q_WS_X11 - // Qt::WA_PaintOnScreen is only supported for X11, but leads - // to substantial bugs with Qt 4.2.x/Windows - canvas()->setAttribute(Qt::WA_PaintOnScreen, true); -#endif -} - -// Added by Dhanya on 19.06.2012 to disable zooming when any of the axes range -// has been set -void SlsQt1DPlot::DisableZoom(bool disable) { - if (disableZoom != disable) { - disableZoom = disable; - if (disable) { - if (zoomer) { - zoomer->setMousePattern(QwtEventPattern::MouseSelect1, - Qt::NoButton); - zoomer->setMousePattern(QwtEventPattern::MouseSelect2, - Qt::NoButton, Qt::ControlModifier); - zoomer->setMousePattern(QwtEventPattern::MouseSelect3, - Qt::NoButton); - } - if (panner) - panner->setMouseButton(Qt::NoButton); - } else { - if (zoomer) { - zoomer->setMousePattern(QwtEventPattern::MouseSelect1, - Qt::LeftButton); - zoomer->setMousePattern(QwtEventPattern::MouseSelect2, - Qt::RightButton, Qt::ControlModifier); - zoomer->setMousePattern(QwtEventPattern::MouseSelect3, - Qt::RightButton); - } - if (panner) - panner->setMouseButton(Qt::MiddleButton); - } - } -} - -} // namespace sls +// SPDX-License-Identifier: LGPL-3.0-or-other +// Copyright (C) 2026 Contributors to the SLS Detector Package + +// Custom Qt6 painting based 1D plot. See SlsQt1DPlot.h for the contract. + +#include "SlsQt1DPlot.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace sls { + +namespace { + +constexpr int kTickLen = 4; +constexpr double kMinSpan = 1e-9; +constexpr double kPixelClamp = 1.0e6; + +// Colours of SlsQtH1D::SetLineColor(). The original qwt plot had a white +// canvas; the new plotting stack uses the shared dark theme, so the first +// colour (black in the qwt version) and the dark variants are mapped to +// bright equivalents so that a curve is never invisible on the background. +QColor lineColorForIndex(int c) { + switch (c) { + case 0: + return QColor(Qt::white); + case 1: + return QColor(Qt::red); + case 2: + return QColor(Qt::blue); + case 3: + return QColor(Qt::green); + case 4: + return QColor(Qt::magenta); + case 5: + return QColor(Qt::cyan); + case 6: + return QColor(220, 200, 40); // dark yellow + case 7: + return QColor(190, 190, 190); // gray + case 8: + return QColor(110, 160, 255); // dark blue, lightened + case 9: + return QColor(90, 210, 130); // dark green, lightened + case 10: + return QColor(230, 130, 230); // dark magenta, lightened + default: + return QColor(Qt::white); + } +} + +QRectF rectFromRanges(double xLo, double xHi, double yLo, double yHi) { + return QRectF(xLo, yLo, xHi - xLo, yHi - yLo); +} + +QString formatValue(double v) { return QString::number(v, 'g', 5); } + +} // namespace + +// --------------------------------------------------------------------------- +// SlsQtH1D +// --------------------------------------------------------------------------- + +SlsQtH1D::SlsQtH1D(QString title, int n, double xmin, double xmax, double *data) + : m_title(std::move(title)) { + initialize(); + SetData(n, xmin, xmax, data); +} + +SlsQtH1D::SlsQtH1D(QString title, int n, double *data_x, double *data_y) + : m_title(std::move(title)) { + initialize(); + SetData(n, data_x, data_y); +} + +SlsQtH1D::~SlsQtH1D() { + if (m_plot) + m_plot->removeHistogram(this); +} + +void SlsQtH1D::initialize() { + m_ndata = 0; + m_dx = 0.0; + m_pen = QPen(); + SetLineColor(); +} + +void SlsQtH1D::Attach(SlsQt1DPlot *p) { + if (!p) + return; + if (m_plot == p) + return; + if (m_plot) + m_plot->removeHistogram(this); + m_plot = p; + p->addHistogram(this); +} + +void SlsQtH1D::Detach(SlsQt1DPlot *p) { + (void)p; + if (m_plot) { + SlsQt1DPlot *plot = m_plot; + m_plot = nullptr; + plot->removeHistogram(this); + } +} + +int SlsQtH1D::SetLineColor(int c) { + static int last_color = 1; + if (c < 0) + c = (last_color + 1) % 3; + m_pen.setColor(lineColorForIndex(c)); + last_color = c; + return c; +} + +int SlsQtH1D::SetLineWidth(int w) { + m_pen.setWidth(w); + return w; +} + +void SlsQtH1D::SetLineStyle(int s) { + switch (s) { + case 1: + m_pen.setStyle(Qt::DashLine); + break; + case 2: + m_pen.setStyle(Qt::DotLine); + break; + case 3: + m_pen.setStyle(Qt::DashDotLine); + break; + case 4: + m_pen.setStyle(Qt::DashDotDotLine); + break; + case 5: + m_pen.setStyle(Qt::CustomDashLine); + break; + default: + m_pen.setStyle(Qt::SolidLine); + break; + } +} + +void SlsQtH1D::setStyleLinesorDots(bool isLines) { m_linesMode = isLines; } + +void SlsQtH1D::setSymbolMarkers(bool isMarker) { m_markerMode = isMarker; } + +void SlsQtH1D::SetData(int n, double xmin, double xmax, double *data) { + setUpArrays(n); + m_ndata = n; + if (xmin > xmax) + std::swap(xmin, xmax); + // Deliberately divided by n (not n-1): the old qwt code defined the bins + // this way and the GUI/ROI mapping depends on it. + m_dx = (xmax - xmin) / n; + m_ymin = m_ymax = data ? data[0] : 0.0; + m_firstXgt0 = -1.0; + m_firstYgt0 = -1.0; + for (int i = 0; i < m_ndata; ++i) { + const double xv = i ? m_x[static_cast(i - 1)] + m_dx : xmin; + m_x[static_cast(i)] = xv; + m_y[static_cast(i)] = data ? data[i] : 0.0; + const double yv = m_y[static_cast(i)]; + if (data && m_ymin > yv) + m_ymin = yv; + if (data && m_ymax < yv) + m_ymax = yv; + if (xv > 0 && (m_firstXgt0 < 0 || m_firstXgt0 > xv)) + m_firstXgt0 = xv; + if (yv > 0 && (m_firstYgt0 < 0 || m_firstYgt0 > yv)) + m_firstYgt0 = yv; + } +} + +void SlsQtH1D::SetData(int n, double *data_x, double *data_y) { + const int reverse = + (data_x && n > 0 && data_x[0] > data_x[n - 1]) ? 1 : 0; + setUpArrays(n); + m_ndata = n; + m_dx = -1.0; // not regular intervals + m_ymin = m_ymax = data_y ? data_y[0] : 0.0; + m_firstXgt0 = -1.0; + m_firstYgt0 = -1.0; + for (int i = 0; i < m_ndata; ++i) { + const int b = reverse ? n - i - 1 : i; + m_x[static_cast(b)] = data_x ? data_x[i] : 0.0; + m_y[static_cast(b)] = data_y ? data_y[i] : 0.0; + const double xv = m_x[static_cast(b)]; + const double yv = m_y[static_cast(b)]; + if (data_y && m_ymin > yv) + m_ymin = yv; + if (data_y && m_ymax < yv) + m_ymax = yv; + if (xv > 0 && (m_firstXgt0 < 0 || m_firstXgt0 > xv)) + m_firstXgt0 = xv; + if (yv > 0 && (m_firstYgt0 < 0 || m_firstYgt0 > yv)) + m_firstYgt0 = yv; + } +} + +void SlsQtH1D::setUpArrays(int n) { + n = n < 1 ? 1 : n; // overflow bin + m_x.assign(static_cast(n) + 1, 0.0); + m_y.assign(static_cast(n) + 1, 0.0); +} + +int SlsQtH1D::checkIndex(int bx) { + return (bx < 0 || bx > m_ndata) ? m_ndata : bx; +} + +double SlsQtH1D::FillBin(int bx, double v) { + bx = checkIndex(bx); + return SetBinContent(bx, m_y[static_cast(bx)] + v); +} + +double SlsQtH1D::Fill(double x, double v) { return FillBin(FindBinIndex(x), v); } + +double SlsQtH1D::SetBinContent(int bx, double v) { + bx = checkIndex(bx); + m_y[static_cast(bx)] = v; + if (bx < m_ndata) { + if (m_y[static_cast(bx)] < m_ymin) + m_ymin = m_y[static_cast(bx)]; + if (m_y[static_cast(bx)] > 0 && + (m_firstYgt0 <= 0 || m_y[static_cast(bx)] < m_firstYgt0)) + m_firstYgt0 = m_y[static_cast(bx)]; + if (m_y[static_cast(bx)] > m_ymax) + m_ymax = m_y[static_cast(bx)]; + } + return m_y[static_cast(bx)]; +} + +double SlsQtH1D::SetContent(double x, double v) { + return SetBinContent(FindBinIndex(x), v); +} + +int SlsQtH1D::FindBinIndex(double px) { + int b = 0; + for (; b < m_ndata; b++) { + if (m_x[static_cast(b)] > px) + break; + } + if (b == 0) + return 0; + if (std::fabs(px - m_x[static_cast(b - 1)]) < + std::fabs(px - m_x[static_cast(b)])) + return b - 1; + return b; +} + +SlsQtH1D *SlsQtH1D::Add(double v) { + for (int bx = 0; bx < m_ndata; bx++) + FillBin(bx, v); + return this; +} + +// --------------------------------------------------------------------------- +// SlsQt1DPlot - construction / state +// --------------------------------------------------------------------------- + +SlsQt1DPlot::SlsQt1DPlot(QWidget *parent, bool gain) + : QWidget(parent), m_gainPlot(gain) { + setAttribute(Qt::WA_OpaquePaintEvent, true); + setMouseTracking(true); + setFocusPolicy(Qt::StrongFocus); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + setMinimumSize(40, 30); + setAutoFillBackground(false); + + m_theme = sls::plot::PlotTheme(); + m_titleFont = QFont(); + m_xTitleFont = QFont(); + m_yTitleFont = QFont(); + m_tickFont = m_theme.tickFont; + + if (m_gainPlot) { + m_yAuto = false; + m_disableZoom = true; + m_title.clear(); + m_yTitle = QStringLiteral("Gain"); + } + + recomputeBase(); + m_zoomStack.clear(); + m_zoomStack.push_back(baseRect()); + m_zoomIndex = 0; +} + +SlsQt1DPlot::~SlsQt1DPlot() { + for (SlsQtH1D *h : m_hists) { + if (h) + h->m_plot = nullptr; + } + m_hists.clear(); +} + +void SlsQt1DPlot::addHistogram(SlsQtH1D *h) { + if (!h) + return; + if (std::find(m_hists.begin(), m_hists.end(), h) == m_hists.end()) + m_hists.push_back(h); + recomputeBase(); + update(); +} + +void SlsQt1DPlot::removeHistogram(SlsQtH1D *h) { + const auto it = std::find(m_hists.begin(), m_hists.end(), h); + if (it != m_hists.end()) + m_hists.erase(it); + recomputeBase(); + update(); +} + +void SlsQt1DPlot::recomputeBase() { + bool have = false; + double xmin = 0.0, xmax = 0.0, ymin = 0.0, ymax = 0.0; + double firstX = -1.0, firstY = -1.0; + for (SlsQtH1D *h : m_hists) { + if (!h || h->GetNBinsX() <= 0) + continue; + const double hx0 = h->GetXMin(); + const double hx1 = h->GetXMax(); + const double hy0 = h->GetYMin(); + const double hy1 = h->GetYMax(); + if (!std::isfinite(hx0) || !std::isfinite(hx1) || + !std::isfinite(hy0) || !std::isfinite(hy1)) + continue; + if (!have) { + xmin = hx0; + xmax = hx1; + ymin = hy0; + ymax = hy1; + have = true; + } else { + xmin = std::min(xmin, hx0); + xmax = std::max(xmax, hx1); + ymin = std::min(ymin, hy0); + ymax = std::max(ymax, hy1); + } + const double fx = h->GetFirstXgtZero(); + if (fx > 0 && (firstX < 0 || fx < firstX)) + firstX = fx; + const double fy = h->GetFirstYgtZero(); + if (fy > 0 && (firstY < 0 || fy < firstY)) + firstY = fy; + } + + if (!have) { + m_bxLo = 0.0; + m_bxHi = 1.0; + m_byLo = 0.0; + m_byHi = 1.0; + } else { + const auto padLo = [](double v) { return v < 0 ? v * 1.02 : v / 1.02; }; + const auto padHi = [](double v) { return v < 0 ? v / 1.02 : v * 1.02; }; + m_bxLo = padLo(xmin); + m_bxHi = padHi(xmax); + m_byLo = padLo(ymin); + m_byHi = padHi(ymax); + + if (m_logX) { + if (!(m_bxLo > 0.0)) + m_bxLo = (firstX > 0) ? firstX * 0.98 : 1e-2; + if (!(m_bxHi > m_bxLo)) + m_bxHi = m_bxLo * 10.0; + } else if (!(m_bxHi > m_bxLo)) { + const double c = m_bxLo; + m_bxLo = c - 1.0; + m_bxHi = c + 1.0; + } + + if (m_gainPlot) { + m_byLo = 0.0; + m_byHi = 3.0; + } else if (m_logY) { + // The y axis is logarithmic, so the auto-range padding must be + // done in log10 space. Padding the linear value (the old + // ymax * 1.02) only adds ~0.0086 decades, i.e. ~1.5 px on a + // multi-decade plot, which leaves the peak glued to the top frame + // (observable on the white curve vs. the white frame). Pad each + // side by 2% of the visible decade span instead. + const double yLo = + (ymin > 0.0) ? ymin : ((firstY > 0.0) ? firstY : 1e-2); + double yHi = (ymax > 0.0) ? ymax : yLo; + double logLo = std::log10(yLo); + double logHi = std::log10(yHi); + if (!(logHi > logLo)) + logHi = logLo + 1.0; // flat/degenerate log data: one decade + const double pad = 0.02 * (logHi - logLo); + m_byLo = std::pow(10.0, logLo - pad); + m_byHi = std::pow(10.0, logHi + pad); + if (!std::isfinite(m_byLo) || !(m_byLo > 0.0)) + m_byLo = yLo * 0.98; + if (!std::isfinite(m_byHi) || !(m_byHi > m_byLo)) + m_byHi = m_byLo * 10.0; + } else if (!(m_byHi > m_byLo)) { + const double c = m_byLo; + m_byLo = c - 1.0; + m_byHi = c + 1.0; + } + } + + if (m_xAuto) { + m_xLo = m_bxLo; + m_xHi = m_bxHi; + } + if (m_gainPlot) { + m_yLo = 0.0; + m_yHi = 3.0; + } else if (m_yAuto) { + m_yLo = m_byLo; + m_yHi = m_byHi; + } + clampView(); + // Keep the bottom of the zoom stack (the "full view") in sync with the + // data range; qwt's zoomer did this through setZoomBase() as well. + if (!m_zoomStack.empty()) + m_zoomStack.front() = baseRect(); +} + +void SlsQt1DPlot::clampView() { + if (!std::isfinite(m_xLo) || !std::isfinite(m_xHi)) { + m_xLo = m_bxLo; + m_xHi = m_bxHi; + } + if (m_logX) { + if (!(m_xLo > 0.0)) + m_xLo = 1e-3; + if (!(m_xHi > m_xLo)) + m_xHi = m_xLo * 10.0; + } else if (!(m_xHi > m_xLo)) { + const double c = m_xLo; + m_xLo = c - 1.0; + m_xHi = c + 1.0; + } + + if (m_gainPlot) { + m_yLo = 0.0; + m_yHi = 3.0; + return; + } + if (!std::isfinite(m_yLo) || !std::isfinite(m_yHi)) { + m_yLo = m_byLo; + m_yHi = m_byHi; + } + if (m_logY) { + if (!(m_yLo > 0.0)) + m_yLo = 1e-3; + if (!(m_yHi > m_yLo)) + m_yHi = m_yLo * 10.0; + } else if (!(m_yHi > m_yLo)) { + const double c = m_yLo; + m_yLo = c - 1.0; + m_yHi = c + 1.0; + } +} + +void SlsQt1DPlot::setView(double xLo, double xHi, double yLo, double yHi) { + if (xLo > xHi) + std::swap(xLo, xHi); + if (yLo > yHi) + std::swap(yLo, yHi); + m_xLo = xLo; + m_xHi = xHi; + m_yLo = yLo; + m_yHi = yHi; + clampView(); +} + +QRectF SlsQt1DPlot::baseRect() const { + return rectFromRanges(m_bxLo, m_bxHi, m_byLo, m_byHi); +} + +QRectF SlsQt1DPlot::currentRect() const { + return rectFromRanges(m_xLo, m_xHi, m_yLo, m_yHi); +} + +QRectF SlsQt1DPlot::viewRect() const { return currentRect(); } + +void SlsQt1DPlot::emitZoomed() { emit PlotZoomedSignal(currentRect()); } + +double SlsQt1DPlot::tx(double v) const { + if (m_logX) + return std::log10(v > 1e-12 ? v : 1e-12); + return v; +} + +double SlsQt1DPlot::ty(double v) const { + if (m_logY) + return std::log10(v > 1e-12 ? v : 1e-12); + return v; +} + +double SlsQt1DPlot::itx(double t) const { + if (m_logX) + return std::pow(10.0, t); + return t; +} + +double SlsQt1DPlot::ity(double t) const { + if (m_logY) + return std::pow(10.0, t); + return t; +} + +QPointF SlsQt1DPlot::toWidget(double x, double y, const Geometry &g) const { + const double xl = tx(m_xLo); + const double xh = tx(m_xHi); + const double yl = ty(m_yLo); + const double yh = ty(m_yHi); + // Map the axis limits onto the first/last INSIDE pixel of the plot + // rectangle (not one past the right/bottom edge or one above the top + // edge): a tick exactly at an axis limit must stay inside and be drawn. + double px = g.plot.left(); + double py = g.plot.bottom(); + if (xh > xl && g.plot.width() > 1) + px += (tx(x) - xl) / (xh - xl) * (g.plot.width() - 1); + if (yh > yl && g.plot.height() > 1) + py -= (ty(y) - yl) / (yh - yl) * (g.plot.height() - 1); + px = std::max(-kPixelClamp, std::min(kPixelClamp, px)); + py = std::max(-kPixelClamp, std::min(kPixelClamp, py)); + return QPointF(px, py); +} + +QPointF SlsQt1DPlot::toData(const QPointF &pos, const Geometry &g) const { + const double xl = tx(m_xLo); + const double xh = tx(m_xHi); + const double yl = ty(m_yLo); + const double yh = ty(m_yHi); + const double fx = + g.plot.width() > 1 ? (pos.x() - g.plot.left()) / (g.plot.width() - 1) + : 0.0; + const double fy = + g.plot.height() > 1 ? (g.plot.bottom() - pos.y()) / (g.plot.height() - 1) + : 0.0; + return QPointF(itx(xl + (xh - xl) * fx), ity(yl + (yh - yl) * fy)); +} + +// --------------------------------------------------------------------------- +// SlsQt1DPlot - public API +// --------------------------------------------------------------------------- + +void SlsQt1DPlot::SetTitle(QString title) { + m_title = std::move(title); + update(); +} + +void SlsQt1DPlot::SetXTitle(QString title) { + m_xTitle = std::move(title); + update(); +} + +void SlsQt1DPlot::SetYTitle(QString title) { + m_yTitle = std::move(title); + update(); +} + +void SlsQt1DPlot::SetTitleFont(const QFont &f) { + m_titleFont = f; + update(); +} + +void SlsQt1DPlot::SetXFont(const QFont &f) { + m_xTitleFont = f; + update(); +} + +void SlsQt1DPlot::SetYFont(const QFont &f) { + m_yTitleFont = f; + update(); +} + +void SlsQt1DPlot::InsertHLine(double y) { + m_hasHLine = true; + m_hLine = y; + update(); +} + +void SlsQt1DPlot::RemoveHLine() { + m_hasHLine = false; + update(); +} + +void SlsQt1DPlot::InsertVLine(double v) { + m_hasVLine = true; + m_vLine = v; + update(); +} + +void SlsQt1DPlot::RemoveVLine() { + m_hasVLine = false; + update(); +} + +void SlsQt1DPlot::DisableZoom(bool disable) { + if (m_gainPlot) + disable = true; // the gain plot never zooms + if (m_disableZoom == disable) + return; + m_disableZoom = disable; + if (disable) { + m_rubberBand = false; + m_panning = false; + unsetCursor(); + } + update(); +} + +void SlsQt1DPlot::EnableXAutoScaling() { + m_xAuto = true; + recomputeBase(); + update(); +} + +void SlsQt1DPlot::EnableYAutoScaling() { + if (m_gainPlot) + return; + m_yAuto = true; + recomputeBase(); + update(); +} + +void SlsQt1DPlot::SetXMinMax(double min, double max) { + if (min > max) + std::swap(min, max); + m_xAuto = false; + m_xLo = min; + m_xHi = max; + clampView(); + update(); +} + +void SlsQt1DPlot::SetYMinMax(double min, double max) { + if (m_gainPlot) + return; + if (min > max) + std::swap(min, max); + m_yAuto = false; + m_yLo = min; + m_yHi = max; + clampView(); + update(); +} + +double SlsQt1DPlot::GetXMinimum() const { + if (!m_hists.empty() && m_hists.front()) + return m_hists.front()->GetXMin(); + return m_bxLo; +} + +double SlsQt1DPlot::GetXMaximum() const { + if (!m_hists.empty() && m_hists.front()) + return m_hists.front()->GetXMax(); + return m_bxHi; +} + +double SlsQt1DPlot::GetYMinimum() const { + if (!m_hists.empty() && m_hists.front()) + return m_hists.front()->GetYMin(); + return m_byLo; +} + +double SlsQt1DPlot::GetYMaximum() const { + if (!m_hists.empty() && m_hists.front()) + return m_hists.front()->GetYMax(); + return m_byHi; +} + +void SlsQt1DPlot::SetZoom(double xmin, double ymin, double x_width, + double y_width) { + if (!(x_width > 0.0)) + x_width = 1.0; + if (!(y_width > 0.0)) + y_width = 1.0; + m_xAuto = false; + if (!m_gainPlot) + m_yAuto = false; + setView(xmin, xmin + x_width, ymin, ymin + y_width); + update(); +} + +void SlsQt1DPlot::SetZoomBase(double xmin, double ymin, double x_width, + double y_width) { + if (!(x_width > 0.0)) + x_width = 1.0; + if (!(y_width > 0.0)) + y_width = 1.0; + m_bxLo = xmin; + m_bxHi = xmin + x_width; + m_byLo = ymin; + m_byHi = ymin + y_width; + if (m_logX) { + if (!(m_bxLo > 0.0)) + m_bxLo = 1e-2; + if (!(m_bxHi > m_bxLo)) + m_bxHi = m_bxLo * 10.0; + } + if (m_gainPlot) { + m_byLo = 0.0; + m_byHi = 3.0; + } else if (m_logY) { + if (!(m_byLo > 0.0)) + m_byLo = 1e-2; + if (!(m_byHi > m_byLo)) + m_byHi = m_byLo * 10.0; + } + if (m_xAuto) { + m_xLo = m_bxLo; + m_xHi = m_bxHi; + } + if (m_gainPlot) { + m_yLo = 0.0; + m_yHi = 3.0; + } else if (m_yAuto) { + m_yLo = m_byLo; + m_yHi = m_byHi; + } + clampView(); + m_zoomStack.clear(); + m_zoomStack.push_back(baseRect()); + m_zoomIndex = 0; + update(); +} + +void SlsQt1DPlot::alignScales() { + // Kept for API compatibility. The custom painter aligns the frame and the + // tick labels itself; there are no qwt scale widgets to align. +} + +void SlsQt1DPlot::SetLogX(bool yes) { + if (m_logX == yes) + return; + m_logX = yes; + if (yes && !(m_xLo > 0.0)) + m_xAuto = true; + recomputeBase(); + clampView(); + m_zoomStack.clear(); + m_zoomStack.push_back(baseRect()); + m_zoomIndex = 0; + update(); +} + +void SlsQt1DPlot::SetLogY(bool yes) { + if (m_gainPlot || m_logY == yes) + return; + m_logY = yes; + if (yes && !(m_yLo > 0.0)) + m_yAuto = true; + recomputeBase(); + clampView(); + m_zoomStack.clear(); + m_zoomStack.push_back(baseRect()); + m_zoomIndex = 0; + update(); +} + +void SlsQt1DPlot::EnableRoiBoxes(std::vector roi, + int ymin, int ymax) { + m_rois = std::move(roi); + m_roiYMin = ymin; + m_roiYMax = ymax; + m_roiOn = !m_rois.empty(); + update(); +} + +void SlsQt1DPlot::DisableRoiBoxes() { + m_rois.clear(); + m_roiOn = false; + update(); +} + +void SlsQt1DPlot::SetZoomX(const QRectF &rect) { + double x0 = 0.0, y0 = 0.0, x1 = 0.0, y1 = 0.0; + rect.getCoords(&x0, &y0, &x1, &y1); + (void)y0; + (void)y1; + if (!std::isfinite(x0) || !std::isfinite(x1)) + return; + if (x0 > x1) + std::swap(x0, x1); + m_xAuto = false; + m_xLo = x0; + m_xHi = x1; + clampView(); + update(); +} + +void SlsQt1DPlot::UnZoom() { + resetZoom(true); + update(); +} + +void SlsQt1DPlot::Update() { + recomputeBase(); + update(); +} + +void SlsQt1DPlot::resetZoom(bool emitSignal) { + m_zoomStack.clear(); + m_zoomStack.push_back(baseRect()); + m_zoomIndex = 0; + applyZoomRect(baseRect()); + if (m_gainPlot) { + m_yLo = 0.0; + m_yHi = 3.0; + } + if (emitSignal) + emitZoomed(); + update(); +} + +void SlsQt1DPlot::zoomOutOneLevel() { + if (m_zoomIndex <= 0 || m_zoomStack.empty()) + return; + --m_zoomIndex; + applyZoomRect(m_zoomStack[static_cast(m_zoomIndex)]); + if (m_gainPlot) { + m_yLo = 0.0; + m_yHi = 3.0; + } + emitZoomed(); + update(); +} + +void SlsQt1DPlot::applyZoomRect(const QRectF &rect) { + double x0 = 0.0, y0 = 0.0, x1 = 0.0, y1 = 0.0; + rect.getCoords(&x0, &y0, &x1, &y1); + if (!std::isfinite(x0) || !std::isfinite(x1) || !std::isfinite(y0) || + !std::isfinite(y1)) + return; + setView(x0, x1, y0, y1); +} + +void SlsQt1DPlot::pushZoomRect(const QRectF &rect, bool emitSignal) { + applyZoomRect(rect); + if (m_gainPlot) { + m_yLo = 0.0; + m_yHi = 3.0; + } + const QRectF current = currentRect(); + if (m_zoomStack.empty()) { + m_zoomStack.push_back(baseRect()); + m_zoomIndex = 0; + } + if (m_zoomIndex + 1 < static_cast(m_zoomStack.size())) + m_zoomStack.resize(static_cast(m_zoomIndex) + 1); + if (m_zoomIndex < 0) + m_zoomIndex = 0; + if (m_zoomStack[static_cast(m_zoomIndex)] != current) { + m_zoomStack.push_back(current); + m_zoomIndex = static_cast(m_zoomStack.size()) - 1; + } + m_xAuto = false; + if (!m_gainPlot) + m_yAuto = false; + if (emitSignal) + emitZoomed(); + update(); +} + +void SlsQt1DPlot::zoomAbout(const QPointF &pos, double factor, bool push) { + const Geometry g = computeGeometry(); + if (g.plot.width() <= 0 || g.plot.height() <= 0) + return; + if (!g.plot.contains(pos.toPoint())) + return; + const double xl = tx(m_xLo); + const double xh = tx(m_xHi); + const double yl = ty(m_yLo); + const double yh = ty(m_yHi); + const double fx = + std::max(0.0, std::min(1.0, (pos.x() - g.plot.left()) / g.plot.width())); + const double fy = std::max( + 0.0, std::min(1.0, (g.plot.bottom() - pos.y()) / g.plot.height())); + const double cx = xl + (xh - xl) * fx; + const double cy = yl + (yh - yl) * fy; + const double nxl = cx - (cx - xl) * factor; + const double nxh = cx + (xh - cx) * factor; + const double nyl = cy - (cy - yl) * factor; + const double nyh = cy + (yh - cy) * factor; + if (!(nxh - nxl > kMinSpan) || !(nyh - nyl > kMinSpan)) + return; + QRectF rect = rectFromRanges(itx(nxl), itx(nxh), ity(nyl), ity(nyh)); + if (m_gainPlot) { + // keep the gain y range fixed in data coordinates + rect = rectFromRanges(itx(nxl), itx(nxh), m_yLo, m_yHi); + } + if (push) + pushZoomRect(rect, true); + else { + applyZoomRect(rect); + emitZoomed(); + update(); + } +} + +// --------------------------------------------------------------------------- +// SlsQt1DPlot - painting +// --------------------------------------------------------------------------- + +std::vector SlsQt1DPlot::tickValues(double lo, double hi, bool log, + int maxTicks) const { + if (log) { + double l = lo > 0 ? lo : 1e-9; + double h = hi > l ? hi : l * 10.0; + std::vector out; + if (maxTicks < 2) + maxTicks = 2; + const auto lt = + sls::plot::computeLinearTicks(std::log10(l), std::log10(h), + maxTicks); + out.reserve(lt.size()); + for (double t : lt) { + const double v = std::pow(10.0, t); + if (std::isfinite(v) && v > 0) + out.push_back(v); + } + return out; + } + return sls::plot::computeLinearTicks(lo, hi, maxTicks); +} + +std::vector +SlsQt1DPlot::tickLabels(const std::vector &ticks, double lo, double hi, + bool log) const { + std::vector labels; + labels.reserve(ticks.size()); + if (log) { + for (double v : ticks) { + if (v >= 1e5 || v < 1e-2) { + labels.push_back(QString::number(v, 'g', 3)); + } else if (v >= 1.0) { + const double r = std::round(v); + labels.push_back(std::fabs(v - r) < 1e-9 + ? QString::number(r, 'f', 0) + : QString::number(v, 'g', 3)); + } else { + labels.push_back(QString::number(v, 'g', 3)); + } + } + } else { + double step = 1.0; + if (ticks.size() >= 2) + step = ticks[1] - ticks[0]; + else + step = (hi - lo) / 8.0; + for (double v : ticks) + labels.push_back(sls::plot::formatTick(v, step)); + } + return labels; +} + +SlsQt1DPlot::Geometry SlsQt1DPlot::computeGeometry() const { + Geometry g; + const QFontMetrics fmTick(m_tickFont); + const QFontMetrics fmAxisX(m_xTitleFont); + const QFontMetrics fmAxisY(m_yTitleFont); + const QFontMetrics fmTitle(m_titleFont); + + const int titleH = m_title.isEmpty() ? 0 : fmTitle.height() + 4; + const int xTitleH = m_xTitle.isEmpty() ? 0 : fmAxisX.height() + 2; + const int yTitleW = m_yTitle.isEmpty() ? 0 : fmAxisY.height() + 2; + + // Legend: count the curves that ask for an entry and lay them out in one + // or more rows. The height is reserved at the very bottom of the widget. + int legendH = 0; + { + std::vector entries; + for (SlsQtH1D *h : m_hists) { + if (h && h->legendVisible()) + entries.push_back(h); + } + if (!entries.empty()) { + const int rowH = fmTick.height() + 4; + const int avail = std::max(40, width() - 8); + int rows = 1; + int used = 0; + for (SlsQtH1D *h : entries) { + const int w = + 20 + (h->title().isEmpty() + ? 0 + : sls::plot::textWidth(fmTick, h->title()) + 4); + if (used > 0 && used + w > avail) { + ++rows; + used = 0; + } + used += w; + } + const int maxRows = std::max(1, (height() / 3) / rowH); + if (rows > maxRows) + rows = maxRows; + legendH = rows * rowH + 2; + } + } + + if (m_gainPlot) { + // The old qwt gain plot forced divideScale(0, 3, 3, 0, 1): exactly the + // ticks 0, 1, 2, 3 regardless of the widget height. The generic 1/2/5 + // chooser would yield 0, 0.5, 1, ... in a taller window. + g.yTicks = {0.0, 1.0, 2.0, 3.0}; + g.yLabels = {QStringLiteral("0"), QStringLiteral("1"), + QStringLiteral("2"), QStringLiteral("3")}; + } else { + const int availH = std::max( + 20, height() - titleH - xTitleH - legendH - (fmTick.height() + 6)); + const int maxYT = + std::max(2, std::min(8, availH / (fmTick.height() + 8))); + g.yTicks = tickValues(m_yLo, m_yHi, m_logY, maxYT); + g.yLabels = tickLabels(g.yTicks, m_yLo, m_yHi, m_logY); + } + int yLabelW = 0; + for (const QString &s : g.yLabels) + yLabelW = std::max(yLabelW, sls::plot::textWidth(fmTick, s)); + + int left = 3 + yTitleW + yLabelW + kTickLen + 2; + const int right = 8; + int plotW = width() - left - right; + if (plotW < 20) { + left = 3; + plotW = std::max(10, width() - left - right); + } + + // Choose the number of x ticks so that the labels do not overlap. + std::vector xt = tickValues(m_xLo, m_xHi, m_logX, 8); + std::vector xl = tickLabels(xt, m_xLo, m_xHi, m_logX); + int maxXLabelW = 12; + for (const QString &s : xl) + maxXLabelW = std::max(maxXLabelW, sls::plot::textWidth(fmTick, s)); + int maxXT = std::max(2, std::min(8, plotW / (maxXLabelW + 12))); + g.xTicks = tickValues(m_xLo, m_xHi, m_logX, maxXT); + g.xLabels = tickLabels(g.xTicks, m_xLo, m_xHi, m_logX); + + const int bottom = + 4 + fmTick.height() + 3 + xTitleH + legendH + 1; + // y tick labels are vertically centred on the tick, so the plot rectangle + // must not start at y = 0: in gain mode there is no title and the topmost + // label ("3") would be clipped to its lower half at the widget edge. + // Reserve at least half a tick-label height at the top (title-less non-gain + // plots benefit as well; a title already provides the room). + const int topMargin = std::max(titleH, fmTick.height() / 2 + 1); + int top = topMargin; + QRect plot(left, top, width() - left - right, height() - top - bottom); + if (plot.width() < 20 || plot.height() < 20) { + left = 3; + top = topMargin; + plot = QRect(left, top, std::max(10, width() - left - 3), + std::max(10, height() - top - 3)); + } + + if (plot.left() < 0) + plot.setLeft(0); + if (plot.top() < 0) + plot.setTop(0); + if (plot.right() >= width()) + plot.setRight(std::max(plot.left() + 1, width() - 1)); + if (plot.bottom() >= height()) + plot.setBottom(std::max(plot.top() + 1, height() - 1)); + + g.plot = plot; + g.titleH = titleH; + g.xTitleH = xTitleH; + g.yTitleW = yTitleW; + g.legendH = legendH; + return g; +} + +void SlsQt1DPlot::paintGrid(QPainter &p, const Geometry &g) const { + p.setRenderHint(QPainter::Antialiasing, false); + QPen gridPen(m_theme.grid); + gridPen.setStyle(Qt::SolidLine); + gridPen.setWidth(1); + gridPen.setCosmetic(true); + p.setPen(gridPen); + for (double v : g.xTicks) { + const int x = qRound(toWidget(v, m_yLo, g).x()); + if (x > g.plot.left() && x < g.plot.right()) + p.drawLine(x, g.plot.top(), x, g.plot.bottom()); + } + for (double v : g.yTicks) { + const int y = qRound(toWidget(m_xLo, v, g).y()); + if (y > g.plot.top() && y < g.plot.bottom()) + p.drawLine(g.plot.left(), y, g.plot.right(), y); + } +} + +void SlsQt1DPlot::paintCurves(QPainter &p, const Geometry &g) const { + p.save(); + p.setClipRect(g.plot); + p.setRenderHint(QPainter::Antialiasing, false); + const QRectF markerRect = QRectF(g.plot).adjusted(-3, -3, 3, 3); + for (SlsQtH1D *h : m_hists) { + if (!h || h->GetNBinsX() <= 0) + continue; + const double *xs = h->GetX(); + const double *ys = h->GetY(); + const int n = h->GetNBinsX(); + if (!xs || !ys) + continue; + + QPen pen = h->pen(); + pen.setCosmetic(true); + if (pen.style() == Qt::NoPen) + pen.setStyle(Qt::SolidLine); + p.setPen(pen); + p.setBrush(Qt::NoBrush); + + const auto valid = [&](int i) { + const double xv = xs[i]; + const double yv = ys[i]; + if (!std::isfinite(xv) || !std::isfinite(yv)) + return false; + if (m_logX && !(xv > 0.0)) + return false; + if (m_logY && !(yv > 0.0)) + return false; + return true; + }; + + if (h->isLines()) { + QPolygonF poly; + poly.reserve(n); + const auto flush = [&]() { + if (poly.size() >= 2) + p.drawPolyline(poly); + else if (poly.size() == 1) + p.drawPoint(poly[0]); + poly.clear(); + }; + for (int i = 0; i < n; ++i) { + if (!valid(i)) { + flush(); + continue; + } + poly << toWidget(xs[i], ys[i], g); + } + flush(); + } else { + for (int i = 0; i < n; ++i) { + if (!valid(i)) + continue; + const QPointF pt = toWidget(xs[i], ys[i], g); + if (markerRect.contains(pt)) + p.drawPoint(pt); + } + } + + if (h->isMarkers()) { + for (int i = 0; i < n; ++i) { + if (!valid(i)) + continue; + const QPointF pt = toWidget(xs[i], ys[i], g); + if (!markerRect.contains(pt)) + continue; + const double cx = pt.x(); + const double cy = pt.y(); + p.drawLine(QPointF(cx - 2.0, cy), QPointF(cx + 2.0, cy)); + p.drawLine(QPointF(cx, cy - 2.0), QPointF(cx, cy + 2.0)); + } + } + } + p.restore(); +} + +void SlsQt1DPlot::paintDecorations(QPainter &p, const Geometry &g) const { + if (!m_roiOn && !m_hasHLine && !m_hasVLine) + return; + p.save(); + p.setClipRect(g.plot); + p.setRenderHint(QPainter::Antialiasing, false); + + if (m_roiOn) { + QPen roiPen(QColor(255, 235, 59)); + roiPen.setWidthF(1.5); + roiPen.setCosmetic(true); + p.setPen(roiPen); + p.setBrush(Qt::NoBrush); + for (const slsDetectorDefs::ROI &roi : m_rois) { + double x0 = roi.xmin; + double x1 = roi.xmax - 1; + if (x1 < x0) + x1 = x0; + double y0 = m_roiYMin; + double y1 = m_roiYMax - 1; + if (y1 < y0) + y1 = y0; + const QPointF a = toWidget(x0, y0, g); + const QPointF b = toWidget(x1, y1, g); + p.drawRect(QRectF(a, b).normalized()); + } + } + + QPen hvPen(QColor(255, 215, 0)); + hvPen.setStyle(Qt::SolidLine); + hvPen.setWidth(1); + hvPen.setCosmetic(true); + p.setPen(hvPen); + if (m_hasHLine) { + const QPointF a = toWidget(m_xLo, m_hLine, g); + const QPointF b = toWidget(m_xHi, m_hLine, g); + p.drawLine(a, b); + } + if (m_hasVLine) { + const QPointF a = toWidget(m_vLine, m_yLo, g); + const QPointF b = toWidget(m_vLine, m_yHi, g); + p.drawLine(a, b); + } + p.restore(); +} + +void SlsQt1DPlot::paintFrame(QPainter &p, const Geometry &g) const { + p.setRenderHint(QPainter::Antialiasing, false); + const QRect r = g.plot; + const QFontMetrics fmTick(m_tickFont); + + QPen framePen(m_theme.frame); + framePen.setWidth(1); + framePen.setCosmetic(true); + p.setPen(framePen); + p.setBrush(Qt::NoBrush); + p.drawRect(r.adjusted(0, 0, -1, -1)); + + QPen tickPen(m_theme.tick); + tickPen.setWidth(1); + tickPen.setCosmetic(true); + + // x ticks and labels + p.setFont(m_tickFont); + for (int i = 0; i < static_cast(g.xTicks.size()); ++i) { + const int x = qRound(toWidget(g.xTicks[static_cast(i)], m_yLo, + g) + .x()); + if (x < r.left() || x > r.right()) + continue; + p.setPen(tickPen); + p.drawLine(x, r.bottom() + 1, x, r.bottom() + kTickLen); + if (i < static_cast(g.xLabels.size())) { + const QString &lab = g.xLabels[static_cast(i)]; + p.setPen(m_theme.text); + int w = sls::plot::textWidth(fmTick, lab) + 8; + int lx = x - w / 2; + if (lx < 0) + lx = 0; + if (lx + w > width()) + lx = std::max(0, width() - w); + p.drawText(QRect(lx, r.bottom() + kTickLen + 2, w, fmTick.height()), + Qt::AlignHCenter | Qt::AlignTop, lab); + } + } + + // y ticks and labels + for (int i = 0; i < static_cast(g.yTicks.size()); ++i) { + const int y = qRound(toWidget(m_xLo, g.yTicks[static_cast(i)], + g) + .y()); + if (y < r.top() || y > r.bottom()) + continue; + p.setPen(tickPen); + p.drawLine(r.left() - kTickLen, y, r.left() - 1, y); + if (i < static_cast(g.yLabels.size())) { + const QString &lab = g.yLabels[static_cast(i)]; + p.setPen(m_theme.text); + const int w = sls::plot::textWidth(fmTick, lab) + 4; + int lx = r.left() - kTickLen - 2 - w; + if (lx < 0) + lx = 0; + p.drawText(QRect(lx, y - fmTick.height() / 2, w, fmTick.height()), + Qt::AlignRight | Qt::AlignVCenter, lab); + } + } + + // titles + p.setPen(m_theme.text); + if (!m_title.isEmpty()) { + p.setFont(m_titleFont); + p.drawText(QRect(0, 0, width(), g.titleH), Qt::AlignCenter, m_title); + } + if (!m_xTitle.isEmpty()) { + const QFontMetrics fmAxisX(m_xTitleFont); + p.setFont(m_xTitleFont); + const int y = height() - g.legendH - g.xTitleH; + p.drawText(QRect(r.left(), y, r.width(), + std::max(g.xTitleH, fmAxisX.height())), + Qt::AlignHCenter | Qt::AlignTop, m_xTitle); + } + if (!m_yTitle.isEmpty()) { + p.setFont(m_yTitleFont); + const int axisH = QFontMetrics(m_yTitleFont).height(); + p.save(); + p.translate(1 + g.yTitleW / 2, r.center().y()); + p.rotate(-90.0); + p.drawText(QRect(-r.height() / 2, -axisH / 2, r.height(), axisH), + Qt::AlignCenter, m_yTitle); + p.restore(); + } +} + +void SlsQt1DPlot::paintLegend(QPainter &p, const Geometry &g) const { + if (g.legendH <= 0) + return; + std::vector entries; + for (SlsQtH1D *h : m_hists) { + if (h && h->legendVisible()) + entries.push_back(h); + } + if (entries.empty()) + return; + + const QFontMetrics fm(m_tickFont); + const int rowH = fm.height() + 4; + const int avail = std::max(40, width() - 8); + std::vector> rows; + std::vector rowW; + std::vector current; + int curW = 0; + for (SlsQtH1D *h : entries) { + const int w = + 20 + (h->title().isEmpty() + ? 0 + : sls::plot::textWidth(fm, h->title()) + 4); + if (!current.empty() && curW + w > avail) { + rows.push_back(current); + rowW.push_back(curW); + current.clear(); + curW = 0; + } + current.push_back(h); + curW += w; + } + if (!current.empty()) { + rows.push_back(current); + rowW.push_back(curW); + } + const int maxRows = std::max(1, g.legendH / rowH); + if (static_cast(rows.size()) > maxRows) { + rows.resize(static_cast(maxRows)); + rowW.resize(static_cast(maxRows)); + } + + p.setRenderHint(QPainter::Antialiasing, false); + p.setFont(m_tickFont); + int y = height() - g.legendH + 2; + for (size_t ri = 0; ri < rows.size(); ++ri) { + int x = (width() - rowW[ri]) / 2; + const int cy = y + rowH / 2; + for (SlsQtH1D *h : rows[ri]) { + QPen sample(h->pen().color()); + sample.setStyle(Qt::SolidLine); + sample.setWidth(2); + sample.setCosmetic(true); + p.setPen(sample); + p.drawLine(x, cy, x + 16, cy); + x += 20; + if (!h->title().isEmpty()) { + p.setPen(m_theme.text); + const int tw = sls::plot::textWidth(fm, h->title()); + p.drawText(QRect(x, y, tw + 2, rowH), + Qt::AlignLeft | Qt::AlignVCenter, h->title()); + x += tw + 4; + } + } + y += rowH; + } +} + +void SlsQt1DPlot::paintTracker(QPainter &p, const Geometry &g) const { + if (!m_trackValid || !g.plot.contains(m_trackPos.toPoint())) + return; + const QPointF d = toData(m_trackPos, g); + if (!std::isfinite(d.x()) || !std::isfinite(d.y())) + return; + + const QFontMetrics fm(m_tickFont); + const QString text = + QStringLiteral("x: %1 y: %2").arg(formatValue(d.x()), formatValue(d.y())); + QRect box = fm.boundingRect(text); + box.adjust(-5, -3, 5, 3); + int bx = qRound(m_trackPos.x()) + 12; + int by = qRound(m_trackPos.y()) + 12; + if (bx + box.width() > width() - 2) + bx = width() - 2 - box.width(); + if (by + box.height() > height() - 2) + by = height() - 2 - box.height(); + if (bx < 2) + bx = 2; + if (by < 2) + by = 2; + + p.save(); + p.setRenderHint(QPainter::Antialiasing, false); + QPen cross(QColor(255, 255, 255, 90)); + cross.setWidth(1); + cross.setStyle(Qt::DashLine); + p.setClipRect(g.plot); + p.setPen(cross); + const int cx = qRound(m_trackPos.x()); + const int cy = qRound(m_trackPos.y()); + p.drawLine(cx, g.plot.top(), cx, g.plot.bottom()); + p.drawLine(g.plot.left(), cy, g.plot.right(), cy); + p.restore(); + + const QRect textRect(bx, by, box.width(), box.height()); + p.save(); + p.setPen(Qt::NoPen); + p.setBrush(QColor(255, 255, 255, 205)); + p.drawRect(textRect); + p.setPen(QColor(20, 20, 20)); + p.setFont(m_tickFont); + p.drawText(textRect, Qt::AlignCenter, text); + p.restore(); +} + +void SlsQt1DPlot::paintRubberBand(QPainter &p, const Geometry &g) const { + if (!m_rubberBand) + return; + QRectF rr = QRectF(m_rubberStart, m_rubberCur).normalized(); + rr = rr.intersected(QRectF(g.plot)); + if (rr.width() < 1.0 && rr.height() < 1.0) + return; + QPen pen(QColor(140, 180, 255)); + pen.setStyle(Qt::DashLine); + pen.setWidth(1); + pen.setCosmetic(true); + p.save(); + p.setRenderHint(QPainter::Antialiasing, false); + p.setPen(pen); + p.setBrush(QColor(140, 180, 255, 40)); + p.drawRect(rr); + p.restore(); +} + +void SlsQt1DPlot::paintEvent(QPaintEvent *event) { + (void)event; + QPainter p(this); + p.fillRect(rect(), m_theme.background); + if (width() < 8 || height() < 8) + return; + const Geometry g = computeGeometry(); + if (g.plot.width() <= 0 || g.plot.height() <= 0) + return; + paintGrid(p, g); + paintCurves(p, g); + paintDecorations(p, g); + paintFrame(p, g); + paintLegend(p, g); + paintTracker(p, g); + paintRubberBand(p, g); +} + +// --------------------------------------------------------------------------- +// SlsQt1DPlot - interaction +// --------------------------------------------------------------------------- + +void SlsQt1DPlot::mousePressEvent(QMouseEvent *event) { + const QPointF pos = sls::plot::eventPosition(event); + const Geometry g = computeGeometry(); + if (zoomAllowed()) { + if (event->button() == Qt::LeftButton && + g.plot.contains(pos.toPoint())) { + m_rubberBand = true; + m_rubberStart = pos; + m_rubberCur = pos; + setCursor(Qt::CrossCursor); + update(); + event->accept(); + return; + } + if (event->button() == Qt::MiddleButton) { + m_panning = true; + m_panStart = pos; + m_panXnLo = tx(m_xLo); + m_panXnHi = tx(m_xHi); + m_panYnLo = ty(m_yLo); + m_panYnHi = ty(m_yHi); + setCursor(Qt::ClosedHandCursor); + event->accept(); + return; + } + if (event->button() == Qt::RightButton) { + if (event->modifiers() & Qt::ControlModifier) + resetZoom(true); + else + zoomOutOneLevel(); + event->accept(); + return; + } + } + QWidget::mousePressEvent(event); +} + +void SlsQt1DPlot::mouseMoveEvent(QMouseEvent *event) { + const QPointF pos = sls::plot::eventPosition(event); + const Geometry g = computeGeometry(); + const bool inside = g.plot.contains(pos.toPoint()); + if (inside != m_trackValid || pos != m_trackPos) { + m_trackValid = inside; + m_trackPos = pos; + update(); + } + + if (m_rubberBand) { + m_rubberCur = pos; + update(); + event->accept(); + return; + } + if (m_panning) { + if (g.plot.width() > 0 && g.plot.height() > 0) { + const double dtx = (pos.x() - m_panStart.x()) / g.plot.width() * + (m_panXnHi - m_panXnLo); + const double dty = (pos.y() - m_panStart.y()) / g.plot.height() * + (m_panYnHi - m_panYnLo); + setView(itx(m_panXnLo - dtx), itx(m_panXnHi - dtx), + ity(m_panYnLo + dty), ity(m_panYnHi + dty)); + if (m_gainPlot) { + m_yLo = 0.0; + m_yHi = 3.0; + } + m_xAuto = false; + if (!m_gainPlot) + m_yAuto = false; + emitZoomed(); + update(); + } + event->accept(); + return; + } + QWidget::mouseMoveEvent(event); +} + +void SlsQt1DPlot::mouseReleaseEvent(QMouseEvent *event) { + if (m_rubberBand && event->button() == Qt::LeftButton) { + m_rubberBand = false; + unsetCursor(); + const QRectF raw = QRectF(m_rubberStart, m_rubberCur).normalized(); + const Geometry g = computeGeometry(); + if (raw.width() >= 5.0 && raw.height() >= 5.0 && + g.plot.width() > 0 && g.plot.height() > 0) { + const QRectF rr = raw.intersected(QRectF(g.plot)); + if (rr.width() >= 5.0 && rr.height() >= 5.0) { + const QPointF p1 = toData(rr.topLeft(), g); + const QPointF p2 = toData(rr.bottomRight(), g); + const double x0 = std::min(p1.x(), p2.x()); + const double x1 = std::max(p1.x(), p2.x()); + const double y0 = std::min(p1.y(), p2.y()); + const double y1 = std::max(p1.y(), p2.y()); + pushZoomRect(rectFromRanges(x0, x1, y0, y1), true); + } + } + update(); + event->accept(); + return; + } + if (m_panning && event->button() == Qt::MiddleButton) { + m_panning = false; + unsetCursor(); + if (!m_zoomStack.empty() && m_zoomIndex >= 0 && + m_zoomIndex < static_cast(m_zoomStack.size())) + m_zoomStack[static_cast(m_zoomIndex)] = currentRect(); + emitZoomed(); + event->accept(); + return; + } + QWidget::mouseReleaseEvent(event); +} + +void SlsQt1DPlot::wheelEvent(QWheelEvent *event) { + if (!zoomAllowed()) { + event->ignore(); + return; + } + const QPointF pos = sls::plot::eventPosition(event); + const Geometry g = computeGeometry(); + if (!g.plot.contains(pos.toPoint())) { + event->ignore(); + return; + } + const int dy = event->angleDelta().y(); + if (dy > 0) { + zoomAbout(pos, 1.0 / 1.18, true); + event->accept(); + } else if (dy < 0) { + zoomOutOneLevel(); + event->accept(); + } else { + event->ignore(); + } +} + +void SlsQt1DPlot::leaveEvent(QEvent *event) { + if (m_trackValid) { + m_trackValid = false; + update(); + } + QWidget::leaveEvent(event); +} + +} // namespace sls diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DZoomer.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DZoomer.cpp deleted file mode 100644 index a8a60d43c..000000000 --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DZoomer.cpp +++ /dev/null @@ -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 -#include -#include - -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 diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DHist.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DHist.cpp index 098e2621b..100b48655 100644 --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DHist.cpp +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DHist.cpp @@ -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 -#include -using std::cout; -using std::endl; +#include +#include +#include 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(nb) + 1; + if (data.size() != needed) + data.assign(needed, 0.0); + data[static_cast(nb)] = 0.0; + if (d) { - memcpy(data, d, nb * sizeof(double)); + std::memcpy(data.data(), d, static_cast(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(std::floor((x - x_min) / x_width)); + const int by = static_cast(std::floor((y - y_min) / y_width)); + return GetBinIndex(bx, by); +} + +double SlsQt2DHist::GetBinValue(int bx, int by) const { + return data[static_cast(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(index)] = v; +} + void SlsQt2DHist::SetMinMax(double zmin, double zmax) { - /* if(zmin 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(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(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(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(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(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(std::floor(u)); + int j0 = static_cast(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(i0 + 1); + const size_t j1 = static_cast(j0 + 1); + const size_t i0s = static_cast(i0); + const size_t j0s = static_cast(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(nb)]; + const int ix = static_cast(std::floor(bx)); + const int iy = static_cast(std::floor(by)); + if (ix < 0 || ix >= nx || iy < 0 || iy >= ny) + return data[static_cast(nb)]; + return data[static_cast(ix + iy * nx)]; +} + +} // namespace sls \ No newline at end of file diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlot.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlot.cpp index ecd7b6eb3..3ecadc422 100644 --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlot.cpp +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlot.cpp @@ -1,374 +1,877 @@ -// SPDX-License-Identifier: LGPL-3.0-or-other -// Copyright (C) 2021 Contributors to the SLS Detector Package -#include "SlsQt2DPlot.h" -#include "qDefs.h" -#include "qVersionResolve.h" -#include "sls/logger.h" - -// Suppressing warning until qwt has a fix, avoid -// patching and should be backwards compatible -// https://doc.qt.io/qt-5/qflags-obsolete.html -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#pragma GCC diagnostic pop - -#include -#include - -namespace sls { - -SlsQt2DPlot::SlsQt2DPlot(QWidget *parent, bool gain) - : QwtPlot(parent), gainPlot(gain) { - isLog = 0; - axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); - axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); - d_spectrogram = new QwtPlotSpectrogram(); - hist = new SlsQt2DHist(); - SetupZoom(); - SetupColorMap(); - d_spectrogram->setData(hist); - d_spectrogram->attach(this); - plotLayout()->setAlignCanvasToScales(true); - FillTestPlot(); - setFont(qDefs::GetDefaultFont()); - SetTitleFont(qDefs::GetDefaultFont()); - SetXFont(qDefs::GetDefaultFont()); - SetYFont(qDefs::GetDefaultFont()); - SetZFont(qDefs::GetDefaultFont()); - Update(); - - if (gainPlot) { - setTitle("Gain"); - SetZTitle(""); - enableAxis(QwtPlot::yLeft, false); - enableAxis(QwtPlot::xBottom, false); - DisableZoom(true); - // set only major ticks from 0 to 3 - auto div = axisScaleEngine(QwtPlot::yRight)->divideScale(0, 3, 3, 0, 1); - setAxisScaleDiv(QwtPlot::yRight, div); - } -} - -SlsQt2DPlot::~SlsQt2DPlot() = default; - -void SlsQt2DPlot::SetTitle(QString title) { setTitle(title); } - -void SlsQt2DPlot::SetXTitle(QString title) { - setAxisTitle(QwtPlot::xBottom, title); -} - -void SlsQt2DPlot::SetYTitle(QString title) { - setAxisTitle(QwtPlot::yLeft, title); -} - -void SlsQt2DPlot::SetZTitle(QString title) { - setAxisTitle(QwtPlot::yRight, title); -} - -void SlsQt2DPlot::SetTitleFont(const QFont &f) { - QwtText t(""); - t.setFont(f); - t.setRenderFlags(Qt::AlignLeft | Qt::AlignVCenter); - setTitle(t); -} - -void SlsQt2DPlot::SetXFont(const QFont &f) { - QwtText t(""); - t.setFont(f); - setAxisTitle(QwtPlot::xBottom, t); -} - -void SlsQt2DPlot::SetYFont(const QFont &f) { - QwtText t(""); - t.setFont(f); - setAxisTitle(QwtPlot::yLeft, t); -} - -void SlsQt2DPlot::SetZFont(const QFont &f) { - QwtText t(""); - t.setFont(f); - setAxisTitle(QwtPlot::yRight, t); -} - -void SlsQt2DPlot::SetupColorMap() { - d_spectrogram->setColorMap(myColourMap(0)); - for (double level = 0.5; level < 10.0; level += 1.0) - (contourLevelsLinear) += level; - d_spectrogram->setContourLevels(contourLevelsLinear); - - for (double level = 0.5; level < 10.0; level += 1.0) - (contourLevelsLog) += (pow(10, 2 * level / 10.0) - 1) / 99.0 * 10; - - // A color bar on the right axis - rightAxis = axisWidget(QwtPlot::yRight); - - rightAxis->setTitle("Intensity"); - rightAxis->setColorBarEnabled(true); - enableAxis(QwtPlot::yRight); -} - -void SlsQt2DPlot::FillTestPlot(int mode) { - static int nx = 50; - static int ny = 50; - static double *the_data = nullptr; - if (the_data == nullptr) - the_data = new double[nx * ny]; - - double dmax = sqrt(pow(nx / 2.0 - 0.5, 2) + pow(ny / 2.0 - 0.5, 2)); - for (int i = 0; i < nx; i++) { - for (int j = 0; j < ny; j++) { - double d = sqrt(pow(nx / 2.0 - (i + 0.5), 2) + - pow(ny / 2.0 - (j + 0.5), 2)); - - if (mode % 3) - the_data[i + j * nx] = 10 * d / dmax; - else - the_data[i + j * nx] = 10 * (1 - d / dmax); - } - } - - hist->SetData(nx, 200, 822, ny, -0.5, ny - 0.5, the_data); -} - -void SlsQt2DPlot::SetupZoom() { - // LeftButton for the zooming - // MiddleButton for the panning - // RightButton: zoom out by 1 - // Ctrl+RighButton: zoom out to full size - - zoomer = new SlsQt2DZoomer(canvas()); - zoomer->SetHist(hist); - zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, - Qt::ControlModifier); - zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); - panner = new QwtPlotPanner(canvas()); - panner->setAxisEnabled(QwtPlot::yRight, false); - panner->setMouseButton(Qt::MiddleButton); - - // Avoid jumping when labels with more/less digits - // appear/disappear when scrolling vertically - - const QFontMetrics fm(axisWidget(QwtPlot::yLeft)->font()); - QwtScaleDraw *sd = axisScaleDraw(QwtPlot::yLeft); - sd->setMinimumExtent(qResolve_GetQFontWidth(fm, "100.00")); - const QColor c(Qt::darkBlue); - zoomer->setRubberBandPen(c); - zoomer->setTrackerPen(c); - - connect(zoomer, SIGNAL(zoomed(const QRectF &)), this, - SIGNAL(PlotZoomedSignal(const QRectF &))); - - connect(panner, SIGNAL(panned(int, int)), this, - SLOT(GetPannedCoord(int, int))); -} - -void SlsQt2DPlot::UnZoom(bool replot) { - - zoomer->setZoomBase(QRectF(hist->GetXMin(), hist->GetYMin(), - hist->GetXMax() - hist->GetXMin(), - hist->GetYMax() - hist->GetYMin())); - zoomer->setZoomBase(replot); // Call replot for the attached plot before - // initializing the zoomer with its scales. - // zoomer->zoom(0); -} - -void SlsQt2DPlot::GetPannedCoord(int, int) { - double xmin = invTransform(QwtPlot::xBottom, 0); - double xmax = invTransform(QwtPlot::xBottom, canvas()->rect().width()); - double ymax = invTransform(QwtPlot::yLeft, 0); - double ymin = invTransform(QwtPlot::yLeft, canvas()->rect().height()); - LOG(logDEBUG1) << "Rect1 " << xmin << "\t" << xmax << "\t" << ymin << "\t" - << ymax; - QPointF topLeft = QPointF(xmin, ymin); - QPointF bottomRight = QPointF(xmax, ymax); - const QRectF rectf = QRectF(topLeft, bottomRight); - rectf.getCoords(&xmin, &ymin, &xmax, &ymax); - LOG(logDEBUG1) << "RectF " << xmin << "\t" << xmax << "\t" << ymin << "\t" - << ymax; - emit PlotZoomedSignal(rectf); -} - -void SlsQt2DPlot::SetZoom(const QRectF &rect) { - double xmin = 0, xmax = 0, ymin = 0, ymax = 0; - rect.getCoords(&xmin, &ymin, &xmax, &ymax); - LOG(logDEBUG1) << "Plot zooming in to " << xmin << " " << xmax << " " - << ymin << " " << ymax; - SetXMinMax(xmin, xmax); - SetYMinMax(ymin, ymax); - replot(); -} - -void SlsQt2DPlot::SetZoom(double xmin, double ymin, double x_width, - double y_width) { - zoomer->setZoomBase(QRectF(xmin, ymin, x_width, y_width)); -} - -void SlsQt2DPlot::DisableZoom(bool disable) { - if (disableZoom != disable) { - disableZoom = disable; - -#ifdef VERBOSE - if (disable) - std::cout << "Disabling zoom\n"; - else - std::cout << "Enabling zoom\n"; -#endif - if (disable) { - if (zoomer) { - zoomer->setMousePattern(QwtEventPattern::MouseSelect1, - Qt::NoButton); - zoomer->setMousePattern(QwtEventPattern::MouseSelect2, - Qt::NoButton, Qt::ControlModifier); - zoomer->setMousePattern(QwtEventPattern::MouseSelect3, - Qt::NoButton); - } - if (panner) - panner->setMouseButton(Qt::NoButton); - } else { - if (zoomer) { - zoomer->setMousePattern(QwtEventPattern::MouseSelect1, - Qt::LeftButton); - zoomer->setMousePattern(QwtEventPattern::MouseSelect2, - Qt::RightButton, Qt::ControlModifier); - zoomer->setMousePattern(QwtEventPattern::MouseSelect3, - Qt::RightButton); - } - if (panner) - panner->setMouseButton(Qt::MiddleButton); - } - } -} - -void SlsQt2DPlot::SetZMinMax(double zmin, double zmax) { - hist->SetMinMax(zmin, zmax); -} - -QwtLinearColorMap *SlsQt2DPlot::myColourMap(QVector colourStops) { - - int ns = 5; - - double r[] = {0.00, 0.00, 0.87, 1.00, 0.51}; - double g[] = {0.00, 0.81, 1.00, 0.20, 0.00}; - double b[] = {0.51, 1.00, 0.12, 0.00, 0.00}; - - // QColor c1, c2, c; - QColor c2, c; - c2.setRgbF(r[ns - 1], g[ns - 1], b[ns - 1]); - QwtLinearColorMap *copyMap = new QwtLinearColorMap(Qt::lightGray, c2); - - for (int is = 0; is < ns - 1; is++) { - c.setRgbF(r[is], g[is], b[is]); - copyMap->addColorStop(colourStops[is], c); - } - - return copyMap; -} - -QwtLinearColorMap *SlsQt2DPlot::myColourMap(int log) { - QVector cs{0.0, 0.34, 0.61, 0.84, 1.0}; - if (log) { - for (int i = 0; i < cs.size(); ++i) - cs[i] = (pow(10, 2 * cs[i]) - 1) / 99.0; - } - return myColourMap(cs); -} - -void SlsQt2DPlot::Update() { - if (isLog) - hist->SetMinimumToFirstGreaterThanZero(); - const QwtInterval zInterval = d_spectrogram->data()->interval(Qt::ZAxis); - rightAxis->setColorMap(zInterval, myColourMap(isLog)); - if (!zoomer->zoomRectIndex()) - UnZoom(); - if (!gainPlot) { - setAxisScale(QwtPlot::yRight, zInterval.minValue(), - zInterval.maxValue()); - } - plotLayout()->setAlignCanvasToScales(true); - replot(); -} - -void SlsQt2DPlot::SetInterpolate(bool enable) { - hist->Interpolate(enable); - Update(); -} - -void SlsQt2DPlot::SetContour(bool enable) { - d_spectrogram->setDisplayMode(QwtPlotSpectrogram::ContourMode, enable); - Update(); -} - -void SlsQt2DPlot::SetLogz(bool enable, bool isMin, bool isMax, double min, - double max) { - LogZ(enable); - SetZRange(isMin, isMax, min, max); -} - -void SlsQt2DPlot::SetZRange(bool isMin, bool isMax, double min, double max) { - if (isLog) { - SetZMinimumToFirstGreaterThanZero(); - } - - // set zmin and zmax - if (isMin || isMax) { - double zmin = (isMin ? min : GetZMinimum()); - double zmax = (isMax ? max : GetZMaximum()); - SetZMinMax(zmin, zmax); - } - - Update(); -} - -void SlsQt2DPlot::LogZ(bool on) { - if (on) { - isLog = 1; - d_spectrogram->setColorMap(myColourMap(isLog)); - setAxisScaleEngine(QwtPlot::yRight, new QwtLogScaleEngine); - d_spectrogram->setContourLevels(contourLevelsLog); - } else { - isLog = 0; - d_spectrogram->setColorMap(myColourMap(isLog)); - setAxisScaleEngine(QwtPlot::yRight, new QwtLinearScaleEngine); - d_spectrogram->setContourLevels(contourLevelsLinear); - } - Update(); -} - -void SlsQt2DPlot::showSpectrogram(bool on) { - d_spectrogram->setDisplayMode(QwtPlotSpectrogram::ImageMode, on); - d_spectrogram->setDefaultContourPen(on ? QPen() : QPen(Qt::NoPen)); - Update(); -} - -void SlsQt2DPlot::EnableRoiBoxes(std::vector roi) { - roiBoxes.clear(); - for (auto &r : roi) { - auto box = std::make_unique(); - box->setPen(QColor(Qt::yellow), 2.0, Qt::SolidLine); - // TopLeft - BottomRight (max points are +1 on graph) - QRectF myRect(QPointF(r.xmin, r.ymin), QPointF(r.xmax - 1, r.ymax - 1)); - box->setRect(myRect); - box->attach(this); - roiBoxes.push_back(std::move(box)); - } - replot(); -} - -void SlsQt2DPlot::DisableRoiBoxes() { - for (auto &r : roiBoxes) { - r->detach(); - } - replot(); -} - -} // namespace sls +// SPDX-License-Identifier: LGPL-3.0-or-other +// Copyright (C) 2026 Contributors to the SLS Detector Package +#include "SlsQt2DPlot.h" + +#include "SlsQtFastImage.h" +#include "SlsQtPlotCommon.h" +#include "SlsQtScalePanel.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace sls { + +namespace { +constexpr int kLowResGrid = 256; // marching-squares grid is subsampled to this +constexpr size_t kMaxContourSegs = 120000; +} // namespace + +SlsQt2DPlot::SlsQt2DPlot(QWidget *parent, bool gain) + : QWidget(parent), m_gain(gain) { + m_hist = new SlsQt2DHist(); + std::memcpy(m_palette, plot::paletteLut(plot::Palette::Color), + sizeof(m_palette)); + setupUi(); + + m_view->onZoomChanged = [this](double x1, double y1, double x2, double y2) { + onViewZoomed(x1, y1, x2, y2); + }; + m_view->onColorRangeChanged = [this](double, double) { + if (m_syncingZ) + return; + // The user dragged the scale/histogram markers or edited the spin + // boxes: that range is now authoritative until the Plot tab forces a + // new one through SetZRange()/SetZMinMax(). + m_panelZOverride = true; + m_smoothDirty = true; + m_contourDirty = true; + if (m_interp) + rebuildSmoothImage(); + if (m_contourOn) + updateContours(); + if (m_view) + m_view->update(); + }; + m_view->onPaletteChanged = [this](const QRgb *lut) { + std::memcpy(m_palette, lut, sizeof(m_palette)); + m_smoothDirty = true; + if (m_interp) + rebuildSmoothImage(); + if (m_view) + m_view->update(); + }; + m_view->onPaintOverlay = [this](QPainter &p, const QTransform &t) { + paintOverlay(p, t); + }; + + if (m_gain) { + // Plain 0..3 gain map: fixed palette/range, no axes, no zoom. The + // scale panel is not created for it (the parent plot keeps the + // colour controls). + m_view->setAxesVisible(false); + m_view->setZoomEnabled(false); + m_view->setIntegerValues(true); + m_view->setPaletteLut(plot::paletteLut(plot::Palette::Gain4)); + std::memcpy(m_palette, plot::paletteLut(plot::Palette::Gain4), + sizeof(m_palette)); + m_view->setTitle(QStringLiteral("Gain")); + applyZRange(0.0, 3.0); + } + + FillTestPlot(); + Update(); +} + +SlsQt2DPlot::~SlsQt2DPlot() { + // The child widgets are destroyed after this body: drop the callbacks that + // capture this (and m_hist) so nothing can call into a half-destroyed + // plot while the QWidget children are torn down. + if (m_view) { + m_view->onZoomChanged = nullptr; + m_view->onColorRangeChanged = nullptr; + m_view->onPaletteChanged = nullptr; + m_view->onPaintOverlay = nullptr; + } + delete m_hist; +} + +void SlsQt2DPlot::setupUi() { + auto *layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(0); + + m_view = new SlsQtFastImage(this); + layout->addWidget(m_view, 1); + + if (!m_gain) { + // One compact caption row for the z-axis (colour scale) title: the old + // qwt plot showed it next to the colour bar, the ScalePanel replaces + // the bar, so it lives directly above the panel (same dark style as + // the histogram strip, no extra heavy widget). + m_zTitleLabel = new QLabel(this); + m_zFont = m_view->axisTitleFont(); + m_zTitleLabel->setFont(m_zFont); + m_zTitleLabel->setAlignment(Qt::AlignCenter); + m_zTitleLabel->setContentsMargins(0, 1, 0, 1); + m_zTitleLabel->setSizePolicy(QSizePolicy::Preferred, + QSizePolicy::Fixed); + m_zTitleLabel->setStyleSheet(QStringLiteral( + "QLabel { background-color: rgb(28, 28, 28);" + " color: rgb(230, 230, 230); }")); + m_zTitleLabel->hide(); // shown by SetZTitle() once a title is set + layout->addWidget(m_zTitleLabel, 0); + + // Fixed 78 px histogram strip + palette/log/min-max controls. + m_panel = new SlsQtScalePanel(m_view, this); + layout->addWidget(m_panel, 0); + } +} + +// --------------------------------------------------------------------------- +// titles +// --------------------------------------------------------------------------- +void SlsQt2DPlot::SetTitle(QString title) { setTitle(title); } + +void SlsQt2DPlot::setTitle(const QString &title) { + if (m_view) + m_view->setTitle(title); +} + +QString SlsQt2DPlot::title() const { return m_view ? m_view->title() : QString(); } + +void SlsQt2DPlot::SetXTitle(QString title) { + if (m_view) + m_view->setXAxisTitle(title); +} + +void SlsQt2DPlot::SetYTitle(QString title) { + if (m_view) + m_view->setYAxisTitle(title); +} + +void SlsQt2DPlot::SetZTitle(QString title) { + m_zTitle = title; + if (!m_zTitleLabel || m_gain) + return; + m_zTitleLabel->setText(title); + // No empty caption row: the panel keeps its exact 78 px height/look when + // no z title is configured. + m_zTitleLabel->setVisible(!title.isEmpty()); +} + +void SlsQt2DPlot::SetTitleFont(const QFont &f) { + if (m_view) + m_view->setTitleFont(f); +} + +void SlsQt2DPlot::SetXFont(const QFont &f) { + if (m_view) + m_view->setAxisTitleFont(f); +} + +void SlsQt2DPlot::SetYFont(const QFont &f) { + if (m_view) + m_view->setAxisTitleFont(f); +} + +void SlsQt2DPlot::SetZFont(const QFont &f) { + m_zFont = f; + if (m_zTitleLabel) + m_zTitleLabel->setFont(f); +} + +// --------------------------------------------------------------------------- +// viewport / zoom +// --------------------------------------------------------------------------- +void SlsQt2DPlot::UnZoom(bool replot) { + m_applyViewPending = false; + if (m_view && m_view->hasImage()) + m_view->resetView(); + if (replot) { + if (m_view) + m_view->update(); + if (m_panel) + m_panel->refresh(); + } +} + +void SlsQt2DPlot::SetZoom(double xmin, double ymin, double x_width, + double y_width) { + SetZoom(QRectF(xmin, ymin, x_width, y_width)); +} + +void SlsQt2DPlot::SetZoom(const QRectF &rect) { + if (!m_view || !m_hist) + return; + const QRectF r = rect.normalized(); + if (!(r.width() > 0.0) || !(r.height() > 0.0)) + return; + m_applyViewPending = false; + m_view->setViewport(dataXToImage(r.left()), dataYToImage(r.top()), + dataXToImage(r.right()), dataYToImage(r.bottom())); + m_view->update(); +} + +void SlsQt2DPlot::DisableZoom(bool disable) { + m_zoomDisabled = disable; + if (m_view && !m_gain) + m_view->setZoomEnabled(!disable); +} + +void SlsQt2DPlot::EnableXAutoScaling() { + if (m_gain) + return; + m_autoX = true; + m_applyViewPending = true; + applyPendingView(); +} + +void SlsQt2DPlot::EnableYAutoScaling() { + if (m_gain) + return; + m_autoY = true; + m_applyViewPending = true; + applyPendingView(); +} + +void SlsQt2DPlot::SetXMinMax(double min, double max) { + if (m_gain) + return; + m_autoX = false; + m_reqX0 = min; + m_reqX1 = max; + m_applyViewPending = true; + applyPendingView(); +} + +void SlsQt2DPlot::SetYMinMax(double min, double max) { + if (m_gain) + return; + m_autoY = false; + m_reqY0 = min; + m_reqY1 = max; + m_applyViewPending = true; + applyPendingView(); +} + +void SlsQt2DPlot::applyPendingView() { + m_applyViewPending = false; + if (m_gain || !m_view || !m_hist) + return; + const int nx = m_hist->GetNBinsX(); + const int ny = m_hist->GetNBinsY(); + if (nx < 1 || ny < 1) + return; + + double u0 = 0.0, u1 = double(nx); + double v0 = 0.0, v1 = double(ny); + if (!m_autoX) { + u0 = dataXToImage(m_reqX0); + u1 = dataXToImage(m_reqX1); + } + if (!m_autoY) { + v0 = dataYToImage(m_reqY0); + v1 = dataYToImage(m_reqY1); + } + if (u1 < u0) + std::swap(u0, u1); + if (v1 < v0) + std::swap(v0, v1); + + // FastImageView refuses viewports smaller than kMinimumViewport; expand + // instead of silently ignoring the request. + const double kMin = SlsQtFastImage::kMinimumViewport; + if (!(u1 - u0 >= kMin)) { + const double c = 0.5 * (u0 + u1); + u0 = c - 0.5 * kMin; + u1 = c + 0.5 * kMin; + } + if (!(v1 - v0 >= kMin)) { + const double c = 0.5 * (v0 + v1); + v0 = c - 0.5 * kMin; + v1 = c + 0.5 * kMin; + } + m_view->setViewport(u0, v0, u1, v1); +} + +void SlsQt2DPlot::onViewZoomed(double x1, double y1, double x2, double y2) { + if (!m_hist) + return; + double dx1 = imageXToData(x1), dx2 = imageXToData(x2); + double dy1 = imageYToData(y1), dy2 = imageYToData(y2); + if (dx2 < dx1) + std::swap(dx1, dx2); + if (dy2 < dy1) + std::swap(dy1, dy2); + emit PlotZoomedSignal(QRectF(dx1, dy1, dx2 - dx1, dy2 - dy1)); +} + +// --------------------------------------------------------------------------- +// z range / colour mapping +// --------------------------------------------------------------------------- +void SlsQt2DPlot::applyZRange(double lo, double hi) { + if (!m_view) + return; + if (m_gain) { + double a = 0.0, b = 0.0; + m_view->colorRange(a, b); + if (a == 0.0 && b == 3.0) + return; + m_syncingZ = true; + m_view->setColorRange(0.0, 3.0); + m_syncingZ = false; + return; + } + double curLo = 0.0, curHi = 0.0; + m_view->colorRange(curLo, curHi); + if (curLo == lo && curHi == hi) + return; + m_syncingZ = true; + m_view->setColorRange(lo, hi); + m_syncingZ = false; + m_smoothDirty = true; + m_contourDirty = true; + if (m_interp) + rebuildSmoothImage(); + if (m_contourOn) + updateContours(); + if (m_panel) + m_panel->refresh(); +} + +void SlsQt2DPlot::SetZMinMax(double zmin, double zmax) { + if (m_gain) + return; + m_hist->SetMinMax(zmin, zmax); + // An explicitly requested range is authoritative: keep it across the + // per-frame Update() calls until SetZRange(false, false, ...) clears it. + m_userZOverride = true; + m_panelZOverride = false; + applyZRange(m_hist->GetMinimum(), m_hist->GetMaximum()); + if (m_view) + m_view->update(); + if (m_panel) + m_panel->refresh(); +} + +void SlsQt2DPlot::SetZMinimumToFirstGreaterThanZero() { + if (m_gain) + return; + m_hist->SetMinimumToFirstGreaterThanZero(); + // This is the automatic log minimum, so it releases both overrides. + m_userZOverride = false; + m_panelZOverride = false; + Update(); +} + +void SlsQt2DPlot::SetLogz(bool enable, bool isMin, bool isMax, double min, + double max) { + LogZ(enable); + SetZRange(isMin, isMax, min, max); +} + +void SlsQt2DPlot::SetZRange(bool isMin, bool isMax, double min, double max) { + if (m_gain) + return; + if (m_logZ) + m_hist->SetMinimumToFirstGreaterThanZero(); + if (isMin || isMax) { + double zmin = isMin ? min : m_hist->GetMinimum(); + double zmax = isMax ? max : m_hist->GetMaximum(); + if (!(zmax > zmin)) + zmax = zmin + 1.0; + m_hist->SetMinMax(zmin, zmax); + // An explicit range from the Plot tab (qTabPlot's min/max z controls) + // wins over both the panel and the auto range, and must survive the + // Update() that follows (in particular the log-min re-derivation). + m_userZOverride = true; + m_panelZOverride = false; + applyZRange(zmin, zmax); + } else { + // Neither end is pinned: fall back to the automatic range on the next + // Update() (the scale-panel override, if any, still takes precedence + // there). qDrawPlot calls this every frame while the z-range check + // boxes are off. + m_userZOverride = false; + } + Update(); +} + +void SlsQt2DPlot::LogZ(bool on) { + if (m_gain) + return; + m_logZ = (on != 0); + if (m_view) + m_view->setLogScale(m_logZ); + m_smoothDirty = true; + m_contourDirty = true; + if (m_panel) + m_panel->setImageLog(m_logZ); // keeps the panel's lin/log chooser in sync + Update(); +} + +// --------------------------------------------------------------------------- +// data +// --------------------------------------------------------------------------- +void SlsQt2DPlot::SetData(int nbinsx, double xmin, double xmax, int nbinsy, + double ymin, double ymax, double *d, double zmin, + double zmax) { + m_hist->SetData(nbinsx, xmin, xmax, nbinsy, ymin, ymax, d, zmin, zmax); + const bool newGeometry = (m_hist->GetNBinsX() != m_lastNx || + m_hist->GetNBinsY() != m_lastNy); + m_lastNx = m_hist->GetNBinsX(); + m_lastNy = m_hist->GetNBinsY(); + if (newGeometry) { + // New frame geometry: drop the scale-panel override and fit the whole + // frame (zoom is preserved across frames of the same size). An + // explicit Plot-tab range (m_userZOverride) survives: qDrawPlot still + // has those min/max values and re-applies them every frame. + m_panelZOverride = false; + m_applyViewPending = true; + } + if (zmax != -1.0) { + // The frame itself carries an explicit z range: it takes over from any + // previous user/panel range (and Update() must apply it, not skip). + m_userZOverride = false; + m_panelZOverride = false; + } + pushImage(); + m_smoothDirty = true; + m_contourDirty = true; + Update(); +} + +void SlsQt2DPlot::pushImage() { + if (!m_view || !m_hist) + return; + const int nx = m_hist->GetNBinsX(); + const int ny = m_hist->GetNBinsY(); + if (nx < 1 || ny < 1) + return; + m_view->setImageCopy(m_hist->GetDataPtr(), nx, ny); +} + +void SlsQt2DPlot::SetBinValue(int bx, int by, double v) { + m_hist->SetBinValue(bx, by, v); + if (m_view && m_hist->GetNBinsX() > 0 && m_hist->GetNBinsY() > 0) { + pushImage(); + m_smoothDirty = true; + m_contourDirty = true; + Update(); + } +} + +void SlsQt2DPlot::FillTestPlot(int mode) { + const int nx = 50; + const int ny = 50; + m_testData.assign(static_cast(nx) * static_cast(ny), 0.0); + const double dmax = + std::sqrt(std::pow(nx / 2.0 - 0.5, 2) + std::pow(ny / 2.0 - 0.5, 2)); + for (int i = 0; i < nx; i++) { + for (int j = 0; j < ny; j++) { + const double d = std::sqrt(std::pow(nx / 2.0 - (i + 0.5), 2) + + std::pow(ny / 2.0 - (j + 0.5), 2)); + m_testData[static_cast(i) + + static_cast(j) * static_cast(nx)] = + (mode % 3) ? 10 * d / dmax : 10 * (1 - d / dmax); + } + } + SetData(nx, 200, 822, ny, -0.5, ny - 0.5, m_testData.data()); +} + +void SlsQt2DPlot::Update() { + if (!m_view) + return; + if (m_gain) { + m_view->update(); + return; + } + if (m_applyViewPending) + applyPendingView(); + if (!m_panelZOverride && !m_userZOverride && m_hist) { + if (m_logZ) + m_hist->SetMinimumToFirstGreaterThanZero(); + applyZRange(m_hist->GetMinimum(), m_hist->GetMaximum()); + } + if (m_interp && m_smoothDirty) + rebuildSmoothImage(); + if (m_contourOn && m_contourDirty) + updateContours(); + m_view->update(); + if (m_panel) + m_panel->refresh(); +} + +// --------------------------------------------------------------------------- +// rendering options +// --------------------------------------------------------------------------- +void SlsQt2DPlot::SetInterpolate(bool enable) { + m_interp = enable; + m_smoothDirty = true; + if (m_interp) + rebuildSmoothImage(); + else { + m_smooth = QImage(); + m_smoothDirty = false; + } + if (m_view) + m_view->update(); +} + +void SlsQt2DPlot::SetContour(bool enable) { + m_contourOn = enable; + m_contourDirty = true; + if (m_contourOn) + updateContours(); + else + m_contourSegments.clear(); + if (m_view) + m_view->update(); +} + +void SlsQt2DPlot::showSpectrogram(bool on) { + m_showImage = on; + if (m_view) + m_view->update(); +} + +// --------------------------------------------------------------------------- +// ROI overlays: the ROI list is in bin indices; pixel (ix,iy) covers +// [ix,ix+1)x[iy,iy+1) in FastImageView coordinates, so the conversion is the +// identity on the index (not on the data coordinate). +// --------------------------------------------------------------------------- +void SlsQt2DPlot::EnableRoiBoxes(std::vector roi) { + m_roiRects.clear(); + m_roiRects.reserve(roi.size()); + for (const auto &r : roi) { + if (r.xmax < r.xmin || r.ymax < r.ymin) + continue; + m_roiRects.emplace_back(QRectF(double(r.xmin), double(r.ymin), + double(r.xmax - r.xmin + 1), + double(r.ymax - r.ymin + 1))); + } + if (m_view) { + m_view->setOverlayRects(m_roiRects); + m_view->update(); + } +} + +void SlsQt2DPlot::DisableRoiBoxes() { + m_roiRects.clear(); + if (m_view) { + m_view->clearOverlayRects(); + m_view->update(); + } +} + +// --------------------------------------------------------------------------- +// coordinate conversions: data (bin-centre) <-> image (pixel-edge) +// --------------------------------------------------------------------------- +double SlsQt2DPlot::dataXToImage(double x) const { + const double w = m_hist->GetXBinWidth(); + return (w > 0.0) ? (x - m_hist->GetXMin()) / w : 0.0; +} + +double SlsQt2DPlot::dataYToImage(double y) const { + const double w = m_hist->GetYBinWidth(); + return (w > 0.0) ? (y - m_hist->GetYMin()) / w : 0.0; +} + +double SlsQt2DPlot::imageXToData(double u) const { + return m_hist->GetXMin() + u * m_hist->GetXBinWidth(); +} + +double SlsQt2DPlot::imageYToData(double v) const { + return m_hist->GetYMin() + v * m_hist->GetYBinWidth(); +} + +// --------------------------------------------------------------------------- +// bilinear interpolation overlay +// +// SlsQtFastImage always displays one colour per data pixel. When the user +// enables "interpolate" we compose the same colour-mapped image at data +// resolution and let QPainter resample it bilinearly on top of the (opaque) +// pixel image; pixel detail / deep zoom keeps the crisp pixel view. The ROI +// boxes are redrawn above it so they stay visible. +// --------------------------------------------------------------------------- +void SlsQt2DPlot::rebuildSmoothImage() { + m_smoothDirty = false; + if (!m_interp || !m_view || !m_hist) { + m_smooth = QImage(); + return; + } + const int nx = m_hist->GetNBinsX(); + const int ny = m_hist->GetNBinsY(); + const double *src = m_hist->GetDataPtr(); + if (nx < 1 || ny < 1 || !src) { + m_smooth = QImage(); + return; + } + if (m_smooth.size() != QSize(nx, ny) || + m_smooth.format() != QImage::Format_RGB32) + m_smooth = QImage(nx, ny, QImage::Format_RGB32); + + double lo = 0.0, hi = 1.0; + m_view->colorRange(lo, hi); + const bool log = m_view->logScale(); + const double loD = log ? plot::logClamp(lo) : lo; + const double hiD = log ? plot::logClamp(hi) : hi; + double range = hiD - loD; + if (!std::isfinite(range) || !(range > 0.0)) + range = 1.0; + const double scale = 255.0 / range; + const bool zeroWhite = m_view->zeroWhite(); + const QRgb *pal = m_palette; + + for (int y = 0; y < ny; y++) { + // Exactly one flip, like SlsQtFastImage: QImage row = ny-1-dataRow. + QRgb *line = reinterpret_cast(m_smooth.scanLine(ny - 1 - y)); + const double *s = src + static_cast(y) * static_cast(nx); + for (int x = 0; x < nx; x++) { + const double v = s[x]; + if (!std::isfinite(v)) { + line[x] = pal[0]; + continue; + } + if (zeroWhite && !(v > 0.0)) { + line[x] = qRgb(255, 255, 255); + continue; + } + int idx = + static_cast(((log ? plot::logClamp(v) : v) - loD) * scale); + if (idx < 0) + idx = 0; + else if (idx > 255) + idx = 255; + line[x] = pal[idx]; + } + } +} + +// --------------------------------------------------------------------------- +// marching squares: ~9 levels over the visible colour range, on a subsampled +// grid (the full 1024x512 grid at 9 levels is unnecessary and slow), in +// FastImageView pixel-edge coordinates. The segments are stored in data +// coordinates and clipped to the plot rect by the FastImageView paint hook. +// --------------------------------------------------------------------------- +void SlsQt2DPlot::updateContours() { + m_contourSegments.clear(); + m_contourDirty = false; + if (!m_contourOn || m_gain || !m_hist || !m_view) + return; + const int nx = m_hist->GetNBinsX(); + const int ny = m_hist->GetNBinsY(); + const double *d = m_hist->GetDataPtr(); + if (!d || nx < 2 || ny < 2) + return; + + double lo = 0.0, hi = 1.0; + m_view->colorRange(lo, hi); + std::vector levels; + levels.reserve(9); + if (m_logZ) { + double a = (lo > 0.0 && std::isfinite(lo)) ? std::log10(lo) : 0.0; + double b = (hi > 0.0 && std::isfinite(hi)) ? std::log10(hi) : a + 1.0; + if (!(b > a)) + b = a + 1.0; + for (int k = 1; k <= 9; k++) + levels.push_back(std::pow(10.0, a + (b - a) * k / 10.0)); + } else { + if (!std::isfinite(lo) || !std::isfinite(hi) || !(hi > lo)) + return; + for (int k = 1; k <= 9; k++) + levels.push_back(lo + (hi - lo) * k / 10.0); + } + + const int step = + std::max(1, static_cast(std::ceil( + double(std::max(nx, ny)) / double(kLowResGrid)))); + + auto intersect = [](double pu, double pv, double qu, double qv, double pval, + double qval, double L) { + const double dv = qval - pval; + double t = (std::abs(dv) > 1e-12) ? (L - pval) / dv : 0.5; + t = std::min(1.0, std::max(0.0, t)); + return QPointF(pu + (qu - pu) * t, pv + (qv - pv) * t); + }; + + // Subsample the grid, but always include the last row/column: a plain + // "i + step < nx" loop left the outermost (up to step-1 pixels wide) band + // without contour segments (R8). Clamping the last sample to nx-1/ny-1 + // makes the contours cover the full frame. + std::vector gridX; + gridX.reserve(static_cast(nx) / static_cast(step) + 2); + for (int i = 0; i < nx; i += step) + gridX.push_back(i); + if (gridX.back() != nx - 1) + gridX.push_back(nx - 1); + std::vector gridY; + gridY.reserve(static_cast(ny) / static_cast(step) + 2); + for (int j = 0; j < ny; j += step) + gridY.push_back(j); + if (gridY.back() != ny - 1) + gridY.push_back(ny - 1); + + for (size_t gy = 0; gy + 1 < gridY.size(); gy++) { + const int j = gridY[gy]; + const int jNext = gridY[gy + 1]; + for (size_t gx = 0; gx + 1 < gridX.size(); gx++) { + const int i = gridX[gx]; + const int iNext = gridX[gx + 1]; + const size_t i0 = static_cast(i); + const size_t i1 = static_cast(iNext); + const size_t j0 = static_cast(j); + const size_t j1 = static_cast(jNext); + const double va = d[i0 + j0 * nx]; + const double vb = d[i1 + j0 * nx]; + const double vc = d[i1 + j1 * nx]; + const double vd = d[i0 + j1 * nx]; + if (!std::isfinite(va) || !std::isfinite(vb) || + !std::isfinite(vc) || !std::isfinite(vd)) + continue; + const double u0 = i + 0.5; + const double u1 = iNext + 0.5; + const double v0 = j + 0.5; + const double v1 = jNext + 0.5; + for (double L : levels) { + const int code = (va > L ? 1 : 0) | (vb > L ? 2 : 0) | + (vc > L ? 4 : 0) | (vd > L ? 8 : 0); + if (code == 0 || code == 15) + continue; + const QPointF e0 = + intersect(u0, v0, u1, v0, va, vb, L); // bottom + const QPointF e1 = + intersect(u1, v0, u1, v1, vb, vc, L); // right + const QPointF e2 = + intersect(u0, v1, u1, v1, vd, vc, L); // top + const QPointF e3 = + intersect(u0, v0, u0, v1, va, vd, L); // left + const bool centerHigh = (va + vb + vc + vd) * 0.25 > L; + auto add = [this](const QPointF &a, const QPointF &b) { + m_contourSegments.push_back({a, b}); + }; + switch (code) { + case 1: + add(e3, e0); + break; + case 2: + add(e0, e1); + break; + case 3: + add(e3, e1); + break; + case 4: + add(e1, e2); + break; + case 5: + if (centerHigh) { + add(e0, e1); + add(e2, e3); + } else { + add(e3, e0); + add(e1, e2); + } + break; + case 6: + add(e0, e2); + break; + case 7: + add(e2, e3); + break; + case 8: + add(e2, e3); + break; + case 9: + add(e0, e2); + break; + case 10: + if (centerHigh) { + add(e3, e0); + add(e1, e2); + } else { + add(e0, e1); + add(e2, e3); + } + break; + case 11: + add(e1, e2); + break; + case 12: + add(e1, e3); + break; + case 13: + add(e0, e1); + break; + case 14: + add(e3, e0); + break; + default: + break; + } + if (m_contourSegments.size() >= kMaxContourSegs) + return; + } + } + } +} + +// --------------------------------------------------------------------------- +// clipped paint hook +// --------------------------------------------------------------------------- +void SlsQt2DPlot::drawRois(QPainter &p, const QTransform &t) const { + if (m_roiRects.empty()) + return; + QPen pen(Qt::yellow); + pen.setWidth(1); + pen.setCosmetic(true); + p.save(); + p.setPen(pen); + p.setBrush(Qt::NoBrush); + for (const QRectF &r : m_roiRects) { + const QRectF wr = + QRectF(t.map(r.topLeft()), t.map(r.bottomRight())).normalized(); + p.drawRect(wr); + } + p.restore(); +} + +void SlsQt2DPlot::paintOverlay(QPainter &p, const QTransform &t) { + if (!m_view) + return; + + bool smoothDrawn = false; + if (!m_showImage) { + // WqtPlotSpectrogram image-mode equivalent: hide the image (contours + // and ROI boxes keep painting on the dark background). + p.fillRect(p.viewport(), plot::PlotTheme().background); + } else if (m_interp && !m_smooth.isNull()) { + // Deep zoom keeps the crisp pixel view (grid + values must stay + // readable); otherwise the bilinear image replaces the blocky one. + const double sx = std::abs(t.m11()); + if (sx > 0.0 && sx < 16.0) { + const QRectF target = + QRectF(t.map(QPointF(0.0, 0.0)), + t.map(QPointF(double(m_hist->GetNBinsX()), + double(m_hist->GetNBinsY())))) + .normalized(); + p.save(); + p.setRenderHint(QPainter::SmoothPixmapTransform, true); + p.drawImage(target, m_smooth); + p.restore(); + smoothDrawn = true; + } + } + if (!m_showImage || smoothDrawn) + drawRois(p, t); + + if (m_contourOn && !m_contourSegments.empty()) { + QPen pen(QColor(255, 255, 255, 190)); + pen.setWidth(1); + p.save(); + p.setPen(pen); + p.setBrush(Qt::NoBrush); + for (const ContourSegment &s : m_contourSegments) + p.drawLine(t.map(s.a), t.map(s.b)); + p.restore(); + } +} + +} // namespace sls \ No newline at end of file diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQtFastImage.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQtFastImage.cpp new file mode 100644 index 000000000..012800106 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQtFastImage.cpp @@ -0,0 +1,1212 @@ +// SPDX-License-Identifier: LGPL-3.0-or-other +// Copyright (C) 2026 Contributors to the SLS Detector Package +#include "SlsQtFastImage.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace sls { + +namespace { + +constexpr int kScaleBarWidth = 50; // optional in-view colour bar, widget px +constexpr QRgb kWhite = qRgb(255, 255, 255); + +} // namespace + +SlsQtFastImage::SlsQtFastImage(QWidget *parent) : QWidget(parent) { + setMouseTracking(true); + setFocusPolicy(Qt::StrongFocus); + setMinimumSize(200, 200); + setAttribute(Qt::WA_OpaquePaintEvent, true); + setAttribute(Qt::WA_NoSystemBackground, true); + + const QFont base = font(); + m_titleFont = base; + m_titleFont.setPixelSize(13); + m_titleFont.setBold(true); + m_axisTitleFont = base; + m_axisTitleFont.setPixelSize(11); + m_tickFont = base; + m_tickFont.setPixelSize(10); + + setPaletteLut(plot::paletteLut(plot::Palette::Color)); +} + +SlsQtFastImage::~SlsQtFastImage() = default; + +// --------------------------------------------------------------------------- +// image input +// --------------------------------------------------------------------------- +void SlsQtFastImage::setImageCopy(const float *data, int nx, int ny) { + if (!data || nx <= 0 || ny <= 0) + return; + const size_t n = static_cast(nx) * static_cast(ny); + if (m_owned.size() != n) + m_owned.resize(n); + std::memcpy(m_owned.data(), data, n * sizeof(float)); + const bool newSize = (nx != m_nx || ny != m_ny); + m_data = m_owned.data(); + m_nx = nx; + m_ny = ny; + m_dirty = true; + if (newSize) { + m_hist.clear(); + m_histMs = 0; + m_vpW = -1.0; + m_vpH = -1.0; + } + if (m_vpW < 0) + m_vpW = nx; + if (m_vpH < 0) + m_vpH = ny; + clampViewport(); + update(); +} + +void SlsQtFastImage::setImageCopy(const double *data, int nx, int ny) { + if (!data || nx <= 0 || ny <= 0) + return; + const size_t n = static_cast(nx) * static_cast(ny); + if (m_owned.size() != n) + m_owned.resize(n); + for (size_t i = 0; i < n; i++) + m_owned[i] = static_cast(data[i]); + const bool newSize = (nx != m_nx || ny != m_ny); + m_data = m_owned.data(); + m_nx = nx; + m_ny = ny; + m_dirty = true; + if (newSize) { + m_hist.clear(); + m_histMs = 0; + m_vpW = -1.0; + m_vpH = -1.0; + } + if (m_vpW < 0) + m_vpW = nx; + if (m_vpH < 0) + m_vpH = ny; + clampViewport(); + update(); +} + +// --------------------------------------------------------------------------- +// colour mapping +// --------------------------------------------------------------------------- +void SlsQtFastImage::setPaletteLut(const QRgb *lut) { + if (!lut) + return; + if (onPaletteChanged) + onPaletteChanged(lut); + std::memcpy(m_palette, lut, sizeof(m_palette)); + m_paletteIndex = -1; + for (int i = 0; i <= int(plot::Palette::Gain4); i++) { + if (lut == plot::paletteLut(static_cast(i))) { + m_paletteIndex = i; + break; + } + } + m_dirty = true; + update(); +} + +int SlsQtFastImage::paletteIndex() const { return m_paletteIndex; } + +void SlsQtFastImage::setLogScale(bool on) { + if (m_logScale == on) + return; + m_logScale = on; + m_histMs = 0; // bins follow the mapping + m_dirty = true; + update(); +} + +bool SlsQtFastImage::logScale() const { return m_logScale; } + +void SlsQtFastImage::setIntegerValues(bool on) { + m_integerValues = on; + update(); +} + +bool SlsQtFastImage::integerValues() const { return m_integerValues; } + +void SlsQtFastImage::setZeroWhite(bool on) { + m_zeroWhite = on; + m_dirty = true; + update(); +} + +bool SlsQtFastImage::zeroWhite() const { return m_zeroWhite; } + +void SlsQtFastImage::setColorRange(double lo, double hi) { + m_clo = lo; + m_chi = hi; + m_defClo = lo; + m_defChi = hi; + m_histMs = 0; // the bins follow the window: recompute on the next render + m_dirty = true; + if (onColorRangeChanged) + onColorRangeChanged(lo, hi); + update(); +} + +void SlsQtFastImage::colorRange(double &lo, double &hi) const { + lo = m_clo; + hi = m_chi; +} + +const std::vector &SlsQtFastImage::histogram() const { return m_hist; } + +void SlsQtFastImage::histogramRange(double &lo, double &hi) const { + lo = m_histLo; + hi = m_histHi; +} + +void SlsQtFastImage::invalidateHistogram() { + m_hist.clear(); + m_histMs = 0; +} + +// --------------------------------------------------------------------------- +// geometry / zoom +// --------------------------------------------------------------------------- +void SlsQtFastImage::setPixelAspectX(double a) { + m_pixelAspectX = (a > 0.0 && std::isfinite(a)) ? a : 1.0; + update(); +} + +double SlsQtFastImage::pixelAspectX() const { return m_pixelAspectX; } + +void SlsQtFastImage::setViewport(double x1, double y1, double x2, double y2) { + if (!std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(x2) || + !std::isfinite(y2)) + return; + if (x2 - x1 < kMinimumViewport || y2 - y1 < kMinimumViewport) + return; + m_vpX = x1; + m_vpY = y1; + m_vpW = x2 - x1; + m_vpH = y2 - y1; + clampViewport(); + update(); +} + +void SlsQtFastImage::viewport(double &x, double &y, double &w, + double &h) const { + x = m_vpX; + y = m_vpY; + w = vpW(); + h = vpH(); +} + +void SlsQtFastImage::resetView() { + if (!hasImage()) + return; // nothing to reset yet (and 0,0,0,0 would collapse the map) + m_vpX = 0.0; + m_vpY = 0.0; + m_vpW = m_nx; + m_vpH = m_ny; + if (onZoomChanged) + onZoomChanged(0.0, 0.0, double(m_nx), double(m_ny)); + update(); +} + +bool SlsQtFastImage::hasImage() const { return m_nx > 0 && m_ny > 0; } + +int SlsQtFastImage::imageWidth() const { return m_nx; } + +int SlsQtFastImage::imageHeight() const { return m_ny; } + +QPointF SlsQtFastImage::widgetToData(const QPointF &widgetPos) const { + if (!hasImage()) + return QPointF(0.0, 0.0); + const Fit fit = computeFit(); + if (!(fit.sx > 0.0) || !(fit.sy > 0.0)) + return QPointF(0.0, 0.0); + const double x = + m_vpX + (widgetPos.x() - fit.ir.left() - fit.ox) / fit.sx; + const double y = (m_vpY + vpH()) - + (widgetPos.y() - fit.ir.top() - fit.oy) / fit.sy; + return QPointF(x, y); +} + +QPointF SlsQtFastImage::dataToWidget(const QPointF &dataPos) const { + if (!hasImage()) + return QPointF(0.0, 0.0); + const Fit fit = computeFit(); + const double wx = fit.ir.left() + fit.ox + (dataPos.x() - m_vpX) * fit.sx; + const double wy = fit.ir.top() + fit.oy + + ((m_vpY + vpH()) - dataPos.y()) * fit.sy; + return QPointF(wx, wy); +} + +// --------------------------------------------------------------------------- +// overlays / ROI editor +// --------------------------------------------------------------------------- +void SlsQtFastImage::setRoiRect(double x0, double y0, double x1, double y1, + bool on) { + m_roiX0 = x0; + m_roiY0 = y0; + m_roiX1 = x1; + m_roiY1 = y1; + m_roiOn = on; + update(); +} + +void SlsQtFastImage::setRoiRectVisible(bool on) { + m_roiOn = on; + update(); +} + +bool SlsQtFastImage::roiRect(double &x0, double &y0, double &x1, + double &y1) const { + x0 = m_roiX0; + y0 = m_roiY0; + x1 = m_roiX1; + y1 = m_roiY1; + return m_roiOn; +} + +void SlsQtFastImage::setOverlayRects(const std::vector &rects) { + m_overlays = rects; + update(); +} + +void SlsQtFastImage::clearOverlayRects() { + m_overlays.clear(); + update(); +} + +const std::vector &SlsQtFastImage::overlayRects() const { + return m_overlays; +} + +void SlsQtFastImage::setReceiverRoiRect(double x0, double y0, double x1, + double y1, bool on) { + m_rxX0 = x0; + m_rxY0 = y0; + m_rxX1 = x1; + m_rxY1 = y1; + m_rxOn = on; + update(); +} + +void SlsQtFastImage::clearReceiverRoiRect() { + m_rxOn = false; + update(); +} + +void SlsQtFastImage::beginRoiEdit(bool on) { + m_roiEdit = on; + m_roiGrab = 0; + setCursor(on ? Qt::CrossCursor : Qt::ArrowCursor); + update(); +} + +bool SlsQtFastImage::roiEditActive() const { return m_roiEdit; } + +void SlsQtFastImage::setColorBarVisible(bool on) { + m_showBar = on; + update(); +} + +bool SlsQtFastImage::colorBarVisible() const { return m_showBar; } + +bool SlsQtFastImage::isScaleDragging() const { return m_dragScale; } + +void SlsQtFastImage::setAxesVisible(bool on) { + m_axesVisible = on; + update(); +} + +bool SlsQtFastImage::axesVisible() const { return m_axesVisible; } + +void SlsQtFastImage::setZoomEnabled(bool on) { + m_zoomEnabled = on; + if (!on) { + m_dragging = false; + m_dragScale = false; + } + update(); +} + +bool SlsQtFastImage::zoomEnabled() const { return m_zoomEnabled; } + +// --------------------------------------------------------------------------- +// titles +// --------------------------------------------------------------------------- +void SlsQtFastImage::setTitle(const QString &title) { + m_title = title; + update(); +} + +QString SlsQtFastImage::title() const { return m_title; } + +void SlsQtFastImage::setXAxisTitle(const QString &title) { + m_xTitle = title; + update(); +} + +QString SlsQtFastImage::xAxisTitle() const { return m_xTitle; } + +void SlsQtFastImage::setYAxisTitle(const QString &title) { + m_yTitle = title; + update(); +} + +QString SlsQtFastImage::yAxisTitle() const { return m_yTitle; } + +void SlsQtFastImage::setTitleFont(const QFont &f) { + m_titleFont = f; + update(); +} + +QFont SlsQtFastImage::titleFont() const { return m_titleFont; } + +void SlsQtFastImage::setAxisTitleFont(const QFont &f) { + m_axisTitleFont = f; + update(); +} + +QFont SlsQtFastImage::axisTitleFont() const { return m_axisTitleFont; } + +void SlsQtFastImage::setTickFont(const QFont &f) { + m_tickFont = f; + update(); +} + +QFont SlsQtFastImage::tickFont() const { return m_tickFont; } + +// --------------------------------------------------------------------------- +// layout helpers +// --------------------------------------------------------------------------- +QRect SlsQtFastImage::imageRect() const { + const QFontMetrics titleFm(m_titleFont); + const QFontMetrics axisFm(m_axisTitleFont); + int top = m_axesVisible ? m_theme.topMargin : 0; + int bottom = m_axesVisible ? m_theme.bottomMargin : 0; + int left = m_axesVisible ? m_theme.leftMargin : 0; + int right = m_axesVisible ? m_theme.rightMargin : 0; + if (!m_title.isEmpty()) + top += titleFm.height() + 4; + if (!m_xTitle.isEmpty()) + bottom += axisFm.height() + 4; + if (!m_yTitle.isEmpty()) + left += axisFm.height() + 6; + if (m_showBar) + right += kScaleBarWidth; + int x0 = left, y0 = top; + int x1 = width() - right, y1 = height() - bottom; + if (x1 - x0 < 10) + x1 = x0 + 10; + if (y1 - y0 < 10) + y1 = y0 + 10; + return QRect(x0, y0, x1 - x0, y1 - y0); +} + +QRect SlsQtFastImage::scaleRect() const { + if (!m_showBar) + return QRect(); + const QRect ir = imageRect(); + return QRect(ir.right() + 4, ir.top(), kScaleBarWidth - 4, ir.height()); +} + +SlsQtFastImage::Fit SlsQtFastImage::computeFit() const { + Fit f; + f.ir = imageRect(); + if (!hasImage() || !(vpW() > 0.0) || !(vpH() > 0.0)) + return f; + if (m_pixelAspectX != 1.0) { + const double fitY = double(f.ir.height()) / vpH(); + const double fitX = double(f.ir.width()) / (vpW() * m_pixelAspectX); + f.sy = std::min(fitY, fitX); + f.sx = f.sy * m_pixelAspectX; + } else { + const double fitX = double(f.ir.width()) / vpW(); + const double fitY = double(f.ir.height()) / vpH(); + f.sx = f.sy = std::min(fitX, fitY); + } + f.ox = (f.ir.width() - vpW() * f.sx) * 0.5; + f.oy = (f.ir.height() - vpH() * f.sy) * 0.5; + return f; +} + +// Keeps the viewport inside the image and no smaller than the minimum. +void SlsQtFastImage::clampViewport() { + if (!hasImage()) + return; + if (m_vpW > m_nx) + m_vpW = m_nx; + if (m_vpH > m_ny) + m_vpH = m_ny; + if (m_vpW < std::min(kMinimumViewport, double(m_nx))) + m_vpW = std::min(kMinimumViewport, double(m_nx)); + if (m_vpH < std::min(kMinimumViewport, double(m_ny))) + m_vpH = std::min(kMinimumViewport, double(m_ny)); + if (m_vpX < 0.0) + m_vpX = 0.0; + if (m_vpX + vpW() > m_nx) + m_vpX = m_nx - vpW(); + if (m_vpY < 0.0) + m_vpY = 0.0; + if (m_vpY + vpH() > m_ny) + m_vpY = m_ny - vpH(); +} + +// The whole-frame view is letterboxed on purpose; any other view keeps the +// shape of the plot area so the image always fills it (used on resize and +// when the viewport is initialised for zoom, not during wheel zoom). +void SlsQtFastImage::matchViewportToWindow() { + if (!hasImage()) + return; + if (vpW() >= m_nx - 0.5 && vpH() >= m_ny - 0.5) + return; + const QRect ir = imageRect(); + if (ir.width() <= 0 || ir.height() <= 0) + return; + const double ar = double(ir.width()) / double(ir.height()) / m_pixelAspectX; + double w = vpW(), h = vpH(); + if (w / h > ar) + h = w / ar; // too wide -> grow vertically + else + w = h * ar; // too tall -> grow horizontally + if (w > m_nx) { // grown past the sensor: shrink both, keep the shape + h *= m_nx / w; + w = m_nx; + } + if (h > m_ny) { + w *= m_ny / h; + h = m_ny; + } + const double cx = m_vpX + vpW() / 2.0, cy = m_vpY + vpH() / 2.0; + m_vpW = w; + m_vpH = h; + m_vpX = cx - w / 2.0; + m_vpY = cy - h / 2.0; + clampViewport(); + if (onZoomChanged) + onZoomChanged(m_vpX, m_vpY, m_vpX + vpW(), m_vpY + vpH()); +} + +void SlsQtFastImage::resizeEvent(QResizeEvent *) { + matchViewportToWindow(); + update(); +} + +// --------------------------------------------------------------------------- +// composition: one scanline write per image row, exactly one flip +// --------------------------------------------------------------------------- +void SlsQtFastImage::renderImage() { + m_dirty = false; + if (!m_data || m_nx <= 0 || m_ny <= 0) + return; + if (m_image.size() != QSize(m_nx, m_ny) || + m_image.format() != QImage::Format_RGB32) + m_image = QImage(m_nx, m_ny, QImage::Format_RGB32); + + // log: values <= 0 are capped at 1e-2 (log10 = -2), so an empty pixel is + // still distinguishable instead of becoming -inf + const double loD = m_logScale ? sls::plot::logClamp(m_clo) : m_clo; + const double hiD = m_logScale ? sls::plot::logClamp(m_chi) : m_chi; + const double range = (hiD > loD) ? (hiD - loD) : 1.0; + const double scale = 255.0 / range; + const bool logScale = m_logScale; + const bool zeroWhite = m_zeroWhite; + const QRgb *palette = m_palette; + + for (int y = 0; y < m_ny; y++) { + // QImage row 0 is the top, data row 0 is the bottom: the flip happens + // here, once, and nowhere else. + QRgb *line = reinterpret_cast(m_image.scanLine(m_ny - 1 - y)); + const float *src = m_data + static_cast(y) * size_t(m_nx); + if (logScale) { + for (int x = 0; x < m_nx; x++) { + const double v = src[x]; + if (!std::isfinite(v)) { + line[x] = palette[0]; + continue; + } + if (zeroWhite && !(v > 0.0)) { + line[x] = kWhite; + continue; + } + int idx = int((sls::plot::logClamp(v) - loD) * scale); + if (idx < 0) + idx = 0; + else if (idx > 255) + idx = 255; + line[x] = palette[idx]; + } + } else { + for (int x = 0; x < m_nx; x++) { + const double v = src[x]; + if (!std::isfinite(v)) { + line[x] = palette[0]; + continue; + } + if (zeroWhite && !(v > 0.0)) { + line[x] = kWhite; + continue; + } + int idx = int((v - loD) * scale); + if (idx < 0) + idx = 0; + else if (idx > 255) + idx = 255; + line[x] = palette[idx]; + } + } + } + + // Histogram for the scale panel: walking the whole frame is cheap enough at + // the image cadence, but the panel only needs the shape, so a few times a + // second is plenty. Bin over the window the strip displays (the colour + // range widened by half a range; log space when log), skip values outside + // it - a photon map accumulates to thousands of counts while its scale + // shows 0..12, so full-range binning would put the whole window in one bin. + const qint64 now = QDateTime::currentMSecsSinceEpoch(); + if (m_hist.empty() || m_hist.size() != 256 || now - m_histMs > 300) { + m_histMs = now; + double dlo, dhi; + if (m_logScale) { + const double a = sls::plot::logClamp(m_clo); + const double b = sls::plot::logClamp(m_chi); + dlo = a; + dhi = b; + } else { + dlo = m_clo; + dhi = m_chi; + } + if (!std::isfinite(dlo) || !std::isfinite(dhi)) + dlo = 0.0, dhi = 1.0; + if (!(dhi > dlo)) + dhi = dlo + 1.0; + const double span = dhi - dlo; + double hlo = dlo - 0.5 * span; + double hhi = dhi + 0.5 * span; + if (!(hhi > hlo)) + hhi = hlo + 1.0; + m_histLo = hlo; + m_histHi = hhi; + m_hist.assign(256, 0); + const double sc = 255.0 / (hhi - hlo); + const size_t n = size_t(m_nx) * size_t(m_ny); + for (size_t p = 0; p < n; p++) { + const double raw = m_data[p]; + if (!std::isfinite(raw)) + continue; + const double v = logScale ? sls::plot::logClamp(raw) : raw; + if (v < hlo || v > hhi) + continue; // outside the visible window + int b = int((v - hlo) * sc); + if (b < 0) + b = 0; + else if (b > 255) + b = 255; + m_hist[b]++; + } + if (onImageChanged) + onImageChanged(); + } +} + +// --------------------------------------------------------------------------- +// painting +// --------------------------------------------------------------------------- +void SlsQtFastImage::paintEvent(QPaintEvent *) { + if (m_dirty) + renderImage(); + QPainter p(this); + p.fillRect(rect(), m_theme.background); + if (!hasImage()) + return; + + const Fit fit = computeFit(); + m_sx = fit.sx; + drawImage(p, fit); + drawAxes(p, fit); + drawPixelDetail(p, fit); + // Overlays last (before titles) so a ROI edge that lies on a pixel + // boundary is not hidden by the pixel grid. + drawOverlays(p, fit); + if (onPaintOverlay) { + // Data-space overlay hook (contour lines etc.), clipped like the image. + p.save(); + p.setClipRect(fit.ir); + const QTransform dataToWidget( + fit.sx, 0.0, 0.0, -fit.sy, + fit.ir.left() + fit.ox - m_vpX * fit.sx, + fit.ir.top() + fit.oy + (m_vpY + vpH()) * fit.sy); + onPaintOverlay(p, dataToWidget); + p.restore(); + } + drawTitles(p, fit); + if (m_showBar) + drawColorBar(p); +} + +void SlsQtFastImage::drawImage(QPainter &p, const Fit &fit) { + const QRect ir = fit.ir; + p.save(); + // Zoomed in, the scaled image is larger than the plot area: without this + // clip it spills over the frame and the tick labels. + p.setClipRect(ir); + p.translate(ir.left() + fit.ox, ir.top() + fit.oy); + p.scale(fit.sx, fit.sy); + // Display row of the top edge of the viewport (QImage rows are top-down). + const double topRow = double(m_ny) - (m_vpY + vpH()); + p.translate(-m_vpX, -topRow); + p.drawImage(QPoint(0, 0), m_image); + p.restore(); +} + +void SlsQtFastImage::drawOverlays(QPainter &p, const Fit &fit) { + const QRect ir = fit.ir; + auto toWidget = [&](double x, double y) { + return QPointF(ir.left() + fit.ox + (x - m_vpX) * fit.sx, + ir.top() + fit.oy + ((m_vpY + vpH()) - y) * fit.sy); + }; + auto rectWidget = [&](double x0, double y0, double x1, double y1) { + const QRectF r(toWidget(x0, y0), toWidget(x1, y1)); + return r.normalized(); + }; + + // Overlays live in the same plot area: clip them as well. + p.save(); + p.setClipRect(ir); + + // Editable yellow ROI (gate ROI), drawn in data coordinates. + if (m_roiOn && m_roiX1 > m_roiX0 && m_roiY1 > m_roiY0) { + const QRectF r = rectWidget(m_roiX0, m_roiY0, m_roiX1, m_roiY1); + QPen pen(Qt::yellow); + pen.setWidth(m_roiEdit ? 2 : 1); + pen.setCosmetic(true); + p.setPen(pen); + p.setBrush(Qt::NoBrush); + p.drawRect(r); + if (m_roiEdit) { // corner and edge handles: what can be grabbed + const double hw = 3.0; // half handle size, in widget pixels + const double xs[3] = {r.left(), r.center().x(), r.right()}; + const double ys[3] = {r.top(), r.center().y(), r.bottom()}; + p.setBrush(QColor(255, 255, 80)); + for (int iy = 0; iy < 3; iy++) { + for (int ix = 0; ix < 3; ix++) { + if (ix == 1 && iy == 1) + continue; // centre handle would only be confusing + p.drawRect( + QRectF(xs[ix] - hw, ys[iy] - hw, 2 * hw, 2 * hw)); + } + } + } + } + + // Additional yellow rectangles (e.g. all receiver ROIs). + if (!m_overlays.empty()) { + QPen pen(Qt::yellow); + pen.setWidth(1); + pen.setCosmetic(true); + p.setPen(pen); + p.setBrush(Qt::NoBrush); + for (const QRectF &o : m_overlays) { + if (!(o.width() > 0.0) || !(o.height() > 0.0)) + continue; + p.drawRect(rectWidget(o.left(), o.top(), o.left() + o.width(), + o.top() + o.height())); + } + } + + // Red receiver-ROI box, same data coordinates. + if (m_rxOn && m_rxX1 > m_rxX0 && m_rxY1 > m_rxY0) { + QPen pen(Qt::red); + pen.setWidth(1); + pen.setCosmetic(true); + p.setPen(pen); + p.setBrush(Qt::NoBrush); + p.drawRect(rectWidget(m_rxX0, m_rxY0, m_rxX1, m_rxY1)); + } + p.restore(); // back to the full widget for the axes +} + +void SlsQtFastImage::drawAxes(QPainter &p, const Fit &fit) { + if (!m_axesVisible) + return; + const QRect ir = fit.ir; + p.setFont(m_tickFont); + const double x0 = m_vpX, x1 = m_vpX + vpW(); + const double y0 = m_vpY, y1 = m_vpY + vpH(); + const double stepX = sls::plot::niceStep(x1 - x0, 8); + const double stepY = sls::plot::niceStep(y1 - y0, 8); + const std::vector ticksX = sls::plot::computeLinearTicks(x0, x1, 8); + const std::vector ticksY = sls::plot::computeLinearTicks(y0, y1, 8); + + p.save(); + p.setClipRect(ir); + QPen grid(m_theme.grid); + grid.setStyle(Qt::DotLine); + QPen tick(m_theme.tick); + tick.setWidth(1); + for (double gx : ticksX) { + const double wx = fit.ir.left() + fit.ox + (gx - m_vpX) * fit.sx; + p.setPen(grid); + p.drawLine(QPointF(wx, ir.top()), QPointF(wx, ir.bottom())); + } + for (double gy : ticksY) { + const double wy = + fit.ir.top() + fit.oy + ((m_vpY + vpH()) - gy) * fit.sy; + p.setPen(grid); + p.drawLine(QPointF(ir.left(), wy), QPointF(ir.right(), wy)); + } + p.restore(); + + // ticks and labels outside the frame + p.save(); + p.setPen(tick); + for (double gx : ticksX) { + const double wx = fit.ir.left() + fit.ox + (gx - m_vpX) * fit.sx; + p.drawLine(QPointF(wx, ir.bottom() + 1), QPointF(wx, ir.bottom() + 4)); + p.setPen(m_theme.tick); + p.drawText(QRectF(wx - 30, ir.bottom() + 5, 60, 14), + Qt::AlignHCenter | Qt::AlignTop, + sls::plot::formatTick(gx, stepX)); + p.setPen(tick); + } + for (double gy : ticksY) { + const double wy = + fit.ir.top() + fit.oy + ((m_vpY + vpH()) - gy) * fit.sy; + p.drawLine(QPointF(ir.left() - 4, wy), QPointF(ir.left() - 1, wy)); + p.drawText(QRectF(ir.left() - 50, wy - 7, 44, 14), + Qt::AlignRight | Qt::AlignVCenter, + sls::plot::formatTick(gy, stepY)); + } + p.setPen(QPen(m_theme.frame)); + p.setBrush(Qt::NoBrush); + p.drawRect(ir.adjusted(0, 0, -1, -1)); + p.restore(); +} + +void SlsQtFastImage::drawPixelDetail(QPainter &p, const Fit &fit) { + // Pixel outlines and in-pixel values, once one pixel is big enough. The + // thresholds are computed from the fit scale, not from a fixed zoom level. + if (m_sx < 16.0) + return; + const QRect ir = fit.ir; + const double x0 = m_vpX, x1 = m_vpX + vpW(); + const double y0 = m_vpY, y1 = m_vpY + vpH(); + p.save(); + p.setClipRect(ir); + // thin outline around every pixel (only when a sane number is visible) + if (vpW() <= 256 && vpH() <= 256) { + QPen px(QColor(55, 55, 55)); + px.setCosmetic(true); + p.setPen(px); + for (int gx = int(std::floor(x0)); gx <= int(std::ceil(x1)); gx++) { + const double wx = ir.left() + fit.ox + (gx - m_vpX) * fit.sx; + if (wx < ir.left() - 0.5 || wx > ir.right() + 0.5) + continue; + p.drawLine(QPointF(wx, ir.top()), QPointF(wx, ir.bottom())); + } + for (int gy = int(std::floor(y0)); gy <= int(std::ceil(y1)); gy++) { + const double wy = + ir.top() + fit.oy + ((m_vpY + vpH()) - gy) * fit.sy; + if (wy < ir.top() - 0.5 || wy > ir.bottom() + 0.5) + continue; + p.drawLine(QPointF(ir.left(), wy), QPointF(ir.right(), wy)); + } + } + if (m_sx >= 50.0 && vpW() <= 64 && vpH() <= 64) { + const int maxChars = m_integerValues ? 5 : 6; + const double cell = std::min(fit.sx, fit.sy); + const double bySize = cell * 0.30; + const double byWidth = fit.sx * 0.92 / (0.62 * maxChars); + QFont f = m_tickFont; + f.setPixelSize(std::max( + 7, std::min(20, int(std::min(bySize, byWidth))))); + p.setFont(f); + for (int gy = int(std::floor(y0)); gy <= int(std::ceil(y1)); gy++) { + if (gy < 0 || gy >= m_ny) + continue; + for (int gx = int(std::floor(x0)); gx <= int(std::ceil(x1)); gx++) { + if (gx < 0 || gx >= m_nx) + continue; + const double v = m_data[gx + gy * m_nx]; + if (!std::isfinite(v)) + continue; + // text colour from the pixel that was actually painted + const QRgb c = m_image.pixel(gx, m_ny - 1 - gy); + const int lum = + (qRed(c) * 299 + qGreen(c) * 587 + qBlue(c) * 114) / 1000; + p.setPen(lum > 140 ? QColor(15, 15, 15) + : QColor(245, 245, 245)); + const QString txt = + m_integerValues + ? QString::number(qint64(std::llround(v))) + : QString::number(v, 'f', 1); + const QPointF ctr = + QPointF(ir.left() + fit.ox + (gx + 0.5 - m_vpX) * fit.sx, + ir.top() + fit.oy + + ((m_vpY + vpH()) - (gy + 0.5)) * fit.sy); + p.drawText(QRectF(ctr.x() - fit.sx * 0.5, + ctr.y() - fit.sy * 0.5, fit.sx, fit.sy), + Qt::AlignCenter, txt); + } + } + } + p.restore(); +} + +void SlsQtFastImage::drawTitles(QPainter &p, const Fit &fit) { + const QRect ir = fit.ir; + if (!m_title.isEmpty()) { + p.setFont(m_titleFont); + p.setPen(m_theme.text); + p.drawText(QRectF(0, 1, width(), ir.top() - 2), + Qt::AlignHCenter | Qt::AlignVCenter, m_title); + } + if (!m_yTitle.isEmpty()) { + const QFontMetrics fm(m_axisTitleFont); + p.save(); + p.setFont(m_axisTitleFont); + p.setPen(m_theme.text); + p.translate(fm.height() / 2.0 + 4.0, ir.center().y()); + p.rotate(-90.0); + p.drawText(QRectF(-ir.height() / 2.0, -fm.height() / 2.0, + ir.height(), fm.height()), + Qt::AlignCenter, m_yTitle); + p.restore(); + } + if (!m_xTitle.isEmpty()) { + p.setFont(m_axisTitleFont); + p.setPen(m_theme.text); + p.drawText(QRectF(ir.left(), ir.bottom() + m_theme.bottomMargin, + ir.width(), + height() - ir.bottom() - m_theme.bottomMargin), + Qt::AlignHCenter | Qt::AlignTop, m_xTitle); + } +} + +void SlsQtFastImage::drawColorBar(QPainter &p) { + const QRect sr = scaleRect(); + if (sr.height() <= 0) + return; + for (int yy = sr.top(); yy <= sr.bottom(); yy++) { + const double frac = 1.0 - double(yy - sr.top()) / sr.height(); + int idx = int(frac * 255.0); + if (idx < 0) + idx = 0; + else if (idx > 255) + idx = 255; + p.setPen(m_palette[idx]); + p.drawLine(sr.left(), yy, sr.right(), yy); + } + p.setPen(m_theme.frame); + p.drawRect(sr.adjusted(-1, -1, 1, 1)); + p.setFont(m_tickFont); + p.setPen(m_theme.text); + p.drawText(sr.left(), sr.top() + 1, sr.width(), 12, Qt::AlignCenter, + QString::number(m_chi, 'g', 4)); + p.drawText(sr.left(), sr.bottom() - 11, sr.width(), 12, Qt::AlignCenter, + QString::number(m_clo, 'g', 4)); +} + +double SlsQtFastImage::valueAt(const QPoint &pos) const { + const QRect sr = scaleRect(); + if (sr.height() <= 0 || !sr.contains(pos)) + return m_clo - 1.0; + const double frac = 1.0 - double(pos.y() - sr.top()) / sr.height(); + return m_clo + frac * (m_chi - m_clo); +} + +// --------------------------------------------------------------------------- +// interaction +// --------------------------------------------------------------------------- +void SlsQtFastImage::mousePressEvent(QMouseEvent *e) { + if (e->button() != Qt::LeftButton) + return; + const QPoint ip = sls::plot::eventPosition(e).toPoint(); + if (m_roiEdit && hasImage()) { + // which part of the yellow rectangle was grabbed? + const QPointF d = widgetToData(QPointF(ip)); + const QPointF d2 = widgetToData(QPointF(ip + QPoint(8, 0))); + const double tol = std::max(1e-9, std::abs(d2.x() - d.x())); + const bool nearL = std::abs(d.x() - m_roiX0) <= tol; + const bool nearR = std::abs(d.x() - m_roiX1) <= tol; + const bool nearB = std::abs(d.y() - m_roiY0) <= tol; + const bool nearT = std::abs(d.y() - m_roiY1) <= tol; + const bool inX = d.x() >= m_roiX0 - tol && d.x() <= m_roiX1 + tol; + const bool inY = d.y() >= m_roiY0 - tol && d.y() <= m_roiY1 + tol; + m_roiGrab = 0; + if (nearL && nearB) + m_roiGrab = 6; + else if (nearR && nearB) + m_roiGrab = 7; + else if (nearL && nearT) + m_roiGrab = 8; + else if (nearR && nearT) + m_roiGrab = 9; + else if (nearL && inY) + m_roiGrab = 2; + else if (nearR && inY) + m_roiGrab = 3; + else if (nearB && inX) + m_roiGrab = 4; + else if (nearT && inX) + m_roiGrab = 5; + else if (inX && inY) + m_roiGrab = 1; + else + m_roiGrab = 10; // start a new rectangle at the cursor + m_roiPress = d; + m_roiStart[0] = m_roiX0; + m_roiStart[1] = m_roiY0; + m_roiStart[2] = m_roiX1; + m_roiStart[3] = m_roiY1; + if (m_roiGrab == 10) { + m_roiX0 = m_roiX1 = std::max(0.0, std::min(double(m_nx), d.x())); + m_roiY0 = m_roiY1 = std::max(0.0, std::min(double(m_ny), d.y())); + m_roiOn = true; + } + update(); + return; + } + const QRect sr = scaleRect(); + if (sr.height() > 0 && sr.contains(ip)) { + m_dragScale = true; + m_dragScaleY = ip.y(); + m_dragClo = m_clo; + m_dragChi = m_chi; + m_dragMax = (ip.y() < sr.top() + sr.height() / 2); + setCursor(Qt::SizeVerCursor); + return; + } + if (!m_zoomEnabled) + return; // fixed view (gain map): no panning + m_dragging = true; + m_lastPos = QPointF(ip); + m_dragVpX = m_vpX; + m_dragVpY = m_vpY; + setCursor(Qt::ClosedHandCursor); +} + +void SlsQtFastImage::mouseMoveEvent(QMouseEvent *e) { + const QPointF pos = sls::plot::eventPosition(e); + if (m_roiEdit && hasImage()) { + const QPointF d = widgetToData(pos); + const double x = std::max(0.0, std::min(double(m_nx), d.x())); + const double y = std::max(0.0, std::min(double(m_ny), d.y())); + constexpr double kMin = 2.0; // a ROI smaller than this is unusable + if (m_roiGrab == 10) { // dragging out a new rectangle + m_roiX0 = std::min(m_roiPress.x(), x); + m_roiX1 = std::max(m_roiPress.x(), x); + m_roiY0 = std::min(m_roiPress.y(), y); + m_roiY1 = std::max(m_roiPress.y(), y); + m_roiOn = true; + } else if (m_roiGrab == 1) { // move the whole rectangle + const double dx = x - m_roiPress.x(); + const double dy = y - m_roiPress.y(); + double x0 = m_roiStart[0] + dx, x1 = m_roiStart[2] + dx; + double y0 = m_roiStart[1] + dy, y1 = m_roiStart[3] + dy; + if (x0 < 0.0) { + x1 -= x0; + x0 = 0.0; + } + if (x1 > m_nx) { + x0 -= (x1 - m_nx); + x1 = m_nx; + } + if (y0 < 0.0) { + y1 -= y0; + y0 = 0.0; + } + if (y1 > m_ny) { + y0 -= (y1 - m_ny); + y1 = m_ny; + } + m_roiX0 = x0; + m_roiX1 = x1; + m_roiY0 = y0; + m_roiY1 = y1; + } else if (m_roiGrab != 0) { // one edge or one corner + double x0 = m_roiStart[0], y0 = m_roiStart[1]; + double x1 = m_roiStart[2], y1 = m_roiStart[3]; + const bool left = (m_roiGrab == 2 || m_roiGrab == 6 || + m_roiGrab == 8); + const bool right = (m_roiGrab == 3 || m_roiGrab == 7 || + m_roiGrab == 9); + const bool bottom = (m_roiGrab == 4 || m_roiGrab == 6 || + m_roiGrab == 7); + const bool top = (m_roiGrab == 5 || m_roiGrab == 8 || + m_roiGrab == 9); + if (left && x <= x1 - kMin) + x0 = x; + if (right && x >= x0 + kMin) + x1 = x; + if (bottom && y <= y1 - kMin) + y0 = y; + if (top && y >= y0 + kMin) + y1 = y; + m_roiX0 = x0; + m_roiY0 = y0; + m_roiX1 = x1; + m_roiY1 = y1; + } + update(); + if (m_roiGrab == 0) { // hovering: show what grabbing here would do + const QPointF dd = widgetToData(pos); + const QPointF dd2 = widgetToData(pos + QPointF(8, 0)); + const double tol = std::max(1e-9, std::abs(dd2.x() - dd.x())); + const bool nearL = std::abs(dd.x() - m_roiX0) <= tol; + const bool nearR = std::abs(dd.x() - m_roiX1) <= tol; + const bool nearB = std::abs(dd.y() - m_roiY0) <= tol; + const bool nearT = std::abs(dd.y() - m_roiY1) <= tol; + const bool inside = dd.x() >= m_roiX0 - tol && + dd.x() <= m_roiX1 + tol && + dd.y() >= m_roiY0 - tol && + dd.y() <= m_roiY1 + tol; + if ((nearL && nearT) || (nearR && nearB)) + setCursor(Qt::SizeFDiagCursor); + else if ((nearL && nearB) || (nearR && nearT)) + setCursor(Qt::SizeBDiagCursor); + else if (nearL || nearR) + setCursor(Qt::SizeHorCursor); + else if (nearT || nearB) + setCursor(Qt::SizeVerCursor); + else + setCursor(inside ? Qt::OpenHandCursor : Qt::CrossCursor); + } + return; + } + if (m_dragScale) { + const QRect sr = scaleRect(); + if (sr.height() <= 0) + return; + const double delta = double(sls::plot::eventPosition(e).toPoint().y() - m_dragScaleY) / + double(sr.height()) * (m_dragChi - m_dragClo); + if (m_dragMax) { + m_chi = m_dragChi - delta; + if (m_chi < m_clo + 1.0) + m_chi = m_clo + 1.0; + } else { + m_clo = m_dragClo - delta; + if (m_clo > m_chi - 1.0) + m_clo = m_chi - 1.0; + } + m_dirty = true; + update(); + return; + } + if (!m_dragging) { + const QPoint hp = pos.toPoint(); + const QRect ir2 = imageRect(); + const QRect sr = scaleRect(); + if (sr.height() > 0 && sr.contains(hp)) { + setCursor(Qt::SizeVerCursor); + setToolTip(QStringLiteral("Scale: %1") + .arg(valueAt(hp), 0, 'f', 0)); + } else if (ir2.contains(hp) && hasImage()) { + setCursor(Qt::OpenHandCursor); + // widgetToData() returns data rows (row 0 = bottom), matching the + // ROOT plots and the ROI list: (0,0) is the bottom-left pixel. + const QPointF d = widgetToData(pos); + const int ix = int(std::floor(d.x())); + const int iy = int(std::floor(d.y())); + if (ix >= 0 && ix < m_nx && iy >= 0 && iy < m_ny) + setToolTip(QStringLiteral("(x=%1, y=%2) = %3") + .arg(ix) + .arg(iy) + .arg(double(m_data[ix + iy * m_nx]), 0, 'f', 1)); + } else { + setCursor(Qt::ArrowCursor); + setToolTip(QString()); + } + return; + } + const QPointF now = widgetToData(pos); + const QPointF then = widgetToData(m_lastPos); + m_vpX = m_dragVpX - (now.x() - then.x()); + m_vpY = m_dragVpY - (now.y() - then.y()); + clampViewport(); + update(); + if (onZoomChanged) + onZoomChanged(m_vpX, m_vpY, m_vpX + vpW(), m_vpY + vpH()); +} + +void SlsQtFastImage::mouseReleaseEvent(QMouseEvent *e) { + if (e->button() == Qt::LeftButton && m_roiGrab != 0) { + m_roiGrab = 0; + if (onRoiEdited && m_roiX1 - m_roiX0 >= 2.0 && + m_roiY1 - m_roiY0 >= 2.0) { + onRoiEdited(int(std::lround(m_roiX0)), + int(std::lround(m_roiY0)), + int(std::lround(m_roiX1)), + int(std::lround(m_roiY1))); + } + return; + } + if (e->button() == Qt::LeftButton) { + if (m_dragging && onZoomChanged) + onZoomChanged(m_vpX, m_vpY, m_vpX + vpW(), m_vpY + vpH()); + m_dragging = false; + const bool wasScale = m_dragScale; + m_dragScale = false; + setCursor(Qt::ArrowCursor); + if (wasScale && onScaleReleased) + onScaleReleased(); // one histogram/scale refresh, after the drag + } +} + +void SlsQtFastImage::wheelEvent(QWheelEvent *e) { + if (!hasImage() || !m_zoomEnabled) + return; + const QPointF imgPt = widgetToData(sls::plot::eventPosition(e)); + const double mx = imgPt.x(), my = imgPt.y(); + + const double factor = (e->angleDelta().y() > 0) ? 1.0 / 1.18 : 1.18; + double nw = vpW() * factor, nh = vpH() * factor; + if (nw < std::min(kMinimumViewport, double(m_nx))) + nw = std::min(kMinimumViewport, double(m_nx)); + if (nh < std::min(kMinimumViewport, double(m_ny))) + nh = std::min(kMinimumViewport, double(m_ny)); + if (nw > m_nx) + nw = m_nx; + if (nh > m_ny) + nh = m_ny; + + // Keep the data point under the cursor fixed. (The reference reshaped the + // viewport to the window while zooming in; that moves the cursor point and + // breaks the "zoom keeps the cursor point fixed" invariant.) + const double fracX = (mx - m_vpX) / vpW(); + const double fracY = (my - m_vpY) / vpH(); + m_vpX = mx - fracX * nw; + m_vpY = my - fracY * nh; + m_vpW = nw; + m_vpH = nh; + clampViewport(); + + if (onZoomChanged) + onZoomChanged(m_vpX, m_vpY, m_vpX + vpW(), m_vpY + vpH()); + setToolTip(QStringLiteral("Zoom: %1%").arg(int(100.0 * m_nx / vpW()))); + update(); +} + +void SlsQtFastImage::mouseDoubleClickEvent(QMouseEvent *e) { + const QRect sr = scaleRect(); + if (sr.height() > 0 && sr.contains(sls::plot::eventPosition(e).toPoint())) { + m_clo = m_defClo; + m_chi = m_defChi; + m_histMs = 0; + m_dirty = true; + update(); + } else if (m_zoomEnabled) { + resetView(); + } +} + +} // namespace sls diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQtPlotCommon.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQtPlotCommon.cpp new file mode 100644 index 000000000..7bcd43e16 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQtPlotCommon.cpp @@ -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 + +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(rr * 255.0 + 0.5), + static_cast(gg * 255.0 + 0.5), + static_cast(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(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 computeLinearTicks(double lo, double hi, int maxTicks) { + std::vector 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(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(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(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 diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQtScalePanel.cpp b/slsDetectorGui/slsDetectorPlotting/src/SlsQtScalePanel.cpp new file mode 100644 index 000000000..57dda1948 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQtScalePanel.cpp @@ -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 +#include +#include +#include +#include +#include +#include + +#include +#include + +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 *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 *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 *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(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::of(&QComboBox::currentIndexChanged), + this, [this](int) { push(); }); + connect(m_imageLogCombo, + QOverload::of(&QComboBox::currentIndexChanged), this, + [this](int i) { + if (m_suppress || !m_view) + return; + m_view->setLogScale(i == 1); + refresh(); + }); + connect(m_histoLogCombo, + QOverload::of(&QComboBox::currentIndexChanged), this, + [this](int) { updateHisto(); }); + m_histo->onRangeChanged = [this](double a, double b) { + if (m_suppress || !m_view) + return; + m_view->setColorRange(a, b); + m_controlLo = a; + m_controlHi = b; + refresh(); + }; + + 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(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 diff --git a/slsDetectorGui/src/qCloneWidget.cpp b/slsDetectorGui/src/qCloneWidget.cpp index 0b526dffb..cd30c52bf 100644 --- a/slsDetectorGui/src/qCloneWidget.cpp +++ b/slsDetectorGui/src/qCloneWidget.cpp @@ -9,7 +9,6 @@ #include #include #include -#include namespace sls { diff --git a/slsDetectorGui/src/qDacWidget.cpp b/slsDetectorGui/src/qDacWidget.cpp index cd2489707..24f0f81d6 100644 --- a/slsDetectorGui/src/qDacWidget.cpp +++ b/slsDetectorGui/src/qDacWidget.cpp @@ -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); diff --git a/slsDetectorGui/src/qDetectorMain.cpp b/slsDetectorGui/src/qDetectorMain.cpp index be08272d2..20145a798 100644 --- a/slsDetectorGui/src/qDetectorMain.cpp +++ b/slsDetectorGui/src/qDetectorMain.cpp @@ -15,8 +15,12 @@ #include "sls/ToString.h" #include "sls/versionAPI.h" +#include +#include #include +#include #include +#include #include #include @@ -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( diff --git a/slsDetectorGui/src/qDrawPlot.cpp b/slsDetectorGui/src/qDrawPlot.cpp index 54ffffbfd..c0709c904 100644 --- a/slsDetectorGui/src/qDrawPlot.cpp +++ b/slsDetectorGui/src/qDrawPlot.cpp @@ -13,7 +13,6 @@ #include #include #include -#include 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 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(&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"; } diff --git a/slsDetectorGui/src/qTabDataOutput.cpp b/slsDetectorGui/src/qTabDataOutput.cpp index d7335950b..60e429020 100644 --- a/slsDetectorGui/src/qTabDataOutput.cpp +++ b/slsDetectorGui/src/qTabDataOutput.cpp @@ -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::of(&QButtonGroup::buttonClicked) +#endif + #include #include #include @@ -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())); } diff --git a/slsDetectorGui/src/qVersionResolve.cpp b/slsDetectorGui/src/qVersionResolve.cpp index a348f1375..42a2c7d09 100644 --- a/slsDetectorGui/src/qVersionResolve.cpp +++ b/slsDetectorGui/src/qVersionResolve.cpp @@ -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 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 diff --git a/slsDetectorGui/tests/CMakeLists.txt b/slsDetectorGui/tests/CMakeLists.txt new file mode 100644 index 000000000..554d37215 --- /dev/null +++ b/slsDetectorGui/tests/CMakeLists.txt @@ -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 --target plotting_test +# Run: QT_QPA_PLATFORM=offscreen /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() diff --git a/slsDetectorGui/tests/plotting_test.cpp b/slsDetectorGui/tests/plotting_test.cpp new file mode 100644 index 000000000..26d0e052a --- /dev/null +++ b/slsDetectorGui/tests/plotting_test.cpp @@ -0,0 +1,1882 @@ +// 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 (verification task). +// +// Everything is checked through the public API or through rendered pixels; the +// widgets are shown on the offscreen QPA platform and rendered synchronously +// with QWidget::grab(), so the assertions exercise the same paint path the GUI +// uses. The performance slot is the acceptance benchmark for 1024x512 frames. + +#include "SlsQt1DPlot.h" +#include "SlsQt2DHist.h" +#include "SlsQt2DPlot.h" +#include "SlsQtFastImage.h" +#include "SlsQtPlotCommon.h" +#include "SlsQtScalePanel.h" +#include "sls/sls_detector_defs.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace { + +constexpr QRgb kBackground = qRgb(28, 28, 28); + +bool near(double a, double b, double eps = 1e-6) { + return std::abs(a - b) <= eps; +} + +// Repaint synchronously (runs renderImage + paintEvent) and grab the result. +QImage render(QWidget &w) { + w.repaint(); + return w.grab().toImage(); +} + +QPointF widgetPos(const sls::SlsQtFastImage &view, double dataX, + double dataY) { + return view.dataToWidget(QPointF(dataX, dataY)); +} + +// Most common colour of the 7x7 pixels around the data point. Sampling one +// pixel would sometimes hit an axis grid line or a pixel outline drawn on top +// of the image, which is exactly what the plot is supposed to do; the cell +// colour is the majority of the neighbourhood. +QRgb dominantPixelAtData(const sls::SlsQtFastImage &view, const QImage &img, + double dataX, double dataY, int radius = 3) { + const QPointF p = widgetPos(view, dataX, dataY); + const int cx = int(std::lround(p.x())); + const int cy = int(std::lround(p.y())); + QHash counts; + for (int dy = -radius; dy <= radius; dy++) { + for (int dx = -radius; dx <= radius; dx++) { + const int x = cx + dx, y = cy + dy; + if (x < 0 || y < 0 || x >= img.width() || y >= img.height()) + continue; + counts[img.pixel(x, y)]++; + } + } + QRgb best = kBackground; + int bestCount = -1; + for (auto it = counts.constBegin(); it != counts.constEnd(); ++it) { + if (it.value() > bestCount) { + bestCount = it.value(); + best = it.key(); + } + } + return best; +} + +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); +} + +void sendWheel(QWidget &w, const QPointF &pos, int deltaY) { +#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) + QWheelEvent e(pos, QPointF(w.mapToGlobal(pos.toPoint())), QPoint(), + QPoint(0, deltaY), Qt::NoButton, Qt::NoModifier, + Qt::NoScrollPhase, false); +#else + // Qt 5.9 (RHEL 7): the scroll-phase constructor does not exist yet. + QWheelEvent e(pos, QPointF(w.mapToGlobal(pos.toPoint())), QPoint(), + QPoint(0, deltaY), 0, Qt::Vertical, Qt::NoButton, + Qt::NoModifier); +#endif + QCoreApplication::sendEvent(&w, &e); +} + +// True when a pixel close to (centre +/- radius) is drawn in a yellow tone. +bool yellowNear(const QImage &img, const QPoint ¢re, int radius = 2) { + for (int dy = -radius; dy <= radius; dy++) { + for (int dx = -radius; dx <= radius; dx++) { + const int x = centre.x() + dx, y = centre.y() + dy; + if (x < 0 || y < 0 || x >= img.width() || y >= img.height()) + continue; + const QRgb c = img.pixel(x, y); + if (qRed(c) > 180 && qGreen(c) > 180 && qBlue(c) < 90) + return true; + } + } + return false; +} + +bool isYellow(QRgb c) { + return qRed(c) > 200 && qGreen(c) > 170 && qBlue(c) < 130; +} + +bool isBright(QRgb c) { + return qRed(c) > 120 && qGreen(c) > 120 && qBlue(c) > 120; +} + +int countPixels(const QImage &img, bool (*pred)(QRgb)) { + int n = 0; + for (int y = 0; y < img.height(); y++) { + for (int x = 0; x < img.width(); x++) { + if (pred(img.pixel(x, y))) + n++; + } + } + return n; +} + +// Nice steps must be 1, 2 or 5 times a power of ten. +bool is125Step(double step) { + if (!(step > 0.0) || !std::isfinite(step)) + return false; + const double mag = std::pow(10.0, std::floor(std::log10(step) + 1e-9)); + const double norm = step / mag; + return near(norm, 1.0, 1e-6) || near(norm, 2.0, 1e-6) || + near(norm, 5.0, 1e-6); +} + +// A 1024x512 acceptance frame: sin(x/40) + cos(y/30). +std::vector acceptanceFrame(double phase = 0.0) { + std::vector f(size_t(1024) * 512); + for (int y = 0; y < 512; y++) { + for (int x = 0; x < 1024; x++) { + f[size_t(y) * 1024 + x] = + float(std::sin(x / 40.0 + phase) + std::cos(y / 30.0)); + } + } + return f; +} + +} // namespace + +class PlottingTest : public QObject { + Q_OBJECT + + private slots: + // ---- foundation: palettes / ticks / formatting ------------------------ + void palettesAndLuts(); + void paletteLogClamp(); + void tickMath(); + void tickFormatting(); + + // ---- FastImageView ---------------------------------------------------- + void fastImageOwnsFrame(); + void fastImageYUp(); + void fastImageHistogramWindow(); + void fastImageHistogramLogWindow(); + void fastImageLogClamp(); + void fastImageZeroWhite(); + void fastImageZoomCursorInvariance(); + void fastImageViewportClamping(); + void fastImageClipsToPlotRect(); + void fastImageOverlaysInDataCoordinates(); + void fastImageTitlesAndAspect(); + + // ---- ScaleHisto / ScalePanel ----------------------------------------- + void scaleHistoThreeWayFreeze(); + void scaleHistoMaxMarker(); + void scalePanelReentrancy(); + void scalePanelFreezeAndPushRules(); + void scalePanelDetachLifetime(); + + // ---- 1D plot ---------------------------------------------------------- + void h1dDataApi(); + void oneDimensionalRangeZoomLogAndGain(); + void oneDimensionalRoiBoxes(); + + // ---- 2D plot ---------------------------------------------------------- + void twoDHistogramContainer(); + void twoDimensionalDataZRangeAndPanel(); + void twoDimensionalLogInterpolateAndContour(); + void twoDimensionalRoiAndClipping(); + void twoDimensionalGainMode(); + + // ---- acceptance benchmark -------------------------------------------- + void performance1024x512(); +}; + +// --------------------------------------------------------------------------- +// palettes / LUTs +// --------------------------------------------------------------------------- +void PlottingTest::palettesAndLuts() { + // Gain4 is the fixed categorical palette and is not in the chooser. + QCOMPARE(sls::plot::paletteCount(), 18); + QCOMPARE(int(sls::plot::Palette::Gain4), 18); + + QSet names; + for (int i = 0; i < sls::plot::paletteCount(); i++) { + const auto p = static_cast(i); + const QRgb *lut = sls::plot::paletteLut(p); + QVERIFY2(lut != nullptr, "palette LUT must never be null"); + // The same pointer is handed out every time (built once). + QVERIFY(sls::plot::paletteLut(p) == lut); + for (int k = 0; k < 256; k++) { + QVERIFY2(qAlpha(lut[k]) == 255, "LUT entries must be opaque"); + } + const char *n = sls::plot::paletteName(p); + QVERIFY(n != nullptr && n[0] != '\0'); + QVERIFY2(!names.contains(QString::fromLatin1(n)), + "palette names must be unique"); + names.insert(QString::fromLatin1(n)); + } + + // Grey ramps: exact endpoints and monotonicity. + const QRgb *gray = sls::plot::paletteLut(sls::plot::Palette::Gray); + QCOMPARE(gray[0], qRgb(0, 0, 0)); + QCOMPARE(gray[255], qRgb(255, 255, 255)); + const QRgb *grayR = sls::plot::paletteLut(sls::plot::Palette::Gray_r); + QCOMPARE(grayR[0], qRgb(255, 255, 255)); + QCOMPARE(grayR[255], qRgb(0, 0, 0)); + + // BW1/BW2 are monotonic grey ramps with different gamma. + for (auto p : {sls::plot::Palette::BW1, sls::plot::Palette::BW2}) { + const QRgb *lut = sls::plot::paletteLut(p); + for (int k = 0; k < 256; k++) { + QVERIFY(qRed(lut[k]) == qGreen(lut[k]) && + qRed(lut[k]) == qBlue(lut[k])); + if (k > 0) + QVERIFY(qRed(lut[k]) >= qRed(lut[k - 1])); + } + } + QVERIFY(qRed(sls::plot::paletteLut(sls::plot::Palette::BW1)[128]) != + qRed(sls::plot::paletteLut(sls::plot::Palette::BW2)[128])); + + // Color is the jet-like default and differs from the others; Gain4 exists + // as a fixed categorical map even though paletteCount() hides it. + QVERIFY(sls::plot::paletteLut(sls::plot::Palette::Color)[10] != + sls::plot::paletteLut(sls::plot::Palette::Viridis)[10]); + const QRgb *gain = sls::plot::paletteLut(sls::plot::Palette::Gain4); + QVERIFY(gain != nullptr); + QVERIFY(gain[0] != sls::plot::paletteLut(sls::plot::Palette::Color)[0]); + QString gainName = QString::fromLatin1( + sls::plot::paletteName(sls::plot::Palette::Gain4)); + QVERIFY(gainName.contains(QStringLiteral("gain"), Qt::CaseInsensitive)); +} + +void PlottingTest::paletteLogClamp() { + // Empty pixels (0 / negative pedestal) must not become -inf. + QCOMPARE(sls::plot::logClamp(-3.0), -2.0); + QCOMPARE(sls::plot::logClamp(0.0), -2.0); + QCOMPARE(sls::plot::logClamp(1e-9), -2.0); + QCOMPARE(sls::plot::logClamp(0.01), -2.0); + QVERIFY(near(sls::plot::logClamp(0.02), std::log10(0.02), 1e-12)); + QCOMPARE(sls::plot::logClamp(1.0), 0.0); + QCOMPARE(sls::plot::logClamp(100.0), 2.0); + QVERIFY(sls::plot::logClamp(1e6) == 6.0); +} + +// --------------------------------------------------------------------------- +// tick math / formatting +// --------------------------------------------------------------------------- +void PlottingTest::tickMath() { + for (double span : {0.9, 10.0, 1000.0, 3.7, 1e6, 1e-3, 1024.0, 512.0}) { + QVERIFY2(is125Step(sls::plot::niceStep(span, 8)), "step = 1/2/5*10^n"); + } + QCOMPARE(sls::plot::niceStep(1000.0, 8), 200.0); + QVERIFY(near(sls::plot::niceStep(0.9, 8), 0.2)); + QCOMPARE(sls::plot::niceStep(0.0, 8), 1.0); // degenerate + QCOMPARE(sls::plot::niceStep(-5.0, 8), 1.0); // degenerate + + // Ticks cover the visible range, never exceed the requested density and + // are uniformly spaced. + for (auto range : {std::pair{0.0, 1024.0}, + std::pair{-2.0, 2.0}, + std::pair{0.3, 0.7}, + std::pair{-300.0, 1300.0}}) { + const std::vector ticks = + sls::plot::computeLinearTicks(range.first, range.second, 8); + QVERIFY(!ticks.empty()); + QVERIFY2(ticks.size() <= 9, "at most maxTicks+1 tick values"); + QVERIFY(ticks.front() >= range.first - 1e-9); + QVERIFY(ticks.back() <= range.second + 1e-9); + const double step = sls::plot::niceStep(range.second - range.first, 8); + QVERIFY(near(ticks.front(), 0.0, 1e-9) || + std::fmod(ticks.front(), step) < 1e-6); + for (double v : ticks) { + const double n = v / step; + QVERIFY2(near(n, std::round(n), 1e-6), + "ticks are multiples of the nice step"); + } + } + QVERIFY(sls::plot::computeLinearTicks(1.0, 1.0, 8).empty()); + QVERIFY(sls::plot::computeLinearTicks(2.0, 1.0, 8).empty()); + QVERIFY(sls::plot::computeLinearTicks( + std::numeric_limits::quiet_NaN(), 1.0, 8) + .empty()); + + // Theme values are the contract shared by 1D/2D and the image view. + const sls::plot::PlotTheme theme; + QCOMPARE(theme.leftMargin, 52); + QCOMPARE(theme.bottomMargin, 26); + QCOMPARE(theme.topMargin, 6); + QCOMPARE(theme.rightMargin, 6); + QCOMPARE(theme.tickFont.pixelSize(), 10); + const QRect r = sls::plot::plotRectFor(QSize(400, 300), theme); + QCOMPARE(r, QRect(52, 6, 400 - 52 - 6, 300 - 6 - 26)); + QVERIFY(sls::plot::plotRectFor(QSize(10, 10), theme).width() >= 10); +} + +void PlottingTest::tickFormatting() { + QCOMPARE(sls::plot::formatTick(200.0, 200.0), QStringLiteral("200")); + QCOMPARE(sls::plot::formatTick(0.2, 0.2), QStringLiteral("0.2")); + QCOMPARE(sls::plot::formatTick(1.0, 0.5), QStringLiteral("1")); + QCOMPARE(sls::plot::formatTick(3.0, 0.5), QStringLiteral("3")); + QCOMPARE(sls::plot::formatTick(3.5, 0.5), QStringLiteral("3.5")); + QCOMPARE(sls::plot::formatTick(0.25, 0.05), QStringLiteral("0.25")); + QCOMPARE(sls::plot::formatTick(-0.0, 0.5), QStringLiteral("0")); + QCOMPARE(sls::plot::formatTick(-200.0, 200.0), QStringLiteral("-200")); + QVERIFY(sls::plot::formatTick(2.5e7, 1e7).contains(QLatin1Char('e'))); + QCOMPARE(sls::plot::formatTick( + std::numeric_limits::infinity(), 1.0), + QStringLiteral("?")); + // No trailing zeros anywhere, and labels stay short. + for (double v : {0.0, 1.0, 2.0, 5.0, 10.0, 100.0, -100.0, 0.5, 2.5}) { + const QString s = sls::plot::formatTick(v, 1.0); + QVERIFY2(!s.contains(QStringLiteral(".0")), qPrintable(s)); + QVERIFY2(s.size() <= 6, qPrintable(s)); + } +} + +// --------------------------------------------------------------------------- +// FastImageView: buffer ownership, orientation, histogram, colour mapping +// --------------------------------------------------------------------------- +void PlottingTest::fastImageOwnsFrame() { + sls::SlsQtFastImage view; + view.resize(200, 200); // sx ~ 35 px => no in-pixel text over cell centres + view.show(); + QTest::qWait(5); + + view.setPaletteLut(sls::plot::paletteLut(sls::plot::Palette::Color)); + view.setColorRange(0.0, 2.0); + std::vector src(16, 1.0f); + view.setImageCopy(src.data(), 4, 4); + const QRgb expected = sls::plot::paletteLut(sls::plot::Palette::Color)[127]; + QCOMPARE(dominantPixelAtData(view, render(view), 0.5, 0.5), expected); + + // The producer owns and recycles its buffer: the view must have copied it. + std::fill(src.begin(), src.end(), 2.0f); + // Force a recomposition from the widget-owned data (no new frame pushed). + view.setColorRange(0.0, 2.0); + const QImage after = render(view); + QCOMPARE(dominantPixelAtData(view, after, 0.5, 0.5), expected); + + // Same for the double overload (the GUI feeds double frames). + std::vector dsrc(16, 1.0); + view.setImageCopy(dsrc.data(), 4, 4); + QCOMPARE(dominantPixelAtData(view, render(view), 1.5, 1.5), expected); + std::fill(dsrc.begin(), dsrc.end(), 2.0); + view.setColorRange(0.0, 2.0); + QCOMPARE(dominantPixelAtData(view, render(view), 1.5, 1.5), expected); + + // Invalid input is ignored, the previous frame stays valid. + view.setImageCopy(static_cast(nullptr), 4, 4); + view.setImageCopy(src.data(), 0, 4); + QCOMPARE(view.imageWidth(), 4); + QCOMPARE(view.imageHeight(), 4); +} + +void PlottingTest::fastImageYUp() { + sls::SlsQtFastImage view; + view.resize(200, 200); + view.show(); + QTest::qWait(5); + view.setPaletteLut(sls::plot::paletteLut(sls::plot::Palette::Gray)); + view.setColorRange(0.0, 4.0); + // row 0 = bottom = 0, row 1 = top = 3 + std::vector f{0, 0, 0, 0, 3, 3, 3, 3}; + view.setImageCopy(f.data(), 4, 2); + const QImage img = render(view); + + // Data y is up: y=0.5 (bottom row) is drawn below y=1.5 (top row). + QVERIFY(widgetPos(view, 0.5, 0.5).y() > widgetPos(view, 0.5, 1.5).y()); + const QRgb *lut = sls::plot::paletteLut(sls::plot::Palette::Gray); + QCOMPARE(dominantPixelAtData(view, img, 0.5, 0.5), lut[0]); + QCOMPARE(dominantPixelAtData(view, img, 0.5, 1.5), + lut[int((3.0 - 0.0) * 255.0 / 4.0)]); + // Exactly one flip: both quarters of the top row match, no mirrored mix. + QCOMPARE(dominantPixelAtData(view, img, 2.5, 1.5), + dominantPixelAtData(view, img, 0.5, 1.5)); +} + +void PlottingTest::fastImageHistogramWindow() { + sls::SlsQtFastImage view; + view.resize(200, 200); + view.show(); + QTest::qWait(5); + view.setLogScale(false); + + // 64x32 ramp, value == x: only x in [0,4] is inside the 1..3 window. + const int nx = 64, ny = 32; + std::vector ramp(size_t(nx) * ny); + for (int y = 0; y < ny; y++) + for (int x = 0; x < nx; x++) + ramp[size_t(y) * nx + x] = float(x); + view.setColorRange(1.0, 3.0); + view.setImageCopy(ramp.data(), nx, ny); + render(view); + + double lo = 0.0, hi = 0.0; + view.histogramRange(lo, hi); + QVERIFY(near(lo, 0.0) && near(hi, 4.0)); + QCOMPARE(int(view.histogram().size()), 256); + long long sum = 0; + for (int v : view.histogram()) + sum += v; + QCOMPARE(sum, 5LL * ny); // 0,1,2,3,4 in-window; 5..63 skipped + + // The histogram follows a colour-range change (invalidated, not stale). + // Range 10.2..19.8 -> window 5.1..24.9 (not aligned with the integer ramp). + view.setColorRange(10.2, 19.8); + render(view); + view.histogramRange(lo, hi); + QVERIFY(near(lo, 5.4) && near(hi, 24.6)); + sum = 0; + for (int v : view.histogram()) + sum += v; + QCOMPARE(sum, 19LL * ny); // x = 6..24 + + // Outside values are skipped instead of piling into the edge bins. + QCOMPARE(view.histogram().front(), 0); + QCOMPARE(view.histogram().back(), 0); +} + +void PlottingTest::fastImageHistogramLogWindow() { + sls::SlsQtFastImage view; + view.resize(200, 200); + view.show(); + QTest::qWait(5); + const int nx = 64, ny = 32; + std::vector ramp(size_t(nx) * ny); + for (int y = 0; y < ny; y++) + for (int x = 0; x < nx; x++) + ramp[size_t(y) * nx + x] = float(x); + + view.setLogScale(true); + QVERIFY(view.logScale()); + view.setColorRange(1.0, 100.0); + view.setImageCopy(ramp.data(), nx, ny); + render(view); + + double lo = 0.0, hi = 0.0; + view.histogramRange(lo, hi); + // log10(1) - 1 .. log10(100) + 1 + QVERIFY(near(lo, -1.0) && near(hi, 3.0)); + long long sum = 0; + for (int v : view.histogram()) + sum += v; + // x=0 is clamped to 1e-2 (log -2) and is outside; x=1..63 are inside. + QCOMPARE(sum, 63LL * ny); +} + +void PlottingTest::fastImageLogClamp() { + sls::SlsQtFastImage view; + view.resize(200, 200); + view.show(); + QTest::qWait(5); + view.setPaletteLut(sls::plot::paletteLut(sls::plot::Palette::Color)); + view.setLogScale(true); + // Lower end is exactly the 1e-2 log clamp, so everything <= 0 maps to the + // first LUT entry while 0.02 (just above the clamp) does not. + view.setColorRange(0.01, 100.0); + std::vector f{-100.0f, 0.0f, 0.01f, 0.02f, 1000.0f, 1000.0f, 1.0f, + 1.0f}; + view.setImageCopy(f.data(), 4, 2); + const QImage img = render(view); + const QRgb *lut = sls::plot::paletteLut(sls::plot::Palette::Color); + + const QRgb clamped0 = dominantPixelAtData(view, img, 0.5, 0.5); + QCOMPARE(clamped0, lut[0]); + QCOMPARE(dominantPixelAtData(view, img, 1.5, 0.5), clamped0); + QCOMPARE(dominantPixelAtData(view, img, 2.5, 0.5), clamped0); + // 0.02 is > 1e-2, so it is not clamped to the bottom colour. + QVERIFY(dominantPixelAtData(view, img, 3.5, 0.5) != clamped0); + // Above the range: top colour, no wraparound. + QCOMPARE(dominantPixelAtData(view, img, 0.5, 1.5), lut[255]); +} + +void PlottingTest::fastImageZeroWhite() { + sls::SlsQtFastImage view; + view.resize(200, 200); + view.show(); + QTest::qWait(5); + view.setPaletteLut(sls::plot::paletteLut(sls::plot::Palette::Color)); + view.setColorRange(0.0, 2.0); + + std::vector f(16, 1.0f); + f[0] = 0.0f; // data pixel (0,0), bottom-left + view.setImageCopy(f.data(), 4, 4); + const QRgb *lut = sls::plot::paletteLut(sls::plot::Palette::Color); + + QVERIFY(!view.zeroWhite()); + QCOMPARE(dominantPixelAtData(view, render(view), 0.5, 0.5), lut[0]); + + view.setZeroWhite(true); + QVERIFY(view.zeroWhite()); + QCOMPARE(dominantPixelAtData(view, render(view), 0.5, 0.5), qRgb(255, 255, 255)); + // A real value is not affected. + QCOMPARE(dominantPixelAtData(view, render(view), 1.5, 1.5), lut[127]); + + // Non-finite pixels use the lowest colour, even with zero-white on. + f[0] = std::numeric_limits::quiet_NaN(); + view.setImageCopy(f.data(), 4, 4); + QCOMPARE(dominantPixelAtData(view, render(view), 0.5, 0.5), lut[0]); + + view.setIntegerValues(true); + QVERIFY(view.integerValues()); + view.setIntegerValues(false); + QVERIFY(!view.integerValues()); +} + +// --------------------------------------------------------------------------- +// FastImageView: zoom / viewport / clipping +// --------------------------------------------------------------------------- +void PlottingTest::fastImageZoomCursorInvariance() { + sls::SlsQtFastImage view; + view.resize(400, 300); + view.show(); + QTest::qWait(5); + // Square image: the whole-image fit is height-limited with a constant + // horizontal letterbox, so the cursor-fixed rule can hold exactly even when + // the viewport is clamped at the minimum size during deep zoom. + const int nx = 64, ny = 64; + std::vector ramp(size_t(nx) * ny, 1.0f); + view.setColorRange(0.0, 2.0); + view.setImageCopy(ramp.data(), nx, ny); + view.resetView(); + + int zoomCalls = 0; + view.onZoomChanged = [&](double, double, double, double) { zoomCalls++; }; + view.setViewport(10.0, 5.0, 30.0, 15.0); // programmatic: no callback + QCOMPARE(zoomCalls, 0); + view.resetView(); + QCOMPARE(zoomCalls, 1); + + const QPointF cursor(200.0, 150.0); + for (int i = 0; i < 5; i++) { + const QPointF before = view.widgetToData(cursor); + sendWheel(view, cursor, 120); // zoom in, factor 1/1.18 + const QPointF after = view.widgetToData(cursor); + QVERIFY2(near(before.x(), after.x(), 1e-6), + "wheel zoom must keep the cursor x fixed"); + QVERIFY2(near(before.y(), after.y(), 1e-6), + "wheel zoom must keep the cursor y fixed"); + } + double vx, vy, vw, vh; + view.viewport(vx, vy, vw, vh); + QVERIFY(vw < nx && vh < ny); + QVERIFY(zoomCalls >= 6); // 1 reset + 5 wheels + + // Deep zoom clamps to the minimum viewport instead of collapsing. + for (int i = 0; i < 40; i++) + sendWheel(view, cursor, 120); + view.viewport(vx, vy, vw, vh); + QVERIFY2(vw >= sls::SlsQtFastImage::kMinimumViewport - 1e-9, + "viewport clamps to the minimum width"); + QVERIFY2(vh >= sls::SlsQtFastImage::kMinimumViewport - 1e-9, + "viewport clamps to the minimum height"); + + // Zooming back out stops at the full frame and keeps the cursor point. + for (int i = 0; i < 60; i++) { + const QPointF before = view.widgetToData(cursor); + sendWheel(view, cursor, -120); + const QPointF after = view.widgetToData(cursor); + QVERIFY(near(before.x(), after.x(), 1e-6)); + QVERIFY(near(before.y(), after.y(), 1e-6)); + } + view.viewport(vx, vy, vw, vh); + QVERIFY(near(vw, nx) && near(vh, ny)); + QVERIFY(near(vx, 0.0) && near(vy, 0.0)); +} + +void PlottingTest::fastImageViewportClamping() { + sls::SlsQtFastImage view; + view.resize(400, 300); + view.show(); + QTest::qWait(5); + const int nx = 64, ny = 32; + std::vector ramp(size_t(nx) * ny, 1.0f); + view.setImageCopy(ramp.data(), nx, ny); + view.resetView(); + double x, y, w, h; + + // Requested viewports are clamped to the image bounds. + view.setViewport(-100.0, -100.0, 5000.0, 5000.0); + view.viewport(x, y, w, h); + QVERIFY(near(x, 0.0) && near(y, 0.0)); + QVERIFY(near(w, nx) && near(h, ny)); + + // A viewport smaller than the minimum is rejected (state unchanged). + view.setViewport(10.0, 10.0, 10.5, 10.5); + view.viewport(x, y, w, h); + QVERIFY(near(w, nx) && near(h, ny)); + + // A viewport that would stick out on the right/top is slid back inside. + view.setViewport(60.0, 28.0, 70.0, 38.0); + view.viewport(x, y, w, h); + QVERIFY(near(w, 10.0) && near(h, 10.0)); + QVERIFY(x >= 0.0 && x + w <= nx + 1e-9); + QVERIFY(y >= 0.0 && y + h <= ny + 1e-9); + + // Non-finite values are ignored. + const double nan = std::numeric_limits::quiet_NaN(); + view.setViewport(nan, 0.0, 10.0, 10.0); + view.viewport(x, y, w, h); + QVERIFY(near(w, 10.0) && near(h, 10.0)); + + view.resetView(); + view.viewport(x, y, w, h); + QVERIFY(near(x, 0.0) && near(y, 0.0) && near(w, nx) && near(h, ny)); + + // Pixel aspect stretches x only and is validated. + view.setPixelAspectX(2.0); + QCOMPARE(view.pixelAspectX(), 2.0); + view.setPixelAspectX(-1.0); + QCOMPARE(view.pixelAspectX(), 1.0); +} + +void PlottingTest::fastImageClipsToPlotRect() { + sls::SlsQtFastImage view; + view.resize(400, 300); + view.show(); + QTest::qWait(5); + const int nx = 1024, ny = 512; + std::vector frame = acceptanceFrame(); + view.setColorRange(-2.0, 2.0); + view.setImageCopy(frame.data(), nx, ny); + view.resetView(); + + // Margins of the widget: the plot rect is QRect(52, 6, w-58, h-32). + const QRect ir = sls::plot::plotRectFor(view.size(), sls::plot::PlotTheme()); + QCOMPARE(ir, QRect(52, 6, 400 - 58, 300 - 32)); + + // Zoom so the scaled image is much larger than the plot area; without the + // clip it would paint over the right/top margins. + view.setViewport(100.0, 100.0, 164.0, 132.0); + const QImage img = render(view); + QVERIFY(img.width() == 400 && img.height() == 300); + + for (int y = ir.top(); y <= ir.bottom(); y++) { + for (int x = ir.right() + 1; x < img.width(); x++) { + QVERIFY2(img.pixel(x, y) == kBackground, + "zoomed image must be clipped to the plot rect (right " + "margin)"); + } + } + for (int x = ir.left(); x <= img.width() - 1; x++) { + for (int y = 0; y < ir.top(); y++) { + QVERIFY2(img.pixel(x, y) == kBackground, + "zoomed image must be clipped to the plot rect (top " + "margin)"); + } + } + // ... while the image itself is definitely painted inside. + QVERIFY(img.pixel(ir.center()) != kBackground); +} + +void PlottingTest::fastImageOverlaysInDataCoordinates() { + sls::SlsQtFastImage view; + view.resize(400, 300); + view.show(); + QTest::qWait(5); + const int nx = 1024, ny = 512; + std::vector frame = acceptanceFrame(); + view.setColorRange(-2.0, 2.0); + view.setImageCopy(frame.data(), nx, ny); + view.resetView(); + + // (120,110) lower-left + 20x10, entirely inside the view. + view.setOverlayRects({QRectF(120.0, 110.0, 20.0, 10.0)}); + QCOMPARE(int(view.overlayRects().size()), 1); + QImage img = render(view); + const QPointF topLeft = view.dataToWidget(QPointF(120.0, 120.0)); + QVERIFY2(yellowNear(img, topLeft.toPoint(), 2), + "overlay must be drawn at its data coordinates (yellow)"); + const QPointF bottomRight = view.dataToWidget(QPointF(140.0, 110.0)); + QVERIFY(yellowNear(img, bottomRight.toPoint(), 2)); + + // A rectangle crossing the plot edge is clipped: no yellow outside. + view.setOverlayRects({QRectF(1000.0, 400.0, 400.0, 400.0)}); + img = render(view); + const QRect ir = sls::plot::plotRectFor(view.size(), sls::plot::PlotTheme()); + for (int x = ir.right() + 1; x < img.width(); x++) { + for (int y = 0; y < img.height(); y++) { + const QRgb c = img.pixel(x, y); + QVERIFY2(!(qRed(c) > 180 && qGreen(c) > 180 && qBlue(c) < 90), + "overlays must be clipped to the plot rect"); + } + } + view.clearOverlayRects(); + QVERIFY(view.overlayRects().empty()); + + // Editable gate ROI and receiver ROI are reported back in data coords. + view.setRoiRect(10.0, 20.0, 110.0, 220.0); + double x0, y0, x1, y1; + QVERIFY(view.roiRect(x0, y0, x1, y1)); + QVERIFY(near(x0, 10.0) && near(y1, 220.0)); + view.setRoiRectVisible(false); + QVERIFY(!view.roiRect(x0, y0, x1, y1)); + view.setReceiverRoiRect(5.0, 6.0, 7.0, 8.0); + view.clearReceiverRoiRect(); +} + +void PlottingTest::fastImageTitlesAndAspect() { + sls::SlsQtFastImage view; + view.resize(400, 300); + view.show(); + QTest::qWait(5); + std::vector ramp(64 * 32, 1.0f); + view.setImageCopy(ramp.data(), 64, 32); + + QVERIFY(view.title().isEmpty()); + view.setTitle(QStringLiteral("Detector 0")); + view.setXAxisTitle(QStringLiteral("x [px]")); + view.setYAxisTitle(QStringLiteral("y [px]")); + QCOMPARE(view.title(), QStringLiteral("Detector 0")); + QCOMPARE(view.xAxisTitle(), QStringLiteral("x [px]")); + QCOMPARE(view.yAxisTitle(), QStringLiteral("y [px]")); + // A title consumes a row at the top; the image must still render. + const QImage img = render(view); + const QRect ir = sls::plot::plotRectFor(view.size(), sls::plot::PlotTheme()); + QVERIFY(img.pixel(ir.center()) != kBackground); + + QFont f; + f.setPixelSize(17); + view.setTitleFont(f); + QCOMPARE(view.titleFont().pixelSize(), 17); + view.setAxisTitleFont(f); + QCOMPARE(view.axisTitleFont().pixelSize(), 17); + view.setTickFont(f); + QCOMPARE(view.tickFont().pixelSize(), 17); +} + +// --------------------------------------------------------------------------- +// ScaleHisto: three-way freeze rule +// --------------------------------------------------------------------------- +void PlottingTest::scaleHistoThreeWayFreeze() { + sls::SlsQtScaleHisto histo; + histo.resize(400, 38); + histo.show(); + QTest::qWait(5); + + std::vector bins(256, 0); + bins[100] = 10; + bins[200] = 300; + histo.setData(&bins, 0.0, 1.0, 0.2, 0.8, false, false); + double dw0 = 0.0, dw1 = 0.0; + histo.displayedWindow(dw0, dw1); + QVERIFY(near(dw0, -0.1, 1e-9) && near(dw1, 1.1, 1e-9)); + double cw0 = 0.0, cw1 = 0.0; + histo.currentWindow(cw0, cw1); + QVERIFY(near(cw0, 0.2) && near(cw1, 0.8)); + + int rangeCalls = 0; + double newLo = 0.0, newHi = 0.0; + histo.onRangeChanged = [&](double a, double b) { + rangeCalls++; + newLo = a; + newHi = b; + }; + + const int W = histo.width(); + const QPointF marker(W * 0.25, 19.0); + sendMouse(histo, QEvent::MouseButtonPress, marker, Qt::LeftButton, + Qt::LeftButton); + QVERIFY(histo.isDragging()); + + // Freeze #1 (bars): a live histogram update must be ignored. + const std::vector *frozen = histo.displayedHistogram(); + QVERIFY(frozen != nullptr); + QVERIFY(frozen != &bins); + QCOMPARE(int(frozen->size()), 256); + QCOMPARE((*frozen)[100], 10); + std::vector live2(256, 0); + live2[50] = 999; + histo.setData(&live2, 0.0, 1.0, 0.0, 1.0, false, false); + QVERIFY2(histo.displayedHistogram() == frozen, + "histogram bars must be frozen while dragging"); + QCOMPARE((*histo.displayedHistogram())[100], 10); + QCOMPARE((*histo.displayedHistogram())[200], 300); + + // Freeze #2 (axis window): still the press-time window after a move. + const int previewAtPress = histo.previewX(); + sendMouse(histo, QEvent::MouseMove, QPointF(W * 0.40, 19.0), + Qt::NoButton, Qt::LeftButton); + QVERIFY(histo.isDragging()); + double fw0 = 0.0, fw1 = 0.0; + histo.displayedWindow(fw0, fw1); + QVERIFY2(near(fw0, dw0) && near(fw1, dw1), + "axis window must stay frozen while dragging"); + + // Freeze #3 (cursor mapping): the pre-move range is used, so these must be + // stable no matter how often the mouse moves. + double l0 = 0.0, l1 = 0.0; + histo.currentWindow(l0, l1); + QVERIFY(l0 > 0.2); // preview moved the low end + for (int i = 0; i < 3; i++) + sendMouse(histo, QEvent::MouseMove, QPointF(W * 0.40, 19.0), + Qt::NoButton, Qt::LeftButton); + double l2 = 0.0, l3 = 0.0; + histo.currentWindow(l2, l3); + QVERIFY(near(l0, l2) && near(l1, l3)); + QVERIFY2(histo.previewX() != previewAtPress, + "only the dashed preview line moves"); + QCOMPARE(rangeCalls, 0); // nothing applied before release + + // Painting mid-drag must not mutate the frozen state either. + (void)histo.grab(); + histo.displayedWindow(fw0, fw1); + QVERIFY(near(fw0, dw0) && near(fw1, dw1)); + QVERIFY(histo.displayedHistogram() == frozen); + + sendMouse(histo, QEvent::MouseButtonRelease, QPointF(W * 0.40, 19.0), + Qt::LeftButton, Qt::NoButton); + QVERIFY(!histo.isDragging()); + QCOMPARE(rangeCalls, 1); // applied exactly once, on release + QVERIFY(near(newLo, l2) && near(newHi, l3)); + QVERIFY2(histo.displayedHistogram() == &bins, + "live histogram is restored after release"); + double nw0 = 0.0, nw1 = 0.0; + histo.displayedWindow(nw0, nw1); + QVERIFY2(!near(nw0, dw0) || !near(nw1, dw1), + "the axis rebuilds from the new range after release"); + + // A press far away from both markers is ignored. + sendMouse(histo, QEvent::MouseButtonPress, QPointF(W * 0.5, 19.0), + Qt::LeftButton, Qt::LeftButton); + QVERIFY(!histo.isDragging()); + sendMouse(histo, QEvent::MouseButtonRelease, QPointF(W * 0.5, 19.0), + Qt::LeftButton, Qt::NoButton); + QCOMPARE(rangeCalls, 1); +} + +void PlottingTest::scaleHistoMaxMarker() { + sls::SlsQtScaleHisto histo; + histo.resize(400, 38); + histo.show(); + QTest::qWait(5); + std::vector bins(256, 1); + histo.setData(&bins, 0.0, 1.0, 0.2, 0.8, false, false); + + int rangeCalls = 0; + double newLo = 0.0, newHi = 0.0; + histo.onRangeChanged = [&](double a, double b) { + rangeCalls++; + newLo = a; + newHi = b; + }; + const int W = histo.width(); + sendMouse(histo, QEvent::MouseButtonPress, QPointF(W * 0.75, 19.0), + Qt::LeftButton, Qt::LeftButton); + QVERIFY(histo.isDragging()); + sendMouse(histo, QEvent::MouseMove, QPointF(W * 0.60, 19.0), + Qt::NoButton, Qt::LeftButton); + sendMouse(histo, QEvent::MouseButtonRelease, QPointF(W * 0.60, 19.0), + Qt::LeftButton, Qt::NoButton); + QCOMPARE(rangeCalls, 1); + QVERIFY(newLo < newHi); + QVERIFY(newHi < 0.8); // max marker dragged down +} + +// --------------------------------------------------------------------------- +// ScalePanel: re-entrancy, control synchronisation, strip freeze +// --------------------------------------------------------------------------- +void PlottingTest::scalePanelReentrancy() { + sls::SlsQtFastImage view; + view.resize(300, 300); + view.show(); + QTest::qWait(5); + std::vector ramp(64 * 32); + for (int i = 0; i < 64 * 32; i++) + ramp[i] = float(i % 100) / 10.0f; + view.setColorRange(0.0, 10.0); + view.setImageCopy(ramp.data(), 64, 32); + view.repaint(); + + sls::SlsQtScalePanel panel(&view); + panel.resize(760, 78); + panel.show(); + QTest::qWait(5); + QVERIFY(panel.histogramWidget() != nullptr); + QVERIFY(panel.view() == &view); + QVERIFY(!panel.isDragging()); + + // view -> controls -> view must not recurse (sympass guard): one change, + // one control update, no push-back loop. The min/max spin boxes were + // removed from the plot window; the range is owned by the Plot tab, so + // the panel only keeps the last range it read from/wrote to the view + // (controlRange(), not spin-box widgets). + int rangeCalls = 0; + view.onColorRangeChanged = [&](double, double) { rangeCalls++; }; + panel.setColorRange(1.0, 5.0); + QCOMPARE(rangeCalls, 1); + double a = 0.0, b = 0.0; + view.colorRange(a, b); + QVERIFY(near(a, 1.0) && near(b, 5.0)); + panel.controlRange(a, b); + QVERIFY(near(a, 1.0) && near(b, 5.0)); + + // refresh()/push() round trip is stable (idempotent, no re-entrancy). + panel.refresh(); + panel.push(); + view.colorRange(a, b); + QVERIFY(near(a, 1.0) && near(b, 5.0)); + panel.refresh(); + panel.refresh(); + view.colorRange(a, b); + QVERIFY(near(a, 1.0) && near(b, 5.0)); + + // Palette and image-log controls stay in sync with the view. + panel.setPaletteChoice(3); + QCOMPARE(view.paletteIndex(), 3); + QCOMPARE(view.paletteIndex(), int(sls::plot::Palette::Turbo)); + QCOMPARE(panel.paletteChoice(), 3); + panel.setImageLog(true); + QVERIFY(view.logScale()); + QVERIFY(!view.isScaleDragging()); + panel.setImageLog(false); + QVERIFY(!view.logScale()); + panel.setHistoLog(true); + QVERIFY(panel.histoLog()); + + // A strip drag freezes the strip; refresh() during the drag (the image + // keeps arriving in the real GUI) must not feed back into it. + sls::SlsQtScaleHisto *strip = panel.histogramWidget(); + double sw0 = 0.0, sw1 = 0.0; + strip->displayedWindow(sw0, sw1); + const std::vector *live = strip->displayedHistogram(); + QVERIFY(live != nullptr); + const int W = strip->width(); + sendMouse(*strip, QEvent::MouseButtonPress, QPointF(W * 0.25, 10.0), + Qt::LeftButton, Qt::LeftButton); + QVERIFY(strip->isDragging()); + QVERIFY(panel.isDragging()); + const std::vector *frozen = strip->displayedHistogram(); + QVERIFY2(frozen != live, "drag paints a snapshot, not the live bars"); + panel.refresh(); + sendMouse(*strip, QEvent::MouseMove, QPointF(W * 0.40, 10.0), + Qt::NoButton, Qt::LeftButton); + panel.refresh(); + double dw0 = 0.0, dw1 = 0.0; + strip->displayedWindow(dw0, dw1); + QVERIFY2(near(dw0, sw0) && near(dw1, sw1), + "panel refresh must not move the frozen strip"); + QVERIFY2(strip->displayedHistogram() == frozen, + "panel refresh must not replace the frozen bars"); + + sendMouse(*strip, QEvent::MouseButtonRelease, QPointF(W * 0.40, 10.0), + Qt::LeftButton, Qt::NoButton); + QVERIFY(!strip->isDragging()); + QVERIFY(!panel.isDragging()); + // Release applied the previewed range to the view. + view.colorRange(a, b); + QVERIFY(b > a); + QVERIFY(!near(a, 1.0) || !near(b, 5.0)); + + // Detach/reattach keeps working and preserves the view callbacks. + panel.setView(nullptr); + QVERIFY(panel.view() == nullptr); + panel.setView(&view); + QVERIFY(panel.view() == &view); + panel.refresh(); // must not crash with a fresh attachment +} + +// --------------------------------------------------------------------------- +// ScalePanel R1/R2 (task-11): strip freeze and the controls->view push rules +// --------------------------------------------------------------------------- +void PlottingTest::scalePanelFreezeAndPushRules() { + sls::SlsQtFastImage view; + view.resize(400, 400); + view.show(); + QTest::qWait(5); + std::vector data(64 * 64); + for (int i = 0; i < 64 * 64; i++) + data[size_t(i)] = float(i % 100) / 10.0f; + view.setColorRange(1.0, 5.0); + view.setImageCopy(data.data(), 64, 64); + view.repaint(); + + sls::SlsQtScalePanel panel(&view); + panel.resize(760, 78); + panel.show(); + QTest::qWait(5); + + double lo = 0.0, hi = 0.0; + panel.controlRange(lo, hi); + QVERIFY(near(lo, 1.0) && near(hi, 5.0)); + int rangeCalls = 0; + view.onColorRangeChanged = [&](double, double) { rangeCalls++; }; + + // R1: while a strip marker is dragged, incoming frames may change the + // view's colour range, but refresh() must keep the controls frozen at the + // press-time values (and the strip axis/bars frozen as well). + auto *strip = panel.histogramWidget(); + double frozenW0 = 0.0, frozenW1 = 0.0; + strip->displayedWindow(frozenW0, frozenW1); + const std::vector *liveBars = strip->displayedHistogram(); + sendMouse(*strip, QEvent::MouseButtonPress, + QPointF(strip->width() * 0.25, strip->height() / 2.0), + Qt::LeftButton, Qt::LeftButton); + QVERIFY(strip->isDragging()); + const std::vector *frozenBars = strip->displayedHistogram(); + QVERIFY2(frozenBars != nullptr && frozenBars != liveBars, + "drag paints a press-time histogram snapshot"); + view.setColorRange(2.0, 7.0); + panel.refresh(); + panel.controlRange(lo, hi); + QVERIFY2(near(lo, 1.0) && near(hi, 5.0), + "control range frozen while the strip marker is dragged (R1)"); + view.setColorRange(3.0, 9.0); + panel.refresh(); + panel.controlRange(lo, hi); + QVERIFY2(near(lo, 1.0) && near(hi, 5.0), + "control range still frozen after a second live range change (R1)"); + double dw0 = 0.0, dw1 = 0.0; + strip->displayedWindow(dw0, dw1); + QVERIFY(near(dw0, frozenW0) && near(dw1, frozenW1)); + QVERIFY(strip->displayedHistogram() == frozenBars); + // Move the low marker from its 1/4 place towards 2/5 (the preview value). + sendMouse(*strip, QEvent::MouseMove, + QPointF(strip->width() * 0.40, strip->height() / 2.0), + Qt::NoButton, Qt::LeftButton); + double cw0 = 0.0, cw1 = 0.0; + strip->currentWindow(cw0, cw1); + QVERIFY(cw0 > 2.0); + sendMouse(*strip, QEvent::MouseButtonRelease, + QPointF(strip->width() * 0.40, strip->height() / 2.0), + Qt::LeftButton, Qt::NoButton); + QVERIFY(!strip->isDragging()); + // On release the strip range is applied and the controls follow it. + double vlo = 0.0, vhi = 0.0; + view.colorRange(vlo, vhi); + QVERIFY2(near(vlo, cw0) && near(vhi, cw1), + "strip range applied to the view on release (R1)"); + panel.controlRange(lo, hi); + QVERIFY(std::abs(lo - vlo) <= 0.051); + QVERIFY(std::abs(hi - vhi) <= 0.051); + + // R2: palette/log changes must NOT push the control range into the view + // (that would fire onColorRangeChanged and pin the 2D panel override). + // Only an explicit control-range edit may change the range. + view.setColorRange(0.408939, 40.8); // e.g. SlsQt2DPlot's auto z range + view.repaint(); + const int callsBefore = rangeCalls; + panel.setPaletteChoice(3); + QCOMPARE(rangeCalls, callsBefore); + double a = 0.0, b = 0.0; + view.colorRange(a, b); + QVERIFY2(near(a, 0.408939) && near(b, 40.8), + "palette change leaves the auto z range bit-exact (R2)"); + double plo = 0.0, phi = 0.0; + QVERIFY(!panel.lastPushedRange(plo, phi)); + panel.setImageLog(true); + panel.setImageLog(false); + QCOMPARE(rangeCalls, callsBefore); + view.colorRange(a, b); + QVERIFY(near(a, 0.408939) && near(b, 40.8)); + QVERIFY(!panel.lastPushedRange(plo, phi)); + panel.controlRange(lo, hi); + QVERIFY(near(lo, 0.4, 0.051) && near(hi, 40.8, 0.051)); + + // A real operator edit is the only path that pushes a range, exactly once. + panel.setControlRange(2.5, 8.0); + QCOMPARE(rangeCalls, callsBefore + 1); + view.colorRange(a, b); + QVERIFY(near(a, 2.5) && near(b, 8.0)); + QVERIFY(panel.lastPushedRange(plo, phi)); + QVERIFY(near(plo, 2.5) && near(phi, 8.0)); + // A later palette change still does not push the (now edited) range. + panel.setPaletteChoice(5); + QCOMPARE(rangeCalls, callsBefore + 1); + view.colorRange(a, b); + QVERIFY(near(a, 2.5) && near(b, 8.0)); +} + +// --------------------------------------------------------------------------- +// ScalePanel R6 (task-11): the strip never keeps a pointer to a dead histogram +// --------------------------------------------------------------------------- +void PlottingTest::scalePanelDetachLifetime() { + std::vector ramp(64 * 32, 1.0f); + + // Detaching the panel clears the strip's raw histogram pointer, and the + // orphaned strip can still be repainted/grab'ed safely. + auto *view = new sls::SlsQtFastImage; + view->resize(300, 300); + view->show(); + QTest::qWait(5); + view->setImageCopy(ramp.data(), 64, 32); + view->repaint(); + auto *panel = new sls::SlsQtScalePanel(view); + panel->resize(600, 78); + panel->show(); + QTest::qWait(5); + panel->histogramWidget()->repaint(); + QVERIFY(panel->histogramWidget()->displayedHistogram() != nullptr); + panel->setView(nullptr); + QVERIFY(panel->view() == nullptr); + QVERIFY2(panel->histogramWidget()->displayedHistogram() == nullptr, + "detach drops the live histogram pointer (R6)"); + (void)panel->histogramWidget()->grab(); // must not read freed memory + panel->refresh(); + delete panel; + + // Destroying the view clears the strip through the destroyed connection; + // repainting the orphaned panel afterwards is safe. + auto *view2 = new sls::SlsQtFastImage; + view2->resize(300, 300); + view2->show(); + QTest::qWait(5); + view2->setImageCopy(ramp.data(), 64, 32); + view2->repaint(); + auto *panel2 = new sls::SlsQtScalePanel(view2); + panel2->resize(600, 78); + panel2->show(); + QTest::qWait(5); + panel2->histogramWidget()->repaint(); + QVERIFY(panel2->histogramWidget()->displayedHistogram() != nullptr); + delete view2; + QVERIFY(panel2->view() == nullptr); + QVERIFY2(panel2->histogramWidget()->displayedHistogram() == nullptr, + "destroyed view drops the live histogram pointer (R6)"); + (void)panel2->histogramWidget()->grab(); + panel2->refresh(); + delete panel2; + delete view; +} + +// --------------------------------------------------------------------------- +// 1D: SlsQtH1D data container +// --------------------------------------------------------------------------- +void PlottingTest::h1dDataApi() { + std::vector data(10); + for (int i = 0; i < 10; i++) + data[i] = double(i + 1); + sls::SlsQtH1D h(QStringLiteral("hist"), 10, 0.0, 10.0, data.data()); + QCOMPARE(h.GetNBinsX(), 10); + QCOMPARE(h.title(), QStringLiteral("hist")); + QCOMPARE(h.GetXMin(), 0.0); + // Bin width is (xmax - xmin) / n, so for n=10 the last bin starts at 9. + QCOMPARE(h.GetXMax(), 9.0); + QCOMPARE(h.GetYMin(), 1.0); + QCOMPARE(h.GetYMax(), 10.0); + QCOMPARE(h.GetFirstXgtZero(), 1.0); + QCOMPARE(h.GetFirstYgtZero(), 1.0); + + // Fill/FillBin/SetContent/SetBinContent follow the old qwt data contract. + QCOMPARE(h.FillBin(0, 5.0), 6.0); + QCOMPARE(h.GetY()[0], 6.0); + QCOMPARE(h.Fill(5.0, 2.0), 8.0); // y[5] was 6, FindBinIndex(5) == 5 + QCOMPARE(h.SetContent(0.0, 42.0), 42.0); + QCOMPARE(h.SetBinContent(9, 100.0), 100.0); + QCOMPARE(h.GetYMax(), 100.0); + h.Add(1.0); + QCOMPARE(h.GetY()[9], 101.0); + + // Irregular x arrays: decreasing input is stored increasing. + double xs[3] = {2.0, 1.0, 0.0}; + double ys[3] = {7.0, 8.0, 9.0}; + h.SetData(3, xs, ys); + QCOMPARE(h.GetNBinsX(), 3); + QCOMPARE(h.GetX()[0], 0.0); + QCOMPARE(h.GetX()[2], 2.0); + QCOMPARE(h.GetY()[0], 9.0); + QCOMPARE(h.GetY()[2], 7.0); + + // Curve style API used by qDrawPlot. + QCOMPARE(h.SetLineWidth(2), 2); + h.SetLineStyle(1); + QCOMPARE(h.pen().style(), Qt::DashLine); + QCOMPARE(h.SetLineColor(1), 1); + QCOMPARE(h.pen().color(), QColor(Qt::red)); + h.setStyleLinesorDots(false); + QVERIFY(!h.isLines()); + h.setSymbolMarkers(true); + QVERIFY(h.isMarkers()); + QVERIFY(h.legendVisible()); + h.setLegendVisible(false); + QVERIFY(!h.legendVisible()); +} + +// --------------------------------------------------------------------------- +// 1D: auto range / explicit range / zoom / log axes / gain mode / markers +// --------------------------------------------------------------------------- +void PlottingTest::oneDimensionalRangeZoomLogAndGain() { + sls::SlsQt1DPlot plot; + plot.resize(600, 400); + plot.show(); + QTest::qWait(5); + QVERIFY(!plot.isGainPlot()); + QVERIFY(!plot.isZoomDisabled()); + + std::vector y(101); + for (int i = 0; i < 101; i++) + y[i] = 200.0 + 100.0 * std::sin(i / 10.0); + sls::SlsQtH1D curve(QStringLiteral("curve"), 101, 0.0, 101.0, y.data()); + curve.SetLineColor(1); + curve.Attach(&plot); + plot.SetTitle(QStringLiteral("1D plot")); + plot.SetXTitle(QStringLiteral("x")); + plot.SetYTitle(QStringLiteral("counts")); + plot.Update(); + + // Auto range covers the data with the documented 2 % padding. + // viewRect() is QRectF(xLo, yLo, width, height): top() is the lower data + // bound and bottom() the upper one. + const QRectF base = plot.viewRect(); + QVERIFY(base.left() <= 0.0); + QVERIFY(base.right() >= 100.0); + QVERIFY(base.top() <= curve.GetYMin()); + QVERIFY(base.bottom() >= curve.GetYMax()); + + QImage img = render(plot); + QVERIFY2(countPixels(img, [](QRgb c) { return c != kBackground; }) > 500, + "1D plot must paint frame, grid, labels and curve"); + + // Explicit ranges. + plot.SetXMinMax(20.0, 40.0); + QRectF v = plot.viewRect(); + QVERIFY(near(v.left(), 20.0) && near(v.width(), 20.0)); + plot.SetYMinMax(0.0, 100.0); + v = plot.viewRect(); + QVERIFY(near(v.top(), 0.0) && near(v.bottom(), 100.0)); + plot.SetZoom(10.0, 50.0, 20.0, 100.0); + v = plot.viewRect(); + QVERIFY(near(v.left(), 10.0) && near(v.top(), 50.0)); + QVERIFY(near(v.width(), 20.0) && near(v.height(), 100.0)); + + // UnZoom restores the auto range. + plot.UnZoom(); + v = plot.viewRect(); + QVERIFY(near(v.left(), base.left()) && near(v.width(), base.width())); + QVERIFY(near(v.top(), base.top()) && near(v.height(), base.height())); + + // Wheel zoom shrinks the view and reports the viewport. + QSignalSpy spy(&plot, &sls::SlsQt1DPlot::PlotZoomedSignal); + const double w0 = plot.viewRect().width(); + sendWheel(plot, QPointF(300.0, 200.0), 120); + QVERIFY(plot.viewRect().width() < w0); + QVERIFY(spy.count() >= 1); + QVERIFY(spy.takeLast().at(0).toRectF().width() > 0.0); + + // DisableZoom freezes the view. + plot.DisableZoom(true); + QVERIFY(plot.isZoomDisabled()); + const QRectF frozen = plot.viewRect(); + sendWheel(plot, QPointF(300.0, 200.0), 120); + QVERIFY(near(plot.viewRect().width(), frozen.width())); + plot.DisableZoom(false); + QVERIFY(!plot.isZoomDisabled()); + + // Log axes keep the ranges positive. + plot.SetXMinMax(1.0, 100.0); + plot.SetYMinMax(1.0, 100.0); + plot.SetLogX(true); + plot.SetLogY(true); + QRectF lv = plot.viewRect(); + QVERIFY(lv.left() > 0.0 && lv.top() > 0.0); + QVERIFY(lv.right() > lv.left() * 50.0); + QVERIFY(lv.bottom() > lv.top() * 50.0); + (void)render(plot); // must not crash in log mode + plot.SetLogX(false); + plot.SetLogY(false); + + // SetZoomX is the gain-plot x synchronisation path. + plot.SetZoomX(QRectF(5.0, 0.0, 10.0, 1.0)); + v = plot.viewRect(); + QVERIFY(near(v.left(), 5.0) && near(v.width(), 10.0)); + plot.EnableXAutoScaling(); + QVERIFY(plot.viewRect().width() > 15.0); + + // G/H marker lines, SetYStep and alignScales (API compatibility). + plot.SetYMinMax(0.0, 300.0); + plot.InsertHLine(150.0); + plot.InsertVLine(50.0); + plot.SetYStep(2); + plot.alignScales(); + img = render(plot); + QVERIFY2(countPixels(img, isYellow) > 20, + "H/V marker lines are painted in the plot"); + plot.RemoveHLine(); + plot.RemoveVLine(); + plot.EnableYAutoScaling(); + + // O1 (task-10): on a log-y axis the auto-range padding is applied in + // log10 space (2 % of the decade span on each side), not to the linear + // value, so the top point is not glued to the frame. + plot.SetLogY(true); + const QRectF logBase = plot.viewRect(); + const double logYMin = std::log10(curve.GetYMin()); + const double logYMax = std::log10(curve.GetYMax()); + const double padY = 0.02 * (logYMax - logYMin); + QVERIFY(near(std::log10(logBase.top()), logYMin - padY, 1e-9)); + QVERIFY(near(std::log10(logBase.bottom()), logYMax + padY, 1e-9)); + plot.SetLogY(false); + + // Gain mode: fixed 0..3 y range, no zoom, log ignored. + sls::SlsQt1DPlot gain(nullptr, true); + gain.resize(400, 120); + gain.show(); + QTest::qWait(5); + QVERIFY(gain.isGainPlot()); + QVERIFY(gain.isZoomDisabled()); + std::vector g(64, 1.0); + g[10] = 2.0; + g[30] = 3.0; + sls::SlsQtH1D gcurve(QStringLiteral("gain"), 64, 0.0, 64.0, g.data()); + gcurve.Attach(&gain); + gain.Update(); + QRectF gv = gain.viewRect(); + QVERIFY(near(gv.top(), 0.0) && near(gv.bottom(), 3.0)); + gain.SetLogY(true); // ignored for gain plots + QVERIFY(near(gain.viewRect().top(), 0.0)); + QVERIFY(near(gain.viewRect().bottom(), 3.0)); + gain.SetYMinMax(0.0, 100.0); // ignored for gain plots + QVERIFY(near(gain.viewRect().bottom(), 3.0)); + const QImage gshort = render(gain); + QVERIFY(countPixels(gshort, [](QRgb c) { return c != kBackground; }) > 100); + // O2/task-14: the topmost gain tick label ("3") must be fully inside the + // widget in both a short and a tall gain plot. The top-left label area + // (x < plot.left) contains no frame/grid pixels, so it isolates the label. + auto topLabelVisible = [](const QImage &img) { + int count = 0, maxY = -1; + for (int y = 0; y < 18; y++) { + for (int x = 0; x < 28; x++) { + if (!isBright(img.pixel(x, y))) + continue; + count++; + maxY = std::max(maxY, y); + } + } + return count > 5 && maxY >= 8; + }; + QVERIFY2(topLabelVisible(gshort), + "gain top tick label (3) visible at the widget top (O2)"); + gain.resize(400, 340); + QTest::qWait(5); + const QImage gtall = render(gain); + QVERIFY2(topLabelVisible(gtall), + "gain top tick label (3) visible in a tall gain plot (O2)"); +} + +void PlottingTest::oneDimensionalRoiBoxes() { + sls::SlsQt1DPlot plot; + plot.resize(600, 400); + plot.show(); + QTest::qWait(5); + std::vector y(100); + for (int i = 0; i < 100; i++) + y[i] = double(i); + sls::SlsQtH1D curve(QStringLiteral("curve"), 100, 0.0, 100.0, y.data()); + curve.SetLineColor(1); + curve.Attach(&plot); + plot.Update(); + + std::vector rois{slsDetectorDefs::ROI(10, 30), + slsDetectorDefs::ROI(50, 70)}; + plot.EnableRoiBoxes(rois, 0, 100); + QVERIFY(countPixels(render(plot), isYellow) > 100); + + // ROI boxes live in data coordinates and are clipped to the view: a view + // that does not contain them paints no yellow at all. + plot.SetXMinMax(0.0, 5.0); + QCOMPARE(countPixels(render(plot), isYellow), 0); + plot.EnableXAutoScaling(); + QVERIFY(countPixels(render(plot), isYellow) > 100); + + plot.DisableRoiBoxes(); + QCOMPARE(countPixels(render(plot), isYellow), 0); +} + +// --------------------------------------------------------------------------- +// 2D: SlsQt2DHist data container +// --------------------------------------------------------------------------- +void PlottingTest::twoDHistogramContainer() { + sls::SlsQt2DHist hist(4, 0.0, 4.0, 3, 0.0, 3.0); + QCOMPARE(hist.GetNBinsX(), 4); + QCOMPARE(hist.GetNBinsY(), 3); + QCOMPARE(hist.GetXBinWidth(), 1.0); + QCOMPARE(hist.GetYBinWidth(), 1.0); + QCOMPARE(hist.GetXMin(), 0.0); + QCOMPARE(hist.GetXMax(), 4.0); + + std::vector d(12); + for (int by = 0; by < 3; by++) + for (int bx = 0; bx < 4; bx++) + d[size_t(bx) + size_t(by) * 4] = double(bx + by * 4); + hist.SetData(4, 0.0, 4.0, 3, 0.0, 3.0, d.data()); + QCOMPARE(hist.GetBinIndex(1, 1), 5); + QCOMPARE(hist.GetBinValue(1, 1), 5.0); + QCOMPARE(hist.FindBinIndex(0.5, 0.5), 0); + QCOMPARE(hist.FindBinIndex(3.9, 2.9), 11); + QCOMPARE(hist.GetBinIndex(-1, 0), 12); // under/overflow bin + // Auto z range with 2 % padding. + QCOMPARE(hist.GetMinimum(), 0.0); + QVERIFY(near(hist.GetMaximum(), 11.0 * 1.02)); + QVERIFY(near(hist.GetMean(), 5.5)); + + hist.SetMinMax(2.0, 5.0); + QCOMPARE(hist.GetMinimum(), 2.0); + QCOMPARE(hist.GetMaximum(), 5.0); + QCOMPARE(hist.SetMinimumToFirstGreaterThanZero(), 1.0); + QCOMPARE(hist.GetMinimum(), 1.0); + + // Sampling: box vs bilinear. + QVERIFY(!hist.IsInterpolated()); + QCOMPARE(hist.value(1.5, 1.5), 5.0); + QCOMPARE(hist.value(-5.0, -5.0), 0.0); // under/overflow bin + hist.Interpolate(true); + QVERIFY(hist.IsInterpolated()); + QCOMPARE(hist.value(1.5, 1.5), 5.0); // bin centre is exact + QVERIFY(hist.value(1.0, 1.5) > 4.0 && hist.value(1.0, 1.5) < 6.0); + + // SetBinValue never touches the under/overflow bin. + hist.SetBinValue(2, 1, 42.0); + QCOMPARE(hist.GetBinValue(2, 1), 42.0); + hist.SetBinValue(-1, 0, 99.0); + QCOMPARE(hist.GetBinValue(-1, 0), 0.0); + + // A null buffer with the same geometry keeps the previous frame (the + // QImage contract only documents zeroing when the buffer is reallocated); + // a *different* geometry reallocates and zeroes it. Neutral accessors. + hist.SetData(4, 0.0, 4.0, 3, 0.0, 3.0, nullptr); + QCOMPARE(hist.GetBinValue(2, 1), 42.0); + hist.SetData(5, 0.0, 5.0, 2, 0.0, 2.0, nullptr); + QCOMPARE(hist.GetNBinsX(), 5); + QCOMPARE(hist.GetNBinsY(), 2); + for (int by = 0; by < 2; by++) + for (int bx = 0; bx < 5; bx++) + QCOMPARE(hist.GetBinValue(bx, by), 0.0); + hist.SetData(0, 0.0, 4.0, 3, 0.0, 3.0, nullptr); + QCOMPARE(hist.GetNBinsX(), 5); // invalid geometry ignored + + // R3 (task-12): NaN/Inf bins are skipped by the automatic z range/mean. + std::vector nf(12); + for (int i = 0; i < 12; i++) + nf[size_t(i)] = double(i + 1); // 1..12 + nf[0] = std::numeric_limits::quiet_NaN(); // 1 + nf[5] = std::numeric_limits::infinity(); // 6 + nf[7] = -std::numeric_limits::infinity(); // 8 + hist.SetData(4, 0.0, 4.0, 3, 0.0, 3.0, nf.data()); + QVERIFY(std::isfinite(hist.GetMinimum())); + QVERIFY(std::isfinite(hist.GetMaximum())); + QVERIFY(std::isfinite(hist.GetMean())); + QVERIFY(near(hist.GetMinimum(), 2.0 / 1.02)); // smallest finite bin + QVERIFY(near(hist.GetMaximum(), 12.0 * 1.02)); + QVERIFY(near(hist.GetMean(), 7.0)); // (sum finite 63) / 9 + + // No finite bin at all: a harmless 0..1 range and a zero mean. + std::vector allnf(12, std::numeric_limits::quiet_NaN()); + hist.SetData(4, 0.0, 4.0, 3, 0.0, 3.0, allnf.data()); + QCOMPARE(hist.GetMinimum(), 0.0); + QCOMPARE(hist.GetMaximum(), 1.0); + QCOMPARE(hist.GetMean(), 0.0); + + // R5 (task-12): all-negative data is padded OUTWARD on both ends; the + // high end must stay above the data maximum (the brightest bin must not be + // clipped - multiplying a negative max by 1.02 would move it below). + std::vector neg(12); + for (int i = 0; i < 12; i++) + neg[size_t(i)] = (i % 2) ? -10.0 : -20.0; + hist.SetData(4, 0.0, 4.0, 3, 0.0, 3.0, neg.data()); + QVERIFY(hist.GetMinimum() < -20.0); + QVERIFY(near(hist.GetMinimum(), -20.4)); + QVERIFY(hist.GetMaximum() > -10.0); + QVERIFY(near(hist.GetMaximum(), -9.8)); +} + +// --------------------------------------------------------------------------- +// 2D: SetData / z range / scale panel integration +// --------------------------------------------------------------------------- +void PlottingTest::twoDimensionalDataZRangeAndPanel() { + sls::SlsQt2DPlot plot; + plot.resize(700, 600); + plot.show(); + QTest::qWait(5); + QVERIFY(!plot.isGainPlot()); + QVERIFY(plot.imageView() != nullptr); + QVERIFY(plot.scalePanel() != nullptr); + + plot.SetTitle(QStringLiteral("2D detector")); + QCOMPARE(plot.title(), QStringLiteral("2D detector")); + plot.SetXTitle(QStringLiteral("x")); + plot.SetYTitle(QStringLiteral("y")); + // The colour-scale title is a compact caption row above the scale panel. + plot.SetZTitle(QStringLiteral("counts [a.u.]")); + QVERIFY(plot.zTitleLabel() != nullptr); + QTest::qWait(5); + QVERIFY2(plot.zTitleLabel()->isVisible(), + "SetZTitle() shows the z-axis caption"); + QCOMPARE(plot.zTitleLabel()->text(), QStringLiteral("counts [a.u.]")); + plot.SetZTitle(QString()); + QTest::qWait(5); + QVERIFY2(!plot.zTitleLabel()->isVisible(), + "an empty z title hides the caption row again"); + + plot.FillTestPlot(); + QCOMPARE(plot.GetXMinimum(), 200.0); + QCOMPARE(plot.GetXMaximum(), 822.0); + QCOMPARE(plot.GetYMinimum(), -0.5); + QCOMPARE(plot.GetYMaximum(), 49.5); + QVERIFY(plot.GetZMaximum() > plot.GetZMinimum()); + QVERIFY(plot.imageView()->hasImage()); + QCOMPARE(plot.imageView()->imageWidth(), 50); + QCOMPARE(plot.imageView()->imageHeight(), 50); + QVERIFY(plot.imageView()->hasImage()); + + // Z range is pushed to the canvas and the scale panel stays in sync. + plot.SetZMinMax(2.0, 8.0); + QCOMPARE(plot.GetZMinimum(), 2.0); + QCOMPARE(plot.GetZMaximum(), 8.0); + double lo = 0.0, hi = 0.0; + plot.imageView()->colorRange(lo, hi); + QVERIFY(near(lo, 2.0) && near(hi, 8.0)); + QVERIFY(plot.scalePanel()->view() == plot.imageView()); + + // Panel -> plot direction. + plot.scalePanel()->setColorRange(3.0, 6.0); + plot.imageView()->colorRange(lo, hi); + QVERIFY(near(lo, 3.0) && near(hi, 6.0)); + + // Fresh data with an explicit z range. + std::vector d(4 * 3); + for (int i = 0; i < 12; i++) + d[size_t(i)] = double(i); + plot.SetData(4, 0.0, 4.0, 3, 0.0, 3.0, d.data(), 1.0, 9.0); + QCOMPARE(plot.imageView()->imageWidth(), 4); + QCOMPARE(plot.imageView()->imageHeight(), 3); + QCOMPARE(plot.GetZMinimum(), 1.0); + QCOMPARE(plot.GetZMaximum(), 9.0); + QCOMPARE(plot.GetBinValue(1, 1), 5.0); + QCOMPARE(plot.GetBinIndex(1, 1), 5); + QCOMPARE(plot.FindBinIndex(0.5, 0.5), 0); + + plot.SetBinValue(1, 1, 42.0); + QCOMPARE(plot.GetBinValue(1, 1), 42.0); + QCOMPARE(*(plot.GetDataPtr() + 1 + 1 * 4), 42.0); + + // Whole-image fit: no paint outside the plot rectangle of the canvas. + plot.UnZoom(); + QImage img = render(*plot.imageView()); + const QRect ir = + sls::plot::plotRectFor(plot.imageView()->size(), sls::plot::PlotTheme()); + for (int x = ir.right() + 1; x < img.width(); x++) { + for (int y = 0; y < img.height(); y++) { + QVERIFY2(img.pixel(x, y) == kBackground, + "2D canvas must not paint in the right margin"); + } + } + QVERIFY(img.pixel(ir.center()) != kBackground); + + plot.EnableXAutoScaling(); + plot.EnableYAutoScaling(); + plot.SetXMinMax(1.0, 3.0); + plot.SetYMinMax(0.5, 2.5); + QVERIFY(plot.imageView()->hasImage()); + plot.UnZoom(false); +} + +// --------------------------------------------------------------------------- +// 2D: log z, interpolation, contours +// --------------------------------------------------------------------------- +void PlottingTest::twoDimensionalLogInterpolateAndContour() { + sls::SlsQt2DPlot plot; + plot.resize(800, 600); + plot.show(); + QTest::qWait(5); + plot.FillTestPlot(); + plot.UnZoom(); + + // Log z reaches the canvas and the panel chooser. + plot.LogZ(true); + QVERIFY(plot.imageView()->logScale()); + plot.LogZ(false); + QVERIFY(!plot.imageView()->logScale()); + + // SetLogz(enable, isMin, isMax, min, max) sets the range and the scale. + // An explicit Plot-tab / SetLogz() range is honoured in log mode too (the + // old qwt behaviour): the requested zmin/zmax reach the data and the + // canvas. + plot.SetLogz(true, true, true, 0.1, 9.0); + QVERIFY(plot.imageView()->logScale()); + QVERIFY(near(plot.GetZMinimum(), 0.1)); + QVERIFY(near(plot.GetZMaximum(), 9.0)); + double zlo = 0.0, zhi = 0.0; + plot.imageView()->colorRange(zlo, zhi); + QVERIFY(near(zlo, 0.1) && near(zhi, 9.0)); + + // The explicit range survives the Update() calls of streaming frames ... + plot.Update(); + QVERIFY(near(plot.GetZMinimum(), 0.1)); + QVERIFY(near(plot.GetZMaximum(), 9.0)); + plot.imageView()->colorRange(zlo, zhi); + QVERIFY(near(zlo, 0.1) && near(zhi, 9.0)); + + // ... while SetZRange(false, false) (qDrawPlot's per-frame call while the + // z-range check boxes are off) drops the explicit pin and returns to the + // automatic log range. + plot.SetZRange(false, false, 0.0, 0.0); + QVERIFY(plot.GetZMinimum() > 0.0); + QVERIFY(!(near(plot.GetZMinimum(), 0.1) && near(plot.GetZMaximum(), 9.0))); + plot.imageView()->colorRange(zlo, zhi); + QVERIFY(near(zlo, plot.GetZMinimum()) && near(zhi, plot.GetZMaximum())); + + // Contours are painted through the clipped overlay hook. + const QImage blocky = render(*plot.imageView()); + plot.SetContour(true); + const QImage contours = render(*plot.imageView()); + QVERIFY2(blocky != contours, "SetContour(true) changes the rendered image"); + const QRect ir = + sls::plot::plotRectFor(plot.imageView()->size(), sls::plot::PlotTheme()); + for (int x = ir.right() + 1; x < contours.width(); x++) { + for (int y = 0; y < contours.height(); y++) { + QVERIFY2(contours.pixel(x, y) == kBackground, + "contours must be clipped to the plot rect"); + } + } + plot.SetContour(false); + QVERIFY(render(*plot.imageView()) == blocky); + + // Bilinear interpolation overlay. + plot.SetInterpolate(true); + const QImage smooth = render(*plot.imageView()); + QVERIFY2(smooth != blocky, "SetInterpolate(true) changes the rendered image"); + plot.SetInterpolate(false); + QVERIFY(render(*plot.imageView()) == blocky); + + // Spectrogram image can be hidden without losing contours/ROI paint. + plot.showSpectrogram(false); + QVERIFY(render(*plot.imageView()) != blocky); + plot.showSpectrogram(true); + QVERIFY(render(*plot.imageView()) == blocky); + + // R8 (task-12): on a >256-wide frame the marching-squares grid is + // subsampled; the last row/column must be included so the contours reach + // the image edges (pre-fix an outer band up to step-1 bins wide was empty). + plot.LogZ(false); + { + std::vector big(size_t(1024) * 1024); + for (int y = 0; y < 1024; y++) + for (int x = 0; x < 1024; x++) + big[size_t(y) * 1024 + size_t(x)] = double(x + y); + plot.SetData(1024, -0.5, 1023.5, 1024, -0.5, 1023.5, big.data()); + plot.UnZoom(); + plot.SetContour(true); + plot.showSpectrogram(false); // contour-only render on the dark canvas + const QImage edgeImg = render(*plot.imageView()); + const QPointF imgRight = + plot.imageView()->dataToWidget(QPointF(1024.0, 0.0)); + const QPointF imgTop = + plot.imageView()->dataToWidget(QPointF(0.0, 1024.0)); + int maxX = -1; + int minY = std::numeric_limits::max(); + for (int y = ir.top(); y <= ir.bottom(); y++) { + for (int x = ir.left(); x <= ir.right(); x++) { + if (!isBright(edgeImg.pixel(x, y))) + continue; + maxX = std::max(maxX, x); + minY = std::min(minY, y); + } + } + QVERIFY2(maxX >= int(std::lround(imgRight.x())) - 1, + "contours reach the image right edge (R8)"); + QVERIFY2(minY <= int(std::lround(imgTop.y())) + 1, + "contours reach the image top edge (R8)"); + plot.showSpectrogram(true); + plot.SetContour(false); + plot.FillTestPlot(); // restore the small test frame + } + + // R3 (task-12): a frame with NaN/Inf bins keeps the z range and the canvas + // colour range finite (auto range skips the non-finite bins). + plot.SetZRange(false, false, 0.0, 0.0); + { + std::vector nf(50 * 50); + for (int i = 0; i < 50 * 50; i++) + nf[size_t(i)] = double(i % 100); + nf[0] = std::numeric_limits::quiet_NaN(); + nf[1] = std::numeric_limits::infinity(); + nf[2] = -std::numeric_limits::infinity(); + plot.SetData(50, -0.5, 49.5, 50, -0.5, 49.5, nf.data()); + double qlo = 0.0, qhi = 0.0; + plot.imageView()->colorRange(qlo, qhi); + QVERIFY(std::isfinite(qlo) && std::isfinite(qhi)); + QVERIFY(qhi > qlo); + QVERIFY(std::isfinite(plot.GetZMinimum())); + QVERIFY(std::isfinite(plot.GetZMaximum())); + QVERIFY(std::isfinite(plot.GetZMean())); + (void)render(*plot.imageView()); + + std::vector allnf(50 * 50, + std::numeric_limits::quiet_NaN()); + plot.SetData(50, -0.5, 49.5, 50, -0.5, 49.5, allnf.data()); + plot.imageView()->colorRange(qlo, qhi); + QVERIFY(near(qlo, 0.0) && near(qhi, 1.0)); + } + + plot.LogZ(false); +} + +// --------------------------------------------------------------------------- +// 2D: ROI boxes, viewport/zoom, no paint outside the plot rect +// --------------------------------------------------------------------------- +void PlottingTest::twoDimensionalRoiAndClipping() { + sls::SlsQt2DPlot plot; + plot.resize(700, 600); + plot.show(); + QTest::qWait(5); + std::vector d(100 * 80); + for (int y = 0; y < 80; y++) + for (int x = 0; x < 100; x++) + d[size_t(y) * 100 + x] = double(x + y); + plot.SetData(100, 0.0, 100.0, 80, 0.0, 80.0, d.data()); + plot.UnZoom(); + + std::vector rois{slsDetectorDefs::ROI(10, 29, 20, 39)}; + plot.EnableRoiBoxes(rois); + const std::vector &ov = plot.imageView()->overlayRects(); + QCOMPARE(int(ov.size()), 1); + QVERIFY(near(ov[0].left(), 10.0) && near(ov[0].top(), 20.0)); + QVERIFY(near(ov[0].width(), 20.0) && near(ov[0].height(), 20.0)); + QImage img = render(*plot.imageView()); + const QPointF roiCorner = plot.imageView()->dataToWidget(QPointF(10.0, 20.0)); + QVERIFY2(yellowNear(img, roiCorner.toPoint(), 3), + "ROI box is painted in data coordinates"); + plot.DisableRoiBoxes(); + QVERIFY(plot.imageView()->overlayRects().empty()); + + // Programmatic zoom: data rect -> image pixel-edge viewport. + plot.SetZoom(QRectF(20.0, 20.0, 20.0, 20.0)); + double x = 0.0, y = 0.0, w = 0.0, h = 0.0; + plot.imageView()->viewport(x, y, w, h); + QVERIFY(near(x, 20.0) && near(y, 20.0)); + QVERIFY(near(w, 20.0) && near(h, 20.0)); + QVERIFY(plot.imageView()->hasImage()); + + // Deep zoom: the canvas must still be clipped to its plot rect. + img = render(*plot.imageView()); + const QRect ir = + sls::plot::plotRectFor(plot.imageView()->size(), sls::plot::PlotTheme()); + for (int xx = ir.right() + 1; xx < img.width(); xx++) { + for (int yy = 0; yy < img.height(); yy++) { + QVERIFY2(img.pixel(xx, yy) == kBackground, + "zoomed 2D image must be clipped to the plot rect"); + } + } + + // User zoom emits the data-coordinate viewport for the gain-plot sync. + QSignalSpy spy(&plot, &sls::SlsQt2DPlot::PlotZoomedSignal); + sendWheel(*plot.imageView(), + QPointF(plot.imageView()->width() / 2.0, + plot.imageView()->height() / 2.0), + 120); + QVERIFY(spy.count() >= 1); + const QRectF zr = spy.takeLast().at(0).toRectF(); + QVERIFY(zr.width() > 0.0 && zr.height() > 0.0); + QVERIFY(zr.width() <= 100.0 && zr.height() <= 80.0); + plot.UnZoom(); +} + +// --------------------------------------------------------------------------- +// 2D: gain mode +// --------------------------------------------------------------------------- +void PlottingTest::twoDimensionalGainMode() { + sls::SlsQt2DPlot gain(nullptr, true); + gain.resize(200, 200); + gain.show(); + QTest::qWait(5); + QVERIFY(gain.isGainPlot()); + QVERIFY(gain.scalePanel() == nullptr); + QVERIFY(gain.zTitleLabel() == nullptr); + QVERIFY(!gain.imageView()->axesVisible()); + QVERIFY(!gain.imageView()->zoomEnabled()); + QCOMPARE(gain.imageView()->paletteIndex(), + int(sls::plot::Palette::Gain4)); + double lo = 0.0, hi = 0.0; + gain.imageView()->colorRange(lo, hi); + QVERIFY(near(lo, 0.0) && near(hi, 3.0)); + + // Four quadrants, one per gain bit (data layout: x fastest, y up). + std::vector d(8 * 8); + for (int by = 0; by < 8; by++) + for (int bx = 0; bx < 8; bx++) { + const int g = (bx < 4 ? 0 : 1) + (by < 4 ? 2 : 0); + d[size_t(bx) + size_t(by) * 8] = double(g); + } + gain.SetData(8, 0.0, 8.0, 8, 0.0, 8.0, d.data()); + QCOMPARE(gain.imageView()->imageWidth(), 8); + QCOMPARE(gain.imageView()->imageHeight(), 8); + const QImage img = render(*gain.imageView()); + const QRgb c0 = img.pixel(int(gain.imageView()->dataToWidget(QPointF(1.5, 1.5)).x()), + int(gain.imageView()->dataToWidget(QPointF(1.5, 1.5)).y())); + const QRgb c1 = img.pixel(int(gain.imageView()->dataToWidget(QPointF(5.5, 1.5)).x()), + int(gain.imageView()->dataToWidget(QPointF(5.5, 1.5)).y())); + const QRgb c2 = img.pixel(int(gain.imageView()->dataToWidget(QPointF(1.5, 5.5)).x()), + int(gain.imageView()->dataToWidget(QPointF(1.5, 5.5)).y())); + const QRgb c3 = img.pixel(int(gain.imageView()->dataToWidget(QPointF(5.5, 5.5)).x()), + int(gain.imageView()->dataToWidget(QPointF(5.5, 5.5)).y())); + // Data value = (x>=4 ? 1 : 0) + (y>=4 ? 2 : 0); the bottom half (small y) + // adds 2, so the bottom-left cell is gain bit 2. + const QRgb *gainLut = sls::plot::paletteLut(sls::plot::Palette::Gain4); + QCOMPARE(c0, gainLut[170]); // value 2 + QCOMPARE(c1, gainLut[255]); // value 3 + QCOMPARE(c2, gainLut[0]); // value 0 + QCOMPARE(c3, gainLut[85]); // value 1 + // All four categorical colours are actually painted somewhere. + QSet present; + for (int yy = 0; yy < img.height(); yy++) + for (int xx = 0; xx < img.width(); xx++) + present.insert(img.pixel(xx, yy)); + for (int k : {0, 85, 170, 255}) + QVERIFY2(present.contains(gainLut[k]), + "all four gain categories are painted"); +} + +// --------------------------------------------------------------------------- +// acceptance benchmark: 1024x512 float frames at >= 20 Hz +// --------------------------------------------------------------------------- +void PlottingTest::performance1024x512() { + sls::SlsQtFastImage view; + view.resize(1100, 600); + view.show(); + QTest::qWait(20); + std::vector frame = acceptanceFrame(); + view.setColorRange(-2.0, 2.0); + view.setImageCopy(frame.data(), 1024, 512); + view.repaint(); + + // Warm up: first paints allocate the cached QImage and font paths. + for (int i = 0; i < 5; i++) { + frame[0] = float(i); + view.setImageCopy(frame.data(), 1024, 512); + view.repaint(); + } + + const int frames = 60; + QElapsedTimer timer; + timer.start(); + for (int i = 0; i < frames; i++) { + frame[0] = float(i); + view.setImageCopy(frame.data(), 1024, 512); + view.repaint(); // synchronous: copy + compose + paint + } + const double seconds = double(timer.nsecsElapsed()) / 1e9; + const double fps = double(frames) / seconds; + qInfo("1024x512 benchmark: %.1f fps (%.2f ms/frame)", fps, + 1000.0 * seconds / frames); + QVERIFY2(fps >= 20.0, "1024x512 frames must render at >= 20 fps"); +} + +QTEST_MAIN(PlottingTest) +#include "plotting_test.moc"