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