]> Creatis software - clitk.git/blob - vv/vvToolROIManager.cxx
Add dicom rt struct reader (with progress dialog)
[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 "vvROIActor.h"
26 #include "vvMeshReader.h"
27 #include "vvStructSelector.h"
28 #include "vvToolManager.h"
29 #include "vvProgressDialog.h"
30
31 // clitk
32 #include "clitkDicomRTStruct2ImageFilter.h"
33 #include "clitkDicomRT_StructureSet.h"
34
35 // Qt
36 #include <QFileDialog>
37 #include <QMessageBox>
38 #include <QColorDialog>
39 #include <QAbstractEventDispatcher>
40 #include <QXmlStreamReader>
41  
42 // vtk
43 #include <vtkLookupTable.h>
44 #include <vtkRenderWindow.h>
45
46 //------------------------------------------------------------------------------
47 // Create the tool and automagically (I like this word) insert it in
48 // the main window menu.
49 ADD_TOOL(vvToolROIManager);
50 //------------------------------------------------------------------------------
51
52 //------------------------------------------------------------------------------
53 vvToolROIManager::vvToolROIManager(vvMainWindowBase * parent, Qt::WindowFlags f):
54   QWidget(parent->GetTab()), 
55   vvToolBase<vvToolROIManager>(parent),
56   Ui::vvToolROIManager()
57 {
58   // Store parent
59   mMainWindow = parent;
60   
61   // Assume the initial tab ROI index is 2
62   mIndexFirstTab = 2;
63
64   // Build the UI
65   Ui_vvToolROIManager::setupUi(this);
66   setAttribute(Qt::WA_DeleteOnClose);
67   mTree->clear();
68   mTree->header()->resizeSection(0, 30);
69   mGroupBoxROI->setEnabled(false);
70   
71   // Disable "Load dicom" button -> not useful
72   frame_4->hide();
73
74   // Set default LUT
75   mDefaultLUTColor = vtkSmartPointer<vtkLookupTable>::New();
76   for(int i=0; i<mDefaultLUTColor->GetNumberOfTableValues(); i++) {
77     double r = (rand()/(RAND_MAX+1.0));
78     double v = (rand()/(RAND_MAX+1.0));
79     double b = (rand()/(RAND_MAX+1.0));
80     mDefaultLUTColor->SetTableValue(i, r, v, b);
81   }
82 #include "vvDefaultLut.h"
83
84   // Initialization
85   mCurrentSlicerManager = NULL;
86   mNumberOfVisibleROI = 0;
87   mNumberOfVisibleContourROI = 0;
88   mOpenFileBrowserFlag = true; // by default, open the file browser when the tool is launched
89
90   // InitializeNewTool must be called to start
91 }
92 //------------------------------------------------------------------------------
93
94
95 //------------------------------------------------------------------------------
96 vvToolROIManager::~vvToolROIManager()
97 {
98   mROIActorsList.clear();
99 }
100 //------------------------------------------------------------------------------
101
102
103 //------------------------------------------------------------------------------
104 // STATIC
105 void vvToolROIManager::Initialize() {
106   SetToolName("ROIManager");
107   SetToolMenuName("Display ROI (binary image)");
108   SetToolIconFilename(":/common/icons/tool-roi.png");
109   SetToolTip("Display ROI from a binary image.");
110   SetToolExperimental(false);
111 }
112 //------------------------------------------------------------------------------
113
114
115
116 //------------------------------------------------------------------------------
117 void  vvToolROIManager::InitializeNewTool(bool ReadStateFlag) 
118 {
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 = qFindChild<QWidget*>(mMainWindow->GetTab(), "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 {
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("Sorry only 3D yet"), tr("Sorry only 3D yet"));
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 {
248   if (m == mCurrentSlicerManager) { 
249     close();
250     return;
251   }
252 }
253 //------------------------------------------------------------------------------
254
255
256 //------------------------------------------------------------------------------
257 void vvToolROIManager::close()
258 {
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
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 {
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"),
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 {
319   if (filename.size() == 0) return;
320   
321   // For each selected file, open the image
322   for(int i=0; i<filename.size(); i++) {
323     // Open Image
324     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
325     vvImageReader::Pointer reader = vvImageReader::New();
326     std::vector<std::string> filenames;
327     filenames.push_back(filename[i].toStdString());
328     reader->SetInputFilenames(filenames);
329     reader->Update(vvImageReader::IMAGE);
330     QApplication::restoreOverrideCursor();
331
332     if (reader->GetLastError().size() != 0) {
333       std::cerr << "Error while reading " << filename[i].toStdString() << std::endl;
334       QString error = "Cannot open file \n";
335       error += reader->GetLastError().c_str();
336       QMessageBox::information(this,tr("Reading problem"),error);
337       return;
338     }
339     vvImage::Pointer binaryImage = reader->GetOutput();
340     AddImage(binaryImage, filename[i].toStdString(), mBackgroundValueSpinBox->value(),
341              (!mBGModeCheckBox->isChecked()));
342     mOpenedBinaryImageFilenames.push_back(filename[i]);
343   }
344
345   // Update the contours
346   UpdateAllContours(); 
347 }
348 //------------------------------------------------------------------------------
349
350
351 //------------------------------------------------------------------------------
352 void vvToolROIManager::OpenDicomImage(std::string filename) 
353 {
354   // GUI selector of roi
355   vvMeshReader reader;
356   reader.SetFilename(filename);
357   vvStructSelector selector;
358   selector.SetStructures(reader.GetROINames());
359   
360   if (selector.exec()) {
361     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
362     
363     vvProgressDialog p("Reading ROI...", true);
364     p.SetCancelButtonEnabled(false);
365
366     // Read information
367     clitk::DicomRT_StructureSet::Pointer s = clitk::DicomRT_StructureSet::New();
368     s->Read(filename);
369
370     // Loop on selected struct
371     std::vector<int> list = selector.getSelectedItems();
372     for (uint i=0; i<list.size(); i++) {
373       p.SetProgress(i, list.size());
374       
375       clitk::DicomRTStruct2ImageFilter filter;
376       filter.SetCropMaskEnabled(true);
377       filter.SetImage(mCurrentImage);
378       filter.SetROI(s->GetROIFromROINumber(list[i])); 
379       filter.SetWriteOutputFlag(false);
380       filter.Update();  
381
382       // Get image
383       vvImage::Pointer binaryImage = vvImage::New();
384       binaryImage->AddVtkImage(filter.GetOutput());
385     
386       // Add to gui
387       AddImage(binaryImage, s->GetROIFromROINumber(list[i])->GetName(), 0, true);
388       mOpenedBinaryImageFilenames.push_back(filename.c_str());
389     }
390
391     QApplication::restoreOverrideCursor();
392   }
393   // Update the contours
394   UpdateAllContours(); 
395 }
396 //------------------------------------------------------------------------------
397
398
399 //------------------------------------------------------------------------------
400 void vvToolROIManager::AddImage(vvImage * binaryImage, std::string filename, 
401                                 double BG, bool modeBG) 
402 {
403   // Check Dimension
404   int dim = mCurrentImage->GetNumberOfDimensions();
405   int bin_dim = binaryImage->GetNumberOfDimensions();
406   if (dim < bin_dim) {
407     std::ostringstream os;
408     os << "Error. Loaded binary image is " << bin_dim
409        << "D while selected image is " << dim << "D" << std::endl;
410     QMessageBox::information(this,tr("Reading problem"),os.str().c_str());
411     return;
412   }
413   
414   // Compute roi index
415   int n = mROIList.size();
416   
417   // Compute the name of the new ROI
418   std::ostringstream oss;
419   oss << vtksys::SystemTools::GetFilenameName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename));
420   std::string name = oss.str();
421   
422   // Set color
423   std::vector<double> color;
424   color.push_back(1);
425   color.push_back(0);
426   color.push_back(0);
427
428   // Create ROI
429   clitk::DicomRT_ROI::Pointer roi = clitk::DicomRT_ROI::New();
430   roi->SetFromBinaryImage(binaryImage, n, name, color, filename);
431
432   // Add a new roi to the list
433   mROIList.push_back(roi);
434  
435   // Set BG or FG mode
436   if (modeBG) 
437     roi->SetBackgroundValueLabelImage(BG);
438   else 
439     roi->SetForegroundValueLabelImage(BG);
440   
441   // Change color
442   if (n<mDefaultLUTColor->GetNumberOfTableValues ()) {
443     double * color = mDefaultLUTColor->GetTableValue(n % mDefaultLUTColor->GetNumberOfTableValues ());
444     roi->SetDisplayColor(color[0], color[1], color[2]);
445   }
446   
447   // Add a new roi actor
448   QSharedPointer<vvROIActor> actor = QSharedPointer<vvROIActor>(new vvROIActor);
449   actor->SetBGMode(modeBG);
450   actor->SetROI(roi);
451   actor->SetSlicerManager(mCurrentSlicerManager);
452   actor->Initialize(n+1); // depth is n+1 to start at 1
453   mROIActorsList.push_back(actor);
454   
455   // CheckBox for "All"
456   if (actor->IsVisible()) mNumberOfVisibleROI++;
457   if (actor->IsContourVisible()) mNumberOfVisibleContourROI++;
458   
459   // Add ROI in tree
460   mTreeWidgetList.push_back(QSharedPointer<QTreeWidgetItem>(new QTreeWidgetItem(mTree)));
461   QTreeWidgetItem * w = mTreeWidgetList.back().data();
462   w->setText(0, QString("%1").arg(roi->GetROINumber()));
463   w->setText(1, QString("%1").arg(roi->GetName().c_str()));
464   w->setText(3, QString("%1").arg(actor->GetDepth()));  
465   QBrush brush(QColor(roi->GetDisplayColor()[0]*255, 
466                       roi->GetDisplayColor()[1]*255, 
467                       roi->GetDisplayColor()[2]*255));
468   brush.setStyle(Qt::SolidPattern);
469   w->setBackground(2, brush);
470   mMapROIToTreeWidget[roi] = w;
471   mMapTreeWidgetToROI[w] = roi;
472   mTree->resizeColumnToContents(0);
473   mTree->resizeColumnToContents(1);
474
475   // Update 
476   UpdateAllROIStatus(); 
477 }
478 //------------------------------------------------------------------------------
479
480
481 //------------------------------------------------------------------------------
482 void vvToolROIManager::UpdateAllContours() 
483 {
484   if (mCurrentSlicerManager == NULL) return;
485   // Render loaded ROIs (the first is sufficient)
486   for(unsigned int i=0; i<mROIList.size(); i++) {
487     mROIActorsList[i]->Update();
488   }
489   for(int i=0; i<mCurrentSlicerManager->GetNumberOfSlicers(); i++) {
490     mCurrentSlicerManager->GetSlicer(i)->Render();
491   }
492 }
493 //------------------------------------------------------------------------------
494
495
496 //------------------------------------------------------------------------------
497 void vvToolROIManager::UpdateAllROIStatus() {
498   int nbVisible = 0;
499   int nb = mROIList.size();
500   for(int i=0; i<nb; i++) {
501     if (mROIActorsList[i]->IsVisible()) {
502       nbVisible++;
503     }
504   }
505
506   // change the states
507   disconnect(mCheckBoxShowAll, SIGNAL(stateChanged(int)), this, SLOT(AllVisibleROIToggled(int)));  
508   disconnect(mContourCheckBoxShowAll, SIGNAL(toggled(bool)), this, SLOT(AllVisibleContourROIToggled(bool)));
509   if (nbVisible == nb) mCheckBoxShowAll->setCheckState(Qt::Checked);
510   else {
511     if (nbVisible == 0) mCheckBoxShowAll->setCheckState(Qt::Unchecked);
512     else mCheckBoxShowAll->setCheckState(Qt::PartiallyChecked);
513   }
514   connect(mContourCheckBoxShowAll, SIGNAL(toggled(bool)), this, SLOT(AllVisibleContourROIToggled(bool)));
515   connect(mCheckBoxShowAll, SIGNAL(stateChanged(int)), this, SLOT(AllVisibleROIToggled(int)));
516 }
517 //------------------------------------------------------------------------------
518
519
520 //------------------------------------------------------------------------------
521 void vvToolROIManager::SelectedItemChangedInTree() {
522   // Search which roi is selected
523   QList<QTreeWidgetItem *> l = mTree->selectedItems();
524   if (l.size() == 0) {
525     //    mCurrentROIActor = 0;
526     mCurrentROI = NULL;
527     mGroupBoxROI->setEnabled(false);
528     return;
529   }
530   QTreeWidgetItem * w = l[0];
531   if (w == NULL) return;
532   if (w == 0) return;
533   if (mMapTreeWidgetToROI.find(w) == mMapTreeWidgetToROI.end()) {
534     //    mCurrentROIActor = 0;
535     mCurrentROI = NULL;
536     mGroupBoxROI->setEnabled(false);
537     return;
538   }
539   if (w == NULL) return;
540   clitk::DicomRT_ROI * roi = mMapTreeWidgetToROI[w];
541   if (roi == NULL) return; // sometimes it is called while there is no roi anymore
542
543   // Get selected roi actor
544   int n = roi->GetROINumber();
545   QSharedPointer<vvROIActor> actor = mROIActorsList[n];
546   mCurrentROI = roi;
547   mCurrentROIActor = actor;
548
549   // Warning -> avoid unuseful Render here by disconnect slider 
550   // Update GUI
551   disconnect(mTree, SIGNAL(itemSelectionChanged()), this, SLOT(SelectedItemChangedInTree()));
552   disconnect(mCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleROIToggled(bool)));
553   disconnect(mOpacitySlider, SIGNAL(valueChanged(int)), this, SLOT(OpacityChanged(int)));
554   disconnect(mChangeColorButton, SIGNAL(clicked()), this, SLOT(ChangeColor()));
555   disconnect(mContourCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleContourROIToggled(bool)));  
556   disconnect(mChangeContourColorButton, SIGNAL(clicked()), this, SLOT(ChangeContourColor()));
557   disconnect(mContourWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeContourWidth(int)));
558   disconnect(mDepthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeDepth(int)));
559
560   mROInameLabel->setText(roi->GetName().c_str());
561   mCheckBoxShow->setChecked(actor->IsVisible());
562   mContourCheckBoxShow->setChecked(actor->IsContourVisible());
563   mContourWidthSpinBox->setValue(actor->GetContourWidth());
564   mDepthSpinBox->setValue(actor->GetDepth());
565   w->setText(3, QString("%1").arg(actor->GetDepth()));
566   mOpacitySlider->setValue((int)lrint(actor->GetOpacity()*100));
567   mOpacitySpinBox->setValue((int)lrint(actor->GetOpacity()*100));
568
569   connect(mTree, SIGNAL(itemSelectionChanged()), this, SLOT(SelectedItemChangedInTree()));
570   connect(mCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleROIToggled(bool)));
571   connect(mOpacitySlider, SIGNAL(valueChanged(int)), this, SLOT(OpacityChanged(int)));
572   connect(mChangeColorButton, SIGNAL(clicked()), this, SLOT(ChangeColor()));
573   connect(mContourCheckBoxShow, SIGNAL(toggled(bool)), this, SLOT(VisibleContourROIToggled(bool)));  
574   connect(mChangeContourColorButton, SIGNAL(clicked()), this, SLOT(ChangeContourColor()));
575   connect(mContourWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeContourWidth(int)));
576   connect(mDepthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(ChangeDepth(int)));
577
578   
579   // Set the current color to the selected ROI name
580   mROInameLabel->setAutoFillBackground(true);// # This is important!!
581   // mROInameLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");
582   QColor color = QColor(mCurrentROI->GetDisplayColor()[0]*255,
583                         mCurrentROI->GetDisplayColor()[1]*255,
584                         mCurrentROI->GetDisplayColor()[2]*255);
585   // QString values = QString("%1, %2, %3").arg(color.red()).arg(color.green()).arg(color.blue());
586   // mROInameLabel->setStyleSheet("QLabel { background-color: rgb("+values+"); }");
587
588   QPalette* palette = new QPalette();
589   QColor colorFG = QColor((1-mCurrentROI->GetDisplayColor()[0])*255,
590                           (1-mCurrentROI->GetDisplayColor()[1])*255,
591                           (1-mCurrentROI->GetDisplayColor()[2])*255);
592   palette->setColor(QPalette::WindowText,colorFG);
593   palette->setColor(QPalette::Background, color);
594   mROInameLabel->setPalette(*palette);  
595
596   // Enable the group box (in case no selection before)
597   mGroupBoxROI->setEnabled(true);
598 }
599 //------------------------------------------------------------------------------
600
601
602 //------------------------------------------------------------------------------
603 void vvToolROIManager::VisibleROIToggled(bool b) {
604   if (mCurrentROIActor == NULL) return;
605   if (b == mCurrentROIActor->IsVisible()) return; // nothing to do
606   mCurrentROIActor->SetVisible(b);
607   UpdateAllROIStatus();
608   mCurrentSlicerManager->Render(); 
609 }
610 //------------------------------------------------------------------------------
611
612
613 //------------------------------------------------------------------------------
614 void vvToolROIManager::VisibleContourROIToggled(bool b) {
615   if (mCurrentROIActor == NULL) return;
616   if (mCurrentROIActor->IsContourVisible() == b) return; // nothing to do
617   mCurrentROIActor->SetContourVisible(b);
618   mCurrentROIActor->UpdateColor();
619   mCurrentSlicerManager->Render(); 
620 }
621 //------------------------------------------------------------------------------
622
623
624 //------------------------------------------------------------------------------
625 void vvToolROIManager::OpacityChanged(int v) {
626   if (mCurrentROIActor == NULL) return;
627   mCurrentROIActor->SetOpacity((double)v/100.0);
628   mCurrentROIActor->UpdateColor();
629   mCurrentSlicerManager->Render(); 
630 }
631 //------------------------------------------------------------------------------
632
633
634 //------------------------------------------------------------------------------
635 void vvToolROIManager::AllVisibleROIToggled(int b) {
636   bool status = false;
637   if ((mCheckBoxShowAll->checkState() == Qt::Checked) ||
638       (mCheckBoxShowAll->checkState() == Qt::PartiallyChecked))  status = true;
639
640   for(uint i=0; i<mROIList.size(); i++) {
641     mROIActorsList[i]->SetVisible(status);
642   }
643   if (status) mCheckBoxShowAll->setCheckState(Qt::Checked);
644   else  mCheckBoxShowAll->setCheckState(Qt::Unchecked);
645   mCheckBoxShow->setChecked(status);
646   mCurrentSlicerManager->Render(); 
647 }
648 //------------------------------------------------------------------------------
649
650
651 //------------------------------------------------------------------------------
652 void vvToolROIManager::AllVisibleContourROIToggled(bool b) {
653   bool status = false;
654   if ((mContourCheckBoxShowAll->checkState() == Qt::Checked) ||
655       (mContourCheckBoxShowAll->checkState() == Qt::PartiallyChecked))  status = true;
656   // Update current 
657   for(uint i=0; i<mROIActorsList.size(); i++) {
658     mROIActorsList[i]->SetContourVisible(status);
659   }
660   // Update current selection
661   if (status) mContourCheckBoxShowAll->setCheckState(Qt::Checked);
662   else  mContourCheckBoxShowAll->setCheckState(Qt::Unchecked);
663   mContourCheckBoxShow->setChecked(status);
664   mCurrentSlicerManager->Render(); 
665 }
666 //------------------------------------------------------------------------------
667
668
669 //------------------------------------------------------------------------------
670 void vvToolROIManager::ChangeColor() {
671   if (mCurrentROIActor == NULL) return;
672   QColor color;
673   color.setRgbF(mCurrentROIActor->GetROI()->GetDisplayColor()[0],
674                 mCurrentROIActor->GetROI()->GetDisplayColor()[1],
675                 mCurrentROIActor->GetROI()->GetDisplayColor()[2]);
676   QColor c = QColorDialog::getColor(color, this, "Choose the ROI color");
677   mCurrentROIActor->GetROI()->SetDisplayColor(c.redF(), c.greenF(), c.blueF());
678   mCurrentROIActor->UpdateColor();
679
680   QTreeWidgetItem * w = mMapROIToTreeWidget[mCurrentROI];
681   QBrush brush(QColor(mCurrentROI->GetDisplayColor()[0]*255,
682                       mCurrentROI->GetDisplayColor()[1]*255,
683                       mCurrentROI->GetDisplayColor()[2]*255));
684   brush.setStyle(Qt::SolidPattern);
685   w->setBackground(2, brush);
686   // Render
687   mCurrentSlicerManager->Render();
688 }
689 //------------------------------------------------------------------------------
690
691
692 //------------------------------------------------------------------------------
693 void vvToolROIManager::ChangeContourColor() {
694   if (mCurrentROIActor == NULL) return;
695   QColor color;
696   color.setRgbF(mCurrentROIActor->GetContourColor()[0], 
697                 mCurrentROIActor->GetContourColor()[1], 
698                 mCurrentROIActor->GetContourColor()[2]);
699   //  QColorDialog d(color);
700   QColor c = QColorDialog::getColor(color, this, "Choose the contour color");
701   if (!c.isValid()) return; // User cancel
702   mCurrentROIActor->SetContourColor(c.redF(), c.greenF(), c.blueF());
703   mCurrentROIActor->UpdateColor();
704   mCurrentSlicerManager->Render();
705 }
706 //------------------------------------------------------------------------------
707
708
709 //------------------------------------------------------------------------------
710 void vvToolROIManager::ChangeContourWidth(int n) {
711   if (mCurrentROIActor == NULL) return;
712   mCurrentROIActor->SetContourWidth(n);
713   mCurrentROIActor->UpdateColor();
714   mCurrentSlicerManager->Render();
715 }
716 //------------------------------------------------------------------------------
717
718
719 //------------------------------------------------------------------------------
720 void vvToolROIManager::ChangeDepth(int n) {
721   if (mCurrentROIActor == NULL) return;
722   mCurrentROIActor->SetDepth(n);
723   // mCurrentROIActor->UpdateImage(); // FIXME  
724   mCurrentSlicerManager->Render();
725   QList<QTreeWidgetItem *> l = mTree->selectedItems();
726   QTreeWidgetItem * w = l[0];
727   w->setText(3, QString("%1").arg(mCurrentROIActor->GetDepth()));
728 }
729 //------------------------------------------------------------------------------
730
731
732 //------------------------------------------------------------------------------
733 void vvToolROIManager::ReloadCurrentROI() {
734
735   // Remove all contours/overlay first
736   bool visible = mCurrentROIActor->IsVisible();
737   bool cvisible = mCurrentROIActor->IsContourVisible();
738   mCurrentROIActor->SetVisible(false);
739   mCurrentROIActor->SetContourVisible(false);
740   mCurrentSlicerManager->Render();
741   
742   // Reload image
743   vvImageReader::Pointer reader = vvImageReader::New();
744   reader->SetInputFilename(mCurrentROI->GetFilename());
745   reader->Update(vvImageReader::IMAGE);
746   if (reader->GetLastError() != "") {
747     // No message just ignore (because can be from dicom)
748     // QMessageBox::information(mMainWindowBase, tr("Sorry, error. Could not reload"), 
749     //                          reader->GetLastError().c_str());
750     return;
751   }
752
753   // Free the previous image
754   mCurrentROI->GetImage()->GetFirstVTKImageData()->ReleaseData(); // Needed to free
755   mCurrentROI->GetImage()->Reset();
756   mCurrentROI->SetImage(reader->GetOutput());
757
758   mCurrentROIActor->RemoveActors();
759
760   // Update visu
761   mCurrentROIActor->UpdateImage();
762   mCurrentROIActor->SetVisible(visible);
763   mCurrentROIActor->SetContourVisible(cvisible);
764   mCurrentSlicerManager->Render();    
765 }
766 //------------------------------------------------------------------------------
767
768
769 //------------------------------------------------------------------------------
770 void  vvToolROIManager::SaveState(std::auto_ptr<QXmlStreamWriter> & m_XmlWriter)
771 {
772   // Get index of the image
773   int n = mMainWindow->GetSlicerManagers().size();
774   int index=-1;
775   for(int i=0; i<n; i++) {
776     if (mCurrentSlicerManager == mMainWindow->GetSlicerManagers()[i]) index = i;
777   }
778   if (index == -1) {
779     std::cerr << "Error while writing state for ROIManager tool no currentimage founded." << std::endl;
780     return;
781   }
782   m_XmlWriter->writeTextElement("Image_Index", QString::number(index));
783
784
785   // Write ROI
786   for(uint i=0; i<mROIActorsList.size(); i++) {
787     QSharedPointer<vvROIActor> roi = mROIActorsList[i];
788
789     m_XmlWriter->writeStartElement("ROI");
790     m_XmlWriter->writeTextElement("Image", mOpenedBinaryImageFilenames[i]);
791
792     m_XmlWriter->writeStartElement("Overlay");
793     m_XmlWriter->writeAttribute("Red",  QString("%1").arg(roi->GetOverlayColor()[0]));
794     m_XmlWriter->writeAttribute("Green",QString("%1").arg(roi->GetOverlayColor()[1]));
795     m_XmlWriter->writeAttribute("Blue", QString("%1").arg(roi->GetOverlayColor()[2]));
796     m_XmlWriter->writeAttribute("Visible", QString("%1").arg(roi->IsVisible()));
797     m_XmlWriter->writeAttribute("Opacity", QString("%1").arg(roi->GetOpacity()));
798     m_XmlWriter->writeAttribute("Depth", QString("%1").arg(roi->GetDepth()));
799     m_XmlWriter->writeEndElement();
800    
801     m_XmlWriter->writeStartElement("Contour");
802     m_XmlWriter->writeAttribute("Red",  QString("%1").arg(roi->GetContourColor()[0]));
803     m_XmlWriter->writeAttribute("Green",QString("%1").arg(roi->GetContourColor()[1]));
804     m_XmlWriter->writeAttribute("Blue", QString("%1").arg(roi->GetContourColor()[2]));
805     m_XmlWriter->writeAttribute("Visible", QString("%1").arg(roi->IsContourVisible()));
806     m_XmlWriter->writeAttribute("Width", QString("%1").arg(roi->GetContourWidth()));
807     m_XmlWriter->writeEndElement();
808
809     m_XmlWriter->writeEndElement();
810   }
811 }
812 //------------------------------------------------------------------------------
813
814
815 //------------------------------------------------------------------------------
816 void vvToolROIManager::ReadXMLInformation() 
817 {
818   std::string value="";
819   mInitialImageIndex = -1;
820   while (!(m_XmlReader->isEndElement() && value == GetToolName().toStdString())) { 
821     m_XmlReader->readNext();
822     value = m_XmlReader->qualifiedName().toString().toStdString();
823     
824     if (value == "Image_Index") 
825       mInitialImageIndex = m_XmlReader->readElementText().toInt();
826     
827     if (m_XmlReader->isStartElement()) {
828       if (value == "ROI") {
829         ReadXMLInformation_ROI();
830       }      
831     }
832   }
833 }
834 //------------------------------------------------------------------------------
835
836
837 //------------------------------------------------------------------------------
838 void vvToolROIManager::ReadXMLInformation_ROI() 
839 {
840   QString s;
841   std::string value="";
842   QSharedPointer<vvROIActor> param = QSharedPointer<vvROIActor>(new vvROIActor);
843   param->SetVisible(true);
844   clitk::DicomRT_ROI::Pointer roi = clitk::DicomRT_ROI::New();
845   // r->SetDisplayColor(1,1,1);
846   param->SetROI(roi);
847
848   float r=1.0,g=1.0,b=1.0;
849   float cr=1.0,cg=1.0,cb=1.0;
850   float opacity = 0.7;
851   bool visible = true;
852   bool cvisible = true;
853   int width = 1;
854   int depth=1;
855
856   while (!(m_XmlReader->isEndElement() && value == "ROI")) { 
857     m_XmlReader->readNext();
858     value = m_XmlReader->qualifiedName().toString().toStdString();
859     if (value == "Image") {
860       s = m_XmlReader->readElementText();
861     }
862     
863     if (value == "Overlay" && m_XmlReader->isStartElement()) {
864       QXmlStreamAttributes attributes = m_XmlReader->attributes();
865       if (!m_XmlReader->hasError())
866         r = attributes.value("Red").toString().toFloat();
867       if (!m_XmlReader->hasError())
868         g = attributes.value("Green").toString().toFloat();
869       if (!m_XmlReader->hasError())
870         b = attributes.value("Blue").toString().toFloat();
871       if (!m_XmlReader->hasError())
872         visible = attributes.value("Visible").toString().toInt();
873       if (!m_XmlReader->hasError())
874         opacity = attributes.value("Opacity").toString().toFloat();
875       if (!m_XmlReader->hasError())
876         depth = attributes.value("Depth").toString().toFloat();
877     }
878
879
880     if (value == "Contour" && m_XmlReader->isStartElement()) {
881       QXmlStreamAttributes attributes = m_XmlReader->attributes();
882       if (!m_XmlReader->hasError())
883         cr = attributes.value("Red").toString().toFloat();
884       if (!m_XmlReader->hasError())
885         cg = attributes.value("Green").toString().toFloat();
886       if (!m_XmlReader->hasError())
887         cb = attributes.value("Blue").toString().toFloat();
888       if (!m_XmlReader->hasError())
889         cvisible = attributes.value("Visible").toString().toInt();
890       if (!m_XmlReader->hasError())
891         width = attributes.value("Width").toString().toFloat();
892     }
893     param->SetOverlayColor(r,g,b);
894     param->SetVisible(visible);
895     param->SetOpacity(opacity); 
896     param->SetDepth(depth); 
897
898     param->SetContourColor(cr,cg,cb);
899     param->SetContourVisible(cvisible);
900     param->SetContourWidth(width);
901   }
902   mROIFilenames.push_back(s);
903   mROIActorsParamList.push_back(param);
904 }
905 //------------------------------------------------------------------------------