]> Creatis software - clitk.git/blob - vv/vvToolROIManager.cxx
Correct Bounds in Input Contour Mapper
[clitk.git] / vv / vvToolROIManager.cxx
1 /*=========================================================================
2   Program:   vv                     http://www.creatis.insa-lyon.fr/rio/vv
3
4   Authors belong to:
5   - University of LYON              http://www.universite-lyon.fr/
6   - Léon Bérard cancer center       http://www.centreleonberard.fr
7   - CREATIS CNRS laboratory         http://www.creatis.insa-lyon.fr
8
9   This software is distributed WITHOUT ANY WARRANTY; without even
10   the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11   PURPOSE.  See the copyright notices for more information.
12
13   It is distributed under dual licence
14
15   - BSD        See included LICENSE.txt file
16   - CeCILL-B   http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
17   ===========================================================================**/
18
19 // vv
20 #include "vvToolROIManager.h"
21 #include "vvImageReader.h"
22 #include "vvImageWriter.h"
23 #include "vvROIActor.h"
24 #include "vvSlicer.h"
25 #include "vvMeshReader.h"
26 #include "vvStructSelector.h"
27 #include "vvToolManager.h"
28 #include "vvProgressDialog.h"
29
30 // clitk
31 #include "clitkDicomRTStruct2ImageFilter.h"
32 #include "clitkDicomRT_StructureSet.h"
33
34 // Qt
35 #include <QFileDialog>
36 #include <QMessageBox>
37 #include <QColorDialog>
38 #include <QAbstractEventDispatcher>
39 #include <QXmlStreamReader>
40
41 // vtk
42 #include <vtkLookupTable.h>
43 #include <vtkRenderWindow.h>
44
45 //------------------------------------------------------------------------------
46 // Create the tool and automagically (I like this word) insert it in
47 // the main window menu.
48 ADD_TOOL(vvToolROIManager);
49 //------------------------------------------------------------------------------
50
51 //------------------------------------------------------------------------------
52 vvToolROIManager::vvToolROIManager(vvMainWindowBase * parent, Qt::WindowFlags f):
53   QWidget(parent->GetTab()),
54   vvToolBase<vvToolROIManager>(parent),
55   Ui::vvToolROIManager()
56 { //out << __func__ << endl;
57   // Store parent
58   mMainWindow = parent;
59
60   // Assume the initial tab ROI index is 2
61   mIndexFirstTab = 2;
62
63   // Build the UI
64   Ui_vvToolROIManager::setupUi(this);
65   setAttribute(Qt::WA_DeleteOnClose);
66   mTree->clear();
67   mTree->header()->resizeSection(0, 30);
68   mGroupBoxROI->setEnabled(false);
69
70   // Disable "Load dicom" button -> not useful
71   frame_4->hide();
72
73   // Set default LUT
74   mDefaultLUTColor = vtkSmartPointer<vtkLookupTable>::New();
75   for(int i=0; i<mDefaultLUTColor->GetNumberOfTableValues(); i++) {
76     double r = (rand()/(RAND_MAX+1.0));
77     double v = (rand()/(RAND_MAX+1.0));
78     double b = (rand()/(RAND_MAX+1.0));
79     mDefaultLUTColor->SetTableValue(i, r, v, b);
80   }
81 #include "vvDefaultLut.h"
82
83   // Initialization
84   mCurrentSlicerManager = NULL;
85   mNumberOfVisibleROI = 0;
86   mNumberOfVisibleContourROI = 0;
87   mOpenFileBrowserFlag = true; // by default, open the file browser when the tool is launched
88
89   // InitializeNewTool must be called to start
90 }
91 //------------------------------------------------------------------------------
92
93
94 //------------------------------------------------------------------------------
95 vvToolROIManager::~vvToolROIManager()
96 { //out << __func__ << endl;
97   mROIActorsList.clear();
98 }
99 //------------------------------------------------------------------------------
100
101
102 //------------------------------------------------------------------------------
103 // STATIC
104 void vvToolROIManager::Initialize()
105 { //out << __func__ << endl;
106   SetToolName("ROIManager");
107   SetToolMenuName("Open ROI (binary image or RT-STRUCT)");
108   SetToolIconFilename(":/common/icons/tool-roi.png");
109   SetToolTip("Display ROI from a binary image or a RT-struct file.");
110   SetToolExperimental(false);
111 }
112 //------------------------------------------------------------------------------
113
114
115
116 //------------------------------------------------------------------------------
117 void  vvToolROIManager::InitializeNewTool(bool ReadStateFlag)
118 { //out << __func__ << endl;
119   // Check if we need to start a new tool or read in the state file to load
120   if (ReadStateFlag == false) {
121     // Select the current image as the target
122     int i = mMainWindow->GetSlicerManagerCurrentIndex();
123     mCurrentSlicerManager = mMainWindow->GetSlicerManagers()[i];
124     // Set it as current (only if not ReadStateFlag)
125     mMainWindow->GetTab()->setCurrentIndex(mIndexFirstTab);
126   }
127   else {
128     // Set the first tab in front to avoid displaying two roimanager
129     // in the same tab. Because toolcreatorBase do show() and I am too
130     // lazy to find another solution now.
131     mMainWindow->GetTab()->setCurrentIndex(0);
132
133     // Read all information in the XML
134     ReadXMLInformation();
135
136     // Check that a ROI is not already present
137     mInitialImageIndex += mImageIndex;
138     if (mInitialImageIndex >= mMainWindow->GetSlicerManagers().size()) {
139       QMessageBox::warning(this, "ROIManager tool", QString("Image index %1 not found, abort.").arg(mInitialImageIndex));
140       close();
141       return;
142     }
143
144     // Set the attached image
145     mCurrentSlicerManager = mMainWindow->GetSlicerManagers()[mInitialImageIndex];
146   }
147
148   // Tab insertion, check that another tool does not already exist for this image
149   std::vector<vvToolBaseBase*> & tools =
150     vvToolManager::GetInstance()->GetToolCreatorFromName(GetToolName())->GetListOfTool();
151   if (tools.size() > 0) {
152     for(uint i=0; i<tools.size()-1; i++) { // current tool is last
153       vvToolROIManager * t = dynamic_cast<vvToolROIManager*>(tools[i]);
154       if (mCurrentSlicerManager == t->GetCurrentSlicerManager()) {
155         QMessageBox::warning(this, "ROIManager tool", "Already a ROI for this image, abort.");
156         close();
157         return;
158       }
159     }
160   }
161
162   // Display tool in the correct tab
163   QWidget * tab = mMainWindow->GetTab()->findChild<QWidget*>("ROItab");
164   tab->layout()->addWidget(this);
165
166   // If not read in a file we start automatically the browser to load
167   // a roi file (binary image)
168   if (ReadStateFlag) {
169     mOpenFileBrowserFlag = false;
170     InputIsSelected(mCurrentSlicerManager);
171     mOpenFileBrowserFlag = true;
172   }
173   else InputIsSelected(mCurrentSlicerManager);
174
175   // Load ROI (if read in the XML files, empty otherwise)
176   OpenBinaryImage(mROIFilenames);
177
178   // Set the options to the open roi
179   for(uint i=0; i<mROIActorsParamList.size(); i++) {
180     QSharedPointer<vvROIActor> roi = mROIActorsList[i];
181     QSharedPointer<vvROIActor> roi_param = mROIActorsParamList[i];
182     roi->CopyParameters(roi_param);
183
184     // Update Tree
185     QTreeWidgetItem * w = mMapROIToTreeWidget[roi->GetROI()];
186     QBrush brush(QColor(roi->GetROI()->GetDisplayColor()[0]*255,
187                         roi->GetROI()->GetDisplayColor()[1]*255,
188                         roi->GetROI()->GetDisplayColor()[2]*255));
189     brush.setStyle(Qt::SolidPattern);
190     w->setBackground(2, brush);
191     w->setText(3, QString("%1").arg(roi->GetDepth()));
192     roi->UpdateColor();
193   }
194
195   // Display the ROI
196   UpdateAllContours();
197   UpdateAllROIStatus();
198
199   // Connect event from mainwindow to this widget
200   connect(mMainWindow, SIGNAL(AnImageIsBeingClosed(vvSlicerManager *)),
201           this, SLOT(AnImageIsBeingClosed(vvSlicerManager *)));
202   connect(mMainWindow, SIGNAL(SelectedImageHasChanged(vvSlicerManager *)),
203           this, SLOT(SelectedImageHasChanged(vvSlicerManager *)));
204   connect(mOpenBinaryButton, SIGNAL(clicked()), this, SLOT(Open()));
205   //  connect(mOpenDicomButton, SIGNAL(clicked()), this, SLOT(OpenDicomImage()));
206   connect(mTree, SIGNAL(itemSelectionChanged()), this, SLOT(SelectedItemChangedInTree()));
207   connect(mCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleROIToggled(bool)));
208   connect(mOpacitySlider, SIGNAL(valueChanged(int)), this, SLOT(OpacityChanged(int)));
209   connect(mChangeColorButton, SIGNAL(clicked()), this, SLOT(ChangeColor()));
210   connect(mContourCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleContourROIToggled(bool)));
211   connect(mChangeContourColorButton, SIGNAL(clicked()), this, SLOT(ChangeContourColor()));
212   connect(mContourWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeContourWidth(int)));
213   connect(mDepthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeDepth(int)));
214   connect(mReloadButton, SIGNAL(clicked()), this, SLOT(ReloadCurrentROI()));
215   connect(mCheckBoxShowAll, SIGNAL(stateChanged(int)), this, SLOT(AllVisibleROIToggled(int)));
216   connect(mContourCheckBoxShowAll, SIGNAL(toggled(bool)), this, SLOT(AllVisibleContourROIToggled(bool)));
217   connect(mCloseButton, SIGNAL(clicked()), this, SLOT(close()));
218 }
219 //------------------------------------------------------------------------------
220
221
222 //------------------------------------------------------------------------------
223 void vvToolROIManager::InputIsSelected(vvSlicerManager *m)
224 { //out << __func__ << endl;
225   // Initialization
226   mCurrentSlicerManager = m;
227   mCurrentImage = mCurrentSlicerManager->GetImage();
228
229   // Refuse if non 3D image
230   if (mCurrentImage->GetNumberOfDimensions() != 3) {
231     QMessageBox::information(this,tr("Warning"), tr("Warning 3D ROI on a 4D image will results in some display bugs"));
232     //close();
233     //return;
234   }
235
236   // Change gui
237   mLabelInputInfo->setText(QString("%1").arg(m->GetFileName().c_str()));
238
239   // Auto display browser to select new contours
240   if (mOpenFileBrowserFlag) Open();
241 }
242 //------------------------------------------------------------------------------
243
244
245 //------------------------------------------------------------------------------
246 void vvToolROIManager::AnImageIsBeingClosed(vvSlicerManager * m)
247 { //out << __func__ << endl;
248   if (m == mCurrentSlicerManager) {
249     close();
250     return;
251   }
252 }
253 //------------------------------------------------------------------------------
254
255
256 //------------------------------------------------------------------------------
257 void vvToolROIManager::close()
258 { //out << __func__ << endl;
259   disconnect(mTree, SIGNAL(itemSelectionChanged()), this, SLOT(SelectedItemChangedInTree()));
260   disconnect(mCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleROIToggled(bool)));
261   disconnect(mOpacitySlider, SIGNAL(valueChanged(int)), this, SLOT(OpacityChanged(int)));
262   disconnect(mChangeColorButton, SIGNAL(clicked()), this, SLOT(ChangeColor()));
263   disconnect(mContourCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleContourROIToggled(bool)));
264   disconnect(mChangeContourColorButton, SIGNAL(clicked()), this, SLOT(ChangeContourColor()));
265   disconnect(mContourWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeContourWidth(int)));
266   disconnect(mDepthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeDepth(int)));
267
268   // Remove actors
269   for (unsigned int i = 0; i < mROIActorsList.size(); i++) {
270     mROIActorsList[i]->RemoveActors();
271   }
272   mROIActorsList.clear();
273
274   QWidget::close();
275   for(int i=0; i<mCurrentSlicerManager->GetNumberOfSlicers(); i++) {
276     mCurrentSlicerManager->GetSlicer(i)->Render();
277   }
278 }
279 //------------------------------------------------------------------------------
280
281
282 //------------------------------------------------------------------------------
283 void vvToolROIManager::SelectedImageHasChanged(vvSlicerManager * m)
284 { //out << __func__ << endl;
285   if (mCurrentSlicerManager == NULL) return;
286   if (m == NULL) return;
287   if (m != mCurrentSlicerManager) hide();
288   else {
289     show();
290   }
291 }
292 //------------------------------------------------------------------------------
293
294
295 //------------------------------------------------------------------------------
296 void vvToolROIManager::Open()
297 { //out << __func__ << endl;
298   // Open images
299   QString Extensions = "Images or Dicom-Struct files ( *.mha *.mhd *.hdr *.his *.dcm RS*)";
300   Extensions += ";;All Files (*)";
301   QStringList filename =
302     QFileDialog::getOpenFileNames(this,tr("Open binary image or DICOM RT Struct"),
303                                   mMainWindowBase->GetInputPathName(),Extensions);
304   if (filename.size() == 0) return;
305   if (filename.size() > 1) { OpenBinaryImage(filename); return; }
306
307   // Try to read dicom rt ?
308   clitk::DicomRT_StructureSet::Pointer s = clitk::DicomRT_StructureSet::New();
309   if (s->IsDicomRTStruct(filename[0].toStdString())) OpenDicomImage(filename[0].toStdString());
310   else OpenBinaryImage(filename);
311
312 }
313 //------------------------------------------------------------------------------
314
315
316 //------------------------------------------------------------------------------
317 void vvToolROIManager::OpenBinaryImage(QStringList & filename)
318 { //out << __func__ << endl;
319   if (filename.size() == 0) return;
320
321   vvProgressDialog p("Reading ROI ...", true);
322   p.SetCancelButtonEnabled(false);
323   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
324
325   // For each selected file, open the image
326   for(int i=0; i<filename.size(); i++) {
327     p.SetProgress(i, filename.size());
328
329     // Open Image
330     vvImageReader::Pointer reader = vvImageReader::New();
331     std::vector<std::string> filenames;
332     filenames.push_back(filename[i].toStdString());
333     reader->SetInputFilenames(filenames);
334     reader->Update(vvImageReader::IMAGE);
335
336     if (reader->GetLastError().size() != 0) {
337       std::cerr << "Error while reading " << filename[i].toStdString() << std::endl;
338       QString error = "Cannot open file \n";
339       error += reader->GetLastError().c_str();
340       QMessageBox::information(this,tr("Reading problem"),error);
341       return;
342     }
343     vvImage::Pointer binaryImage = reader->GetOutput();
344     std::ostringstream oss;
345     oss << vtksys::SystemTools::
346       GetFilenameName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename[i].toStdString()));
347     std::string name = oss.str();
348     AddImage(binaryImage, name, filename[i].toStdString(), mBackgroundValueSpinBox->value(),
349              (!mBGModeCheckBox->isChecked()));
350     mOpenedBinaryImageFilenames.push_back(filename[i]);
351   }
352   QApplication::restoreOverrideCursor();
353
354   // Update the contours
355   UpdateAllContours();
356 }
357 //------------------------------------------------------------------------------
358
359
360 //------------------------------------------------------------------------------
361 void vvToolROIManager::OpenDicomImage(std::string filename)
362 { //out << __func__ << endl;
363   // GUI selector of roi
364   vvMeshReader reader;
365   reader.SetFilename(filename);
366
367   vvStructSelector selector;
368   selector.SetStructures(reader.GetROINames());
369   selector.SetPropagationCheckBoxFlag(false);
370
371   if (selector.exec()) {
372     vvProgressDialog p("Reading ROI...", true);
373     p.SetCancelButtonEnabled(false);
374     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
375
376     // Read information
377     clitk::DicomRT_StructureSet::Pointer s = clitk::DicomRT_StructureSet::New();
378     s->Read(filename);
379
380     // Loop on selected struct
381     std::vector<int> list = selector.getSelectedItems();
382     for (uint i=0; i<list.size(); i++) {
383       p.SetProgress(i, list.size());
384
385       clitk::DicomRTStruct2ImageFilter filter;
386       filter.SetCropMaskEnabled(true);
387       filter.SetImage(mCurrentImage);
388       filter.SetROI(s->GetROIFromROINumber(list[i]));
389       filter.SetWriteOutputFlag(false);
390       filter.Update();
391
392       // Get image
393       vvImage::Pointer binaryImage = vvImage::New();
394       binaryImage->AddVtkImage(filter.GetOutput());
395
396       // Add to gui
397       AddImage(binaryImage, s->GetROIFromROINumber(list[i])->GetName(), "", 0, true); // "" = no filename
398       mOpenedBinaryImageFilenames.push_back(filename.c_str());
399     }
400
401     QApplication::restoreOverrideCursor();
402   }
403   // Update the contours
404   UpdateAllContours();
405 }
406 //------------------------------------------------------------------------------
407
408
409 //------------------------------------------------------------------------------
410 void vvToolROIManager::AddImage(vvImage * binaryImage,
411                                 std::string name,
412                                 std::string filename,
413                                 double BG, bool modeBG)
414 { //out << __func__ << endl;
415   // Check Dimension
416   int dim = mCurrentImage->GetNumberOfDimensions();
417   int bin_dim = binaryImage->GetNumberOfDimensions();
418   if (dim < bin_dim) {
419     std::ostringstream os;
420     os << "Error. Loaded binary image is " << bin_dim
421        << "D while selected image is " << dim << "D" << std::endl;
422     QMessageBox::information(this,tr("Reading problem"),os.str().c_str());
423     return;
424   }
425
426   // Compute roi index
427   int n = mROIList.size();
428
429   // Compute the name of the new ROI
430   // std::ostringstream oss;
431   // oss << vtksys::SystemTools::GetFilenameName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename));
432   // std::string name = oss.str();
433
434   // Set color
435   std::vector<double> color;
436   color.push_back(1);
437   color.push_back(0);
438   color.push_back(0);
439
440   // Create ROI
441   clitk::DicomRT_ROI::Pointer roi = clitk::DicomRT_ROI::New();
442   roi->SetFromBinaryImage(binaryImage, n, name, color, filename);
443
444   // Add a new roi to the list
445   mROIList.push_back(roi);
446
447   // Set BG or FG mode
448   if (modeBG)
449     roi->SetBackgroundValueLabelImage(BG);
450   else
451     roi->SetForegroundValueLabelImage(BG);
452
453   // Change color
454   if (n<mDefaultLUTColor->GetNumberOfTableValues ()) {
455     double * color = mDefaultLUTColor->GetTableValue(n % mDefaultLUTColor->GetNumberOfTableValues ());
456     roi->SetDisplayColor(color[0], color[1], color[2]);
457   }
458
459   // Add a new roi actor
460   QSharedPointer<vvROIActor> actor = QSharedPointer<vvROIActor>(new vvROIActor);
461   actor->SetBGMode(modeBG);
462   actor->SetROI(roi);
463   actor->SetSlicerManager(mCurrentSlicerManager);
464   actor->Initialize(n+1); // depth is n+1 to start at 1
465   mROIActorsList.push_back(actor);
466
467   // CheckBox for "All"
468   if (actor->IsVisible()) mNumberOfVisibleROI++;
469   if (actor->IsContourVisible()) mNumberOfVisibleContourROI++;
470
471   // Add ROI in tree
472   mTreeWidgetList.push_back(QSharedPointer<QTreeWidgetItem>(new QTreeWidgetItem(mTree)));
473   QTreeWidgetItem * w = mTreeWidgetList.back().data();
474   w->setText(0, QString("%1").arg(roi->GetROINumber()));
475   w->setText(1, QString("%1").arg(roi->GetName().c_str()));
476   w->setText(3, QString("%1").arg(actor->GetDepth()));
477   QBrush brush(QColor(roi->GetDisplayColor()[0]*255,
478                       roi->GetDisplayColor()[1]*255,
479                       roi->GetDisplayColor()[2]*255));
480   brush.setStyle(Qt::SolidPattern);
481   w->setBackground(2, brush);
482   mMapROIToTreeWidget[roi] = w;
483   mMapTreeWidgetToROI[w] = roi;
484   mTree->resizeColumnToContents(0);
485   mTree->resizeColumnToContents(1);
486
487   // Update
488   UpdateAllROIStatus();
489 }
490 //------------------------------------------------------------------------------
491
492
493 //------------------------------------------------------------------------------
494 void vvToolROIManager::UpdateAllContours()
495 { //out << __func__ << endl;
496   if (mCurrentSlicerManager == NULL) return;
497   // Render loaded ROIs (the first is sufficient)
498   for(unsigned int i=0; i<mROIList.size(); i++) {
499     mROIActorsList[i]->Update();
500   }
501   mCurrentSlicerManager->Render();
502 }
503 //------------------------------------------------------------------------------
504
505
506 //------------------------------------------------------------------------------
507 void vvToolROIManager::UpdateAllROIStatus()
508 { //out << __func__ << endl;
509   int nbVisible = 0;
510   int nb = mROIList.size();
511   for(int i=0; i<nb; i++) {
512     if (mROIActorsList[i]->IsVisible()) {
513       nbVisible++;
514     }
515   }
516
517   // change the states
518   disconnect(mCheckBoxShowAll, SIGNAL(stateChanged(int)), this, SLOT(AllVisibleROIToggled(int)));
519   disconnect(mContourCheckBoxShowAll, SIGNAL(toggled(bool)), this, SLOT(AllVisibleContourROIToggled(bool)));
520   if (nbVisible == nb) mCheckBoxShowAll->setCheckState(Qt::Checked);
521   else {
522     if (nbVisible == 0) mCheckBoxShowAll->setCheckState(Qt::Unchecked);
523     else mCheckBoxShowAll->setCheckState(Qt::PartiallyChecked);
524   }
525   connect(mContourCheckBoxShowAll, SIGNAL(toggled(bool)), this, SLOT(AllVisibleContourROIToggled(bool)));
526   connect(mCheckBoxShowAll, SIGNAL(stateChanged(int)), this, SLOT(AllVisibleROIToggled(int)));
527 }
528 //------------------------------------------------------------------------------
529
530
531 //------------------------------------------------------------------------------
532 void vvToolROIManager::SelectedItemChangedInTree()
533 { //out << __func__ << endl;
534   // Search which roi is selected
535   QList<QTreeWidgetItem *> l = mTree->selectedItems();
536   if (l.size() == 0) {
537     //    mCurrentROIActor = 0;
538     mCurrentROI = NULL;
539     mGroupBoxROI->setEnabled(false);
540     return;
541   }
542   QTreeWidgetItem * w = l[0];
543   if (w == NULL) return;
544   if (w == 0) return;
545   if (mMapTreeWidgetToROI.find(w) == mMapTreeWidgetToROI.end()) {
546     //    mCurrentROIActor = 0;
547     mCurrentROI = NULL;
548     mGroupBoxROI->setEnabled(false);
549     return;
550   }
551   if (w == NULL) return;
552   clitk::DicomRT_ROI * roi = mMapTreeWidgetToROI[w];
553   if (roi == NULL) return; // sometimes it is called while there is no roi anymore
554
555   // Get selected roi actor
556   int n = roi->GetROINumber();
557   QSharedPointer<vvROIActor> actor = mROIActorsList[n];
558   mCurrentROI = roi;
559   mCurrentROIActor = actor;
560
561   // Warning -> avoid unuseful Render here by disconnect slider
562   // Update GUI
563   disconnect(mTree, SIGNAL(itemSelectionChanged()), this, SLOT(SelectedItemChangedInTree()));
564   disconnect(mCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleROIToggled(bool)));
565   disconnect(mOpacitySlider, SIGNAL(valueChanged(int)), this, SLOT(OpacityChanged(int)));
566   disconnect(mChangeColorButton, SIGNAL(clicked()), this, SLOT(ChangeColor()));
567   disconnect(mContourCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleContourROIToggled(bool)));
568   disconnect(mChangeContourColorButton, SIGNAL(clicked()), this, SLOT(ChangeContourColor()));
569   disconnect(mContourWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeContourWidth(int)));
570   disconnect(mDepthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeDepth(int)));
571
572   mROInameLabel->setText(roi->GetName().c_str());
573   mCheckBoxShow->setChecked(actor->IsVisible());
574   mContourCheckBoxShow->setChecked(actor->IsContourVisible());
575   mContourWidthSpinBox->setValue(actor->GetContourWidth());
576   mDepthSpinBox->setValue(actor->GetDepth());
577   w->setText(3, QString("%1").arg(actor->GetDepth()));
578   mOpacitySlider->setValue((int)lrint(actor->GetOpacity()*100));
579   mOpacitySpinBox->setValue((int)lrint(actor->GetOpacity()*100));
580
581   connect(mTree, SIGNAL(itemSelectionChanged()), this, SLOT(SelectedItemChangedInTree()));
582   connect(mCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleROIToggled(bool)));
583   connect(mOpacitySlider, SIGNAL(valueChanged(int)), this, SLOT(OpacityChanged(int)));
584   connect(mChangeColorButton, SIGNAL(clicked()), this, SLOT(ChangeColor()));
585   connect(mContourCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleContourROIToggled(bool)));
586   connect(mChangeContourColorButton, SIGNAL(clicked()), this, SLOT(ChangeContourColor()));
587   connect(mContourWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeContourWidth(int)));
588   connect(mDepthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeDepth(int)));
589
590
591   // Set the current color to the selected ROI name
592   mROInameLabel->setAutoFillBackground(true);// # This is important!!
593   // mROInameLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");
594   QColor color = QColor(mCurrentROI->GetDisplayColor()[0]*255,
595                         mCurrentROI->GetDisplayColor()[1]*255,
596                         mCurrentROI->GetDisplayColor()[2]*255);
597   // QString values = QString("%1, %2, %3").arg(color.red()).arg(color.green()).arg(color.blue());
598   // mROInameLabel->setStyleSheet("QLabel { background-color: rgb("+values+"); }");
599
600   QPalette* palette = new QPalette();
601   QColor colorFG = QColor((1-mCurrentROI->GetDisplayColor()[0])*255,
602                           (1-mCurrentROI->GetDisplayColor()[1])*255,
603                           (1-mCurrentROI->GetDisplayColor()[2])*255);
604   palette->setColor(QPalette::WindowText,colorFG);
605   palette->setColor(QPalette::Background, color);
606   mROInameLabel->setPalette(*palette);
607
608   // Enable the group box (in case no selection before)
609   mGroupBoxROI->setEnabled(true);
610 }
611 //------------------------------------------------------------------------------
612
613
614 //------------------------------------------------------------------------------
615 void vvToolROIManager::VisibleROIToggled(bool b)
616 { //out << __func__ << endl;
617   if (mCurrentROIActor == NULL) return;
618   if (b == mCurrentROIActor->IsVisible()) return; // nothing to do
619   mCurrentROIActor->SetVisible(b);
620   UpdateAllROIStatus();
621   mCurrentSlicerManager->Render();
622 }
623 //------------------------------------------------------------------------------
624
625
626 //------------------------------------------------------------------------------
627 void vvToolROIManager::VisibleContourROIToggled(bool b)
628 { //out << __func__ << endl;
629   if (mCurrentROIActor == NULL) return;
630   if (mCurrentROIActor->IsContourVisible() == b) return; // nothing to do
631   mCurrentROIActor->SetContourVisible(b);
632   mCurrentROIActor->UpdateColor();
633   mCurrentSlicerManager->Render();
634 }
635 //------------------------------------------------------------------------------
636
637
638 //------------------------------------------------------------------------------
639 void vvToolROIManager::OpacityChanged(int v)
640 { //out << __func__ << endl;
641   if (mCurrentROIActor == NULL) return;
642   mCurrentROIActor->SetOpacity((double)v/100.0);
643   mCurrentROIActor->UpdateColor();
644   mCurrentSlicerManager->Render();
645 }
646 //------------------------------------------------------------------------------
647
648
649 //------------------------------------------------------------------------------
650 void vvToolROIManager::AllVisibleROIToggled(int b)
651 { //out << __func__ << endl;
652   bool status = false;
653   if ((mCheckBoxShowAll->checkState() == Qt::Checked) ||
654       (mCheckBoxShowAll->checkState() == Qt::PartiallyChecked))  status = true;
655
656   for(uint i=0; i<mROIList.size(); i++) {
657     mROIActorsList[i]->SetVisible(status);
658   }
659   if (status) mCheckBoxShowAll->setCheckState(Qt::Checked);
660   else  mCheckBoxShowAll->setCheckState(Qt::Unchecked);
661   mCheckBoxShow->setChecked(status);
662   mCurrentSlicerManager->Render();
663 }
664 //------------------------------------------------------------------------------
665
666
667 //------------------------------------------------------------------------------
668 void vvToolROIManager::AllVisibleContourROIToggled(bool b)
669 { //out << __func__ << endl;
670   bool status = false;
671   if ((mContourCheckBoxShowAll->checkState() == Qt::Checked) ||
672       (mContourCheckBoxShowAll->checkState() == Qt::PartiallyChecked))  status = true;
673   // Update current
674   for(uint i=0; i<mROIActorsList.size(); i++) {
675     mROIActorsList[i]->SetContourVisible(status);
676   }
677   // Update current selection
678   if (status) mContourCheckBoxShowAll->setCheckState(Qt::Checked);
679   else  mContourCheckBoxShowAll->setCheckState(Qt::Unchecked);
680   mContourCheckBoxShow->setChecked(status);
681   mCurrentSlicerManager->Render();
682 }
683 //------------------------------------------------------------------------------
684
685
686 //------------------------------------------------------------------------------
687 void vvToolROIManager::ChangeColor()
688 { //out << __func__ << endl;
689   if (mCurrentROIActor == NULL) return;
690   QColor color;
691   color.setRgbF(mCurrentROIActor->GetROI()->GetDisplayColor()[0],
692                 mCurrentROIActor->GetROI()->GetDisplayColor()[1],
693                 mCurrentROIActor->GetROI()->GetDisplayColor()[2]);
694   QColor c = QColorDialog::getColor(color, this, "Choose the ROI color");
695   if (!c.isValid()) return;// User cancel
696
697   mCurrentROIActor->GetROI()->SetDisplayColor(c.redF(), c.greenF(), c.blueF());
698   mCurrentROIActor->UpdateColor();
699
700   QTreeWidgetItem * w = mMapROIToTreeWidget[mCurrentROI];
701   QBrush brush(QColor(mCurrentROI->GetDisplayColor()[0]*255,
702                       mCurrentROI->GetDisplayColor()[1]*255,
703                       mCurrentROI->GetDisplayColor()[2]*255));
704   brush.setStyle(Qt::SolidPattern);
705   w->setBackground(2, brush);
706   // Render
707   mCurrentSlicerManager->Render();
708 }
709 //------------------------------------------------------------------------------
710
711
712 //------------------------------------------------------------------------------
713 void vvToolROIManager::ChangeContourColor()
714 { //out << __func__ << endl;
715   if (mCurrentROIActor == NULL) return;
716   QColor color;
717   color.setRgbF(mCurrentROIActor->GetContourColor()[0],
718                 mCurrentROIActor->GetContourColor()[1],
719                 mCurrentROIActor->GetContourColor()[2]);
720   //  QColorDialog d(color);
721   QColor c = QColorDialog::getColor(color, this, "Choose the contour color");
722   if (!c.isValid()) return; // User cancel
723   mCurrentROIActor->SetContourColor(c.redF(), c.greenF(), c.blueF());
724   mCurrentROIActor->UpdateColor();
725   mCurrentSlicerManager->Render();
726 }
727 //------------------------------------------------------------------------------
728
729
730 //------------------------------------------------------------------------------
731 void vvToolROIManager::ChangeContourWidth(int n)
732 { //out << __func__ << endl;
733   if (mCurrentROIActor == NULL) return;
734   mCurrentROIActor->SetContourWidth(n);
735   mCurrentROIActor->UpdateColor();
736   mCurrentSlicerManager->Render();
737 }
738 //------------------------------------------------------------------------------
739
740
741 //------------------------------------------------------------------------------
742 void vvToolROIManager::ChangeDepth(int n)
743 { //out << __func__ << endl;
744   if (mCurrentROIActor == NULL) return;
745   mCurrentROIActor->SetDepth(n);
746   // mCurrentROIActor->UpdateImage(); // FIXME
747   mCurrentSlicerManager->Render();
748   QList<QTreeWidgetItem *> l = mTree->selectedItems();
749   QTreeWidgetItem * w = l[0];
750   w->setText(3, QString("%1").arg(mCurrentROIActor->GetDepth()));
751 }
752 //------------------------------------------------------------------------------
753
754
755 //------------------------------------------------------------------------------
756 void vvToolROIManager::ReloadCurrentROI()
757 { //out << __func__ << endl;
758   if (mCurrentROI->GetFilename() == "") {
759     return; // do nothing (contour from rt struct do not reload)
760   }
761
762   // Remove all contours/overlay first
763   bool visible = mCurrentROIActor->IsVisible();
764   bool cvisible = mCurrentROIActor->IsContourVisible();
765   mCurrentROIActor->SetVisible(false);
766   mCurrentROIActor->SetContourVisible(false);
767   mCurrentSlicerManager->Render();
768
769   // Reload image
770   vvImageReader::Pointer reader = vvImageReader::New();
771   reader->SetInputFilename(mCurrentROI->GetFilename());
772   reader->Update(vvImageReader::IMAGE);
773   if (reader->GetLastError() != "") {
774     // No message just ignore (because can be from dicom)
775     // QMessageBox::information(mMainWindowBase, tr("Sorry, error. Could not reload"),
776     //                          reader->GetLastError().c_str());
777     return;
778   }
779
780   // Free the previous image
781   mCurrentROI->GetImage()->GetFirstVTKImageData()->ReleaseData(); // Needed to free
782   mCurrentROI->GetImage()->Reset();
783   mCurrentROI->SetImage(reader->GetOutput());
784
785   mCurrentROIActor->RemoveActors();
786
787   // Update visu
788   mCurrentROIActor->UpdateImage();
789   mCurrentROIActor->SetVisible(visible);
790   mCurrentROIActor->SetContourVisible(cvisible);
791   mCurrentSlicerManager->Render();
792 }
793 //------------------------------------------------------------------------------
794
795
796 //------------------------------------------------------------------------------
797 void  vvToolROIManager::SaveState(std::auto_ptr<QXmlStreamWriter> & m_XmlWriter)
798 { //out << __func__ << endl;
799   // Get index of the image
800   int n = mMainWindow->GetSlicerManagers().size();
801   int index=-1;
802   for(int i=0; i<n; i++) {
803     if (mCurrentSlicerManager == mMainWindow->GetSlicerManagers()[i]) index = i;
804   }
805   if (index == -1) {
806     std::cerr << "Error while writing state for ROIManager tool no currentimage founded." << std::endl;
807     return;
808   }
809   m_XmlWriter->writeTextElement("Image_Index", QString::number(index));
810
811
812   // Write ROI
813   for(uint i=0; i<mROIActorsList.size(); i++) {
814     QSharedPointer<vvROIActor> roi = mROIActorsList[i];
815
816     m_XmlWriter->writeStartElement("ROI");
817     m_XmlWriter->writeTextElement("Image", mOpenedBinaryImageFilenames[i]);
818
819     m_XmlWriter->writeStartElement("Overlay");
820     m_XmlWriter->writeAttribute("Red",  QString("%1").arg(roi->GetOverlayColor()[0]));
821     m_XmlWriter->writeAttribute("Green",QString("%1").arg(roi->GetOverlayColor()[1]));
822     m_XmlWriter->writeAttribute("Blue", QString("%1").arg(roi->GetOverlayColor()[2]));
823     m_XmlWriter->writeAttribute("Visible", QString("%1").arg(roi->IsVisible()));
824     m_XmlWriter->writeAttribute("Opacity", QString("%1").arg(roi->GetOpacity()));
825     m_XmlWriter->writeAttribute("Depth", QString("%1").arg(roi->GetDepth()));
826     m_XmlWriter->writeEndElement();
827
828     m_XmlWriter->writeStartElement("Contour");
829     m_XmlWriter->writeAttribute("Red",  QString("%1").arg(roi->GetContourColor()[0]));
830     m_XmlWriter->writeAttribute("Green",QString("%1").arg(roi->GetContourColor()[1]));
831     m_XmlWriter->writeAttribute("Blue", QString("%1").arg(roi->GetContourColor()[2]));
832     m_XmlWriter->writeAttribute("Visible", QString("%1").arg(roi->IsContourVisible()));
833     m_XmlWriter->writeAttribute("Width", QString("%1").arg(roi->GetContourWidth()));
834     m_XmlWriter->writeEndElement();
835
836     m_XmlWriter->writeEndElement();
837   }
838 }
839 //------------------------------------------------------------------------------
840
841
842 //------------------------------------------------------------------------------
843 void vvToolROIManager::ReadXMLInformation()
844 { //out << __func__ << endl;
845   std::string value="";
846   mInitialImageIndex = -1;
847   while (!(m_XmlReader->isEndElement() && value == GetToolName().toStdString())) {
848     m_XmlReader->readNext();
849     value = m_XmlReader->qualifiedName().toString().toStdString();
850
851     if (value == "Image_Index")
852       mInitialImageIndex = m_XmlReader->readElementText().toInt();
853
854     if (m_XmlReader->isStartElement()) {
855       if (value == "ROI") {
856         ReadXMLInformation_ROI();
857       }
858     }
859   }
860 }
861 //------------------------------------------------------------------------------
862
863
864 //------------------------------------------------------------------------------
865 void vvToolROIManager::ReadXMLInformation_ROI()
866 { //out << __func__ << endl;
867   QString s;
868   std::string value="";
869   QSharedPointer<vvROIActor> param = QSharedPointer<vvROIActor>(new vvROIActor);
870   param->SetVisible(true);
871   clitk::DicomRT_ROI::Pointer roi = clitk::DicomRT_ROI::New();
872   // r->SetDisplayColor(1,1,1);
873   param->SetROI(roi);
874
875   float r=1.0,g=1.0,b=1.0;
876   float cr=1.0,cg=1.0,cb=1.0;
877   float opacity = 0.7;
878   bool visible = true;
879   bool cvisible = true;
880   int width = 1;
881   int depth=1;
882
883   while (!(m_XmlReader->isEndElement() && value == "ROI")) {
884     m_XmlReader->readNext();
885     value = m_XmlReader->qualifiedName().toString().toStdString();
886     if (value == "Image") {
887       s = m_XmlReader->readElementText();
888     }
889
890     if (value == "Overlay" && m_XmlReader->isStartElement()) {
891       QXmlStreamAttributes attributes = m_XmlReader->attributes();
892       if (!m_XmlReader->hasError())
893         r = attributes.value("Red").toString().toFloat();
894       if (!m_XmlReader->hasError())
895         g = attributes.value("Green").toString().toFloat();
896       if (!m_XmlReader->hasError())
897         b = attributes.value("Blue").toString().toFloat();
898       if (!m_XmlReader->hasError())
899         visible = attributes.value("Visible").toString().toInt();
900       if (!m_XmlReader->hasError())
901         opacity = attributes.value("Opacity").toString().toFloat();
902       if (!m_XmlReader->hasError())
903         depth = attributes.value("Depth").toString().toFloat();
904     }
905
906
907     if (value == "Contour" && m_XmlReader->isStartElement()) {
908       QXmlStreamAttributes attributes = m_XmlReader->attributes();
909       if (!m_XmlReader->hasError())
910         cr = attributes.value("Red").toString().toFloat();
911       if (!m_XmlReader->hasError())
912         cg = attributes.value("Green").toString().toFloat();
913       if (!m_XmlReader->hasError())
914         cb = attributes.value("Blue").toString().toFloat();
915       if (!m_XmlReader->hasError())
916         cvisible = attributes.value("Visible").toString().toInt();
917       if (!m_XmlReader->hasError())
918         width = attributes.value("Width").toString().toFloat();
919     }
920     param->SetOverlayColor(r,g,b);
921     param->SetVisible(visible);
922     param->SetOpacity(opacity);
923     param->SetDepth(depth);
924
925     param->SetContourColor(cr,cg,cb);
926     param->SetContourVisible(cvisible);
927     param->SetContourWidth(width);
928   }
929   mROIFilenames.push_back(s);
930   mROIActorsParamList.push_back(param);
931 }
932 //------------------------------------------------------------------------------