InstrumentWidgetPickTab.cpp 63.6 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
#include "MantidAPI/WorkspaceFactory.h"
26
#include "MantidDataObjects/Peak.h"
27
#include "MantidGeometry/Crystal/OrientedLattice.h"
Lamar Moore's avatar
Lamar Moore committed
28
29
#include "MantidGeometry/Instrument/ComponentInfo.h"
#include "MantidGeometry/Instrument/DetectorInfo.h"
LamarMoore's avatar
LamarMoore committed
30
#include "MantidKernel/Unit.h"
31
#include "MantidKernel/V3D.h"
32
33
34

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

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

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

55
56
using Mantid::API::AlgorithmManager;

57
58
59
namespace MantidQt {
namespace MantidWidgets {

60
61
using namespace boost::math;

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

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

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

  // 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
100
  m_plot = new MiniPlot(this);
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
167
  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);
168
  collapsePlotPanel();
169
170
171

  m_selectionType = Single;

172
173
  m_infoController = nullptr;
  m_plotController = nullptr;
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
220

  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");

221
222
223
224
225
226
  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");

227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
  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)");

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

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

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

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

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

/**
LamarMoore's avatar
LamarMoore committed
320
321
 * Display the miniplot's context menu.
 */
322
void InstrumentWidgetPickTab::plotContextMenu() {
323
  QMenu context(m_plot);
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
399

  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
400
401
 * Update the plot caption. The captions shows the selection type.
 */
402
403
404
405
406
void InstrumentWidgetPickTab::setPlotCaption() {
  m_plotPanel->setCaption(m_plotController->getPlotCaption());
}

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

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

/**
LamarMoore's avatar
LamarMoore committed
425
426
 * Set the selection type according to which tool button is checked.
 */
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
455
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;
456
457
458
459
  } else if (m_peakCompare->isChecked()) {
    m_selectionType = ComparePeak;
    m_activeTool->setText("Tool: Compare crystal peak(s)");
    surfaceMode = ProjectionSurface::ComparePeakMode;
460
461
462
463
  } else if (m_peakAlign->isChecked()) {
    m_selectionType = AlignPeak;
    m_activeTool->setText("Tool: Align crystal peak(s)");
    surfaceMode = ProjectionSurface::AlignPeakMode;
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
491
  } 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));
492
493
494
495
496
497
498
  } 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));
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
529
  } 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
530
531
 * Respond to the show event.
 */
532
void InstrumentWidgetPickTab::showEvent(QShowEvent * /*unused*/) {
533
534
535
536
537
538
539
540
541
  // 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
542
543
 * Keep current curve permanently displayed on the plot.
 */
544
545
546
void InstrumentWidgetPickTab::storeCurve() { m_plot->store(); }

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

/**
LamarMoore's avatar
LamarMoore committed
556
557
558
 * Set the x units for the integrated tube plot.
 * @param units :: The x units in terms of TubeXUnits.
 */
559
560
561
562
563
564
565
566
567
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
568
569
570
 * Get the color of the overlay shapes in this tab.
 * @return
 */
571
572
573
574
575
QColor InstrumentWidgetPickTab::getShapeBorderColor() const {
  return QColor(Qt::green);
}

/**
576
 * Do something when the time bin integration range has changed.
LamarMoore's avatar
LamarMoore committed
577
 */
Tom Titcombe's avatar
Tom Titcombe committed
578
579
void InstrumentWidgetPickTab::changedIntegrationRange(double /*unused*/,
                                                      double /*unused*/) {
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
  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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
  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 *)));
611
612
613
614
615
616
617
618
619
620
621
  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()));
622
  auto *p3d = dynamic_cast<Projection3D *>(surface);
623
624
625
626
  if (p3d) {
    connect(p3d, SIGNAL(finishedMove()), this,
            SLOT(updatePlotMultipleDetectors()));
  }
Antti Soininen's avatar
Antti Soininen committed
627
628
629
  m_infoController =
      new ComponentInfoController(this, m_instrWidget, m_selectionInfoDisplay);
  m_plotController = new DetectorPlotController(this, m_instrWidget, m_plot);
630
631
632
633
  m_plotController->setTubeXUnits(
      static_cast<DetectorPlotController::TubeXUnits>(m_tubeXUnitsCache));
  m_plotController->setPlotType(
      static_cast<DetectorPlotController::PlotType>(m_plotTypeCache));
634
  // miniplot X unit
635
  const auto &actor = m_instrWidget->getInstrumentActor();
636
637
638
  // default X axis label
  m_plot->setXLabel(QString::fromStdString(
      actor.getWorkspace()->getAxis(0)->unit()->unitID()));
639
640
641
}

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

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

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

/**
LamarMoore's avatar
LamarMoore committed
661
662
663
 * Restore (read and apply) tab's persistent settings from the provided
 * QSettings instance
 */
664
665
666
667
668
669
670
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();
}
671
672
673
674
void InstrumentWidgetPickTab::addToContextMenu(
    QAction *action,
    std::function<bool(std::map<std::string, bool>)> &actionCondition) {
  auto pair = std::make_pair(action, actionCondition);
675
  m_addedActions.emplace_back(pair);
676
}
677
/**
LamarMoore's avatar
LamarMoore committed
678
679
680
 * Fill in the context menu.
 * @param context :: A menu to fill.
 */
681
682
683
684
685
686
687
688
689
690
691
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;
  }
692
  std::map<std::string, bool> tabBools = {};
693
  tabBools.insert(std::make_pair("plotStored", m_plot->hasStored()));
694
695
696
697
698
699
700
  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);
    }
  }
701
702
703
704
  return res;
}

/**
LamarMoore's avatar
LamarMoore committed
705
706
707
 * Select a tool on the tab
 * @param tool One of the enumerated tool types, @see ToolType
 */
708
709
710
711
712
713
714
715
716
717
718
719
720
721
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;
722
723
  case PeakCompare:
    m_peakCompare->setChecked(true);
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
755
  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);
756
  m_plotController->zoomOutOnPlot();
757
758
759
  m_plotController->updatePlot();
}

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

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

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

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

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

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

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

826
827
828
829
/** 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) {
830
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
831
  API::TSVSerialiser tsv(lines);
832
833
834
835
836
837

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

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

  // load active push button
  std::vector<QPushButton *> buttons{
LamarMoore's avatar
LamarMoore committed
842
843
844
      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};
845
846
847
848
849
850
851

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

/** 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 {
863
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
864
  API::TSVSerialiser tsv, tab;
865
866
867

  // save active push button
  std::vector<QPushButton *> buttons{
LamarMoore's avatar
LamarMoore committed
868
869
870
      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};
871
872
873
874
875
876
877
878

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

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

885
886
887
//=====================================================================================//

/**
LamarMoore's avatar
LamarMoore committed
888
889
890
891
892
 * 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
893
894
895
ComponentInfoController::ComponentInfoController(
    InstrumentWidgetPickTab *tab, const InstrumentWidget *instrWidget,
    QTextEdit *infoDisplay)
896
    : QObject(tab), m_tab(tab), m_instrWidget(instrWidget),
897
      m_selectionInfoDisplay(infoDisplay), m_freezePlot(false),
898
899
      m_instrWidgetBlocked(false),
      m_currentPickID(std::numeric_limits<size_t>::max()) {}
900
901

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

911
  const auto &actor = m_instrWidget->getInstrumentActor();
912
  const auto &componentInfo = actor.componentInfo();
913
  QString text = "";
914
915
  if (componentInfo.isDetector(pickID)) {
    text += displayDetectorInfo(pickID);
916
  } else if (auto componentID = actor.getComponentID(pickID)) {
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
    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
932
933
934
 * Return string with info on a detector.
 * @param index :: A detector Index.
 */
935
QString ComponentInfoController::displayDetectorInfo(size_t index) {
936
937
938
939
940
941
  if (m_instrWidgetBlocked) {
    clear();
    return "";
  }

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

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

  text = "Selected detector: " +
         QString::fromStdString(componentInfo.name(index)) + "\n";
  text += "Detector ID: " + QString::number(detid) + '\n';
  QString wsIndex;
952
953
  auto ws = actor.getWorkspaceIndex(index);
  wsIndex = ws == InstrumentActor::INVALID_INDEX ? "None" : QString::number(ws);
Lamar Moore's avatar
Lamar Moore committed
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
  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';

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

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