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