]> Creatis software - clitk.git/blob - vv/vvMainWindow.cxx
Merge branch 'master' of git://git.creatis.insa-lyon.fr/clitk
[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(inverseButton,SIGNAL(clicked()),this,SLOT(SwitchWindowLevel()));
313   connect(applyWindowLevelToAllButton,SIGNAL(clicked()),this,SLOT(ApplyWindowLevelToAllImages()));
314
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(UpdateSliceRange(int,int,int,int,int)),
956                 this,SLOT(UpdateSliceRange(int,int,int,int,int)));
957         connect(mSlicerManagers.back(), SIGNAL(UpdateLinkManager(std::string,int,double,double,double,int)),
958                 this,SLOT(UpdateLinkManager(std::string,int,double,double,double,int)));
959         connect(mSlicerManagers.back(), SIGNAL(UpdateLinkedNavigation(std::string,vvSlicerManager*,vvSlicer*)),
960                 this,SLOT(UpdateLinkedNavigation(std::string,vvSlicerManager*,vvSlicer*)));
961         connect(mSlicerManagers.back(), SIGNAL(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)),
962                 this,SLOT(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)));
963         connect(mSlicerManagers.back(),SIGNAL(LandmarkAdded()),landmarksPanel,SLOT(AddPoint()));
964         InitSlicers();
965         numberofsuccesulreads++;
966       }
967     }
968   }
969   if (numberofsuccesulreads) {
970     NOViewWidget->show();
971     NEViewWidget->show();
972     SOViewWidget->show();
973     SEViewWidget->show();
974     UpdateTree();
975     InitDisplay();
976     ShowLastImage();
977
978     // Try to guess default WindowLevel
979     double range[2];
980     mSlicerManagers.back()->GetImage()->GetFirstVTKImageData()->GetScalarRange(range);
981     if ((range[0] == 0) && (range[1] == 1)) {
982       presetComboBox->setCurrentIndex(5);// binary
983     } else {
984       // TODO
985     }
986   }
987   QApplication::restoreOverrideCursor();
988 }
989 //------------------------------------------------------------------------------
990
991 //------------------------------------------------------------------------------
992 void vvMainWindow::UpdateTree()
993 {
994   DataTree->resizeColumnToContents(COLUMN_TREE);
995   DataTree->resizeColumnToContents(COLUMN_UL_VIEW);
996   DataTree->resizeColumnToContents(COLUMN_UR_VIEW);
997   DataTree->resizeColumnToContents(COLUMN_DL_VIEW);
998   DataTree->resizeColumnToContents(COLUMN_DR_VIEW);
999   DataTree->resizeColumnToContents(COLUMN_IMAGE_NAME);
1000   DataTree->resizeColumnToContents(COLUMN_CLOSE_IMAGE);
1001   DataTree->resizeColumnToContents(COLUMN_RELOAD_IMAGE);
1002 }
1003 //------------------------------------------------------------------------------
1004
1005 //------------------------------------------------------------------------------
1006 void vvMainWindow::CurrentImageChanged(std::string id)
1007 {
1008   if (id == mCurrentSelectedImageId) return; // Do nothing
1009   int selected = 0;
1010   for (int i = 0; i < DataTree->topLevelItemCount(); i++) {
1011     if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString().toStdString() == id) {
1012       selected = i;
1013     } else {
1014       DataTree->topLevelItem(i)->setSelected(0);
1015     }
1016     for (int child = 0; child < DataTree->topLevelItem(i)->childCount(); child++)
1017       DataTree->topLevelItem(i)->child(child)->setSelected(0);
1018
1019   }
1020   DataTree->topLevelItem(selected)->setSelected(1);
1021   mCurrentSelectedImageId = id;
1022   emit SelectedImageHasChanged(mSlicerManagers[selected]);
1023 }
1024 //------------------------------------------------------------------------------
1025
1026 //------------------------------------------------------------------------------
1027 void vvMainWindow::CurrentPickedImageChanged(std::string id)
1028 {
1029   if (id == mCurrentPickedImageId) return; // Do nothing
1030   int selected = 0;
1031   for (int i = 0; i < DataTree->topLevelItemCount(); i++) {
1032     if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString().toStdString() == id) {
1033       selected = i;
1034     } else {
1035       DataTree->topLevelItem(i)->setSelected(0);
1036     }
1037     for (int child = 0; child < DataTree->topLevelItem(i)->childCount(); child++)
1038       DataTree->topLevelItem(i)->child(child)->setSelected(0);
1039
1040   }
1041   DataTree->topLevelItem(selected)->setSelected(1);
1042   mCurrentPickedImageId = id;
1043   mCurrentPickedImageIndex = selected;
1044 }
1045 //------------------------------------------------------------------------------
1046
1047 //------------------------------------------------------------------------------
1048 void vvMainWindow::ImageInfoChanged()
1049 {
1050   contextActions[6]->setEnabled(1);
1051   contextActions[5]->setEnabled(1);
1052   actionSave_As->setEnabled(1);
1053   actionAdd_VF_to_current_Image->setEnabled(1);
1054   actionAdd_fusion_image->setEnabled(1);
1055   actionAdd_overlay_image_to_current_image->setEnabled(1);
1056   actionNorth_East_Window->setEnabled(1);
1057   actionNorth_West_Window->setEnabled(1);
1058   actionSouth_East_Window->setEnabled(1);
1059   actionSouth_West_Window->setEnabled(1);
1060   vvToolManager::GetInstance()->EnableToolsInMenu(this, true);
1061   inverseButton->setEnabled(1);
1062
1063   goToCursorPushButton->setEnabled(1);
1064
1065   if (DataTree->selectedItems().size()) {
1066     int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1067
1068     colorMapComboBox->setEnabled(1);
1069     for (int i = 0; i < DataTree->topLevelItem(index)->childCount(); i++) {
1070       if (DataTree->topLevelItem(index)->child(i)->data(1,Qt::UserRole).toString() == "overlay" ||
1071           DataTree->topLevelItem(index)->child(i)->data(1,Qt::UserRole).toString() == "fusion") {
1072         colorMapComboBox->setEnabled(0);
1073         break;
1074       }
1075     }
1076
1077     std::vector<double> origin;
1078     std::vector<double> inputSpacing;
1079     std::vector<int> inputSize;
1080     std::vector<double> sizeMM;
1081     vtkSmartPointer<vtkMatrix4x4> transformation;
1082     int dimension=0;
1083     QString pixelType;
1084     QString inputSizeInBytes;
1085     QString image = DataTree->selectedItems()[0]->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1086
1087     if (mSlicerManagers[index]->GetSlicer(0)->GetImage()->GetVTKImages().size() > 1 || playMode == 1) {
1088       playButton->setEnabled(1);
1089       frameRateLabel->setEnabled(1);
1090       frameRateSpinBox->setEnabled(1);
1091     } else {
1092       playButton->setEnabled(0);
1093       frameRateLabel->setEnabled(0);
1094       frameRateSpinBox->setEnabled(0);
1095     }
1096
1097     //read image header
1098     int NPixel = 1;
1099
1100     vvImage::Pointer imageSelected;
1101     if (DataTree->topLevelItem(index) == DataTree->selectedItems()[0]) {
1102       imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetImage();
1103     } else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "vector") {
1104       imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetVF();
1105     } else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "overlay") {
1106       imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetOverlay();
1107     } else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "fusion") {
1108       imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetFusion();
1109     }
1110     else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "contour") {
1111       imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetImage();
1112     }
1113     else {
1114       imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetImage();
1115     }
1116
1117     dimension = imageSelected->GetNumberOfDimensions();
1118     origin.resize(dimension);
1119     inputSpacing.resize(dimension);
1120     inputSize.resize(dimension);
1121     sizeMM.resize(dimension);
1122     pixelType = mSlicerManagers[index]->GetImage()->GetScalarTypeAsITKString().c_str();
1123     for (int i = 0; i < dimension; i++) {
1124       origin[i] = imageSelected->GetOrigin()[i];
1125       inputSpacing[i] = imageSelected->GetSpacing()[i];
1126       inputSize[i] = imageSelected->GetSize()[i];
1127       sizeMM[i] = inputSize[i]*inputSpacing[i];
1128       NPixel *= inputSize[i];
1129     }
1130     inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000);
1131     
1132     QString dim = QString::number(dimension) + " (";
1133     dim += pixelType + ")";
1134
1135     infoPanel->setFileName(image);
1136     infoPanel->setDimension(dim);
1137     infoPanel->setSizePixel(GetVectorIntAsString(inputSize));
1138     infoPanel->setSizeMM(GetVectorDoubleAsString(sizeMM));
1139     infoPanel->setOrigin(GetVectorDoubleAsString(origin));
1140     infoPanel->setSpacing(GetVectorDoubleAsString(inputSpacing));
1141     infoPanel->setNPixel(QString::number(NPixel)+" ("+inputSizeInBytes+")");
1142     transformation = imageSelected->GetTransform()->GetMatrix();
1143     infoPanel->setTransformation(Get4x4MatrixDoubleAsString(transformation));
1144
1145     landmarksPanel->SetCurrentLandmarks(mSlicerManagers[index]->GetLandmarks(),
1146                                         mSlicerManagers[index]->GetSlicer(0)->GetImage()->GetVTKImages().size());
1147     landmarksPanel->SetCurrentPath(mInputPathName.toStdString());
1148     landmarksPanel->SetCurrentImage(mSlicerManagers[index]->GetFileName().c_str());
1149
1150     overlayPanel->getCurrentImageName(mSlicerManagers[index]->GetFileName().c_str());
1151     for (int i = 0; i < 4; i++) {
1152       if (DataTree->selectedItems()[0]->data(i+1,Qt::CheckStateRole).toInt() > 0 || i == 3) {
1153         mSlicerManagers[index]->UpdateInfoOnCursorPosition(i);
1154         break;
1155       }
1156     }
1157
1158     infoPanel->setFileName(image);
1159     infoPanel->setDimension(dim);
1160     infoPanel->setSizePixel(GetVectorIntAsString(inputSize));
1161     infoPanel->setSizeMM(GetVectorDoubleAsString(sizeMM));
1162     infoPanel->setOrigin(GetVectorDoubleAsString(origin));
1163     infoPanel->setSpacing(GetVectorDoubleAsString(inputSpacing));
1164     infoPanel->setNPixel(QString::number(NPixel)+" ("+inputSizeInBytes+")");
1165
1166     landmarksPanel->SetCurrentLandmarks(mSlicerManagers[index]->GetLandmarks(),
1167                                         mSlicerManagers[index]->GetSlicer(0)->GetImage()->GetVTKImages().size());
1168     landmarksPanel->SetCurrentPath(mInputPathName.toStdString());
1169     landmarksPanel->SetCurrentImage(mSlicerManagers[index]->GetFileName().c_str());
1170
1171     overlayPanel->getCurrentImageName(mSlicerManagers[index]->GetFileName().c_str());
1172     for (int i = 0; i < 4; i++) {
1173       if (DataTree->selectedItems()[0]->data(i+1,Qt::CheckStateRole).toInt() > 0 || i == 3) {
1174         mSlicerManagers[index]->UpdateInfoOnCursorPosition(i);
1175         break;
1176       }
1177     }
1178     WindowLevelChanged();
1179
1180     if (mSlicerManagers[index]->GetSlicer(0)->GetVF()) {
1181       overlayPanel->getVFName(mSlicerManagers[index]->GetVFName().c_str());
1182       overlayPanel->getVFProperty(mSlicerManagers[index]->GetSlicer(0)->GetVFSubSampling(),
1183                                   mSlicerManagers[index]->GetSlicer(0)->GetVFScale(),
1184                                   mSlicerManagers[index]->GetSlicer(0)->GetVFLog());
1185     } else {
1186       overlayPanel->getVFName(mSlicerManagers[index]->GetVFName().c_str());
1187       overlayPanel->getVFProperty(-1,-1,-1);
1188     }
1189     if (mSlicerManagers[index]->GetSlicer(0)->GetOverlay()) {
1190       overlayPanel->getOverlayName(mSlicerManagers[index]->GetOverlayName().c_str());
1191     } else {
1192       overlayPanel->getOverlayName(mSlicerManagers[index]->GetOverlayName().c_str());
1193     }
1194     
1195     if (mSlicerManagers[index]->GetSlicer(0)->GetFusion()) {
1196       overlayPanel->getFusionName(mSlicerManagers[index]->GetFusionName().c_str());
1197     } else {
1198       overlayPanel->getFusionName(mSlicerManagers[index]->GetFusionName().c_str());
1199     }
1200   }
1201 }
1202 //------------------------------------------------------------------------------
1203
1204 //------------------------------------------------------------------------------
1205 void vvMainWindow::ShowDocumentation()
1206 {
1207   documentation->show();
1208 }
1209 //------------------------------------------------------------------------------
1210
1211 //------------------------------------------------------------------------------
1212 void vvMainWindow::PopupRegisterForm(bool checkCanPush)
1213 {
1214   vvRegisterForm* registerForm = new vvRegisterForm(QUrl("http://www.creatis.insa-lyon.fr/~dsarrut/vvregister/write.php"), getVVSettingsPath(), getSettingsOptionFormat());
1215   if(!checkCanPush) {
1216     registerForm->show();
1217   } else {
1218     if(registerForm->canPush()) {
1219       registerForm->show();
1220       registerForm->acquitPushed();//too bad if there is not internet connection anymore.
1221     }
1222   }
1223 }
1224 //------------------------------------------------------------------------------
1225
1226 //------------------------------------------------------------------------------
1227 void vvMainWindow::ShowHelpDialog()
1228 {
1229   help_dialog->show();
1230 }
1231 //------------------------------------------------------------------------------
1232
1233 //------------------------------------------------------------------------------
1234 void vvMainWindow::ChangeViewMode()
1235 {
1236   QList<int> size;
1237   if (viewMode == 1) {
1238     viewMode = 0;
1239     size.push_back(1);
1240     size.push_back(0);
1241     splitter_3->setSizes(size);
1242     OSplitter->setSizes(size);
1243     DataTree->setColumnHidden(2,1);
1244     DataTree->setColumnHidden(3,1);
1245     DataTree->setColumnHidden(4,1);
1246   } else {
1247     viewMode = 1;
1248     size.push_back(1);
1249     size.push_back(1);
1250     splitter_3->setSizes(size);
1251     OSplitter->setSizes(size);
1252     DataTree->setColumnHidden(2,0);
1253     DataTree->setColumnHidden(3,0);
1254     DataTree->setColumnHidden(4,0);
1255   }
1256   UpdateRenderWindows();
1257   /*
1258   ** I don't know why but for both resized QVTKWidget we also need to render
1259   ** the associated Slicer to redraw crosses.
1260   */
1261   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
1262     if (DataTree->topLevelItem(i)->data(COLUMN_UL_VIEW,Qt::CheckStateRole).toInt() > 1)
1263       mSlicerManagers[i]->GetSlicer(0)->Render();
1264     if (DataTree->topLevelItem(i)->data(COLUMN_DL_VIEW,Qt::CheckStateRole).toInt() > 1)
1265       mSlicerManagers[i]->GetSlicer(2)->Render();
1266   }
1267 }
1268 //------------------------------------------------------------------------------
1269
1270 //------------------------------------------------------------------------------
1271 QString vvMainWindow::GetSizeInBytes(unsigned long size)
1272 {
1273   QString result = "";// QString::number(size);
1274   //result += " bytes (";
1275   if (size > 1000000000) {
1276     size /= 1000000000;
1277     result += QString::number(size);
1278     result += "Gb";//)";
1279   } else if (size > 1000000) {
1280     size /= 1000000;
1281     result += QString::number(size);
1282     result += "Mb";//)";
1283   } else if (size > 1000) {
1284     size /= 1000;
1285     result += QString::number(size);
1286     result += "kb";//)";
1287   }
1288   return result;
1289 }
1290 //------------------------------------------------------------------------------
1291
1292 //------------------------------------------------------------------------------
1293 QString vvMainWindow::Get4x4MatrixDoubleAsString(vtkSmartPointer<vtkMatrix4x4> matrix, const int precision)
1294 {
1295   std::ostringstream strmatrix;
1296
1297   // Figure out the number of digits of the integer part of the largest absolute value
1298   // for each column
1299   unsigned width[4];
1300   for (unsigned int j = 0; j < 4; j++){
1301     double absmax = 0.;
1302     for (unsigned int i = 0; i < 4; i++)
1303       absmax = std::max(absmax, vnl_math_abs(matrix->GetElement(i, j)));
1304     unsigned ndigits = (unsigned)std::max(0.,std::log10(absmax))+1;
1305     width[j] = precision+ndigits+3;
1306   }
1307
1308   // Output with correct width, aligned to the right
1309   for (unsigned int i = 0; i < 4; i++) {
1310     for (unsigned int j = 0; j < 4; j++) {
1311       strmatrix.setf(ios::fixed,ios::floatfield);
1312       strmatrix.precision(precision);
1313       strmatrix.fill(' ');
1314       strmatrix.width(width[j]);
1315       strmatrix << std::right << matrix->GetElement(i, j);
1316     }
1317     strmatrix << std::endl;
1318   }
1319   QString result = strmatrix.str().c_str();
1320   return result;
1321 }
1322 //------------------------------------------------------------------------------
1323
1324 //------------------------------------------------------------------------------
1325 QString vvMainWindow::GetVectorDoubleAsString(std::vector<double> vectorDouble)
1326 {
1327   QString result;
1328   for (unsigned int i= 0; i < vectorDouble.size(); i++) {
1329     if (i != 0)
1330       result += " ";
1331     result += QString::number(vectorDouble[i]);
1332   }
1333   return result;
1334 }
1335 //------------------------------------------------------------------------------
1336
1337 //------------------------------------------------------------------------------
1338 QString vvMainWindow::GetVectorIntAsString(std::vector<int> vectorInt)
1339 {
1340   QString result;
1341   for (unsigned int i= 0; i < vectorInt.size(); i++) {
1342     if (i != 0)
1343       result += " ";
1344     result += QString::number(vectorInt[i]);
1345   }
1346   return result;
1347 }
1348 //------------------------------------------------------------------------------
1349
1350 //------------------------------------------------------------------------------
1351 int vvMainWindow::GetSlicerIndexFromItem(QTreeWidgetItem* item)
1352 {
1353   QString id = item->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString();
1354   for (int i = 0; i < DataTree->topLevelItemCount(); i++) {
1355     if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString() == id)
1356       return i;
1357   }
1358   return -1;
1359 }
1360 //------------------------------------------------------------------------------
1361
1362 //------------------------------------------------------------------------------
1363 QTreeWidgetItem* vvMainWindow::GetItemFromSlicerManager(vvSlicerManager* sm)
1364 {
1365   QString id = sm->GetId().c_str();
1366   for (int i = 0; i < DataTree->topLevelItemCount(); i++) {
1367     if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString() == id)
1368       return DataTree->topLevelItem(i);
1369   }
1370   return NULL;
1371 }
1372 //------------------------------------------------------------------------------
1373
1374 //------------------------------------------------------------------------------
1375 void vvMainWindow::DisplayChanged(QTreeWidgetItem *clickedItem, int column)
1376 {
1377   if ( column >= COLUMN_CLOSE_IMAGE || column <= 0)
1378     return;
1379
1380   // Get parent information (might be the same item)
1381   int slicerManagerIndex = GetSlicerIndexFromItem(clickedItem);
1382   QTreeWidgetItem* clickedParentItem = DataTree->topLevelItem(slicerManagerIndex);
1383   vvSlicer* clickedSlicer = mSlicerManagers[slicerManagerIndex]->GetSlicer(column-1);
1384
1385   // Go over the complete item tree (only 2 levels, parents and children)
1386   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
1387     // Trick to avoid redoing twice the job for a key (sr)
1388     mSlicerManagers[i]->GetSlicer(column-1)->GetRenderWindow()->GetInteractor()->SetKeySym("Crap");
1389
1390     QTreeWidgetItem* currentParentItem = DataTree->topLevelItem(i);
1391     if(currentParentItem != clickedParentItem) {
1392       // Not the branch of the clicked item, uncheck all
1393
1394       // Parent
1395       currentParentItem->setData(column,Qt::CheckStateRole, 0);
1396       mSlicerManagers[i]->UpdateSlicer(column-1, false);
1397
1398       // Children
1399       for (int iChild = 0; iChild < currentParentItem->childCount(); iChild++) {
1400         currentParentItem->child(iChild)->setData(column,Qt::CheckStateRole, 0);
1401       }
1402     }
1403     else {
1404       // Branch of the clicked one: get check status from actor visibility in slicer
1405       // and toggle the clicked one
1406
1407       // Parent
1408       bool vis = clickedSlicer->GetActorVisibility("image", 0);
1409       bool draw = clickedSlicer->GetRenderer()->GetDraw();
1410
1411       // Update slicer (after getting visibility)
1412       mSlicerManagers[slicerManagerIndex]->UpdateSlicer(column-1, true);
1413       mSlicerManagers[slicerManagerIndex]->UpdateInfoOnCursorPosition(column-1);
1414       DisplaySliders(slicerManagerIndex, column-1);
1415       if(clickedParentItem == clickedItem) {
1416         // Toggle
1417         vis = !draw || !vis;
1418       }
1419       clickedSlicer->SetActorVisibility("image", 0, vis);
1420       clickedParentItem->setData(column, Qt::CheckStateRole, vis?2:0);
1421
1422       // Children
1423       std::map<std::string, int> actorTypeCounts;      
1424       for (int iChild = 0; iChild < clickedParentItem->childCount(); iChild++) {
1425         QTreeWidgetItem* currentChildItem = clickedParentItem->child(iChild);
1426         std::string actorType = currentChildItem->data(1,Qt::UserRole).toString().toStdString();
1427         vis = clickedSlicer->GetActorVisibility(actorType, actorTypeCounts[actorType]);
1428         if(currentChildItem == clickedItem) {
1429           // Toggle or force visibility if it was not on this branch so far
1430           vis = !draw || !vis;
1431           clickedSlicer->SetActorVisibility(actorType, actorTypeCounts[actorType], vis);
1432         }
1433         currentChildItem->setData(column, Qt::CheckStateRole, vis?2:0);
1434         actorTypeCounts[actorType]++;
1435       }
1436     }
1437   }
1438
1439   clickedSlicer->Render();
1440 }
1441 //------------------------------------------------------------------------------
1442
1443 void vvMainWindow::InitSlicers()
1444 {
1445   if (mSlicerManagers.size()) {
1446     mSlicerManagers.back()->GenerateDefaultLookupTable();
1447
1448     mSlicerManagers.back()->SetSlicerWindow(0,NOViewWidget->GetRenderWindow());
1449     mSlicerManagers.back()->SetSlicerWindow(1,NEViewWidget->GetRenderWindow());
1450     mSlicerManagers.back()->SetSlicerWindow(2,SOViewWidget->GetRenderWindow());
1451     mSlicerManagers.back()->SetSlicerWindow(3,SEViewWidget->GetRenderWindow());
1452   }
1453 }
1454
1455 //------------------------------------------------------------------------------
1456 void vvMainWindow::InitDisplay()
1457 {
1458   if (mSlicerManagers.size()) {
1459     //BE CAREFUL : this is absolutely necessary to set the interactor style
1460     //in order to have the same style instanciation for all SlicerManagers in
1461     // a same window
1462     for (int j = 0; j < 4; j++) {
1463       vvInteractorStyleNavigator* style = vvInteractorStyleNavigator::New();
1464       style->SetAutoAdjustCameraClippingRange(1);
1465       bool AlreadySelected = false;
1466       for (int i = 0; i < DataTree->topLevelItemCount(); i++) {
1467         mSlicerManagers[i]->SetInteractorStyleNavigator(j,style);
1468
1469         //select the image only if previous are not selected
1470         if (DataTree->topLevelItem(i)->data(j+1,Qt::CheckStateRole).toInt() > 1) {
1471           mSlicerManagers[i]->UpdateSlicer(j,1);
1472           AlreadySelected = true;
1473         } else if (i == DataTree->topLevelItemCount()-1 && !AlreadySelected) {
1474           if (DataTree->selectedItems().size() == 0)
1475             DataTree->topLevelItem(i)->setSelected(1);
1476           DataTree->topLevelItem(i)->setData(j+1,Qt::CheckStateRole,2);
1477           mSlicerManagers[i]->UpdateSlicer(j,1);
1478           DisplaySliders(i,j);
1479         } else {
1480           DataTree->topLevelItem(i)->setData(j+1,Qt::CheckStateRole,0);
1481           mSlicerManagers[i]->UpdateSlicer(j,0);
1482         }
1483       }
1484       style->Delete();
1485     }
1486   }
1487 }
1488 //------------------------------------------------------------------------------
1489
1490 //------------------------------------------------------------------------------
1491 void vvMainWindow::DisplaySliders(int slicer, int window)
1492 {
1493   int range[2];
1494   mSlicerManagers[slicer]->GetSlicer(window)->GetSliceRange(range);
1495   int position = mSlicerManagers[slicer]->GetSlicer(window)->GetSlice();
1496
1497   int tRange[2];
1498   tRange[0] = 0;
1499   tRange[1] = mSlicerManagers[slicer]->GetSlicer(window)->GetTMax();
1500   int tPosition = mSlicerManagers[slicer]->GetSlicer(window)->GetTSlice();
1501   bool showHorizontal = false;
1502   bool showVertical = false;
1503   if (mSlicerManagers[slicer]->GetSlicer(window)->GetImage()->GetNumberOfDimensions() > 3
1504       || (mSlicerManagers[slicer]->GetSlicer(window)->GetImage()->GetNumberOfDimensions() > 2
1505           && mSlicerManagers[slicer]->GetType() != vvImageReader::IMAGEWITHTIME
1506           && mSlicerManagers[slicer]->GetType() != vvImageReader::MERGEDWITHTIME))
1507     showVertical = true;
1508   if (mSlicerManagers[slicer]->GetSlicer(window)->GetImage()->GetNumberOfDimensions() > 3
1509       || mSlicerManagers[slicer]->GetType() == vvImageReader::IMAGEWITHTIME
1510       || mSlicerManagers[slicer]->GetType() == vvImageReader::MERGEDWITHTIME)
1511     showHorizontal = true;
1512
1513   if (showVertical)
1514     verticalSliders[window]->show();
1515   else
1516     verticalSliders[window]->hide();
1517   verticalSliders[window]->setRange(range[0],range[1]);
1518   verticalSliders[window]->setValue(position);
1519
1520   if (showHorizontal)
1521     horizontalSliders[window]->show();
1522   else
1523     horizontalSliders[window]->hide();
1524   horizontalSliders[window]->setRange(tRange[0],tRange[1]);
1525   horizontalSliders[window]->setValue(tPosition);
1526 }
1527 //------------------------------------------------------------------------------
1528
1529 //------------------------------------------------------------------------------
1530 void vvMainWindow::CloseImage(QTreeWidgetItem* item, int column)
1531 {
1532   int index = GetSlicerIndexFromItem(item);
1533
1534   if (DataTree->topLevelItem(index) != item) {
1535     QString warning = "Do you really want to close the overlay : ";
1536     warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1537     QMessageBox msgBox(QMessageBox::Warning, tr("Close Overlay"),
1538                        warning, 0, this);
1539     msgBox.addButton(tr("Close"), QMessageBox::AcceptRole);
1540     msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
1541     if (msgBox.exec() == QMessageBox::AcceptRole) {
1542       std::string overlay_type=item->data(1,Qt::UserRole).toString().toStdString();
1543       int overlay_index=0;
1544       for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++) {
1545         if (DataTree->topLevelItem(index)->\
1546             child(child)->data(1,Qt::UserRole).toString().toStdString() == overlay_type)
1547           overlay_index++;
1548         if (DataTree->topLevelItem(index)->child(child) == item) break;
1549       }
1550       mSlicerManagers[index]->RemoveActor(overlay_type, overlay_index-1);
1551       mSlicerManagers[index]->SetColorMap(0);
1552       DataTree->topLevelItem(index)->takeChild(DataTree->topLevelItem(index)->indexOfChild(item));
1553       mSlicerManagers[index]->Render();
1554     }
1555   } else if (DataTree->topLevelItemCount() <= 1) {
1556     QString warning = "Do you really want to close the image : ";
1557     warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1558     warning += "\nThis is the last image, you're about to close vv !!!";
1559     QMessageBox msgBox(QMessageBox::Warning, tr("Close Image"),
1560                        warning, 0, this);
1561     msgBox.addButton(tr("Close vv"), QMessageBox::AcceptRole);
1562     msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
1563     if (msgBox.exec() == QMessageBox::AcceptRole) {
1564       this->close();
1565     }
1566   } else {
1567     QString warning = "Do you really want to close the image : ";
1568     warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1569     QMessageBox msgBox(QMessageBox::Warning, tr("Close Image"),
1570                        warning, 0, this);
1571     msgBox.addButton(tr("Close"), QMessageBox::AcceptRole);
1572     msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
1573     if (msgBox.exec() == QMessageBox::AcceptRole) {
1574
1575       // Tell tools that we close an image
1576       emit AnImageIsBeingClosed(mSlicerManagers[index]);
1577
1578       std::vector<vvSlicerManager*>::iterator Manageriter = mSlicerManagers.begin();
1579       DataTree->takeTopLevelItem(index);
1580       for (int i = 0; i < index; i++) {
1581         Manageriter++;
1582       }
1583       linkPanel->removeImage(index);
1584       mSlicerManagers[index]->RemoveActors();
1585       delete mSlicerManagers[index];
1586       mSlicerManagers.erase(Manageriter);
1587
1588       //
1589       InitDisplay();
1590     }
1591   }
1592   ImageInfoChanged();
1593 }
1594 //------------------------------------------------------------------------------
1595
1596 //------------------------------------------------------------------------------
1597 void vvMainWindow::ReloadImage(QTreeWidgetItem* item, int column)
1598 {
1599   // int index = GetSlicerIndexFromItem(item);
1600   //   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1601   //   if (item->data(1,Qt::UserRole).toString() == "vector")
1602   //     mSlicerManagers[index]->ReloadVF();
1603   //   else
1604   //     mSlicerManagers[index]->Reload();
1605
1606   //   QApplication::restoreOverrideCursor();
1607   int index = GetSlicerIndexFromItem(item);
1608   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1609   QString role=item->data(1,Qt::UserRole).toString();
1610   if ( role == "vector"){
1611     mSlicerManagers[index]->ReloadVF();
1612   }
1613   else if (role == "overlay"){
1614     mSlicerManagers[index]->ReloadOverlay();
1615   }
1616   else if (role == "fusion"){
1617     mSlicerManagers[index]->ReloadFusion();
1618   }
1619   else{
1620     mSlicerManagers[index]->Reload();
1621   }
1622   // Update view and info
1623   ImageInfoChanged();
1624   mSlicerManagers[index]->Render();
1625   QApplication::restoreOverrideCursor();
1626 }
1627 //------------------------------------------------------------------------------
1628
1629 //------------------------------------------------------------------------------
1630 void vvMainWindow::MousePositionChanged(int visibility,double x, double y, double z, double X, double Y, double Z , double value)
1631 {
1632   infoPanel->setCurrentInfo(visibility,x,y,z,X,Y,Z,value);
1633 }
1634 //------------------------------------------------------------------------------
1635
1636 //------------------------------------------------------------------------------
1637 void vvMainWindow::VectorChanged(int visibility,double x, double y, double z, double value)
1638 {
1639   overlayPanel->getCurrentVectorInfo(visibility,x,y,z,value);
1640 }
1641 //------------------------------------------------------------------------------
1642
1643 //------------------------------------------------------------------------------
1644 void vvMainWindow::OverlayChanged(int visibility, double valueOver, double valueRef)
1645 {
1646   overlayPanel->getCurrentOverlayInfo(visibility,valueOver, valueRef);
1647 }
1648 //------------------------------------------------------------------------------
1649
1650 //------------------------------------------------------------------------------
1651 void vvMainWindow::FusionChanged(int visibility, double value)
1652 {
1653   overlayPanel->getCurrentFusionInfo(visibility,value);
1654 }
1655 //------------------------------------------------------------------------------
1656
1657 //------------------------------------------------------------------------------
1658 void vvMainWindow::WindowLevelChanged()
1659 {
1660   // Base image
1661   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1662   if(index==-1) return;
1663   windowSpinBox->setValue(mSlicerManagers[index]->GetColorWindow());
1664   levelSpinBox->setValue(mSlicerManagers[index]->GetColorLevel());
1665   colorMapComboBox->setCurrentIndex(mSlicerManagers[index]->GetColorMap());
1666   presetComboBox->setCurrentIndex(mSlicerManagers[index]->GetPreset());
1667
1668   // Overlay image
1669   if (mSlicerManagers[index]->GetSlicer(0)->GetOverlay())
1670     overlayPanel->getOverlayProperty(mSlicerManagers[index]->GetOverlayColor(),
1671                                      mSlicerManagers[index]->GetLinkOverlayWindowLevel(),
1672                                      mSlicerManagers[index]->GetOverlayColorWindow(),
1673                                      mSlicerManagers[index]->GetOverlayColorLevel());
1674   else
1675     overlayPanel->getOverlayProperty(-1,0,0.,0.);
1676
1677   // Fusion image
1678   if (mSlicerManagers[index]->GetSlicer(0)->GetFusion())
1679     overlayPanel->getFusionProperty(mSlicerManagers[index]->GetFusionOpacity(),
1680                                     mSlicerManagers[index]->GetFusionThresholdOpacity(),
1681                                     mSlicerManagers[index]->GetFusionColorMap(),
1682                                     mSlicerManagers[index]->GetFusionWindow(),
1683                                     mSlicerManagers[index]->GetFusionLevel());
1684   else
1685     overlayPanel->getFusionProperty(-1, -1, -1, -1, -1);
1686 }
1687 //------------------------------------------------------------------------------
1688
1689 //------------------------------------------------------------------------------
1690 void vvMainWindow::WindowLevelEdited()
1691 {
1692   presetComboBox->setCurrentIndex(6);
1693   UpdateWindowLevel();
1694 }
1695 //------------------------------------------------------------------------------
1696
1697 //------------------------------------------------------------------------------
1698 void vvMainWindow::SetWindowLevel(double w, double l)
1699 {
1700   windowSpinBox->setValue(w);
1701   levelSpinBox->setValue(l);
1702   presetComboBox->setCurrentIndex(6);
1703   colorMapComboBox->setCurrentIndex(0);
1704   UpdateWindowLevel();
1705 }
1706 //------------------------------------------------------------------------------
1707
1708 //------------------------------------------------------------------------------
1709 void vvMainWindow::UpdateWindowLevel()
1710 {
1711   if (DataTree->selectedItems().size()) {
1712     if (presetComboBox->currentIndex() == 7) //For ventilation
1713       colorMapComboBox->setCurrentIndex(5);
1714     int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1715     mSlicerManagers[index]->SetColorWindow(windowSpinBox->value());
1716     mSlicerManagers[index]->SetColorLevel(levelSpinBox->value());
1717     mSlicerManagers[index]->SetPreset(presetComboBox->currentIndex());
1718     mSlicerManagers[index]->Render();
1719     WindowLevelChanged();
1720   }
1721 }
1722 //------------------------------------------------------------------------------
1723
1724 //------------------------------------------------------------------------------
1725 void vvMainWindow::UpdateColorMap()
1726 {
1727   if (DataTree->selectedItems().size()) {
1728     int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1729     mSlicerManagers[index]->SetColorMap(colorMapComboBox->currentIndex());
1730     mSlicerManagers[index]->Render();
1731   }
1732 }
1733 //------------------------------------------------------------------------------
1734 void vvMainWindow::SwitchWindowLevel()
1735 {
1736   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1737   int window = mSlicerManagers[index]->GetColorWindow();
1738   presetComboBox->setCurrentIndex(6);
1739   windowSpinBox->setValue(-window);
1740   UpdateWindowLevel();
1741 }
1742 //------------------------------------------------------------------------------
1743
1744 //------------------------------------------------------------------------------
1745 void vvMainWindow::ApplyWindowLevelToAllImages()
1746 {
1747   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1748   if(index==-1) return;
1749   double window = mSlicerManagers[index]->GetColorWindow();
1750   double level = mSlicerManagers[index]->GetColorLevel();
1751
1752   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
1753     if (mSlicerManagers[i] == NULL)
1754       continue;
1755     mSlicerManagers[i]->SetColorWindow(window);
1756     mSlicerManagers[i]->SetColorLevel(level);
1757     mSlicerManagers[i]->SetPreset(6);
1758     mSlicerManagers[i]->Render();
1759   }
1760 }
1761 //------------------------------------------------------------------------------
1762
1763 //------------------------------------------------------------------------------
1764 void vvMainWindow::UpdateLinkManager(std::string id, int slicer, double x, double y, double z, int temps)
1765 {
1766   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
1767     if (mSlicerManagers[i]->GetId() == id) {
1768       //mSlicerManagers[i]->SetTSlice(temps);
1769       mSlicerManagers[i]->GetSlicer(slicer)->SetCurrentPosition(x,y,z,temps);
1770       mSlicerManagers[i]->UpdateViews(0,slicer);
1771       break;
1772     }
1773   }
1774 }
1775 //------------------------------------------------------------------------------
1776
1777 //------------------------------------------------------------------------------
1778 void vvMainWindow::UpdateLinkedNavigation(std::string id, vvSlicerManager * sm, vvSlicer* refSlicer)
1779 {
1780   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
1781     if (id == mSlicerManagers[i]->GetId()) {
1782       mSlicerManagers[i]->UpdateLinkedNavigation(refSlicer);
1783     }
1784   }
1785 }
1786 //------------------------------------------------------------------------------
1787
1788 //------------------------------------------------------------------------------
1789 void vvMainWindow::ShowContextMenu(QPoint point)
1790 {
1791   if (!DataTree->selectedItems().size()) {
1792     contextActions[1]->setEnabled(0);
1793     contextActions[2]->setEnabled(0);
1794     contextActions[3]->setEnabled(0);
1795     contextActions[4]->setEnabled(0);
1796     contextActions[5]->setEnabled(0);
1797     contextActions[6]->setEnabled(0);
1798   } else {
1799     int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1800     contextActions[1]->setEnabled(1);
1801     contextActions[2]->setEnabled(
1802       DataTree->itemWidget(DataTree->selectedItems()[0],
1803                            COLUMN_RELOAD_IMAGE)->isEnabled());
1804     contextActions[3]->setEnabled(1);
1805     contextActions[5]->setEnabled(1);
1806     contextActions[6]->setEnabled(1);
1807
1808     if (mSlicerManagers[index]->GetDimension() < 3)
1809       contextActions[4]->setEnabled(0);
1810     else
1811       contextActions[4]->setEnabled(1);
1812   }
1813   contextMenu.exec(QCursor::pos());
1814 }
1815 //------------------------------------------------------------------------------
1816
1817 //------------------------------------------------------------------------------
1818 void vvMainWindow::CloseImage()
1819 {
1820   CloseImage(DataTree->selectedItems()[0],0);
1821 }
1822 //------------------------------------------------------------------------------
1823
1824 //------------------------------------------------------------------------------
1825 void vvMainWindow::ReloadImage()
1826 {
1827   ReloadImage(DataTree->selectedItems()[0],0);
1828 }
1829 //------------------------------------------------------------------------------
1830
1831 //------------------------------------------------------------------------------
1832 void vvMainWindow::SelectOverlayImage()
1833 {
1834   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1835
1836   //check if one overlay image is added
1837   for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++)
1838     if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "overlay") {
1839       QString error = "Cannot add more than one compared image\n";
1840       error += "Please remove first ";
1841       error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1842       QMessageBox::information(this,tr("Problem adding compared image !"),error);
1843       return;
1844     }
1845
1846   QString Extensions = EXTENSIONS;
1847   Extensions += ";;All Files (*)";
1848   QString file = QFileDialog::getOpenFileName(this,tr("Load Overlay image"),mInputPathName,Extensions);
1849   if (!file.isEmpty())
1850     AddOverlayImage(index,file);
1851 }
1852 //------------------------------------------------------------------------------
1853
1854 //------------------------------------------------------------------------------
1855 void vvMainWindow::AddOverlayImage(int index, QString file)
1856 {
1857   if (QFile::exists(file))
1858   {
1859     mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str();
1860     itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO(
1861         file.toStdString().c_str(), itk::ImageIOFactory::ReadMode);
1862     reader->SetFileName(file.toStdString().c_str());
1863     reader->ReadImageInformation();
1864     std::string component = reader->GetComponentTypeAsString(reader->GetComponentType());
1865     int dimension = reader->GetNumberOfDimensions();
1866     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1867     vvProgressDialog progress("Opening " + file.toStdString());
1868     qApp->processEvents();
1869
1870     std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str();
1871     if (mSlicerManagers[index]->SetOverlay(file.toStdString(),dimension, component)) {
1872       //create an item in the tree with good settings
1873       QTreeWidgetItem *item = new QTreeWidgetItem();
1874       item->setData(0,Qt::UserRole,file.toStdString().c_str());
1875       item->setData(1,Qt::UserRole,tr("overlay"));
1876       QFileInfo fileinfo(file); //Do not show the path
1877       item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,fileinfo.fileName());
1878       item->setToolTip(COLUMN_IMAGE_NAME, mSlicerManagers[index]->GetListOfAbsoluteFilePathInOneString("overlay").c_str());
1879       qApp->processEvents();
1880
1881       for (int j = 1; j <= 4; j++) {
1882         item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole));
1883       }
1884
1885       //Create the buttons for reload and close
1886       qApp->processEvents();
1887       QTreePushButton* cButton = new QTreePushButton;
1888       cButton->setItem(item);
1889       cButton->setColumn(COLUMN_CLOSE_IMAGE);
1890       cButton->setToolTip(tr("close image"));
1891       cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
1892       connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
1893           this,SLOT(CloseImage(QTreeWidgetItem*, int)));
1894
1895       QTreePushButton* rButton = new QTreePushButton;
1896       rButton->setItem(item);
1897       rButton->setColumn(COLUMN_RELOAD_IMAGE);
1898       rButton->setToolTip(tr("reload image"));
1899       rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
1900       connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
1901           this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
1902
1903       DataTree->topLevelItem(index)->setExpanded(1);
1904       DataTree->topLevelItem(index)->addChild(item);
1905       DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
1906       DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
1907
1908       //set the id of the image
1909       QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString();
1910       item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
1911       UpdateTree();
1912       qApp->processEvents();
1913       ImageInfoChanged();
1914       QApplication::restoreOverrideCursor();
1915     } else {
1916       QApplication::restoreOverrideCursor();
1917       QString error = "Cannot import the new image.\n";
1918       error += mSlicerManagers[index]->GetLastError().c_str();
1919       QMessageBox::information(this,tr("Problem reading image !"),error);
1920     }
1921     WindowLevelChanged();
1922   }
1923   else
1924     QMessageBox::information(this,tr("Problem reading Overlay !"),"File doesn't exist!");
1925 }
1926 //------------------------------------------------------------------------------
1927
1928
1929 //------------------------------------------------------------------------------
1930 void vvMainWindow::AddROI(int index, QString file)
1931 {
1932   /*
1933   // Get slice manager
1934
1935   // Load image
1936
1937   vvImageReader * mReader = new vvImageReader;
1938   mReader->SetInputFilename(filename.toStdString());
1939   mReader->Update(IMAGE);
1940   if (mReader->GetLastError().size() != 0) {
1941     std::cerr << "Error while reading " << filename.toStdString() << std::endl;
1942     QString error = "Cannot open file \n";
1943     error += mReader->GetLastError().c_str();
1944     QMessageBox::information(this,tr("Reading problem"),error);
1945     delete mReader;
1946     return;
1947   }
1948   vvImage::Pointer roi = mReader->GetOutput();
1949
1950   // Create roi in new tool
1951   vvToolStructureSetManager::AddImage(mCurrentSlicerManager, roi);
1952   */
1953 }
1954 //------------------------------------------------------------------------------
1955
1956 //------------------------------------------------------------------------------
1957 void vvMainWindow::SelectFusionImage()
1958 {
1959   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1960
1961   //check if one fusion image is added
1962   for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++)
1963     if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "fusion") {
1964       QString error = "Cannot add more than one fusion image\n";
1965       error += "Please remove first ";
1966       error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
1967       QMessageBox::information(this,tr("Problem adding fusion image !"),error);
1968       return;
1969     }
1970
1971   QString Extensions = EXTENSIONS;
1972   Extensions += ";;All Files (*)";
1973   QString file = QFileDialog::getOpenFileName(this,tr("Load Fusion image"),mInputPathName,Extensions);
1974   if (!file.isEmpty())
1975     AddFusionImage(index,file);
1976 }
1977 //------------------------------------------------------------------------------
1978
1979 //------------------------------------------------------------------------------
1980 void vvMainWindow::ResetTransformationToIdentity()
1981 {
1982   std::string actorType = DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString().toStdString();
1983   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1984   mSlicerManagers[index]->ResetTransformationToIdentity(actorType);
1985   ImageInfoChanged();
1986 }
1987 //------------------------------------------------------------------------------
1988
1989 //------------------------------------------------------------------------------
1990 void vvMainWindow::AddFusionImage(int index, QString file)
1991 {
1992   if (QFile::exists(file))
1993   {
1994     mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str();
1995     itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO(
1996         file.toStdString().c_str(), itk::ImageIOFactory::ReadMode);
1997     reader->SetFileName(file.toStdString().c_str());
1998     reader->ReadImageInformation();
1999     std::string component = reader->GetComponentTypeAsString(reader->GetComponentType());
2000     if (reader) {
2001       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
2002       vvProgressDialog progress("Opening fusion");
2003       qApp->processEvents();
2004
2005       std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str();
2006       if (mSlicerManagers[index]->SetFusion(file.toStdString(),
2007             reader->GetNumberOfDimensions(), component)) {
2008         //create an item in the tree with good settings
2009         QTreeWidgetItem *item = new QTreeWidgetItem();
2010         item->setData(0,Qt::UserRole,file.toStdString().c_str());
2011         item->setData(1,Qt::UserRole,tr("fusion"));
2012         QFileInfo fileinfo(filename.c_str()); //Do not show the path
2013         item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,fileinfo.fileName());
2014         item->setToolTip(COLUMN_IMAGE_NAME, mSlicerManagers[index]->GetListOfAbsoluteFilePathInOneString("fusion").c_str());
2015         qApp->processEvents();
2016
2017         for (int j = 1; j <= 4; j++) {
2018           item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole));
2019         }
2020
2021         //Create the buttons for reload and close
2022         qApp->processEvents();
2023         QTreePushButton* cButton = new QTreePushButton;
2024         cButton->setItem(item);
2025         cButton->setColumn(COLUMN_CLOSE_IMAGE);
2026         cButton->setToolTip(tr("close image"));
2027         cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
2028         connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2029             this,SLOT(CloseImage(QTreeWidgetItem*, int)));
2030
2031         QTreePushButton* rButton = new QTreePushButton;
2032         rButton->setItem(item);
2033         rButton->setColumn(COLUMN_RELOAD_IMAGE);
2034         rButton->setToolTip(tr("reload image"));
2035         rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
2036         connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2037             this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
2038
2039         DataTree->topLevelItem(index)->setExpanded(1);
2040         DataTree->topLevelItem(index)->addChild(item);
2041         DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
2042         DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
2043
2044         //set the id of the image
2045         QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString();
2046         item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
2047         UpdateTree();
2048         qApp->processEvents();
2049         ImageInfoChanged();
2050         QApplication::restoreOverrideCursor();
2051       } else {
2052         QApplication::restoreOverrideCursor();
2053         QString error = "Cannot import the new image.\n";
2054         error += mSlicerManagers[index]->GetLastError().c_str();
2055         QMessageBox::information(this,tr("Problem reading image !"),error);
2056       }
2057     } else {
2058       QString error = "Cannot import the new image.\n";
2059       QMessageBox::information(this,tr("Problem reading image !"),error);
2060     }
2061   }
2062   else
2063     QMessageBox::information(this,tr("Problem reading Fusion !"),"File doesn't exist!");
2064 }
2065 //------------------------------------------------------------------------------
2066
2067
2068 //------------------------------------------------------------------------------
2069 void vvMainWindow::OpenField()
2070 {
2071   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2072   //check if a vector field has already been added
2073   for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++)
2074     if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "vector") {
2075       QString error = "Cannot add more than one vector field\n";
2076       error += "Please remove first ";
2077       error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
2078       QMessageBox::information(this,tr("Problem adding vector field!"),error);
2079       return;
2080     }
2081
2082   QString Extensions = "Images ( *.mhd)";
2083   Extensions += ";;Images ( *.mha)";
2084   Extensions += ";;Images ( *.vf)";
2085   QString file = QFileDialog::getOpenFileName(this,tr("Load deformation field"),mInputPathName,Extensions);
2086   if (!file.isEmpty())
2087     AddField(file,index);
2088 }
2089 //------------------------------------------------------------------------------
2090
2091
2092 //------------------------------------------------------------------------------
2093 void vvMainWindow::AddFieldEntry(QString filename,int index,bool from_disk)
2094 {
2095   //create an item in the tree with good settings
2096   QTreeWidgetItem *item = new QTreeWidgetItem();
2097   item->setData(0,Qt::UserRole,filename.toStdString().c_str());
2098   item->setData(1,Qt::UserRole,tr("vector"));
2099   QFileInfo fileinfo(filename); //Do not show the path
2100   item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,fileinfo.fileName());
2101   item->setToolTip(COLUMN_IMAGE_NAME, mSlicerManagers[index]->GetListOfAbsoluteFilePathInOneString("vector").c_str());
2102   qApp->processEvents();
2103
2104   for (int j = 1; j <= 4; j++) {
2105     item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole));
2106   }
2107
2108   //Create the buttons for reload and close
2109   qApp->processEvents();
2110   QTreePushButton* cButton = new QTreePushButton;
2111   cButton->setItem(item);
2112   cButton->setColumn(COLUMN_CLOSE_IMAGE);
2113   cButton->setToolTip(tr("close vector field"));
2114   cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
2115   connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2116           this,SLOT(CloseImage(QTreeWidgetItem*, int)));
2117
2118   QTreePushButton* rButton = new QTreePushButton;
2119   rButton->setItem(item);
2120   rButton->setColumn(COLUMN_RELOAD_IMAGE);
2121   rButton->setToolTip(tr("reload vector field"));
2122   rButton->setEnabled(from_disk);
2123   rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
2124   connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2125           this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
2126
2127   DataTree->topLevelItem(index)->setExpanded(1);
2128   DataTree->topLevelItem(index)->addChild(item);
2129   DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
2130   DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
2131
2132   //set the id of the image
2133   QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString();
2134   item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
2135   UpdateTree();
2136   qApp->processEvents();
2137   ImageInfoChanged();
2138   QApplication::restoreOverrideCursor();
2139 }
2140 //------------------------------------------------------------------------------
2141
2142
2143 //------------------------------------------------------------------------------
2144 void vvMainWindow::AddField(vvImage::Pointer vf,QString file,int index)
2145 {
2146   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
2147   vvSlicerManager* imageManager = mSlicerManagers[index];
2148   if (imageManager->SetVF(vf,file.toStdString())) {
2149     AddFieldEntry(file,index,false);
2150   } else {
2151     QString error = "Cannot import the vector field for this image.\n";
2152     error += imageManager->GetLastError().c_str();
2153     QMessageBox::information(this,tr("Problem reading VF !"),error);
2154   }
2155   QApplication::restoreOverrideCursor();
2156 }
2157 //------------------------------------------------------------------------------
2158
2159
2160 //------------------------------------------------------------------------------
2161 void vvMainWindow::AddField(QString file,int index)
2162 {
2163   if (QFile::exists(file)) {
2164     mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str();
2165
2166     //init the progress events
2167     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
2168     vvProgressDialog progress("Opening " + file.toStdString());
2169     qApp->processEvents();
2170
2171     //read the vector and put it in the current mSlicerManager
2172     vvSlicerManager* imageManager = mSlicerManagers[index];
2173     qApp->processEvents();
2174
2175     std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str();
2176     if (imageManager->SetVF(file.toStdString())) {
2177       imageManager->Render();
2178       AddFieldEntry(file,index,true);
2179     } else {
2180       QApplication::restoreOverrideCursor();
2181       QString error = "Cannot import the vector field for this image.\n";
2182       error += imageManager->GetLastError().c_str();
2183       QMessageBox::information(this,tr("Problem reading VF !"),error);
2184     }
2185   } else
2186     QMessageBox::information(this,tr("Problem reading VF !"),"File doesn't exist!");
2187
2188 }
2189 //------------------------------------------------------------------------------
2190
2191
2192 //------------------------------------------------------------------------------
2193 void vvMainWindow::SetVFProperty(int subsampling, int scale, int log, int width, double r, double g, double b)
2194 {
2195   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2196   if (mSlicerManagers[index]->GetSlicer(0)->GetVF()) {
2197     for (int i = 0; i < 4; i++) {
2198       mSlicerManagers[index]->GetSlicer(i)->SetVFSubSampling(subsampling);
2199       mSlicerManagers[index]->GetSlicer(i)->SetVFScale(scale);
2200       mSlicerManagers[index]->GetSlicer(i)->SetVFWidth(width);
2201       mSlicerManagers[index]->GetSlicer(i)->SetVFColor(r,g,b);
2202       if (log > 0)
2203         mSlicerManagers[index]->GetSlicer(i)->SetVFLog(1);
2204       else
2205         mSlicerManagers[index]->GetSlicer(i)->SetVFLog(0);
2206     }
2207   }
2208 }
2209 //------------------------------------------------------------------------------
2210
2211
2212 //------------------------------------------------------------------------------
2213 void vvMainWindow::SetOverlayProperty(int color, int linked, double window, double level)
2214 {
2215   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2216   if (mSlicerManagers[index]->GetSlicer(0)->GetOverlay()) {
2217     mSlicerManagers[index]->SetOverlayColor(color);
2218     mSlicerManagers[index]->SetColorMap(0);
2219     mSlicerManagers[index]->SetLinkOverlayWindowLevel(linked);
2220     mSlicerManagers[index]->SetOverlayColorWindow(window);
2221     mSlicerManagers[index]->SetOverlayColorLevel(level);
2222     mSlicerManagers[index]->Render();
2223   }
2224 }
2225 //------------------------------------------------------------------------------
2226
2227 //------------------------------------------------------------------------------
2228 void vvMainWindow::SetFusionProperty(int opacity, int thresOpacity, int colormap,double window, double level, bool showLegend)
2229 {
2230   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2231   if (mSlicerManagers[index]->GetSlicer(0)->GetFusion()) {
2232     mSlicerManagers[index]->SetFusionColorMap(colormap);
2233     mSlicerManagers[index]->SetFusionOpacity(opacity);
2234     mSlicerManagers[index]->SetFusionThresholdOpacity(thresOpacity);
2235     mSlicerManagers[index]->SetFusionWindow(window);
2236     mSlicerManagers[index]->SetFusionLevel(level);
2237     mSlicerManagers[index]->SetFusionShowLegend(showLegend);
2238     mSlicerManagers[index]->SetColorMap(0);
2239     mSlicerManagers[index]->Render();
2240   }
2241 }
2242 //------------------------------------------------------------------------------
2243
2244 //------------------------------------------------------------------------------
2245 void vvMainWindow::SaveAs()
2246 {
2247   if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "vector") {
2248     QMessageBox::warning(this,tr("Unsupported type"),tr("Sorry, saving a vector field is unsupported for the moment"));
2249     return;
2250   }
2251
2252   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2253   int dimension = mSlicerManagers[index]->GetDimension();
2254   QStringList OutputListeFormat;
2255   OutputListeFormat.clear();
2256   if (dimension == 1) {
2257     OutputListeFormat.push_back(".mhd");
2258     OutputListeFormat.push_back(".mha");
2259   }
2260   if (dimension == 2) {
2261     OutputListeFormat.push_back(".bmp");
2262     OutputListeFormat.push_back(".png");
2263     OutputListeFormat.push_back(".jpeg");
2264     OutputListeFormat.push_back(".tif");
2265     OutputListeFormat.push_back(".mhd");
2266     OutputListeFormat.push_back(".mha");
2267     OutputListeFormat.push_back(".hdr");
2268     OutputListeFormat.push_back(".vox");
2269   } else if (dimension == 3) {
2270     OutputListeFormat.push_back(".mhd");
2271     OutputListeFormat.push_back(".mha");
2272     OutputListeFormat.push_back(".nii");
2273     OutputListeFormat.push_back(".nrrd");
2274     OutputListeFormat.push_back(".nhdr");
2275     OutputListeFormat.push_back(".hdr");
2276     OutputListeFormat.push_back(".vox");
2277   } else if (dimension == 4) {
2278     OutputListeFormat.push_back(".mhd");
2279     OutputListeFormat.push_back(".mha");
2280     OutputListeFormat.push_back(".nii");
2281     OutputListeFormat.push_back(".nrrd");
2282     OutputListeFormat.push_back(".nhdr");
2283   }
2284   QString Extensions = "AllFiles(*.*)";
2285   for (int i = 0; i < OutputListeFormat.count(); i++) {
2286     Extensions += ";;Images ( *";
2287     Extensions += OutputListeFormat[i];
2288     Extensions += ")";
2289   }
2290   QString fileName = QFileDialog::getSaveFileName(this,
2291                      tr("Save As"),
2292                      mSlicerManagers[index]->GetFileName().c_str(),
2293                      Extensions);
2294   if (!fileName.isEmpty()) {
2295     std::string fileformat = itksys::SystemTools::GetFilenameLastExtension(fileName.toStdString());
2296     if (OutputListeFormat.contains(
2297           fileformat.c_str())) {
2298       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
2299       std::string action = "Saving";
2300       vvProgressDialog progress("Saving "+fileName.toStdString());
2301       qApp->processEvents();
2302       vvImageWriter::Pointer writer = vvImageWriter::New();
2303       writer->SetOutputFileName(fileName.toStdString());
2304       writer->SetInput(mSlicerManagers[index]->GetImage());
2305
2306       // Check on transform and prompt user
2307       writer->SetSaveTransform(false);
2308       bool bId = true;
2309       for(int i=0; i<4; i++)
2310         for(int j=0; j<4; j++) {
2311           double elt = mSlicerManagers[index]->GetImage()->GetTransform()->GetMatrix()->GetElement(i,j);
2312           if(i==j && elt!=1.)
2313             bId = false;
2314           if(i!=j && elt!=0.)
2315             bId = false;
2316         }
2317       if( !bId ) {
2318         QString warning = "The image has an associated linear transform. Do you want to save it along?";
2319         QMessageBox msgBox(QMessageBox::Warning, tr("Save transform"), warning, 0, this);
2320         msgBox.addButton(tr("Yes"), QMessageBox::AcceptRole);
2321         msgBox.addButton(tr("No"), QMessageBox::RejectRole);
2322         if (msgBox.exec() == QMessageBox::AcceptRole)
2323           writer->SetSaveTransform(true);
2324       }
2325
2326       writer->Update();
2327       QApplication::restoreOverrideCursor();
2328       if (writer->GetLastError().size()) {
2329         QString error = "Saving did not succeed\n";
2330         error += writer->GetLastError().c_str();
2331         QMessageBox::information(this,tr("Saving Problem"),error);
2332         SaveAs();
2333       }
2334     } else {
2335       QString error = fileformat.c_str();
2336       if (error.isEmpty())
2337         error += "no file format specified !";
2338       else
2339         error += " format unknown !!!\n";
2340       QMessageBox::information(this,tr("Saving Problem"),error);
2341       SaveAs();
2342     }
2343   }
2344 }
2345 //------------------------------------------------------------------------------
2346
2347 //------------------------------------------------------------------------------
2348 void vvMainWindow::SaveCurrentState()
2349 {
2350   QString Extensions = "XML Files(*.xml)";
2351   QString fileName = QFileDialog::getSaveFileName(this,
2352                      tr("Save Current Window State"),
2353                      "",
2354                      Extensions);
2355                      
2356   SaveCurrentStateAs(fileName.toStdString());
2357 }
2358 //------------------------------------------------------------------------------
2359
2360 //------------------------------------------------------------------------------
2361 void vvMainWindow::SaveCurrentStateAs(const std::string& stateFile)
2362 {
2363   vvSaveState save_state;
2364   save_state.Run(this, stateFile);
2365 }
2366
2367 //------------------------------------------------------------------------------
2368 void vvMainWindow::ReadSavedState()
2369 {
2370   QString Extensions = "XML Files(*.xml)";
2371   QString fileName = QFileDialog::getOpenFileName(this,
2372                      tr("Load Window State"),
2373                      "",
2374                      Extensions);
2375                      
2376   ReadSavedStateFile(fileName.toStdString());
2377 }
2378 //------------------------------------------------------------------------------
2379
2380 //------------------------------------------------------------------------------
2381 void vvMainWindow::ReadSavedStateFile(const std::string& stateFile)
2382 {
2383   vvReadState read_state;
2384   read_state.Run(this, stateFile);
2385 }
2386 //------------------------------------------------------------------------------
2387
2388 //------------------------------------------------------------------------------
2389 void vvMainWindow::LinkAllImages()
2390 {
2391         linkPanel->linkAll();
2392 }
2393
2394 //------------------------------------------------------------------------------
2395 void vvMainWindow::AddLink(QString image1,QString image2)
2396 {
2397   unsigned int sm1 = 0;
2398   unsigned int sm2 = 0;
2399
2400   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2401     if (image1.toStdString() == mSlicerManagers[i]->GetId()) {
2402       mSlicerManagers[i]->AddLink(image2.toStdString());
2403       sm1 = i;
2404     }
2405     if (image2.toStdString() == mSlicerManagers[i]->GetId()) {
2406       mSlicerManagers[i]->AddLink(image1.toStdString());
2407       sm2 = i;
2408     }
2409   }
2410
2411   if (linkPanel->isLinkAll())   {
2412     emit UpdateLinkedNavigation(mSlicerManagers[sm1]->GetId(), mSlicerManagers[mCurrentPickedImageIndex], mSlicerManagers[mCurrentPickedImageIndex]->GetSlicer(0));
2413     emit UpdateLinkedNavigation(mSlicerManagers[sm2]->GetId(), mSlicerManagers[mCurrentPickedImageIndex], mSlicerManagers[mCurrentPickedImageIndex]->GetSlicer(0));
2414   } else {
2415     emit UpdateLinkedNavigation(mSlicerManagers[sm2]->GetId(), mSlicerManagers[sm1], mSlicerManagers[sm1]->GetSlicer(0));
2416   }
2417 }
2418
2419 //------------------------------------------------------------------------------
2420
2421
2422 //------------------------------------------------------------------------------
2423 void vvMainWindow::RemoveLink(QString image1,QString image2)
2424 {
2425   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2426     if (image1.toStdString() == mSlicerManagers[i]->GetId()) {
2427       mSlicerManagers[i]->RemoveLink(image2.toStdString());
2428     }
2429     if (image2.toStdString() == mSlicerManagers[i]->GetId()) {
2430       mSlicerManagers[i]->RemoveLink(image1.toStdString());
2431     }
2432   }
2433 }
2434 //------------------------------------------------------------------------------
2435
2436 //------------------------------------------------------------------------------
2437 void vvMainWindow::ChangeImageWithIndexOffset(vvSlicerManager *sm, int slicer, int offset)
2438 {
2439   if(mSlicerManagers.size()==1)
2440     return;
2441
2442   int index = 0;
2443   while(sm != mSlicerManagers[index])
2444     index++;
2445   index = (index+offset+mSlicerManagers.size()) % mSlicerManagers.size();
2446
2447   QTreeWidgetItem* item = GetItemFromSlicerManager(mSlicerManagers[index]);
2448   item->setData(slicer+1,Qt::CheckStateRole,2);         //change checkbox
2449   CurrentImageChanged(mSlicerManagers[index]->GetId()); //select new image
2450   DisplayChanged(item,slicer+1);
2451 }
2452 //------------------------------------------------------------------------------
2453
2454 void vvMainWindow::HorizontalSliderMoved(int value,int column, int slicer_index)
2455 {
2456   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2457     if (DataTree->topLevelItem(i)->data(column,Qt::CheckStateRole).toInt() > 1) {
2458       for (int j = 0; j < 4; j++) {
2459         mSlicerManagers[i]->SetTSliceInSlicer(value,j);
2460         //if (mSlicerManagers[i]->GetSlicer(j)->GetImageActor()->GetVisibility())
2461         //UpdateTSlice(j,value);
2462       }
2463       mSlicerManagers[i]->GetSlicer(slicer_index)->Render();
2464       break;
2465     }
2466   }
2467 }
2468 //------------------------------------------------------------------------------
2469
2470
2471 //------------------------------------------------------------------------------
2472 void vvMainWindow::NOHorizontalSliderMoved()
2473 {
2474   // if (mCurrentTime == NOHorizontalSlider->value()) return;
2475   HorizontalSliderMoved(NOHorizontalSlider->value(),COLUMN_UL_VIEW,0);
2476 //  mCurrentTime = NOHorizontalSlider->value();
2477 }
2478 //------------------------------------------------------------------------------
2479
2480
2481 //------------------------------------------------------------------------------
2482 void vvMainWindow::NEHorizontalSliderMoved()
2483 {
2484   // if (mCurrentTime == NEHorizontalSlider->value()) return;
2485   HorizontalSliderMoved(NEHorizontalSlider->value(),COLUMN_UR_VIEW,1);
2486 //  mCurrentTime = NEHorizontalSlider->value();
2487 }
2488 //------------------------------------------------------------------------------
2489
2490
2491 //------------------------------------------------------------------------------
2492 void vvMainWindow::SOHorizontalSliderMoved()
2493 {
2494   // if (mCurrentTime == SOHorizontalSlider->value()) return;
2495   HorizontalSliderMoved(SOHorizontalSlider->value(),COLUMN_DL_VIEW,2);
2496   // mCurrentTime = SOHorizontalSlider->value();
2497 }
2498 //------------------------------------------------------------------------------
2499
2500
2501 //------------------------------------------------------------------------------
2502 void vvMainWindow::SEHorizontalSliderMoved()
2503 {
2504   // if (mCurrentTime == SEHorizontalSlider->value()) return;
2505   HorizontalSliderMoved(SEHorizontalSlider->value(),COLUMN_DR_VIEW,3);
2506   // mCurrentTime = SEHorizontalSlider->value();
2507 }
2508 //------------------------------------------------------------------------------
2509
2510 //------------------------------------------------------------------------------
2511 void vvMainWindow::NOVerticalSliderChanged()
2512 {
2513   static int value=-1;
2514   if (value == NOVerticalSlider->value()) return;
2515   else value = NOVerticalSlider->value();
2516   //  int value = NOVerticalSlider->value();
2517   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2518     if (DataTree->topLevelItem(i)->data(COLUMN_UL_VIEW,Qt::CheckStateRole).toInt() > 1) {
2519       if (mSlicerManagers[i]->GetSlicer(0)->GetSlice() != value) {
2520         mSlicerManagers[i]->GetSlicer(0)->SetSlice(value);
2521         mSlicerManagers[i]->VerticalSliderHasChanged(0, value);
2522
2523         // If nor Update/Render -> slider not work
2524         // only render = ok navigation, but for contour Update needed but slower ?
2525
2526         mSlicerManagers[i]->UpdateSlice(0);  // <-- DS add this. Not too much update ? YES. but needed for ImageContour ...
2527         //mSlicerManagers[i]->GetSlicer(0)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2528       }
2529       break;
2530     }
2531   }
2532 }
2533 //------------------------------------------------------------------------------
2534
2535
2536 //------------------------------------------------------------------------------
2537 void vvMainWindow::NEVerticalSliderChanged()
2538 {
2539   static int value=-1;
2540   if (value == NEVerticalSlider->value()) return;
2541   else value = NEVerticalSlider->value();
2542   //  int value = NEVerticalSlider->value();
2543   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2544     if (DataTree->topLevelItem(i)->data(COLUMN_UR_VIEW,Qt::CheckStateRole).toInt() > 1) {
2545       if (mSlicerManagers[i]->GetSlicer(1)->GetSlice() != value) {
2546         mSlicerManagers[i]->GetSlicer(1)->SetSlice(value);
2547         mSlicerManagers[i]->VerticalSliderHasChanged(1, value);
2548         mSlicerManagers[i]->UpdateSlice(1);
2549         //mSlicerManagers[i]->GetSlicer(1)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2550       }
2551       break;
2552     }
2553   }
2554 }
2555 //------------------------------------------------------------------------------
2556
2557
2558 //------------------------------------------------------------------------------
2559 void vvMainWindow::SOVerticalSliderChanged()
2560 {
2561   static int value=-1;
2562   if (value == SOVerticalSlider->value()) return;
2563   else value = SOVerticalSlider->value();
2564   //int value = SOVerticalSlider->value();
2565   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2566     if (DataTree->topLevelItem(i)->data(COLUMN_DL_VIEW,Qt::CheckStateRole).toInt() > 1) {
2567       if (mSlicerManagers[i]->GetSlicer(2)->GetSlice() != value) {
2568         mSlicerManagers[i]->GetSlicer(2)->SetSlice(value);
2569         mSlicerManagers[i]->VerticalSliderHasChanged(2, value);
2570         mSlicerManagers[i]->UpdateSlice(2);
2571         //mSlicerManagers[i]->GetSlicer(2)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2572       }
2573       // else { DD("avoid SOVerticalSlider slicer update"); }
2574       break;
2575     }
2576   }
2577 }
2578 //------------------------------------------------------------------------------
2579
2580
2581 //------------------------------------------------------------------------------
2582 void vvMainWindow::SEVerticalSliderChanged()
2583 {
2584   static int value=-1;
2585   if (value == SEVerticalSlider->value()) return;
2586   else value = SEVerticalSlider->value();
2587   // int value = SEVerticalSlider->value();
2588   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2589     if (DataTree->topLevelItem(i)->data(COLUMN_DR_VIEW,Qt::CheckStateRole).toInt() > 1) {
2590       if (mSlicerManagers[i]->GetSlicer(3)->GetSlice() != value) {
2591         mSlicerManagers[i]->GetSlicer(3)->SetSlice(value);
2592         mSlicerManagers[i]->VerticalSliderHasChanged(3, value);
2593         mSlicerManagers[i]->UpdateSlice(3);
2594         //mSlicerManagers[i]->GetSlicer(3)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2595       }
2596       break;
2597     }
2598   }
2599 }
2600 //------------------------------------------------------------------------------
2601
2602
2603 //------------------------------------------------------------------------------
2604 void vvMainWindow::UpdateSlice(int slicer, int slice)
2605 {
2606   // DD("vvMainWindow::UpdateSlice");
2607 //   DD(slicer);
2608 //   DD(slice);
2609   if (slicer == 0) {
2610     //    if (slice != NOVerticalSlider->value())
2611     NOVerticalSlider->setValue(slice);
2612   } else {
2613     if (slicer == 1)
2614       NEVerticalSlider->setValue(slice);
2615     else {
2616       if (slicer == 2)
2617         SOVerticalSlider->setValue(slice);
2618       else {
2619         if (slicer == 3)
2620           SEVerticalSlider->setValue(slice);
2621       }
2622     }
2623   }
2624   // DD("vvMainWindow:UpdateSlice END");
2625 }
2626 //------------------------------------------------------------------------------
2627
2628
2629 //------------------------------------------------------------------------------
2630 void vvMainWindow::UpdateTSlice(int slicer, int slice)
2631 {
2632   switch (slicer) {
2633   case 0:
2634     NOHorizontalSlider->setValue(slice);
2635     break;
2636   case 1:
2637     NEHorizontalSlider->setValue(slice);
2638     break;
2639   case 2:
2640     SOHorizontalSlider->setValue(slice);
2641     break;
2642   case 3:
2643     SEHorizontalSlider->setValue(slice);
2644     break;
2645   }
2646 }
2647 //------------------------------------------------------------------------------
2648
2649
2650 //------------------------------------------------------------------------------
2651 void vvMainWindow::UpdateSliceRange(int slicer, int min, int max, int tmin, int tmax)
2652 {
2653   int position = int((min+max)/2);
2654   if (slicer == 0) {
2655     NOVerticalSlider->setValue(position);
2656     NOVerticalSlider->setRange(min,max);
2657     NOHorizontalSlider->setRange(tmin,tmax);
2658   } else if (slicer == 1) {
2659     NEVerticalSlider->setValue(position);
2660     NEVerticalSlider->setRange(min,max);
2661     NEHorizontalSlider->setRange(tmin,tmax);
2662   } else if (slicer == 2) {
2663     SOVerticalSlider->setValue(position);
2664     SOVerticalSlider->setRange(min,max);
2665     SOHorizontalSlider->setRange(tmin,tmax);
2666   } else if (slicer == 3) {
2667     SEVerticalSlider->setValue(position);
2668     SEVerticalSlider->setRange(min,max);
2669     SEHorizontalSlider->setRange(tmin,tmax);
2670   }
2671 }
2672 //------------------------------------------------------------------------------
2673
2674
2675 //------------------------------------------------------------------------------
2676 void vvMainWindow::SaveNOScreenshot()
2677 {
2678   SaveScreenshot(NOViewWidget);
2679 }
2680 //------------------------------------------------------------------------------
2681
2682
2683 //------------------------------------------------------------------------------
2684 void vvMainWindow::SaveNEScreenshot()
2685 {
2686   SaveScreenshot(NEViewWidget);
2687 }
2688 //------------------------------------------------------------------------------
2689
2690
2691 //------------------------------------------------------------------------------
2692 void vvMainWindow::SaveSOScreenshot()
2693 {
2694   SaveScreenshot(SOViewWidget);
2695 }
2696 //------------------------------------------------------------------------------
2697
2698
2699 //------------------------------------------------------------------------------
2700 void vvMainWindow::SaveSEScreenshot()
2701 {
2702   SaveScreenshot(SEViewWidget);
2703 }
2704 //------------------------------------------------------------------------------
2705
2706
2707 //------------------------------------------------------------------------------
2708 void vvMainWindow::SaveScreenshotAllSlices()
2709 {
2710   QVTKWidget *widget = NOViewWidget;
2711
2712   int index = 0;// GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2713   vvSlicerManager * SM = mSlicerManagers[index];
2714   vvImage * image = SM->GetImage();
2715   vvSlicer * slicer = SM->GetSlicer(0);
2716   int orientation = slicer->GetOrientation();
2717   int nbSlices = image->GetSize()[orientation];
2718   vtkSmartPointer<vtkRenderWindow>  renderWindow = widget->GetRenderWindow();
2719
2720   // Select filename base
2721   QString filename = QFileDialog::getSaveFileName(this,
2722                                                   tr("Save As (filename will be completed by slice number)"),
2723                                                   itksys::SystemTools::GetFilenamePath(mSlicerManagers[index]->GetFileName()).c_str(),
2724                                                   "Images( *.png);;Images( *.jpg)");
2725
2726   // Loop on slices
2727   for(int i=0; i<nbSlices; i++) {
2728     // Change the slice
2729     slicer->SetSlice(i); // -> change the slice of the current slicer
2730     SM->UpdateSlice(0); // --> this one emit UpdateSlice
2731     QCoreApplication::flush(); // -> needed to force display of contours 
2732
2733     // Screenshot  
2734     vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter = vtkSmartPointer<vtkWindowToImageFilter>::New();
2735     windowToImageFilter->SetInput(renderWindow);
2736     windowToImageFilter->SetMagnification(1);
2737     windowToImageFilter->SetInputBufferTypeToRGBA(); //also record the alpha (transparency) channel
2738     windowToImageFilter->Update();
2739     
2740     vtkSmartPointer<vtkPNGWriter> writer = vtkSmartPointer<vtkPNGWriter>::New();
2741     std::string fn = itksys::SystemTools::GetFilenameWithoutLastExtension(filename.toStdString());
2742     std::string num = clitk::toString(i);
2743     if (i<10) num = "0"+num;
2744     if (i<100) num = "0"+num;
2745     if (i<1000) num = "0"+num;
2746
2747     fn = itksys::SystemTools::GetFilenamePath(filename.toStdString()) + "/"+ fn 
2748       + "_" + num + itksys::SystemTools::GetFilenameLastExtension(filename.toStdString());
2749     writer->SetFileName(fn.c_str());
2750     writer->SetInput(windowToImageFilter->GetOutput());
2751     writer->Write();
2752   }
2753 }
2754 //------------------------------------------------------------------------------
2755
2756
2757 //------------------------------------------------------------------------------
2758 void vvMainWindow::SaveScreenshot(QVTKWidget *widget)
2759 {
2760   QString Extensions = "Images( *.png);;";
2761   Extensions += "Images( *.jpg);;";
2762   Extensions += "Images( *.bmp);;";
2763   Extensions += "Images( *.tif);;";
2764   Extensions += "Images( *.ppm)";
2765 #if defined(VTK_USE_FFMPEG_ENCODER) || defined(VTK_USE_VIDEO_FOR_WINDOWS)
2766   Extensions += ";;Video( *.avi)";
2767 #endif
2768 #ifdef VTK_USE_MPEG2_ENCODER
2769   Extensions += ";;Video( *.mpg)";
2770 #endif
2771 #ifdef CLITK_EXPERIMENTAL
2772   Extensions += ";;Video( *.gif)";
2773 #endif
2774
2775   int smIndex=GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2776   QString fileName = QFileDialog::getSaveFileName(this,
2777                      tr("Save As"),
2778                      itksys::SystemTools::GetFilenamePath(mSlicerManagers[smIndex]->GetFileName()).c_str(),
2779                      Extensions);
2780
2781   if (!fileName.isEmpty()) {
2782     vtkSmartPointer<vtkWindowToImageFilter> w2i = vtkSmartPointer<vtkWindowToImageFilter>::New();
2783     w2i->SetInput(widget->GetRenderWindow());
2784     w2i->Update();
2785     vtkImageData *image = w2i->GetOutput();
2786
2787     std::string ext(itksys::SystemTools::GetFilenameLastExtension(fileName.toStdString()));
2788
2789     // Image
2790     vtkImageWriter *imgwriter = NULL;
2791     if (ext==".bmp")
2792       imgwriter = vtkBMPWriter::New();
2793     else if (ext==".tif")
2794       imgwriter = vtkTIFFWriter::New();
2795     else if (ext==".ppm")
2796       imgwriter = vtkPNMWriter::New();
2797     else if (ext==".png")
2798       imgwriter = vtkPNGWriter::New();
2799     else if (ext==".jpg")
2800       imgwriter = vtkJPEGWriter::New();
2801
2802     // Snapshot image if not null
2803     if(imgwriter!=NULL) {
2804       imgwriter->SetInput(image);
2805       imgwriter->SetFileName(fileName.toStdString().c_str());
2806       imgwriter->Write();
2807       return;
2808     }
2809
2810     // Video
2811     vtkGenericMovieWriter *vidwriter = NULL;
2812 #if CLITK_EXPERIMENTAL == 1
2813     if (ext==".gif") {
2814       vvAnimatedGIFWriter *gif = vvAnimatedGIFWriter::New();
2815       vidwriter = gif;
2816
2817       // FPS
2818       bool ok;
2819       int fps = QInputDialog::getInteger(this, tr("Number of frames per second"),
2820                                      tr("FPS:"), 5, 0, 1000, 1, &ok);
2821       if(ok)
2822         gif->SetRate(fps);
2823
2824       // Loops
2825       int loops = QInputDialog::getInteger(this, tr("Loops"),
2826                                      tr("Number of loops (0 means infinite):"), 0, 0, 1000000000, 1, &ok);
2827       if(ok)
2828         gif->SetLoops(loops);
2829
2830       // Dithering
2831       QString msg = "Would you like to activate dithering?";
2832       QMessageBox msgBox(QMessageBox::Question, tr("Dithering"),msg, 0, this);
2833       msgBox.addButton(tr("Yes"), QMessageBox::AcceptRole);
2834       msgBox.addButton(tr("No"), QMessageBox::RejectRole);
2835       gif->SetDither(msgBox.exec() == QMessageBox::AcceptRole);
2836     }
2837 #endif
2838 #ifdef VTK_USE_VIDEO_FOR_WINDOWS
2839     if (ext==".avi") {
2840       vtkAVIWriter *mpg = vtkAVIWriter::New();
2841       vidwriter = mpg;
2842       mpg->SetQuality(2);
2843       bool ok;
2844       int fps = QInputDialog::getInteger(this, tr("Number of frames per second"),
2845                                      tr("FPS:"), 5, 0, 1024, 1, &ok);
2846       if(!ok)
2847         fps = 5;
2848       mpg->SetRate(fps);
2849     }
2850 #endif
2851 #ifdef VTK_USE_FFMPEG_ENCODER
2852     if (ext==".avi") {
2853       vtkFFMPEGWriter *mpg = vtkFFMPEGWriter::New();
2854       vidwriter = mpg;
2855       mpg->SetQuality(2);
2856       bool ok;
2857       int fps = QInputDialog::getInteger(this, tr("Number of frames per second"),
2858                                      tr("FPS:"), 5, 0, 1024, 1, &ok);
2859       if(!ok)
2860         fps = 5;
2861       mpg->SetRate(fps);
2862       mpg->SetBitRateTolerance(int(ceil(12.0*1024*1024/fps)));
2863     }
2864 #endif
2865 #ifdef VTK_USE_MPEG2_ENCODER
2866     if (ext==".mpg") {
2867       vtkMPEG2Writer *mpg = vtkMPEG2Writer::New();
2868       vidwriter = mpg;
2869     }
2870 #endif
2871
2872     // Take video if not null
2873     if(vidwriter!=NULL){
2874       vidwriter->SetInput(image);
2875       vidwriter->SetFileName(fileName.toStdString().c_str());
2876       vidwriter->Start();
2877       vvImage * vvImg = mSlicerManagers[smIndex]->GetImage();
2878       int nSlice = vvImg->GetVTKImages().size();
2879       for(int i=0; i<nSlice; i++) {
2880         mSlicerManagers[smIndex]->SetNextTSlice(0);
2881         vtkSmartPointer<vtkWindowToImageFilter> w2i = vtkSmartPointer<vtkWindowToImageFilter>::New();
2882         w2i->SetInput(widget->GetRenderWindow());
2883         w2i->Update();
2884         vidwriter->SetInput(w2i->GetOutput());
2885         vidwriter->Write();
2886       }
2887       vidwriter->End();
2888       vidwriter->Delete();
2889       return;
2890     }
2891
2892     QMessageBox::information(this,tr("Problem saving screenshot !"),tr("Cannot save image.\nPlease set a file extension !!!"));
2893   }
2894 }
2895 //------------------------------------------------------------------------------
2896
2897
2898 //------------------------------------------------------------------------------
2899 void vvMainWindow::GoToCursor()
2900 {
2901   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2902   for (int column = 1; column < 5; column++) {
2903     if (DataTree->selectedItems()[0]->data(column,Qt::CheckStateRole).toInt() > 1) {
2904       double* cursorPos = mSlicerManagers[index]->GetSlicer(column-1)->GetCursorPosition();
2905       mSlicerManagers[index]->GetSlicer(column-1)->SetCurrentPosition(
2906         cursorPos[0],cursorPos[1],cursorPos[2],cursorPos[3]);
2907       mSlicerManagers[index]->UpdateViews(1,column-1);
2908       mSlicerManagers[index]->UpdateLinked(column-1);
2909       break;
2910     }
2911   }
2912 }
2913 //------------------------------------------------------------------------------
2914
2915 //------------------------------------------------------------------------------
2916 void vvMainWindow::PlayPause()
2917 {
2918   if (playMode) {
2919     playMode = 0;
2920     playButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/player_play.png")));
2921     ImageInfoChanged();
2922     return;
2923   } else {
2924     int image_number=DataTree->topLevelItemCount();
2925     bool has_temporal;
2926     for (int i=0; i<image_number; i++)
2927       if (mSlicerManagers[i]->GetImage()->GetVTKImages().size() > 1) {
2928         has_temporal=true;
2929         break;
2930       }
2931     if (has_temporal) {
2932       playMode = 1;
2933       playButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/player_pause.png")));
2934       QTimer::singleShot(1000/mFrameRate, this, SLOT(PlayNext()));
2935     }
2936   }
2937 }
2938 //------------------------------------------------------------------------------
2939
2940 //------------------------------------------------------------------------------
2941 void vvMainWindow::PlayNext()
2942 {
2943   if (playMode && !this->isHidden()) {
2944     int image_number=DataTree->topLevelItemCount();
2945     ///Only play one slicer per SM, and only if the SM is being displayed
2946     for (int i=0; i<image_number; i++)
2947       for (int j=0; j<4; j++)
2948         if (mSlicerManagers[i]->GetImage()->GetVTKImages().size() > 1 &&
2949             DataTree->topLevelItem(i)->data(j+1,Qt::CheckStateRole).toInt() > 0) {
2950           mSlicerManagers[i]->SetNextTSlice(j);
2951           break;
2952         }
2953     QTimer::singleShot(1000/mFrameRate, this, SLOT(PlayNext()));
2954   }
2955 }
2956 //------------------------------------------------------------------------------
2957
2958 void vvMainWindow::ShowLastImage()
2959 {
2960   if (mSlicerManagers.size() > 1) {
2961     QTreeWidgetItem * item=DataTree->topLevelItem(DataTree->topLevelItemCount()-1);
2962     CurrentImageChanged(mSlicerManagers.back()->GetId()); //select new image
2963     item->setData(1,Qt::CheckStateRole,2); //show the new image in the first panel
2964     DisplayChanged(item,1);
2965   }
2966 }
2967
2968 //------------------------------------------------------------------------------
2969 void vvMainWindow::UpdateRenderWindows()
2970 {
2971   if (NOViewWidget->GetRenderWindow()) NOViewWidget->GetRenderWindow()->Render();
2972   if (NEViewWidget->GetRenderWindow()) NEViewWidget->GetRenderWindow()->Render();
2973   if (SOViewWidget->GetRenderWindow()) SOViewWidget->GetRenderWindow()->Render();
2974   if (SEViewWidget->GetRenderWindow()) SEViewWidget->GetRenderWindow()->Render();
2975 }
2976 //------------------------------------------------------------------------------
2977
2978 //------------------------------------------------------------------------------
2979 void vvMainWindow::SegmentationOnCurrentImage()
2980 {
2981   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2982
2983   vvSegmentationDialog segmentation;
2984   segmentation.SetImage(mSlicerManagers[index]->GetSlicer(0)->GetImage());
2985   segmentation.exec();
2986 }
2987 //------------------------------------------------------------------------------
2988
2989 void vvMainWindow::SurfaceViewerLaunch()
2990 {
2991   vvSurfaceViewerDialog surfaceViewer;
2992   surfaceViewer.exec();
2993 }
2994 //------------------------------------------------------------------------------
2995
2996
2997 //------------------------------------------------------------------------------
2998 int vvMainWindow::GetImageDuplicateFilenameNumber(std::string filename)
2999 {
3000   int number=0;
3001   for(unsigned int l=0; l<mSlicerManagers.size(); l++) {
3002     vvSlicerManager * v = mSlicerManagers[l];
3003     if (v->GetBaseFileName() ==
3004         vtksys::SystemTools::GetFilenameName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename))) {
3005       number = std::max(number, v->GetBaseFileNameNumber()+1);
3006     }
3007   }
3008   return number;
3009 }
3010 //------------------------------------------------------------------------------
3011
3012
3013 //------------------------------------------------------------------------------
3014 vvSlicerManager* vvMainWindow::AddImage(vvImage::Pointer image,std::string filename)
3015 {
3016   // Change filename if another image exist with the same name
3017   int number = GetImageDuplicateFilenameNumber(filename);
3018
3019   // Create new SliceManager
3020   vvSlicerManager* slicer_manager = new vvSlicerManager(4);
3021   slicer_manager->SetImage(image);//, IMAGE, number);
3022   //  filename = filename+"_"+clitk::toString(number);
3023   slicer_manager->SetFilename(filename, number);
3024   mSlicerManagers.push_back(slicer_manager);
3025
3026   //create an item in the tree with good settings
3027   QTreeWidgetItem *item = new QTreeWidgetItem();
3028   item->setData(0,Qt::UserRole,slicer_manager->GetFileName().c_str());//files[i].c_str());
3029   item->setData(1,Qt::UserRole,tr("image"));
3030   item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,slicer_manager->GetFileName().c_str());//filename.c_str());
3031   qApp->processEvents();
3032
3033   for (int j = 1; j <= 4; j++) item->setData(j,Qt::CheckStateRole,1);
3034
3035   //Create the buttons for reload and close
3036   qApp->processEvents();
3037   QTreePushButton* cButton = new QTreePushButton;
3038   cButton->setItem(item);
3039   cButton->setColumn(COLUMN_CLOSE_IMAGE);
3040   cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
3041   connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
3042           this,SLOT(CloseImage(QTreeWidgetItem*, int)));
3043
3044   QTreePushButton* rButton = new QTreePushButton;
3045   rButton->setItem(item);
3046   rButton->setColumn(COLUMN_RELOAD_IMAGE);
3047   rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
3048   rButton->setEnabled(0);
3049   connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
3050           this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
3051
3052   DataTree->addTopLevelItem(item);
3053   DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
3054   DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
3055
3056   //set the id of the image
3057   QString id = slicer_manager->GetFileName().c_str() + QString::number(mSlicerManagers.size()-1);
3058   item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
3059   mSlicerManagers.back()->SetId(id.toStdString());
3060
3061   linkPanel->addImage(slicer_manager->GetFileName().c_str()// filename
3062                       , id.toStdString());
3063
3064   connect(mSlicerManagers.back(), SIGNAL(currentImageChanged(std::string)),
3065           this, SLOT(CurrentImageChanged(std::string)));
3066   connect(mSlicerManagers.back(), SIGNAL(currentPickedImageChanged(std::string)),
3067           this, SLOT(CurrentPickedImageChanged(std::string)));
3068   connect(mSlicerManagers.back(), SIGNAL(UpdatePosition(int, double, double, double, double, double, double, double)),
3069           this, SLOT(MousePositionChanged(int,double, double, double, double, double, double, double)));
3070   connect(mSlicerManagers.back(), SIGNAL(UpdateVector(int, double, double, double, double)),
3071           this, SLOT(VectorChanged(int,double,double,double, double)));
3072   connect(mSlicerManagers.back(), SIGNAL(UpdateOverlay(int, double, double)),
3073           this, SLOT(OverlayChanged(int,double,double)));
3074   connect(mSlicerManagers.back(), SIGNAL(UpdateFusion(int, double)),
3075           this, SLOT(FusionChanged(int,double)));
3076   connect(mSlicerManagers.back(), SIGNAL(WindowLevelChanged()),
3077           this,SLOT(WindowLevelChanged()));
3078   connect(mSlicerManagers.back(), SIGNAL(UpdateSlice(int,int)),
3079           this,SLOT(UpdateSlice(int,int)));
3080   connect(mSlicerManagers.back(), SIGNAL(UpdateTSlice(int, int)),
3081           this,SLOT(UpdateTSlice(int, int)));
3082   connect(mSlicerManagers.back(), SIGNAL(UpdateSliceRange(int,int,int,int,int)),
3083           this,SLOT(UpdateSliceRange(int,int,int,int,int)));
3084   connect(mSlicerManagers.back(), SIGNAL(UpdateLinkManager(std::string,int,double,double,double,int)),
3085           this,SLOT(UpdateLinkManager(std::string,int,double,double,double,int)));
3086   connect(mSlicerManagers.back(), SIGNAL(UpdateLinkedNavigation(std::string,vvSlicerManager*,vvSlicer*)),
3087           this,SLOT(UpdateLinkedNavigation(std::string,vvSlicerManager*,vvSlicer*)));
3088   connect(mSlicerManagers.back(), SIGNAL(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)),
3089           this,SLOT(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)));
3090   connect(mSlicerManagers.back(), SIGNAL(LandmarkAdded()),landmarksPanel,SLOT(AddPoint()));
3091   UpdateTree();
3092   qApp->processEvents();
3093   InitSlicers();
3094   ShowLastImage();
3095   InitDisplay();
3096   qApp->processEvents();
3097
3098   // End
3099   ImageInfoChanged();
3100   return slicer_manager;
3101 }
3102 //------------------------------------------------------------------------------
3103
3104
3105 //------------------------------------------------------------------------------
3106 void vvMainWindow::UpdateCurrentSlicer()
3107 {
3108   int index = -1;
3109   if (DataTree->selectedItems().size() > 0) {
3110     index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
3111   }
3112   mSlicerManagerCurrentIndex = index;
3113 }
3114 //------------------------------------------------------------------------------
3115