]> Creatis software - clitk.git/blob - vv/vvMainWindow.cxx
remove argsinfo template
[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)"
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(AddFusionImage()));
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::AddFusionImage()
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     mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str();
1924     itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO(
1925                                          file.toStdString().c_str(), itk::ImageIOFactory::ReadMode);
1926     reader->SetFileName(file.toStdString().c_str());
1927     reader->ReadImageInformation();
1928     std::string component = reader->GetComponentTypeAsString(reader->GetComponentType());
1929     if (reader) {
1930       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1931       vvProgressDialog progress("Opening fusion");
1932       qApp->processEvents();
1933
1934       std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str();
1935       if (mSlicerManagers[index]->SetFusion(file.toStdString(),
1936                                             reader->GetNumberOfDimensions(), component)) {
1937         //create an item in the tree with good settings
1938         QTreeWidgetItem *item = new QTreeWidgetItem();
1939         item->setData(0,Qt::UserRole,file.toStdString().c_str());
1940         item->setData(1,Qt::UserRole,tr("fusion"));
1941         item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,filename.c_str());
1942         qApp->processEvents();
1943
1944         for (int j = 1; j <= 4; j++) {
1945           item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole));
1946           mSlicerManagers[index]->GetSlicer(j-1)->SetActorVisibility("fusion",0,
1947               DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole).toInt());
1948         }
1949
1950         //Create the buttons for reload and close
1951         qApp->processEvents();
1952         QTreePushButton* cButton = new QTreePushButton;
1953         cButton->setItem(item);
1954         cButton->setColumn(COLUMN_CLOSE_IMAGE);
1955         cButton->setToolTip(tr("close image"));
1956         cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
1957         connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
1958                 this,SLOT(CloseImage(QTreeWidgetItem*, int)));
1959
1960         QTreePushButton* rButton = new QTreePushButton;
1961         rButton->setItem(item);
1962         rButton->setColumn(COLUMN_RELOAD_IMAGE);
1963         rButton->setToolTip(tr("reload image"));
1964         rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
1965         connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
1966                 this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
1967
1968         DataTree->topLevelItem(index)->setExpanded(1);
1969         DataTree->topLevelItem(index)->addChild(item);
1970         DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
1971         DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
1972
1973         //set the id of the image
1974         QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString();
1975         item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
1976         UpdateTree();
1977         qApp->processEvents();
1978         ImageInfoChanged();
1979         QApplication::restoreOverrideCursor();
1980       } else {
1981         QApplication::restoreOverrideCursor();
1982         QString error = "Cannot import the new image.\n";
1983         error += mSlicerManagers[index]->GetLastError().c_str();
1984         QMessageBox::information(this,tr("Problem reading image !"),error);
1985       }
1986     } else {
1987       QString error = "Cannot import the new image.\n";
1988       QMessageBox::information(this,tr("Problem reading image !"),error);
1989     }
1990   }
1991 }
1992 //------------------------------------------------------------------------------
1993
1994
1995 //------------------------------------------------------------------------------
1996 void vvMainWindow::OpenField()
1997 {
1998   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
1999   //check if a vector field has already been added
2000   for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++)
2001     if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "vector") {
2002       QString error = "Cannot add more than one vector field\n";
2003       error += "Please remove first ";
2004       error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString();
2005       QMessageBox::information(this,tr("Problem adding vector field!"),error);
2006       return;
2007     }
2008
2009   QString Extensions = "Images ( *.mhd)";
2010   Extensions += ";;Images ( *.vf)";
2011   QString file = QFileDialog::getOpenFileName(this,tr("Load deformation field"),mInputPathName,Extensions);
2012   if (!file.isEmpty())
2013     AddField(file,index);
2014 }
2015 //------------------------------------------------------------------------------
2016
2017
2018 //------------------------------------------------------------------------------
2019 void vvMainWindow::AddFieldEntry(QString filename,int index,bool from_disk)
2020 {
2021   //create an item in the tree with good settings
2022   QTreeWidgetItem *item = new QTreeWidgetItem();
2023   item->setData(0,Qt::UserRole,filename.toStdString().c_str());
2024   item->setData(1,Qt::UserRole,tr("vector"));
2025   item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,filename);
2026   qApp->processEvents();
2027
2028   for (int j = 1; j <= 4; j++) {
2029     item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole));
2030     mSlicerManagers[index]->GetSlicer(j-1)->SetActorVisibility("vector",0,
2031         DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole).toInt());
2032   }
2033
2034   //Create the buttons for reload and close
2035   qApp->processEvents();
2036   QTreePushButton* cButton = new QTreePushButton;
2037   cButton->setItem(item);
2038   cButton->setColumn(COLUMN_CLOSE_IMAGE);
2039   cButton->setToolTip(tr("close vector field"));
2040   cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
2041   connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2042           this,SLOT(CloseImage(QTreeWidgetItem*, int)));
2043
2044   QTreePushButton* rButton = new QTreePushButton;
2045   rButton->setItem(item);
2046   rButton->setColumn(COLUMN_RELOAD_IMAGE);
2047   rButton->setToolTip(tr("reload vector field"));
2048   rButton->setEnabled(from_disk);
2049   rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
2050   connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2051           this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
2052
2053   DataTree->topLevelItem(index)->setExpanded(1);
2054   DataTree->topLevelItem(index)->addChild(item);
2055   DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
2056   DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
2057
2058   //set the id of the image
2059   QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString();
2060   item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
2061   UpdateTree();
2062   qApp->processEvents();
2063   ImageInfoChanged();
2064   QApplication::restoreOverrideCursor();
2065 }
2066 //------------------------------------------------------------------------------
2067
2068
2069 //------------------------------------------------------------------------------
2070 void vvMainWindow::AddField(vvImage::Pointer vf,QString file,int index)
2071 {
2072   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
2073   vvSlicerManager* imageManager = mSlicerManagers[index];
2074   if (imageManager->SetVF(vf,file.toStdString())) {
2075     AddFieldEntry(file,index,false);
2076   } else {
2077     QString error = "Cannot import the vector field for this image.\n";
2078     error += imageManager->GetLastError().c_str();
2079     QMessageBox::information(this,tr("Problem reading VF !"),error);
2080   }
2081   QApplication::restoreOverrideCursor();
2082 }
2083 //------------------------------------------------------------------------------
2084
2085
2086 //------------------------------------------------------------------------------
2087 void vvMainWindow::AddField(QString file,int index)
2088 {
2089   if (QFile::exists(file)) {
2090     mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str();
2091
2092     //init the progress events
2093     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
2094     vvProgressDialog progress("Opening " + file.toStdString());
2095     qApp->processEvents();
2096
2097     //read the vector and put it in the current mSlicerManager
2098     vvSlicerManager* imageManager = mSlicerManagers[index];
2099     qApp->processEvents();
2100
2101     std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str();
2102     if (imageManager->SetVF(file.toStdString())) {
2103       imageManager->Render();
2104       AddFieldEntry(file,index,true);
2105     } else {
2106       QApplication::restoreOverrideCursor();
2107       QString error = "Cannot import the vector field for this image.\n";
2108       error += imageManager->GetLastError().c_str();
2109       QMessageBox::information(this,tr("Problem reading VF !"),error);
2110     }
2111   } else
2112     QMessageBox::information(this,tr("Problem reading VF !"),"File doesn't exist!");
2113
2114 }
2115 //------------------------------------------------------------------------------
2116
2117
2118 //------------------------------------------------------------------------------
2119 void vvMainWindow::SetVFProperty(int subsampling, int scale, int log, int width)
2120 {
2121   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2122   if (mSlicerManagers[index]->GetSlicer(0)->GetVF()) {
2123     for (int i = 0; i < 4; i++) {
2124       mSlicerManagers[index]->GetSlicer(i)->SetVFSubSampling(subsampling);
2125       mSlicerManagers[index]->GetSlicer(i)->SetVFScale(scale);
2126       mSlicerManagers[index]->GetSlicer(i)->SetVFWidth(width);
2127       if (log > 0)
2128         mSlicerManagers[index]->GetSlicer(i)->SetVFLog(1);
2129       else
2130         mSlicerManagers[index]->GetSlicer(i)->SetVFLog(0);
2131     }
2132   }
2133 }
2134 //------------------------------------------------------------------------------
2135
2136
2137 //------------------------------------------------------------------------------
2138 void vvMainWindow::SetOverlayProperty(int color)
2139 {
2140   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2141   if (mSlicerManagers[index]->GetSlicer(0)->GetOverlay()) {
2142     mSlicerManagers[index]->SetOverlayColor(color);
2143     mSlicerManagers[index]->SetColorMap(0);
2144     mSlicerManagers[index]->Render();
2145   }
2146 }
2147 //------------------------------------------------------------------------------
2148
2149 //------------------------------------------------------------------------------
2150 void vvMainWindow::SetFusionProperty(int opacity, int colormap,double window, double level)
2151 {
2152   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2153   if (mSlicerManagers[index]->GetSlicer(0)->GetFusion()) {
2154     mSlicerManagers[index]->SetFusionOpacity(opacity);
2155     mSlicerManagers[index]->SetFusionColorMap(colormap);
2156     mSlicerManagers[index]->SetFusionWindow(window);
2157     mSlicerManagers[index]->SetFusionLevel(level);
2158     mSlicerManagers[index]->SetColorMap(0);
2159     mSlicerManagers[index]->Render();
2160   }
2161 }
2162 //------------------------------------------------------------------------------
2163
2164 //------------------------------------------------------------------------------
2165 void vvMainWindow::SaveAs()
2166 {
2167   if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "vector") {
2168     QMessageBox::warning(this,tr("Unsupported type"),tr("Sorry, saving a vector field is unsupported for the moment"));
2169     return;
2170   }
2171
2172   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2173   int dimension = mSlicerManagers[index]->GetDimension();
2174   QStringList OutputListeFormat;
2175   OutputListeFormat.clear();
2176   if (dimension == 1) {
2177     OutputListeFormat.push_back(".mhd");
2178   }
2179   if (dimension == 2) {
2180     OutputListeFormat.push_back(".bmp");
2181     OutputListeFormat.push_back(".png");
2182     OutputListeFormat.push_back(".jpeg");
2183     OutputListeFormat.push_back(".tif");
2184     OutputListeFormat.push_back(".mhd");
2185     OutputListeFormat.push_back(".hdr");
2186     OutputListeFormat.push_back(".vox");
2187   } else if (dimension == 3) {
2188     OutputListeFormat.push_back(".mhd");
2189     OutputListeFormat.push_back(".hdr");
2190     OutputListeFormat.push_back(".vox");
2191   } else if (dimension == 4) {
2192     OutputListeFormat.push_back(".mhd");
2193   }
2194   QString Extensions = "AllFiles(*.*)";
2195   for (int i = 0; i < OutputListeFormat.count(); i++) {
2196     Extensions += ";;Images ( *";
2197     Extensions += OutputListeFormat[i];
2198     Extensions += ")";
2199   }
2200   QString fileName = QFileDialog::getSaveFileName(this,
2201                      tr("Save As"),
2202                      mSlicerManagers[index]->GetFileName().c_str(),
2203                      Extensions);
2204   if (!fileName.isEmpty()) {
2205     std::string fileformat = itksys::SystemTools::GetFilenameLastExtension(fileName.toStdString());
2206     if (OutputListeFormat.contains(
2207           fileformat.c_str())) {
2208       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
2209       std::string action = "Saving";
2210       vvProgressDialog progress("Saving "+fileName.toStdString());
2211       qApp->processEvents();
2212       vvImageWriter *writer = new vvImageWriter;
2213       writer->SetOutputFileName(fileName.toStdString());
2214       writer->SetInput(mSlicerManagers[index]->GetImage());
2215       writer->Update();
2216       QApplication::restoreOverrideCursor();
2217       if (writer->GetLastError().size()) {
2218         QString error = "Saving did not succeed\n";
2219         error += writer->GetLastError().c_str();
2220         QMessageBox::information(this,tr("Saving Problem"),error);
2221         SaveAs();
2222       }
2223     } else {
2224       QString error = fileformat.c_str();
2225       if (error.isEmpty())
2226         error += "no file format specified !";
2227       else
2228         error += " format unknown !!!\n";
2229       QMessageBox::information(this,tr("Saving Problem"),error);
2230       SaveAs();
2231     }
2232   }
2233 }
2234 //------------------------------------------------------------------------------
2235
2236
2237 //------------------------------------------------------------------------------
2238 void vvMainWindow::AddLink(QString image1,QString image2)
2239 {
2240   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2241     if (image1.toStdString() == mSlicerManagers[i]->GetId()) {
2242       mSlicerManagers[i]->AddLink(image2.toStdString());
2243     }
2244     if (image2.toStdString() == mSlicerManagers[i]->GetId()) {
2245       mSlicerManagers[i]->AddLink(image1.toStdString());
2246     }
2247   }
2248 }
2249 //------------------------------------------------------------------------------
2250
2251
2252 //------------------------------------------------------------------------------
2253 void vvMainWindow::RemoveLink(QString image1,QString image2)
2254 {
2255   // DD("vvMainWindow:RemoveLink");
2256   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2257     if (image1.toStdString() == mSlicerManagers[i]->GetId()) {
2258       mSlicerManagers[i]->RemoveLink(image2.toStdString());
2259     }
2260     if (image2.toStdString() == mSlicerManagers[i]->GetId()) {
2261       mSlicerManagers[i]->RemoveLink(image1.toStdString());
2262     }
2263   }
2264 }
2265 //------------------------------------------------------------------------------
2266
2267 //------------------------------------------------------------------------------
2268 void vvMainWindow::ChangeImageWithIndexOffset(vvSlicerManager *sm, int slicer, int offset)
2269 {
2270   int index = 0;
2271   while(sm != mSlicerManagers[index])
2272     index++;
2273   index = (index+offset) % mSlicerManagers.size();
2274
2275   QTreeWidgetItem* item = GetItemFromSlicerManager(mSlicerManagers[index]);
2276   //CurrentImageChanged(mSlicerManagers[index]->GetId()); //select new image
2277   item->setData(slicer+1,Qt::CheckStateRole,2);         //change checkbox
2278   DisplayChanged(item,slicer+1);
2279 }
2280 //------------------------------------------------------------------------------
2281
2282 void vvMainWindow::HorizontalSliderMoved(int value,int column, int slicer_index)
2283 {
2284   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2285     if (DataTree->topLevelItem(i)->data(column,Qt::CheckStateRole).toInt() > 1) {
2286       for (int j = 0; j < 4; j++) {
2287         mSlicerManagers[i]->SetTSliceInSlicer(value,j);
2288         //if (mSlicerManagers[i]->GetSlicer(j)->GetImageActor()->GetVisibility())
2289         //UpdateTSlice(j,value);
2290       }
2291       mSlicerManagers[i]->GetSlicer(slicer_index)->Render();
2292       break;
2293     }
2294   }
2295 }
2296 //------------------------------------------------------------------------------
2297
2298
2299 //------------------------------------------------------------------------------
2300 void vvMainWindow::NOHorizontalSliderMoved()
2301 {
2302   // if (mCurrentTime == NOHorizontalSlider->value()) return;
2303   HorizontalSliderMoved(NOHorizontalSlider->value(),COLUMN_UL_VIEW,0);
2304 //  mCurrentTime = NOHorizontalSlider->value();
2305 }
2306 //------------------------------------------------------------------------------
2307
2308
2309 //------------------------------------------------------------------------------
2310 void vvMainWindow::NEHorizontalSliderMoved()
2311 {
2312   // if (mCurrentTime == NEHorizontalSlider->value()) return;
2313   HorizontalSliderMoved(NEHorizontalSlider->value(),COLUMN_UR_VIEW,1);
2314 //  mCurrentTime = NEHorizontalSlider->value();
2315 }
2316 //------------------------------------------------------------------------------
2317
2318
2319 //------------------------------------------------------------------------------
2320 void vvMainWindow::SOHorizontalSliderMoved()
2321 {
2322   // if (mCurrentTime == SOHorizontalSlider->value()) return;
2323   HorizontalSliderMoved(SOHorizontalSlider->value(),COLUMN_DL_VIEW,2);
2324   // mCurrentTime = SOHorizontalSlider->value();
2325 }
2326 //------------------------------------------------------------------------------
2327
2328
2329 //------------------------------------------------------------------------------
2330 void vvMainWindow::SEHorizontalSliderMoved()
2331 {
2332   // if (mCurrentTime == SEHorizontalSlider->value()) return;
2333   HorizontalSliderMoved(SEHorizontalSlider->value(),COLUMN_DR_VIEW,3);
2334   // mCurrentTime = SEHorizontalSlider->value();
2335 }
2336 //------------------------------------------------------------------------------
2337
2338 //------------------------------------------------------------------------------
2339 void vvMainWindow::NOVerticalSliderChanged()
2340 {
2341   static int value=-1;
2342   if (value == NOVerticalSlider->value()) return;
2343   else value = NOVerticalSlider->value();
2344   //  int value = NOVerticalSlider->value();
2345   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2346     if (DataTree->topLevelItem(i)->data(COLUMN_UL_VIEW,Qt::CheckStateRole).toInt() > 1) {
2347       if (mSlicerManagers[i]->GetSlicer(0)->GetSlice() != value) {
2348         mSlicerManagers[i]->GetSlicer(0)->SetSlice(value);
2349         mSlicerManagers[i]->VerticalSliderHasChanged(0, value);
2350
2351         // If nor Update/Render -> slider not work
2352         // only render = ok navigation, but for contour Update needed but slower ?
2353
2354         mSlicerManagers[i]->UpdateSlice(0);  // <-- DS add this. Not too much update ? YES. but needed for ImageContour ...
2355         //mSlicerManagers[i]->GetSlicer(0)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2356       }
2357       break;
2358     }
2359   }
2360 }
2361 //------------------------------------------------------------------------------
2362
2363
2364 //------------------------------------------------------------------------------
2365 void vvMainWindow::NEVerticalSliderChanged()
2366 {
2367   static int value=-1;
2368   if (value == NEVerticalSlider->value()) return;
2369   else value = NEVerticalSlider->value();
2370   //  int value = NEVerticalSlider->value();
2371   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2372     if (DataTree->topLevelItem(i)->data(COLUMN_UR_VIEW,Qt::CheckStateRole).toInt() > 1) {
2373       if (mSlicerManagers[i]->GetSlicer(1)->GetSlice() != value) {
2374         mSlicerManagers[i]->GetSlicer(1)->SetSlice(value);
2375         mSlicerManagers[i]->VerticalSliderHasChanged(1, value);
2376         mSlicerManagers[i]->UpdateSlice(1);
2377         //mSlicerManagers[i]->GetSlicer(1)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2378       }
2379       break;
2380     }
2381   }
2382 }
2383 //------------------------------------------------------------------------------
2384
2385
2386 //------------------------------------------------------------------------------
2387 void vvMainWindow::SOVerticalSliderChanged()
2388 {
2389   static int value=-1;
2390   // DD(value);
2391 //   DD(SOVerticalSlider->value());
2392   if (value == SOVerticalSlider->value()) return;
2393   else value = SOVerticalSlider->value();
2394   //int value = SOVerticalSlider->value();
2395   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2396     if (DataTree->topLevelItem(i)->data(COLUMN_DL_VIEW,Qt::CheckStateRole).toInt() > 1) {
2397       if (mSlicerManagers[i]->GetSlicer(2)->GetSlice() != value) {
2398         mSlicerManagers[i]->GetSlicer(2)->SetSlice(value);
2399         mSlicerManagers[i]->VerticalSliderHasChanged(2, value);
2400         mSlicerManagers[i]->UpdateSlice(2);
2401         //mSlicerManagers[i]->GetSlicer(2)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2402       }
2403       // else { DD("avoid SOVerticalSlider slicer update"); }
2404       break;
2405     }
2406   }
2407 }
2408 //------------------------------------------------------------------------------
2409
2410
2411 //------------------------------------------------------------------------------
2412 void vvMainWindow::SEVerticalSliderChanged()
2413 {
2414   static int value=-1;
2415   if (value == SEVerticalSlider->value()) return;
2416   else value = SEVerticalSlider->value();
2417   // int value = SEVerticalSlider->value();
2418   for (unsigned int i = 0; i < mSlicerManagers.size(); i++) {
2419     if (DataTree->topLevelItem(i)->data(COLUMN_DR_VIEW,Qt::CheckStateRole).toInt() > 1) {
2420       if (mSlicerManagers[i]->GetSlicer(3)->GetSlice() != value) {
2421         mSlicerManagers[i]->GetSlicer(3)->SetSlice(value);
2422         mSlicerManagers[i]->VerticalSliderHasChanged(3, value);
2423         mSlicerManagers[i]->UpdateSlice(3);
2424         //mSlicerManagers[i]->GetSlicer(3)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ?
2425       }
2426       break;
2427     }
2428   }
2429 }
2430 //------------------------------------------------------------------------------
2431
2432
2433 //------------------------------------------------------------------------------
2434 void vvMainWindow::UpdateSlice(int slicer, int slice)
2435 {
2436   // DD("vvMainWindow::UpdateSlice");
2437 //   DD(slicer);
2438 //   DD(slice);
2439   if (slicer == 0) {
2440     //    if (slice != NOVerticalSlider->value())
2441     NOVerticalSlider->setValue(slice);
2442   } else {
2443     if (slicer == 1)
2444       NEVerticalSlider->setValue(slice);
2445     else {
2446       if (slicer == 2)
2447         SOVerticalSlider->setValue(slice);
2448       else {
2449         if (slicer == 3)
2450           SEVerticalSlider->setValue(slice);
2451       }
2452     }
2453   }
2454   // DD("vvMainWindow:UpdateSlice END");
2455 }
2456 //------------------------------------------------------------------------------
2457
2458
2459 //------------------------------------------------------------------------------
2460 void vvMainWindow::UpdateTSlice(int slicer, int slice)
2461 {
2462   switch (slicer) {
2463   case 0:
2464     NOHorizontalSlider->setValue(slice);
2465     break;
2466   case 1:
2467     NEHorizontalSlider->setValue(slice);
2468     break;
2469   case 2:
2470     SOHorizontalSlider->setValue(slice);
2471     break;
2472   case 3:
2473     SEHorizontalSlider->setValue(slice);
2474     break;
2475   }
2476 }
2477 //------------------------------------------------------------------------------
2478
2479
2480 //------------------------------------------------------------------------------
2481 void vvMainWindow::UpdateSliceRange(int slicer, int min, int max, int tmin, int tmax)
2482 {
2483   int position = int((min+max)/2);
2484   int tPosition = int((tmin+tmax)/2);
2485   if (slicer == 0) {
2486     NOVerticalSlider->setValue(position);
2487     NOVerticalSlider->setRange(min,max);
2488     NOHorizontalSlider->setRange(tmin,tmax);
2489     NOHorizontalSlider->setValue(tPosition);
2490   } else if (slicer == 1) {
2491     NEVerticalSlider->setValue(position);
2492     NEVerticalSlider->setRange(min,max);
2493     NEHorizontalSlider->setRange(tmin,tmax);
2494     NEHorizontalSlider->setValue(tPosition);
2495   } else if (slicer == 2) {
2496     SOVerticalSlider->setValue(position);
2497     SOVerticalSlider->setRange(min,max);
2498     SOHorizontalSlider->setRange(tmin,tmax);
2499     SOHorizontalSlider->setValue(tPosition);
2500   } else if (slicer == 3) {
2501     SEVerticalSlider->setValue(position);
2502     SEVerticalSlider->setRange(min,max);
2503     SEHorizontalSlider->setRange(tmin,tmax);
2504     SEHorizontalSlider->setValue(tPosition);
2505   }
2506 }
2507 //------------------------------------------------------------------------------
2508
2509
2510 //------------------------------------------------------------------------------
2511 void vvMainWindow::SaveNOScreenshot()
2512 {
2513   vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New();
2514   w2i->SetInput(NOViewWidget->GetRenderWindow());
2515   w2i->Update();
2516   SaveScreenshot(w2i->GetOutput());
2517   w2i->Delete();
2518 }
2519 //------------------------------------------------------------------------------
2520
2521
2522 //------------------------------------------------------------------------------
2523 void vvMainWindow::SaveNEScreenshot()
2524 {
2525   vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New();
2526   w2i->SetInput(NEViewWidget->GetRenderWindow());
2527   w2i->Update();
2528   SaveScreenshot(w2i->GetOutput());
2529   w2i->Delete();
2530 }
2531 //------------------------------------------------------------------------------
2532
2533
2534 //------------------------------------------------------------------------------
2535 void vvMainWindow::SaveSOScreenshot()
2536 {
2537   vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New();
2538   w2i->SetInput(SOViewWidget->GetRenderWindow());
2539   w2i->Update();
2540   SaveScreenshot(w2i->GetOutput());
2541   w2i->Delete();
2542 }
2543 //------------------------------------------------------------------------------
2544
2545
2546 //------------------------------------------------------------------------------
2547 void vvMainWindow::SaveSEScreenshot()
2548 {
2549   vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New();
2550   w2i->SetInput(SEViewWidget->GetRenderWindow());
2551   w2i->Update();
2552   SaveScreenshot(w2i->GetOutput());
2553   w2i->Delete();
2554 }
2555 //------------------------------------------------------------------------------
2556
2557
2558 //------------------------------------------------------------------------------
2559 void vvMainWindow::SaveScreenshot(vtkImageData* image)
2560 {
2561   QString Extensions = "Images( *.png);;";
2562   Extensions += "Images( *.jpg);;";
2563   Extensions += "Images( *.bmp);;";
2564   Extensions += "Images( *.tif);;";
2565   Extensions += "Images( *.ppm)";
2566   QString fileName = QFileDialog::getSaveFileName(this,
2567                      tr("Save As"),
2568                      itksys::SystemTools::GetFilenamePath(
2569                        mSlicerManagers[0]->GetFileName()).c_str(),
2570                      Extensions);
2571   if (!fileName.isEmpty()) {
2572     const char *ext = fileName.toStdString().c_str() + strlen(fileName.toStdString().c_str()) - 4;
2573     if (!strcmp(ext, ".bmp")) {
2574       vtkBMPWriter *bmp = vtkBMPWriter::New();
2575       bmp->SetInput(image);
2576       bmp->SetFileName(fileName.toStdString().c_str());
2577       bmp->Write();
2578       bmp->Delete();
2579     } else if (!strcmp(ext, ".tif")) {
2580       vtkTIFFWriter *tif = vtkTIFFWriter::New();
2581       tif->SetInput(image);
2582       tif->SetFileName(fileName.toStdString().c_str());
2583       tif->Write();
2584       tif->Delete();
2585     } else if (!strcmp(ext, ".ppm")) {
2586       vtkPNMWriter *pnm = vtkPNMWriter::New();
2587       pnm->SetInput(image);
2588       pnm->SetFileName(fileName.toStdString().c_str());
2589       pnm->Write();
2590       pnm->Delete();
2591     } else if (!strcmp(ext, ".png")) {
2592       vtkPNGWriter *png = vtkPNGWriter::New();
2593       png->SetInput(image);
2594       png->SetFileName(fileName.toStdString().c_str());
2595       png->Write();
2596       png->Delete();
2597     } else if (!strcmp(ext, ".jpg")) {
2598       vtkJPEGWriter *jpg = vtkJPEGWriter::New();
2599       jpg->SetInput(image);
2600       jpg->SetFileName(fileName.toStdString().c_str());
2601       jpg->Write();
2602       jpg->Delete();
2603     } else {
2604       QMessageBox::information(this,tr("Problem saving screenshot !"),tr("Cannot save image.\nPlease set a file extension !!!"));
2605     }
2606   }
2607
2608 }
2609 //------------------------------------------------------------------------------
2610
2611
2612 //------------------------------------------------------------------------------
2613 void vvMainWindow::GoToCursor()
2614 {
2615   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2616   for (int column = 1; column < 5; column++) {
2617     if (DataTree->selectedItems()[0]->data(column,Qt::CheckStateRole).toInt() > 1) {
2618       double* cursorPos = mSlicerManagers[index]->GetSlicer(column-1)->GetCursorPosition();
2619       mSlicerManagers[index]->GetSlicer(column-1)->SetCurrentPosition(
2620         cursorPos[0],cursorPos[1],cursorPos[2],cursorPos[3]);
2621       mSlicerManagers[index]->UpdateViews(1,column-1);
2622       mSlicerManagers[index]->UpdateLinked(column-1);
2623       break;
2624     }
2625   }
2626 }
2627 //------------------------------------------------------------------------------
2628
2629 //------------------------------------------------------------------------------
2630 void vvMainWindow::PlayPause()
2631 {
2632   if (playMode) {
2633     playMode = 0;
2634     playButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/player_play.png")));
2635     ImageInfoChanged();
2636     return;
2637   } else {
2638     int image_number=DataTree->topLevelItemCount();
2639     bool has_temporal;
2640     for (int i=0; i<image_number; i++)
2641       if (mSlicerManagers[i]->GetImage()->GetVTKImages().size() > 1) {
2642         has_temporal=true;
2643         break;
2644       }
2645     if (has_temporal) {
2646       playMode = 1;
2647       playButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/player_pause.png")));
2648       QTimer::singleShot(1000/mFrameRate, this, SLOT(PlayNext()));
2649     }
2650   }
2651 }
2652 //------------------------------------------------------------------------------
2653
2654 //------------------------------------------------------------------------------
2655 void vvMainWindow::PlayNext()
2656 {
2657   if (playMode && !this->isHidden()) {
2658     int image_number=DataTree->topLevelItemCount();
2659     ///Only play one slicer per SM, and only if the SM is being displayed
2660     for (int i=0; i<image_number; i++)
2661       for (int j=0; j<4; j++)
2662         if (mSlicerManagers[i]->GetImage()->GetVTKImages().size() > 1 &&
2663             DataTree->topLevelItem(i)->data(j+1,Qt::CheckStateRole).toInt() > 0) {
2664           mSlicerManagers[i]->SetNextTSlice(j);
2665           break;
2666         }
2667     QTimer::singleShot(1000/mFrameRate, this, SLOT(PlayNext()));
2668   }
2669 }
2670 //------------------------------------------------------------------------------
2671
2672 void vvMainWindow::ShowLastImage()
2673 {
2674   if (mSlicerManagers.size() > 1) {
2675     QTreeWidgetItem * item=DataTree->topLevelItem(DataTree->topLevelItemCount()-1);
2676     CurrentImageChanged(mSlicerManagers.back()->GetId()); //select new image
2677     item->setData(1,Qt::CheckStateRole,2); //show the new image in the first panel
2678     DisplayChanged(item,1);
2679   }
2680 }
2681
2682 //------------------------------------------------------------------------------
2683 void vvMainWindow::UpdateRenderWindows()
2684 {
2685   if (NOViewWidget->GetRenderWindow()) NOViewWidget->GetRenderWindow()->Render();
2686   if (NEViewWidget->GetRenderWindow()) NEViewWidget->GetRenderWindow()->Render();
2687   if (SOViewWidget->GetRenderWindow()) SOViewWidget->GetRenderWindow()->Render();
2688   if (SEViewWidget->GetRenderWindow()) SEViewWidget->GetRenderWindow()->Render();
2689 }
2690 //------------------------------------------------------------------------------
2691
2692 //------------------------------------------------------------------------------
2693 void vvMainWindow::SegmentationOnCurrentImage()
2694 {
2695   int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2696
2697   vvSegmentationDialog segmentation;
2698   segmentation.SetImage(mSlicerManagers[index]->GetSlicer(0)->GetImage());
2699   segmentation.exec();
2700 }
2701 //------------------------------------------------------------------------------
2702
2703 void vvMainWindow::SurfaceViewerLaunch()
2704 {
2705   vvSurfaceViewerDialog surfaceViewer;
2706   surfaceViewer.exec();
2707 }
2708 //------------------------------------------------------------------------------
2709
2710
2711 //------------------------------------------------------------------------------
2712 int vvMainWindow::GetImageDuplicateFilenameNumber(std::string filename)
2713 {
2714   int number=0;
2715   for(unsigned int l=0; l<mSlicerManagers.size(); l++) {
2716     vvSlicerManager * v = mSlicerManagers[l];
2717     if (v->GetBaseFileName() ==
2718         vtksys::SystemTools::GetFilenameName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename))) {
2719       number = std::max(number, v->GetBaseFileNameNumber()+1);
2720     }
2721   }
2722   return number;
2723 }
2724 //------------------------------------------------------------------------------
2725
2726
2727 //------------------------------------------------------------------------------
2728 vvSlicerManager* vvMainWindow::AddImage(vvImage::Pointer image,std::string filename)
2729 {
2730   // Change filename if another image exist with the same name
2731   int number = GetImageDuplicateFilenameNumber(filename);
2732
2733   // Create new SliceManager
2734   vvSlicerManager* slicer_manager = new vvSlicerManager(4);
2735   slicer_manager->SetImage(image);//, IMAGE, number);
2736   //  filename = filename+"_"+clitk::toString(number);
2737   slicer_manager->SetFilename(filename, number);
2738   mSlicerManagers.push_back(slicer_manager);
2739
2740   //create an item in the tree with good settings
2741   QTreeWidgetItem *item = new QTreeWidgetItem();
2742   item->setData(0,Qt::UserRole,slicer_manager->GetFileName().c_str());//files[i].c_str());
2743   item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,filename.c_str());
2744   qApp->processEvents();
2745
2746   for (int j = 1; j <= 4; j++) item->setData(j,Qt::CheckStateRole,1);
2747
2748   //Create the buttons for reload and close
2749   qApp->processEvents();
2750   QTreePushButton* cButton = new QTreePushButton;
2751   cButton->setItem(item);
2752   cButton->setColumn(COLUMN_CLOSE_IMAGE);
2753   cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png")));
2754   connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2755           this,SLOT(CloseImage(QTreeWidgetItem*, int)));
2756
2757   QTreePushButton* rButton = new QTreePushButton;
2758   rButton->setItem(item);
2759   rButton->setColumn(COLUMN_RELOAD_IMAGE);
2760   rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")));
2761   rButton->setEnabled(0);
2762   connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)),
2763           this,SLOT(ReloadImage(QTreeWidgetItem*, int)));
2764
2765   DataTree->addTopLevelItem(item);
2766   DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton);
2767   DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton);
2768
2769   //set the id of the image
2770   QString id = slicer_manager->GetFileName().c_str() + QString::number(mSlicerManagers.size()-1);
2771   item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str());
2772   mSlicerManagers.back()->SetId(id.toStdString());
2773
2774   linkPanel->addImage(filename, id.toStdString());
2775
2776   connect(mSlicerManagers.back(), SIGNAL(currentImageChanged(std::string)),
2777           this, SLOT(CurrentImageChanged(std::string)));
2778   connect(mSlicerManagers.back(), SIGNAL(UpdatePosition(int, double, double, double, double, double, double, double)),
2779           this, SLOT(MousePositionChanged(int,double, double, double, double, double, double, double)));
2780   connect(mSlicerManagers.back(), SIGNAL(UpdateVector(int, double, double, double, double)),
2781           this, SLOT(VectorChanged(int,double,double,double, double)));
2782   connect(mSlicerManagers.back(), SIGNAL(UpdateOverlay(int, double, double)),
2783           this, SLOT(OverlayChanged(int,double,double)));
2784   connect(mSlicerManagers.back(), SIGNAL(UpdateFusion(int, double)),
2785           this, SLOT(FusionChanged(int,double)));
2786   connect(mSlicerManagers.back(), SIGNAL(UpdateWindows(int, int, int)),
2787           this,SLOT(WindowsChanged(int, int, int)));
2788   connect(mSlicerManagers.back(), SIGNAL(WindowLevelChanged(double, double,int, int)),
2789           this,SLOT(WindowLevelChanged(double, double, int, int)));
2790   connect(mSlicerManagers.back(), SIGNAL(UpdateSlice(int,int)),
2791           this,SLOT(UpdateSlice(int,int)));
2792   connect(mSlicerManagers.back(), SIGNAL(UpdateTSlice(int, int)),
2793           this,SLOT(UpdateTSlice(int, int)));
2794   connect(mSlicerManagers.back(), SIGNAL(UpdateSliceRange(int,int,int,int,int)),
2795           this,SLOT(UpdateSliceRange(int,int,int,int,int)));
2796   connect(mSlicerManagers.back(), SIGNAL(UpdateLinkManager(std::string,int,double,double,double,int)),
2797           this,SLOT(UpdateLinkManager(std::string,int,double,double,double,int)));
2798   connect(mSlicerManagers.back(), SIGNAL(UpdateLinkedNavigation(std::string,vvSlicerManager*)),
2799           this,SLOT(UpdateLinkedNavigation(std::string,vvSlicerManager*)));
2800   connect(mSlicerManagers.back(), SIGNAL(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)),
2801           this,SLOT(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)));
2802   connect(mSlicerManagers.back(), SIGNAL(LandmarkAdded()),landmarksPanel,SLOT(AddPoint()));
2803   UpdateTree();
2804   qApp->processEvents();
2805   InitSlicers();
2806   ShowLastImage();
2807   InitDisplay();
2808   qApp->processEvents();
2809   
2810   // End
2811   return slicer_manager;
2812 }
2813 //------------------------------------------------------------------------------
2814
2815
2816 //------------------------------------------------------------------------------
2817 void vvMainWindow::UpdateCurrentSlicer()
2818 {
2819   int index = -1;
2820   if (DataTree->selectedItems().size() > 0) {
2821     index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]);
2822   }
2823   mSlicerManagerCurrentIndex = index;
2824 }
2825 //------------------------------------------------------------------------------
2826