]> Creatis software - clitk.git/blob - vv/vvMainWindow.cxx
Resample tool now use new resampleImage class (use the right number of thread)
[clitk.git] / vv / vvMainWindow.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://oncora1.lyon.fnclcc.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 #include <algorithm>
20 #include <QMessageBox>
21 #include <QInputDialog>
22 #include <QTimer>
23 #include "QTreePushButton.h"
24
25 // VV include
26 #include "vvMainWindow.h"
27 #include "vvHelpDialog.h"
28 #include "vvDocumentation.h"
29 #include "vvProgressDialog.h"
30 #include "vvQDicomSeriesSelector.h"
31 #include "vvSlicerManager.h"
32 #include "clitkImageCommon.h"
33 #include "vvSlicer.h"
34 #include "vvInteractorStyleNavigator.h"
35 #include "vvImageWriter.h"
36 #include "vvSegmentationDialog.h"
37 #include "vvSurfaceViewerDialog.h"
38 #include "vvDeformationDialog.h"
39 #include "vvImageWarp.h"
40 #include "vvUtils.h"
41 #include "vvMaximumIntensityProjection.h"
42 #include "vvMidPosition.h"
43 #include "vvMesh.h"
44 #include "vvStructSelector.h"
45 #include "vvMeshReader.h"
46 #include "vvConstants.h"
47 #include "clitkConfiguration.h"
48
49 // ITK include
50 #include "itkImage.h"
51 #include "itkImageFileReader.h"
52 #include "itkByteSwapper.h"
53 #include "itkCommand.h"
54 #include "itkNumericSeriesFileNames.h"
55
56 // VTK include
57 #include "vtkImageData.h"
58 #include "vtkImageActor.h"
59 #include "vtkCornerAnnotation.h"
60 #include "vtkRenderWindow.h"
61 #include "vtkRenderWindowInteractor.h"
62 #include "vtkRenderer.h"
63 #include "vtkRendererCollection.h"
64 #include "vtkWindowToImageFilter.h"
65 #include "vtkBMPWriter.h"
66 #include "vtkTIFFWriter.h"
67 #include "vtkPNMWriter.h"
68 #include "vtkPNGWriter.h"
69 #include "vtkJPEGWriter.h"
70 #include "vtkMatrix4x4.h"
71 #include "vtkTransform.h"
72
73 // Standard includes
74 #include <iostream>
75 #include <sstream>
76 #include <iomanip>
77
78 #define COLUMN_TREE 0
79 #define COLUMN_UL_VIEW 1
80 #define COLUMN_UR_VIEW 2
81 #define COLUMN_DL_VIEW 3
82 #define COLUMN_DR_VIEW 4
83 #define COLUMN_CLOSE_IMAGE 5
84 #define COLUMN_RELOAD_IMAGE 6
85 #define COLUMN_IMAGE_NAME 7
86
87 #define EXTENSIONS "Images ( *.bmp *.png *.jpeg *.jpg *.tif *.mhd *.hdr *.vox *.his *.xdr *.SCAN )"
88
89 /*Data Tree values
90   0,Qt::UserRole full filename
91   1,Qt::CheckStateRole checkbutton UL View
92   1,Qt::UserRole overlay, fusion or vector
93   2,Qt::CheckStateRole checkbutton UR View
94   3,Qt::CheckStateRole checkbutton DL View
95   4,Qt::CheckStateRole checkbutton DR View
96   5,0  short filename
97   5,Qt::UserRole mSlicerManager id*/
98
99 //------------------------------------------------------------------------------
100 vvMainWindow::vvMainWindow():vvMainWindowBase()
101 {
102   setupUi(this); // this sets up the GUI
103
104   mInputPathName = "";
105   mMenuTools = menuTools;
106   //  mMenuSegmentation = menuSegmentation;
107   mContextMenu = &contextMenu;
108   mMenuExperimentalTools = menuExperimental;
109   mMainWidget = this;
110   mCurrentTime = -1;
111   mCurrentSelectedImageId = "";
112
113   //Init the contextMenu
114   this->setContextMenuPolicy(Qt::CustomContextMenu);
115   contextActions.resize(0);
116   QAction* actionOpen_new_image = contextMenu.addAction(QIcon(QString::fromUtf8(":/common/icons/fileopen.png")),
117                                   tr("O&pen new Image"));
118   actionOpen_new_image->setShortcut(QKeySequence(tr("Ctrl+O")));
119   connect(actionOpen_new_image,SIGNAL(triggered()),this,SLOT(OpenImages()));
120   contextActions.push_back(actionOpen_new_image);
121   contextMenu.addSeparator();
122
123   QAction* actionClose_Image = contextMenu.addAction(QIcon(QString::fromUtf8(":/common/icons/exit.png")),
124                                tr("Close Current Image"));
125   connect(actionClose_Image,SIGNAL(triggered()),this,SLOT(CloseImage()));
126   contextActions.push_back(actionClose_Image);
127
128   QAction* actionReload_image = contextMenu.addAction(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")),
129                                 tr("Reload Current Image"));
130   connect(actionReload_image,SIGNAL(triggered()),this,SLOT(ReloadImage()));
131   contextActions.push_back(actionReload_image);
132
133   QAction* actionSave_image = contextMenu.addAction(QIcon(QString::fromUtf8(":/common/icons/filesave.png")),
134                               tr("Save Current Image"));
135   connect(actionSave_image,SIGNAL(triggered()),this,SLOT(SaveAs()));
136   contextActions.push_back(actionSave_image);
137
138   contextMenu.addSeparator();
139
140   contextMenu.addAction(actionAdd_VF_to_current_Image);
141   contextActions.push_back(actionAdd_VF_to_current_Image);
142
143   QAction* actionAdd_Overlay_to_current_Image = menuOverlay->addAction(QIcon(QString::fromUtf8(":/common/icons/GPSup.png")),
144       tr("Add overlay image to current image"));
145   contextMenu.addAction(actionAdd_Overlay_to_current_Image);
146   contextActions.push_back(actionAdd_Overlay_to_current_Image);
147
148   connect(actionAdd_Overlay_to_current_Image,SIGNAL(triggered()), this,SLOT(SelectOverlayImage()));
149
150   contextMenu.addAction(actionAdd_fusion_image);
151   connect(actionAdd_fusion_image,SIGNAL(triggered()),this,SLOT(SelectFusionImage()));
152   contextActions.push_back(actionAdd_fusion_image);
153
154   // TRIAL DS
155   /*
156   QMenu * m = new QMenu(menubar);
157   m->setTitle("TOTO");
158   //  m->setObjectName(QString::fromUtf8("TOTOTO"));
159   contextMenu.addMenu(m);
160   QAction * a = m->addAction(QIcon(QString::fromUtf8(":/common/icons/GPSup.png")),
161                      tr("BIDON"));
162   QAction * b = m->addAction(QIcon(QString::fromUtf8(":/common/icons/GPSup.png")),
163                      tr("BIDON2"));
164   m->addAction(a);
165   m->addAction(b);
166   connect(a,SIGNAL(triggered()),this,SLOT(AddFusionImage()));
167   */
168
169   //init the DataTree
170   mSlicerManagers.resize(0);
171
172   QStringList header;
173   header.append("");
174   header.append("TL");
175   header.append("TR");
176   header.append("BL");
177   header.append("BR");
178   header.append("");
179   header.append("");
180   header.append("Name");
181
182   DataTree->setHeaderLabels(header);
183   DataTree->resizeColumnToContents(COLUMN_TREE);
184   DataTree->resizeColumnToContents(COLUMN_UL_VIEW);
185   DataTree->resizeColumnToContents(COLUMN_UR_VIEW);
186   DataTree->resizeColumnToContents(COLUMN_DL_VIEW);
187   DataTree->resizeColumnToContents(COLUMN_DR_VIEW);
188   DataTree->resizeColumnToContents(COLUMN_CLOSE_IMAGE);
189   DataTree->resizeColumnToContents(COLUMN_RELOAD_IMAGE);
190   DataTree->resizeColumnToContents(COLUMN_IMAGE_NAME);
191
192   viewMode = 1;
193   documentation = new vvDocumentation();
194   help_dialog = new vvHelpDialog();
195   dicomSeriesSelector = new vvDicomSeriesSelector();
196
197   inverseButton->setEnabled(0);
198   actionAdd_Overlay_to_current_Image->setEnabled(0);
199   actionSave_As->setEnabled(0);
200   actionAdd_VF_to_current_Image->setEnabled(0);
201   actionAdd_fusion_image->setEnabled(0);
202
203   //init the sliders
204   verticalSliders.push_back(NOVerticalSlider);
205   verticalSliders.push_back(NEVerticalSlider);
206   verticalSliders.push_back(SOVerticalSlider);
207   verticalSliders.push_back(SEVerticalSlider);
208
209   for (int i =0; i < 4; i++)
210     verticalSliders[i]->hide();
211
212   horizontalSliders.push_back(NOHorizontalSlider);
213   horizontalSliders.push_back(NEHorizontalSlider);
214   horizontalSliders.push_back(SOHorizontalSlider);
215   horizontalSliders.push_back(SEHorizontalSlider);
216
217   for (int i =0; i < 4; i++)
218     horizontalSliders[i]->hide();
219
220
221   connect(NOVerticalSlider,SIGNAL(valueChanged(int)),this,SLOT(NOVerticalSliderChanged()));
222   connect(NEVerticalSlider,SIGNAL(valueChanged(int)),this,SLOT(NEVerticalSliderChanged()));
223   connect(SOVerticalSlider,SIGNAL(valueChanged(int)),this,SLOT(SOVerticalSliderChanged()));
224   connect(SEVerticalSlider,SIGNAL(valueChanged(int)),this,SLOT(SEVerticalSliderChanged()));
225
226   connect(NOHorizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(NOHorizontalSliderMoved()));
227   connect(NEHorizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(NEHorizontalSliderMoved()));
228   connect(SOHorizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(SOHorizontalSliderMoved()));
229   connect(SEHorizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(SEHorizontalSliderMoved()));
230
231   //connect everything
232   connect(actionMaximum_Intensity_Projection,SIGNAL(triggered()),this,SLOT(ComputeMIP()));
233   connect(actionCompute_mid_position_image,SIGNAL(triggered()),this,SLOT(ComputeMidPosition()));
234   connect(actionDeformable_Registration,SIGNAL(triggered()),this,SLOT(ComputeDeformableRegistration()));
235   connect(actionWarp_image_with_vector_field,SIGNAL(triggered()),this,SLOT(WarpImage()));
236   connect(actionLoad_images,SIGNAL(triggered()),this,SLOT(OpenImages()));
237   connect(actionOpen_Dicom,SIGNAL(triggered()),this,SLOT(OpenDicom()));
238   connect(actionOpen_Dicom_Struct,SIGNAL(triggered()),this,SLOT(OpenDCStructContour()));
239   connect(actionOpen_VTK_contour,SIGNAL(triggered()),this,SLOT(OpenVTKContour()));
240   connect(actionOpen_Multiple_Images_As_One,SIGNAL(triggered()),this,SLOT(MergeImages()));
241   connect(actionSlice_Image_As_Multiple_Images,SIGNAL(triggered()),this,SLOT(SliceImages()));
242   connect(actionOpen_Image_With_Time,SIGNAL(triggered()),this,SLOT(OpenImageWithTime()));
243   connect(actionMerge_images_as_n_dim_t, SIGNAL(triggered()), this, SLOT(MergeImagesWithTime()));
244   connect(actionSave_As,SIGNAL(triggered()),this,SLOT(SaveAs()));
245   connect(actionExit,SIGNAL(triggered()),this,SLOT(close()));
246   connect(actionAdd_VF_to_current_Image,SIGNAL(triggered()),this,SLOT(OpenField()));
247   connect(actionNavigation_Help,SIGNAL(triggered()),this,SLOT(ShowHelpDialog()));
248   connect(actionDocumentation,SIGNAL(triggered()),this,SLOT(ShowDocumentation()));
249
250   ///////////////////////////////////////////////
251   connect(actionSegmentation,SIGNAL(triggered()),this,SLOT(SegmentationOnCurrentImage()));
252   connect(actionSurface_Viewer,SIGNAL(triggered()),this,SLOT(SurfaceViewerLaunch()));
253   ///////////////////////////////////////////////
254
255   actionNorth_East_Window->setEnabled(0);
256   actionNorth_West_Window->setEnabled(0);
257   actionSouth_East_Window->setEnabled(0);
258   actionSouth_West_Window->setEnabled(0);
259
260   connect(actionNorth_East_Window,SIGNAL(triggered()),this,SLOT(SaveNEScreenshot()));
261   connect(actionNorth_West_Window,SIGNAL(triggered()),this,SLOT(SaveNOScreenshot()));
262   connect(actionSouth_East_Window,SIGNAL(triggered()),this,SLOT(SaveSEScreenshot()));
263   connect(actionSouth_West_Window,SIGNAL(triggered()),this,SLOT(SaveSOScreenshot()));
264
265   connect(DataTree,SIGNAL(itemSelectionChanged()),this,SLOT(ImageInfoChanged()));
266   connect(DataTree,SIGNAL(itemClicked(QTreeWidgetItem*, int)),this,
267           SLOT(DisplayChanged(QTreeWidgetItem*, int)));
268
269   connect(viewButton,SIGNAL(clicked()),this, SLOT(ChangeViewMode()) );
270   connect(windowSpinBox,SIGNAL(editingFinished()),this,SLOT(WindowLevelEdited()));
271   connect(levelSpinBox,SIGNAL(editingFinished()),this,SLOT(WindowLevelEdited()));
272   connect(colorMapComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(UpdateColorMap()));
273   connect(presetComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(UpdateWindowLevel()));
274   connect(inverseButton,SIGNAL(clicked()),this,SLOT(SwitchWindowLevel()));
275   connect(applyWindowLevelToAllButton,SIGNAL(clicked()),this,SLOT(ApplyWindowLevelToAllImages()));
276
277
278   connect(this,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(ShowContextMenu(QPoint)));
279
280   connect(linkPanel,SIGNAL(addLink(QString,QString)),this,SLOT(AddLink(QString,QString)));
281   connect(linkPanel,SIGNAL(removeLink(QString,QString)),this,SLOT(RemoveLink(QString,QString)));
282   connect(overlayPanel,SIGNAL(VFPropertyUpdated(int,int,int,int,double,double,double)),this,SLOT(SetVFProperty(int,int,int,int,double,double,double)));
283   connect(overlayPanel,SIGNAL(OverlayPropertyUpdated(int)),this,SLOT(SetOverlayProperty(int)));
284   connect(overlayPanel,SIGNAL(FusionPropertyUpdated(int,int,double,double)),
285           this,SLOT(SetFusionProperty(int,int,double,double)));
286   connect(landmarksPanel,SIGNAL(UpdateRenderWindows()),this,SLOT(UpdateRenderWindows()));
287
288   playMode = 0;//pause
289   mFrameRate = 10;
290   playButton->setEnabled(0);
291   frameRateLabel->setEnabled(0);
292   frameRateSpinBox->setEnabled(0);
293   connect(playButton, SIGNAL(clicked()),this,SLOT(PlayPause()));
294   connect(frameRateSpinBox, SIGNAL(valueChanged(int)),this,SLOT(ChangeFrameRate(int)));
295
296   goToCursorPushButton->setEnabled(0);
297   connect(goToCursorPushButton, SIGNAL(clicked()),this,SLOT(GoToCursor()));
298
299   NOViewWidget->hide();
300   NEViewWidget->hide();
301   SOViewWidget->hide();
302   SEViewWidget->hide();
303
304   //Recently opened files
305   std::list<std::string> recent_files = GetRecentlyOpenedImages();
306   if ( !recent_files.empty() ) {
307     QMenu * rmenu = new QMenu("Recently opened files...");
308     rmenu->setIcon(QIcon(QString::fromUtf8(":/common/icons/open.png")));
309     menuFile->insertMenu(actionOpen_Image_With_Time,rmenu);
310     menuFile->insertSeparator(actionOpen_Image_With_Time);
311     for (std::list<std::string>::iterator i = recent_files.begin(); i!=recent_files.end(); i++) {
312       QAction* current=new QAction(QIcon(QString::fromUtf8(":/common/icons/open.png")),
313                                    (*i).c_str(),this);
314       rmenu->addAction(current);
315       connect(current,SIGNAL(triggered()),this,SLOT(OpenRecentImage()));
316     }
317   }
318
319   // Adding all new tools (insertion in the menu)
320   vvToolManager::GetInstance()->InsertToolsInMenu(this);
321
322   if (!CLITK_EXPERIMENTAL)
323     menuExperimental->menuAction()->setVisible(false);
324
325
326   QTimer * timerMemory = new QTimer(this);
327   //timerMemory->setInterval(5);
328   connect(timerMemory, SIGNAL(timeout()), this, SLOT(UpdateMemoryUsage()));
329   timerMemory->start(2000);
330 }
331 //------------------------------------------------------------------------------
332
333
334 //------------------------------------------------------------------------------
335 void vvMainWindow::UpdateMemoryUsage()
336 {
337   //  clitk::PrintMemory(true);
338   if (clitk::GetMemoryUsageInMb() == 0) infoPanel->setMemoryInMb("NA");
339   else infoPanel->setMemoryInMb(QString::number(clitk::GetMemoryUsageInMb())+" MiB");
340 }
341 //------------------------------------------------------------------------------
342
343
344 //------------------------------------------------------------------------------
345 void vvMainWindow::ComputeMIP()
346 {
347   vvMaximumIntensityProjection mip;
348   vvSlicerManager* selected_slicer = mSlicerManagers[GetSlicerIndexFromItem(DataTree->selectedItems()[0])];
349   QFileInfo info(selected_slicer->GetFileName().c_str());
350   mip.Compute(selected_slicer);
351   if (!mip.error)
352     AddImage(mip.GetOutput(),info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_mip.mhd");
353 }
354 //------------------------------------------------------------------------------
355
356
357 //------------------------------------------------------------------------------
358 void vvMainWindow::ComputeMidPosition()
359 {
360   bool ok;
361   int index=GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
362   int ref = QInputDialog::getInteger(this,"Chose reference phase","Reference phase",0,0,\
363                                      mSlicerManagers[index]->GetImage()->GetVTKImages().size()-1,1,&ok);
364   if (ok) {
365     vvMidPosition midp;
366     midp.slicer_manager = mSlicerManagers[index];
367     midp.reference_image_index = ref;
368     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
369     midp.Update();
370     if (midp.error)
371       QMessageBox::warning(this, "Error computing midposition image",midp.error_message.c_str());
372     else {
373       QFileInfo info(midp.slicer_manager->GetFileName().c_str());
374       AddImage(midp.output,info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_midposition.mhd");
375     }
376     QApplication::restoreOverrideCursor();
377   }
378 }
379 //------------------------------------------------------------------------------
380
381
382 //------------------------------------------------------------------------------
383 void vvMainWindow::AddContour(int image_index, vvMesh::Pointer contour, bool propagation)
384 {
385   QTreeWidgetItem *item = new QTreeWidgetItem();
386   item->setData(0,Qt::UserRole,"filename.vtk");
387   item->setData(1,Qt::UserRole,tr("contour"));
388   QBrush brush;
389   brush.setColor(QColor(contour->r*255,contour->g*255,contour->b*255));
390   brush.setStyle(Qt::SolidPattern);
391   item->setData(COLUMN_IMAGE_NAME,Qt::BackgroundRole,brush);
392   item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,contour->structure_name.c_str());
393
394   for (int j = 1; j <= 4; j++)
395     item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(image_index)->data(j,Qt::CheckStateRole));
396
397   QTreePushButton* cButton = new QTreePushButton;
398   cButton->setItem(item);
399   cButton->setColumn(COLUMN_CLOSE_IMAGE);
400   cButton->setToolTip(tr("close image"));
401   cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
402   connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
403           this,SLOT(CloseImage(QTreeWidgetItem*, int)));
404
405   QTreePushButton* rButton = new QTreePushButton;
406   rButton->setItem(item);
407   rButton->setColumn(COLUMN_RELOAD_IMAGE);
408   rButton->setToolTip(tr("reload image"));
409   rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
410   rButton->setEnabled(false);
411   //Not implemented
412   //connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
413   //this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
414
415   DataTree->topLevelItem(image_index)->setExpanded(1);
416   DataTree->topLevelItem(image_index)->addChild(item);
417   DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
418   DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
419   QString id = DataTree->topLevelItem(image_index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString();
420   item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
421
422   UpdateTree();
423   mSlicerManagers[image_index]->AddContour(contour,propagation);
424   mSlicerManagers[image_index]->Render();
425 }
426 //------------------------------------------------------------------------------
427
428
429 //------------------------------------------------------------------------------
430 void vvMainWindow::OpenVTKContour()
431 {
432   if (mSlicerManagers.size() > 0) {
433     QString Extensions = "Images ( *.vtk *.obj)";
434     Extensions += ";;All Files (*)";
435     QString file = QFileDialog::getOpenFileName(this,tr("Open vtkPolyData"),mInputPathName,Extensions);
436     if (file.isNull())
437       return;
438     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
439     int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
440     vvMeshReader reader;
441     reader.SetImage(mSlicerManagers[index]->GetImage());
442     reader.SetModeToVTK();
443     reader.SetFilename(file.toStdString());
444     reader.Update();
445     AddContour(index,reader.GetOutput()[0],false);
446     QApplication::restoreOverrideCursor();
447   }
448 }
449 //------------------------------------------------------------------------------
450
451
452 //------------------------------------------------------------------------------
453 void vvMainWindow::OpenDCStructContour()
454 {
455   if (mSlicerManagers.size() > 0) {
456     QString Extensions = "Dicom Files ( *.dcm RS*)";
457     Extensions += ";;All Files (*)";
458     QString file = QFileDialog::getOpenFileName(this,tr("Merge Images"),mInputPathName,Extensions);
459     if (file.isNull())
460       return;
461     int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
462     vvMeshReader reader;
463     reader.SetFilename(file.toStdString());
464     vvStructSelector selector;
465     selector.SetStructures(reader.GetROINames());
466     if (!mSlicerManagers[index]->GetVF().IsNull())
467       selector.EnablePropagationCheckBox();
468     if (selector.exec()) {
469       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
470       reader.SetSelectedItems(selector.getSelectedItems());
471       reader.SetImage(mSlicerManagers[index]->GetImage());
472       if (selector.PropagationEnabled())
473         reader.SetPropagationVF(mSlicerManagers[index]->GetVF());
474       reader.Update();
475       std::vector<vvMesh::Pointer> contours=reader.GetOutput();
476       for (std::vector<vvMesh::Pointer>::iterator i=contours.begin();
477            i!=contours.end(); i++)
478         AddContour(index,*i,selector.PropagationEnabled());
479       QApplication::restoreOverrideCursor();
480     }
481   }
482 }
483 //------------------------------------------------------------------------------
484
485
486 //------------------------------------------------------------------------------
487 void vvMainWindow::ComputeDeformableRegistration()
488 {
489   if (mSlicerManagers.size() > 0) {
490     int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
491     vvDeformationDialog dialog(index,mSlicerManagers);
492     if (dialog.exec()) {
493       std::string base_name=itksys::SystemTools::GetFilenameWithoutExtension(mSlicerManagers[dialog.GetInputFileIndex()]->GetFileName());
494       AddField(dialog.GetOutput(),dialog.getFieldFile(),dialog.GetInputFileIndex());
495       WarpImage(dialog.GetSelectedSlicer(),dialog.GetReferenceFrameIndex());
496     } else
497       std::cout << "Error or user cancellation while computing deformation field..." << std::endl;
498   } else QMessageBox::information(this, "Need to open image","You must open an image first.");
499 }
500 //------------------------------------------------------------------------------
501
502
503 //------------------------------------------------------------------------------
504 void vvMainWindow::WarpImage()
505 {
506   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
507   if (!mSlicerManagers[index]->GetVF().IsNull()) {
508     bool ok;
509     int ref = QInputDialog::getInteger(this,"Chose reference phase","Reference phase",0,0,\
510                                        mSlicerManagers[index]->GetImage()->GetVTKImages().size()-1,1,&ok);
511     if (ok) {
512       WarpImage(mSlicerManagers[index],ref);
513     }
514   } else
515     QMessageBox::warning(this,tr("No vector field"),tr("Sorry, can't warp without a vector field"));
516 }
517 //------------------------------------------------------------------------------
518
519
520 //------------------------------------------------------------------------------
521 void vvMainWindow::WarpImage(vvSlicerManager* selected_slicer,int reference_phase)
522 {
523   if (!selected_slicer->GetVF().IsNull()) {
524     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
525     QFileInfo info(selected_slicer->GetFileName().c_str());
526     vvImageWarp warp(selected_slicer->GetImage(),selected_slicer->GetVF(),
527                      reference_phase,this);
528     if (warp.ComputeWarpedImage()) {
529       AddImage(warp.GetWarpedImage(),info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_warped.mhd");
530       AddImage(warp.GetDiffImage()  ,info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_diff.mhd");
531       AddImage(warp.GetJacobianImage()  ,info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_jacobian.mhd");
532       QApplication::restoreOverrideCursor();
533     } else {
534       QApplication::restoreOverrideCursor();
535       QMessageBox::warning(this,tr("Different spacings"),tr("The vector field and image spacings must be the same in order to warp."));
536     }
537   } else
538     QMessageBox::warning(this,tr("No vector field"),tr("Sorry, can't warp without a vector field."));
539 }
540 //------------------------------------------------------------------------------
541
542
543 //------------------------------------------------------------------------------
544 vvMainWindow::~vvMainWindow()
545 {
546   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
547     if (mSlicerManagers[i] != NULL)
548       delete mSlicerManagers[i];
549   }
550 }
551 //------------------------------------------------------------------------------
552
553 //------------------------------------------------------------------------------
554 QTabWidget * vvMainWindow::GetTab()
555 {
556   return tabWidget;
557 }
558 //------------------------------------------------------------------------------
559
560
561 //------------------------------------------------------------------------------
562 void vvMainWindow::MergeImages()
563 {
564   QString Extensions = EXTENSIONS;
565   Extensions += ";;All Files (*)";
566   QStringList files = QFileDialog::getOpenFileNames(this,tr("Merge Images"),mInputPathName,Extensions);
567   if (files.isEmpty())
568     return;
569   mInputPathName = itksys::SystemTools::GetFilenamePath(files[0].toStdString()).c_str();
570   std::vector<std::string> vector;
571
572   unsigned int currentDim = 0;
573   std::vector<double> currentSpacing;
574   std::vector<int> currentSize;
575   std::vector<double> currentOrigin;
576
577   for (int i = 0; i < files.size(); i++) {
578     itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO(
579                                          files[i].toStdString().c_str(), itk::ImageIOFactory::ReadMode);
580     reader->SetFileName(files[i].toStdString().c_str());
581     reader->ReadImageInformation();
582     if (reader)        {
583       //NOViewWidget->hide();
584       //NEViewWidget->hide();
585       //SOViewWidget->hide();
586       //SEViewWidget->hide();
587       if (i == 0)
588         currentDim = reader->GetNumberOfDimensions();
589       bool IsOk = true;
590       for (unsigned int j = 0; j < currentDim; j++) {
591         if (i == 0) {
592           if (j == 0) {
593             currentSpacing.resize(currentDim);
594             currentSize.resize(currentDim);
595             currentOrigin.resize(currentDim);
596           }
597           currentOrigin[j] = reader->GetOrigin(j);
598           currentSpacing[j] = reader->GetSpacing(j);
599           currentSize[j] = reader->GetDimensions(j);
600         } else if (currentDim != reader->GetNumberOfDimensions()
601                    || currentSpacing[j] != reader->GetSpacing(j)
602                    || currentSize[j] != (int)reader->GetDimensions(j)
603                    || currentOrigin[j] != reader->GetOrigin(j)) {
604           QString error = "Cannot read file (too different from others ";
605           error += files[i].toStdString().c_str();
606           QMessageBox::information(this,tr("Reading problem"),error);
607           IsOk = false;
608           break;
609         }
610       }
611       if (IsOk)
612         vector.push_back(files[i].toStdString());
613     }
614   }
615   if (vector.size() > 0)
616     LoadImages(vector, MERGED);
617 }
618 //------------------------------------------------------------------------------
619
620 //------------------------------------------------------------------------------
621 void vvMainWindow::SliceImages()
622 {
623   QString Extensions = EXTENSIONS;
624   Extensions += ";;All Files (*)";
625
626   QStringList files = QFileDialog::getOpenFileNames(this,tr("Slice Images"),mInputPathName,Extensions);
627   if (files.isEmpty())
628     return;
629   mInputPathName = itksys::SystemTools::GetFilenamePath(files[0].toStdString()).c_str();
630   std::vector<std::string> vector;
631   for (int i = 0; i < files.size(); i++)
632     vector.push_back(files[i].toStdString());
633   LoadImages(vector, SLICED);
634 }
635 //------------------------------------------------------------------------------
636
637 //------------------------------------------------------------------------------
638 void vvMainWindow::MergeImagesWithTime()
639 {
640   QString Extensions = EXTENSIONS;
641   Extensions += ";;All Files (*)";
642   QStringList files = QFileDialog::getOpenFileNames(this,tr("Merge Images With Time"),mInputPathName,Extensions);
643   if (files.isEmpty())
644     return;
645   mInputPathName = itksys::SystemTools::GetFilenamePath(files[0].toStdString()).c_str();
646   std::vector<std::string> vector;
647
648   unsigned int currentDim = 0;
649   std::vector<double> currentSpacing;
650   std::vector<int> currentSize;
651   std::vector<double> currentOrigin;
652
653   for (int i = 0; i < files.size(); i++) {
654     itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO(
655                                          files[i].toStdString().c_str(), itk::ImageIOFactory::ReadMode);
656     if (reader) {
657       reader->SetFileName(files[i].toStdString().c_str());
658       reader->ReadImageInformation();
659       if (i == 0)
660         currentDim = reader->GetNumberOfDimensions();
661       bool IsOk = true;
662       for (unsigned int j = 0; j < currentDim; j++) {
663         if (i == 0) {
664           if (j == 0) {
665             currentSpacing.resize(currentDim);
666             currentSize.resize(currentDim);
667             currentOrigin.resize(currentDim);
668           }
669           currentOrigin[j] = reader->GetOrigin(j);
670           currentSpacing[j] = reader->GetSpacing(j);
671           currentSize[j] = reader->GetDimensions(j);
672         } else if (currentDim != reader->GetNumberOfDimensions()
673                    || currentSpacing[j] != reader->GetSpacing(j)
674                    || currentSize[j] != (int)reader->GetDimensions(j)
675                    || currentOrigin[j] != reader->GetOrigin(j)) {
676           QString error = "Cannot read file (too different from others ";
677           error += files[i].toStdString().c_str();
678           QMessageBox::information(this,tr("Reading problem"),error);
679           IsOk = false;
680           break;
681         }
682       }
683       if (IsOk)
684         vector.push_back(files[i].toStdString());
685     } else {
686       QString error = "Cannot read file info for ";
687       error += files[i].toStdString().c_str();
688       error += "\n";
689       error += "Maybe you're trying to open an image in an unsupported format?\n";
690       QMessageBox::information(this,tr("Reading problem"),error);
691     }
692   }
693   sort(vector.begin(),vector.end());
694   if (vector.size() > 1)
695     LoadImages(vector, MERGEDWITHTIME);
696   else
697     QMessageBox::warning(this,tr("Reading problem"),"You need to select at least two images to merge images with time.\nIf you only want to open one image, please use the \"Open Image\" function.");
698 }
699 //------------------------------------------------------------------------------
700
701
702 //------------------------------------------------------------------------------
703 void vvMainWindow::OpenDicom()
704 {
705   std::vector<std::string> files;
706
707   std::cout << "dicomSeriesSelector " << std::endl;
708   if (dicomSeriesSelector->exec() == QDialog::Accepted) {
709     files = *(dicomSeriesSelector->GetFilenames());
710     LoadImages(files,DICOM);
711   }
712 }
713 //------------------------------------------------------------------------------
714
715 //------------------------------------------------------------------------------
716 void vvMainWindow::OpenImages()
717 {
718   QString Extensions = EXTENSIONS;
719   Extensions += ";;All Files (*)";
720
721   QStringList files = QFileDialog::getOpenFileNames(this,tr("Load Images"),mInputPathName,Extensions);
722   if (files.isEmpty())
723     return;
724   mInputPathName = itksys::SystemTools::GetFilenamePath(files[0].toStdString()).c_str();
725   std::vector<std::string> vector;
726   for (int i = 0; i < files.size(); i++)
727     vector.push_back(files[i].toStdString());
728   LoadImages(vector, IMAGE);
729 }
730 //------------------------------------------------------------------------------
731 void vvMainWindow::OpenRecentImage()
732 {
733   QAction * caller = qobject_cast<QAction*>(sender());
734   std::vector<std::string> images;
735   images.push_back(caller->text().toStdString());
736   mInputPathName = itksys::SystemTools::GetFilenamePath(images[0]).c_str();
737   LoadImages(images,IMAGE);
738 }
739 //------------------------------------------------------------------------------
740
741
742 //------------------------------------------------------------------------------
743 void vvMainWindow::OpenImageWithTime()
744 {
745   QString Extensions = EXTENSIONS;
746   Extensions += ";;All Files (*)";
747
748   QStringList files = QFileDialog::getOpenFileNames(this,tr("Load Images With Time"),mInputPathName,Extensions);
749   if (files.isEmpty())
750     return;
751   mInputPathName = itksys::SystemTools::GetFilenamePath(files[0].toStdString()).c_str();
752   std::vector<std::string> vector;
753   for (int i = 0; i < files.size(); i++) {
754     vector.push_back(files[i].toStdString());
755   }
756   LoadImages(vector, IMAGEWITHTIME);
757 }
758 //------------------------------------------------------------------------------
759
760
761 //------------------------------------------------------------------------------
762 void vvMainWindow::LoadImages(std::vector<std::string> files, LoadedImageType filetype)
763 {
764   //Separate the way to open images and dicoms
765   int fileSize;
766   if (filetype == IMAGE || filetype == IMAGEWITHTIME)
767     fileSize = files.size();
768   else
769     fileSize = 1;
770
771   // For SLICED, we need the number of slices (ndim and #slices)
772   std::vector<unsigned int> nSlices;
773   nSlices.resize(files.size());
774   std::fill(nSlices.begin(), nSlices.end(), 1);
775   if (filetype == SLICED) {
776     for (int i = 0; i < fileSize; i++) {
777       itk::ImageIOBase::Pointer header = clitk::readImageHeader(files[i]);
778       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
779       if (!header) {
780         nSlices[i] = 0;
781         QString error = "Cannot open file \n";
782         error += files[i].c_str();
783         QMessageBox::information(this,tr("Reading problem"),error);
784         return;
785       }
786       if (header->GetNumberOfDimensions() < 3) {
787         nSlices[i] = 0;
788         QString error = "Dimension problem. Cannot slice \n";
789         error += files[i].c_str();
790         QMessageBox::information(this,tr("Reading problem"),error);
791         return;
792       }
793       nSlices[i] = header->GetDimensions( header->GetNumberOfDimensions()-1 );
794     }
795   }
796
797   //Only add to the list of recently opened files when a single file is opened,
798   //to avoid polluting the list of recently opened files
799   if (files.size() == 1) {
800     QFileInfo finfo=tr(files[0].c_str());
801     AddToRecentlyOpenedImages(finfo.absoluteFilePath().toStdString());
802   }
803   //init the progress events
804   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
805   vvProgressDialog progress("Opening " + files[0],fileSize>1);
806   qApp->processEvents();
807
808   int numberofsuccesulreads=0;
809   //open images as 1 or multiples
810   for (int i = 0; i < fileSize; i++) {
811
812     progress.SetText("Opening " + files[i]);
813     progress.SetProgress(i,fileSize);
814     qApp->processEvents();
815
816     for (unsigned int j = 0; j < nSlices[i]; j++) {
817       //read the image and put it in mSlicerManagers
818       vvSlicerManager* imageManager = new vvSlicerManager(4);
819       qApp->processEvents();
820
821       bool SetImageSucceed=false;
822
823       // Change filename if an image with the same already exist
824       int number = GetImageDuplicateFilenameNumber(files[i] + std::string("_slice"));
825
826       if (filetype == IMAGE || filetype == IMAGEWITHTIME || filetype == SLICED)
827         SetImageSucceed = imageManager->SetImage(files[i],filetype, number, j);
828       else {
829         SetImageSucceed = imageManager->SetImages(files,filetype, number);
830       }
831       if (SetImageSucceed == false) {
832         QApplication::restoreOverrideCursor();
833         QString error = "Cannot open file \n";
834         error += imageManager->GetLastError().c_str();
835         QMessageBox::information(this,tr("Reading problem"),error);
836         delete imageManager;
837       } else {
838         mSlicerManagers.push_back(imageManager);
839
840         //create an item in the tree with good settings
841         QTreeWidgetItem *item = new QTreeWidgetItem();
842         item->setData(0,Qt::UserRole,files[i].c_str());
843         QFileInfo fileinfo(imageManager->GetFileName().c_str()); //Do not show the path
844         item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,fileinfo.fileName());
845         item->setToolTip(COLUMN_IMAGE_NAME,fileinfo.absoluteFilePath());
846         qApp->processEvents();
847
848         //Create the buttons for reload and close
849         qApp->processEvents();
850         QTreePushButton* cButton = new QTreePushButton;
851         cButton->setItem(item);
852         cButton->setColumn(COLUMN_CLOSE_IMAGE);
853         cButton->setToolTip(tr("close image"));
854         cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
855         connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
856                 this,SLOT(CloseImage(QTreeWidgetItem*, int)));
857
858         QTreePushButton* rButton = new QTreePushButton;
859         rButton->setItem(item);
860         rButton->setColumn(COLUMN_RELOAD_IMAGE);
861         rButton->setToolTip(tr("reload image"));
862         rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
863         connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
864                 this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
865
866         DataTree->addTopLevelItem(item);
867         DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
868         DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
869
870         //set the id of the image
871         QString id = files[i].c_str() + QString::number(mSlicerManagers.size()-1);
872         item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
873         mSlicerManagers.back()->SetId(id.toStdString());
874
875         linkPanel->addImage(imageManager->GetFileName(), id.toStdString());
876
877         connect(mSlicerManagers.back(), SIGNAL(currentImageChanged(std::string)),
878                 this,SLOT(CurrentImageChanged(std::string)));
879         connect(mSlicerManagers.back(), SIGNAL(UpdatePosition(int, double, double, double, double, double, double, double)),
880                 this,SLOT(MousePositionChanged(int,double, double, double, double, double, double, double)));
881         connect(mSlicerManagers.back(), SIGNAL(UpdateVector(int, double, double, double, double)),
882                 this, SLOT(VectorChanged(int,double,double,double, double)));
883         connect(mSlicerManagers.back(), SIGNAL(UpdateOverlay(int, double, double)),
884                 this, SLOT(OverlayChanged(int,double,double)));
885         connect(mSlicerManagers.back(), SIGNAL(UpdateFusion(int, double)),
886                 this, SLOT(FusionChanged(int,double)));
887         connect(mSlicerManagers.back(), SIGNAL(UpdateWindows(int, int, int)),
888                 this,SLOT(WindowsChanged(int, int, int)));
889         connect(mSlicerManagers.back(), SIGNAL(WindowLevelChanged(double, double,int, int)),
890                 this,SLOT(WindowLevelChanged(double, double, int, int)));
891         connect(mSlicerManagers.back(), SIGNAL(UpdateSlice(int,int)),
892                 this,SLOT(UpdateSlice(int,int)));
893         connect(mSlicerManagers.back(), SIGNAL(UpdateTSlice(int, int)),
894                 this,SLOT(UpdateTSlice(int, int)));
895         connect(mSlicerManagers.back(), SIGNAL(UpdateSliceRange(int,int,int,int,int)),
896                 this,SLOT(UpdateSliceRange(int,int,int,int,int)));
897         connect(mSlicerManagers.back(), SIGNAL(UpdateLinkManager(std::string,int,double,double,double,int)),
898                 this,SLOT(UpdateLinkManager(std::string,int,double,double,double,int)));
899         connect(mSlicerManagers.back(), SIGNAL(UpdateLinkedNavigation(std::string,vvSlicerManager*)),
900                 this,SLOT(UpdateLinkedNavigation(std::string,vvSlicerManager*)));
901         connect(mSlicerManagers.back(), SIGNAL(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)),
902                 this,SLOT(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)));
903         connect(mSlicerManagers.back(),SIGNAL(LandmarkAdded()),landmarksPanel,SLOT(AddPoint()));
904         InitSlicers();
905       }
906       numberofsuccesulreads++;
907     }
908   }
909   if (numberofsuccesulreads) {
910     NOViewWidget->show();
911     NEViewWidget->show();
912     SOViewWidget->show();
913     SEViewWidget->show();
914     UpdateTree();
915     InitDisplay();
916     ShowLastImage();
917
918     // Try to guess default WindowLevel
919     double range[2];
920     mSlicerManagers.back()->GetImage()->GetFirstVTKImageData()->GetScalarRange(range);
921     if ((range[0] == 0) && (range[1] == 1)) {
922       presetComboBox->setCurrentIndex(5);// binary
923     } else {
924       // TODO
925     }
926   }
927   QApplication::restoreOverrideCursor();
928 }
929 //------------------------------------------------------------------------------
930
931 //------------------------------------------------------------------------------
932 void vvMainWindow::UpdateTree()
933 {
934   DataTree->resizeColumnToContents(COLUMN_TREE);
935   DataTree->resizeColumnToContents(COLUMN_UL_VIEW);
936   DataTree->resizeColumnToContents(COLUMN_UR_VIEW);
937   DataTree->resizeColumnToContents(COLUMN_DL_VIEW);
938   DataTree->resizeColumnToContents(COLUMN_DR_VIEW);
939   DataTree->resizeColumnToContents(COLUMN_IMAGE_NAME);
940   DataTree->resizeColumnToContents(COLUMN_CLOSE_IMAGE);
941   DataTree->resizeColumnToContents(COLUMN_RELOAD_IMAGE);
942 }
943 //------------------------------------------------------------------------------
944
945 //------------------------------------------------------------------------------
946 void vvMainWindow::CurrentImageChanged(std::string id)
947 {
948   if (id == mCurrentSelectedImageId) return; // Do nothing
949   int selected = 0;
950   for (int i = 0; i < DataTree->topLevelItemCount(); i++) {
951     if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString().toStdString() == id) {
952       selected = i;
953     } else {
954       DataTree->topLevelItem(i)->setSelected(0);
955     }
956     for (int child = 0; child < DataTree->topLevelItem(i)->childCount(); child++)
957       DataTree->topLevelItem(i)->child(child)->setSelected(0);
958
959   }
960   DataTree->topLevelItem(selected)->setSelected(1);
961   mCurrentSelectedImageId = id;
962   emit SelectedImageHasChanged(mSlicerManagers[selected]);
963 }
964 //------------------------------------------------------------------------------
965
966 //------------------------------------------------------------------------------
967 void vvMainWindow::ImageInfoChanged()
968 {
969   contextActions[6]->setEnabled(1);
970   contextActions[5]->setEnabled(1);
971   actionSave_As->setEnabled(1);
972   actionAdd_VF_to_current_Image->setEnabled(1);
973   actionAdd_fusion_image->setEnabled(1);
974   actionNorth_East_Window->setEnabled(1);
975   actionNorth_West_Window->setEnabled(1);
976   actionSouth_East_Window->setEnabled(1);
977   actionSouth_West_Window->setEnabled(1);
978   inverseButton->setEnabled(1);
979
980   goToCursorPushButton->setEnabled(1);
981
982   if (DataTree->selectedItems().size()) {
983     int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
984
985     colorMapComboBox->setEnabled(1);
986     for (int i = 0; i < DataTree->topLevelItem(index)->childCount(); i++) {
987       if (DataTree->topLevelItem(index)->child(i)->data(1,Qt::UserRole).toString() == "overlay" ||
988           DataTree->topLevelItem(index)->child(i)->data(1,Qt::UserRole).toString() == "fusion") {
989         colorMapComboBox->setEnabled(0);
990         break;
991       }
992     }
993
994     std::vector<double> origin;
995     std::vector<double> inputSpacing;
996     std::vector<int> inputSize;
997     std::vector<double> sizeMM;
998     vtkSmartPointer<vtkMatrix4x4> transformation;
999     int dimension=0;
1000     QString pixelType;
1001     QString inputSizeInBytes;
1002     QString image = DataTree->selectedItems()[0]->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1003
1004     if (mSlicerManagers[index]->GetSlicer(0)->GetImage()->GetVTKImages().size() > 1 || playMode == 1) {
1005       playButton->setEnabled(1);
1006       frameRateLabel->setEnabled(1);
1007       frameRateSpinBox->setEnabled(1);
1008     } else {
1009       playButton->setEnabled(0);
1010       frameRateLabel->setEnabled(0);
1011       frameRateSpinBox->setEnabled(0);
1012     }
1013
1014     //read image header
1015     int NPixel = 1;
1016
1017     vvImage::Pointer imageSelected;
1018     if (DataTree->topLevelItem(index) == DataTree->selectedItems()[0]) {
1019       imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetImage();
1020       dimension = imageSelected->GetNumberOfDimensions();
1021       origin.resize(dimension);
1022       inputSpacing.resize(dimension);
1023       inputSize.resize(dimension);
1024       sizeMM.resize(dimension);
1025       pixelType = mSlicerManagers[index]->GetImage()->GetScalarTypeAsITKString().c_str();
1026       for (int i = 0; i < dimension; i++) {
1027         origin[i] = imageSelected->GetOrigin()[i];
1028         inputSpacing[i] = imageSelected->GetSpacing()[i];
1029         inputSize[i] = imageSelected->GetSize()[i];
1030         sizeMM[i] = inputSize[i]*inputSpacing[i];
1031         NPixel *= inputSize[i];
1032       }
1033       inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000);
1034     } else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "vector") {
1035       imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetVF();
1036       dimension = imageSelected->GetNumberOfDimensions();
1037       origin.resize(dimension);
1038       inputSpacing.resize(dimension);
1039       inputSize.resize(dimension);
1040       sizeMM.resize(dimension);
1041       pixelType = mSlicerManagers[index]->GetVF()->GetScalarTypeAsITKString().c_str();
1042       for (int i = 0; i < dimension; i++) {
1043         origin[i] = imageSelected->GetOrigin()[i];
1044         inputSpacing[i] = imageSelected->GetSpacing()[i];
1045         inputSize[i] = imageSelected->GetSize()[i];
1046         sizeMM[i] = inputSize[i]*inputSpacing[i];
1047         NPixel *= inputSize[i];
1048       }
1049       inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000);
1050     } else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "overlay") {
1051       imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetOverlay();
1052       dimension = imageSelected->GetNumberOfDimensions();
1053       origin.resize(dimension);
1054       inputSpacing.resize(dimension);
1055       inputSize.resize(dimension);
1056       sizeMM.resize(dimension);
1057       pixelType = mSlicerManagers[index]->GetImage()->GetScalarTypeAsITKString().c_str();
1058       for (int i = 0; i < dimension; i++) {
1059         origin[i] = imageSelected->GetOrigin()[i];
1060         inputSpacing[i] = imageSelected->GetSpacing()[i];
1061         inputSize[i] = imageSelected->GetSize()[i];
1062         sizeMM[i] = inputSize[i]*inputSpacing[i];
1063         NPixel *= inputSize[i];
1064       }
1065       inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000);
1066     } else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "fusion") {
1067       imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetFusion();
1068       dimension = imageSelected->GetNumberOfDimensions();
1069       origin.resize(dimension);
1070       inputSpacing.resize(dimension);
1071       inputSize.resize(dimension);
1072       sizeMM.resize(dimension);
1073       pixelType = mSlicerManagers[index]->GetImage()->GetScalarTypeAsITKString().c_str();
1074       for (int i = 0; i < dimension; i++) {
1075         origin[i] = imageSelected->GetOrigin()[i];
1076         inputSpacing[i] = imageSelected->GetSpacing()[i];
1077         inputSize[i] = imageSelected->GetSize()[i];
1078         sizeMM[i] = inputSize[i]*inputSpacing[i];
1079         NPixel *= inputSize[i];
1080       }
1081       inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000);
1082     }
1083
1084     transformation = imageSelected->GetTransform()->GetMatrix();
1085
1086     QString dim = QString::number(dimension) + " (";
1087     dim += pixelType + ")";
1088
1089     infoPanel->setFileName(image);
1090     infoPanel->setDimension(dim);
1091     infoPanel->setSizePixel(GetVectorIntAsString(inputSize));
1092     infoPanel->setSizeMM(GetVectorDoubleAsString(sizeMM));
1093     infoPanel->setOrigin(GetVectorDoubleAsString(origin));
1094     infoPanel->setSpacing(GetVectorDoubleAsString(inputSpacing));
1095     infoPanel->setNPixel(QString::number(NPixel)+" ("+inputSizeInBytes+")");
1096     infoPanel->setTransformation(Get4x4MatrixDoubleAsString(transformation));
1097
1098     landmarksPanel->SetCurrentLandmarks(mSlicerManagers[index]->GetLandmarks(),
1099                                         mSlicerManagers[index]->GetSlicer(0)->GetImage()->GetVTKImages().size());
1100     landmarksPanel->SetCurrentPath(mInputPathName.toStdString());
1101     landmarksPanel->SetCurrentImage(mSlicerManagers[index]->GetFileName().c_str());
1102
1103     overlayPanel->getCurrentImageName(mSlicerManagers[index]->GetFileName().c_str());
1104     for (int i = 0; i < 4; i++) {
1105       if (DataTree->selectedItems()[0]->data(i+1,Qt::CheckStateRole).toInt() > 0 || i == 3) {
1106         mSlicerManagers[index]->UpdateInfoOnCursorPosition(i);
1107         break;
1108       }
1109     }
1110     windowSpinBox->setValue(mSlicerManagers[index]->GetColorWindow());
1111     levelSpinBox->setValue(mSlicerManagers[index]->GetColorLevel());
1112     presetComboBox->setCurrentIndex(mSlicerManagers[index]->GetPreset());
1113     colorMapComboBox->setCurrentIndex(mSlicerManagers[index]->GetColorMap());
1114
1115     infoPanel->setFileName(image);
1116     infoPanel->setDimension(dim);
1117     infoPanel->setSizePixel(GetVectorIntAsString(inputSize));
1118     infoPanel->setSizeMM(GetVectorDoubleAsString(sizeMM));
1119     infoPanel->setOrigin(GetVectorDoubleAsString(origin));
1120     infoPanel->setSpacing(GetVectorDoubleAsString(inputSpacing));
1121     infoPanel->setNPixel(QString::number(NPixel)+" ("+inputSizeInBytes+")");
1122
1123     landmarksPanel->SetCurrentLandmarks(mSlicerManagers[index]->GetLandmarks(),
1124                                         mSlicerManagers[index]->GetSlicer(0)->GetImage()->GetVTKImages().size());
1125     landmarksPanel->SetCurrentPath(mInputPathName.toStdString());
1126     landmarksPanel->SetCurrentImage(mSlicerManagers[index]->GetFileName().c_str());
1127
1128     overlayPanel->getCurrentImageName(mSlicerManagers[index]->GetFileName().c_str());
1129     for (int i = 0; i < 4; i++) {
1130       if (DataTree->selectedItems()[0]->data(i+1,Qt::CheckStateRole).toInt() > 0 || i == 3) {
1131         mSlicerManagers[index]->UpdateInfoOnCursorPosition(i);
1132         break;
1133       }
1134     }
1135     windowSpinBox->setValue(mSlicerManagers[index]->GetColorWindow());
1136     levelSpinBox->setValue(mSlicerManagers[index]->GetColorLevel());
1137     presetComboBox->setCurrentIndex(mSlicerManagers[index]->GetPreset());
1138     colorMapComboBox->setCurrentIndex(mSlicerManagers[index]->GetColorMap());
1139
1140     if (mSlicerManagers[index]->GetSlicer(0)->GetVF()) {
1141       overlayPanel->getVFName(mSlicerManagers[index]->GetVFName().c_str());
1142       overlayPanel->getVFProperty(mSlicerManagers[index]->GetSlicer(0)->GetVFSubSampling(),
1143                                   mSlicerManagers[index]->GetSlicer(0)->GetVFScale(),
1144                                   mSlicerManagers[index]->GetSlicer(0)->GetVFLog());
1145     } else {
1146       overlayPanel->getVFName(mSlicerManagers[index]->GetVFName().c_str());
1147       overlayPanel->getVFProperty(-1,-1,-1);
1148     }
1149     if (mSlicerManagers[index]->GetSlicer(0)->GetOverlay()) {
1150       overlayPanel->getOverlayName(mSlicerManagers[index]->GetOverlayName().c_str());
1151       overlayPanel->getOverlayProperty(mSlicerManagers[index]->GetOverlayColor());
1152     } else {
1153       overlayPanel->getOverlayName(mSlicerManagers[index]->GetOverlayName().c_str());
1154       overlayPanel->getOverlayProperty(-1);
1155     }
1156     if (mSlicerManagers[index]->GetSlicer(0)->GetFusion()) {
1157       overlayPanel->getFusionName(mSlicerManagers[index]->GetFusionName().c_str());
1158       overlayPanel->getFusionProperty(mSlicerManagers[index]->GetFusionOpacity(),
1159                                       mSlicerManagers[index]->GetFusionColorMap(),
1160                                       mSlicerManagers[index]->GetFusionWindow(),
1161                                       mSlicerManagers[index]->GetFusionLevel());
1162     } else {
1163       overlayPanel->getFusionName(mSlicerManagers[index]->GetFusionName().c_str());
1164       overlayPanel->getFusionProperty(-1, -1,-1,-1);
1165     }
1166   }
1167 }
1168 //------------------------------------------------------------------------------
1169
1170 //------------------------------------------------------------------------------
1171 void vvMainWindow::ShowDocumentation()
1172 {
1173   documentation->show();
1174 }
1175 //------------------------------------------------------------------------------
1176 void vvMainWindow::ShowHelpDialog()
1177 {
1178   help_dialog->show();
1179 }
1180 //------------------------------------------------------------------------------
1181
1182 //------------------------------------------------------------------------------
1183 void vvMainWindow::ChangeViewMode()
1184 {
1185   QListIterator<int> it0(splitter_3->sizes());
1186   QListIterator<int> it1(splitter_3->sizes());
1187   int max0 = 0;
1188   int max1 = 1;
1189   while (it0.hasNext()) {
1190     max0 += it0.next();
1191   }
1192   while (it1.hasNext()) {
1193     max1 += it1.next();
1194   }
1195   QList<int> size0;
1196   QList<int> size1;
1197   if (viewMode == 1) {
1198     viewMode = 0;
1199     size0.push_back(max0);
1200     size0.push_back(0);
1201     size1.push_back(max1);
1202     size1.push_back(0);
1203     splitter_3->setSizes(size0);
1204     OSplitter->setSizes(size1);
1205     DataTree->setColumnHidden(2,1);
1206     DataTree->setColumnHidden(3,1);
1207     DataTree->setColumnHidden(4,1);
1208   } else {
1209     viewMode = 1;
1210     size0.push_back(int(max0/2));
1211     size0.push_back(int(max0/2));
1212     size1.push_back(int(max1/2));
1213     size1.push_back(int(max1/2));
1214     splitter_3->setSizes(size0);
1215     OSplitter->setSizes(size1);
1216     DataTree->setColumnHidden(2,0);
1217     DataTree->setColumnHidden(3,0);
1218     DataTree->setColumnHidden(4,0);
1219   }
1220 }
1221 //------------------------------------------------------------------------------
1222
1223 //------------------------------------------------------------------------------
1224 QString vvMainWindow::GetSizeInBytes(unsigned long size)
1225 {
1226   QString result = "";// QString::number(size);
1227   //result += " bytes (";
1228   if (size > 1000000000) {
1229     size /= 1000000000;
1230     result += QString::number(size);
1231     result += "Gb";//)";
1232   } else if (size > 1000000) {
1233     size /= 1000000;
1234     result += QString::number(size);
1235     result += "Mb";//)";
1236   } else if (size > 1000) {
1237     size /= 1000;
1238     result += QString::number(size);
1239     result += "kb";//)";
1240   }
1241   return result;
1242 }
1243 //------------------------------------------------------------------------------
1244
1245 //------------------------------------------------------------------------------
1246 QString vvMainWindow::Get4x4MatrixDoubleAsString(vtkSmartPointer<vtkMatrix4x4> matrix)
1247 {
1248   std::ostringstream strmatrix;
1249
1250   for (unsigned int i = 0; i < 4; i++) {
1251     for (unsigned int j = 0; j < 4; j++) {
1252       strmatrix.flags(ios::showpos);
1253       strmatrix.width(10);
1254       strmatrix.precision(3);
1255       strmatrix.setf(ios::fixed,ios::floatfield);
1256       strmatrix.fill(' ');
1257       strmatrix << std::left << matrix->GetElement(i, j);
1258       //strmatrix.width(10);
1259       strmatrix << " ";
1260     }
1261     strmatrix << std::endl;
1262   }
1263   QString result = strmatrix.str().c_str();
1264   return result;
1265 }
1266 //------------------------------------------------------------------------------
1267
1268 //------------------------------------------------------------------------------
1269 QString vvMainWindow::GetVectorDoubleAsString(std::vector<double> vectorDouble)
1270 {
1271   QString result;
1272   for (unsigned int i= 0; i < vectorDouble.size(); i++) {
1273     if (i != 0)
1274       result += " ";
1275     result += QString::number(vectorDouble[i]);
1276   }
1277   return result;
1278 }
1279 //------------------------------------------------------------------------------
1280
1281 //------------------------------------------------------------------------------
1282 QString vvMainWindow::GetVectorIntAsString(std::vector<int> vectorInt)
1283 {
1284   QString result;
1285   for (unsigned int i= 0; i < vectorInt.size(); i++) {
1286     if (i != 0)
1287       result += " ";
1288     result += QString::number(vectorInt[i]);
1289   }
1290   return result;
1291 }
1292 //------------------------------------------------------------------------------
1293
1294 //------------------------------------------------------------------------------
1295 int vvMainWindow::GetSlicerIndexFromItem(QTreeWidgetItem* item)
1296 {
1297   QString id = item->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString();
1298   for (int i = 0; i < DataTree->topLevelItemCount(); i++) {
1299     if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString() == id)
1300       return i;
1301   }
1302   return -1;
1303 }
1304 //------------------------------------------------------------------------------
1305
1306 //------------------------------------------------------------------------------
1307 QTreeWidgetItem* vvMainWindow::GetItemFromSlicerManager(vvSlicerManager* sm)
1308 {
1309   QString id = sm->GetId().c_str();
1310   for (int i = 0; i < DataTree->topLevelItemCount(); i++) {
1311     if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString() == id)
1312       return DataTree->topLevelItem(i);
1313   }
1314   return NULL;
1315 }
1316 //------------------------------------------------------------------------------
1317
1318 //------------------------------------------------------------------------------
1319 void vvMainWindow::DisplayChanged(QTreeWidgetItem *clicked_item, int column)
1320 {
1321   int index = GetSlicerIndexFromItem(clicked_item);
1322   if ( column >= COLUMN_CLOSE_IMAGE || column <= 0)
1323     return;
1324   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
1325     //Trick to avoid redoing twice the job for a key (sr)
1326     mSlicerManagers[i]->GetSlicer(column-1)->GetRenderWindow()-> GetInteractor()->SetKeySym("Crap");
1327
1328     QTreeWidgetItem* current_row=DataTree->topLevelItem(i);
1329     if (DataTree->topLevelItem(index) == current_row) {
1330       vvSlicer* clicked_slicer=mSlicerManagers[i]->GetSlicer(column-1);
1331       if (current_row == clicked_item) {
1332         //If we just activated a slicer
1333         if (current_row->data(column,Qt::CheckStateRole).toInt() > 0) {
1334           mSlicerManagers[i]->UpdateSlicer(column-1,clicked_item->data(column,Qt::CheckStateRole).toInt());
1335           mSlicerManagers[i]->UpdateInfoOnCursorPosition(column-1);
1336           DisplaySliders(i,column-1);
1337           std::map<std::string,int> overlay_counts;
1338           for (int child = 0; child < current_row->childCount(); child++) {
1339             std::string overlay_type =
1340               current_row->child(child)->data(1,Qt::UserRole).toString().toStdString();
1341             overlay_counts[overlay_type]++;
1342             current_row->child(child)->setData(column,Qt::CheckStateRole,
1343                                                current_row->data(column,Qt::CheckStateRole));
1344             clicked_slicer->SetActorVisibility(overlay_type,overlay_counts[overlay_type]-1,true);
1345           }
1346         } else { //We don't allow simply desactivating a slicer
1347           clicked_item->setData(column,Qt::CheckStateRole,2);
1348           return;
1349         }
1350       }
1351       //if we clicked on the vector(or overlay) and not the image
1352       else {
1353         if (clicked_item->data(column,Qt::CheckStateRole).toInt()) {
1354           current_row->setData(column,Qt::CheckStateRole,2);
1355           mSlicerManagers[i]->UpdateSlicer(column-1,2);
1356           mSlicerManagers[i]->UpdateInfoOnCursorPosition(column-1);
1357           DisplaySliders(i,column-1);
1358         }
1359         int vis = clicked_item->data(column,Qt::CheckStateRole).toInt();
1360         std::string overlay_type = clicked_item->data(1,Qt::UserRole).toString().toStdString();
1361         int overlay_index=0;
1362         for (int child = 0; child < current_row->childCount(); child++) {
1363           if (current_row->child(child)->data(1,Qt::UserRole).toString().toStdString() == overlay_type)
1364             overlay_index++;
1365           if (current_row->child(child) == clicked_item) break;
1366         }
1367         clicked_slicer->SetActorVisibility(
1368           clicked_item->data(1,Qt::UserRole).toString().toStdString(), overlay_index-1,vis);
1369       }
1370     } else if (current_row->data(column,Qt::CheckStateRole).toInt() > 0) {
1371       current_row->setData(column,Qt::CheckStateRole,0);
1372       mSlicerManagers[i]->UpdateSlicer(column-1,0);
1373       std::map<std::string,int> overlay_counts;
1374       for (int child = 0; child < current_row->childCount(); child++) {
1375         std::string overlay_type =
1376           current_row->child(child)->data(1,Qt::UserRole).toString().toStdString();
1377         overlay_counts[overlay_type]++;
1378         current_row->child(child)->setData(column,Qt::CheckStateRole,0);
1379         vvSlicer * current_slicer=mSlicerManagers[i]->GetSlicer(column-1);
1380         current_slicer->SetActorVisibility(overlay_type,overlay_counts[overlay_type]-1,false);
1381       }
1382     }
1383     //mSlicerManagers[i]->SetColorMap(-1);
1384     mSlicerManagers[i]->SetColorMap();
1385   }
1386   mSlicerManagers[index]->GetSlicer(column-1)->Render();
1387 }
1388 //------------------------------------------------------------------------------
1389
1390 void vvMainWindow::InitSlicers()
1391 {
1392   if (mSlicerManagers.size()) {
1393     mSlicerManagers.back()->GenerateDefaultLookupTable();
1394
1395     mSlicerManagers.back()->SetSlicerWindow(0,NOViewWidget->GetRenderWindow());
1396     mSlicerManagers.back()->SetSlicerWindow(1,NEViewWidget->GetRenderWindow());
1397     mSlicerManagers.back()->SetSlicerWindow(2,SOViewWidget->GetRenderWindow());
1398     mSlicerManagers.back()->SetSlicerWindow(3,SEViewWidget->GetRenderWindow());
1399   }
1400 }
1401
1402 //------------------------------------------------------------------------------
1403 void vvMainWindow::InitDisplay()
1404 {
1405   if (mSlicerManagers.size()) {
1406     //BE CAREFUL : this is absolutely necessary to set the interactor style
1407     //in order to have the same style instanciation for all SlicerManagers in
1408     // a same window
1409     for (int j = 0; j < 4; j++) {
1410       vvInteractorStyleNavigator* style = vvInteractorStyleNavigator::New();
1411       style->SetAutoAdjustCameraClippingRange(1);
1412       bool AlreadySelected = false;
1413       for (int i = 0; i < DataTree->topLevelItemCount(); i++) {
1414         mSlicerManagers[i]->SetInteractorStyleNavigator(j,style);
1415
1416         //select the image only if previous are not selected
1417         if (DataTree->topLevelItem(i)->data(j+1,Qt::CheckStateRole).toInt() > 1) {
1418           mSlicerManagers[i]->UpdateSlicer(j,1);
1419           AlreadySelected = true;
1420         } else if (i == DataTree->topLevelItemCount()-1 && !AlreadySelected) {
1421           if (DataTree->selectedItems().size() == 0)
1422             DataTree->topLevelItem(i)->setSelected(1);
1423           DataTree->topLevelItem(i)->setData(j+1,Qt::CheckStateRole,2);
1424           mSlicerManagers[i]->UpdateSlicer(j,1);
1425           DisplaySliders(i,j);
1426         } else {
1427           DataTree->topLevelItem(i)->setData(j+1,Qt::CheckStateRole,0);
1428           mSlicerManagers[i]->UpdateSlicer(j,0);
1429         }
1430       }
1431       style->Delete();
1432     }
1433   }
1434 }
1435 //------------------------------------------------------------------------------
1436
1437 //------------------------------------------------------------------------------
1438 void vvMainWindow::DisplaySliders(int slicer, int window)
1439 {
1440   int range[2];
1441   mSlicerManagers[slicer]->GetSlicer(window)->GetSliceRange(range);
1442   int position = mSlicerManagers[slicer]->GetSlicer(window)->GetSlice();
1443
1444   int tRange[2];
1445   tRange[0] = 0;
1446   tRange[1] = mSlicerManagers[slicer]->GetSlicer(window)->GetTMax();
1447   int tPosition = mSlicerManagers[slicer]->GetSlicer(window)->GetTSlice();
1448   bool showHorizontal = false;
1449   bool showVertical = false;
1450   if (mSlicerManagers[slicer]->GetSlicer(window)->GetImage()->GetNumberOfDimensions() > 3
1451       || (mSlicerManagers[slicer]->GetSlicer(window)->GetImage()->GetNumberOfDimensions() > 2
1452           && mSlicerManagers[slicer]->GetType() != IMAGEWITHTIME
1453           && mSlicerManagers[slicer]->GetType() != MERGEDWITHTIME))
1454     showVertical = true;
1455   if (mSlicerManagers[slicer]->GetSlicer(window)->GetImage()->GetNumberOfDimensions() > 3
1456       || mSlicerManagers[slicer]->GetType() == IMAGEWITHTIME
1457       || mSlicerManagers[slicer]->GetType() == MERGEDWITHTIME)
1458     showHorizontal = true;
1459
1460   if (showVertical)
1461     verticalSliders[window]->show();
1462   else
1463     verticalSliders[window]->hide();
1464   verticalSliders[window]->setRange(range[0],range[1]);
1465   verticalSliders[window]->setValue(position);
1466
1467   if (showHorizontal)
1468     horizontalSliders[window]->show();
1469   else
1470     horizontalSliders[window]->hide();
1471   horizontalSliders[window]->setRange(tRange[0],tRange[1]);
1472   horizontalSliders[window]->setValue(tPosition);
1473 }
1474 //------------------------------------------------------------------------------
1475
1476 //------------------------------------------------------------------------------
1477 void vvMainWindow::CloseImage(QTreeWidgetItem* item, int column)
1478 {
1479   int index = GetSlicerIndexFromItem(item);
1480
1481   if (DataTree->topLevelItem(index) != item) {
1482     QString warning = "Do you really want to close the overlay : ";
1483     warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1484     QMessageBox msgBox(QMessageBox::Warning, tr("Close Overlay"),
1485                        warning, 0, this);
1486     msgBox.addButton(tr("Close"), QMessageBox::AcceptRole);
1487     msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
1488     if (msgBox.exec() == QMessageBox::AcceptRole) {
1489       std::string overlay_type=item->data(1,Qt::UserRole).toString().toStdString();
1490       int overlay_index=0;
1491       for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++) {
1492         if (DataTree->topLevelItem(index)->\
1493             child(child)->data(1,Qt::UserRole).toString().toStdString() == overlay_type)
1494           overlay_index++;
1495         if (DataTree->topLevelItem(index)->child(child) == item) break;
1496       }
1497       mSlicerManagers[index]->RemoveActor(overlay_type, overlay_index-1);
1498       mSlicerManagers[index]->SetColorMap(0);
1499       DataTree->topLevelItem(index)->takeChild(DataTree->topLevelItem(index)->indexOfChild(item));
1500       mSlicerManagers[index]->Render();
1501     }
1502   } else if (DataTree->topLevelItemCount() <= 1) {
1503     QString warning = "Do you really want to close the image : ";
1504     warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1505     warning += "\nThis is the last image, you're about to close vv !!!";
1506     QMessageBox msgBox(QMessageBox::Warning, tr("Close Image"),
1507                        warning, 0, this);
1508     msgBox.addButton(tr("Close vv"), QMessageBox::AcceptRole);
1509     msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
1510     if (msgBox.exec() == QMessageBox::AcceptRole) {
1511       this->close();
1512     }
1513   } else {
1514     QString warning = "Do you really want to close the image : ";
1515     warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1516     QMessageBox msgBox(QMessageBox::Warning, tr("Close Image"),
1517                        warning, 0, this);
1518     msgBox.addButton(tr("Close"), QMessageBox::AcceptRole);
1519     msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
1520     if (msgBox.exec() == QMessageBox::AcceptRole) {
1521
1522       // Tell tools that we close an image
1523       emit AnImageIsBeingClosed(mSlicerManagers[index]);
1524
1525       std::vector<vvSlicerManager*>::iterator Manageriter = mSlicerManagers.begin();
1526       DataTree->takeTopLevelItem(index);
1527       for (int i = 0; i < index; i++) {
1528         Manageriter++;
1529       }
1530       linkPanel->removeImage(index);
1531       mSlicerManagers[index]->RemoveActors();
1532       delete mSlicerManagers[index];
1533       mSlicerManagers.erase(Manageriter);
1534
1535       //
1536       InitDisplay();
1537     }
1538   }
1539   ImageInfoChanged();
1540 }
1541 //------------------------------------------------------------------------------
1542
1543 //------------------------------------------------------------------------------
1544 void vvMainWindow::ReloadImage(QTreeWidgetItem* item, int column)
1545 {
1546   // int index = GetSlicerIndexFromItem(item);
1547   //   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1548   //   if (item->data(1,Qt::UserRole).toString() == "vector")
1549   //     mSlicerManagers[index]->ReloadVF();
1550   //   else
1551   //     mSlicerManagers[index]->Reload();
1552
1553   //   QApplication::restoreOverrideCursor();
1554   int index = GetSlicerIndexFromItem(item);
1555   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1556   QString role=item->data(1,Qt::UserRole).toString();
1557   if ( role == "vector")
1558     mSlicerManagers[index]->ReloadVF();
1559   else if (role == "overlay")
1560     mSlicerManagers[index]->ReloadOverlay();
1561   else if (role == "fusion")
1562     mSlicerManagers[index]->ReloadFusion();
1563   else
1564     mSlicerManagers[index]->Reload();
1565
1566   // Update view and info
1567   ImageInfoChanged();
1568   mSlicerManagers[index]->Render();
1569   QApplication::restoreOverrideCursor();
1570 }
1571 //------------------------------------------------------------------------------
1572
1573 //------------------------------------------------------------------------------
1574 void vvMainWindow::MousePositionChanged(int visibility,double x, double y, double z, double X, double Y, double Z , double value)
1575 {
1576   infoPanel->setCurrentInfo(visibility,x,y,z,X,Y,Z,value);
1577 }
1578 //------------------------------------------------------------------------------
1579
1580 //------------------------------------------------------------------------------
1581 void vvMainWindow::VectorChanged(int visibility,double x, double y, double z, double value)
1582 {
1583   overlayPanel->getCurrentVectorInfo(visibility,x,y,z,value);
1584 }
1585 //------------------------------------------------------------------------------
1586
1587 //------------------------------------------------------------------------------
1588 void vvMainWindow::OverlayChanged(int visibility, double valueOver, double valueRef)
1589 {
1590   overlayPanel->getCurrentOverlayInfo(visibility,valueOver, valueRef);
1591 }
1592 //------------------------------------------------------------------------------
1593
1594 //------------------------------------------------------------------------------
1595 void vvMainWindow::FusionChanged(int visibility, double value)
1596 {
1597   overlayPanel->getCurrentFusionInfo(visibility,value);
1598 }
1599 //------------------------------------------------------------------------------
1600
1601 //------------------------------------------------------------------------------
1602 void vvMainWindow::WindowsChanged(int window, int view, int slice)
1603 {
1604   infoPanel->setViews(window, view, slice);
1605 }
1606 //------------------------------------------------------------------------------
1607
1608 //------------------------------------------------------------------------------
1609 void vvMainWindow::WindowLevelChanged(double window, double level,int preset,int colormap)
1610 {
1611   windowSpinBox->setValue(window);
1612   levelSpinBox->setValue(level);
1613   colorMapComboBox->setCurrentIndex(colormap);
1614   presetComboBox->setCurrentIndex(preset);
1615 }
1616 //------------------------------------------------------------------------------
1617
1618 //------------------------------------------------------------------------------
1619 void vvMainWindow::WindowLevelEdited()
1620 {
1621   presetComboBox->setCurrentIndex(6);
1622   UpdateWindowLevel();
1623 }
1624 //------------------------------------------------------------------------------
1625
1626 //------------------------------------------------------------------------------
1627 void vvMainWindow::UpdateWindowLevel()
1628 {
1629   if (DataTree->selectedItems().size()) {
1630     if (presetComboBox->currentIndex() == 7) //For ventilation
1631       colorMapComboBox->setCurrentIndex(5);
1632     int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1633     mSlicerManagers[index]->SetColorWindow(windowSpinBox->value());
1634     mSlicerManagers[index]->SetColorLevel(levelSpinBox->value());
1635     mSlicerManagers[index]->SetPreset(presetComboBox->currentIndex());
1636     mSlicerManagers[index]->Render();
1637     windowSpinBox->setValue(mSlicerManagers[index]->GetColorWindow());
1638     levelSpinBox->setValue(mSlicerManagers[index]->GetColorLevel());
1639   }
1640 }
1641 //------------------------------------------------------------------------------
1642
1643 //------------------------------------------------------------------------------
1644 void vvMainWindow::UpdateColorMap()
1645 {
1646   if (DataTree->selectedItems().size()) {
1647     int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1648     mSlicerManagers[index]->SetColorMap(colorMapComboBox->currentIndex());
1649     mSlicerManagers[index]->Render();
1650   }
1651 }
1652 //------------------------------------------------------------------------------
1653 void vvMainWindow::SwitchWindowLevel()
1654 {
1655   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1656   int window = mSlicerManagers[index]->GetColorWindow();
1657   presetComboBox->setCurrentIndex(6);
1658   windowSpinBox->setValue(-window);
1659   UpdateWindowLevel();
1660 }
1661 //------------------------------------------------------------------------------
1662
1663 //------------------------------------------------------------------------------
1664 void vvMainWindow::ApplyWindowLevelToAllImages()
1665 {
1666   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
1667     if (mSlicerManagers[i] == NULL)
1668       continue;
1669     mSlicerManagers[i]->SetColorWindow(windowSpinBox->value());
1670     mSlicerManagers[i]->SetColorLevel(levelSpinBox->value());
1671     mSlicerManagers[i]->SetPreset(6);
1672     mSlicerManagers[i]->Render();
1673   }
1674 }
1675 //------------------------------------------------------------------------------
1676
1677 //------------------------------------------------------------------------------
1678 void vvMainWindow::UpdateLinkManager(std::string id, int slicer, double x, double y, double z, int temps)
1679 {
1680   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
1681     if (mSlicerManagers[i]->GetId() == id) {
1682       //mSlicerManagers[i]->SetTSlice(temps);
1683       mSlicerManagers[i]->GetSlicer(slicer)->SetCurrentPosition(x,y,z,temps);
1684       mSlicerManagers[i]->UpdateViews(0,slicer);
1685       break;
1686     }
1687   }
1688 }
1689 //------------------------------------------------------------------------------
1690
1691 //------------------------------------------------------------------------------
1692 void vvMainWindow::UpdateLinkedNavigation(std::string id, vvSlicerManager * sm)
1693 {
1694   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
1695     if (id == mSlicerManagers[i]->GetId()) {
1696       mSlicerManagers[i]->UpdateLinkedNavigation(sm->GetSlicer(0));
1697     }
1698   }
1699 }
1700 //------------------------------------------------------------------------------
1701
1702 //------------------------------------------------------------------------------
1703 void vvMainWindow::ShowContextMenu(QPoint point)
1704 {
1705   if (!DataTree->selectedItems().size()) {
1706     contextActions[1]->setEnabled(0);
1707     contextActions[2]->setEnabled(0);
1708     contextActions[3]->setEnabled(0);
1709     contextActions[4]->setEnabled(0);
1710     contextActions[5]->setEnabled(0);
1711     contextActions[6]->setEnabled(0);
1712   } else {
1713     int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1714     contextActions[1]->setEnabled(1);
1715     contextActions[2]->setEnabled(
1716       DataTree->itemWidget(DataTree->selectedItems()[0],
1717                            COLUMN_RELOAD_IMAGE)->isEnabled());
1718     contextActions[3]->setEnabled(1);
1719     contextActions[5]->setEnabled(1);
1720     contextActions[6]->setEnabled(1);
1721
1722     if (mSlicerManagers[index]->GetDimension() < 3)
1723       contextActions[4]->setEnabled(0);
1724     else
1725       contextActions[4]->setEnabled(1);
1726   }
1727   contextMenu.exec(QCursor::pos());
1728 }
1729 //------------------------------------------------------------------------------
1730
1731 //------------------------------------------------------------------------------
1732 void vvMainWindow::CloseImage()
1733 {
1734   CloseImage(DataTree->selectedItems()[0],0);
1735 }
1736 //------------------------------------------------------------------------------
1737
1738 //------------------------------------------------------------------------------
1739 void vvMainWindow::ReloadImage()
1740 {
1741   ReloadImage(DataTree->selectedItems()[0],0);
1742 }
1743 //------------------------------------------------------------------------------
1744
1745 //------------------------------------------------------------------------------
1746 void vvMainWindow::SelectOverlayImage()
1747 {
1748   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1749
1750   //check if one overlay image is added
1751   for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++)
1752     if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "overlay") {
1753       QString error = "Cannot add more than one compared image\n";
1754       error += "Please remove first ";
1755       error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1756       QMessageBox::information(this,tr("Problem adding compared image !"),error);
1757       return;
1758     }
1759
1760   QString Extensions = EXTENSIONS;
1761   Extensions += ";;All Files (*)";
1762   QString file = QFileDialog::getOpenFileName(this,tr("Load Overlay image"),mInputPathName,Extensions);
1763   if (!file.isEmpty())
1764     AddOverlayImage(index,file);
1765 }
1766 //------------------------------------------------------------------------------
1767
1768 //------------------------------------------------------------------------------
1769 void vvMainWindow::AddOverlayImage(int index, QString file)
1770 {
1771
1772   mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str();
1773   itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO(
1774                                        file.toStdString().c_str(), itk::ImageIOFactory::ReadMode);
1775   reader->SetFileName(file.toStdString().c_str());
1776   reader->ReadImageInformation();
1777   std::string component = reader->GetComponentTypeAsString(reader->GetComponentType());
1778   int dimension = reader->GetNumberOfDimensions();
1779   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1780   vvProgressDialog progress("Opening " + file.toStdString());
1781   qApp->processEvents();
1782
1783   std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str();
1784   if (mSlicerManagers[index]->SetOverlay(file.toStdString(),dimension, component)) {
1785     //create an item in the tree with good settings
1786     QTreeWidgetItem *item = new QTreeWidgetItem();
1787     item->setData(0,Qt::UserRole,file.toStdString().c_str());
1788     item->setData(1,Qt::UserRole,tr("overlay"));
1789     QFileInfo fileinfo(file); //Do not show the path
1790     item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,fileinfo.fileName());
1791     item->setToolTip(COLUMN_IMAGE_NAME,fileinfo.absoluteFilePath());
1792     qApp->processEvents();
1793
1794     for (int j = 1; j <= 4; j++) {
1795       item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole));
1796       mSlicerManagers[index]->GetSlicer(j-1)->SetActorVisibility("overlay",0,
1797           DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole).toInt());
1798     }
1799
1800     //Create the buttons for reload and close
1801     qApp->processEvents();
1802     QTreePushButton* cButton = new QTreePushButton;
1803     cButton->setItem(item);
1804     cButton->setColumn(COLUMN_CLOSE_IMAGE);
1805     cButton->setToolTip(tr("close image"));
1806     cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
1807     connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
1808             this,SLOT(CloseImage(QTreeWidgetItem*, int)));
1809
1810     QTreePushButton* rButton = new QTreePushButton;
1811     rButton->setItem(item);
1812     rButton->setColumn(COLUMN_RELOAD_IMAGE);
1813     rButton->setToolTip(tr("reload image"));
1814     rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
1815     connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
1816             this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
1817
1818     DataTree->topLevelItem(index)->setExpanded(1);
1819     DataTree->topLevelItem(index)->addChild(item);
1820     DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
1821     DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
1822
1823     //set the id of the image
1824     QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString();
1825     item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
1826     UpdateTree();
1827     qApp->processEvents();
1828     ImageInfoChanged();
1829     QApplication::restoreOverrideCursor();
1830   } else {
1831     QApplication::restoreOverrideCursor();
1832     QString error = "Cannot import the new image.\n";
1833     error += mSlicerManagers[index]->GetLastError().c_str();
1834     QMessageBox::information(this,tr("Problem reading image !"),error);
1835   }
1836 }
1837 //------------------------------------------------------------------------------
1838
1839
1840 //------------------------------------------------------------------------------
1841 void vvMainWindow::AddROI(int index, QString file)
1842 {
1843   /*
1844   // Get slice manager
1845
1846   // Load image
1847
1848   vvImageReader * mReader = new vvImageReader;
1849   mReader->SetInputFilename(filename.toStdString());
1850   mReader->Update(IMAGE);
1851   if (mReader->GetLastError().size() != 0) {
1852     std::cerr << "Error while reading " << filename.toStdString() << std::endl;
1853     QString error = "Cannot open file \n";
1854     error += mReader->GetLastError().c_str();
1855     QMessageBox::information(this,tr("Reading problem"),error);
1856     delete mReader;
1857     return;
1858   }
1859   vvImage::Pointer roi = mReader->GetOutput();
1860
1861   // Create roi in new tool
1862   vvToolStructureSetManager::AddImage(mCurrentSlicerManager, roi);
1863   */
1864 }
1865 //------------------------------------------------------------------------------
1866
1867 //------------------------------------------------------------------------------
1868 void vvMainWindow::SelectFusionImage()
1869 {
1870   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1871
1872   //check if one fusion image is added
1873   for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++)
1874     if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "fusion") {
1875       QString error = "Cannot add more than one fusion image\n";
1876       error += "Please remove first ";
1877       error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1878       QMessageBox::information(this,tr("Problem adding fusion image !"),error);
1879       return;
1880     }
1881
1882   QString Extensions = EXTENSIONS;
1883   Extensions += ";;All Files (*)";
1884   QString file = QFileDialog::getOpenFileName(this,tr("Load Fusion image"),mInputPathName,Extensions);
1885   if (!file.isEmpty())
1886     AddFusionImage(index,file);
1887 }
1888 //------------------------------------------------------------------------------
1889
1890 //------------------------------------------------------------------------------
1891 void vvMainWindow::AddFusionImage(int index, QString file)
1892 {
1893   mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str();
1894   itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO(
1895                                        file.toStdString().c_str(), itk::ImageIOFactory::ReadMode);
1896   reader->SetFileName(file.toStdString().c_str());
1897   reader->ReadImageInformation();
1898   std::string component = reader->GetComponentTypeAsString(reader->GetComponentType());
1899   if (reader) {
1900     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1901     vvProgressDialog progress("Opening fusion");
1902     qApp->processEvents();
1903
1904     std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str();
1905     if (mSlicerManagers[index]->SetFusion(file.toStdString(),
1906                                           reader->GetNumberOfDimensions(), component)) {
1907       //create an item in the tree with good settings
1908       QTreeWidgetItem *item = new QTreeWidgetItem();
1909       item->setData(0,Qt::UserRole,file.toStdString().c_str());
1910       item->setData(1,Qt::UserRole,tr("fusion"));
1911       QFileInfo fileinfo(filename.c_str()); //Do not show the path
1912       item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,fileinfo.fileName());
1913       item->setToolTip(COLUMN_IMAGE_NAME,fileinfo.absoluteFilePath());
1914       qApp->processEvents();
1915
1916       for (int j = 1; j <= 4; j++) {
1917         item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole));
1918         mSlicerManagers[index]->GetSlicer(j-1)->SetActorVisibility("fusion",0,
1919             DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole).toInt());
1920       }
1921
1922       //Create the buttons for reload and close
1923       qApp->processEvents();
1924       QTreePushButton* cButton = new QTreePushButton;
1925       cButton->setItem(item);
1926       cButton->setColumn(COLUMN_CLOSE_IMAGE);
1927       cButton->setToolTip(tr("close image"));
1928       cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
1929       connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
1930               this,SLOT(CloseImage(QTreeWidgetItem*, int)));
1931
1932       QTreePushButton* rButton = new QTreePushButton;
1933       rButton->setItem(item);
1934       rButton->setColumn(COLUMN_RELOAD_IMAGE);
1935       rButton->setToolTip(tr("reload image"));
1936       rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
1937       connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
1938               this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
1939
1940       DataTree->topLevelItem(index)->setExpanded(1);
1941       DataTree->topLevelItem(index)->addChild(item);
1942       DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
1943       DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
1944
1945       //set the id of the image
1946       QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString();
1947       item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
1948       UpdateTree();
1949       qApp->processEvents();
1950       ImageInfoChanged();
1951       QApplication::restoreOverrideCursor();
1952     } else {
1953       QApplication::restoreOverrideCursor();
1954       QString error = "Cannot import the new image.\n";
1955       error += mSlicerManagers[index]->GetLastError().c_str();
1956       QMessageBox::information(this,tr("Problem reading image !"),error);
1957     }
1958   } else {
1959     QString error = "Cannot import the new image.\n";
1960     QMessageBox::information(this,tr("Problem reading image !"),error);
1961   }
1962 }
1963 //------------------------------------------------------------------------------
1964
1965
1966 //------------------------------------------------------------------------------
1967 void vvMainWindow::OpenField()
1968 {
1969   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1970   //check if a vector field has already been added
1971   for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++)
1972     if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "vector") {
1973       QString error = "Cannot add more than one vector field\n";
1974       error += "Please remove first ";
1975       error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1976       QMessageBox::information(this,tr("Problem adding vector field!"),error);
1977       return;
1978     }
1979
1980   QString Extensions = "Images ( *.mhd)";
1981   Extensions += ";;Images ( *.vf)";
1982   QString file = QFileDialog::getOpenFileName(this,tr("Load deformation field"),mInputPathName,Extensions);
1983   if (!file.isEmpty())
1984     AddField(file,index);
1985 }
1986 //------------------------------------------------------------------------------
1987
1988
1989 //------------------------------------------------------------------------------
1990 void vvMainWindow::AddFieldEntry(QString filename,int index,bool from_disk)
1991 {
1992   //create an item in the tree with good settings
1993   QTreeWidgetItem *item = new QTreeWidgetItem();
1994   item->setData(0,Qt::UserRole,filename.toStdString().c_str());
1995   item->setData(1,Qt::UserRole,tr("vector"));
1996   QFileInfo fileinfo(filename); //Do not show the path
1997   item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,fileinfo.fileName());
1998   item->setToolTip(COLUMN_IMAGE_NAME,fileinfo.absoluteFilePath());
1999   qApp->processEvents();
2000
2001   for (int j = 1; j <= 4; j++) {
2002     item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole));
2003     mSlicerManagers[index]->GetSlicer(j-1)->SetActorVisibility("vector",0,
2004         DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole).toInt());
2005   }
2006
2007   //Create the buttons for reload and close
2008   qApp->processEvents();
2009   QTreePushButton* cButton = new QTreePushButton;
2010   cButton->setItem(item);
2011   cButton->setColumn(COLUMN_CLOSE_IMAGE);
2012   cButton->setToolTip(tr("close vector field"));
2013   cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
2014   connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2015           this,SLOT(CloseImage(QTreeWidgetItem*, int)));
2016
2017   QTreePushButton* rButton = new QTreePushButton;
2018   rButton->setItem(item);
2019   rButton->setColumn(COLUMN_RELOAD_IMAGE);
2020   rButton->setToolTip(tr("reload vector field"));
2021   rButton->setEnabled(from_disk);
2022   rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
2023   connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2024           this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
2025
2026   DataTree->topLevelItem(index)->setExpanded(1);
2027   DataTree->topLevelItem(index)->addChild(item);
2028   DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
2029   DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
2030
2031   //set the id of the image
2032   QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString();
2033   item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
2034   UpdateTree();
2035   qApp->processEvents();
2036   ImageInfoChanged();
2037   QApplication::restoreOverrideCursor();
2038 }
2039 //------------------------------------------------------------------------------
2040
2041
2042 //------------------------------------------------------------------------------
2043 void vvMainWindow::AddField(vvImage::Pointer vf,QString file,int index)
2044 {
2045   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
2046   vvSlicerManager* imageManager = mSlicerManagers[index];
2047   if (imageManager->SetVF(vf,file.toStdString())) {
2048     AddFieldEntry(file,index,false);
2049   } else {
2050     QString error = "Cannot import the vector field for this image.\n";
2051     error += imageManager->GetLastError().c_str();
2052     QMessageBox::information(this,tr("Problem reading VF !"),error);
2053   }
2054   QApplication::restoreOverrideCursor();
2055 }
2056 //------------------------------------------------------------------------------
2057
2058
2059 //------------------------------------------------------------------------------
2060 void vvMainWindow::AddField(QString file,int index)
2061 {
2062   if (QFile::exists(file)) {
2063     mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str();
2064
2065     //init the progress events
2066     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
2067     vvProgressDialog progress("Opening " + file.toStdString());
2068     qApp->processEvents();
2069
2070     //read the vector and put it in the current mSlicerManager
2071     vvSlicerManager* imageManager = mSlicerManagers[index];
2072     qApp->processEvents();
2073
2074     std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str();
2075     if (imageManager->SetVF(file.toStdString())) {
2076       imageManager->Render();
2077       AddFieldEntry(file,index,true);
2078     } else {
2079       QApplication::restoreOverrideCursor();
2080       QString error = "Cannot import the vector field for this image.\n";
2081       error += imageManager->GetLastError().c_str();
2082       QMessageBox::information(this,tr("Problem reading VF !"),error);
2083     }
2084   } else
2085     QMessageBox::information(this,tr("Problem reading VF !"),"File doesn't exist!");
2086
2087 }
2088 //------------------------------------------------------------------------------
2089
2090
2091 //------------------------------------------------------------------------------
2092 void vvMainWindow::SetVFProperty(int subsampling, int scale, int log, int width, double r, double g, double b)
2093 {
2094   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2095   if (mSlicerManagers[index]->GetSlicer(0)->GetVF()) {
2096     for (int i = 0; i < 4; i++) {
2097       mSlicerManagers[index]->GetSlicer(i)->SetVFSubSampling(subsampling);
2098       mSlicerManagers[index]->GetSlicer(i)->SetVFScale(scale);
2099       mSlicerManagers[index]->GetSlicer(i)->SetVFWidth(width);
2100       mSlicerManagers[index]->GetSlicer(i)->SetVFColor(r,g,b);
2101       if (log > 0)
2102         mSlicerManagers[index]->GetSlicer(i)->SetVFLog(1);
2103       else
2104         mSlicerManagers[index]->GetSlicer(i)->SetVFLog(0);
2105     }
2106   }
2107 }
2108 //------------------------------------------------------------------------------
2109
2110
2111 //------------------------------------------------------------------------------
2112 void vvMainWindow::SetOverlayProperty(int color)
2113 {
2114   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2115   if (mSlicerManagers[index]->GetSlicer(0)->GetOverlay()) {
2116     mSlicerManagers[index]->SetOverlayColor(color);
2117     mSlicerManagers[index]->SetColorMap(0);
2118     mSlicerManagers[index]->Render();
2119   }
2120 }
2121 //------------------------------------------------------------------------------
2122
2123 //------------------------------------------------------------------------------
2124 void vvMainWindow::SetFusionProperty(int opacity, int colormap,double window, double level)
2125 {
2126   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2127   if (mSlicerManagers[index]->GetSlicer(0)->GetFusion()) {
2128     mSlicerManagers[index]->SetFusionOpacity(opacity);
2129     mSlicerManagers[index]->SetFusionColorMap(colormap);
2130     mSlicerManagers[index]->SetFusionWindow(window);
2131     mSlicerManagers[index]->SetFusionLevel(level);
2132     mSlicerManagers[index]->SetColorMap(0);
2133     mSlicerManagers[index]->Render();
2134   }
2135 }
2136 //------------------------------------------------------------------------------
2137
2138 //------------------------------------------------------------------------------
2139 void vvMainWindow::SaveAs()
2140 {
2141   if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "vector") {
2142     QMessageBox::warning(this,tr("Unsupported type"),tr("Sorry, saving a vector field is unsupported for the moment"));
2143     return;
2144   }
2145
2146   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2147   int dimension = mSlicerManagers[index]->GetDimension();
2148   QStringList OutputListeFormat;
2149   OutputListeFormat.clear();
2150   if (dimension == 1) {
2151     OutputListeFormat.push_back(".mhd");
2152   }
2153   if (dimension == 2) {
2154     OutputListeFormat.push_back(".bmp");
2155     OutputListeFormat.push_back(".png");
2156     OutputListeFormat.push_back(".jpeg");
2157     OutputListeFormat.push_back(".tif");
2158     OutputListeFormat.push_back(".mhd");
2159     OutputListeFormat.push_back(".hdr");
2160     OutputListeFormat.push_back(".vox");
2161   } else if (dimension == 3) {
2162     OutputListeFormat.push_back(".mhd");
2163     OutputListeFormat.push_back(".hdr");
2164     OutputListeFormat.push_back(".vox");
2165   } else if (dimension == 4) {
2166     OutputListeFormat.push_back(".mhd");
2167   }
2168   QString Extensions = "AllFiles(*.*)";
2169   for (int i = 0; i < OutputListeFormat.count(); i++) {
2170     Extensions += ";;Images ( *";
2171     Extensions += OutputListeFormat[i];
2172     Extensions += ")";
2173   }
2174   QString fileName = QFileDialog::getSaveFileName(this,
2175                      tr("Save As"),
2176                      mSlicerManagers[index]->GetFileName().c_str(),
2177                      Extensions);
2178   if (!fileName.isEmpty()) {
2179     std::string fileformat = itksys::SystemTools::GetFilenameLastExtension(fileName.toStdString());
2180     if (OutputListeFormat.contains(
2181           fileformat.c_str())) {
2182       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
2183       std::string action = "Saving";
2184       vvProgressDialog progress("Saving "+fileName.toStdString());
2185       qApp->processEvents();
2186       vvImageWriter *writer = new vvImageWriter;
2187       writer->SetOutputFileName(fileName.toStdString());
2188       writer->SetInput(mSlicerManagers[index]->GetImage());
2189       writer->Update();
2190       QApplication::restoreOverrideCursor();
2191       if (writer->GetLastError().size()) {
2192         QString error = "Saving did not succeed\n";
2193         error += writer->GetLastError().c_str();
2194         QMessageBox::information(this,tr("Saving Problem"),error);
2195         SaveAs();
2196       }
2197     } else {
2198       QString error = fileformat.c_str();
2199       if (error.isEmpty())
2200         error += "no file format specified !";
2201       else
2202         error += " format unknown !!!\n";
2203       QMessageBox::information(this,tr("Saving Problem"),error);
2204       SaveAs();
2205     }
2206   }
2207 }
2208 //------------------------------------------------------------------------------
2209
2210
2211 //------------------------------------------------------------------------------
2212 void vvMainWindow::AddLink(QString image1,QString image2)
2213 {
2214   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2215     if (image1.toStdString() == mSlicerManagers[i]->GetId()) {
2216       mSlicerManagers[i]->AddLink(image2.toStdString());
2217     }
2218     if (image2.toStdString() == mSlicerManagers[i]->GetId()) {
2219       mSlicerManagers[i]->AddLink(image1.toStdString());
2220     }
2221   }
2222 }
2223 //------------------------------------------------------------------------------
2224
2225
2226 //------------------------------------------------------------------------------
2227 void vvMainWindow::RemoveLink(QString image1,QString image2)
2228 {
2229   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2230     if (image1.toStdString() == mSlicerManagers[i]->GetId()) {
2231       mSlicerManagers[i]->RemoveLink(image2.toStdString());
2232     }
2233     if (image2.toStdString() == mSlicerManagers[i]->GetId()) {
2234       mSlicerManagers[i]->RemoveLink(image1.toStdString());
2235     }
2236   }
2237 }
2238 //------------------------------------------------------------------------------
2239
2240 //------------------------------------------------------------------------------
2241 void vvMainWindow::ChangeImageWithIndexOffset(vvSlicerManager *sm, int slicer, int offset)
2242 {
2243   int index = 0;
2244   while(sm != mSlicerManagers[index])
2245     index++;
2246   index = (index+offset) % mSlicerManagers.size();
2247
2248   QTreeWidgetItem* item = GetItemFromSlicerManager(mSlicerManagers[index]);
2249   //CurrentImageChanged(mSlicerManagers[index]->GetId()); //select new image
2250   item->setData(slicer+1,Qt::CheckStateRole,2);         //change checkbox
2251   DisplayChanged(item,slicer+1);
2252 }
2253 //------------------------------------------------------------------------------
2254
2255 void vvMainWindow::HorizontalSliderMoved(int value,int column, int slicer_index)
2256 {
2257   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2258     if (DataTree->topLevelItem(i)->data(column,Qt::CheckStateRole).toInt() > 1) {
2259       for (int j = 0; j < 4; j++) {
2260         mSlicerManagers[i]->SetTSliceInSlicer(value,j);
2261         //if (mSlicerManagers[i]->GetSlicer(j)->GetImageActor()->GetVisibility())
2262         //UpdateTSlice(j,value);
2263       }
2264       mSlicerManagers[i]->GetSlicer(slicer_index)->Render();
2265       break;
2266     }
2267   }
2268 }
2269 //------------------------------------------------------------------------------
2270
2271
2272 //------------------------------------------------------------------------------
2273 void vvMainWindow::NOHorizontalSliderMoved()
2274 {
2275   // if (mCurrentTime == NOHorizontalSlider->value()) return;
2276   HorizontalSliderMoved(NOHorizontalSlider->value(),COLUMN_UL_VIEW,0);
2277 //  mCurrentTime = NOHorizontalSlider->value();
2278 }
2279 //------------------------------------------------------------------------------
2280
2281
2282 //------------------------------------------------------------------------------
2283 void vvMainWindow::NEHorizontalSliderMoved()
2284 {
2285   // if (mCurrentTime == NEHorizontalSlider->value()) return;
2286   HorizontalSliderMoved(NEHorizontalSlider->value(),COLUMN_UR_VIEW,1);
2287 //  mCurrentTime = NEHorizontalSlider->value();
2288 }
2289 //------------------------------------------------------------------------------
2290
2291
2292 //------------------------------------------------------------------------------
2293 void vvMainWindow::SOHorizontalSliderMoved()
2294 {
2295   // if (mCurrentTime == SOHorizontalSlider->value()) return;
2296   HorizontalSliderMoved(SOHorizontalSlider->value(),COLUMN_DL_VIEW,2);
2297   // mCurrentTime = SOHorizontalSlider->value();
2298 }
2299 //------------------------------------------------------------------------------
2300
2301
2302 //------------------------------------------------------------------------------
2303 void vvMainWindow::SEHorizontalSliderMoved()
2304 {
2305   // if (mCurrentTime == SEHorizontalSlider->value()) return;
2306   HorizontalSliderMoved(SEHorizontalSlider->value(),COLUMN_DR_VIEW,3);
2307   // mCurrentTime = SEHorizontalSlider->value();
2308 }
2309 //------------------------------------------------------------------------------
2310
2311 //------------------------------------------------------------------------------
2312 void vvMainWindow::NOVerticalSliderChanged()
2313 {
2314   static int value=-1;
2315   if (value == NOVerticalSlider->value()) return;
2316   else value = NOVerticalSlider->value();
2317   //  int value = NOVerticalSlider->value();
2318   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2319     if (DataTree->topLevelItem(i)->data(COLUMN_UL_VIEW,Qt::CheckStateRole).toInt() > 1) {
2320       if (mSlicerManagers[i]->GetSlicer(0)->GetSlice() != value) {
2321         mSlicerManagers[i]->GetSlicer(0)->SetSlice(value);
2322         mSlicerManagers[i]->VerticalSliderHasChanged(0, value);
2323
2324         // If nor Update/Render -> slider not work
2325         // only render = ok navigation, but for contour Update needed but slower ?
2326
2327         mSlicerManagers[i]->UpdateSlice(0);  // <-- DS add this. Not too much update ? YES. but needed for ImageContour ...
2328         //mSlicerManagers[i]->GetSlicer(0)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2329       }
2330       break;
2331     }
2332   }
2333 }
2334 //------------------------------------------------------------------------------
2335
2336
2337 //------------------------------------------------------------------------------
2338 void vvMainWindow::NEVerticalSliderChanged()
2339 {
2340   static int value=-1;
2341   if (value == NEVerticalSlider->value()) return;
2342   else value = NEVerticalSlider->value();
2343   //  int value = NEVerticalSlider->value();
2344   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2345     if (DataTree->topLevelItem(i)->data(COLUMN_UR_VIEW,Qt::CheckStateRole).toInt() > 1) {
2346       if (mSlicerManagers[i]->GetSlicer(1)->GetSlice() != value) {
2347         mSlicerManagers[i]->GetSlicer(1)->SetSlice(value);
2348         mSlicerManagers[i]->VerticalSliderHasChanged(1, value);
2349         mSlicerManagers[i]->UpdateSlice(1);
2350         //mSlicerManagers[i]->GetSlicer(1)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2351       }
2352       break;
2353     }
2354   }
2355 }
2356 //------------------------------------------------------------------------------
2357
2358
2359 //------------------------------------------------------------------------------
2360 void vvMainWindow::SOVerticalSliderChanged()
2361 {
2362   static int value=-1;
2363   if (value == SOVerticalSlider->value()) return;
2364   else value = SOVerticalSlider->value();
2365   //int value = SOVerticalSlider->value();
2366   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2367     if (DataTree->topLevelItem(i)->data(COLUMN_DL_VIEW,Qt::CheckStateRole).toInt() > 1) {
2368       if (mSlicerManagers[i]->GetSlicer(2)->GetSlice() != value) {
2369         mSlicerManagers[i]->GetSlicer(2)->SetSlice(value);
2370         mSlicerManagers[i]->VerticalSliderHasChanged(2, value);
2371         mSlicerManagers[i]->UpdateSlice(2);
2372         //mSlicerManagers[i]->GetSlicer(2)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2373       }
2374       // else { DD("avoid SOVerticalSlider slicer update"); }
2375       break;
2376     }
2377   }
2378 }
2379 //------------------------------------------------------------------------------
2380
2381
2382 //------------------------------------------------------------------------------
2383 void vvMainWindow::SEVerticalSliderChanged()
2384 {
2385   static int value=-1;
2386   if (value == SEVerticalSlider->value()) return;
2387   else value = SEVerticalSlider->value();
2388   // int value = SEVerticalSlider->value();
2389   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2390     if (DataTree->topLevelItem(i)->data(COLUMN_DR_VIEW,Qt::CheckStateRole).toInt() > 1) {
2391       if (mSlicerManagers[i]->GetSlicer(3)->GetSlice() != value) {
2392         mSlicerManagers[i]->GetSlicer(3)->SetSlice(value);
2393         mSlicerManagers[i]->VerticalSliderHasChanged(3, value);
2394         mSlicerManagers[i]->UpdateSlice(3);
2395         //mSlicerManagers[i]->GetSlicer(3)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2396       }
2397       break;
2398     }
2399   }
2400 }
2401 //------------------------------------------------------------------------------
2402
2403
2404 //------------------------------------------------------------------------------
2405 void vvMainWindow::UpdateSlice(int slicer, int slice)
2406 {
2407   // DD("vvMainWindow::UpdateSlice");
2408 //   DD(slicer);
2409 //   DD(slice);
2410   if (slicer == 0) {
2411     //    if (slice != NOVerticalSlider->value())
2412     NOVerticalSlider->setValue(slice);
2413   } else {
2414     if (slicer == 1)
2415       NEVerticalSlider->setValue(slice);
2416     else {
2417       if (slicer == 2)
2418         SOVerticalSlider->setValue(slice);
2419       else {
2420         if (slicer == 3)
2421           SEVerticalSlider->setValue(slice);
2422       }
2423     }
2424   }
2425   // DD("vvMainWindow:UpdateSlice END");
2426 }
2427 //------------------------------------------------------------------------------
2428
2429
2430 //------------------------------------------------------------------------------
2431 void vvMainWindow::UpdateTSlice(int slicer, int slice)
2432 {
2433   switch (slicer) {
2434   case 0:
2435     NOHorizontalSlider->setValue(slice);
2436     break;
2437   case 1:
2438     NEHorizontalSlider->setValue(slice);
2439     break;
2440   case 2:
2441     SOHorizontalSlider->setValue(slice);
2442     break;
2443   case 3:
2444     SEHorizontalSlider->setValue(slice);
2445     break;
2446   }
2447 }
2448 //------------------------------------------------------------------------------
2449
2450
2451 //------------------------------------------------------------------------------
2452 void vvMainWindow::UpdateSliceRange(int slicer, int min, int max, int tmin, int tmax)
2453 {
2454   int position = int((min+max)/2);
2455   int tPosition = int((tmin+tmax)/2);
2456   if (slicer == 0) {
2457     NOVerticalSlider->setValue(position);
2458     NOVerticalSlider->setRange(min,max);
2459     NOHorizontalSlider->setRange(tmin,tmax);
2460     NOHorizontalSlider->setValue(tPosition);
2461   } else if (slicer == 1) {
2462     NEVerticalSlider->setValue(position);
2463     NEVerticalSlider->setRange(min,max);
2464     NEHorizontalSlider->setRange(tmin,tmax);
2465     NEHorizontalSlider->setValue(tPosition);
2466   } else if (slicer == 2) {
2467     SOVerticalSlider->setValue(position);
2468     SOVerticalSlider->setRange(min,max);
2469     SOHorizontalSlider->setRange(tmin,tmax);
2470     SOHorizontalSlider->setValue(tPosition);
2471   } else if (slicer == 3) {
2472     SEVerticalSlider->setValue(position);
2473     SEVerticalSlider->setRange(min,max);
2474     SEHorizontalSlider->setRange(tmin,tmax);
2475     SEHorizontalSlider->setValue(tPosition);
2476   }
2477 }
2478 //------------------------------------------------------------------------------
2479
2480
2481 //------------------------------------------------------------------------------
2482 void vvMainWindow::SaveNOScreenshot()
2483 {
2484   vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New();
2485   w2i->SetInput(NOViewWidget->GetRenderWindow());
2486   w2i->Update();
2487   SaveScreenshot(w2i->GetOutput());
2488   w2i->Delete();
2489 }
2490 //------------------------------------------------------------------------------
2491
2492
2493 //------------------------------------------------------------------------------
2494 void vvMainWindow::SaveNEScreenshot()
2495 {
2496   vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New();
2497   w2i->SetInput(NEViewWidget->GetRenderWindow());
2498   w2i->Update();
2499   SaveScreenshot(w2i->GetOutput());
2500   w2i->Delete();
2501 }
2502 //------------------------------------------------------------------------------
2503
2504
2505 //------------------------------------------------------------------------------
2506 void vvMainWindow::SaveSOScreenshot()
2507 {
2508   vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New();
2509   w2i->SetInput(SOViewWidget->GetRenderWindow());
2510   w2i->Update();
2511   SaveScreenshot(w2i->GetOutput());
2512   w2i->Delete();
2513 }
2514 //------------------------------------------------------------------------------
2515
2516
2517 //------------------------------------------------------------------------------
2518 void vvMainWindow::SaveSEScreenshot()
2519 {
2520   vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New();
2521   w2i->SetInput(SEViewWidget->GetRenderWindow());
2522   w2i->Update();
2523   SaveScreenshot(w2i->GetOutput());
2524   w2i->Delete();
2525 }
2526 //------------------------------------------------------------------------------
2527
2528
2529 //------------------------------------------------------------------------------
2530 void vvMainWindow::SaveScreenshot(vtkImageData* image)
2531 {
2532   QString Extensions = "Images( *.png);;";
2533   Extensions += "Images( *.jpg);;";
2534   Extensions += "Images( *.bmp);;";
2535   Extensions += "Images( *.tif);;";
2536   Extensions += "Images( *.ppm)";
2537   QString fileName = QFileDialog::getSaveFileName(this,
2538                      tr("Save As"),
2539                      itksys::SystemTools::GetFilenamePath(
2540                        mSlicerManagers[0]->GetFileName()).c_str(),
2541                      Extensions);
2542   if (!fileName.isEmpty()) {
2543     const char *ext = fileName.toStdString().c_str() + strlen(fileName.toStdString().c_str()) - 4;
2544     if (!strcmp(ext, ".bmp")) {
2545       vtkBMPWriter *bmp = vtkBMPWriter::New();
2546       bmp->SetInput(image);
2547       bmp->SetFileName(fileName.toStdString().c_str());
2548       bmp->Write();
2549       bmp->Delete();
2550     } else if (!strcmp(ext, ".tif")) {
2551       vtkTIFFWriter *tif = vtkTIFFWriter::New();
2552       tif->SetInput(image);
2553       tif->SetFileName(fileName.toStdString().c_str());
2554       tif->Write();
2555       tif->Delete();
2556     } else if (!strcmp(ext, ".ppm")) {
2557       vtkPNMWriter *pnm = vtkPNMWriter::New();
2558       pnm->SetInput(image);
2559       pnm->SetFileName(fileName.toStdString().c_str());
2560       pnm->Write();
2561       pnm->Delete();
2562     } else if (!strcmp(ext, ".png")) {
2563       vtkPNGWriter *png = vtkPNGWriter::New();
2564       png->SetInput(image);
2565       png->SetFileName(fileName.toStdString().c_str());
2566       png->Write();
2567       png->Delete();
2568     } else if (!strcmp(ext, ".jpg")) {
2569       vtkJPEGWriter *jpg = vtkJPEGWriter::New();
2570       jpg->SetInput(image);
2571       jpg->SetFileName(fileName.toStdString().c_str());
2572       jpg->Write();
2573       jpg->Delete();
2574     } else {
2575       QMessageBox::information(this,tr("Problem saving screenshot !"),tr("Cannot save image.\nPlease set a file extension !!!"));
2576     }
2577   }
2578
2579 }
2580 //------------------------------------------------------------------------------
2581
2582
2583 //------------------------------------------------------------------------------
2584 void vvMainWindow::GoToCursor()
2585 {
2586   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2587   for (int column = 1; column < 5; column++) {
2588     if (DataTree->selectedItems()[0]->data(column,Qt::CheckStateRole).toInt() > 1) {
2589       double* cursorPos = mSlicerManagers[index]->GetSlicer(column-1)->GetCursorPosition();
2590       mSlicerManagers[index]->GetSlicer(column-1)->SetCurrentPosition(
2591         cursorPos[0],cursorPos[1],cursorPos[2],cursorPos[3]);
2592       mSlicerManagers[index]->UpdateViews(1,column-1);
2593       mSlicerManagers[index]->UpdateLinked(column-1);
2594       break;
2595     }
2596   }
2597 }
2598 //------------------------------------------------------------------------------
2599
2600 //------------------------------------------------------------------------------
2601 void vvMainWindow::PlayPause()
2602 {
2603   if (playMode) {
2604     playMode = 0;
2605     playButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/player_play.png")));
2606     ImageInfoChanged();
2607     return;
2608   } else {
2609     int image_number=DataTree->topLevelItemCount();
2610     bool has_temporal;
2611     for (int i=0; i<image_number; i++)
2612       if (mSlicerManagers[i]->GetImage()->GetVTKImages().size() > 1) {
2613         has_temporal=true;
2614         break;
2615       }
2616     if (has_temporal) {
2617       playMode = 1;
2618       playButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/player_pause.png")));
2619       QTimer::singleShot(1000/mFrameRate, this, SLOT(PlayNext()));
2620     }
2621   }
2622 }
2623 //------------------------------------------------------------------------------
2624
2625 //------------------------------------------------------------------------------
2626 void vvMainWindow::PlayNext()
2627 {
2628   if (playMode && !this->isHidden()) {
2629     int image_number=DataTree->topLevelItemCount();
2630     ///Only play one slicer per SM, and only if the SM is being displayed
2631     for (int i=0; i<image_number; i++)
2632       for (int j=0; j<4; j++)
2633         if (mSlicerManagers[i]->GetImage()->GetVTKImages().size() > 1 &&
2634             DataTree->topLevelItem(i)->data(j+1,Qt::CheckStateRole).toInt() > 0) {
2635           mSlicerManagers[i]->SetNextTSlice(j);
2636           break;
2637         }
2638     QTimer::singleShot(1000/mFrameRate, this, SLOT(PlayNext()));
2639   }
2640 }
2641 //------------------------------------------------------------------------------
2642
2643 void vvMainWindow::ShowLastImage()
2644 {
2645   if (mSlicerManagers.size() > 1) {
2646     QTreeWidgetItem * item=DataTree->topLevelItem(DataTree->topLevelItemCount()-1);
2647     CurrentImageChanged(mSlicerManagers.back()->GetId()); //select new image
2648     item->setData(1,Qt::CheckStateRole,2); //show the new image in the first panel
2649     DisplayChanged(item,1);
2650   }
2651 }
2652
2653 //------------------------------------------------------------------------------
2654 void vvMainWindow::UpdateRenderWindows()
2655 {
2656   if (NOViewWidget->GetRenderWindow()) NOViewWidget->GetRenderWindow()->Render();
2657   if (NEViewWidget->GetRenderWindow()) NEViewWidget->GetRenderWindow()->Render();
2658   if (SOViewWidget->GetRenderWindow()) SOViewWidget->GetRenderWindow()->Render();
2659   if (SEViewWidget->GetRenderWindow()) SEViewWidget->GetRenderWindow()->Render();
2660 }
2661 //------------------------------------------------------------------------------
2662
2663 //------------------------------------------------------------------------------
2664 void vvMainWindow::SegmentationOnCurrentImage()
2665 {
2666   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2667
2668   vvSegmentationDialog segmentation;
2669   segmentation.SetImage(mSlicerManagers[index]->GetSlicer(0)->GetImage());
2670   segmentation.exec();
2671 }
2672 //------------------------------------------------------------------------------
2673
2674 void vvMainWindow::SurfaceViewerLaunch()
2675 {
2676   vvSurfaceViewerDialog surfaceViewer;
2677   surfaceViewer.exec();
2678 }
2679 //------------------------------------------------------------------------------
2680
2681
2682 //------------------------------------------------------------------------------
2683 int vvMainWindow::GetImageDuplicateFilenameNumber(std::string filename)
2684 {
2685   int number=0;
2686   for(unsigned int l=0; l<mSlicerManagers.size(); l++) {
2687     vvSlicerManager * v = mSlicerManagers[l];
2688     if (v->GetBaseFileName() ==
2689         vtksys::SystemTools::GetFilenameName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename))) {
2690       number = std::max(number, v->GetBaseFileNameNumber()+1);
2691     }
2692   }
2693   return number;
2694 }
2695 //------------------------------------------------------------------------------
2696
2697
2698 //------------------------------------------------------------------------------
2699 vvSlicerManager* vvMainWindow::AddImage(vvImage::Pointer image,std::string filename)
2700 {
2701   // Change filename if another image exist with the same name
2702   int number = GetImageDuplicateFilenameNumber(filename);
2703
2704   // Create new SliceManager
2705   vvSlicerManager* slicer_manager = new vvSlicerManager(4);
2706   slicer_manager->SetImage(image);//, IMAGE, number);
2707   //  filename = filename+"_"+clitk::toString(number);
2708   slicer_manager->SetFilename(filename, number);
2709   mSlicerManagers.push_back(slicer_manager);
2710
2711   //create an item in the tree with good settings
2712   QTreeWidgetItem *item = new QTreeWidgetItem();
2713   item->setData(0,Qt::UserRole,slicer_manager->GetFileName().c_str());//files[i].c_str());
2714   item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,filename.c_str());
2715   qApp->processEvents();
2716
2717   for (int j = 1; j <= 4; j++) item->setData(j,Qt::CheckStateRole,1);
2718
2719   //Create the buttons for reload and close
2720   qApp->processEvents();
2721   QTreePushButton* cButton = new QTreePushButton;
2722   cButton->setItem(item);
2723   cButton->setColumn(COLUMN_CLOSE_IMAGE);
2724   cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
2725   connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2726           this,SLOT(CloseImage(QTreeWidgetItem*, int)));
2727
2728   QTreePushButton* rButton = new QTreePushButton;
2729   rButton->setItem(item);
2730   rButton->setColumn(COLUMN_RELOAD_IMAGE);
2731   rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
2732   rButton->setEnabled(0);
2733   connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2734           this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
2735
2736   DataTree->addTopLevelItem(item);
2737   DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
2738   DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
2739
2740   //set the id of the image
2741   QString id = slicer_manager->GetFileName().c_str() + QString::number(mSlicerManagers.size()-1);
2742   item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
2743   mSlicerManagers.back()->SetId(id.toStdString());
2744
2745   linkPanel->addImage(filename, id.toStdString());
2746
2747   connect(mSlicerManagers.back(), SIGNAL(currentImageChanged(std::string)),
2748           this, SLOT(CurrentImageChanged(std::string)));
2749   connect(mSlicerManagers.back(), SIGNAL(UpdatePosition(int, double, double, double, double, double, double, double)),
2750           this, SLOT(MousePositionChanged(int,double, double, double, double, double, double, double)));
2751   connect(mSlicerManagers.back(), SIGNAL(UpdateVector(int, double, double, double, double)),
2752           this, SLOT(VectorChanged(int,double,double,double, double)));
2753   connect(mSlicerManagers.back(), SIGNAL(UpdateOverlay(int, double, double)),
2754           this, SLOT(OverlayChanged(int,double,double)));
2755   connect(mSlicerManagers.back(), SIGNAL(UpdateFusion(int, double)),
2756           this, SLOT(FusionChanged(int,double)));
2757   connect(mSlicerManagers.back(), SIGNAL(UpdateWindows(int, int, int)),
2758           this,SLOT(WindowsChanged(int, int, int)));
2759   connect(mSlicerManagers.back(), SIGNAL(WindowLevelChanged(double, double,int, int)),
2760           this,SLOT(WindowLevelChanged(double, double, int, int)));
2761   connect(mSlicerManagers.back(), SIGNAL(UpdateSlice(int,int)),
2762           this,SLOT(UpdateSlice(int,int)));
2763   connect(mSlicerManagers.back(), SIGNAL(UpdateTSlice(int, int)),
2764           this,SLOT(UpdateTSlice(int, int)));
2765   connect(mSlicerManagers.back(), SIGNAL(UpdateSliceRange(int,int,int,int,int)),
2766           this,SLOT(UpdateSliceRange(int,int,int,int,int)));
2767   connect(mSlicerManagers.back(), SIGNAL(UpdateLinkManager(std::string,int,double,double,double,int)),
2768           this,SLOT(UpdateLinkManager(std::string,int,double,double,double,int)));
2769   connect(mSlicerManagers.back(), SIGNAL(UpdateLinkedNavigation(std::string,vvSlicerManager*)),
2770           this,SLOT(UpdateLinkedNavigation(std::string,vvSlicerManager*)));
2771   connect(mSlicerManagers.back(), SIGNAL(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)),
2772           this,SLOT(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)));
2773   connect(mSlicerManagers.back(), SIGNAL(LandmarkAdded()),landmarksPanel,SLOT(AddPoint()));
2774   UpdateTree();
2775   qApp->processEvents();
2776   InitSlicers();
2777   ShowLastImage();
2778   InitDisplay();
2779   qApp->processEvents();
2780
2781   // End
2782   ImageInfoChanged();
2783   return slicer_manager;
2784 }
2785 //------------------------------------------------------------------------------
2786
2787
2788 //------------------------------------------------------------------------------
2789 void vvMainWindow::UpdateCurrentSlicer()
2790 {
2791   int index = -1;
2792   if (DataTree->selectedItems().size() > 0) {
2793     index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2794   }
2795   mSlicerManagerCurrentIndex = index;
2796 }
2797 //------------------------------------------------------------------------------
2798