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