-
Notifications
You must be signed in to change notification settings - Fork 122
/
MantidDock.cpp
1731 lines (1516 loc) · 54.9 KB
/
MantidDock.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 "MantidDock.h"
#include "MantidUI.h"
#include "MantidMatrix.h"
#include "../ApplicationWindow.h"
#include "../pixmaps.h"
#include "MantidWSIndexDialog.h"
#include "FlowLayout.h"
#include "WorkspaceIcons.h"
#include <MantidAPI/AlgorithmFactory.h>
#include <MantidAPI/FileProperty.h>
#include <MantidAPI/WorkspaceGroup.h>
#include <MantidGeometry/MDGeometry/IMDDimension.h>
#include <MantidGeometry/Crystal/OrientedLattice.h>
#include <MantidQtAPI/InterfaceManager.h>
#include <MantidQtAPI/Message.h>
#include <boost/assign/list_of.hpp>
#include <Poco/Path.h>
#include <algorithm>
#include <sstream>
using namespace Mantid::API;
using namespace Mantid::Kernel;
using namespace Mantid::Geometry;
namespace
{
/// static logger for dock widget
Mantid::Kernel::Logger docklog("MantidDockWidget");
Mantid::Kernel::Logger treelog("MantidTreeWidget");
WorkspaceIcons WORKSPACE_ICONS = WorkspaceIcons();
}
MantidDockWidget::MantidDockWidget(MantidUI *mui, ApplicationWindow *parent) :
QDockWidget(tr("Workspaces"),parent), m_mantidUI(mui), m_updateCount( 0 ),
m_treeUpdating(false), m_ads(Mantid::API::AnalysisDataService::Instance())
{
setObjectName("exploreMantid"); // this is needed for QMainWindow::restoreState()
setMinimumHeight(150);
setMinimumWidth(200);
parent->addDockWidget( Qt::RightDockWidgetArea, this );
QFrame *f = new QFrame(this);
setWidget(f);
m_tree = new MantidTreeWidget(this,m_mantidUI);
m_tree->setHeaderLabel("Workspaces");
FlowLayout * buttonLayout = new FlowLayout();
m_loadButton = new QPushButton("Load");
m_saveButton = new QPushButton("Save");
m_deleteButton = new QPushButton("Delete");
m_groupButton= new QPushButton("Group");
m_sortButton= new QPushButton("Sort");
if(m_groupButton)
m_groupButton->setEnabled(false);
buttonLayout->addWidget(m_loadButton);
buttonLayout->addWidget(m_saveButton);
buttonLayout->addWidget(m_deleteButton);
buttonLayout->addWidget(m_groupButton);
buttonLayout->addWidget(m_sortButton);
//
QVBoxLayout * layout = new QVBoxLayout();
f->setLayout(layout);
layout->addLayout(buttonLayout);
layout->addWidget(m_tree);
//
m_loadMenu = new QMenu(this);
QAction* loadFileAction = new QAction("File",this);
QAction *liveDataAction = new QAction("Live Data",this);
m_loadMapper = new QSignalMapper(this);
m_loadMapper->setMapping(liveDataAction,"StartLiveData");
m_loadMapper->setMapping(loadFileAction,"Load");
connect(liveDataAction,SIGNAL(activated()), m_loadMapper, SLOT(map()));
connect(loadFileAction,SIGNAL(activated()),m_loadMapper,SLOT(map()));
connect(m_loadMapper, SIGNAL(mapped(const QString &)), m_mantidUI, SLOT(showAlgorithmDialog(const QString&)));
m_loadMenu->addAction(loadFileAction);
m_loadMenu->addAction(liveDataAction);
m_loadButton->setMenu(m_loadMenu);
// Dialog box used for user to specify fodler to save multiple workspaces into
m_saveFolderDialog = new QFileDialog;
m_saveFolderDialog->setFileMode(QFileDialog::DirectoryOnly);
m_saveFolderDialog->setOption(QFileDialog::ShowDirsOnly);
// SET UP SORT
createSortMenuActions();
createWorkspaceMenuActions();
connect(m_saveButton,SIGNAL(clicked()),this,SLOT(saveWorkspaces()));
connect(m_deleteButton,SIGNAL(clicked()),this,SLOT(deleteWorkspaces()));
connect(m_tree,SIGNAL(itemClicked(QTreeWidgetItem*, int)),this,SLOT(clickedWorkspace(QTreeWidgetItem*, int)));
connect(m_tree,SIGNAL(itemSelectionChanged()),this,SLOT(workspaceSelected()));
connect(m_groupButton,SIGNAL(clicked()),this,SLOT(groupingButtonClick()));
m_tree->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_tree, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(popupMenu(const QPoint &)));
// call this slot directly after the signal is received. just increment the update counter
connect(m_mantidUI, SIGNAL(workspace_renamed(QString,QString)), this, SLOT(recordWorkspaceRename(QString,QString)),Qt::DirectConnection);
// call this slot directly after the signal is received. just increment the update counter
connect(m_mantidUI, SIGNAL(ADS_updated()), this, SLOT(incrementUpdateCount()), Qt::DirectConnection);
// this slot is called when the GUI thread is free. decrement the counter. do nothing until the counter == 0
connect(m_mantidUI, SIGNAL(ADS_updated()), this, SLOT(updateTree()), Qt::QueuedConnection);
connect(m_mantidUI, SIGNAL(workspaces_cleared()), m_tree, SLOT(clear()),Qt::QueuedConnection);
connect(m_tree,SIGNAL(itemSelectionChanged()),this,SLOT(treeSelectionChanged()));
connect(m_tree, SIGNAL(itemExpanded(QTreeWidgetItem*)), this, SLOT(populateChildData(QTreeWidgetItem*)));
m_tree->setDragEnabled(true);
}
MantidDockWidget::~MantidDockWidget()
{
}
/** Returns the name of the selected workspace
* (the first one if more than one is selected)
*/
QString MantidDockWidget::getSelectedWorkspaceName() const
{
QList<QTreeWidgetItem*> items = m_tree->selectedItems();
QString str("");
if( !items.empty() )
{
QTreeWidgetItem *item = items[0];
if (item) str = item->text(0);
}
return str;
}
/// Returns a pointer to the selected workspace (the first if multiple workspaces selected)
Mantid::API::Workspace_sptr MantidDockWidget::getSelectedWorkspace() const
{
QString workspaceName = getSelectedWorkspaceName();
if (m_ads.doesExist(workspaceName.toStdString()))
{
return m_ads.retrieve(workspaceName.toStdString());
}
else
{
return Mantid::API::Workspace_sptr();
}
}
/**
* Create the action items associated with the dock
*/
void MantidDockWidget::createWorkspaceMenuActions()
{
m_showData = new QAction(tr("Show Data"),this);
connect(m_showData,SIGNAL(triggered()),m_mantidUI,SLOT(importWorkspace()));
m_showInst = new QAction(tr("Show Instrument"),this);
connect(m_showInst,SIGNAL(triggered()),m_mantidUI,SLOT(showMantidInstrumentSelected()));
m_plotSpec = new QAction(tr("Plot Spectrum..."),this);
connect(m_plotSpec,SIGNAL(triggered()),this,SLOT(plotSpectra()));
m_plotSpecErr = new QAction(tr("Plot Spectrum with Errors..."),this);
connect(m_plotSpecErr,SIGNAL(triggered()),this,SLOT(plotSpectraErr()));
m_plotSpecDistr = new QAction(tr("Plot spectrum as distribution..."),this);
connect(m_plotSpecDistr,SIGNAL(triggered()),this,SLOT(plotSpectraDistribution()));
m_colorFill = new QAction(tr("Color Fill Plot"), this);
connect(m_colorFill, SIGNAL(triggered()), this, SLOT(drawColorFillPlot()));
m_showDetectors = new QAction(tr("Show Detectors"),this);
connect(m_showDetectors,SIGNAL(activated()),this,SLOT(showDetectorTable()));
m_showBoxData = new QAction(tr("Show Box Data Table"),this);
connect(m_showBoxData,SIGNAL(activated()),m_mantidUI,SLOT(importBoxDataTable()));
m_showVatesGui = new QAction(tr("Show Vates Simple Interface"), this);
{ QIcon icon; icon.addFile(QString::fromUtf8(":/VatesSimpleGuiViewWidgets/icons/pvIcon.png"), QSize(), QIcon::Normal, QIcon::Off);
m_showVatesGui->setIcon(icon); }
connect(m_showVatesGui, SIGNAL(activated()), m_mantidUI, SLOT(showVatesSimpleInterface()));
m_showMDPlot = new QAction(tr("Plot MD"), this);
connect(m_showMDPlot, SIGNAL(activated()), m_mantidUI, SLOT(showMDPlot()));
m_showListData = new QAction(tr("List Data"), this);
connect(m_showListData, SIGNAL(activated()), m_mantidUI, SLOT(showListData()));
m_showSpectrumViewer = new QAction(tr("Show Spectrum Viewer"), this);
connect(m_showSpectrumViewer, SIGNAL(activated()), m_mantidUI, SLOT(showSpectrumViewer()));
m_showSliceViewer = new QAction(tr("Show Slice Viewer"), this);
{ QIcon icon; icon.addFile(QString::fromUtf8(":/SliceViewer/icons/SliceViewerWindow_icon.png"), QSize(), QIcon::Normal, QIcon::Off);
m_showSliceViewer->setIcon(icon); }
connect(m_showSliceViewer, SIGNAL(activated()), m_mantidUI, SLOT(showSliceViewer()));
m_showLogs = new QAction(tr("Sample Logs..."), this);
connect(m_showLogs,SIGNAL(triggered()),m_mantidUI,SLOT(showLogFileWindow()));
m_showHist = new QAction(tr("Show History"), this);
connect(m_showHist,SIGNAL(triggered()),m_mantidUI,SLOT(showAlgorithmHistory()));
m_saveNexus = new QAction(tr("Save Nexus"),this);
connect(m_saveNexus,SIGNAL(activated()),m_mantidUI,SLOT(saveNexusWorkspace()));
m_rename = new QAction(tr("Rename"),this);
connect(m_rename,SIGNAL(activated()),this,SLOT(renameWorkspace()));
m_delete = new QAction(tr("Delete"),this);
connect(m_delete,SIGNAL(triggered()),this,SLOT(deleteWorkspaces()));
m_showTransposed = new QAction(tr("Show Transposed"),this);
connect(m_showTransposed,SIGNAL(triggered()),m_mantidUI,SLOT(importTransposed()));
m_convertToMatrixWorkspace = new QAction(tr("Convert to MatrixWorkspace"),this);
m_convertToMatrixWorkspace->setIcon(QIcon(getQPixmap("mantid_matrix_xpm")));
connect(m_convertToMatrixWorkspace,SIGNAL(triggered()),this,SLOT(convertToMatrixWorkspace()));
m_convertMDHistoToMatrixWorkspace = new QAction(tr("Convert to MatrixWorkspace"),this);
m_convertMDHistoToMatrixWorkspace->setIcon(QIcon(getQPixmap("mantid_matrix_xpm")));
connect(m_convertMDHistoToMatrixWorkspace,SIGNAL(triggered()),this,SLOT(convertMDHistoToMatrixWorkspace()));
m_clearUB = new QAction(tr("Clear UB Matrix"), this);
connect(m_clearUB, SIGNAL(activated()), this, SLOT(clearUB()));
}
/**
* Create actions for sorting.
*/
void MantidDockWidget::createSortMenuActions()
{
chooseByName();
m_sortMenu = new QMenu(this);
QAction* m_ascendingSortAction = new QAction("Ascending", this);
QAction* m_descendingSortAction = new QAction("Descending", this);
QAction* m_byNameChoice = new QAction("Name", this);
QAction* m_byLastModifiedChoice = new QAction("Last Modified", this);
m_ascendingSortAction->setCheckable(true);
m_ascendingSortAction->setEnabled(true);
m_ascendingSortAction->setToggleAction(true);
m_descendingSortAction->setCheckable(true);
m_descendingSortAction->setEnabled(true);
m_descendingSortAction->setToggleAction(true);
QActionGroup *sortDirectionGroup = new QActionGroup(m_sortMenu);
sortDirectionGroup->addAction(m_ascendingSortAction);
sortDirectionGroup->addAction(m_descendingSortAction);
sortDirectionGroup->setExclusive(true);
m_ascendingSortAction->setChecked(true);
m_byNameChoice->setCheckable(true);
m_byNameChoice->setEnabled(true);
m_byNameChoice->setToggleAction(true);
m_byLastModifiedChoice->setCheckable(true);
m_byLastModifiedChoice->setEnabled(true);
m_byLastModifiedChoice->setToggleAction(true);
m_sortChoiceGroup = new QActionGroup(m_sortMenu);
m_sortChoiceGroup->addAction(m_byNameChoice);
m_sortChoiceGroup->addAction(m_byLastModifiedChoice);
m_sortChoiceGroup->setExclusive(true);
m_byNameChoice->setChecked(true);
connect(m_ascendingSortAction, SIGNAL(activated()), this, SLOT(sortAscending()));
connect(m_descendingSortAction, SIGNAL(activated()), this, SLOT(sortDescending()));
connect(m_byNameChoice, SIGNAL(activated()), this, SLOT(chooseByName()));
connect(m_byLastModifiedChoice, SIGNAL(activated()), this, SLOT(chooseByLastModified()));
m_sortMenu->addActions(sortDirectionGroup->actions());
m_sortMenu->addSeparator();
m_sortMenu->addActions(m_sortChoiceGroup->actions());
m_sortButton->setMenu(m_sortMenu);
}
/**
* When an item is expanded, populate the child data for this item
* @param item :: The item being expanded
*/
void MantidDockWidget::populateChildData(QTreeWidgetItem* item)
{
QVariant userData = item->data(0, Qt::UserRole);
if ( userData.isNull() ) return;
// Clear it first
while( item->childCount() > 0 )
{
auto * widgetItem = item->takeChild(0);
delete widgetItem;
}
Workspace_sptr workspace = userData.value<Workspace_sptr>();
if(auto group = boost::dynamic_pointer_cast<WorkspaceGroup>(workspace))
{
const size_t nmembers = group->getNumberOfEntries();
for(size_t i = 0; i < nmembers; ++i)
{
auto ws = group->getItem(i);
auto * node = addTreeEntry(std::make_pair(ws->name(), ws), item);
excludeItemFromSort(node);
if (shouldBeSelected(node->text(0))) node->setSelected(true);
}
}
else
{
QString details;
try
{
details = workspace->toString().c_str();
}
catch(std::runtime_error& e)
{
details = QString("Error: %1").arg(e.what());
}
QStringList rows = details.split(QLatin1Char('\n'), QString::SkipEmptyParts);
rows.append(QString("Memory used: ") + workspace->getMemorySizeAsStr().c_str());
auto iend = rows.constEnd();
for(auto itr = rows.constBegin(); itr != iend; ++itr)
{
MantidTreeWidgetItem *data = new MantidTreeWidgetItem(QStringList(*itr), m_tree);
data->setFlags(Qt::NoItemFlags);
excludeItemFromSort(data);
item->addChild(data);
}
}
}
/**
* Set tree item's icon based on the ID of the workspace.
* @param item :: A workspace tree item.
* @param wsID :: An icon type code.
*/
void MantidDockWidget::setItemIcon(QTreeWidgetItem *item, const std::string & wsID)
{
try
{
item->setIcon(0, QIcon(WORKSPACE_ICONS.getIcon(wsID)));
}
catch(std::runtime_error&)
{
docklog.warning() << "Cannot find icon for workspace ID '" << wsID << "'\n";
}
}
/**
* Update the workspace tree to match the current state of the ADS.
* It is important that the workspace tree is modified only by this method.
*/
void MantidDockWidget::updateTree()
{
// do not update until the counter is zero
if ( m_updateCount.deref() ) return;
// find all expanded top-level entries
QStringList expanded;
int n = m_tree->topLevelItemCount();
for(int i = 0; i < n; ++i)
{
auto item = m_tree->topLevelItem(i);
if ( item->isExpanded() )
{
expanded << item->text(0);
}
}
// create a new tree
setTreeUpdating(true);
populateTopLevel(m_ads.topLevelItems(), expanded);
setTreeUpdating(false);
// Re-sort
m_tree->sort();
}
/**
* Slot to be connected directly to ADS_updated signal. Increase m_updateCount and return.
*/
void MantidDockWidget::incrementUpdateCount()
{
m_updateCount.ref();
}
/**
* Save the old and the new name in m_renameMap. This is needed to restore selection
* of the renamed workspace (if it was selected before renaming).
* @param old_name :: Old name of a renamed workspace.
* @param new_name :: New name of a renamed workspace.
*/
void MantidDockWidget::recordWorkspaceRename(QString old_name, QString new_name)
{
// check if old_name has been recently a new name
QList<QString> oldNames = m_renameMap.keys(old_name);
// non-empty list of oldNames become new_name
if ( !oldNames.isEmpty() )
{
foreach(QString name, oldNames)
{
m_renameMap[name] = new_name;
}
}
else
{
// record a new rename pair
m_renameMap[old_name] = new_name;
}
}
/**
* Flips the flag indicating whether a tree update is in progress. Actions such as sorting
* are disabled while an update is in progress.
* @param state The required state for the flag
*/
void MantidDockWidget::setTreeUpdating(const bool state)
{
m_treeUpdating = state;
}
/**
* Clears the tree and re-populates it with the given top level items
* @param topLevelItems The map of names to workspaces
* @param expanded Names of items who should expanded after being populated
*/
void MantidDockWidget::populateTopLevel(const std::map<std::string,Mantid::API::Workspace_sptr> & topLevelItems,
const QStringList & expanded)
{
// collect names of selected workspaces
QList<QTreeWidgetItem *> selected = m_tree->selectedItems();
m_selectedNames.clear(); // just in case
foreach( QTreeWidgetItem *item, selected)
{
m_selectedNames << item->text(0);
}
// populate the tree from scratch
m_tree->clear();
auto iend = topLevelItems.end();
for(auto it = topLevelItems.begin(); it != iend; ++it)
{
auto *node = addTreeEntry(*it);
QString name = node->text(0);
if(expanded.contains(name)) node->setExpanded(true);
// see if item must be selected
if ( shouldBeSelected(name) ) node->setSelected(true);
}
m_selectedNames.clear();
m_renameMap.clear();
}
/**
* Adds a node for the given named item, including a single child ID item to make each node have a expandable button
* and allowing plotting to work from non-expanded items
* @param item A name/workspace pair to add.
* @param parent If not null then add the new items as a child of the given item
*/
MantidTreeWidgetItem * MantidDockWidget::addTreeEntry(const std::pair<std::string,Mantid::API::Workspace_sptr> & item, QTreeWidgetItem* parent)
{
MantidTreeWidgetItem *node = new MantidTreeWidgetItem(QStringList(item.first.c_str()), m_tree);
node->setData(0,Qt::UserRole, QVariant::fromValue(item.second));
// A a child ID item so that it becomes expandable. Using the correct ID is needed when plotting from non-expanded groups.
const std::string wsID = item.second->id();
MantidTreeWidgetItem *idNode = new MantidTreeWidgetItem(QStringList(wsID.c_str()), m_tree);
idNode->setFlags(Qt::NoItemFlags);
node->addChild(idNode);
setItemIcon(node,wsID);
if(parent)
{
parent->addChild(node);
}
else
{
m_tree->addTopLevelItem(node);
}
return node;
}
/**
* Check if a workspace should be selected after dock update.
* @param name :: Name of a workspace to check.
*/
bool MantidDockWidget::shouldBeSelected(QString name) const
{
QStringList renamed = m_renameMap.keys(name);
if ( !renamed.isEmpty() )
{
foreach(QString oldName,renamed)
{
if ( m_selectedNames.contains(oldName) )
{
return true;
}
}
}
else if(m_selectedNames.contains(name))
{
return true;
}
return false;
}
/**
* Add the actions that are appropriate for a MatrixWorkspace
* @param menu :: The menu to store the items
* @param matrixWS :: The workspace related to the menu
*/
void MantidDockWidget::addMatrixWorkspaceMenuItems(QMenu *menu, const Mantid::API::MatrixWorkspace_const_sptr & matrixWS) const
{
// Add all options except plot of we only have 1 value
menu->addAction(m_showData);
menu->addAction(m_showInst);
// Disable the 'show instrument' option if a workspace doesn't have an instrument attached
m_showInst->setEnabled( matrixWS->getInstrument() && !matrixWS->getInstrument()->getName().empty() );
menu->addSeparator();
menu->addAction(m_plotSpec);
menu->addAction(m_plotSpecErr);
// Don't plot a spectrum if only one X value
m_plotSpec->setEnabled ( matrixWS->blocksize() > 1 );
m_plotSpecErr->setEnabled ( matrixWS->blocksize() > 1 );
menu->addAction(m_showSpectrumViewer); // The 2D spectrum viewer
menu->addAction(m_colorFill);
// Show the color fill plot if you have more than one histogram
m_colorFill->setEnabled( ( matrixWS->axes() > 1 && matrixWS->getNumberHistograms() > 1) );
menu->addAction(m_showSliceViewer); // The 2D slice viewer
menu->addSeparator();
menu->addAction(m_showDetectors);
menu->addAction(m_showLogs);
menu->addAction(m_showHist);
menu->addAction(m_saveNexus);
}
/**
* Add the actions that are appropriate for a MDEventWorkspace
* @param menu :: The menu to store the items
* @param WS :: The workspace related to the menu
*/
void MantidDockWidget::addMDEventWorkspaceMenuItems(QMenu *menu, const Mantid::API::IMDEventWorkspace_const_sptr & WS) const
{
Q_UNUSED(WS);
//menu->addAction(m_showBoxData); // Show MD Box data (for debugging only)
menu->addAction(m_showVatesGui); // Show the Vates simple interface
if (!MantidQt::API::InterfaceManager::hasVatesLibraries())
{
m_showVatesGui->setEnabled(false);
}
else
{
std::size_t nDim = WS->getNonIntegratedDimensions().size();
m_showVatesGui->setEnabled(nDim >= 3 && nDim < 5);
}
menu->addAction(m_showSliceViewer); // The 2D slice viewer
menu->addAction(m_showHist); // Algorithm history
menu->addAction(m_showListData); // Show data in table
menu->addAction(m_showLogs);
}
void MantidDockWidget::addMDHistoWorkspaceMenuItems(QMenu *menu, const Mantid::API::IMDWorkspace_const_sptr &WS) const
{
Q_UNUSED(WS);
menu->addAction(m_showHist); // Algorithm history
menu->addAction(m_showVatesGui); // Show the Vates simple interface
if (!MantidQt::API::InterfaceManager::hasVatesLibraries())
{
m_showVatesGui->setEnabled(false);
}
else
{
std::size_t nDim = WS->getNonIntegratedDimensions().size();
m_showVatesGui->setEnabled(nDim >= 3 && nDim < 5);
}
menu->addAction(m_showSliceViewer); // The 2D slice viewer
menu->addAction(m_showMDPlot); // A plot of intensity vs bins
menu->addAction(m_showListData); // Show data in table
menu->addAction(m_convertMDHistoToMatrixWorkspace);
menu->addAction(m_showLogs);
}
/** Add the actions that are appropriate for a PeaksWorkspace
* @param menu :: The menu to store the items
* @param WS :: The workspace related to the menu
*/
void MantidDockWidget::addPeaksWorkspaceMenuItems(QMenu *menu, const Mantid::API::IPeaksWorkspace_const_sptr &WS) const
{
Q_UNUSED(WS);
menu->addAction(m_showData);
menu->addAction(m_showVatesGui); // Show the Vates simple interface
if (!MantidQt::API::InterfaceManager::hasVatesLibraries())
{
m_showVatesGui->setEnabled(false);
}
menu->addSeparator();
menu->addAction(m_showDetectors);
menu->addAction(m_showHist);
}
/**
* Add the actions that are appropriate for a MatrixWorkspace
* @param menu :: The menu to store the items
*/
void MantidDockWidget::addWorkspaceGroupMenuItems(QMenu *menu) const
{
m_plotSpec->setEnabled(true);
menu->addAction(m_plotSpec);
m_plotSpecErr->setEnabled(true);
menu->addAction(m_plotSpecErr);
menu->addAction(m_colorFill);
m_colorFill->setEnabled(true);
menu->addSeparator();
menu->addAction(m_saveNexus);
}
/**
* Add the actions that are appropriate for a MatrixWorkspace
* @param menu :: The menu to store the items
*/
void MantidDockWidget::addTableWorkspaceMenuItems(QMenu * menu) const
{
menu->addAction(m_showData);
menu->addAction(m_showTransposed);
menu->addAction(m_showHist);
menu->addAction(m_saveNexus);
menu->addAction(m_convertToMatrixWorkspace);
}
/**
* Add menu for clearing workspace items.
* @param menu : Parent menu.
* @param wsName : Name of the selected workspace.
*/
void MantidDockWidget::addClearMenuItems(QMenu* menu, const QString& wsName)
{
QMenu* clearMenu = new QMenu(tr("Clear Options"), this);
m_clearUB->setEnabled( m_mantidUI->hasUB(wsName) );
clearMenu->addAction(m_clearUB);
menu->addMenu(clearMenu);
}
void MantidDockWidget::clickedWorkspace(QTreeWidgetItem* item, int)
{
Q_UNUSED(item);
}
void MantidDockWidget::workspaceSelected()
{
QList<QTreeWidgetItem*> selectedItems=m_tree->selectedItems();
if(selectedItems.isEmpty()) return;
QString wsName=selectedItems[0]->text(0);
if(m_ads.doesExist(wsName.toStdString()))
{
m_mantidUI->enableSaveNexus(wsName);
}
}
/**
* Save all selected workspaces
*/
void MantidDockWidget::saveWorkspaces()
{
QList<QTreeWidgetItem*> items = m_tree->selectedItems();
if(items.empty())
return;
// Call same save asction as popup menu for a single workspace
if(items.size() == 1)
{
m_mantidUI->saveNexusWorkspace();
}
else
{
m_saveFolderDialog->open(this, SLOT(saveWorkspacesToFolder(const QString &)));
}
}
/**
* Handler for the directory browser being closed when selecting save on multiple workspaces
*
* @param folder Path to folder to save workspaces in
*/
void MantidDockWidget::saveWorkspacesToFolder(const QString &folder)
{
QList<QTreeWidgetItem*> items = m_tree->selectedItems();
// Loop through multiple items selected from the mantid tree
QList<QTreeWidgetItem*>::iterator itr=items.begin();
for (itr = items.begin(); itr != items.end(); ++itr)
{
QString workspaceName = (*itr)->text(0);
QString filename = folder + "/" + workspaceName + ".nxs";
IAlgorithm_sptr saveAlg = AlgorithmManager::Instance().create("SaveNexus");
saveAlg->initialize();
saveAlg->setProperty("InputWorkspace", workspaceName.toStdString());
saveAlg->setProperty("Filename", filename.toStdString());
saveAlg->execute();
}
}
/**
deleteWorkspaces
*/
void MantidDockWidget::deleteWorkspaces()
{
QList<QTreeWidgetItem*> items = m_tree->selectedItems();
if(items.empty())
{
MantidMatrix* m = dynamic_cast<MantidMatrix*>(m_mantidUI->appWindow()->activeWindow());
if (!m || !m->isA("MantidMatrix")) return;
if(m->workspaceName().isEmpty()) return;
if(m_ads.doesExist(m->workspaceName().toStdString()))
{
m_mantidUI->deleteWorkspace(m->workspaceName());
}
return;
}
//loop through multiple items selected from the mantid tree
QList<QTreeWidgetItem*>::iterator itr=items.begin();
for (itr = items.begin(); itr != items.end(); ++itr)
{
m_mantidUI->deleteWorkspace((*itr)->text(0));
}//end of for loop for selected items
}
void MantidDockWidget::sortAscending()
{
if(isTreeUpdating()) return;
m_tree->setSortOrder(Qt::Ascending);
m_tree->sort();
}
void MantidDockWidget::sortDescending()
{
if(isTreeUpdating()) return;
m_tree->setSortOrder(Qt::Descending);
m_tree->sort();
}
void MantidDockWidget::chooseByName()
{
if(isTreeUpdating()) return;
m_tree->setSortScheme(ByName);
m_tree->sort();
}
void MantidDockWidget::chooseByLastModified()
{
if(isTreeUpdating()) return;
m_tree->setSortScheme(ByLastModified);
m_tree->sort();
}
void MantidDockWidget::excludeItemFromSort(MantidTreeWidgetItem *item)
{
static int counter = 1;
item->setSortPos( counter );
counter++;
}
/**
* Saves a workspace based on the program the user chooses to save to.
* @param name :: A string containing the name of the program
*/
void MantidDockWidget::saveToProgram(const QString & name)
{
//Create a map for the keys and details to go into
std::map<std::string,std::string> programKeysAndDetails;
programKeysAndDetails["name"] = name.toStdString();
//Get a list of the program detail keys (mandatory - target, saveusing) (optional - arguments, save parameters, workspace type)
std::vector<std::string> programKeys = (Mantid::Kernel::ConfigService::Instance().getKeys(("workspace.sendto." + programKeysAndDetails.find("name")->second)));
for (size_t i=0; i<programKeys.size(); i++)
{
//Assign a key to its value using the map
programKeysAndDetails[programKeys[i]] = (Mantid::Kernel::ConfigService::Instance().getString(("workspace.sendto." + programKeysAndDetails.find("name")->second + "." + programKeys[i])));
}
//Check to see if mandatory information is included
if ((programKeysAndDetails.count("name") != 0) && (programKeysAndDetails.count("target") != 0) && (programKeysAndDetails.count("saveusing") != 0))
{
std::string expTarget = Poco::Path::expand(programKeysAndDetails.find("target")->second);
QFileInfo target = QString::fromStdString(expTarget);
if(target.exists())
{
try
{
//Setup a shared pointer for the algorithm using the appropriate save type
Mantid::API::IAlgorithm_sptr alg;
//Convert to QString and create Algorithm
QString saveUsing = QString::fromStdString(programKeysAndDetails.find("saveusing")->second);
//Create a new save based on what files the new program can open
alg = m_mantidUI->createAlgorithm(saveUsing);
//Get the file extention based on the workspace
Property* prop = alg->getProperty("Filename");
FileProperty *fileProp = dynamic_cast<FileProperty*>(prop);
std::string ext;
if(fileProp)
{
ext = fileProp->getDefaultExt();
}
//Save as.. default save + the file type i.e .nxs
alg->setPropertyValue("fileName", "auto_save_" + selectedWsName.toStdString() + ext);
//Save the workspace
alg->setPropertyValue("InputWorkspace", selectedWsName.toStdString());
//If there are any save parameters
if (programKeysAndDetails.count("saveparameters") != 0)
{
QString saveParametersGrouped = QString::fromStdString(programKeysAndDetails.find("saveparameters")->second);
QStringList saveParameters = saveParametersGrouped.split(',');
//For each one found split it up and assign the parameter
for (int i = 0; i<saveParameters.size(); i++)
{
QStringList sPNameAndDetail = saveParameters[i].split('=');
std::string saveParameterName = sPNameAndDetail[0].trimmed().toStdString();
std::string saveParameterDetail = sPNameAndDetail[1].trimmed().toStdString();
if(saveParameterDetail == "True")
alg->setProperty(saveParameterName, true);
else if(saveParameterDetail == "False")
alg->setProperty(saveParameterName, false);
else //if not true or false then must be a value
{
alg->setPropertyValue(saveParameterName, saveParameterDetail);
}
}
}
//Execute the save
m_mantidUI->executeAlgorithmAsync(alg, true);
//alg->execute();
//Get the save location of the file (should be default Mantid folder)
//std::string savedFile = alg->getProperty("Filename");
QString savedFile = QString::fromStdString(alg->getProperty("Filename"));
QStringList arguments;
//Arguments for the program to take. Default will be the file anyway.
if (programKeysAndDetails.count("arguments") != 0)
{
QString temp = QString::fromStdString(programKeysAndDetails.find("arguments")->second);
temp.replace(QString("[file]"), savedFile);
//temp.replace(QString("[user]"), user;
arguments = temp.split(",");
}
else
arguments.insert(0, savedFile);
//convert the list into a standard vector for compatibility with Poco
std::vector<std::string> argumentsV;
for (int i = 0; i<arguments.size(); i++)
{
argumentsV.assign(1, (arguments[i].toStdString()));
}
//Execute the program
try
{
Mantid::Kernel::ConfigService::Instance().launchProcess(expTarget, argumentsV);
}
catch(std::runtime_error&)
{
QMessageBox::information(this, "Error", "User tried to open program from: " + QString::fromStdString(expTarget) + " There was an error opening the program. Please check the target and arguments list to ensure that these are correct");
}
}
catch(std::exception&)
{
QMessageBox::information(this, "Mantid - Send to Program", "A file property wasn't found. Please check that the correct"
+ QString("save algorithm was used.\n(View -> Preferences -> Mantid -> SendTo -> Edit -> SaveUsing)") );
}
}
else
QMessageBox::information(this, "Target Path Error", "User tried to open program from: " + QString::fromStdString(expTarget) + " The target file path for the program can't be found. Please check that the full path is correct");
}
}
void MantidDockWidget::renameWorkspace()
{
//get selected workspace
QList<QTreeWidgetItem*>selectedItems=m_tree->selectedItems();
QStringList selctedwsNames;
if(!selectedItems.empty())
{
for(int i=0; i < selectedItems.size(); ++i)
{
selctedwsNames.append(selectedItems[i]->text(0));
}
}
m_mantidUI->renameWorkspace(selctedwsNames);
}
void MantidDockWidget::showDetectorTable()
{
//get selected workspace
QList<QTreeWidgetItem*>selectedItems=m_tree->selectedItems();
QString selctedwsName;
if(!selectedItems.empty())
{
selctedwsName=selectedItems[0]->text(0);
}
m_mantidUI->createDetectorTable(selctedwsName,std::vector<int>());
}
void MantidDockWidget::popupMenu(const QPoint & pos)
{
QTreeWidgetItem* treeItem = m_tree->itemAt(pos);
selectedWsName = "";
if( treeItem ) selectedWsName = treeItem->text(0);
else m_tree->selectionModel()->clear();
QMenu *menu(NULL);
//If no workspace is here then have load raw and dae
if( selectedWsName.isEmpty() )
{
menu = m_loadMenu;
}
//else show instrument, sample logs and delete
else
{
// Fresh menu
menu = new QMenu(this);
menu->setObjectName("WorkspaceContextMenu");
Mantid::API::Workspace_const_sptr ws;
try
{
ws = m_ads.retrieve(selectedWsName.toStdString());
}
catch(Mantid::Kernel::Exception::NotFoundError &)
{
// Nothing to do
return;
}
// Add the items that are appropriate for the type
if( MatrixWorkspace_const_sptr matrixWS = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(ws) )
{
addMatrixWorkspaceMenuItems(menu, matrixWS);
}
else if( IMDEventWorkspace_const_sptr mdeventWS = boost::dynamic_pointer_cast<const IMDEventWorkspace>(ws) )
{
addMDEventWorkspaceMenuItems(menu, mdeventWS);
}
else if( IMDWorkspace_const_sptr mdWS = boost::dynamic_pointer_cast<const IMDWorkspace>(ws) )
{
addMDHistoWorkspaceMenuItems(menu, mdWS);
}
else if( IPeaksWorkspace_const_sptr peaksWS = boost::dynamic_pointer_cast<const IPeaksWorkspace>(ws) )
{
addPeaksWorkspaceMenuItems(menu, peaksWS);
}
else if( boost::dynamic_pointer_cast<const WorkspaceGroup>(ws) )
{
addWorkspaceGroupMenuItems(menu);
}
else if( boost::dynamic_pointer_cast<const Mantid::API::ITableWorkspace>(ws) )
{
addTableWorkspaceMenuItems(menu);
}
addClearMenuItems(menu, selectedWsName);
//Get the names of the programs for the send to option
std::vector<std::string> programNames = (Mantid::Kernel::ConfigService::Instance().getKeys("workspace.sendto.name"));
bool firstPass(true);
//Check to see if any options aren't visible
for (size_t i = 0; i<programNames.size(); i++)
{
std::string visible = Mantid::Kernel::ConfigService::Instance().getString("workspace.sendto." + programNames[i] + ".visible");
std::string target = Mantid::Kernel::ConfigService::Instance().getString("workspace.sendto." + programNames[i] + ".target");
if (Mantid::Kernel::ConfigService::Instance().isExecutable(target) && visible == "Yes")
{
bool compatible(true);
std::string saveUsing(Mantid::Kernel::ConfigService::Instance().getString("workspace.sendto." + programNames[i] + ".saveusing") );
try
{
Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create(saveUsing);