None of this has a reader:
- ScalingSettings::scaling_regularize and its setter/getter
- ScaleOnTheFlyResult::succesful (never set) and ::time_s (set, never read),
with the timing that only fed the latter
- JFJochImage::last_fit_viewport_ (written twice, read nowhere) and the
comment claiming the retry uses it - the retry keys off initial_fit_done_
- JFJochDiffractionImage::ice_ring_width_Q_recipA, and a QtConcurrent include
in a file that uses none
- an unused gemmi::Op accumulator in the spindle-angle helper
- <random> in Merge.{h,cpp}, from before the half-set split became a hash
- an orphaned comment describing the Ceres B-factor residual deleted in
014e43a4c, and two trailing comments that had collided on one line
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
253 lines
10 KiB
C++
253 lines
10 KiB
C++
// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
|
|
// SPDX-License-Identifier: GPL-3.0-only
|
|
|
|
#pragma once
|
|
|
|
#include <cmath>
|
|
#include <memory>
|
|
|
|
#include <QElapsedTimer>
|
|
#include <QTimer>
|
|
#include <QGraphicsView>
|
|
#include <QGraphicsItem>
|
|
#include <QImage>
|
|
#include <QMouseEvent>
|
|
#include <QPainterPath>
|
|
#include <QTransform>
|
|
#include <QPointF>
|
|
#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{};
|
|
|
|
[[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<float>(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<int>(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<const QImage> img_;
|
|
public:
|
|
explicit JFJochImageItem(std::shared_ptr<const QImage> 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;
|
|
|
|
// 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;
|
|
|
|
bool auto_bg = false;
|
|
bool auto_fg = false;
|
|
bool hdr_mode = false;
|
|
|
|
double scale_factor = 1.0;
|
|
|
|
size_t W = 0, H = 0;
|
|
size_t prev_W = 0, prev_H = 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<float> 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<QImage> frame_ = std::make_shared<QImage>();
|
|
|
|
// Persistent image item — never destroyed/recreated on overlay update
|
|
JFJochImageItem *image_item_ = nullptr;
|
|
// Overlay items managed separately
|
|
QList<QGraphicsItem *> 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;
|
|
|
|
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.
|
|
void ScheduleRenderImage();
|
|
bool render_pending_ = false;
|
|
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);
|
|
void hoverScenePos(QPointF scenePos);
|
|
// A new frame has been rendered into Frame(). Follower views repaint on this.
|
|
void frameRendered();
|
|
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 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<const QImage> Frame() const { return frame_; }
|
|
}; |