/
SliceViewer.cpp
2980 lines (2607 loc) · 105 KB
/
SliceViewer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
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
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
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
481
482
483
484
485
486
487
488
489
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
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
643
644
645
646
647
648
649
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iosfwd>
#include <limits>
#include <sstream>
#include <vector>
#include <boost/make_shared.hpp>
#include "MantidKernel/Strings.h"
#include <boost/math/special_functions/fpclassify.hpp>
#include "MantidKernel/UsageService.h"
#include "MantidAPI/AnalysisDataService.h"
#include "MantidAPI/CoordTransform.h"
#include "MantidAPI/IMDHistoWorkspace.h"
#include "MantidAPI/IMDIterator.h"
#include "MantidAPI/MatrixWorkspace.h"
#include "MantidGeometry/Crystal/PeakTransformHKL.h"
#include "MantidGeometry/Crystal/PeakTransformQSample.h"
#include "MantidGeometry/Crystal/PeakTransformQLab.h"
#include "MantidAPI/IPeaksWorkspace.h"
#include "MantidAPI/IMDEventWorkspace.h"
#include "MantidAPI/AlgorithmManager.h"
#include "MantidGeometry/MDGeometry/IMDDimension.h"
#include "MantidGeometry/MDGeometry/MDBoxImplicitFunction.h"
#include "MantidGeometry/MDGeometry/MDHistoDimension.h"
#include "MantidGeometry/MDGeometry/MDTypes.h"
#include "MantidKernel/ReadLock.h"
#include "MantidQtAPI/PlotAxis.h"
#include "MantidQtAPI/MantidDesktopServices.h"
#include "MantidQtAPI/MdSettings.h"
#include "MantidQtAPI/SignalBlocker.h"
#include "MantidQtAPI/SignalRange.h"
#include "MantidQtAPI/TSVSerialiser.h"
#include "MantidQtAPI/NonOrthogonal.h"
#include "MantidQtAPI/QwtRasterDataMDNonOrthogonal.h"
#include "MantidQtSliceViewer/SliceViewer.h"
#include "MantidQtSliceViewer/CustomTools.h"
#include "MantidQtSliceViewer/DimensionSliceWidget.h"
#include "MantidQtSliceViewer/LineOverlay.h"
#include "MantidQtSliceViewer/SnapToGridDialog.h"
#include "MantidQtSliceViewer/XYLimitsDialog.h"
#include "MantidQtSliceViewer/ConcretePeaksPresenter.h"
#include "MantidQtSliceViewer/CompositePeaksPresenter.h"
#include "MantidQtSliceViewer/ProxyCompositePeaksPresenter.h"
#include "MantidQtSliceViewer/PeakViewFactory.h"
#include "MantidQtSliceViewer/PeakBoundingBox.h"
#include "MantidQtSliceViewer/PeaksViewerOverlayDialog.h"
#include "MantidQtSliceViewer/SliceViewerFunctions.h"
#include "MantidQtMantidWidgets/SelectWorkspacesDialog.h"
#include <qwt_plot_panner.h>
#include <qwt_plot_rescaler.h>
#include <Poco/AutoPtr.h>
#include <Poco/DOM/Document.h>
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/NodeIterator.h>
#include <Poco/DOM/NodeList.h>
#include <Poco/Exception.h>
using namespace Mantid;
using namespace Mantid::Kernel;
using namespace Mantid::Geometry;
using namespace Mantid::API;
using MantidQt::API::MantidDesktopServices;
using MantidQt::API::SyncedCheckboxes;
using MantidQt::API::SignalBlocker;
using Poco::XML::DOMParser;
using Poco::XML::Document;
using Poco::XML::Element;
using Poco::XML::Node;
using Poco::XML::NodeList;
using Poco::XML::NodeIterator;
using Poco::XML::NodeFilter;
using MantidQt::API::AlgorithmRunner;
namespace MantidQt {
namespace SliceViewer {
const QString SliceViewer::NoNormalizationKey = "No";
const QString SliceViewer::VolumeNormalizationKey = "Volume";
const QString SliceViewer::NumEventsNormalizationKey = "# Events";
//------------------------------------------------------------------------------
/** Constructor */
SliceViewer::SliceViewer(QWidget *parent)
: QWidget(parent), m_ws(), m_firstWorkspaceOpen(false), m_dimensions(),
m_data(nullptr), m_X(), m_Y(), m_dimX(0), m_dimY(1), m_logColor(false),
m_fastRender(true), m_rebinMode(false), m_rebinLocked(true),
m_mdSettings(new MantidQt::API::MdSettings()), m_logger("SliceViewer"),
m_firstNonOrthogonalWorkspaceOpen(true), m_nonOrthogonalDefault(false),
m_oldDimNonOrthogonal(false), m_canSwitchScales(false),
m_peaksPresenter(boost::make_shared<CompositePeaksPresenter>(this)),
m_proxyPeaksPresenter(
boost::make_shared<ProxyCompositePeaksPresenter>(m_peaksPresenter)),
m_peaksSliderWidget(NULL), m_lastRatioState(Guess) {
ui.setupUi(this);
std::string enableNonOrthogonal;
Kernel::ConfigService::Instance().getValue("sliceviewer.nonorthogonal",
enableNonOrthogonal);
if (enableNonOrthogonal == "true") {
m_nonOrthogonalDefault = true;
}
m_inf = std::numeric_limits<double>::infinity();
// Point m_plot to the plot created in QtDesigner
m_plot = ui.safeQwtPlot;
// Add a spectrograph
m_spect = new QwtPlotSpectrogram();
m_spect->attach(m_plot);
// Set up the ColorBarWidget
m_colorBar = ui.colorBarWidget;
m_colorBar->setViewRange(0, 10);
QObject::connect(m_colorBar, SIGNAL(changedColorRange(double, double, bool)),
this, SLOT(colorRangeChanged()));
// ---- Set the color map on the data ------
m_data = Kernel::make_unique<API::QwtRasterDataMD>();
m_spect->setColorMap(m_colorBar->getColorMap());
m_plot->autoRefresh();
// Make the splitter use the minimum size for the controls and not stretch out
ui.splitter->setStretchFactor(0, 0);
ui.splitter->setStretchFactor(1, 1);
QSplitterHandle *handle = ui.splitter->handle(1);
QVBoxLayout *layout = new QVBoxLayout(handle);
layout->setSpacing(0);
layout->setMargin(0);
QFrame *line = new QFrame(handle);
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
layout->addWidget(line);
initZoomer();
// hide unused buttons
ui.btnZoom->hide(); // hidden for a long time
// ----------- Toolbar button signals ----------------
QObject::connect(ui.btnResetZoom, SIGNAL(clicked()), this, SLOT(resetZoom()));
QObject::connect(ui.btnClearLine, SIGNAL(clicked()), this, SLOT(clearLine()));
QObject::connect(ui.btnRangeFull, SIGNAL(clicked()), this,
SLOT(setColorScaleAutoFull()));
QObject::connect(ui.btnRangeSlice, SIGNAL(clicked()), this,
SLOT(setColorScaleAutoSlice()));
QObject::connect(ui.btnRebinRefresh, SIGNAL(clicked()), this,
SLOT(rebinParamsChanged()));
QObject::connect(ui.btnAutoRebin, SIGNAL(toggled(bool)), this,
SLOT(autoRebin_toggled(bool)));
QObject::connect(ui.btnPeakOverlay, SIGNAL(clicked()), this,
SLOT(peakOverlay_clicked()));
// ----------- Other signals ----------------
QObject::connect(m_colorBar, SIGNAL(colorBarDoubleClicked()), this,
SLOT(loadColorMapSlot()));
m_algoRunner = new AlgorithmRunner(this);
QObject::connect(m_algoRunner, SIGNAL(algorithmComplete(bool)), this,
SLOT(dynamicRebinComplete(bool)));
initMenus();
loadSettings();
updateDisplay();
m_nonOrthogonalOverlay = new NonOrthogonalOverlay(m_plot, m_plot->canvas());
m_nonOrthogonalOverlay->disable();
// -------- Line Overlay ----------------
m_lineOverlay = new LineOverlay(m_plot, m_plot->canvas());
m_lineOverlay->setShown(false);
m_overlayWSOutline = new LineOverlay(m_plot, m_lineOverlay);
m_overlayWSOutline->setShowHandles(false);
m_overlayWSOutline->setShowLine(false);
m_overlayWSOutline->setShown(false);
// -------- Peak Overlay ----------------
m_peakTransformSelector.registerCandidate(
boost::make_shared<PeakTransformHKLFactory>());
m_peakTransformSelector.registerCandidate(
boost::make_shared<PeakTransformQSampleFactory>());
m_peakTransformSelector.registerCandidate(
boost::make_shared<PeakTransformQLabFactory>());
this->setAcceptDrops(true);
// --------- Rescaler --------------------
m_rescaler = new QwtPlotRescaler(m_plot->canvas());
Mantid::Kernel::UsageService::Instance().registerFeatureUsage(
"Interface", "SliceViewer", false);
}
void SliceViewer::updateAspectRatios() {
bool lockAspectRatios = false;
if (m_aspectRatioType == Guess) {
/* Lock aspect ratios, if that feature has been enabled, and if the plot x
* and
* y units
* are suitable.
*/
lockAspectRatios =
m_X->getMDUnits().isQUnit() && m_Y->getMDUnits().isQUnit();
} else {
// Lock everything (or not)
lockAspectRatios = m_aspectRatioType == All;
}
m_rescaler->setEnabled(lockAspectRatios);
m_rescaler->setReferenceAxis(QwtPlot::xBottom);
m_rescaler->setAspectRatio(QwtPlot::yLeft, 1.0);
m_rescaler->setAspectRatio(QwtPlot::yRight, 0.0);
m_rescaler->setAspectRatio(QwtPlot::xTop, 0.0);
m_rescaler->setExpandingDirection(QwtPlotRescaler::ExpandBoth);
}
//------------------------------------------------------------------------------
/// Destructor
SliceViewer::~SliceViewer() {
saveSettings();
delete m_rescaler;
// Don't delete Qt objects, I think these are auto-deleted
}
//------------------------------------------------------------------------------
/** Load QSettings from .ini-type files */
void SliceViewer::loadSettings() {
QSettings settings;
settings.beginGroup("Mantid/SliceViewer");
// Maintain backwards compatibility with use of LogColorScale
int scaleType = settings.value("ColorScale", -1).toInt();
if (scaleType == -1) {
scaleType = settings.value("LogColorScale", 0).toInt();
}
double nth_power = settings.value("PowerScaleExponent", 2.0).toDouble();
// Load Colormap. If the file is invalid the default stored colour map is
// used.
// If the user selected a unified color map for the SliceViewer and the VSI,
// then this is loaded.
if (m_mdSettings != NULL && m_mdSettings->getUsageGeneralMdColorMap()) {
m_currentColorMapFile = m_mdSettings->getGeneralMdColorMapFile();
} else {
m_currentColorMapFile = settings.value("ColormapFile", "").toString();
}
// Set values from settings
if (!m_currentColorMapFile.isEmpty())
loadColorMap(m_currentColorMapFile);
m_colorBar->setScale(scaleType);
m_colorBar->setExponent(nth_power);
// Last saved image file
m_lastSavedFile = settings.value("LastSavedImagePath", "").toString();
bool transparentZeros = settings.value("TransparentZeros", 1).toInt();
this->setTransparentZeros(transparentZeros);
const int aspectRatioOption = settings.value("LockAspectRatios", 0).toInt();
this->setAspectRatio(static_cast<AspectRatioType>(aspectRatioOption));
settings.endGroup();
}
//------------------------------------------------------------------------------
/** Save settings for next time. */
void SliceViewer::saveSettings() {
QSettings settings;
settings.beginGroup("Mantid/SliceViewer");
settings.setValue("ColormapFile", m_currentColorMapFile);
settings.setValue("ColorScale", m_colorBar->getScale());
settings.setValue("PowerScaleExponent", m_colorBar->getExponent());
settings.setValue("LastSavedImagePath", m_lastSavedFile);
settings.setValue("TransparentZeros",
(m_actionTransparentZeros->isChecked() ? 1 : 0));
settings.setValue("LockAspectRatios", static_cast<int>(m_aspectRatioType));
settings.endGroup();
}
//------------------------------------------------------------------------------
/** set an icon given the control and a string.
* @param btn the widget to give the new icon
* @param iconName the path of the new icon
* @param mode the mode of the icon
* @param state on or off state of the icon
*/
void SliceViewer::setIconFromString(QAbstractButton *btn,
const std::string &iconName,
QIcon::Mode mode = QIcon::Mode::Normal,
QIcon::State state = QIcon::State::Off) {
QIcon icon;
icon.addFile(QString::fromStdString(iconName), QSize(), mode, state);
btn->setIcon(icon);
}
/** set an icon given the control and a string.
* @param action the menu action to give the new icon
* @param iconName the path of the new icon
* @param mode the mode of the icon
* @param state on or off state of the icon
*/
void SliceViewer::setIconFromString(QAction *action,
const std::string &iconName,
QIcon::Mode mode = QIcon::Mode::Normal,
QIcon::State state = QIcon::State::Off) {
QIcon icon;
icon.addFile(QString::fromStdString(iconName), QSize(), mode, state);
action->setIcon(icon);
}
//------------------------------------------------------------------------------
/** Create the menus */
void SliceViewer::initMenus() {
// ---------------------- Build the menu bar -------------------------
// Find the top-level parent
QWidget *widget = this;
while (widget && widget->parentWidget())
widget = widget->parentWidget();
QMainWindow *parentWindow = dynamic_cast<QMainWindow *>(widget);
QMenuBar *bar;
if (parentWindow)
// Use the QMainWindow menu bar
bar = parentWindow->menuBar();
else {
// Widget is not in a QMainWindow. Make a menu bar
bar = new QMenuBar(this);
bar->setObjectName("Main Menu Bar");
ui.verticalLayout->insertWidget(0, bar);
}
QAction *action;
// --------------- File Menu ----------------------------------------
m_menuFile = new QMenu("&File", this);
action = new QAction(QPixmap(), "&Close", this);
connect(action, SIGNAL(triggered()), this, SLOT(close()));
m_actionFileClose = action;
m_menuFile->addAction(action);
action = new QAction(QPixmap(), "&Save to image file", this);
action->setShortcut(Qt::Key_S + Qt::ControlModifier);
connect(action, SIGNAL(triggered()), this, SLOT(saveImage()));
m_menuFile->addAction(action);
action = new QAction(QPixmap(), "Copy image to &Clipboard", this);
action->setShortcut(Qt::Key_C + Qt::ControlModifier);
connect(action, SIGNAL(triggered()), this, SLOT(copyImageToClipboard()));
m_menuFile->addAction(action);
// --------------- View Menu ----------------------------------------
m_menuView = new QMenu("&View", this);
action = new QAction(QPixmap(), "&Reset Zoom", this);
connect(action, SIGNAL(triggered()), this, SLOT(resetZoom()));
setIconFromString(action, g_iconViewFull);
m_menuView->addAction(action);
action = new QAction(QPixmap(), "&Set X/Y View Size", this);
connect(action, SIGNAL(triggered()), this, SLOT(setXYLimitsDialog()));
m_menuView->addAction(action);
action = new QAction(QPixmap(), "Zoom &In", this);
action->setShortcut(Qt::Key_Plus + Qt::ControlModifier);
connect(action, SIGNAL(triggered()), this, SLOT(zoomInSlot()));
m_menuView->addAction(action);
action = new QAction(QPixmap(), "Zoom &Out", this);
action->setShortcut(Qt::Key_Minus + Qt::ControlModifier);
connect(action, SIGNAL(triggered()), this, SLOT(zoomOutSlot()));
m_menuView->addAction(action);
action = new QAction(QPixmap(), "&Fast Rendering Mode", this);
action->setShortcut(Qt::Key_F + Qt::ControlModifier);
action->setCheckable(true);
action->setChecked(true);
connect(action, SIGNAL(toggled(bool)), this, SLOT(setFastRender(bool)));
m_menuView->addAction(action);
m_menuView->addSeparator();
action = new QAction(QPixmap(), "Enable/Disable R&ebin Mode", this);
m_syncRebinMode = new SyncedCheckboxes(action, ui.btnRebinMode, false);
connect(m_syncRebinMode, SIGNAL(toggled(bool)), this,
SLOT(RebinMode_toggled(bool)));
m_menuView->addAction(action);
action = new QAction(QPixmap(), "Rebin Current View", this);
action->setShortcut(Qt::Key_R + Qt::ControlModifier);
action->setEnabled(false);
connect(action, SIGNAL(triggered()), this, SLOT(rebinParamsChanged()));
m_menuView->addAction(action);
m_actionRefreshRebin = action;
action = new QAction(QPixmap(), "Auto Rebin", this);
m_syncAutoRebin = new SyncedCheckboxes(action, ui.btnAutoRebin, false);
connect(action, SIGNAL(toggled(bool)), this, SLOT(autoRebin_toggled(bool)));
m_syncAutoRebin->setEnabled(false); // Cannot auto rebin by default.
m_menuView->addAction(action);
m_menuView->addSeparator();
action = new QAction(QPixmap(), "Peak Overlay", this);
connect(action, SIGNAL(triggered()), this, SLOT(peakOverlay_clicked()));
m_menuView->addAction(action);
m_menuView->addSeparator();
QActionGroup *group = new QActionGroup(this);
const QString normalization = " Normalization";
action = new QAction(QPixmap(),
SliceViewer::NoNormalizationKey + normalization, this);
m_menuView->addAction(action);
action->setActionGroup(group);
action->setCheckable(true);
connect(action, SIGNAL(triggered()), this, SLOT(changeNormalizationNone()));
m_actionNormalizeNone = action;
action = new QAction(
QPixmap(), SliceViewer::VolumeNormalizationKey + normalization, this);
m_menuView->addAction(action);
action->setActionGroup(group);
action->setCheckable(true);
action->setChecked(true);
connect(action, SIGNAL(triggered()), this, SLOT(changeNormalizationVolume()));
m_actionNormalizeVolume = action;
action = new QAction(
QPixmap(), SliceViewer::NumEventsNormalizationKey + normalization, this);
m_menuView->addAction(action);
action->setActionGroup(group);
action->setCheckable(true);
connect(action, SIGNAL(triggered()), this,
SLOT(changeNormalizationNumEvents()));
m_actionNormalizeNumEvents = action;
// Mirror the menu options directly in the Ui.
ui.comboNormalization->addItem(SliceViewer::NoNormalizationKey);
ui.comboNormalization->addItem(SliceViewer::VolumeNormalizationKey);
ui.comboNormalization->addItem(SliceViewer::NumEventsNormalizationKey);
connect(this->ui.comboNormalization,
SIGNAL(currentIndexChanged(const QString &)),
SLOT(onNormalizationChanged(const QString &)));
m_menuView->addSeparator();
group = new QActionGroup(this);
action = new QAction(QPixmap(), "Lock Aspect Ratios (Guess)", this);
action->setCheckable(true);
action->setChecked(true); // This is our default
action->setActionGroup(group);
m_lockAspectRatiosActionGuess = action;
connect(action, SIGNAL(triggered()), this, SLOT(changeAspectRatioGuess()));
m_menuView->addAction(action);
action = new QAction(QPixmap(), "Lock Aspect Ratios (All)", this);
action->setCheckable(true);
action->setActionGroup(group);
m_lockAspectRatiosActionAll = action;
connect(action, SIGNAL(triggered()), this, SLOT(changeAspectRatioAll()));
m_menuView->addAction(action);
action = new QAction(QPixmap(), "Unlock Aspect Ratios (All)", this);
action->setCheckable(true);
action->setActionGroup(group);
m_lockAspectRatiosActionUnlock = action;
connect(action, SIGNAL(triggered()), this, SLOT(changeAspectRatioUnlock()));
m_menuView->addAction(action);
// --------------- Color options Menu ----------------------------------------
m_menuColorOptions = new QMenu("&ColorMap", this);
action = new QAction(QPixmap(), "&Load Colormap", this);
connect(action, SIGNAL(triggered()), this, SLOT(loadColorMapSlot()));
m_menuColorOptions->addAction(action);
action = new QAction(QPixmap(), "&Current View Range", this);
connect(action, SIGNAL(triggered()), this, SLOT(setColorScaleAutoSlice()));
action->setIconVisibleInMenu(true);
{ setIconFromString(action, g_iconZoomPlus); }
m_menuColorOptions->addAction(action);
action = new QAction(QPixmap(), "&Full Range", this);
connect(action, SIGNAL(triggered()), this, SLOT(setColorScaleAutoFull()));
{ setIconFromString(action, g_iconZoomMinus); }
m_menuColorOptions->addAction(action);
action = new QAction(QPixmap(), "Transparent &Zeros", this);
action->setCheckable(true);
action->setChecked(true);
m_actionTransparentZeros = action;
connect(action, SIGNAL(toggled(bool)), this, SLOT(setTransparentZeros(bool)));
m_menuColorOptions->addAction(action);
// --------------- Help Menu ----------------------------------------
m_menuHelp = new QMenu("&Help", this);
action = new QAction(QPixmap(), "&Slice Viewer Help (browser)", this);
action->setShortcut(Qt::Key_F1);
connect(action, SIGNAL(triggered()), this, SLOT(helpSliceViewer()));
m_menuHelp->addAction(action);
action = new QAction(QPixmap(), "&Line Viewer Help (browser)", this);
connect(action, SIGNAL(triggered()), this, SLOT(helpLineViewer()));
m_menuHelp->addAction(action);
action = new QAction(QPixmap(), "&Peaks Viewer Help (browser)", this);
connect(action, SIGNAL(triggered()), this, SLOT(helpPeaksViewer()));
m_menuHelp->addAction(action);
// --------------- Line Menu ----------------------------------------
m_menuLine = new QMenu("&Line", this);
// Line mode menu, synced to the button
action = new QAction(QPixmap(), "&Line Mode", this);
action->setShortcut(Qt::Key_L + Qt::ControlModifier);
m_syncLineMode = new SyncedCheckboxes(action, ui.btnDoLine, false);
connect(m_syncLineMode, SIGNAL(toggled(bool)), this,
SLOT(LineMode_toggled(bool)));
m_menuLine->addAction(action);
// Snap-to-grid, synced to the button
action = new QAction(QPixmap(), "&Snap to Grid", this);
m_syncSnapToGrid = new SyncedCheckboxes(action, ui.btnSnapToGrid, false);
connect(m_syncSnapToGrid, SIGNAL(toggled(bool)), this,
SLOT(SnapToGrid_toggled(bool)));
m_menuLine->addAction(action);
// --------------- Peaks Menu ----------------------------------------
m_menuPeaks = new QMenu("&Peak", this);
action = new QAction(QPixmap(), "&Overlay Options", this);
connect(action, SIGNAL(triggered()), this,
SLOT(onPeaksViewerOverlayOptions()));
m_menuPeaks->addAction(action);
action = new QAction(QPixmap(), "&Visible Columns", this);
connect(action, SIGNAL(triggered()), this,
SIGNAL(peaksTableColumnOptions())); // just re-emit
m_menuPeaks->addAction(action);
m_menuPeaks->setEnabled(false); // Until a PeaksWorkspace is selected.
// Add all the needed menus
bar->addMenu(m_menuFile);
bar->addMenu(m_menuView);
bar->addMenu(m_menuColorOptions);
bar->addMenu(m_menuLine);
bar->addMenu(m_menuPeaks);
bar->addMenu(m_menuHelp);
}
//------------------------------------------------------------------------------
/** Intialize the zooming/panning tools */
void SliceViewer::initZoomer() {
QwtPlotPicker *zoomer = new QwtPlotPicker(m_plot->canvas());
zoomer->setSelectionFlags(QwtPicker::RectSelection |
QwtPicker::DragSelection);
zoomer->setMousePattern(QwtEventPattern::MouseSelect1, Qt::LeftButton);
zoomer->setTrackerMode(QwtPicker::AlwaysOff);
const QColor c(Qt::darkBlue);
zoomer->setRubberBand(QwtPicker::RectRubberBand);
zoomer->setRubberBandPen(c);
QObject::connect(zoomer, SIGNAL(selected(const QwtDoubleRect &)), this,
SLOT(zoomRectSlot(const QwtDoubleRect &)));
// Zoom in/out using middle-click+drag or the mouse wheel
CustomMagnifier *magnif = new CustomMagnifier(m_plot->canvas());
magnif->setAxisEnabled(QwtPlot::yRight, false); // Don't do the colorbar axis
magnif->setWheelFactor(0.9);
magnif->setMouseButton(Qt::MidButton);
// Have to flip the keys to match our flipped mouse wheel
magnif->setZoomInKey(Qt::Key_Minus, Qt::NoModifier);
magnif->setZoomOutKey(Qt::Key_Equal, Qt::NoModifier);
// Hook-up listener to rescaled event
QObject::connect(magnif, SIGNAL(rescaled(double)), this,
SLOT(magnifierRescaled(double)));
// Pan using the right mouse button + drag
QwtPlotPanner *panner = new QwtPlotPanner(m_plot->canvas());
panner->setMouseButton(Qt::RightButton);
panner->setAxisEnabled(QwtPlot::yRight, false); // Don't do the colorbar axis
QObject::connect(panner, SIGNAL(panned(int, int)), this,
SLOT(panned(int, int))); // Handle panning.
// Custom picker for showing the current coordinates
CustomPicker *picker =
new CustomPicker(m_spect->xAxis(), m_spect->yAxis(), m_plot->canvas());
QObject::connect(picker, SIGNAL(mouseMoved(double, double)), this,
SLOT(showInfoAt(double, double)));
}
//------------------------------------------------------------------------------
/** Programmatically show/hide the controls (sliders etc)
*
* @param visible :: true if you want to show the controls.
*/
void SliceViewer::showControls(bool visible) {
ui.frmControls->setVisible(visible);
}
//------------------------------------------------------------------------------
/** Add (as needed) and update DimensionSliceWidget's. */
void SliceViewer::updateDimensionSliceWidgets() {
// Create all necessary widgets
if (m_dimWidgets.size() < m_ws->getNumDims()) {
for (size_t d = m_dimWidgets.size(); d < m_ws->getNumDims(); d++) {
DimensionSliceWidget *widget = new DimensionSliceWidget(this);
ui.verticalLayoutControls->insertWidget(int(d), widget);
// Slots for changes on the dimension widget
QObject::connect(widget, SIGNAL(changedShownDim(int, int, int)), this,
SLOT(changedShownDim(int, int, int)));
QObject::connect(widget, SIGNAL(changedSlicePoint(int, double)), this,
SLOT(updateDisplaySlot(int, double)));
// Slots for dynamic rebinning
QObject::connect(widget, SIGNAL(changedThickness(int, double)), this,
SLOT(rebinParamsChanged()));
QObject::connect(widget, SIGNAL(changedNumBins(int, int)), this,
SLOT(rebinParamsChanged()));
// Save in this list
m_dimWidgets.push_back(widget);
}
}
// Hide unnecessary ones
for (size_t d = m_ws->getNumDims(); d < m_dimWidgets.size(); d++) {
DimensionSliceWidget *widget = m_dimWidgets[d];
widget->hide();
}
bool dimXset = false;
bool dimYset = false;
// put non integrated dimensions first
for (size_t d = 0; d < m_dimensions.size(); d++) {
if ((dimXset == false) &&
(m_ws->getDimension(d)->getIsIntegrated() == false)) {
m_dimX = d;
dimXset = true;
}
if ((dimYset == false) &&
(m_ws->getDimension(d)->getIsIntegrated() == false) && (d != m_dimX)) {
m_dimY = d;
dimYset = true;
}
if ((dimXset == true) && (dimYset == true)) {
break;
}
}
int maxLabelWidth = 10;
int maxUnitsWidth = 10;
// Set each dimension
for (size_t d = 0; d < m_dimensions.size(); d++) {
DimensionSliceWidget *widget = m_dimWidgets[d];
widget->blockSignals(true);
widget->setDimension(int(d), m_dimensions[d]);
// Default slicing layout
if (d == m_dimX)
widget->setShownDim(0);
else if (d == m_dimY)
widget->setShownDim(1);
else
widget->setShownDim(-1);
// To harmonize the layout, find the largest label
int w;
w = widget->ui.lblName->sizeHint().width();
if (w > maxLabelWidth)
maxLabelWidth = w;
w = widget->ui.lblUnits->sizeHint().width();
if (w > maxUnitsWidth)
maxUnitsWidth = w;
// if the workspace is already binned, update the interface with the
// existing number of bins
if (m_ws->isMDHistoWorkspace()) {
auto dim = m_ws->getDimension(d);
int numBins = static_cast<int>(dim->getNBins());
widget->setNumBins(numBins);
}
widget->blockSignals(false);
}
// Make the labels all the same width
for (size_t d = 0; d < m_ws->getNumDims(); d++) {
DimensionSliceWidget *widget = m_dimWidgets[d];
widget->ui.lblName->setMinimumSize(QSize(maxLabelWidth, 0));
widget->ui.lblUnits->setMinimumSize(QSize(maxUnitsWidth, 0));
}
}
//------------------------------------------
void SliceViewer::switchQWTRaster(bool useNonOrthogonal) {
m_coordinateTransform = createCoordinateTransform(m_ws, m_dimX, m_dimY);
if (useNonOrthogonal && ui.btnNonOrthogonalToggle->isChecked()) {
m_data = Kernel::make_unique<API::QwtRasterDataMDNonOrthogonal>();
applyNonOrthogonalAxisScaleDraw();
} else {
applyOrthogonalAxisScaleDraw();
m_data = Kernel::make_unique<API::QwtRasterDataMD>();
}
m_coordinateTransform = createCoordinateTransform(m_ws, m_dimX, m_dimY);
m_data->setWorkspace(m_ws);
this->setTransparentZeros(false);
if (m_firstNonOrthogonalWorkspaceOpen && m_nonOrthogonalDefault) {
m_firstNonOrthogonalWorkspaceOpen = false;
ui.btnNonOrthogonalToggle->toggle();
}
updateDisplay();
}
//------------------------------------------------------------------------------
/** Set the displayed workspace. Updates UI.
*
* @param ws :: IMDWorkspace to show.
*/
void SliceViewer::setWorkspace(Mantid::API::IMDWorkspace_sptr ws) {
m_ws = ws;
m_coordinateTransform = createCoordinateTransform(ws, m_dimX, m_dimY);
// disconnect and reconnect here
QObject::connect(this, SIGNAL(changedShownDim(size_t, size_t)), this,
SLOT(checkForHKLDimension()));
QObject::connect(this, SIGNAL(changedShownDim(size_t, size_t)), this,
SLOT(switchAxis()));
QObject::connect(ui.btnNonOrthogonalToggle, SIGNAL(toggled(bool)), this,
SLOT(switchQWTRaster(bool)));
QObject::connect(ui.btnNonOrthogonalToggle, SIGNAL(toggled(bool)), this,
SLOT(setNonOrthogonalbtn()));
m_firstNonOrthogonalWorkspaceOpen = true;
m_data->setWorkspace(ws);
m_plot->setWorkspace(ws);
autoRebinIfRequired();
// Set the normalization appropriate
this->setNormalization(ws->displayNormalization(), false);
// Only allow perpendicular lines if looking at a matrix workspace.
bool matrix = bool(boost::dynamic_pointer_cast<MatrixWorkspace>(m_ws));
m_lineOverlay->setAngleSnapMode(matrix);
m_lineOverlay->setAngleSnap(matrix ? 90 : 45);
// Can't use dynamic rebin mode with a MatrixWorkspace
m_syncRebinMode->setEnabled(!matrix);
// Go to no normalization by default for MatrixWorkspaces
if (matrix)
this->setNormalization(Mantid::API::NoNormalization,
false /* without updating */);
// Emit the signal that we changed the workspace
emit workspaceChanged();
// For MDEventWorkspace, estimate the resolution and change the # of bins
// accordingly
IMDEventWorkspace_sptr mdew =
boost::dynamic_pointer_cast<IMDEventWorkspace>(m_ws);
std::vector<coord_t> binSizes = m_ws->estimateResolution();
// Copy the dimensions to this so they can be modified
m_dimensions.clear();
std::ostringstream mess;
for (size_t d = 0; d < m_ws->getNumDims(); d++) {
// Choose the number of bins based on the resolution of the workspace (for
// MDEWs)
coord_t min = m_ws->getDimension(d)->getMinimum();
coord_t max = m_ws->getDimension(d)->getMaximum();
if (max < min) {
coord_t tmp = max;
max = min;
min = tmp;
}
if (!std::isfinite(min) || !std::isfinite(max)) {
mess << "Dimension " << m_ws->getDimension(d)->getName()
<< " has a bad range: (";
mess << min << ", " << max << ")\n";
}
size_t numBins = static_cast<size_t>((max - min) / binSizes[d]);
MDHistoDimension_sptr dim(
new MDHistoDimension(m_ws->getDimension(d).get()));
dim->setRange(numBins, min, max);
m_dimensions.push_back(dim);
}
if (!mess.str().empty()) {
mess << "Bad ranges could cause memory allocation errors. Please fix the "
"workspace.\n"
"You can continue using Mantid.";
throw std::out_of_range(mess.str());
}
// Adjust the range to that of visible data
if (mdew) {
std::vector<Mantid::Geometry::MDDimensionExtents<coord_t>> ext =
mdew->getMinimumExtents();
for (size_t d = 0; d < mdew->getNumDims(); d++) {
size_t newNumBins =
size_t(ext[d].getSize() / m_dimensions[d]->getBinWidth() + 1);
m_dimensions[d]->setRange(newNumBins, ext[d].getMin(), ext[d].getMax());
}
}
// Build up the widgets
this->updateDimensionSliceWidgets();
// This will auto scale the color bar to the current slice when the workspace
// is
// loaded. This always happens when a workspace is loaded for the first time.
// For live event data workspaces subsequent updates might not lead to an auto
// scaling of the color scale range (if this is explicitly turned off).
if (shouldAutoScaleForNewlySetWorkspace(m_firstWorkspaceOpen,
m_colorBar->getAutoScale())) {
findRangeFull();
m_colorBar->setViewRange(m_colorRangeFull);
m_colorBar->updateColorMap();
}
// Initial display update
this->updateDisplay(
!m_firstWorkspaceOpen /*Force resetting the axes, the first time*/);
// Don't reset axes next time
m_firstWorkspaceOpen = true;
// For showing the original coordinates
ui.frmMouseInfo->setVisible(false);
if (m_ws->hasOriginalWorkspace()) {
IMDWorkspace_sptr origWS =
boost::dynamic_pointer_cast<IMDWorkspace>(m_ws->getOriginalWorkspace());
auto toOrig = m_ws->getTransformToOriginal();
if (toOrig) {
ui.frmMouseInfo->setVisible(true);
ui.lblOriginalWorkspace->setText(
QString::fromStdString("in '" + origWS->getName() + "'"));
}
}
// Enable peaks overlays according to the dimensionality and the displayed
// dimensions.
enablePeakOverlaysIfAppropriate();
// Send out a signal
emit changedShownDim(m_dimX, m_dimY);
m_canSwitchScales = true;
}
//------------------------------------------------------------------------------
/** Set the workspace to view using its name.
* The workspace should be a MDHistoWorkspace or a MDEventWorkspace,
* with at least 2 dimensions.
*
* @param wsName :: name of the MDWorkspace to look for
* @throw std::runtime_error if the workspace is not found or is a
*MatrixWorkspace
*/
void SliceViewer::setWorkspace(const QString &wsName) {
IMDWorkspace_sptr ws = boost::dynamic_pointer_cast<IMDWorkspace>(
AnalysisDataService::Instance().retrieve(wsName.toStdString()));
if (!ws)
throw std::runtime_error("SliceViewer can only view MDWorkspaces.");
if (boost::dynamic_pointer_cast<MatrixWorkspace>(ws))
throw std::runtime_error(
"SliceViewer cannot view MatrixWorkspaces. "
"Please select a MDEventWorkspace or a MDHistoWorkspace.");
this->setWorkspace(ws);
}
//------------------------------------------------------------------------------
/** @return the workspace in the SliceViewer */
Mantid::API::IMDWorkspace_sptr SliceViewer::getWorkspace() { return m_ws; }
//------------------------------------------------------------------------------
/** Load a color map from a file
*
* @param filename :: file to open; empty to ask via a dialog box.
*/
void SliceViewer::loadColorMap(QString filename) {
QString fileselection;
if (filename.isEmpty()) {
fileselection = MantidColorMap::loadMapDialog(m_currentColorMapFile, this);
if (fileselection.isEmpty())
return;
} else
fileselection = filename;
m_currentColorMapFile = fileselection;
// Load from file
m_colorBar->getColorMap().loadMap(fileselection);
m_spect->setColorMap(m_colorBar->getColorMap());
m_colorBar->updateColorMap();
this->updateDisplay();
}
//==============================================================================
//================================ SLOTS =======================================
//==============================================================================
//------------------------------------------------------------------------------
/** Automatically sets the min/max of the color scale,
* using the limits in the entire data set of the workspace
* (every bin, even those not currently visible).
*/
void SliceViewer::setColorScaleAutoFull() {
this->findRangeFull();
m_colorBar->setViewRange(m_colorRangeFull);
this->updateDisplay();
}
//------------------------------------------------------------------------------
/** Automatically sets the min/max of the color scale,
* using the limits in the data that is currently visible
* in the plot (only the bins in this slice and within the
* view limits)
*/
void SliceViewer::setColorScaleAutoSlice() {
this->findRangeSlice();
m_colorBar->setViewRange(m_colorRangeSlice);
this->updateDisplay();
}
void SliceViewer::setAspectRatio(AspectRatioType type) {
SignalBlocker<QAction> actionGuess(m_lockAspectRatiosActionGuess);
SignalBlocker<QAction> actionAll(m_lockAspectRatiosActionAll);
SignalBlocker<QAction> actionUnlock(m_lockAspectRatiosActionUnlock);
actionGuess->setChecked(type == Guess);
actionAll->setChecked(type == All);
actionUnlock->setChecked(type == Unlock);
m_aspectRatioType = type;
// Redraw the view.
this->updateDisplay(true /*force axis reset*/);
}
void SliceViewer::changeAspectRatioGuess() { this->setAspectRatio(Guess); }
void SliceViewer::changeAspectRatioAll() { this->setAspectRatio(All); }
void SliceViewer::changeAspectRatioUnlock() { this->setAspectRatio(Unlock); }
//------------------------------------------------------------------------------
/// Slot called when the ColorBarWidget changes the range of colors
void SliceViewer::colorRangeChanged() {
m_spect->setColorMap(m_colorBar->getColorMap());
this->updateDisplay();
}
//------------------------------------------------------------------------------
/** Set whether to display 0 signal as "transparent" color.
*
* @param transparent :: true if you want zeros to be transparent.
*/
void SliceViewer::setTransparentZeros(bool transparent) {
SignalBlocker<QAction> transparentZeros(m_actionTransparentZeros);
transparentZeros->setChecked(transparent);
// Set and display
m_data->setZerosAsNan(transparent);
this->updateDisplay();
}
//------------------------------------------------------------------------------
/// Slot called when changing the normalization menu
void SliceViewer::changeNormalizationNone() {
this->setNormalization(Mantid::API::NoNormalization, true);
}
void SliceViewer::changeNormalizationVolume() {
this->setNormalization(Mantid::API::VolumeNormalization, true);
}
void SliceViewer::changeNormalizationNumEvents() {
this->setNormalization(Mantid::API::NumEventsNormalization, true);
}
/**
* @brief Slot to handle change in normalization kicked-off from the combo box.
* @param normalizationKey : Text key for type of normalization switched to.
*/
void SliceViewer::onNormalizationChanged(const QString &normalizationKey) {
if (normalizationKey == SliceViewer::NoNormalizationKey) {
changeNormalizationNone();
} else if (normalizationKey == SliceViewer::VolumeNormalizationKey) {
changeNormalizationVolume();
} else {
changeNormalizationNumEvents();
}
}
//------------------------------------------------------------------------------
/** Set the normalization mode for viewing the data
*
* @param norm :: MDNormalization enum. 0=none; 1=volume; 2=# of events
* @param update :: update the displayed image. If false, just sets it and shows