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