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