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