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