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