// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute // SPDX-License-Identifier: GPL-3.0-only #pragma once #include #include #include #include #include #include #include #include #include #include #include #include "../../common/ColorScale.h" #include "../../common/JFJochMessages.h" // Q_DECLARE_METATYPE(ROIMessage) // Maps one pixel value to a colour. Shared by the generic float path and by subclasses that // colour straight out of their own buffer, so the two cannot drift apart. Apply() takes a // real value; the callers handle their own gap/bad/saturated encoding. struct PixelColorMap { const rgb *lut = nullptr; int lut_size = 0; float minv = 0.0f; float range = 0.0f; float inv_range = 0.0f; float inv_range_log = 0.0f; bool hdr = false; rgb gap{}, bad{}, saturated{}, beam_stop{}; [[nodiscard]] rgb Apply(float v) const { float f; const float v_minv = v - minv; if (hdr) { if (v_minv <= 0.0f) f = 0.0f; else if (v_minv >= range) f = static_cast(lut_size); else f = std::log1p(v_minv) * inv_range_log; } else f = v_minv * inv_range; if (f < 0.0f) f = 0.0f; auto idx = static_cast(f + 0.5f); if (idx <= 0) idx = 0; else if (idx >= lut_size) idx = lut_size - 1; return lut[idx]; } }; // Draws a rendered frame. A QGraphicsPixmapItem would mean converting the whole image into a // QPixmap on every recolour, which costs one extra allocation and a full pass over the pixels. // The frame is held by shared_ptr so that several views can show the same pixels. class JFJochImageItem : public QGraphicsItem { std::shared_ptr img_; public: explicit JFJochImageItem(std::shared_ptr img) : img_(std::move(img)) {} QRectF boundingRect() const override; QPainterPath opaqueArea() const override; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; void refresh(); // the buffer behind the item changed }; class JFJochImage : public QGraphicsView { Q_OBJECT bool m_adjustForegroundWithWheel = false; bool m_adjustBackgroundWithWheel = false; // Viewport-lock support: guard prevents the emit<->apply ping-pong between // two linked views, and the helper broadcasts the current transform+center. bool m_applyingViewport = false; void emitViewportChanged(); void DrawROI(); virtual void addCustomOverlay(); void updateROI(); void drawPixelLabels(QPainter *painter, const QRectF &rect); void wheelEvent(QWheelEvent* event) override; void resizeEvent(QResizeEvent *event) override; void contextMenuEvent(QContextMenuEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; protected: // Only the view that owns detector counts offers a region of interest; for the others a // shift-drag would draw a box that means nothing. [[nodiscard]] virtual bool AllowROI() const { return false; } bool show_saturation = false; // Beam-stop shadow drawn in its own colour; off shows it as an ordinary masked pixel. bool show_beam_stop = true; bool auto_bg = false; bool auto_fg = false; bool hdr_mode = false; double scale_factor = 1.0; size_t W = 0, H = 0; // Scene position of the image's top-left pixel: the image covers [origin_, origin_ + (W, H)) of the // scene. Zero but for a detector plane raster that starts elsewhere (JFJochDiffractionImage). QPointF origin_{0, 0}; [[nodiscard]] QRectF ImageRect() const { return {origin_, QSizeF(static_cast(W), static_cast(H))}; } size_t prev_W = 0, prev_H = 0; // Height of one pixel as it is drawn, in units of its width. 1.0 for a detector image, where // pixels are square; a grid scan whose x and y steps differ sets it so that a cell is drawn // in the proportion of the area it covers. Only the view transform is anisotropic - scene // coordinates stay one unit per pixel everywhere. qreal pixel_aspect_ = 1.0; qreal prev_aspect_ = 1.0; // Track initial fit state and last image size bool initial_fit_done_ = false; QColor feature_color = Qt::magenta; // Decimal places for non-integer per-pixel value labels. Float images are // unreadable with many decimals, so subclasses can lower this. int label_decimals_ = 3; float foreground = 10.0; float background = 0.0; ColorScale color_scale; std::vector image_fp; // The rendered RGB frame. Reused across frames (no per-frame allocation) and held by // shared_ptr so follower views can display the very same pixels - see JFJochFollowerImage. // The pointer itself is stable for the lifetime of the widget; only its contents change. std::shared_ptr frame_ = std::make_shared(); // Persistent image item — never destroyed/recreated on overlay update JFJochImageItem *image_item_ = nullptr; // Overlay items managed separately QList overlay_items_; // Helper: add an overlay item to the scene and track it for selective removal void addOverlayItem(QGraphicsItem *item); enum class MouseEventType {None, Panning, DrawingROI, MovingROI, ResizingROI, EditingExternalROI}; MouseEventType mouse_event_type = MouseEventType::None; // Hooks for editing a named, persistent ROI drawn by a subclass (the base only // owns the mouse events; the subclass knows the loaded ROIs). roiEditPress returns // true to claim the gesture for ROI editing. virtual bool roiEditPress(const QPointF &scenePos) { return false; } virtual void roiEditMove(const QPointF &scenePos) {} virtual void roiEditRelease() {} virtual void roiScratchDrawn() {} // a shift/ctrl-drag finished drawing a new box/circle QPoint lastMousePos; // To track panning movement // Resizing which edge/corner enum class ResizeHandle { None, Left, Right, Top, Bottom, TopLeft, TopRight, BottomLeft, BottomRight, Inside }; ResizeHandle active_handle_ = ResizeHandle::None; ResizeHandle hover_handle_ = ResizeHandle::None; enum class RoiType {RoiBox, RoiCircle}; RoiType roi_type = RoiType::RoiBox; QPointF roiStartPos; QPointF roiEndPos; QRectF roiBox; // Text for the per-pixel value label at (x, y). The base reads image_fp, which is what the // float-valued views hold; a view whose source is exact integers overrides this so the label // is exact and no float copy of the image has to exist at all. [[nodiscard]] virtual QString PixelLabel(int x, int y) const; void drawForeground(QPainter *painter, const QRectF &rect) override; static QPointF RoundPoint(const QPointF& p); virtual void mouseHover(const QPointF &scenePos, Qt::KeyboardModifiers modifiers) = 0; // Hover feedback (status bar, resolution readout, magnifier) used to be regenerated on every // single mouse motion. Each regeneration dirties the window, and on a remote X session every // repaint costs a full-window pixel upload, so the thing to minimise is the number of // repaints. ~15 Hz is far below the motion event rate and well above what the eye follows. // // The rate limit is applied inline rather than from a timer on purpose: running the update // inside the mouse event keeps its damage in the same repaint as anything else that event // triggers (a pan), instead of costing a second one. The timer only covers the tail, so the // final position is still reported once the pointer stops. static constexpr int kHoverIntervalMs = 66; void ScheduleHoverUpdate(const QPointF &scenePos, Qt::KeyboardModifiers modifiers); void UpdateHover(); void leaveEvent(QEvent *event) override; QPointF hover_scene_pos_; Qt::KeyboardModifiers hover_modifiers_ = Qt::NoModifier; QElapsedTimer hover_rate_; QTimer *hover_tail_timer_ = nullptr; // Panning and wheel zooming repaint once per input event, which is fine locally and hopeless // on a remote display (see ScheduleHoverUpdate above - same reasoning, same cadence, same // inline-plus-tail shape). On a remote session the skipped events only accumulate - a pan its // pixel delta, a zoom its wheel steps - and the accumulated gesture is applied whole, so the // view ends exactly where the same gesture would have put it unthrottled. Locally every event // is still applied inline and nothing changes. void ApplyPendingPan(); QPoint pending_pan_; QElapsedTimer pan_rate_; QTimer *pan_tail_timer_ = nullptr; void ApplyPendingZoom(); int pending_zoom_steps_ = 0; QPoint zoom_anchor_vp_; QElapsedTimer zoom_rate_; QTimer *zoom_tail_timer_ = nullptr; ResizeHandle hitTestROIHandle(const QPointF& scenePos, qreal tol = 3.0) const; void updateOverlay(); void RenderImage(); PixelColorMap MakeColorMap() const; // Colour one row into `out`. Called from worker threads, so it must stay const. The base // maps image_fp; a subclass whose source is already a compact buffer can map that directly // and skip materialising the float image. virtual void ColorRow(size_t y, const PixelColorMap &map, QRgb *out) const; // Re-render once the event queue drains. The foreground slider and the wheel emit far // faster than a large image can be recoloured, so intermediate values are dropped // instead of queueing a full recolour per event. On a remote display the drain still // repaints once per event, so there the recolour is additionally held to the hover cadence. void ScheduleRenderImage(); bool render_pending_ = false; QElapsedTimer render_rate_; QTimer *render_tail_timer_ = nullptr; bool image_dirty_ = false; // frame_ changed since the item was last refreshed void ClearFrame(); // drop the pixels and tell followers // Set while a pan/zoom moves the scrollbars, so onScroll() does not rebuild the overlay // once per scrollbar; the gesture rebuilds it once itself. bool suppress_overlay_update_ = false; void Redraw(); // Invalidate image_item_ and overlay tracking after scene()->clear() void resetScenePointers(); // Perform initial fit-to-view (shorter direction), once per image size void fitToViewShorterSideOnce(); // Render the current frame to an image at native resolution, optionally including the overlay // (spots, predictions, rings, ROIs). Used by both the clipboard and save-to-file actions. QImage renderToImage(bool with_overlay); void copyImageToClipboard(); void copyImageWithOverlayToClipboard(); void saveImageToFile(bool with_overlay); void clearROIInternal(); signals: void autoForegroundChanged(bool input); void foregroundChanged(float v); void backgroundChanged(float v); void writeStatusBar(QString string, int timeout_ms = 0); void roiBoxUpdated(QRect box); void roiCircleUpdated(double x, double y, double radius); void viewportChanged(QTransform transform, QPointF center); // A new frame has been rendered into Frame(). Follower views repaint on this. void frameRendered(); // Asks for a move through the dataset (e.g. Home/End/PageUp/PageDown in a subclass' // keyPressEvent): the navigation toolbar applies the step, clamped to the dataset's range. void stepImage(int steps); private slots: void onScroll(int value); public slots: void setFeatureColor(QColor input); void setColorMap(int color_map); virtual void changeForeground(float val); void changeBackground(float val); void SetROIBox(QRect box); void SetROICircle(double x, double y, double radius); void centerOnSpot(QPointF point); void applyViewport(QTransform transform, QPointF center); void fitToView(); void adjustForeground(bool input); void adjustBackground(bool input); void setZoom(double input); public: explicit JFJochImage(QWidget *parent = nullptr); double GetScaleFactor() const; // The rendered frame, for views that want to show the same pixels without redoing the work [[nodiscard]] std::shared_ptr Frame() const { return frame_; } };