InstrumentWidgetPickTab.cpp 63.4 KB
Newer Older
1
2
3
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4
5
//   NScD Oak Ridge National Laboratory, European Spallation Source,
//   Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6
// SPDX - License - Identifier: GPL - 3.0 +
Roman Tolchenov's avatar
Roman Tolchenov committed
7
#include "MantidQtWidgets/InstrumentView/InstrumentWidgetPickTab.h"
8
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
Roman Tolchenov's avatar
Roman Tolchenov committed
9
#include "MantidQtWidgets/Common/TSVSerialiser.h"
10
#endif
Roman Tolchenov's avatar
Roman Tolchenov committed
11
12
13
14
15
16
17
#include "MantidQtWidgets/InstrumentView/CollapsiblePanel.h"
#include "MantidQtWidgets/InstrumentView/InstrumentActor.h"
#include "MantidQtWidgets/InstrumentView/InstrumentWidget.h"
#include "MantidQtWidgets/InstrumentView/PeakMarker2D.h"
#include "MantidQtWidgets/InstrumentView/Projection3D.h"
#include "MantidQtWidgets/InstrumentView/ProjectionSurface.h"
#include "MantidQtWidgets/InstrumentView/UnwrappedSurface.h"
18

Nick Draper's avatar
Nick Draper committed
19
#include "MantidAPI/AlgorithmManager.h"
20
#include "MantidAPI/AnalysisDataService.h"
21
#include "MantidAPI/Axis.h"
22
23
#include "MantidAPI/IPeaksWorkspace.h"
#include "MantidAPI/MatrixWorkspace.h"
24
#include "MantidAPI/Sample.h"
25
26
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidGeometry/Crystal/OrientedLattice.h"
Lamar Moore's avatar
Lamar Moore committed
27
28
#include "MantidGeometry/Instrument/ComponentInfo.h"
#include "MantidGeometry/Instrument/DetectorInfo.h"
LamarMoore's avatar
LamarMoore committed
29
#include "MantidKernel/Unit.h"
30
#include "MantidKernel/V3D.h"
31
32
33

#include <QAction>
#include <QActionGroup>
LamarMoore's avatar
LamarMoore committed
34
35
#include <QApplication>
#include <QGridLayout>
36
#include <QLabel>
LamarMoore's avatar
LamarMoore committed
37
#include <QMenu>
38
39
#include <QMessageBox>
#include <QPixmap>
LamarMoore's avatar
LamarMoore committed
40
#include <QPushButton>
41
#include <QSettings>
LamarMoore's avatar
LamarMoore committed
42
43
44
#include <QSignalMapper>
#include <QTextEdit>
#include <QVBoxLayout>
45

46
#include <algorithm>
47
48
#include <cfloat>
#include <cmath>
49
50
#include <numeric>
#include <vector>
51

52
53
#include <boost/math/constants/constants.hpp>

54
55
using Mantid::API::AlgorithmManager;

56
57
58
namespace MantidQt {
namespace MantidWidgets {

59
60
using namespace boost::math;

61
namespace {
Lamar Moore's avatar
Lamar Moore committed
62
63
// Get the phi angle between the detector with reference to the origin
// Makes assumptions about beam direction. Legacy code and not robust.
64
65
66
67
double getPhi(const Mantid::Kernel::V3D &pos) {
  return std::atan2(pos[1], pos[0]);
}

Lamar Moore's avatar
Lamar Moore committed
68
69
// Calculate the phi angle between detector and beam, and then offset.
// Makes assumptions about beam direction. Legacy code and not robust.
70
71
72
73
74
75
double getPhiOffset(const Mantid::Kernel::V3D &pos, const double offset) {
  double avgPos = getPhi(pos);
  return avgPos < 0 ? -(offset + avgPos) : offset - avgPos;
}
} // namespace

76
/**
LamarMoore's avatar
LamarMoore committed
77
78
79
 * Constructor.
 * @param instrWidget :: Parent InstrumentWidget.
 */
80
81
InstrumentWidgetPickTab::InstrumentWidgetPickTab(InstrumentWidget *instrWidget)
    : InstrumentWidgetTab(instrWidget), m_freezePlot(false),
82
83
84
85
      m_tubeXUnitsCache(0), m_plotTypeCache(0),
      m_addedActions(
          std::vector<std::pair<
              QAction *, std::function<bool(std::map<std::string, bool>)>>>{}) {
86
87
88
89
90
91
92
93
94
95
96
97
98

  // connect to InstrumentWindow signals
  connect(m_instrWidget, SIGNAL(integrationRangeChanged(double, double)), this,
          SLOT(changedIntegrationRange(double, double)));

  m_plotSum = true;

  QVBoxLayout *layout = new QVBoxLayout(this);

  // set up the selection display
  m_selectionInfoDisplay = new QTextEdit(this);

  // set up the plot widget
99
  m_plot = new MiniPlot(this);
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
  connect(m_plot, SIGNAL(showContextMenu()), this, SLOT(plotContextMenu()));

  // Plot context menu actions
  m_sumDetectors = new QAction("Sum", this);
  m_sumDetectors->setCheckable(true);
  m_sumDetectors->setChecked(true);
  m_integrateTimeBins = new QAction("Integrate", this);
  m_integrateTimeBins->setCheckable(true);
  m_summationType = new QActionGroup(this);
  m_summationType->addAction(m_sumDetectors);
  m_summationType->addAction(m_integrateTimeBins);
  m_logY = new QAction("Y log scale", this);
  m_linearY = new QAction("Y linear scale", this);
  m_yScale = new QActionGroup(this);
  m_yScale->addAction(m_linearY);
  m_yScale->addAction(m_logY);
  m_logY->setCheckable(true);
  m_linearY->setCheckable(true);
  m_linearY->setChecked(true);
  connect(m_sumDetectors, SIGNAL(triggered()), this, SLOT(sumDetectors()));
  connect(m_integrateTimeBins, SIGNAL(triggered()), this,
          SLOT(integrateTimeBins()));
  connect(m_logY, SIGNAL(triggered()), m_plot, SLOT(setYLogScale()));
  connect(m_linearY, SIGNAL(triggered()), m_plot, SLOT(setYLinearScale()));

  m_unitsMapper = new QSignalMapper(this);

  m_detidUnits = new QAction("Detector ID", this);
  m_detidUnits->setCheckable(true);
  m_unitsMapper->setMapping(m_detidUnits, DetectorPlotController::DETECTOR_ID);
  connect(m_detidUnits, SIGNAL(triggered()), m_unitsMapper, SLOT(map()));

  m_lengthUnits = new QAction("Tube length", this);
  m_lengthUnits->setCheckable(true);
  m_unitsMapper->setMapping(m_lengthUnits, DetectorPlotController::LENGTH);
  connect(m_lengthUnits, SIGNAL(triggered()), m_unitsMapper, SLOT(map()));

  m_phiUnits = new QAction("Phi", this);
  m_phiUnits->setCheckable(true);
  m_unitsMapper->setMapping(m_phiUnits, DetectorPlotController::PHI);
  connect(m_phiUnits, SIGNAL(triggered()), m_unitsMapper, SLOT(map()));

  m_outOfPlaneAngleUnits = new QAction("Out of plane angle", this);
  m_outOfPlaneAngleUnits->setCheckable(true);
  m_unitsMapper->setMapping(m_outOfPlaneAngleUnits,
                            DetectorPlotController::OUT_OF_PLANE_ANGLE);
  connect(m_outOfPlaneAngleUnits, SIGNAL(triggered()), m_unitsMapper,
          SLOT(map()));

  m_unitsGroup = new QActionGroup(this);
  m_unitsGroup->addAction(m_detidUnits);
  m_unitsGroup->addAction(m_lengthUnits);
  m_unitsGroup->addAction(
      m_phiUnits); // re #4169 disabled until fixed or removed
  m_unitsGroup->addAction(m_outOfPlaneAngleUnits);
  connect(m_unitsMapper, SIGNAL(mapped(int)), this, SLOT(setTubeXUnits(int)));

  // Instrument display context menu actions
  m_storeCurve = new QAction("Store curve", this);
  connect(m_storeCurve, SIGNAL(triggered()), this, SLOT(storeCurve()));
  m_savePlotToWorkspace = new QAction("Save plot to workspace", this);
  connect(m_savePlotToWorkspace, SIGNAL(triggered()), this,
          SLOT(savePlotToWorkspace()));

  CollapsibleStack *panelStack = new CollapsibleStack(this);
  m_infoPanel = panelStack->addPanel("Selection", m_selectionInfoDisplay);
  m_plotPanel = panelStack->addPanel("Name", m_plot);
167
  collapsePlotPanel();
168
169
170

  m_selectionType = Single;

171
172
  m_infoController = nullptr;
  m_plotController = nullptr;
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219

  m_activeTool = new QLabel(this);
  // set up the tool bar

  m_zoom = new QPushButton();
  m_zoom->setCheckable(true);
  m_zoom->setAutoExclusive(true);
  m_zoom->setIcon(QIcon(":/PickTools/zoom.png"));
  m_zoom->setToolTip("Zoom in and out");

  m_one = new QPushButton();
  m_one->setCheckable(true);
  m_one->setAutoExclusive(true);
  m_one->setChecked(true);
  m_one->setToolTip("Select single pixel");
  m_one->setIcon(QIcon(":/PickTools/selection-pointer.png"));

  m_tube = new QPushButton();
  m_tube->setCheckable(true);
  m_tube->setAutoExclusive(true);
  m_tube->setIcon(QIcon(":/PickTools/selection-tube.png"));
  m_tube->setToolTip("Select whole tube");

  m_rectangle = new QPushButton();
  m_rectangle->setCheckable(true);
  m_rectangle->setAutoExclusive(true);
  m_rectangle->setIcon(QIcon(":/PickTools/selection-box.png"));
  m_rectangle->setToolTip("Draw a rectangle");

  m_ellipse = new QPushButton();
  m_ellipse->setCheckable(true);
  m_ellipse->setAutoExclusive(true);
  m_ellipse->setIcon(QIcon(":/PickTools/selection-circle.png"));
  m_ellipse->setToolTip("Draw a ellipse");

  m_ring_ellipse = new QPushButton();
  m_ring_ellipse->setCheckable(true);
  m_ring_ellipse->setAutoExclusive(true);
  m_ring_ellipse->setIcon(QIcon(":/PickTools/selection-circle-ring.png"));
  m_ring_ellipse->setToolTip("Draw an elliptical ring");

  m_ring_rectangle = new QPushButton();
  m_ring_rectangle->setCheckable(true);
  m_ring_rectangle->setAutoExclusive(true);
  m_ring_rectangle->setIcon(QIcon(":/PickTools/selection-box-ring.png"));
  m_ring_rectangle->setToolTip("Draw a rectangular ring");

220
221
222
223
224
225
  m_sector = new QPushButton();
  m_sector->setCheckable(true);
  m_sector->setAutoExclusive(true);
  m_sector->setIcon(QIcon(":/PickTools/selection-sector.png"));
  m_sector->setToolTip("Draw a circular sector");

226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
  m_free_draw = new QPushButton();
  m_free_draw->setCheckable(true);
  m_free_draw->setAutoExclusive(true);
  m_free_draw->setIcon(QIcon(":/PickTools/brush.png"));
  m_free_draw->setToolTip("Draw an arbitrary shape");

  m_edit = new QPushButton();
  m_edit->setCheckable(true);
  m_edit->setAutoExclusive(true);
  m_edit->setIcon(QIcon(":/PickTools/selection-edit.png"));
  m_edit->setToolTip("Edit a shape");

  m_peak = new QPushButton();
  m_peak->setCheckable(true);
  m_peak->setAutoExclusive(true);
  m_peak->setIcon(QIcon(":/PickTools/selection-peak.png"));
  m_peak->setToolTip("Add single crystal peak");

  m_peakSelect = new QPushButton();
  m_peakSelect->setCheckable(true);
  m_peakSelect->setAutoExclusive(true);
  m_peakSelect->setIcon(QIcon(":/PickTools/eraser.png"));
  m_peakSelect->setToolTip("Erase single crystal peak(s)");

250
251
252
  m_peakCompare = new QPushButton();
  m_peakCompare->setCheckable(true);
  m_peakCompare->setAutoExclusive(true);
253
  m_peakCompare->setIcon(QIcon(":/PickTools/selection-peak-compare.png"));
254
255
  m_peakCompare->setToolTip("Compare single crystal peak(s)");

256
257
258
  m_peakAlign = new QPushButton();
  m_peakAlign->setCheckable(true);
  m_peakAlign->setAutoExclusive(true);
259
  m_peakAlign->setIcon(QIcon(":/PickTools/selection-peak-plane.png"));
260
261
  m_peakAlign->setToolTip("Crystal peak alignment tool");

262
  auto *toolBox = new QGridLayout();
263
264
265
266
267
268
  toolBox->addWidget(m_zoom, 0, 0);
  toolBox->addWidget(m_edit, 0, 1);
  toolBox->addWidget(m_ellipse, 0, 2);
  toolBox->addWidget(m_rectangle, 0, 3);
  toolBox->addWidget(m_ring_ellipse, 0, 4);
  toolBox->addWidget(m_ring_rectangle, 0, 5);
269
270
  toolBox->addWidget(m_sector, 0, 6);
  toolBox->addWidget(m_free_draw, 0, 7);
271
272
273
274
  toolBox->addWidget(m_one, 1, 0);
  toolBox->addWidget(m_tube, 1, 1);
  toolBox->addWidget(m_peak, 1, 2);
  toolBox->addWidget(m_peakSelect, 1, 3);
275
  toolBox->addWidget(m_peakCompare, 1, 4);
276
  toolBox->addWidget(m_peakAlign, 1, 5);
Mathieu Tillet's avatar
Mathieu Tillet committed
277
  toolBox->setColumnStretch(8, 1);
278
279
280
281
282
283
  toolBox->setSpacing(2);
  connect(m_zoom, SIGNAL(clicked()), this, SLOT(setSelectionType()));
  connect(m_one, SIGNAL(clicked()), this, SLOT(setSelectionType()));
  connect(m_tube, SIGNAL(clicked()), this, SLOT(setSelectionType()));
  connect(m_peak, SIGNAL(clicked()), this, SLOT(setSelectionType()));
  connect(m_peakSelect, SIGNAL(clicked()), this, SLOT(setSelectionType()));
284
  connect(m_peakCompare, SIGNAL(clicked()), this, SLOT(setSelectionType()));
285
  connect(m_peakAlign, SIGNAL(clicked()), this, SLOT(setSelectionType()));
286
287
288
289
  connect(m_rectangle, SIGNAL(clicked()), this, SLOT(setSelectionType()));
  connect(m_ellipse, SIGNAL(clicked()), this, SLOT(setSelectionType()));
  connect(m_ring_ellipse, SIGNAL(clicked()), this, SLOT(setSelectionType()));
  connect(m_ring_rectangle, SIGNAL(clicked()), this, SLOT(setSelectionType()));
290
  connect(m_sector, SIGNAL(clicked()), this, SLOT(setSelectionType()));
291
292
293
294
295
296
297
298
299
  connect(m_free_draw, SIGNAL(clicked()), this, SLOT(setSelectionType()));
  connect(m_edit, SIGNAL(clicked()), this, SLOT(setSelectionType()));

  // lay out the widgets
  layout->addWidget(m_activeTool);
  layout->addLayout(toolBox);
  layout->addWidget(panelStack);
}

300
301
302
303
304
/**
 * If the workspace is monochromatic, the plot panel is useless and should be
 * collapsed
 */
void InstrumentWidgetPickTab::collapsePlotPanel() {
305
  if (!m_instrWidget->isIntegrable()) {
Mathieu Tillet's avatar
Mathieu Tillet committed
306
    m_plotPanel->collapseCaption();
307
308
  } else
    m_plotPanel->expandCaption();
309
310
}

311
/**
LamarMoore's avatar
LamarMoore committed
312
313
 * Returns true if the plot can be updated when the mouse moves over detectors
 */
314
315
316
317
318
bool InstrumentWidgetPickTab::canUpdateTouchedDetector() const {
  return !m_peak->isChecked();
}

/**
LamarMoore's avatar
LamarMoore committed
319
320
 * Display the miniplot's context menu.
 */
321
void InstrumentWidgetPickTab::plotContextMenu() {
322
  QMenu context(m_plot);
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398

  auto plotType = m_plotController->getPlotType();

  if (plotType == DetectorPlotController::TubeSum ||
      plotType == DetectorPlotController::TubeIntegral) {
    // only for multiple detector selectors
    context.addActions(m_summationType->actions());
    m_sumDetectors->setChecked(plotType == DetectorPlotController::TubeSum);
    m_integrateTimeBins->setChecked(plotType !=
                                    DetectorPlotController::TubeSum);
    m_integrateTimeBins->setEnabled(true);
    context.addSeparator();
  }

  if (m_plot->hasStored()) {
    // the remove menu
    QMenu *removeCurves = new QMenu("Remove", this);
    QSignalMapper *signalMapper = new QSignalMapper(this);
    QStringList labels = m_plot->getLabels();
    foreach (QString label, labels) {
      QColor c = m_plot->getCurveColor(label);
      QPixmap pixmap(16, 2);
      pixmap.fill(c);
      QAction *remove = new QAction(QIcon(pixmap), label, removeCurves);
      removeCurves->addAction(remove);
      connect(remove, SIGNAL(triggered()), signalMapper, SLOT(map()));
      signalMapper->setMapping(remove, label);
    }
    connect(signalMapper, SIGNAL(mapped(const QString &)), this,
            SLOT(removeCurve(const QString &)));
    context.addMenu(removeCurves);
  }

  // the axes menu
  QMenu *axes = new QMenu("Axes", this);
  axes->addActions(m_yScale->actions());
  if (m_plot->isYLogScale()) {
    m_logY->setChecked(true);
  } else {
    m_linearY->setChecked(true);
  }

  // Tube x units menu options
  if (plotType == DetectorPlotController::TubeIntegral) {
    axes->addSeparator();
    axes->addActions(m_unitsGroup->actions());
    auto tubeXUnits = m_plotController->getTubeXUnits();
    switch (tubeXUnits) {
    case DetectorPlotController::DETECTOR_ID:
      m_detidUnits->setChecked(true);
      break;
    case DetectorPlotController::LENGTH:
      m_lengthUnits->setChecked(true);
      break;
    case DetectorPlotController::PHI:
      m_phiUnits->setChecked(true);
      break;
    case DetectorPlotController::OUT_OF_PLANE_ANGLE:
      m_outOfPlaneAngleUnits->setChecked(true);
      break;
    default:
      m_detidUnits->setChecked(true);
    }
  }
  context.addMenu(axes);

  // save plot to workspace
  if (m_plot->hasStored() || m_plot->hasCurve()) {
    context.addAction(m_savePlotToWorkspace);
  }

  // show menu
  context.exec(QCursor::pos());
}

/**
LamarMoore's avatar
LamarMoore committed
399
400
 * Update the plot caption. The captions shows the selection type.
 */
401
402
403
404
405
void InstrumentWidgetPickTab::setPlotCaption() {
  m_plotPanel->setCaption(m_plotController->getPlotCaption());
}

/**
LamarMoore's avatar
LamarMoore committed
406
407
 * Switch to the detectors summing regime.
 */
408
409
410
411
412
413
414
void InstrumentWidgetPickTab::sumDetectors() {
  m_plotController->setPlotType(DetectorPlotController::TubeSum);
  m_plotController->updatePlot();
  setPlotCaption();
}

/**
LamarMoore's avatar
LamarMoore committed
415
416
 * Switch to the time bin integration regime.
 */
417
418
419
420
421
422
423
void InstrumentWidgetPickTab::integrateTimeBins() {
  m_plotController->setPlotType(DetectorPlotController::TubeIntegral);
  m_plotController->updatePlot();
  setPlotCaption();
}

/**
LamarMoore's avatar
LamarMoore committed
424
425
 * Set the selection type according to which tool button is checked.
 */
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
void InstrumentWidgetPickTab::setSelectionType() {
  ProjectionSurface::InteractionMode surfaceMode =
      ProjectionSurface::PickSingleMode;
  auto plotType = m_plotController->getPlotType();
  if (m_zoom->isChecked()) {
    m_selectionType = Single;
    m_activeTool->setText("Tool: Navigation");
    surfaceMode = ProjectionSurface::MoveMode;
  } else if (m_one->isChecked()) {
    m_selectionType = Single;
    m_activeTool->setText("Tool: Pixel selection");
    surfaceMode = ProjectionSurface::PickSingleMode;
    plotType = DetectorPlotController::Single;
  } else if (m_tube->isChecked()) {
    m_selectionType = Tube;
    m_activeTool->setText("Tool: Tube/bank selection");
    surfaceMode = ProjectionSurface::PickTubeMode;
    if (plotType < DetectorPlotController::TubeSum) {
      plotType = DetectorPlotController::TubeSum;
    }
  } else if (m_peak->isChecked()) {
    m_selectionType = AddPeak;
    m_activeTool->setText("Tool: Add a single crystal peak");
    surfaceMode = ProjectionSurface::AddPeakMode;
    plotType = DetectorPlotController::Single;
  } else if (m_peakSelect->isChecked()) {
    m_selectionType = ErasePeak;
    m_activeTool->setText("Tool: Erase crystal peak(s)");
    surfaceMode = ProjectionSurface::ErasePeakMode;
455
456
457
458
  } else if (m_peakCompare->isChecked()) {
    m_selectionType = ComparePeak;
    m_activeTool->setText("Tool: Compare crystal peak(s)");
    surfaceMode = ProjectionSurface::ComparePeakMode;
459
460
461
462
  } else if (m_peakAlign->isChecked()) {
    m_selectionType = AlignPeak;
    m_activeTool->setText("Tool: Align crystal peak(s)");
    surfaceMode = ProjectionSurface::AlignPeakMode;
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
  } else if (m_rectangle->isChecked()) {
    m_selectionType = Draw;
    m_activeTool->setText("Tool: Rectangle");
    surfaceMode = ProjectionSurface::DrawRegularMode;
    plotType = DetectorPlotController::Single;
    m_instrWidget->getSurface()->startCreatingShape2D(
        "rectangle", Qt::green, QColor(255, 255, 255, 80));
  } else if (m_ellipse->isChecked()) {
    m_selectionType = Draw;
    m_activeTool->setText("Tool: Ellipse");
    surfaceMode = ProjectionSurface::DrawRegularMode;
    plotType = DetectorPlotController::Single;
    m_instrWidget->getSurface()->startCreatingShape2D(
        "ellipse", Qt::green, QColor(255, 255, 255, 80));
  } else if (m_ring_ellipse->isChecked()) {
    m_selectionType = Draw;
    m_activeTool->setText("Tool: Elliptical ring");
    surfaceMode = ProjectionSurface::DrawRegularMode;
    plotType = DetectorPlotController::Single;
    m_instrWidget->getSurface()->startCreatingShape2D(
        "ring ellipse", Qt::green, QColor(255, 255, 255, 80));
  } else if (m_ring_rectangle->isChecked()) {
    m_selectionType = Draw;
    m_activeTool->setText("Tool: Rectangular ring");
    surfaceMode = ProjectionSurface::DrawRegularMode;
    plotType = DetectorPlotController::Single;
    m_instrWidget->getSurface()->startCreatingShape2D(
        "ring rectangle", Qt::green, QColor(255, 255, 255, 80));
491
492
493
494
495
496
497
  } else if (m_sector->isChecked()) {
    m_selectionType = Draw;
    m_activeTool->setText("Tool: Circular sector");
    surfaceMode = ProjectionSurface::DrawRegularMode;
    plotType = DetectorPlotController::Single;
    m_instrWidget->getSurface()->startCreatingShape2D(
        "sector", Qt::green, QColor(255, 255, 255, 80));
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
  } else if (m_free_draw->isChecked()) {
    m_selectionType = Draw;
    m_activeTool->setText("Tool: Arbitrary shape");
    surfaceMode = ProjectionSurface::DrawFreeMode;
    plotType = DetectorPlotController::Single;
    m_instrWidget->getSurface()->startCreatingFreeShape(
        Qt::green, QColor(255, 255, 255, 80));
  } else if (m_edit->isChecked()) {
    m_selectionType = Draw;
    m_activeTool->setText("Tool: Shape editing");
    surfaceMode = ProjectionSurface::DrawRegularMode;
    plotType = DetectorPlotController::Single;
  }
  m_plotController->setPlotType(plotType);
  auto surface = m_instrWidget->getSurface();
  if (surface) {
    surface->setInteractionMode(surfaceMode);
    auto interactionMode = surface->getInteractionMode();
    if (interactionMode == ProjectionSurface::DrawRegularMode ||
        interactionMode == ProjectionSurface::MoveMode) {
      updatePlotMultipleDetectors();
    } else {
      m_plot->clearAll();
      m_plot->replot();
    }
    setPlotCaption();
  }
  m_instrWidget->updateInfoText();
}

/**
LamarMoore's avatar
LamarMoore committed
529
530
 * Respond to the show event.
 */
531
void InstrumentWidgetPickTab::showEvent(QShowEvent * /*unused*/) {
532
533
534
535
536
537
538
539
540
  // Make the state of the display view consistent with the current selection
  // type
  setSelectionType();
  // make sure picking updated
  m_instrWidget->updateInstrumentView(true);
  m_instrWidget->getSurface()->changeBorderColor(getShapeBorderColor());
}

/**
LamarMoore's avatar
LamarMoore committed
541
542
 * Keep current curve permanently displayed on the plot.
 */
543
544
545
void InstrumentWidgetPickTab::storeCurve() { m_plot->store(); }

/**
LamarMoore's avatar
LamarMoore committed
546
547
548
 * Remove a stored curve.
 * @param label :: The label of the curve to remove
 */
549
550
551
552
553
554
void InstrumentWidgetPickTab::removeCurve(const QString &label) {
  m_plot->removeCurve(label);
  m_plot->replot();
}

/**
LamarMoore's avatar
LamarMoore committed
555
556
557
 * Set the x units for the integrated tube plot.
 * @param units :: The x units in terms of TubeXUnits.
 */
558
559
560
561
562
563
564
565
566
void InstrumentWidgetPickTab::setTubeXUnits(int units) {
  if (units < 0 || units >= DetectorPlotController::NUMBER_OF_UNITS)
    return;
  auto tubeXUnits = static_cast<DetectorPlotController::TubeXUnits>(units);
  m_plotController->setTubeXUnits(tubeXUnits);
  m_plotController->updatePlot();
}

/**
LamarMoore's avatar
LamarMoore committed
567
568
569
 * Get the color of the overlay shapes in this tab.
 * @return
 */
570
571
572
573
574
QColor InstrumentWidgetPickTab::getShapeBorderColor() const {
  return QColor(Qt::green);
}

/**
575
 * Do something when the time bin integration range has changed.
LamarMoore's avatar
LamarMoore committed
576
 */
Tom Titcombe's avatar
Tom Titcombe committed
577
578
void InstrumentWidgetPickTab::changedIntegrationRange(double /*unused*/,
                                                      double /*unused*/) {
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
  m_plotController->updatePlot();
  auto surface = m_instrWidget->getSurface();
  if (surface) {
    auto interactionMode = surface->getInteractionMode();
    if (interactionMode == ProjectionSurface::DrawRegularMode ||
        interactionMode == ProjectionSurface::MoveMode) {
      updatePlotMultipleDetectors();
    }
  }
}

void InstrumentWidgetPickTab::initSurface() {
  ProjectionSurface *surface = getSurface().get();
  connect(surface, SIGNAL(singleComponentTouched(size_t)), this,
          SLOT(singleComponentTouched(size_t)));
  connect(surface, SIGNAL(singleComponentPicked(size_t)), this,
          SLOT(singleComponentPicked(size_t)));
LamarMoore's avatar
LamarMoore committed
596
597
598
599
600
601
602
603
604
605
606
607
608
609
  connect(surface,
          SIGNAL(comparePeaks(
              const std::pair<std::vector<Mantid::Geometry::IPeak *>,
                              std::vector<Mantid::Geometry::IPeak *>> &)),
          this,
          SLOT(comparePeaks(
              const std::pair<std::vector<Mantid::Geometry::IPeak *>,
                              std::vector<Mantid::Geometry::IPeak *>> &)));
  connect(surface,
          SIGNAL(alignPeaks(const std::vector<Mantid::Kernel::V3D> &,
                            const Mantid::Geometry::IPeak *)),
          this,
          SLOT(alignPeaks(const std::vector<Mantid::Kernel::V3D>,
                          const Mantid::Geometry::IPeak *)));
610
611
612
613
614
615
616
617
618
619
620
  connect(surface, SIGNAL(peaksWorkspaceAdded()), this,
          SLOT(updateSelectionInfoDisplay()));
  connect(surface, SIGNAL(peaksWorkspaceDeleted()), this,
          SLOT(updateSelectionInfoDisplay()));
  connect(surface, SIGNAL(shapeCreated()), this, SLOT(shapeCreated()));
  connect(surface, SIGNAL(shapeChangeFinished()), this,
          SLOT(updatePlotMultipleDetectors()));
  connect(surface, SIGNAL(shapesCleared()), this,
          SLOT(updatePlotMultipleDetectors()));
  connect(surface, SIGNAL(shapesRemoved()), this,
          SLOT(updatePlotMultipleDetectors()));
621
  auto *p3d = dynamic_cast<Projection3D *>(surface);
622
623
624
625
  if (p3d) {
    connect(p3d, SIGNAL(finishedMove()), this,
            SLOT(updatePlotMultipleDetectors()));
  }
Antti Soininen's avatar
Antti Soininen committed
626
627
628
  m_infoController =
      new ComponentInfoController(this, m_instrWidget, m_selectionInfoDisplay);
  m_plotController = new DetectorPlotController(this, m_instrWidget, m_plot);
629
630
631
632
  m_plotController->setTubeXUnits(
      static_cast<DetectorPlotController::TubeXUnits>(m_tubeXUnitsCache));
  m_plotController->setPlotType(
      static_cast<DetectorPlotController::PlotType>(m_plotTypeCache));
633
  // miniplot X unit
634
  const auto &actor = m_instrWidget->getInstrumentActor();
635
636
637
  // default X axis label
  m_plot->setXLabel(QString::fromStdString(
      actor.getWorkspace()->getAxis(0)->unit()->unitID()));
638
639
640
}

/**
LamarMoore's avatar
LamarMoore committed
641
642
 * Return current ProjectionSurface.
 */
643
std::shared_ptr<ProjectionSurface> InstrumentWidgetPickTab::getSurface() const {
644
645
646
  return m_instrWidget->getSurface();
}

647
648
const InstrumentWidget *InstrumentWidgetPickTab::getInstrumentWidget() const {
  return m_instrWidget;
649
650
}

651
/**
LamarMoore's avatar
LamarMoore committed
652
653
 * Save tab's persistent settings to the provided QSettings instance
 */
654
655
656
657
658
659
void InstrumentWidgetPickTab::saveSettings(QSettings &settings) const {
  settings.setValue("TubeXUnits", m_plotController->getTubeXUnits());
  settings.setValue("PlotType", m_plotController->getPlotType());
}

/**
LamarMoore's avatar
LamarMoore committed
660
661
662
 * Restore (read and apply) tab's persistent settings from the provided
 * QSettings instance
 */
663
664
665
666
667
668
669
void InstrumentWidgetPickTab::loadSettings(const QSettings &settings) {
  // loadSettings is called when m_plotController is not created yet.
  // Cache the settings and apply them later
  m_tubeXUnitsCache = settings.value("TubeXUnits", 0).toInt();
  m_plotTypeCache =
      settings.value("PlotType", DetectorPlotController::Single).toInt();
}
670
671
672
673
void InstrumentWidgetPickTab::addToContextMenu(
    QAction *action,
    std::function<bool(std::map<std::string, bool>)> &actionCondition) {
  auto pair = std::make_pair(action, actionCondition);
674
  m_addedActions.emplace_back(pair);
675
}
676
/**
LamarMoore's avatar
LamarMoore committed
677
678
679
 * Fill in the context menu.
 * @param context :: A menu to fill.
 */
680
681
682
683
684
685
686
687
688
689
690
bool InstrumentWidgetPickTab::addToDisplayContextMenu(QMenu &context) const {
  m_freezePlot = true;
  bool res = false;
  if (m_plot->hasCurve()) {
    context.addAction(m_storeCurve);
    res = true;
  }
  if (m_plot->hasStored() || m_plot->hasCurve()) {
    context.addAction(m_savePlotToWorkspace);
    res = true;
  }
691
  std::map<std::string, bool> tabBools = {};
692
  tabBools.insert(std::make_pair("plotStored", m_plot->hasStored()));
693
694
695
696
697
698
699
  tabBools.insert(std::make_pair("hasCurve", m_plot->hasCurve()));
  tabBools.insert(std::make_pair("isTube", m_tube->isChecked()));
  for (auto actionPair : m_addedActions) {
    if (actionPair.second && actionPair.second(tabBools)) {
      context.addAction(actionPair.first);
    }
  }
700
701
702
703
  return res;
}

/**
LamarMoore's avatar
LamarMoore committed
704
705
706
 * Select a tool on the tab
 * @param tool One of the enumerated tool types, @see ToolType
 */
707
708
709
710
711
712
713
714
715
716
717
718
719
720
void InstrumentWidgetPickTab::selectTool(const ToolType tool) {
  switch (tool) {
  case Zoom:
    m_zoom->setChecked(true);
    break;
  case PixelSelect:
    m_one->setChecked(true);
    break;
  case TubeSelect:
    m_tube->setChecked(true);
    break;
  case PeakSelect:
    m_peak->setChecked(true);
    break;
721
722
  case PeakCompare:
    m_peakCompare->setChecked(true);
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
  case PeakErase:
    m_peakSelect->setChecked(true);
    break;
  case DrawRectangle:
    m_rectangle->setChecked(true);
    break;
  case DrawEllipse:
    m_ellipse->setChecked(true);
    break;
  case DrawFree:
    m_free_draw->setChecked(true);
    break;
  case EditShape:
    m_edit->setChecked(true);
    break;
  default:
    throw std::invalid_argument("Invalid tool type.");
  }
  setSelectionType();
}

void InstrumentWidgetPickTab::singleComponentTouched(size_t pickID) {
  if (canUpdateTouchedDetector()) {
    m_infoController->displayInfo(pickID);
    m_plotController->setPlotData(pickID);
    m_plotController->updatePlot();
  }
}

void InstrumentWidgetPickTab::singleComponentPicked(size_t pickID) {
  m_infoController->displayInfo(pickID);
  m_plotController->setPlotData(pickID);
755
  m_plotController->zoomOutOnPlot();
756
757
758
  m_plotController->updatePlot();
}

759
760
761
void InstrumentWidgetPickTab::comparePeaks(
    const std::pair<std::vector<Mantid::Geometry::IPeak *>,
                    std::vector<Mantid::Geometry::IPeak *>> &peaks) {
762
763
764
  m_infoController->displayComparePeaksInfo(peaks);
}

765
766
767
void InstrumentWidgetPickTab::alignPeaks(
    const std::vector<Mantid::Kernel::V3D> &planePeaks,
    const Mantid::Geometry::IPeak *peak) {
Samuel Jackson's avatar
Samuel Jackson committed
768
  m_infoController->displayAlignPeaksInfo(planePeaks, peak);
769
770
}

771
/**
LamarMoore's avatar
LamarMoore committed
772
773
774
 * Update the selection display using currently selected detector.
 * Updates non-detector information on it.
 */
775
776
777
778
779
void InstrumentWidgetPickTab::updateSelectionInfoDisplay() {
  // updateSelectionInfo(m_currentDetID);
}

/**
LamarMoore's avatar
LamarMoore committed
780
781
 * Respond to the shapeCreated signal from the surface.
 */
782
783
784
785
786
787
788
789
790
void InstrumentWidgetPickTab::shapeCreated() {
  if (!isVisible())
    return;
  if (!m_free_draw->isChecked()) {
    selectTool(EditShape);
  }
}

/**
LamarMoore's avatar
LamarMoore committed
791
792
793
 * Update the mini-plot with information from multiple detector
 * selected with drawn shapes.
 */
794
795
796
797
798
void InstrumentWidgetPickTab::updatePlotMultipleDetectors() {
  if (!isVisible())
    return;
  ProjectionSurface &surface = *getSurface();
  if (surface.hasMasks()) {
799
    std::vector<size_t> dets;
800
801
802
803
804
805
806
807
    surface.getMaskedDetectors(dets);
    m_plotController->setPlotData(dets);
  } else {
    m_plotController->clear();
  }
  m_plot->replot();
}

808
809
810
811
812
813
814
815
816
817
/**
 * Clear all the tab's widgets.
 */
void InstrumentWidgetPickTab::clearWidgets() {
  m_plotController->clear();
  m_infoController->clear();
  selectTool(ToolType::PixelSelect);
  collapsePlotPanel();
}

818
/**
LamarMoore's avatar
LamarMoore committed
819
820
 * Save data plotted on the miniplot into a MatrixWorkspace.
 */
821
822
823
824
void InstrumentWidgetPickTab::savePlotToWorkspace() {
  m_plotController->savePlotToWorkspace();
}

825
826
827
828
/** Load pick tab state from a Mantid project file
 * @param lines :: lines from the project file to load state from
 */
void InstrumentWidgetPickTab::loadFromProject(const std::string &lines) {
829
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
830
  API::TSVSerialiser tsv(lines);
831
832
833
834
835
836

  if (!tsv.selectSection("picktab"))
    return;

  std::string tabLines;
  tsv >> tabLines;
837
  API::TSVSerialiser tab(tabLines);
838
839
840

  // load active push button
  std::vector<QPushButton *> buttons{
LamarMoore's avatar
LamarMoore committed
841
842
843
      m_zoom,         m_edit,           m_ellipse,   m_rectangle,
      m_ring_ellipse, m_ring_rectangle, m_free_draw, m_one,
      m_tube,         m_peak,           m_peakSelect};
844
845
846
847
848
849
850

  tab.selectLine("ActiveTools");
  for (auto button : buttons) {
    bool value;
    tab >> value;
    button->setChecked(value);
  }
851
852
853
854
855
#else
  Q_UNUSED(lines);
  throw std::runtime_error(
      "MaskBinsData::loadFromProject() not implemented for Qt >= 5");
#endif
856
857
858
859
860
861
}

/** Save the state of the pick tab to a Mantid project file
 * @return a string representing the state of the pick tab
 */
std::string InstrumentWidgetPickTab::saveToProject() const {
862
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
863
  API::TSVSerialiser tsv, tab;
864
865
866

  // save active push button
  std::vector<QPushButton *> buttons{
LamarMoore's avatar
LamarMoore committed
867
868
869
      m_zoom,         m_edit,           m_ellipse,   m_rectangle,
      m_ring_ellipse, m_ring_rectangle, m_free_draw, m_one,
      m_tube,         m_peak,           m_peakSelect};
870
871
872
873
874
875
876
877

  tab.writeLine("ActiveTools");
  for (auto button : buttons) {
    tab << button->isChecked();
  }

  tsv.writeSection("picktab", tab.outputLines());
  return tsv.outputLines();
878
879
880
881
#else
  throw std::runtime_error(
      "MaskBinsData::saveToProject() not implemented for Qt >= 5");
#endif
882
883
}

884
885
886
//=====================================================================================//

/**
LamarMoore's avatar
LamarMoore committed
887
888
889
890
891
 * Create and setup iteself.
 * @param tab :: QObject parent - the tab.
 * @param instrWidget :: A pointer to an InstrumentWidget instance.
 * @param infoDisplay :: Widget on which to display the information.
 */
Antti Soininen's avatar
Antti Soininen committed
892
893
894
ComponentInfoController::ComponentInfoController(
    InstrumentWidgetPickTab *tab, const InstrumentWidget *instrWidget,
    QTextEdit *infoDisplay)
895
    : QObject(tab), m_tab(tab), m_instrWidget(instrWidget),
896
      m_selectionInfoDisplay(infoDisplay), m_freezePlot(false),
897
898
      m_instrWidgetBlocked(false),
      m_currentPickID(std::numeric_limits<size_t>::max()) {}
899
900

/**
LamarMoore's avatar
LamarMoore committed
901
902
903
 * Display info on a component refered to by a pick ID.
 * @param pickID :: A pick ID of a component.
 */
904
905
906
907
908
909
void ComponentInfoController::displayInfo(size_t pickID) {
  if (m_freezePlot) { // freeze the plot for one update
    m_freezePlot = false;
    pickID = m_currentPickID;
  }

910
  const auto &actor = m_instrWidget->getInstrumentActor();
911
  const auto &componentInfo = actor.componentInfo();
912
  QString text = "";
913
914
  if (componentInfo.isDetector(pickID)) {
    text += displayDetectorInfo(pickID);
915
  } else if (auto componentID = actor.getComponentID(pickID)) {
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
    text += displayNonDetectorInfo(componentID);
  } else {
    clear();
  }
  // display info about peak overlays
  text += getPeakOverlayInfo();

  if (!text.isEmpty()) {
    m_selectionInfoDisplay->setText(text);
  } else {
    clear();
  }
}

/**
LamarMoore's avatar
LamarMoore committed
931
932
933
 * Return string with info on a detector.
 * @param index :: A detector Index.
 */
934
QString ComponentInfoController::displayDetectorInfo(size_t index) {
935
936
937
938
939
940
  if (m_instrWidgetBlocked) {
    clear();
    return "";
  }

  QString text;
Lamar Moore's avatar
Lamar Moore committed
941
942
943

  // collect info about selected detector and add it to text
  const auto &actor = m_instrWidget->getInstrumentActor();
944
  const auto &componentInfo = actor.componentInfo();
Lamar Moore's avatar
Lamar Moore committed
945
946
947
948
949
950
  auto detid = actor.getDetID(index);

  text = "Selected detector: " +
         QString::fromStdString(componentInfo.name(index)) + "\n";
  text += "Detector ID: " + QString::number(detid) + '\n';
  QString wsIndex;
951
952
  auto ws = actor.getWorkspaceIndex(index);
  wsIndex = ws == InstrumentActor::INVALID_INDEX ? "None" : QString::number(ws);
Lamar Moore's avatar
Lamar Moore committed
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
  text += "Workspace index: " + wsIndex + '\n';
  Mantid::Kernel::V3D pos = componentInfo.position(index);
  text += "xyz: " + QString::number(pos.X()) + "," + QString::number(pos.Y()) +
          "," + QString::number(pos.Z()) + '\n';
  double r, t, p;
  pos.getSpherical(r, t, p);
  text += "rtp: " + QString::number(r) + "," + QString::number(t) + "," +
          QString::number(p) + '\n';
  if (componentInfo.hasParent(index)) {
    QString textpath;
    auto parent = index;
    while (componentInfo.hasParent(parent)) {
      parent = componentInfo.parent(parent);
      textpath =
          "/" + QString::fromStdString(componentInfo.name(parent)) + textpath;
    }
    text += "Component path:" + textpath + "/" +
            QString::fromStdString(componentInfo.name(index)) + '\n';

972
    const double integrated = actor.getIntegratedCounts(index);
973
974
975
    const QString counts = integrated == InstrumentActor::INVALID_VALUE
                               ? "N/A"
                               : QString::number(integrated);
976
977
    text += "Counts: " + counts + '\n';
    // display info about peak overlays
978
    text += actor.getParameterInfo(index);
979
980
981
982
983
  }
  return text;
}

/**
LamarMoore's avatar
LamarMoore committed
984
985
986
987
 * string with information about a selected non-detector component (such as
 * choppers, etc).
 * @param compID :: A component ID for a component to display.
 */
988
989
QString ComponentInfoController::displayNonDetectorInfo(
    Mantid::Geometry::ComponentID compID) {
Lamar Moore's avatar
Lamar Moore committed
990
  const auto &actor = m_instrWidget->getInstrumentActor();
991
  const auto &componentInfo = actor.componentInfo();
Lamar Moore's avatar
Lamar Moore committed
992
  auto component = componentInfo.indexOf(compID);
993
  QString text = "Selected component: ";
Lamar Moore's avatar
Lamar Moore committed
994
995
  text += QString::fromStdString(componentInfo.name(component)) + '\n';
  Mantid::Kernel::V3D pos = componentInfo.position(component);
996
997
998
999
1000
  text += "xyz: " + QString::number(pos.X()) + "," + QString::number(pos.Y()) +
          "," + QString::number(pos.Z()) + '\n';
  double r, t, p;
  pos.getSpherical(r, t, p);
  text += "rtp: " + QString::number(r) + "," + QString::number(t) + "," +
For faster browsing, not all history is shown. View entire blame