InstrumentWidgetMaskTab.cpp 48.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/InstrumentWidgetMaskTab.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
#include "MantidQtWidgets/InstrumentView/DetXMLFile.h"
#include "MantidQtWidgets/InstrumentView/InstrumentActor.h"
#include "MantidQtWidgets/InstrumentView/InstrumentWidget.h"
#include "MantidQtWidgets/InstrumentView/ProjectionSurface.h"
15
16
17
18
19
20

#include "MantidAPI/AlgorithmManager.h"
#include "MantidAPI/AnalysisDataService.h"
#include "MantidAPI/FrameworkManager.h"
#include "MantidAPI/IMaskWorkspace.h"
#include "MantidAPI/ITableWorkspace.h"
21
#include "MantidAPI/MatrixWorkspace.h"
22
23
24
25
// #include "MantidDataObjects/TableWorkspace.h"
#include "MantidKernel/Logger.h"
#include "MantidKernel/Strings.h"

Roman Tolchenov's avatar
Roman Tolchenov committed
26
#include "MantidQtWidgets/Common/QtPropertyBrowser/qtpropertymanager.h"
LamarMoore's avatar
LamarMoore committed
27
#include "MantidQtWidgets/Common/QtPropertyBrowser/qttreepropertybrowser.h"
28
29
// Suppress a warning coming out of code that isn't ours
#if defined(__INTEL_COMPILER)
30
#pragma warning disable 1125
31
#elif defined(__GNUC__)
32
33
34
35
#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
#pragma GCC diagnostic push
#endif
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
36
#endif
Roman Tolchenov's avatar
Roman Tolchenov committed
37
#include "MantidQtWidgets/Common/QtPropertyBrowser/DoubleEditorFactory.h"
LamarMoore's avatar
LamarMoore committed
38
#include "MantidQtWidgets/Common/QtPropertyBrowser/qteditorfactory.h"
39
#if defined(__INTEL_COMPILER)
40
#pragma warning enable 1125
41
#elif defined(__GNUC__)
42
43
44
#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
#pragma GCC diagnostic pop
#endif
45
46
#endif

Samuel Jones's avatar
Samuel Jones committed
47
#include <Poco/Path.h>
48
49
#include <QAction>
#include <QApplication>
50
51
#include <QCheckBox>
#include <QGridLayout>
52
#include <QGroupBox>
53
54
55
56
57
58
#include <QHBoxLayout>
#include <QLabel>
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
#include <QRadioButton>
59
#include <QSettings>
60
61
62
63
#include <QTemporaryFile>
#include <QTextEdit>
#include <QToolTip>
#include <QVBoxLayout>
64

Roman Tolchenov's avatar
Roman Tolchenov committed
65
#include "MantidQtWidgets/Common/FileDialogHandler.h"
66
67

#include <algorithm>
LamarMoore's avatar
LamarMoore committed
68
#include <cfloat>
69
#include <fstream>
LamarMoore's avatar
LamarMoore committed
70
#include <numeric>
71

72
73
using Mantid::API::AlgorithmManager;

74
75
76
77
78
namespace MantidQt {
namespace MantidWidgets {
InstrumentWidgetMaskTab::InstrumentWidgetMaskTab(InstrumentWidget *instrWidget)
    : InstrumentWidgetTab(instrWidget), m_activity(Select),
      m_hasMaskToApply(false), m_maskBins(false), m_userEditing(true),
Peterson, Peter's avatar
Peterson, Peter committed
79
80
81
      m_groupManager(nullptr), m_stringManager(nullptr),
      m_doubleManager(nullptr), m_browser(nullptr), m_left(nullptr),
      m_top(nullptr), m_right(nullptr), m_bottom(nullptr) {
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

  // main layout
  QVBoxLayout *layout = new QVBoxLayout(this);

  m_activeTool = new QLabel(this);
  layout->addWidget(m_activeTool);

  // Create the tool buttons

  m_move = new QPushButton();
  m_move->setCheckable(true);
  m_move->setAutoExclusive(true);
  m_move->setIcon(QIcon(":/PickTools/zoom.png"));
  m_move->setToolTip("Move the instrument (Ctrl+Alt+M)");
  m_move->setShortcut(QKeySequence("Ctrl+Alt+M"));

  m_pointer = new QPushButton();
  m_pointer->setCheckable(true);
  m_pointer->setAutoExclusive(true);
  m_pointer->setIcon(QIcon(":/MaskTools/selection-edit.png"));
  m_pointer->setToolTip("Select and edit shapes (Ctrl+Alt+P)");
  m_pointer->setShortcut(QKeySequence("Ctrl+Alt+P"));

  m_ellipse = new QPushButton();
  m_ellipse->setCheckable(true);
  m_ellipse->setAutoExclusive(true);
  m_ellipse->setIcon(QIcon(":/MaskTools/selection-circle.png"));
  m_ellipse->setToolTip("Draw an ellipse (Ctrl+Alt+E)");
  m_ellipse->setShortcut(QKeySequence("Ctrl+Alt+E"));

  m_rectangle = new QPushButton();
  m_rectangle->setCheckable(true);
  m_rectangle->setAutoExclusive(true);
  m_rectangle->setIcon(QIcon(":/MaskTools/selection-box.png"));
  m_rectangle->setToolTip("Draw a rectangle (Ctrl+Alt+R)");
  m_rectangle->setShortcut(QKeySequence("Ctrl+Alt+R"));

119
120
121
122
123
124
  m_pixel = new QPushButton();
  m_pixel->setCheckable(true);
  m_pixel->setAutoExclusive(true);
  m_pixel->setIcon(QIcon(":/PickTools/selection-pointer.png"));
  m_pixel->setToolTip("Mask a pixel");		  

125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
  m_ring_ellipse = new QPushButton();
  m_ring_ellipse->setCheckable(true);
  m_ring_ellipse->setAutoExclusive(true);
  m_ring_ellipse->setIcon(QIcon(":/MaskTools/selection-circle-ring.png"));
  m_ring_ellipse->setToolTip("Draw an elliptical ring (Shift+Alt+E)");
  m_ring_ellipse->setShortcut(QKeySequence("Shift+Alt+E"));

  m_ring_rectangle = new QPushButton();
  m_ring_rectangle->setCheckable(true);
  m_ring_rectangle->setAutoExclusive(true);
  m_ring_rectangle->setIcon(QIcon(":/MaskTools/selection-box-ring.png"));
  m_ring_rectangle->setToolTip("Draw a rectangular ring (Shift+Alt+R)");
  m_ring_rectangle->setShortcut(QKeySequence("Shift+Alt+R"));

  m_free_draw = new QPushButton();
  m_free_draw->setCheckable(true);
  m_free_draw->setAutoExclusive(true);
  m_free_draw->setIcon(QIcon(":/MaskTools/brush.png"));
  m_free_draw->setToolTip("Draw an arbitrary shape (Shift+Alt+A)");
  m_free_draw->setShortcut(QKeySequence("Shift+Alt+A"));

146
  auto *toolBox = new QHBoxLayout();
147
148
149
150
151
152
153
  toolBox->addWidget(m_move);
  toolBox->addWidget(m_pointer);
  toolBox->addWidget(m_ellipse);
  toolBox->addWidget(m_rectangle);
  toolBox->addWidget(m_ring_ellipse);
  toolBox->addWidget(m_ring_rectangle);
  toolBox->addWidget(m_free_draw);
154
  toolBox->addWidget(m_pixel);
155
156
157
158
159
160
161
162
163
  toolBox->setMargin(0);

  connect(m_move, SIGNAL(clicked()), this, SLOT(setActivity()));
  connect(m_pointer, SIGNAL(clicked()), this, SLOT(setActivity()));
  connect(m_ellipse, SIGNAL(clicked()), this, SLOT(setActivity()));
  connect(m_rectangle, SIGNAL(clicked()), this, SLOT(setActivity()));
  connect(m_ring_ellipse, SIGNAL(clicked()), this, SLOT(setActivity()));
  connect(m_ring_rectangle, SIGNAL(clicked()), this, SLOT(setActivity()));
  connect(m_free_draw, SIGNAL(clicked()), this, SLOT(setActivity()));
164
  connect(m_pixel, SIGNAL(clicked()), this, SLOT(setActivity()));
165
  m_move->setChecked(true);
166
  auto *toolGroup = new QFrame();
167
168
169
170
171
172
173
174
175
176
177
178
  toolGroup->setLayout(toolBox);

  layout->addWidget(toolGroup);

  // create mask/group switch
  m_masking_on = new QRadioButton("Mask");
  m_grouping_on = new QRadioButton("Group");
  m_roi_on = new QRadioButton("ROI");
  m_masking_on->setChecked(true);
  connect(m_masking_on, SIGNAL(clicked()), this, SLOT(toggleMaskGroup()));
  connect(m_grouping_on, SIGNAL(clicked()), this, SLOT(toggleMaskGroup()));
  connect(m_roi_on, SIGNAL(clicked()), this, SLOT(toggleMaskGroup()));
179
  auto *radioLayout = new QHBoxLayout();
180
181
182
183
  radioLayout->addWidget(m_masking_on);
  radioLayout->addWidget(m_roi_on);
  radioLayout->addWidget(m_grouping_on);
  radioLayout->setMargin(0);
184
  auto *radioGroup = new QGroupBox();
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
  radioGroup->setStyleSheet("border: none;");
  radioGroup->setLayout(radioLayout);

  layout->addWidget(radioGroup);

  // Create property browser

  /* Create property managers: they create, own properties, get and set values
   */

  m_groupManager = new QtGroupPropertyManager(this);
  m_doubleManager = new QtDoublePropertyManager(this);
  connect(m_doubleManager, SIGNAL(propertyChanged(QtProperty *)), this,
          SLOT(doubleChanged(QtProperty *)));

  /* Create editors and assign them to the managers */

  DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory(this);

  m_browser = new QtTreePropertyBrowser();
  m_browser->setFactoryForManager(m_doubleManager, doubleEditorFactory);

  layout->addWidget(m_browser);

  // Algorithm buttons

  m_applyToData = new QPushButton("Apply to Data");
  m_applyToData->setToolTip("Apply current detector and bin masks to the data "
                            "workspace. Cannot be reverted.");
  connect(m_applyToData, SIGNAL(clicked()), this, SLOT(applyMask()));

  m_applyToView = new QPushButton("Apply to View");
  m_applyToView->setToolTip("Apply current mask to the view.");
  connect(m_applyToView, SIGNAL(clicked()), this, SLOT(applyMaskToView()));

220
221
222
223
224
225
  m_saveShapesToTable = new QPushButton("Save Shapes to Table");
  m_saveShapesToTable->setToolTip(
      "Store the current Mask/ROI/Group shapes as a table");
  connect(m_saveShapesToTable, SIGNAL(clicked()), this,
          SLOT(saveShapesToTable()));

226
227
228
229
230
231
232
233
234
  m_clearAll = new QPushButton("Clear All");
  m_clearAll->setToolTip(
      "Clear all masking that have not been applied to the data.");
  connect(m_clearAll, SIGNAL(clicked()), this, SLOT(clearMask()));

  m_save_as_workspace_exclude =
      new QAction("As Detector Mask to workspace", this);
  m_save_as_workspace_exclude->setToolTip(
      "Save current detector mask to mask workspace.");
235
  connect(m_save_as_workspace_exclude, SIGNAL(triggered()), this,
236
237
238
239
240
241
          SLOT(saveMaskToWorkspace()));

  m_save_as_workspace_include =
      new QAction("As Detector ROI to workspace", this);
  m_save_as_workspace_include->setToolTip(
      "Save current detector mask as ROI to mask workspace.");
242
  connect(m_save_as_workspace_include, SIGNAL(triggered()), this,
243
244
245
246
247
          SLOT(saveInvertedMaskToWorkspace()));

  m_save_as_file_exclude = new QAction("As Detector Mask to file", this);
  m_save_as_file_exclude->setToolTip(
      "Save current detector mask to mask file.");
248
  connect(m_save_as_file_exclude, SIGNAL(triggered()), this,
249
250
251
252
          SLOT(saveMaskToFile()));

  m_save_as_file_include = new QAction("As Detector ROI to file", this);
  m_save_as_file_include->setToolTip("Save current mask as ROI to mask file.");
253
  connect(m_save_as_file_include, SIGNAL(triggered()), this,
254
255
256
257
258
259
          SLOT(saveInvertedMaskToFile()));

  m_save_as_cal_file_exclude =
      new QAction("As Detector Mask to cal file", this);
  m_save_as_cal_file_exclude->setToolTip(
      "Save current detector mask to cal file.");
260
  connect(m_save_as_cal_file_exclude, SIGNAL(triggered()), this,
261
262
263
264
265
          SLOT(saveMaskToCalFile()));

  m_save_as_cal_file_include = new QAction("As Detector ROI to cal file", this);
  m_save_as_cal_file_include->setToolTip(
      "Save current detector mask as ROI to cal file.");
266
  connect(m_save_as_cal_file_include, SIGNAL(triggered()), this,
267
268
269
270
271
272
273
274
275
          SLOT(saveInvertedMaskToCalFile()));

  m_save_as_table_xrange_exclude =
      new QAction("As Detector Mask to table", this);
  m_save_as_table_xrange_exclude->setToolTip(
      "Save current detector mask to a table workspace with x-range. "
      "The name of output table workspace is 'MaskBinTable'. "
      "If the output table workspace has alrady exist, then "
      "the newly masked detectors will be added to output workspace.");
276
  connect(m_save_as_table_xrange_exclude, SIGNAL(triggered()), this,
277
278
279
280
281
          SLOT(saveMaskToTable()));

  m_save_group_file_include = new QAction("As include group to file", this);
  m_save_group_file_include->setToolTip(
      "Save current mask as include group to a file.");
282
  connect(m_save_group_file_include, SIGNAL(triggered()), this,
283
284
285
286
287
          SLOT(saveIncludeGroupToFile()));

  m_save_group_file_exclude = new QAction("As exclude group to file", this);
  m_save_group_file_exclude->setToolTip(
      "Save current mask as exclude group to a file.");
288
  connect(m_save_group_file_exclude, SIGNAL(triggered()), this,
289
290
291
292
          SLOT(saveExcludeGroupToFile()));

  m_extract_to_workspace = new QAction("Extract detectors to workspace", this);
  m_extract_to_workspace->setToolTip("Extract detectors to workspace.");
293
  connect(m_extract_to_workspace, SIGNAL(triggered()), this,
294
295
296
297
          SLOT(extractDetsToWorkspace()));

  m_sum_to_workspace = new QAction("Sum detectors to workspace", this);
  m_sum_to_workspace->setToolTip("Sum detectors to workspace.");
298
  connect(m_sum_to_workspace, SIGNAL(triggered()), this,
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
          SLOT(sumDetsToWorkspace()));

  // Save button and its menus
  m_saveButton = new QPushButton("Apply and Save");
  m_saveButton->setToolTip(
      "Save current masking/grouping to a file or a workspace.");

  m_saveMask = new QMenu(this);
  m_saveMask->addAction(m_save_as_workspace_exclude);
  m_saveMask->addAction(m_save_as_file_exclude);
  m_saveMask->addAction(m_save_as_cal_file_exclude);
  m_saveMask->addSeparator();
  m_saveMask->addAction(m_save_as_table_xrange_exclude);
  connect(m_saveMask, SIGNAL(hovered(QAction *)), this,
          SLOT(showSaveMenuTooltip(QAction *)));

  m_saveButton->setMenu(m_saveMask);

  m_saveGroup = new QMenu(this);
  m_saveGroup->addAction(m_extract_to_workspace);
  m_saveGroup->addAction(m_sum_to_workspace);
  m_saveGroup->addSeparator();

  connect(m_saveGroup, SIGNAL(hovered(QAction *)), this,
          SLOT(showSaveMenuTooltip(QAction *)));

  m_saveROI = new QMenu(this);
  m_saveROI->addAction(m_save_as_workspace_include);
  m_saveROI->addAction(m_save_as_file_include);
  m_saveROI->addAction(m_save_as_cal_file_include);
  m_saveROI->addSeparator();
  m_saveROI->addAction(m_extract_to_workspace);
  m_saveROI->addAction(m_sum_to_workspace);

  connect(m_saveROI, SIGNAL(hovered(QAction *)), this,
          SLOT(showSaveMenuTooltip(QAction *)));

336
337
  auto *box = new QGroupBox("View");
  auto *buttons = new QGridLayout();
338
  buttons->addWidget(m_applyToView, 0, 0, 1, 2);
339
340
341
  buttons->addWidget(m_saveShapesToTable, 1, 0, 1, 2);
  buttons->addWidget(m_saveButton, 2, 0);
  buttons->addWidget(m_clearAll, 2, 1);
342
343
344
345
346
347
348
349
350

  box->setLayout(buttons);
  layout->addWidget(box);

  box = new QGroupBox("Workspace");
  buttons = new QGridLayout();
  buttons->addWidget(m_applyToData, 0, 0);
  box->setLayout(buttons);
  layout->addWidget(box);
351
352
353

  connect(m_instrWidget, SIGNAL(maskedWorkspaceOverlayed()), this,
          SLOT(enableApplyButtons()));
354
355
356
}

/**
LamarMoore's avatar
LamarMoore committed
357
358
 * Initialize the tab when new projection surface is created.
 */
359
void InstrumentWidgetMaskTab::initSurface() {
360
  connect(m_instrWidget->getSurface().get(), SIGNAL(singleComponentPicked(size_t)), this,
361
          SLOT(singlePixelPicked(size_t)));
362
363
364
365
366
367
368
369
370
371
372
373
374
375
  connect(m_instrWidget->getSurface().get(), SIGNAL(shapeCreated()), this,
          SLOT(shapeCreated()));
  connect(m_instrWidget->getSurface().get(), SIGNAL(shapeSelected()), this,
          SLOT(shapeSelected()));
  connect(m_instrWidget->getSurface().get(), SIGNAL(shapesDeselected()), this,
          SLOT(shapesDeselected()));
  connect(m_instrWidget->getSurface().get(), SIGNAL(shapeChanged()), this,
          SLOT(shapeChanged()));
  connect(m_instrWidget->getSurface().get(), SIGNAL(shapesCleared()), this,
          SLOT(shapesCleared()));
  enableApplyButtons();
}

/**
LamarMoore's avatar
LamarMoore committed
376
377
378
 * Selects between masking/grouping
 * @param mode The required mode, @see Mode
 */
379
380
381
void InstrumentWidgetMaskTab::setMode(Mode mode) {
  switch (mode) {
  case Mask:
382
    m_masking_on->setChecked(true);
383
384
    break;
  case Group:
385
    m_grouping_on->setChecked(true);
386
387
    break;
  case ROI:
388
    m_roi_on->setChecked(true);
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
    break;
  default:
    throw std::invalid_argument("Invalid Mask tab mode. Use Mask/Group.");
  };
  toggleMaskGroup();
}

void InstrumentWidgetMaskTab::selectTool(Activity tool) {
  switch (tool) {
  case Move:
    m_move->setChecked(true);
    break;
  case Select:
    m_pointer->setChecked(true);
    break;
  case DrawEllipse:
    m_ellipse->setChecked(true);
    break;
  case DrawRectangle:
    m_rectangle->setChecked(true);
    break;
  case DrawEllipticalRing:
    m_ring_ellipse->setChecked(true);
    break;
  case DrawRectangularRing:
    m_ring_rectangle->setChecked(true);
    break;
  case DrawFree:
    m_free_draw->setChecked(true);
    break;
419
420
421
  case Pixel:
    m_pixel->setChecked(true);
    break;
422
423
424
425
426
427
428
  default:
    throw std::invalid_argument("Invalid tool type.");
  }
  setActivity();
}

/**
LamarMoore's avatar
LamarMoore committed
429
430
 * Set tab's activity based on the currently selected tool button.
 */
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
void InstrumentWidgetMaskTab::setActivity() {
  const QColor borderColor = getShapeBorderColor();
  const QColor fillColor = getShapeFillColor();
  QString whatIsBeingSelected = m_maskBins && getMode() == Mode::Mask
                                    ? "Selecting bins"
                                    : "Selecting detectors";
  if (m_move->isChecked()) {
    m_activity = Move;
    m_instrWidget->getSurface()->setInteractionMode(
        ProjectionSurface::MoveMode);
    m_activeTool->setText("Tool: Navigation");
  } else if (m_pointer->isChecked()) {
    m_activity = Select;
    m_instrWidget->getSurface()->setInteractionMode(
        ProjectionSurface::DrawRegularMode);
    m_activeTool->setText("Tool: Shape editing. " + whatIsBeingSelected);
  } else if (m_ellipse->isChecked()) {
    m_activity = DrawEllipse;
    m_instrWidget->getSurface()->startCreatingShape2D("ellipse", borderColor,
                                                      fillColor);
    m_instrWidget->getSurface()->setInteractionMode(
        ProjectionSurface::DrawRegularMode);
    m_activeTool->setText("Tool: Ellipse. " + whatIsBeingSelected);
  } else if (m_rectangle->isChecked()) {
    m_activity = DrawRectangle;
    m_instrWidget->getSurface()->startCreatingShape2D("rectangle", borderColor,
                                                      fillColor);
    m_instrWidget->getSurface()->setInteractionMode(
        ProjectionSurface::DrawRegularMode);
    m_activeTool->setText("Tool: Rectangle. " + whatIsBeingSelected);
  } else if (m_ring_ellipse->isChecked()) {
    m_activity = DrawEllipticalRing;
    m_instrWidget->getSurface()->startCreatingShape2D("ring ellipse",
                                                      borderColor, fillColor);
    m_instrWidget->getSurface()->setInteractionMode(
        ProjectionSurface::DrawRegularMode);
    m_activeTool->setText("Tool: Elliptical ring. " + whatIsBeingSelected);
  } else if (m_ring_rectangle->isChecked()) {
    m_activity = DrawRectangularRing;
    m_instrWidget->getSurface()->startCreatingShape2D("ring rectangle",
                                                      borderColor, fillColor);
    m_instrWidget->getSurface()->setInteractionMode(
        ProjectionSurface::DrawRegularMode);
    m_activeTool->setText("Tool: Rectangular ring. " + whatIsBeingSelected);
  } else if (m_free_draw->isChecked()) {
    m_activity = DrawFree;
    m_instrWidget->getSurface()->startCreatingFreeShape(borderColor, fillColor);
    m_instrWidget->getSurface()->setInteractionMode(
        ProjectionSurface::DrawFreeMode);
    m_activeTool->setText("Tool: Free draw. " + whatIsBeingSelected);
481
482
   } else if (m_pixel->isChecked()) {
    m_activity = Pixel;
483
484
    m_instrWidget->getSurface()->setInteractionMode(
        ProjectionSurface::PickSingleMode);
485
486
    m_activeTool->setText("Tool: Pixel selection. " + whatIsBeingSelected);
   }
487
488
489
  m_instrWidget->updateInfoText();
}

490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/**
 * Slot responding on the pick of a single detector pixel for masking.
 */
void InstrumentWidgetMaskTab::singlePixelPicked(size_t pickID){
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    std::vector<long unsigned int> detectorId{static_cast<long unsigned int>(pickID)};
    auto &actor = m_instrWidget->getInstrumentActor();
    actor.addMaskBinsData(detectorId);
    m_instrWidget->updateInstrumentView(); // to refresh the pick image

    auto wsMask = actor.getMaskWorkspace();
    Mantid::detid_t detId = actor.getDetID(pickID);

    // try to mask the detector, ignore any failure
    try {
      wsMask->setMasked(detId);
    } catch (...) {
    }
    // update detector colours
    m_instrWidget->getInstrumentActor().updateColors();
    m_instrWidget->updateInstrumentDetectors();
    QApplication::restoreOverrideCursor();
    enableApplyButtons();
}

515
/**
LamarMoore's avatar
LamarMoore committed
516
517
 * Slot responding on creation of a new masking shape.
 */
518
519
520
521
522
523
524
525
526
527
void InstrumentWidgetMaskTab::shapeCreated() {
  if (!isVisible())
    return;
  if (m_activity != DrawFree) {
    setSelectActivity();
  }
  enableApplyButtons();
}

/**
LamarMoore's avatar
LamarMoore committed
528
529
 * Slot responding on selection of a new masking shape.
 */
530
531
532
void InstrumentWidgetMaskTab::shapeSelected() { setProperties(); }

/**
LamarMoore's avatar
LamarMoore committed
533
534
 * Slot responding on deselecting all masking shapes.
 */
535
536
537
void InstrumentWidgetMaskTab::shapesDeselected() { clearProperties(); }

/**
LamarMoore's avatar
LamarMoore committed
538
539
 * Slot responding on a change of a masking shape.
 */
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
void InstrumentWidgetMaskTab::shapeChanged() {
  if (!m_left)
    return; // check that everything is ok
  m_userEditing =
      false; // this prevents resetting shape properties by doubleChanged(...)
  RectF rect = m_instrWidget->getSurface()->getCurrentBoundingRect();
  m_doubleManager->setValue(m_left, rect.x0());
  m_doubleManager->setValue(m_top, rect.y1());
  m_doubleManager->setValue(m_right, rect.x1());
  m_doubleManager->setValue(m_bottom, rect.y0());
  for (QMap<QtProperty *, QString>::iterator it = m_doublePropertyMap.begin();
       it != m_doublePropertyMap.end(); ++it) {
    m_doubleManager->setValue(
        it.key(), m_instrWidget->getSurface()->getCurrentDouble(it.value()));
  }
  for (QMap<QString, QtProperty *>::iterator it = m_pointPropertyMap.begin();
       it != m_pointPropertyMap.end(); ++it) {
    QtProperty *prop = it.value();
    QList<QtProperty *> subs = prop->subProperties();
    if (subs.size() != 2)
      continue;
    QPointF p = m_instrWidget->getSurface()->getCurrentPoint(it.key());
    m_doubleManager->setValue(subs[0], p.x());
    m_doubleManager->setValue(subs[1], p.y());
  }
  m_userEditing = true;
}

/**
LamarMoore's avatar
LamarMoore committed
569
570
 * Slot responding on removing all masking shapes.
 */
571
572
573
void InstrumentWidgetMaskTab::shapesCleared() { enableApplyButtons(); }

/**
LamarMoore's avatar
LamarMoore committed
574
575
 * Removes the mask shapes from the screen.
 */
576
577
578
579
580
void InstrumentWidgetMaskTab::clearShapes() {
  m_instrWidget->getSurface()->clearMask();
  setSelectActivity();
}

581
void InstrumentWidgetMaskTab::showEvent(QShowEvent * /*unused*/) {
582
583
584
585
586
587
588
589
590
591
592
593
  setActivity();
  m_instrWidget->setMouseTracking(true);
  enableApplyButtons();
  m_instrWidget->updateInstrumentView(true);
  m_instrWidget->getSurface()->changeBorderColor(getShapeBorderColor());
}

void InstrumentWidgetMaskTab::clearProperties() {
  m_browser->clear();
  m_doublePropertyMap.clear();
  m_pointPropertyMap.clear();
  m_pointComponentsMap.clear();
594
595
596
597
  m_left = nullptr;
  m_top = nullptr;
  m_right = nullptr;
  m_bottom = nullptr;
598
599
600
601
602
603
604
}

void InstrumentWidgetMaskTab::setProperties() {
  clearProperties();
  m_userEditing = false;

  // bounding rect property
605
  QtProperty *boundingRectGroup = m_groupManager->addProperty("Bounding Rect");
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
  m_browser->addProperty(boundingRectGroup);
  m_left = addDoubleProperty("left");
  m_top = addDoubleProperty("top");
  m_right = addDoubleProperty("right");
  m_bottom = addDoubleProperty("bottom");
  boundingRectGroup->addSubProperty(m_left);
  boundingRectGroup->addSubProperty(m_top);
  boundingRectGroup->addSubProperty(m_right);
  boundingRectGroup->addSubProperty(m_bottom);

  // point properties
  QStringList pointProperties =
      m_instrWidget->getSurface()->getCurrentPointNames();
  foreach (QString name, pointProperties) {
    QtProperty *point = m_groupManager->addProperty(name);
    QtProperty *prop_x = addDoubleProperty("x");
    QtProperty *prop_y = addDoubleProperty("y");
    point->addSubProperty(prop_x);
    point->addSubProperty(prop_y);
    m_browser->addProperty(point);
    m_pointComponentsMap[prop_x] = name;
    m_pointComponentsMap[prop_y] = name;
    m_pointPropertyMap[name] = point;
  }

  // double properties
  QStringList doubleProperties =
      m_instrWidget->getSurface()->getCurrentDoubleNames();
  foreach (QString name, doubleProperties) {
    QtProperty *prop = addDoubleProperty(name);
    m_browser->addProperty(prop);
    m_doublePropertyMap[prop] = name;
  }

  shapeChanged();
}

643
644
645
646
647
648
649
/**
 * Save shapes to a table workspace
 */
void InstrumentWidgetMaskTab::saveShapesToTable() const {
  m_instrWidget->getSurface()->saveShapesToTableWorkspace();
}

650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
void InstrumentWidgetMaskTab::doubleChanged(QtProperty *prop) {
  if (!m_userEditing)
    return;
  if (prop == m_left || prop == m_top || prop == m_right || prop == m_bottom) {
    QRectF rect(
        QPointF(m_doubleManager->value(m_left), m_doubleManager->value(m_top)),
        QPointF(m_doubleManager->value(m_right),
                m_doubleManager->value(m_bottom)));
    m_instrWidget->getSurface()->setCurrentBoundingRect(RectF(rect));
  } else {
    QString name = m_doublePropertyMap[prop];
    if (!name.isEmpty()) {
      m_instrWidget->getSurface()->setCurrentDouble(
          name, m_doubleManager->value(prop));
    } else {
      name = m_pointComponentsMap[prop];
      if (!name.isEmpty()) {
        QtProperty *point_prop = m_pointPropertyMap[name];
        QList<QtProperty *> subs = point_prop->subProperties();
        if (subs.size() != 2)
          return;
        QPointF p(m_doubleManager->value(subs[0]),
                  m_doubleManager->value(subs[1]));
        m_instrWidget->getSurface()->setCurrentPoint(name, p);
      }
    }
  }
  m_instrWidget->update();
}

/**
LamarMoore's avatar
LamarMoore committed
681
682
683
 * Apply the constructed mask to the data workspace. This operation cannot be
 * reverted.
 */
684
685
686
void InstrumentWidgetMaskTab::applyMask() {
  storeMask();
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
687
  m_instrWidget->getInstrumentActor().applyMaskWorkspace();
688
689
690
691
692
  enableApplyButtons();
  QApplication::restoreOverrideCursor();
}

/**
LamarMoore's avatar
LamarMoore committed
693
694
 * Apply the constructed mask to the view only.
 */
695
696
697
698
699
700
void InstrumentWidgetMaskTab::applyMaskToView() {
  storeMask();
  enableApplyButtons();
}

/**
LamarMoore's avatar
LamarMoore committed
701
702
 * Remove all masking that has not been applied to the data workspace.
 */
703
704
void InstrumentWidgetMaskTab::clearMask() {
  clearShapes();
705
  m_instrWidget->getInstrumentActor().clearMasks();
706
707
708
709
710
  m_instrWidget->updateInstrumentView();
  enableApplyButtons();
}

/**
LamarMoore's avatar
LamarMoore committed
711
712
713
714
715
716
 * Create a MaskWorkspace from the mask defined in this tab.
 * @param invertMask ::  if true, the selected mask will be inverted; if false,
 * the mask will be used as is
 * @param temp :: Set true to create a temporary workspace with a fixed name. If
 * false the name will be unique.
 */
717
Mantid::API::MatrixWorkspace_sptr
718
InstrumentWidgetMaskTab::createMaskWorkspace(bool invertMask, bool temp) const {
719
720
  m_instrWidget->updateInstrumentView(); // to refresh the pick image
  Mantid::API::MatrixWorkspace_sptr inputWS =
721
      m_instrWidget->getInstrumentActor().getMaskMatrixWorkspace();
722
723
724
  Mantid::API::MatrixWorkspace_sptr outputWS;
  const std::string outputWorkspaceName = generateMaskWorkspaceName(temp);

725
  auto alg = AlgorithmManager::Instance().create("ExtractMask", -1);
726
727
728
729
730
731
732
733
734
  alg->setProperty("InputWorkspace", inputWS);
  alg->setPropertyValue("OutputWorkspace", outputWorkspaceName);
  alg->execute();

  outputWS = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
      Mantid::API::AnalysisDataService::Instance().retrieve(
          outputWorkspaceName));

  if (invertMask) {
Nick Draper's avatar
Nick Draper committed
735
736
    auto invertAlg =
        AlgorithmManager::Instance().create("BinaryOperateMasks", -1);
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
    invertAlg->setPropertyValue("InputWorkspace1", outputWorkspaceName);
    invertAlg->setPropertyValue("OutputWorkspace", outputWorkspaceName);
    invertAlg->setPropertyValue("OperationType", "NOT");
    invertAlg->execute();

    outputWS->setTitle("InvertedMaskWorkspace");
  } else {
    outputWS->setTitle("MaskWorkspace");
  }

  return outputWS;
}

void InstrumentWidgetMaskTab::saveInvertedMaskToWorkspace() {
  saveMaskingToWorkspace(true);
}

void InstrumentWidgetMaskTab::saveMaskToWorkspace() {
  saveMaskingToWorkspace(false);
}

void InstrumentWidgetMaskTab::saveInvertedMaskToFile() {
  saveMaskingToFile(true);
}

void InstrumentWidgetMaskTab::saveMaskToFile() { saveMaskingToFile(false); }

void InstrumentWidgetMaskTab::saveMaskToCalFile() {
  saveMaskingToCalFile(false);
}

void InstrumentWidgetMaskTab::saveInvertedMaskToCalFile() {
  saveMaskingToCalFile(true);
}

void InstrumentWidgetMaskTab::saveMaskToTable() {
  saveMaskingToTableWorkspace(false);
}

/**
LamarMoore's avatar
LamarMoore committed
777
778
 * Extract selected detectors to a new workspace
 */
779
780
void InstrumentWidgetMaskTab::extractDetsToWorkspace() {
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
781
  std::vector<size_t> dets;
782
  m_instrWidget->getSurface()->getMaskedDetectors(dets);
783
784
  const auto &actor = m_instrWidget->getInstrumentActor();
  DetXMLFile mapFile(actor.getDetIDs(dets));
785
786
787
  std::string fname = mapFile();
  if (!fname.empty()) {
    std::string workspaceName = m_instrWidget->getWorkspaceName().toStdString();
Nick Draper's avatar
Nick Draper committed
788
    auto alg = AlgorithmManager::Instance().create("GroupDetectors");
789
790
791
792
793
794
795
796
797
    alg->setPropertyValue("InputWorkspace", workspaceName);
    alg->setPropertyValue("MapFile", fname);
    alg->setPropertyValue("OutputWorkspace", workspaceName + "_selection");
    alg->execute();
  }
  QApplication::restoreOverrideCursor();
}

/**
LamarMoore's avatar
LamarMoore committed
798
799
 * Sum selected detectors to a new workspace
 */
800
801
void InstrumentWidgetMaskTab::sumDetsToWorkspace() {
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
802
  std::vector<size_t> dets;
803
  m_instrWidget->getSurface()->getMaskedDetectors(dets);
804
805
  DetXMLFile mapFile(m_instrWidget->getInstrumentActor().getDetIDs(dets),
                     DetXMLFile::Sum);
806
807
808
809
  std::string fname = mapFile();

  if (!fname.empty()) {
    std::string workspaceName = m_instrWidget->getWorkspaceName().toStdString();
Nick Draper's avatar
Nick Draper committed
810
    auto alg = AlgorithmManager::Instance().create("GroupDetectors");
811
812
813
814
815
816
817
818
819
    alg->setPropertyValue("InputWorkspace", workspaceName);
    alg->setPropertyValue("MapFile", fname);
    alg->setPropertyValue("OutputWorkspace", workspaceName + "_sum");
    alg->execute();
  }
  QApplication::restoreOverrideCursor();
}

void InstrumentWidgetMaskTab::saveIncludeGroupToFile() {
Ian Bush's avatar
Ian Bush committed
820
821
  QString fname = m_instrWidget->getSaveFileName("Save grouping file",
                                                 "XML files (*.xml);;All (*)");
822
  if (!fname.isEmpty()) {
823
    std::vector<size_t> dets;
824
    m_instrWidget->getSurface()->getMaskedDetectors(dets);
825
826
    DetXMLFile mapFile(m_instrWidget->getInstrumentActor().getDetIDs(dets),
                       DetXMLFile::Sum, fname);
827
828
829
830
  }
}

void InstrumentWidgetMaskTab::saveExcludeGroupToFile() {
Ian Bush's avatar
Ian Bush committed
831
832
  QString fname = m_instrWidget->getSaveFileName("Save grouping file",
                                                 "XML files (*.xml);;All (*)");
833
  if (!fname.isEmpty()) {
834
    std::vector<size_t> dets;
835
    m_instrWidget->getSurface()->getMaskedDetectors(dets);
836
837
    const auto &actor = m_instrWidget->getInstrumentActor();
    DetXMLFile mapFile(actor.getAllDetIDs(), actor.getDetIDs(dets), fname);
838
839
840
841
842
843
844
845
  }
}

void InstrumentWidgetMaskTab::showSaveMenuTooltip(QAction *action) {
  QToolTip::showText(QCursor::pos(), action->toolTip(), this);
}

/**
LamarMoore's avatar
LamarMoore committed
846
847
848
 * Toggle between different modes
 *
 */
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
void InstrumentWidgetMaskTab::toggleMaskGroup() {
  Mode mode = getMode();

  enableApplyButtons();
  if (mode == Mode::Mask) {
    m_saveButton->setMenu(m_saveMask);
    m_saveButton->setText("Apply and Save");
  } else if (mode == Mode::ROI) {
    m_saveButton->setMenu(m_saveROI);
    m_saveButton->setText("Apply and Save");
  } else {
    m_saveButton->setMenu(m_saveGroup);
    m_saveButton->setText("Save");
  }
  m_instrWidget->getSurface()->changeBorderColor(getShapeBorderColor());
  m_instrWidget->updateInstrumentView();
}

/**
LamarMoore's avatar
LamarMoore committed
868
869
870
871
872
873
 * Save the constructed mask to a workspace with unique name of type
 * "MaskWorkspace_#".
 * The mask is not applied to the data workspace being displayed.
 * @param invertMask ::  if true, the selected mask will be inverted; if false,
 * the mask will be used as is
 */
874
875
876
877
878
879
void InstrumentWidgetMaskTab::saveMaskingToWorkspace(bool invertMask) {
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  // Make sure we have stored the Mask in the helper MaskWorkspace
  storeDetectorMask(invertMask);
  setSelectActivity();
  createMaskWorkspace(false, false);
880
881
882
883
884
885
886
887
888

#if 0
			// TESTCASE
			double minbinvalue = m_instrWidget->getInstrumentActor()->minBinValue();
			double maxbinvalue = m_instrWidget->getInstrumentActor()->maxBinValue();
			std::cout << "Range of X: " << minbinvalue << ", " << maxbinvalue << ".\n";

#endif

889
890
891
892
893
  enableApplyButtons();
  QApplication::restoreOverrideCursor();
}

/**
LamarMoore's avatar
LamarMoore committed
894
895
896
897
898
 * Save the constructed mask to a file.
 * The mask is not applied to the data workspace being displayed.
 * @param invertMask ::  if true, the selected mask will be inverted; if false,
 * the mask will be used as is
 */
899
900
901
902
903
904
905
906
907
908
909
910
911
void InstrumentWidgetMaskTab::saveMaskingToFile(bool invertMask) {
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  // Make sure we have stored the Mask in the helper MaskWorkspace
  storeDetectorMask(invertMask);
  setSelectActivity();
  Mantid::API::MatrixWorkspace_sptr outputWS = createMaskWorkspace(false, true);
  if (outputWS) {
    clearShapes();

    QApplication::restoreOverrideCursor();
    QString fileName = m_instrWidget->getSaveFileName(
        "Select location and name for the mask file",
912
        "XML files (*.xml);;All (*)");
913
914
915
916
917
918
919
920
921
922
923
924
925
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

    if (!fileName.isEmpty()) {

      // Call "SaveMask()"
      Mantid::API::IAlgorithm_sptr alg =
          Mantid::API::AlgorithmManager::Instance().create("SaveMask", -1);
      alg->setProperty(
          "InputWorkspace",
          boost::dynamic_pointer_cast<Mantid::API::Workspace>(outputWS));
      alg->setPropertyValue("OutputFile", fileName.toStdString());
      alg->execute();
    }
926
    Mantid::API::AnalysisDataService::Instance().remove(outputWS->getName());
927
928
929
930
931
932
  }
  enableApplyButtons();
  QApplication::restoreOverrideCursor();
}

/**
LamarMoore's avatar
LamarMoore committed
933
934
935
936
937
 * Save the constructed mask to a cal file.
 * The mask is not applied to the data workspace being displayed.
 * @param invertMask ::  if true, the selected mask will be inverted; if false,
 * the mask will be used as is
 */
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
void InstrumentWidgetMaskTab::saveMaskingToCalFile(bool invertMask) {
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  // Make sure we have stored the Mask in the helper MaskWorkspace
  storeDetectorMask(invertMask);

  setSelectActivity();
  Mantid::API::MatrixWorkspace_sptr outputWS = createMaskWorkspace(false, true);
  if (outputWS) {
    clearShapes();
    QString fileName = m_instrWidget->getSaveFileName(
        "Select location and name for the mask file", "cal files (*.cal)");
    if (!fileName.isEmpty()) {
      Mantid::API::IAlgorithm_sptr alg =
          Mantid::API::AlgorithmManager::Instance().create(
              "MaskWorkspaceToCalFile", -1);
954
      alg->setPropertyValue("InputWorkspace", outputWS->getName());
955
956
957
958
      alg->setPropertyValue("OutputFile", fileName.toStdString());
      alg->setProperty("Invert", false);
      alg->execute();
    }
959
    Mantid::API::AnalysisDataService::Instance().remove(outputWS->getName());
960
961
962
963
964
965
  }
  enableApplyButtons();
  QApplication::restoreOverrideCursor();
}

/**
LamarMoore's avatar
LamarMoore committed
966
967
968
969
 * Apply and save the mask to a TableWorkspace with X-range
 * @param invertMask :: if true, the selected mask will be inverted; if false,
 * the mask will be used as is
 */
970
971
972
973
974
975
976
977
978
979
980
981
void InstrumentWidgetMaskTab::saveMaskingToTableWorkspace(bool invertMask) {
  UNUSED_ARG(invertMask);

  // Set override cursor
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  // Make sure that we have stored the mask in the helper Mask workspace
  storeDetectorMask();
  setSelectActivity();

  // Apply the view (no workspace) to a buffered mask workspace
  Mantid::API::MatrixWorkspace_sptr inputWS =
982
      m_instrWidget->getInstrumentActor().getMaskMatrixWorkspace();
983
984

  // Extract from MaskWorkspace to a TableWorkspace
985
986
  double xmin = m_instrWidget->getInstrumentActor().minBinValue();
  double xmax = m_instrWidget->getInstrumentActor().maxBinValue();
987
988
989
990
991
992
993
994
995
996
997
998
  // std::cout << "[DB] Selected x-range: " << xmin << ", " << xmax << ".\n";

  // Always use the same name
  const std::string outputWorkspaceName("MaskBinTable");

  // Check whether it is going to add a line in an existing workspace
  Mantid::API::ITableWorkspace_sptr temptablews;
  bool overwrite = false;
  try {
    temptablews = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
        Mantid::API::AnalysisDataService::Instance().retrieve(
            outputWorkspaceName));
999
  } catch (const Mantid::Kernel::Exception::NotFoundError &) {
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
    std::cout << "TableWorkspace " << outputWorkspaceName
              << " cannot be found in ADS."
              << ".\n";
  }

  if (temptablews)
    overwrite = true;

  std::cout << "[DB] MaskTableWorkspace is found? = " << overwrite << ". "
            << ".\n";

Nick Draper's avatar
Nick Draper committed
1011
  auto alg = AlgorithmManager::Instance().create("ExtractMaskToTable", -1);
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
  alg->setProperty("InputWorkspace", inputWS);
  if (overwrite)
    alg->setPropertyValue("MaskTableWorkspace", outputWorkspaceName);
  alg->setPropertyValue("OutputWorkspace", outputWorkspaceName);
  alg->setProperty("Xmin", xmin);
  alg->setProperty("Xmax", xmax);
  alg->execute();

  // Restore the previous state
  enableApplyButtons();
  QApplication::restoreOverrideCursor();

  if (alg->isExecuted()) {
    // Mantid::API::MatrixWorkspace_sptr outputWS
    Mantid::API::ITableWorkspace_sptr outputWS =
        boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
            Mantid::API::AnalysisDataService::Instance().retrieve(
                outputWorkspaceName));

    outputWS->setTitle("MaskBinTable");
  } else {
    QMessageBox::critical(this, "MantidPlot - Error",
                          "Algorithm ExtractMaskToTable fails to execute. ");
  }
}

/**
LamarMoore's avatar
LamarMoore committed
1039
1040
1041
 * Generate a unique name for the mask worspace which will be saved in the ADS.
 * It will have a form MaskWorkspace[_#]
 */
1042
1043
1044
1045
1046
1047
1048
std::string
InstrumentWidgetMaskTab::generateMaskWorkspaceName(bool temp) const {
  if (temp)
    return "__MaskTab_MaskWorkspace";
  auto wsNames = Mantid::API::AnalysisDataService::Instance().getObjectNames();
  int maxIndex = 0;
  const std::string baseName = "MaskWorkspace";
Tom Titcombe's avatar
Tom Titcombe committed
1049
  for (auto &wsName : wsNames) {
1050
1051
    if (wsName.find(baseName) == 0) {
      int index = Mantid::Kernel::Strings::endsWithInt(wsName);
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
      if (index > 0 && index > maxIndex)
        maxIndex = index;
      else
        maxIndex = 1;
    }
  }
  if (maxIndex > 0) {
    return baseName + "_" + Mantid::Kernel::Strings::toString(maxIndex + 1);
  }
  return baseName;
}

/**
LamarMoore's avatar
LamarMoore committed
1065
1066
1067
 * Sets the m_hasMaskToApply flag and
 * enables/disables the apply and clear buttons.
 */
1068
void InstrumentWidgetMaskTab::enableApplyButtons() {
1069
  const auto &instrActor = m_instrWidget->getInstrumentActor();
1070
1071
  auto mode = getMode();

1072
  m_maskBins = !instrActor.wholeRange();
1073
  bool hasMaskShapes = m_instrWidget->getSurface()->hasMasks();
1074
1075
  bool hasMaskWorkspace = instrActor.hasMaskWorkspace();
  bool hasBinMask = instrActor.hasBinMask();
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
  bool hasDetectorMask = hasMaskShapes || hasMaskWorkspace;
  bool hasMask = hasDetectorMask || hasBinMask;

  bool enableBinMasking = hasMaskShapes && m_maskBins && mode == Mode::Mask;

  if (m_maskBins && mode == Mode::Mask) {
    m_applyToView->setText("Apply bin mask to View");
  } else {
    m_applyToView->setText("Apply detector mask to View");
  }

  if ((mode == Mode::Mask) || (mode == Mode::ROI)) {
    m_hasMaskToApply = hasMask;
    m_applyToData->setEnabled(hasMask);
    m_applyToView->setEnabled(hasMaskShapes);
  } else {
    m_applyToData->setEnabled(false);
    m_applyToView->setEnabled(false);
  }
1095
  m_saveShapesToTable->setEnabled(hasMaskShapes);
1096
1097
1098
1099
1100
1101
  m_saveButton->setEnabled(hasDetectorMask && (!enableBinMasking));
  m_clearAll->setEnabled(hasMask);
  setActivity();
}

/**
LamarMoore's avatar
LamarMoore committed
1102
1103
 * Sets tab activity to Select: select and modify shapes.
 */
1104
1105
1106
1107
1108
1109
void InstrumentWidgetMaskTab::setSelectActivity() {
  m_pointer->setChecked(true);
  setActivity();
}

/**
LamarMoore's avatar
LamarMoore committed
1110
1111
 * It tab in masking, ROI or grouping mode?
 */
1112
InstrumentWidgetMaskTab::Mode InstrumentWidgetMaskTab::getMode() const {
1113
  if (m_masking_on->isChecked())
1114
    return Mode::Mask;
1115
  if (m_roi_on->isChecked())
1116
    return Mode::ROI;
1117
  if (m_grouping_on->isChecked())
1118
1119
1120
1121
1122
1123
    return Mode::Group;

  throw std::logic_error("Invalid mode");
}

/**
LamarMoore's avatar
LamarMoore committed
1124
1125
 * Border color.
 */
1126
1127
1128
1129
1130
1131
1132
1133
1134
QColor InstrumentWidgetMaskTab::getShapeBorderColor() const {
  if (getMode() == Mode::Mask)
    return Qt::red;
  if (getMode() == Mode::ROI)
    return Qt::yellow;
  return Qt::blue;
}

/**
LamarMoore's avatar
LamarMoore committed
1135
1136
 * Shape fill color.
 */
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
QColor InstrumentWidgetMaskTab::getShapeFillColor() const {
  return QColor(255, 255, 255, 100);
}

QtProperty *
InstrumentWidgetMaskTab::addDoubleProperty(const QString &name) const {
  QtProperty *prop = m_doubleManager->addProperty(name);
  m_doubleManager->setDecimals(prop, 6);
  return prop;
}

/**
LamarMoore's avatar
LamarMoore committed
1149
1150
 * Store the mask defined by the shape tools to the helper m_maskWorkspace.
 */
1151
1152
1153
1154
1155
1156
1157
void InstrumentWidgetMaskTab::storeDetectorMask(bool isROI) {
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  m_pointer->setChecked(true);
  setActivity();
  m_instrWidget->updateInstrumentView(); // to refresh the pick image
  Mantid::API::IMaskWorkspace_sptr wsFresh;

1158
1159
  const auto &actor = m_instrWidget->getInstrumentActor();
  std::vector<size_t> dets;
1160
1161
  // get detectors covered by the shapes
  m_instrWidget->getSurface()->getMaskedDetectors(dets);
1162
1163
  if (!dets.empty()) {
    auto wsMask = actor.getMaskWorkspace();
1164
1165
1166
1167
1168
1169
1170
1171
    // have to cast up to the MaskWorkspace to get access to clone()

    std::set<Mantid::detid_t> detList;
    if (isROI) {
      // need to invert the mask before adding the new shape
      // but not if the mask is fresh and empty
      if (wsMask->getNumberMasked() > 0) {
        wsFresh = boost::dynamic_pointer_cast<Mantid::API::IMaskWorkspace>(
1172
1173
            actor.extractCurrentMask());
        actor.invertMaskWorkspace();
1174
1175
      }
    }
Lamar Moore's avatar
Lamar Moore committed
1176
    for (auto det : dets)
1177
      detList.insert(actor.getDetID(det));
1178
1179
1180

    if (!detList.empty()) {
      // try to mask each detector separately and ignore any failure
Lamar Moore's avatar
Lamar Moore committed
1181
      for (auto det : detList) {
1182
1183
        try {
          if (isROI && wsFresh) {
1184
1185
            if (wsMask->isMasked(det))
              wsFresh->setMasked(det);
1186
          } else {
1187
            wsMask->setMasked(det);
1188
1189
1190
1191
1192
1193
          }
        } catch (...) {
        }
      }
      if (isROI) {
        if (wsFresh)
1194
          m_instrWidget->getInstrumentActor().setMaskMatrixWorkspace(
1195
1196
1197
              boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
                  wsFresh));
        // need to invert the mask before displaying
1198
        m_instrWidget->getInstrumentActor().invertMaskWorkspace();
1199
1200
      }
      // update detector colours
1201
      m_instrWidget->getInstrumentActor().updateColors();
1202
1203
1204
1205
1206
1207
1208
1209
1210
      m_instrWidget->updateInstrumentDetectors();
    }
  }
  // remove masking shapes
  clearShapes();
  QApplication::restoreOverrideCursor();
}

void InstrumentWidgetMaskTab::storeBinMask() {
1211
  std::vector<size_t> dets;
1212
1213
1214
  // get detectors covered by the shapes
  m_instrWidget->getSurface()->getMaskedDetectors(dets);
  // mask some bins
1215
  m_instrWidget->getInstrumentActor().addMaskBinsData(dets);
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
  // remove masking shapes
  clearShapes();
  enableApplyButtons();
}

/// Store current shapes as a mask (detector or bin)
void InstrumentWidgetMaskTab::storeMask() {
  if (m_maskBins && getMode() == Mode::Mask) {
    storeBinMask();
  } else {
    storeDetectorMask(getMode() == Mode::ROI);
  }
}

Tom Titcombe's avatar
Tom Titcombe committed
1230
1231
void InstrumentWidgetMaskTab::changedIntegrationRange(double /*unused*/,
                                                      double /*unused*/) {
1232
1233
  enableApplyButtons();
}
1234

1235
/** Load mask tab state from a Mantid project file
1236
1237
1238
 * @param lines :: lines from the project file to load state from
 */
void InstrumentWidgetMaskTab::loadFromProject(const std::string &lines) {
1239
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
1240
  API::TSVSerialiser tsv(lines);
1241

1242
1243
  if (!tsv.selectSection("masktab"))
    return;
1244

1245
1246
  std::string tabLines;
  tsv >> tabLines;
1247
  API::TSVSerialiser tab(tabLines);
1248

1249
1250
1251
  std::vector<QPushButton *> buttons{
      m_move,         m_pointer,        m_ellipse,  m_rectangle,
      m_ring_ellipse, m_ring_rectangle, m_free_draw};
1252

1253
1254
1255
1256
1257
1258
  tab.selectLine("ActiveTools");
  for (auto button : buttons) {
    bool value;
    tab >> value;
    button->setChecked(value);
  }
1259

1260
1261
  std::vector<QRadioButton *> typeButtons{m_masking_on, m_grouping_on,
                                          m_roi_on};
1262

1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
  tab.selectLine("ActiveType");
  for (auto type : typeButtons) {
    bool value;
    tab >> value;
    type->setChecked(value);
  }

  if (tab.selectLine("MaskViewWorkspace")) {
    // the view was masked. We should load reapply this from a cached
    // workspace in the project folder
    std::string maskWSName;
    tab >> maskWSName;
    loadMaskViewFromProject(maskWSName);
1276
  }
1277
1278
1279
1280
1281
#else
  Q_UNUSED(lines);
  throw std::runtime_error(
      "InstrumentWidgetMaskTab::loadFromProject() not implemented for Qt >= 5");
#endif
1282
}
1283

1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
/** Load a mask workspace applied to the instrument actor from the project
 *
 * This is for the case where masks have been applied to the instrument actor
 * but not to the workspace itself or saved to a workspace/table
 *
 * @param name :: name of the file to load from the project folder
 */
void InstrumentWidgetMaskTab::loadMaskViewFromProject(const std::string &name) {
  using namespace Mantid::API;
  using namespace Mantid::Kernel;
1294

1295
1296
1297
  QSettings settings;
  auto workingDir = settings.value("Project/WorkingDirectory", "").toString();
  auto fileName = workingDir.toStdString() + "/" + name;
1298
1299
1300
1301
1302
  auto maskWS = loadMask(fileName);

  if (!maskWS)
    return; // if we couldn't load it then just fail silently

1303
1304
1305
  auto &actor = m_instrWidget->getInstrumentActor();
  actor.setMaskMatrixWorkspace(maskWS);
  actor.updateColors();
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
  m_instrWidget->updateInstrumentDetectors();
  m_instrWidget->updateInstrumentView();
}

/** Load a mask workspace given a file name
 *
 * This will attempt to load a mask workspace using the supplied file name and
 * assume that the instrument is the same one as the actor in the instrument
 * view.
 *
 * @param fileName :: the full path to the mask file on disk
 * @return a pointer to the loaded mask workspace
 */
Mantid::API::MatrixWorkspace_sptr
InstrumentWidgetMaskTab::loadMask(const std::string &fileName) {
  using namespace Mantid::API;

  // build path and input properties etc.
1324
1325
  const auto &actor = m_instrWidget->getInstrumentActor();
  auto workspace = actor.getWorkspace();
1326
1327
  auto instrument = workspace->getInstrument();
  auto instrumentName = instrument->getName();
1328
  auto tempName = "__" + workspace->getName() + "MaskView";
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341

  // load the mask from the project folder
  try {
    auto alg = AlgorithmManager::Instance().create("LoadMask", -1);
    alg->initialize();
    alg->setPropertyValue("Instrument", instrumentName);
    alg->setPropertyValue("InputFile", fileName);
    alg->setPropertyValue("OutputWorkspace", tempName);
    alg->execute();
  } catch (...) {
    // just fail silently, if we can't load the mask then we should
    // give up at this point.
    return nullptr;
1342
  }
1343
1344

  // get the mask workspace and remove from ADS to clean up
1345
1346
1347
  auto &ads = AnalysisDataService::Instance();
  auto maskWS = ads.retrieveWS<MatrixWorkspace>(tempName);
  ads.remove(tempName);
1348
1349

  return maskWS;
1350
1351
}

1352
1353
1354
1355
/** Save the state of the mask tab to a Mantid project file
 * @return a string representing the state of the mask tab
 */
std::string InstrumentWidgetMaskTab::saveToProject() const {
1356
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
1357
1358
  API::TSVSerialiser tsv;
  API::TSVSerialiser tab;
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376

  std::vector<QPushButton *> buttons{
      m_move,         m_pointer,        m_ellipse,  m_rectangle,
      m_ring_ellipse, m_ring_rectangle, m_free_draw};

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

  std::vector<QRadioButton *> typeButtons{m_masking_on, m_grouping_on,
                                          m_roi_on};

  tab.writeLine("ActiveType");
  for (auto type : typeButtons) {
    tab << type->isChecked();
  }

1377
1378
1379
1380
1381
1382
1383
1384
1385
  // Save the masks applied to view but not saved to a workspace
  auto wsName =
      m_instrWidget->getWorkspaceName().toStdString() + "MaskView.xml";
  bool success = saveMaskViewToProject(wsName);
  if (success)
    tab.writeLine("MaskViewWorkspace") << wsName;

  tsv.writeSection("masktab", tab.outputLines());
  return tsv.outputLines();
1386
1387
1388
1389
#else
  throw std::runtime_error(
      "InstrumentWidgetMaskTab::saveToProject() not implemented for Qt >= 5");
#endif
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
}

/** Save a mask workspace containing masks applied to the instrument view
 *
 * This will save masks which have been applied to the instrument view actor
 * but have not be applied to the workspace or exported to a seperate
 * workspace/table already
 *
 * @param name :: the name to call the workspace in the project folder
 * @return whether a workspace was successfully saved to the project
 */
bool InstrumentWidgetMaskTab::saveMaskViewToProject(
Samuel Jones's avatar
Samuel Jones committed
1402
    const std::string &name, const std::string &projectPath) const {
1403
1404
  using namespace Mantid::API;
  using namespace Mantid::Kernel;
1405

1406
  try {
Samuel Jones's avatar
Samuel Jones committed
1407
1408
1409
1410
1411
1412
1413
    QString workingDir;
    QSettings settings;
    if (projectPath == "") {
      workingDir = settings.value("Project/WorkingDirectory", "").toString();
    } else {
      workingDir = QString::fromStdString(projectPath);
    }
1414
1415
    Poco::Path filepath(workingDir.toStdString());
    auto fileName = filepath.append(name).toString();
Samuel Jones's avatar
Samuel Jones committed
1416

1417
    // get masked detector workspace from actor
1418