]> Creatis software - creaContours.git/blob - lib/Interface_ManagerContour_NDimensions/wxContourEventHandler.cxx__
289f2c4e1418bb48b2c47bcc302d4f9ab30f5800
[creaContours.git] / lib / Interface_ManagerContour_NDimensions / wxContourEventHandler.cxx__
1
2
3 /*  Diagrama de Secuaencia de cambiar un instante
4 wxContourEventHandler :: changeInstant()
5         OutlineModelManager :: ->setInstant( _actualInstant );
6                 OutlineModelManager :: updateToActualInstant()
7                   OutlineModelManager :: getOutlinesAtInstant(Instant * anInstant, bool ifAnnotate)
8                     OutlineModelManager :: annotateOutlinesWrap(std::vector<std::string> kNamesVector, std::vector<ContourThing **> theOutlinesVector)
9         wxContourEventHandler :: updateInstantOutlines()
10                 OutlineModelManager :: getActualInstantOutlines ()
11                 wxVtkBaseView_SceneManager :: addToScene( std::vector< std::string> theKeyNameVector, bool append, bool visualization, bool control, bool ifActive, bool ifShowCtrlPoints )
12                         wxVtkBaseView_SceneManager :: addToScene( std::string theKeyName, bool append, bool visualization, bool control, bool ifActive, bool ifShowCtrlPoints )
13                                 wxVtkBaseView_SceneManager :: getContourWrap_ViewControlOf
14                                         MAP  find
15                            void wxVtkBaseView_SceneManager :: addToScene( std::string theKeyName, ContourWrap_ViewControl * contourWRP, bool append, bool visualization, bool control, bool ifActive, bool ifShowCtrlPoints )
16
17 */
18
19
20 /*!
21  \mainpage NDimension with wxWidgets and maracas
22
23  \section intro Introduction
24
25  This is the introduction. 
26
27
28
29   \dot
30
31
32 digraph example_0 {
33         graph [ ratio=fill];
34     node [shape=record, fontname=Helvetica, fontsize=10];
35
36         _wxContourGUIExample                    [ label="wxContourGUIExample"                   URL="\ref wxContourGUIExample"];
37         _wxContourEventHandler                  [ label="wxContourEventHandler"                 URL="\ref wxContourEventHandler"];
38
39         _OutlineModelManager                    [ label="OutlineModelManager"                   URL="\ref OutlineModelManager"];
40         _wxInstantChooserPanel                  [ label="wxInstantChooserPanel"                 URL="\ref wxInstantChooserPanel"];
41         _wxContourViewPanel                             [ label="wxContourViewPanel"                    URL="\ref wxContourViewPanel"];
42         _wxContour_ButtonsBar                   [ label="wxContour_ButtonsBar"                  URL="\ref wxContour_ButtonsBar"];       
43         _OutlineModelManager                    [ label="OutlineModelManager"                   URL="\ref OutlineModelManager"];
44         _wxVtkBaseView_SceneManager             [ label="wxVtkBaseView_SceneManager"    URL="\ref wxVtkBaseView_SceneManager"];
45         _SomeEnvironment                                [ label="SomeEnvironment"                               URL="\ref SomeEnvironment"];
46                 
47
48         _wxContourGUIExample                    ->      _wxContourEventHandler                  [ arrowhead="open", style="dashed" ];
49         _wxContourGUIExample                    ->      _OutlineModelManager                    [ arrowhead="open", style="dashed" ];
50         _wxContourGUIExample                    ->      _wxInstantChooserPanel                  [ arrowhead="open", style="dashed" ];
51         _wxContourGUIExample                    ->      _wxContourViewPanel                             [ arrowhead="open", style="dashed" ];
52         _wxContourGUIExample                    ->      _wxContour_ButtonsBar                   [ arrowhead="open", style="dashed" ];
53         _wxContourViewPanel                             ->      wxMaracas_N_ViewersWidget               [ arrowhead="open", style="dashed" ];
54         _wxContourEventHandler                  ->      _OutlineModelManager                    [ arrowhead="open", style="dashed" ];
55         _wxContourEventHandler                  ->      _wxVtkBaseView_SceneManager             [ arrowhead="open", style="dashed" ];
56         _OutlineModelManager                    ->      _SomeEnvironment                                [ arrowhead="open", style="dashed" ];
57         
58 }
59
60 \enddot
61
62
63
64 */
65
66
67
68 //----------------------------------------------------------------------------------------------------------------
69 // Class definition include
70 //----------------------------------------------------------------------------------------------------------------
71 #include "wxContourEventHandler.h"
72 #include <wx/filedlg.h>
73 #include <wx/spinctrl.h>
74 #include <iostream>
75 #include <fstream>
76
77 //----------------------------------------------------------------------------------------------------------------
78 // Class implementation
79 //----------------------------------------------------------------------------------------------------------------
80 /** @file wxContourEventHandler.cxx */
81
82
83 //------------------------------------------------------------------------------------------------------------
84 // Includes
85 //------------------------------------------------------------------------------------------------------------
86
87 #include "wxContour_ActionCommandsID.h"
88 #include "NameWrapper.h"
89 #include "ConceptDataWrap.h"
90 #include "OutlineGroup.h"
91
92 #include <manualContour.h>
93 #include "Contour/ContourExtractData.h"
94 #include "ImageSourceThing.h"
95 #include "PanelBullEyeOptions.h"
96
97
98 #include <vtkContourFilter.h>
99 #include <vtkCleanPolyData.h>
100 #include <vtkPolyDataConnectivityFilter.h>         
101 #include <vtkStripper.h>
102 #include <vtkImageReslice.h>
103 #include <vtkMetaImageWriter.h>
104 #include <vtkImageMapToWindowLevelColors.h>
105
106
107
108 //------------------------------------------------------------------------------------------------------------
109 //------------------------------------------------------------------------------------------------------------
110 //------------------------------------------------------------------------------------------------------------
111 /*
112 PanelBullEyeOptions::PanelBullEyeOptions (wxWindow * parent, wxSize size) :
113                  wxPanel(parent, -1, wxDefaultPosition, size)
114 {
115
116         _maxLevels              = 5;
117         _maxSections    = 10;
118         wxSize sizepanel(190,300);
119         wxPanel *panel = this;
120
121
122         wxString lstOptions[2];
123         lstOptions[0]= wxString("General options",wxConvUTF8);
124         lstOptions[1]= wxString("Detail options",wxConvUTF8);
125         _radioboxBullEyeGenOpt  = new wxRadioBox(panel, -1, wxString("General/Detail options",wxConvUTF8), wxDefaultPosition, wxSize(200,45), 2 , lstOptions,  2, wxRA_SPECIFY_COLS);
126         _radioboxBullEyeGenOpt->SetSelection(0);
127
128         _spinctrlBullEyeNumOfCrowns = new wxSpinCtrl( panel , -1,_T("B"),wxDefaultPosition, wxSize(40,20) );
129         _spinctrlBullEyeNumOfCrowns->SetRange(1,_maxLevels);
130         _spinctrlBullEyeNumOfCrowns->SetValue(3);
131
132         _spinctrlBullEyeNumOfSec = new wxSpinCtrl( panel , -1,_T("A"),wxDefaultPosition, wxSize(40,20) );
133         _spinctrlBullEyeNumOfSec->SetRange(1,_maxSections);
134         _spinctrlBullEyeNumOfSec->SetValue(5);
135
136
137         _sliderBullEyeAngle = new wxSlider( panel , -1 ,0,0,180, wxDefaultPosition, wxSize(200,35), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
138
139         wxFlexGridSizer * sizerGeneralOptions                           = new wxFlexGridSizer(10);
140
141         wxFlexGridSizer * sizerGeneralOptionsA                          = new wxFlexGridSizer(1);
142         wxFlexGridSizer * sizerGeneralOptionsB                          = new wxFlexGridSizer(1);
143         wxFlexGridSizer * sizerGeneralOptionsC                          = new wxFlexGridSizer(1);
144         sizerGeneralOptionsA -> Add( new wxStaticText(panel,-1,_T("Crowns")) , 1, wxGROW );
145         sizerGeneralOptionsA -> Add( _spinctrlBullEyeNumOfCrowns , 1/*, wxGROW );
146         sizerGeneralOptionsB -> Add( new wxStaticText(panel,-1,_T("Sections")) , 1, wxGROW );
147         sizerGeneralOptionsB -> Add( _spinctrlBullEyeNumOfSec , 1/*, wxGROW );
148         sizerGeneralOptionsC -> Add( new wxStaticText(panel,-1,_T("      Angle")) , 1, wxGROW );
149         sizerGeneralOptionsC -> Add( _sliderBullEyeAngle , 1/*, wxGROW );
150
151         sizerGeneralOptions -> Add( sizerGeneralOptionsA  , 1/*, wxGROW );
152         sizerGeneralOptions -> Add( new wxStaticText(panel,-1,_T("   ")) , 1, wxGROW );
153         sizerGeneralOptions -> Add( sizerGeneralOptionsB  , 1/*, wxGROW );
154         sizerGeneralOptions -> Add( new wxStaticText(panel,-1,_T("   ")) , 1, wxGROW );
155         sizerGeneralOptions -> Add( sizerGeneralOptionsC  , 1/*, wxGROW );
156
157
158         wxSpinCtrl      *tmpSpinSection;
159         wxSlider        *tmpSliderRadio;
160         wxSlider        *tmpSliderAng;
161
162         wxFlexGridSizer * sizerDetailOptions                            = new wxFlexGridSizer(6);
163
164         sizerDetailOptions -> Add( new wxStaticText(panel,-1,_T("Crown ")) , 1, wxGROW );
165         sizerDetailOptions -> Add( new wxStaticText(panel,-1,_T("  Sections  ")) , 1, wxGROW );
166         sizerDetailOptions -> Add( new wxStaticText(panel,-1,_T("  ")) , 1, wxGROW );
167         sizerDetailOptions -> Add( new wxStaticText(panel,-1,_T("      Radio %")) , 1, wxGROW );
168         sizerDetailOptions -> Add( new wxStaticText(panel,-1,_T("  ")) , 1, wxGROW );
169         sizerDetailOptions -> Add( new wxStaticText(panel,-1,_T("      Angle")) , 1, wxGROW );
170
171         wxString tmpwxstring;
172         int i;
173         for (i=0;i<_maxLevels;i++){
174                 tmpSpinSection = new wxSpinCtrl( panel  , -1,_T(""),wxDefaultPosition, wxSize(40,20) );
175                 tmpSliderRadio = new wxSlider( panel    , -1 ,0,0,100, wxDefaultPosition, wxSize(110,35), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
176                 tmpSliderAng   = new wxSlider( panel    , -1 ,0,0,180, wxDefaultPosition, wxSize(200,35), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
177
178                 tmpSpinSection ->SetRange(1,_maxSections);
179
180                 tmpwxstring.Printf(_T("  %d.  "),i+1);
181                 sizerDetailOptions -> Add( new wxStaticText(panel,-1,tmpwxstring) , 1, wxGROW );
182                 sizerDetailOptions -> Add( tmpSpinSection, 1 );
183                 sizerDetailOptions -> Add( new wxStaticText(panel,-1,_T("  ")) , 1, wxGROW );
184                 sizerDetailOptions -> Add( tmpSliderRadio, 1, wxGROW );
185                 sizerDetailOptions -> Add( new wxStaticText(panel,-1,_T("  ")) , 1, wxGROW );
186                 sizerDetailOptions -> Add( tmpSliderAng, 1, wxGROW );
187
188                 tmpSpinSection  -> SetValue(5);
189                 tmpSliderRadio  -> SetValue( 100-(double)((i)*100.0/_maxLevels) );
190                 tmpSliderAng    -> SetValue(0);
191                 
192                 Connect( tmpSliderRadio->GetId(),       wxEVT_SCROLL_THUMBRELEASE  , (wxObjectEventFunction) &PanelBullEyeOptions::onRefreshPanel );
193                 Connect( tmpSliderRadio->GetId(),       wxEVT_SCROLL_CHANGED  , (wxObjectEventFunction) &PanelBullEyeOptions::onRefreshPanel );
194
195                 _lstBullEyeDetailNumOfSec.push_back( tmpSpinSection );
196                 _lstBullEyeDetailRadio.push_back( tmpSliderRadio );
197                 _lstBullEyeDetailAngle.push_back( tmpSliderAng );
198
199         } //for
200
201         wxFlexGridSizer * sizer                         = new wxFlexGridSizer(1);
202         sizer -> Add( new wxStaticText(panel,-1,_T("")) , 1, wxGROW );
203         sizer -> Add( new wxStaticText(panel,-1,_T("")) , 1, wxGROW );
204         sizer -> Add( _radioboxBullEyeGenOpt , 1, wxGROW );
205         sizer -> Add( new wxStaticText(panel,-1,_T("")) , 1, wxGROW );
206         sizer -> Add( new wxStaticText(panel,-1,_T("      -- Bull Eye general options --")) , 1, wxGROW );
207         sizer -> Add( new wxStaticText(panel,-1,_T("")) , 1, wxGROW );
208         sizer -> Add(  sizerGeneralOptions , 1, wxGROW );
209         sizer -> Add( new wxStaticText(panel,-1,_T("")) , 1, wxGROW );
210         sizer -> Add( new wxStaticText(panel,-1,_T("")) , 1, wxGROW );
211         sizer -> Add( new wxStaticText(panel,-1,_T("      -- Bull Eye detail options --")) , 1, wxGROW );
212         sizer -> Add( new wxStaticText(panel,-1,_T("")) , 1, wxGROW );
213         sizer -> Add(  sizerDetailOptions  , 1, wxGROW );
214
215         Connect( _radioboxBullEyeGenOpt->GetId(),       wxEVT_COMMAND_RADIOBOX_SELECTED , (wxObjectEventFunction) &PanelBullEyeOptions::onRefreshPanel ); 
216         Connect( _spinctrlBullEyeNumOfCrowns->GetId(),  wxEVT_COMMAND_TEXT_UPDATED              , (wxObjectEventFunction) &PanelBullEyeOptions::onRefreshPanel );
217         
218         panel->SetSizer( sizer );
219         panel->SetSize( sizepanel );
220         panel->SetAutoLayout( true );
221         panel->Layout();
222
223         RefreshPanel();
224
225 }
226
227 //------------------------------------------------------------------------------------------------------------
228 PanelBullEyeOptions::~PanelBullEyeOptions() 
229 {
230 }
231
232 //------------------------------------------------------------------------------------------------------------
233 void PanelBullEyeOptions::onRefreshPanel( wxCommandEvent& event )
234 {
235         RefreshPanel();
236 }
237
238 //------------------------------------------------------------------------------------------------------------
239 void PanelBullEyeOptions::RefreshPanel()
240 {
241         int i;
242         bool ok;
243         if (this->_radioboxBullEyeGenOpt->GetSelection()==0){
244                 for (i=0; i<_maxLevels; i++)
245                 {
246                         _lstBullEyeDetailNumOfSec[i]    -> Enable(false);
247                         _lstBullEyeDetailRadio[i]               -> Enable(false);
248                         _lstBullEyeDetailAngle[i]               -> Enable(false);
249                 } // for
250         } else {
251                 int spinSelec = _spinctrlBullEyeNumOfCrowns->GetValue(); 
252                 for (i=0; i<_maxLevels; i++)
253                 {
254                         ok = (i < spinSelec);
255                         _lstBullEyeDetailNumOfSec[i]    -> Enable(ok);
256                         _lstBullEyeDetailRadio[i]               -> Enable(ok);
257                         _lstBullEyeDetailAngle[i]               -> Enable(ok);
258
259                         if (i>0){
260                                 if (_lstBullEyeDetailRadio[i]->GetValue() > _lstBullEyeDetailRadio[i-1]->GetValue())
261                                 {
262                                         _lstBullEyeDetailRadio[i]->SetValue( _lstBullEyeDetailRadio[i-1]->GetValue() );
263                                 } 
264                         }// if i>0
265                 } // for
266         } // if
267 }
268
269 //------------------------------------------------------------------------------------------------------------
270 int PanelBullEyeOptions::GetNumberOfCrowns()
271 {
272         return this->_spinctrlBullEyeNumOfCrowns->GetValue();
273 }
274
275 //------------------------------------------------------------------------------------------------------------
276 int PanelBullEyeOptions::GetNumberOfSections(int nCrown)
277 {
278         int result;
279         if (this->_radioboxBullEyeGenOpt->GetSelection()==0)
280         { 
281                 result = this->_spinctrlBullEyeNumOfSec->GetValue();
282         } else {
283                 result = this->_lstBullEyeDetailNumOfSec[nCrown]->GetValue();
284         }
285         return result;
286 }
287
288 //------------------------------------------------------------------------------------------------------------
289 int PanelBullEyeOptions::GetRadioOfCrown(int nCrown)
290 {
291         int result;
292         double sizeCrowns;
293         if (this->_radioboxBullEyeGenOpt->GetSelection()==0)
294         { 
295                 sizeCrowns = (double)( this->_spinctrlBullEyeNumOfCrowns->GetValue() );
296                 result = 100.0 * (nCrown+1)/sizeCrowns ;
297         } else {
298                 result = this->_lstBullEyeDetailRadio[nCrown]->GetValue();
299         }
300         return result;
301 }
302
303 //------------------------------------------------------------------------------------------------------------
304 double PanelBullEyeOptions::GetAngOfCrownSection(int nCrown,int section)
305 {
306         double angle;
307         if (this->_radioboxBullEyeGenOpt->GetSelection()==0)
308         { 
309                 angle = this->_sliderBullEyeAngle->GetValue();
310         } else {
311                 angle = this->_lstBullEyeDetailAngle[nCrown]->GetValue();
312         }
313         double numOfSec = (double)GetNumberOfSections(nCrown);
314         double deltaSec = GetAngDeltaOfCrownSection(nCrown);
315         return angle + section*deltaSec ;
316 }
317
318 //------------------------------------------------------------------------------------------------------------
319 double PanelBullEyeOptions::GetAngDeltaOfCrownSection(int nCrown)
320 {
321         double numOfSec = (double)GetNumberOfSections(nCrown);
322         return 360.0/numOfSec;
323 }
324
325 */
326
327 //------------------------------------------------------------------------------------------------------------
328 //------------------------------------------------------------------------------------------------------------
329 //------------------------------------------------------------------------------------------------------------
330
331
332         //------------------------------------------------------------------------------------------------------------
333         // Constructors & Destructors
334         //------------------------------------------------------------------------------------------------------------
335
336         wxContourEventHandler ::wxContourEventHandler()
337                 :wxEvtHandler()
338         {
339         _creatingContoursActive                 = false;
340                 _theViewPanel                                   = NULL;
341                 _modelManager                                   = NULL;
342                 _instantPanel                                   = NULL;
343                 _buttonsBar                                             = NULL;
344                 _gridPanel                                              = NULL; 
345                 _drawToolsPanel                                 = NULL;
346                 _operationsToolsPanel                   = NULL;
347                 _autoFormsPanel                                 = NULL; 
348                 _standardToolsPanel                             = NULL;
349                 _editionToolsPanel                              = NULL;
350                 _listViewPanel                                  = NULL;
351                 _sceneManager                                   = NULL;
352                 _actualInstant                                  = NULL;
353                 _performingOperation                    = new PerformingOperation();
354
355                 // EED Interface and Spread
356                 _spreadFrame                                    = NULL;
357                 _segmentationFrame                              = NULL;
358                 _contourPropagation                             = NULL;
359                 _createContourFrame                             = NULL;
360                 _deleteFrame                                    = NULL;
361                 _InformationContourFrame                = NULL;
362                 _interfaceConfigurationFrame    = NULL;
363                 _TestFrame                                              = NULL;
364                 _wxtextctrlTest                                 = NULL;
365                 _panelBullEyeOptions                    = NULL;
366
367                 fileNameContourROI                              = "";
368                 _numberOfVariablesStatistics=6+1;
369
370                 inundo = 0;
371                 inredo = 0;
372                 stundoredo = "data/temp";
373 #if(WIN32)
374                 mkdir(stundoredo.c_str());
375 #else
376                 mkdir(stundoredo.c_str(),755);
377 #endif
378                 stundoredo += "/cont";
379         }
380         //------------------------------------------------------------------------------------------------------------
381         wxContourEventHandler :: ~ wxContourEventHandler()
382         {
383                 delete _actualInstant;
384                 /*delete _theViewPanel;         
385                 delete _instantPanel;
386                 delete _buttonsBar;
387                 delete _actualInstant;  
388                 */       
389                 delete _sceneManager;
390                 delete _performingOperation;
391
392                 
393         }
394         //------------------------------------------------------------------------------------------------------------
395         // Configuration methods
396         //------------------------------------------------------------------------------------------------------------
397         
398         bool wxContourEventHandler :: configureEventsHandling()
399         {
400                 bool configured = true;
401
402                 return configured;
403         }
404
405         //------------------------------------------------------------------------------------------------------------
406         // Methods for capturing events 
407         //------------------------------------------------------------------------------------------------------------
408         void wxContourEventHandler :: onProcessMessage( wxCommandEvent& event )
409         {
410                 
411         }
412         //------------------------------------------------------------------------------------------------------------
413
414         void wxContourEventHandler :: onActionButtonPressed( wxCommandEvent& event )
415         {
416                 const char buttonTool = *(char *)event.GetClientData();
417                 executeActionCommand( buttonTool );             
418         }
419         //------------------------------------------------------------------------------------------------------------          
420         void wxContourEventHandler :: onChangedDeep ( wxCommandEvent& event )
421         {
422                 double val = _theViewPanel->getCurrentDeep();
423                 _instantPanel->setConceptValue( "Axe Depth", (int)val );
424                 _theViewPanel->setActualVertical( (int)val );
425                 changeInstant();
426         }
427
428         //------------------------------------------------------------------------------------------------------------
429         void wxContourEventHandler :: onChangeInstant( wxCommandEvent& event )
430         {               
431                 ConceptDataWrap * dataConcept = NULL; 
432                 if ( _theViewPanel->GetId() == event.GetId() )
433                 {
434                         dataConcept = (ConceptDataWrap *)event.GetClientData();
435                         int value = dataConcept->getActualValue();
436                         _instantPanel->setConceptValue( dataConcept->getName(), value );
437                 }
438                 else
439                 {
440                         dataConcept = _instantPanel->getLastConceptData();
441                         if( dataConcept->getName().compare( _theViewPanel->getVerticalConceptName() ) == 0)
442                         {
443                                 _theViewPanel->setActualVertical( dataConcept->getActualValue());
444                                 //_theViewPanel->setVerticalConcept( dataConcept->getName(), dataConcept->getMinShowedValue()/*dataConcept->getMinValue()*/, /*dataConcept->getMaxValue()*/ dataConcept->getMaxShowedValue(), dataConcept->getMinShowedValue(), dataConcept->getMaxShowedValue(), dataConcept->getActualValue());
445                         }
446                         else if( dataConcept->getName().compare( _theViewPanel->getHorizontalConceptName() ) == 0|| _instantPanel->getIfConceptCheckedAt( dataConcept->getName(), 0 ) )
447                         {
448                                 _theViewPanel->setHorizontalConcept( dataConcept->getName(), dataConcept->getMinShowedValue()/*dataConcept->getMinValue()*/, /*dataConcept->getMaxValue()*/ dataConcept->getMaxShowedValue(), dataConcept->getMinShowedValue(), dataConcept->getMaxShowedValue(), dataConcept->getActualValue());
449                         }
450                 }       
451                 changeInstant();
452         }
453         //------------------------------------------------------------------------------------------------------------
454                 
455         void wxContourEventHandler :: onCreateMultipleROI( wxCommandEvent& event )
456         {
457                 _creatingContoursActive = !_creatingContoursActive;
458                 if( _creatingContoursActive )
459                 {                       
460                         createContour();
461                 }
462         }
463         //------------------------------------------------------------------------------------------------------------
464         void wxContourEventHandler :: onCreateROI( wxCommandEvent& event )
465         {
466                 if( _creatingContoursActive )
467                 {                       
468                         createContour();
469                 }
470         }
471
472         //------------------------------------------------------------------------------------------------------------
473         void wxContourEventHandler :: onStopCreateROI( wxCommandEvent& event )
474         {
475                 
476         }
477
478         //------------------------------------------------------------------------------------------------------------
479         void wxContourEventHandler :: onDeleterROI( wxCommandEvent& event )
480         {
481
482         }
483         //------------------------------------------------------------------------------------------------------------
484         void wxContourEventHandler :: onSelectROI( wxCommandEvent& event )
485         {
486                 
487         }
488         //------------------------------------------------------------------------------------------------------------
489
490
491         void wxContourEventHandler :: onUnSelectROI( wxCommandEvent& event )
492         {
493
494         }
495         //------------------------------------------------------------------------------------------------------------
496
497         void wxContourEventHandler :: onManualHidedROI( wxCommandEvent& event )
498         {
499
500         }
501         //------------------------------------------------------------------------------------------------------------
502
503         void wxContourEventHandler :: onManualShowedROI( wxCommandEvent& event )
504         {
505
506         }
507         //------------------------------------------------------------------------------------------------------------
508
509         void wxContourEventHandler :: onEditingROI( wxCommandEvent& event )
510         {
511
512         }
513         //------------------------------------------------------------------------------------------------------------
514
515         void wxContourEventHandler :: onMovingROI( wxCommandEvent& event )
516         {
517
518         }
519
520         //------------------------------------------------------------------------------------------------------------
521         //  Model management methods
522         //------------------------------------------------------------------------------------------------------------
523
524         void wxContourEventHandler::onSpreadReset( wxCommandEvent& event )
525         {
526                 _wxtextctrlSpread->SetValue(wxString("",wxConvUTF8));
527                 _contourPropagation->resetAppend();
528         }
529
530         //------------------------------------------------------------------------------------------------------------
531         void wxContourEventHandler::onSpreadAdd( wxCommandEvent& event )
532         {
533                 std::vector<double> vecX; 
534                 std::vector<double> vecY; 
535                 std::vector<double> vecZ; 
536                 _theViewPanel->getSceneManager()->GetPointsOfActualContour( &vecX , &vecY , &vecZ );    
537
538                 if (vecX.size()!=0){
539                         std::vector<int> tempVector;
540                         _instantPanel->getInstant( tempVector );
541                         int i,size=vecZ.size();
542                         int actualSlice = tempVector[1];
543                         for ( i=0 ; i<size ; i++ )
544                         {
545                                 vecZ[i] = actualSlice;
546                         } // for
547
548                         _contourPropagation->appendContour(&vecX , &vecY , &vecZ);
549                         wxString newstring;
550                         //newstring.Printf("%s %d -",_wxtextctrlSpread->GetValue(), actualSlice );
551                         newstring.append(wxString(_wxtextctrlSpread->GetValue(),wxConvUTF8));
552                         newstring.append(wxString(" ",wxConvUTF8));
553                         newstring.append(wxString(intToString(actualSlice).c_str(),wxConvUTF8));
554                         _wxtextctrlSpread->SetValue(newstring);
555                 } // if 
556         }
557
558         
559
560         //------------------------------------------------------------------------------------------------------------
561         void wxContourEventHandler::onSpreadGo( wxCommandEvent& event )
562         {
563
564                 //JCP 20-10-08 Undo redo implementation
565                 saveState();
566                 //JCP 20-10-08 Undo redo implementation
567
568                 wxBusyCursor wait;
569                 int typeMethodFindCtrlPoints=_spreadMethodRadiobox->GetSelection();
570                 int typeofcontour = 1;
571                 manualContourModel *manModelContour;
572                 std::vector<double> vecCtrlPointX;
573                 std::vector<double> vecCtrlPointY;
574                 std::vector<double> vecCtrlPointZ;
575                 double  minZ,maxZ;
576                 int z,j,sizeCtrPt;
577 //              double idTmp;
578                 int idTmp;
579
580                 std::vector<int> tempVector;
581                 _instantPanel->getInstant( tempVector );
582 //              tempVector[1];
583
584                 _contourPropagation->getMaxMinZ(&minZ,&maxZ);
585 //JSTG_16-07-08_----------------------------------------------------------------
586                 //_contourPropagation->setInterpolationNumber(maxZ-minZ+1);
587                 _contourPropagation->setInterpolationNumber(100);
588                 _contourPropagation->CalculeSplinePropagation();
589
590                 double          totalZ = maxZ-minZ+1;
591                 double          porcent;
592                 wxString        tmpString;
593 //--------------------------------------------------------------------
594                 for ( z=(int)minZ ; z<=(int)maxZ ; z++ )
595                 {
596                         porcent = 100.0* (z-minZ)/totalZ;
597                         int numero = (int)(z-minZ+1)/(int)totalZ;
598                         std::string stringtemp = "  "+intToString(porcent)+"%            "+intToString(numero)+"            "+intToString(z);
599                         tmpString.Append(wxString(stringtemp.c_str(),wxConvUTF8));
600
601                         //tmpString.Printf("  %d %c            %d/%d            %d", (int)porcent , 37 , (int)(z-minZ+1), (int)totalZ,z );
602                         _staticTextSpread->SetLabel(tmpString);
603
604                         if (_contourPropagation->ifSliceKeyContourExist(z)==false)
605                         {
606                                 manModelContour = factoryManualContourModel( typeofcontour );
607                                 idTmp = _contourPropagation->FindIdWithZ(z);
608                                 if (typeMethodFindCtrlPoints==0) // Initial Points
609                                 {   
610                                         _contourPropagation->GetInitialControlPoints( idTmp , &vecCtrlPointX,&vecCtrlPointY,&vecCtrlPointZ);
611                                 } 
612                                 if (typeMethodFindCtrlPoints==1)  // Automatique Method
613                                 {
614                                         _contourPropagation->GetControlPoints( idTmp  ,&vecCtrlPointX,&vecCtrlPointY,&vecCtrlPointZ);
615                                 }
616                                 if (typeMethodFindCtrlPoints==2)  // sampling
617                                 {
618                                         _contourPropagation->GetControlPoints( idTmp , 20.0 ,&vecCtrlPointX,&vecCtrlPointY,&vecCtrlPointZ);
619                                 }
620         //--------------------------------------------------------------------
621                                 sizeCtrPt = vecCtrlPointX.size();
622                                 for (j=0 ; j<sizeCtrPt ; j++)
623                                 {
624         //JSTG_16-07-08_----------------------------------------------------------------
625                                         manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , -900  );
626         //--------------------------------------------------------------------
627                                 } // for j
628
629                                 tempVector[1]=z;
630                                 std::string theName;
631                                 theName = _modelManager->createOutline( manModelContour, tempVector );
632                                 bool addedModel = theName.compare("") != 0;
633                                 if( addedModel )
634                                 {
635                                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
636                                         this->_theViewPanel->getSpacing(spc);                                   
637                                         //Adding the manualContourControler to interface objects structure
638                                         //Adding the manualViewContour to interface objects structure           
639                                         //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
640                                         _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc,typeofcontour ) ;
641                                 } // if addedModel
642                         }// ifSliceKeyContourExist
643                 } // for z
644                 _staticTextSpread->SetLabel(wxString("   ",wxConvUTF8));
645                 //RefreshInterface();
646
647
648                 
649         }
650
651         //------------------------------------------------------------------------------------------------------------
652         void wxContourEventHandler :: onSpread( )
653         {
654                 if (_spreadFrame==NULL)
655                 {
656                         
657                         _spreadFrame                            = new wxFrame (_theViewPanel, -1,_T(" Spread "), wxDefaultPosition, wxDefaultSize, wxFRAME_TOOL_WINDOW|wxSYSTEM_MENU | wxCAPTION |  wxCLIP_CHILDREN |wxFRAME_FLOAT_ON_PARENT );
658                         
659                         wxSize sizepanel(250,400);
660                         _spreadFrame->SetSize( sizepanel );
661                         _spreadFrame->SetEventHandler( this );
662                         wxPanel *panel                          = getSpreadPanel(_spreadFrame);
663                         panel->SetSize(sizepanel);
664                         /**new wxPanel(_spreadFrame,-1);
665
666                         wxButton *spreadResetBtn        = new wxButton(panel,-1,_T("Reset"),wxDefaultPosition, wxSize(80,35) );
667                         wxButton *spreadAddBtn          = new wxButton(panel,-1,_T("Add"),wxDefaultPosition, wxSize(80,35));
668
669                         wxString lstOptions[3];
670                         lstOptions[0]="A";
671                         lstOptions[1]="B";
672                         lstOptions[2]="C";
673                         _spreadMethodRadiobox                                           = new wxRadioBox(panel, -1, "Method (find ctrl. Points)", wxDefaultPosition, wxSize(200,45), 3 , lstOptions,  3, wxRA_SPECIFY_COLS);
674                         _spreadMethodRadiobox->SetSelection(2);
675
676                         wxButton *spreadGoBtn           = new wxButton(panel,-1,_T("Go"),wxDefaultPosition, wxSize(80,35));
677                         _staticTextSpread                       = new wxStaticText(panel,-1,_T("    "));
678
679                         _wxtextctrlSpread           = new wxTextCtrl(panel,-1, "",wxDefaultPosition, wxSize(200,150), wxTE_MULTILINE );
680
681                         _spreadFrame->SetEventHandler( this );
682                         Connect( spreadResetBtn->GetId(),       wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSpreadReset ); 
683                         Connect( spreadAddBtn->GetId(),         wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSpreadAdd ); 
684                         Connect( spreadGoBtn->GetId(),          wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSpreadGo ); 
685
686                         wxFlexGridSizer * sizer         = new wxFlexGridSizer(1);
687                         sizer -> Add( spreadResetBtn            , 1, wxGROW );
688                         sizer -> Add( spreadAddBtn                      , 1, wxGROW );
689                         sizer -> Add( _spreadMethodRadiobox     , 1, wxGROW );
690                         sizer -> Add( spreadGoBtn                       , 1, wxGROW );
691                         sizer -> Add( _staticTextSpread         , 1, wxGROW );
692                         sizer -> Add( _wxtextctrlSpread         , 1, wxGROW );
693
694
695                         panel->SetSizer( sizer );
696                         panel->SetSize( sizepanel );
697                         panel->SetAutoLayout( true );
698                         panel->Layout();**/
699                         _spreadFrame->Show();
700                 } else {
701                         if (_spreadFrame->IsShown()==true)
702                         {
703                                 _spreadFrame->Show(false);
704                         } else  {
705                                 _spreadFrame->Show(true);
706                         }
707                 }
708         }
709
710         wxPanel* wxContourEventHandler::getSpreadPanel(wxWindow* parent){
711                 //wxPanel *panel                                = new wxPanel(parent,-1);
712
713                 _contourPropagation                     = new ContourPropagation();
714
715                 wxPanel *panel                                                  = new wxPanel(parent,-1,wxDefaultPosition, wxDefaultSize,wxNO_BORDER, wxString("",wxConvUTF8));
716
717                 wxButton *spreadResetBtn        = new wxButton(panel,-1,_T("Reset"),wxDefaultPosition, wxDefaultSize );
718                 wxButton *spreadAddBtn          = new wxButton(panel,-1,_T("Add"),wxDefaultPosition, wxDefaultSize);
719
720                 wxString lstOptions[3];
721                 lstOptions[0]=_T("A");
722                 lstOptions[1]=_T("B");
723                 lstOptions[2]=_T("C");
724                 _spreadMethodRadiobox                                           = new wxRadioBox(panel, -1, _T("Method (find ctrl. Points)"), wxDefaultPosition, wxDefaultSize, 3 , lstOptions,  3, wxRA_SPECIFY_COLS);
725                 _spreadMethodRadiobox->SetSelection(2);
726
727                 wxButton *spreadGoBtn           = new wxButton(panel,-1,_T("Go"),wxDefaultPosition, wxDefaultSize);
728                 _staticTextSpread                       = new wxStaticText(panel,-1,_T("    "));
729
730                 _wxtextctrlSpread           = new wxTextCtrl(panel,-1, _T(""),wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE );
731
732                 
733                 Connect( spreadResetBtn->GetId(),       wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSpreadReset ); 
734                 Connect( spreadAddBtn->GetId(),         wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSpreadAdd ); 
735                 Connect( spreadGoBtn->GetId(),          wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSpreadGo ); 
736
737                 wxFlexGridSizer * sizer         = new wxFlexGridSizer(1);
738                 sizer -> Add( spreadResetBtn            , 1, wxGROW );
739                 sizer -> Add( spreadAddBtn                      , 1, wxGROW );
740                 sizer -> Add( _spreadMethodRadiobox     , 1, wxGROW );
741                 sizer -> Add( spreadGoBtn                       , 1, wxGROW );
742                 sizer -> Add( _staticTextSpread         , 1, wxGROW );
743                 sizer -> Add( _wxtextctrlSpread         , 1, wxGROW );
744
745
746                 panel->SetSizer( sizer );
747                 //panel->SetSize( wxDefaultSize );
748                 panel->SetAutoLayout( true );
749                 panel->Layout();
750                 return panel;
751         }
752
753         //------------------------------------------------------------------------------------------------------------
754         void wxContourEventHandler::onSegmentationAllSlice( wxCommandEvent& event )
755         {
756                 //JCP 20-10-08 Undo redo implementation
757                 saveState();
758                 //JCP 20-10-08 Undo redo implementation
759                 
760                 wxBusyCursor wait;
761                 int                                     x                                       = this->_theViewPanel->GetX();
762                 int                                     y                                       = this->_theViewPanel->GetY();
763                 int z,minZ,maxZ;
764                 double porcent; 
765                 wxString tmpString;
766                 minZ=_mbarrange->GetStart();
767                 maxZ=_mbarrange->GetEnd();
768                 double totalZ = maxZ-minZ+1;
769                 for( z=minZ ; z<=maxZ ; z++ )
770                 {
771                         porcent = 100.0* (z-minZ)/totalZ;
772                         tmpString.Printf(_T("  %d %c            %d/%d            %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ,z );
773                         _staticTextSegmentation->SetLabel(tmpString);
774                         SegmentationOneSlice( x,y,z );
775                 }
776                 _staticTextSegmentation->SetLabel(_T("   "));
777                 RefreshInterface();
778
779                 
780         }
781
782         //------------------------------------------------------------------------------------------------------------
783         void wxContourEventHandler::onSegmentationOneSlice( wxCommandEvent& event )
784         {
785                 //JCP 20-10-08 Undo redo implementation
786                 saveState();
787                 //JCP 20-10-08 Undo redo implementation
788                 
789                 wxBusyCursor wait;
790                 int                                     x                                       = this->_theViewPanel->GetX();
791                 int                                     y                                       = this->_theViewPanel->GetY();
792                 int                                     z                                       = this->_theViewPanel->GetZ();
793                 SegmentationOneSlice( x,y,z );
794                 RefreshInterface();
795
796                 
797         }
798         //------------------------------------------------------------------------------------------------------------
799         void wxContourEventHandler::SegmentationOneSlice( int x, int y, int z )
800         {               
801                 int typeofcontour = 1;
802                 //--Extracting Contour
803                 vtkImageData    *imagedata      = _theViewPanel->getSceneManager()->GetImageData();
804 //              double                  *range          = imagedata->GetScalarRange();  
805 //              double                  thr                     = 1;
806                 int                             isovalue        = _isovalue->GetValue();
807                 int                             sampling        = _sampling->GetValue();
808
809                 vtkImageReslice *imageReslice = vtkImageReslice::New();
810 //EED
811 //              double spc[3];
812 //              imagedata->GetSpacing(spc);
813 //              x = x*spc[0];
814 //              y = y*spc[1];
815 //              z = z*spc[3];
816
817                 imageReslice->SetInput( imagedata );
818                 imageReslice->SetInformationInput(imagedata);
819                 imageReslice->SetResliceAxesDirectionCosines(1,0,0, 0,1,0 ,0,0,1);
820                 imageReslice->SetResliceAxesOrigin(0,0,z);
821                 imageReslice->SetOutputDimensionality(2);
822                 imageReslice->SetInterpolationModeToLinear();
823
824                 imagedata = imageReslice->GetOutput();
825                 imagedata->Update();
826                 imagedata->UpdateInformation();
827
828                 vtkContourFilter* cntVTK = vtkContourFilter::New( );
829                 cntVTK->SetInput( imagedata );
830
831                 cntVTK->SetNumberOfContours( 1 );
832                 //cntVTK->SetValue( 0, vmin );
833 //              cntVTK->SetValue( 0, (range[1]*thr/100) );
834                 cntVTK->SetValue( 1, isovalue );
835         //      cntVTK->SetValue( 1, vmax );
836                 cntVTK->Update( );
837                 cntVTK->UpdateInformation();
838                         
839                 vtkCleanPolyData* cpd = vtkCleanPolyData::New( );
840                 cpd->SetInput( cntVTK->GetOutput( ) );
841                 cpd->ConvertLinesToPointsOff( );
842                 cpd->Update( );
843                 cpd->UpdateInformation();
844
845                 vtkPolyDataConnectivityFilter* conn = vtkPolyDataConnectivityFilter::New( );
846                 conn->SetExtractionModeToClosestPointRegion( );
847                 //conn->SetMaxRecursionDepth( 3000 );
848                         
849                 conn->SetInput( cpd->GetOutput( ) );
850                         
851                 conn->SetClosestPoint( x, y, 0 );
852                 conn->Update( );
853                 conn->UpdateInformation();
854                         
855                 vtkCleanPolyData* cpd2 = vtkCleanPolyData::New( );
856                 cpd2->SetInput( conn->GetOutput( ) );
857                 cpd2->Update();
858                 cpd2->UpdateInformation();
859
860                 vtkStripper* vtkstripper = vtkStripper::New( );
861                 vtkstripper->SetInput( cpd2->GetOutput() );
862                 vtkstripper->Update();
863                 vtkstripper->UpdateInformation();
864
865
866                 vtkPolyData* polyDataResult =  vtkstripper->GetOutput();
867
868                 polyDataResult->Update( );
869                 polyDataResult->UpdateInformation();
870
871 /* EED
872 ofstream myfile;
873 myfile.open ("c:/temp/example.txt");
874 myfile << "\n";
875 polyDataResult->Print(myfile);
876 myfile << "-------------------------------------\n";
877 polyDataResult->GetLines()->Print(myfile);
878 myfile.close();
879 */
880
881                 cntVTK          -> Delete();
882                 cpd2            -> Delete();
883                 cpd                     -> Delete();
884                 conn            -> Delete();
885
886
887 //--Calculating control points
888
889                 std::vector<double> vecX;
890                 std::vector<double> vecY;
891                 std::vector<double> vecZ;
892
893                 std::vector<double> vecCtrlPointX;
894                 std::vector<double> vecCtrlPointY;
895                 std::vector<double> vecCtrlPointZ;
896
897
898                 double *p;
899                 int ii,size=polyDataResult->GetNumberOfPoints();
900                 int id;
901                 for (ii=1;ii<=size;ii++)
902                 {
903                         id      = polyDataResult->GetLines()->GetData()->GetValue(ii);
904                         p       = polyDataResult->GetPoint(id);
905                         double x=p[0];
906                         double y=p[1];
907                         vecX.push_back( p[0] );
908                         vecY.push_back( p[1] );
909                         vecZ.push_back( -900 );
910 //                      vecZ.push_back( p[2] );
911                 }
912
913
914                 ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
915                 extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
916
917 //PROOFS
918                 if (methodRadiobox->GetSelection()==0){
919                         extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
920                 }
921                 if (methodRadiobox->GetSelection()==1){
922                         extractcontrolpoints2d->GetControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
923                 }
924                 if (methodRadiobox->GetSelection()==2){
925                         extractcontrolpoints2d->SetSamplingControlPoints( sampling );
926                         extractcontrolpoints2d->GetSamplingControlPoints(  &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
927                 }
928
929                 //--Adding contour to the system
930
931                 std::vector<int> actualInstantVector;
932                 _instantPanel->getInstant( actualInstantVector );
933                 actualInstantVector[1]=z;
934
935                 int j,sizeCtrPt = vecCtrlPointX.size();
936                 manualContourModel *manModelContour =  factoryManualContourModel( typeofcontour );
937                 manModelContour->SetNumberOfPointsSpline( ((sizeCtrPt/100)+1)*100 );
938                 if (sizeCtrPt>=3){
939                         for (j=0 ; j<sizeCtrPt ; j++)
940                         {
941                                 manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
942                         } // for
943                         std::string theName;
944                         theName = _modelManager->createOutline( manModelContour, actualInstantVector );
945                         bool addedModel = theName.compare("") != 0;
946                         if( addedModel )
947                         {
948                                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
949                                 this->_theViewPanel->getSpacing(spc);                                   
950                                 //Adding the manualContourControler to interface objects structure
951                                 //Adding the manualViewContour to interface objects structure           
952                                 //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
953                                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc, typeofcontour ) ;
954                         }       // if addedModel
955                 } // if sizeCtrPt
956         }
957
958         //------------------------------------------------------------------------------------------------------------
959         void wxContourEventHandler :: onAutomatiqueSegmentation( )
960         {
961                 if (_segmentationFrame==NULL)
962                 {
963                         //JCP 13-10-09
964                         /*int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
965                         double range[2];
966                         _theViewPanel->getSceneManager()->GetImageDataRange(range);*/
967                         //JCP 13-10-09
968
969                          wxSize sizePanel( 300, 470);
970                         _segmentationFrame                                      =  new wxFrame (_theViewPanel, -1,_T("  Segmentation  "), wxDefaultPosition, wxDefaultSize, wxFRAME_TOOL_WINDOW|wxSYSTEM_MENU | wxCAPTION |  wxCLIP_CHILDREN |wxFRAME_FLOAT_ON_PARENT );
971                         _segmentationFrame->SetSize( sizePanel );
972                         wxPanel *panel                                          = getSegmentationPanel(_segmentationFrame);
973                                 /*new wxPanel(_segmentationFrame,-1);
974                         wxButton *segmentationOneSliceBtn       = new wxButton(panel,-1,_T("Actual slice"), wxDefaultPosition, wxSize(200,35) );
975                         wxButton *segmentationAllSliceBtn       = new wxButton(panel,-1,_T("All slices") ,wxDefaultPosition, wxSize(200,35) );
976                         _isovalue                                                       = new wxSlider(panel, -1, 40 , (int)(range[0]), (int)(range[1]), wxDefaultPosition, wxSize(200,35), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
977                         _sampling                                                       = new wxSlider(panel, -1, 20 , 4, 50, wxDefaultPosition, wxSize(200,35), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
978                         wxString lstOptions[3];
979                         lstOptions[0]="A";
980                         lstOptions[1]="B";
981                         lstOptions[2]="C";
982                         methodRadiobox                                          = new wxRadioBox(panel, -1, "Method (find ctrl. Points)", wxDefaultPosition, wxSize(200,45), 3 , lstOptions,  3, wxRA_SPECIFY_COLS);
983                         methodRadiobox->SetSelection(2);
984                         _staticTextSegmentation                         = new wxStaticText(panel,-1,_T("    "));
985
986
987                         _mbarrange                                      =  new mBarRange(panel,70, 65);
988                         _mbarrange->SetMin(0);
989                         _mbarrange->SetStart(0);
990
991                         _mbarrange-> SetOrientation( true );
992                         _mbarrange-> setActiveStateTo(true);
993                         _mbarrange-> setVisibleLabels( true );
994                         _mbarrange-> setDeviceEndMargin(10);
995                         _mbarrange-> setRepresentedValues( 0 , sizeZ );
996                         _mbarrange-> setDeviceBlitStart(10,10); 
997                         _mbarrange-> setIfWithActualDrawed( false );
998                         _mbarrange-> SetStart( 0 );
999                         _mbarrange-> SetEnd( sizeZ );  
1000
1001
1002 //                      _segmentationFrame->SetEventHandler( this );
1003                         segmentationOneSliceBtn->SetEventHandler( this );
1004                         segmentationAllSliceBtn->SetEventHandler( this );
1005                         Connect( segmentationOneSliceBtn->GetId(),   wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSegmentationOneSlice ); 
1006                         Connect( segmentationAllSliceBtn->GetId(),   wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSegmentationAllSlice ); 
1007
1008                         wxFlexGridSizer * sizer                         = new wxFlexGridSizer(1);
1009                         sizer -> Add( new wxStaticText(panel,-1,_T("Isovalue (Gray level)"))  , 1, wxGROW );
1010                         sizer -> Add( _isovalue , 1, wxGROW );
1011                         sizer -> Add( methodRadiobox , 1, wxGROW );
1012                         sizer -> Add( new wxStaticText(panel,-1,_T("Sampling (%)"))  , 1, wxGROW );
1013                         sizer -> Add( _sampling , 1, wxGROW );
1014                         sizer -> Add( segmentationOneSliceBtn , 1, wxGROW );
1015                         sizer -> Add( new wxStaticText(panel,-1,_T(" "))  , 1, wxGROW );
1016                         sizer -> Add( _staticTextSegmentation  , 1, wxGROW );
1017                         sizer -> Add( segmentationAllSliceBtn , 1, wxGROW );
1018                         sizer -> Add( _mbarrange  , 1, wxGROW );
1019
1020                         panel->SetSizer( sizer );
1021                         panel->SetSize( sizePanel );
1022                         panel->SetAutoLayout( true );
1023                         panel->Layout();*/
1024
1025                         this->_theViewPanel->SetVisibleAxis(true);
1026                         this->_theViewPanel->Refresh();
1027                         _segmentationFrame->Show(true);
1028 //JCP 13-10-09 View the method getSegmentationPanel(), this two methods where moved to getSegmentationPanel
1029                         //this->_theViewPanel->SetVisibleAxis(true);
1030                         //this->_theViewPanel->Refresh();
1031                 } else {
1032                         if (_segmentationFrame->IsShown()==true)
1033                         {
1034                                 _segmentationFrame->Show(false);
1035                                 this->_theViewPanel->SetVisibleAxis(false);
1036                                 this->_theViewPanel->Refresh();
1037                         } else  {
1038                                 _segmentationFrame->Show(true);
1039                                 this->_theViewPanel->SetVisibleAxis(true);
1040                                 this->_theViewPanel->Refresh();
1041                         }
1042                 }
1043         }
1044
1045         void wxContourEventHandler::showAxis(bool show){
1046                 this->_theViewPanel->SetVisibleAxis(show);
1047                 this->_theViewPanel->Refresh();
1048         }
1049         wxPanel* wxContourEventHandler::getSegmentationPanel(wxWindow* parent){
1050                 int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
1051                 double range[2];
1052                 _theViewPanel->getSceneManager()->GetImageDataRange(range);
1053
1054                 wxPanel *panel                                          = new wxPanel(parent,-1);
1055                 wxButton *segmentationOneSliceBtn       = new wxButton(panel,-1,_T("Actual slice"), wxDefaultPosition, wxSize(200,35) );
1056                 wxButton *segmentationAllSliceBtn       = new wxButton(panel,-1,_T("All slices") ,wxDefaultPosition, wxSize(200,35) );
1057                 _isovalue                                                       = new wxSlider(panel, -1, 40 , (int)(range[0]), (int)(range[1]), wxDefaultPosition, wxSize(200,35), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
1058                 _sampling                                                       = new wxSlider(panel, -1, 20 , 4, 50, wxDefaultPosition, wxSize(200,35), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
1059                 wxString lstOptions[3];
1060                 lstOptions[0]=_T("A");
1061                 lstOptions[1]=_T("B");
1062                 lstOptions[2]=_T("C");
1063                 methodRadiobox                                          = new wxRadioBox(panel, -1, _T("Method (find ctrl. Points)"), wxDefaultPosition, wxSize(200,45), 3 , lstOptions,  3, wxRA_SPECIFY_COLS);
1064                 methodRadiobox->SetSelection(2);
1065                 _staticTextSegmentation                         = new wxStaticText(panel,-1,_T("    "));
1066
1067
1068                 _mbarrange                                      =  new mBarRange(panel,70, 65);
1069                 _mbarrange->SetMin(0);
1070                 _mbarrange->SetStart(0);
1071
1072                 _mbarrange-> SetOrientation( true );
1073                 _mbarrange-> setActiveStateTo(true);
1074                 _mbarrange-> setVisibleLabels( true );
1075                 _mbarrange-> setDeviceEndMargin(10);
1076                 _mbarrange-> setRepresentedValues( 0 , sizeZ );
1077                 _mbarrange-> setDeviceBlitStart(10,10); 
1078                 _mbarrange-> setIfWithActualDrawed( false );
1079                 _mbarrange-> SetStart( 0 );
1080                 _mbarrange-> SetEnd( sizeZ );  
1081
1082
1083 //                      _segmentationFrame->SetEventHandler( this );
1084                 segmentationOneSliceBtn->SetEventHandler( this );
1085                 segmentationAllSliceBtn->SetEventHandler( this );
1086                 Connect( segmentationOneSliceBtn->GetId(),   wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSegmentationOneSlice ); 
1087                 Connect( segmentationAllSliceBtn->GetId(),   wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSegmentationAllSlice ); 
1088
1089                 wxFlexGridSizer * sizer                         = new wxFlexGridSizer(1);
1090                 sizer -> Add( new wxStaticText(panel,-1,_T("Isovalue (Gray level)"))  , 1, wxGROW );
1091                 sizer -> Add( _isovalue , 1, wxGROW );
1092                 sizer -> Add( methodRadiobox , 1, wxGROW );
1093                 sizer -> Add( new wxStaticText(panel,-1,_T("Sampling (%)"))  , 1, wxGROW );
1094                 sizer -> Add( _sampling , 1, wxGROW );
1095                 sizer -> Add( segmentationOneSliceBtn , 1, wxGROW );
1096                 sizer -> Add( new wxStaticText(panel,-1,_T(" "))  , 1, wxGROW );
1097                 sizer -> Add( _staticTextSegmentation  , 1, wxGROW );
1098                 sizer -> Add( segmentationAllSliceBtn , 1, wxGROW );
1099                 sizer -> Add( _mbarrange  , 1, wxGROW );
1100
1101                 panel->SetSizer( sizer );
1102 //              panel->SetSize( sizePanel );
1103                 panel->SetSize( wxDefaultSize );
1104                 panel->SetAutoLayout( true );
1105                 panel->Layout();
1106                 
1107                 return panel;
1108         }
1109         void wxContourEventHandler :: onInterfaceTestFrame( )
1110         {
1111                 if (_TestFrame==NULL)
1112                 {
1113                         _contourPropagation                     = new ContourPropagation();
1114                         _TestFrame                                      = new wxFrame (_theViewPanel, -1,_T("  Test Segmentation  "), wxDefaultPosition, wxDefaultSize, wxFRAME_TOOL_WINDOW|wxSYSTEM_MENU | wxCAPTION |  wxCLIP_CHILDREN |wxFRAME_FLOAT_ON_PARENT );
1115                         wxSize sizepanel(200,300);
1116                         _TestFrame->SetSize( sizepanel );
1117                         wxPanel *panel                          = new wxPanel(_TestFrame,-1);
1118                         wxButton *spreadResetBtn        = new wxButton(panel,-1,_T("Reset"),wxDefaultPosition, wxSize(80,35) );
1119                         wxButton *spreadAddBtn          = new wxButton(panel,-1,_T("Add"),wxDefaultPosition, wxSize(80,35));
1120                         wxButton *spreadGoBtn           = new wxButton(panel,-1,_T("GoA"),wxDefaultPosition, wxSize(80,35));
1121                         _wxtextctrlTest                         = new wxTextCtrl(panel,-1, _T(""),wxDefaultPosition, wxSize(200,150), wxTE_MULTILINE );
1122
1123                         _TestFrame->SetEventHandler( this );
1124                         Connect( spreadResetBtn->GetId(),       wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onTestReset ); 
1125                         Connect( spreadAddBtn->GetId(),         wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onTestAdd ); 
1126                         Connect( spreadGoBtn->GetId(),          wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onTestGo ); 
1127
1128                         wxFlexGridSizer * sizer         = new wxFlexGridSizer(1);
1129                         sizer -> Add( spreadResetBtn    , 1, wxGROW );
1130                         sizer -> Add( spreadAddBtn              , 1, wxGROW );
1131                         sizer -> Add( spreadGoBtn               , 1, wxGROW );
1132                         sizer -> Add( _wxtextctrlTest , 1, wxGROW );
1133
1134                         panel->SetSizer( sizer );
1135                         panel->SetSize( sizepanel );
1136                         panel->SetAutoLayout( true );
1137                         panel->Layout();
1138                         _TestFrame->Show();
1139                 } else {
1140                         if (_TestFrame->IsShown()==true)
1141                         {
1142                                 _TestFrame->Show(false);
1143                         } else  {
1144                                 _TestFrame->Show(true);
1145                         }
1146                 }
1147         }
1148
1149         void wxContourEventHandler::onTestReset( wxCommandEvent& event )
1150         {
1151                 _wxtextctrlTest->SetValue(_T(""));
1152                 _contourPropagation->resetAppend();
1153         }
1154
1155         //------------------------------------------------------------------------------------------------------------
1156         void wxContourEventHandler::onTestAdd( wxCommandEvent& event )
1157         {
1158                 std::vector<double> vecX; 
1159                 std::vector<double> vecY; 
1160                 std::vector<double> vecZ; 
1161                 _theViewPanel->getSceneManager()->GetPointsOfActualContour( &vecX , &vecY , &vecZ );    
1162
1163                 if (vecX.size()!=0){
1164                         std::vector<int> tempVector;
1165                         _instantPanel->getInstant( tempVector );
1166                         int i,size=vecZ.size();
1167                         int actualSlice = tempVector[1];
1168                         for ( i=0 ; i<size ; i++ )
1169                         {
1170                                 vecZ[i] = actualSlice;
1171                         } // for
1172
1173                         _contourPropagation->appendContour(&vecX , &vecY , &vecZ);
1174                         wxString newstring;
1175                         newstring.append(_wxtextctrlTest->GetValue());
1176                         newstring.append(_T(" "));
1177                         newstring.append(wxString(intToString(actualSlice).c_str(),wxConvUTF8));                        
1178                         //newstring.Printf(_T("%s %d -"),,  );
1179                         newstring.append(_T(" -"));
1180                         _wxtextctrlTest->SetValue(newstring);
1181                 } // if 
1182         }
1183
1184         //------------------------------------------------------------------------------------------------------------
1185         void wxContourEventHandler::onTestGo( wxCommandEvent& event )
1186         {
1187                 std::vector<double> vecX; 
1188                 std::vector<double> vecY; 
1189                 std::vector<double> vecZ; 
1190                 std::vector<int> size; 
1191
1192                 std::vector<double> vecCtrlPointX;
1193                 std::vector<double> vecCtrlPointY;
1194                 std::vector<double> vecCtrlPointZ;
1195
1196                 //Getting the points of the actual contour      
1197
1198                 _contourPropagation->GetKeyContours(&vecX , &vecY , &vecZ, &size);
1199                 for(int i = 0; i < vecX.size();i++){
1200                         vecZ[i] = -900;
1201                 }
1202
1203                 /*std::vector<double> vecX1; 
1204                 std::vector<double> vecY1; 
1205                 std::vector<double> vecZ1;
1206                 _theViewPanel->getSceneManager()->GetPointsOfActualContour( &vecX1 , &vecY1 , &vecZ1 );
1207
1208                 std::ofstream file1;
1209         file1.open( "Temp.txt" );       
1210                 if(file1.is_open())
1211                 {
1212                         for(int i = 0; i < vecX.size(); i++){
1213                                 file1<<vecX[i] <<" X1 "<< vecX1[i] <<" Y "<<vecY[i] <<" Y1 "<< vecY1[i]  <<" Z "<<vecZ[i] <<" Z1 "<< vecZ1[i]<<std::endl;
1214                                 
1215                         }
1216                         file1.close();
1217                 }*/     
1218                         
1219                 
1220
1221                 //Setting the points of the contour 
1222
1223                 ExtractControlPoints2D *extractcontrolpoints2d = new ExtractControlPoints2D();
1224                 extractcontrolpoints2d->SetContour( &vecX , &vecY , &vecZ );
1225
1226                 //Getting the control points of the contour by method A
1227
1228                 extractcontrolpoints2d->GetInitialControlPoints( &vecCtrlPointX , &vecCtrlPointY , &vecCtrlPointZ );
1229                 
1230                 std::vector<int> actualInstantVector;
1231                 _instantPanel->getInstant( actualInstantVector );
1232                 actualInstantVector[1]= this->_theViewPanel->GetZ();
1233
1234
1235
1236
1237
1238                 //Adding the Contour to the scene
1239
1240                 manualContourModel *manModelContour = new manualContourModel();
1241                 int j,sizeCtrPt = vecCtrlPointX.size();
1242                 if (sizeCtrPt>=3){
1243                         for (j=0 ; j<sizeCtrPt ; j++)
1244                         {
1245                                 manModelContour->AddPoint( vecCtrlPointX[j] , vecCtrlPointY[j] , vecCtrlPointZ[j]  );
1246                         } // for
1247                         std::string theName;
1248                         theName = _modelManager->createOutline( manModelContour, actualInstantVector );
1249                         bool addedModel = theName.compare("") != 0;
1250                         if( addedModel )
1251                         {
1252                                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
1253                                 this->_theViewPanel->getSpacing(spc);                                   
1254                                 //Adding the manualContourControler to interface objects structure
1255                                 //Adding the manualViewContour to interface objects structure           
1256                                 //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
1257                                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc,1 ) ;
1258                         }       // if addedModel
1259                 } // if sizeCtrPt
1260         }
1261
1262         //------------------------------------------------------------------------------------------------------------
1263         void wxContourEventHandler::FillGridWithContoursInformation()
1264         {
1265                 wxString tempString;
1266                 _grid->ClearGrid();
1267                 _grid->SetColLabelValue(0, _T("A") );
1268                 _grid->SetColLabelValue(1, _T("B") );
1269                 _grid->SetColLabelValue(2, _T("C") );
1270                 _grid->SetColLabelValue(3, _T("D") );
1271                 _grid->SetColLabelValue(4, _T("E") );
1272                 _grid->SetColLabelValue(5, _T("F") );
1273
1274                 std::vector<int> tempVector;
1275                 _instantPanel->getInstant( tempVector );
1276
1277                 int z,sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
1278                 int ii,sizeLstContourThings;
1279                 for ( z=0 ; z<sizeZ ; z++)
1280                 {
1281                         tempVector[1]=z;
1282                         Instant instant(&tempVector);
1283                         std::vector<ContourThing**> lstContourThings = this->_modelManager->getOutlinesAtInstant( &instant );
1284
1285                         sizeLstContourThings = lstContourThings.size();
1286                         tempString.Printf(_T("%d - %d"),z, sizeLstContourThings);
1287                         _grid->SetRowLabelValue(z, tempString );
1288
1289                         for (ii=0 ; ii<sizeLstContourThings ; ii++)
1290                         {
1291                                 ContourThing **contourthing = lstContourThings[ii];
1292                                 tempString = wxString((*contourthing)->getName().c_str(),wxConvUTF8) ;
1293                                 _grid->SetCellValue( z, ii, tempString );
1294                         }
1295                 }
1296
1297
1298         }
1299
1300         //------------------------------------------------------------------------------------------------------------
1301         std::vector<manualContourModel*> wxContourEventHandler::ExploseEachModel( std::vector<manualContourModel*> lstManConMod )
1302         {
1303                 std::vector<manualContourModel*> lstTmp;
1304                 std::vector<manualContourModel*> lstResult;
1305                 int j,jSize;
1306                 int i,iSize=lstManConMod.size();
1307                 for (i=0;i<iSize;i++)
1308                 {
1309                         lstTmp = lstManConMod[i]->ExploseModel();
1310                         jSize=lstTmp.size();
1311                         for (j=0;j<jSize;j++)
1312                         {
1313                                 lstResult.push_back( lstTmp[j] );
1314                         }
1315                 }
1316                 return lstResult;
1317         }
1318
1319         //------------------------------------------------------------------------------------------------------------
1320         void wxContourEventHandler::onExtractInformation( wxCommandEvent& event )
1321         {
1322                 wxBusyCursor wait;
1323                 int maxContourGroup     =       0;
1324
1325                 _grid->ClearGrid();
1326
1327                 ContourExtractData      *contourextractdata = new ContourExtractData();
1328                 int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
1329                 contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
1330
1331                 std::vector<manualContourModel*> lstManConMod;
1332                 std::vector<manualContourModel*> lstManConModTmp;
1333                 std::vector<manualContourModel*> lstManConModExp;
1334                 std::vector<double> pLstValue;
1335                 std::vector<double> pLstValuePosX;
1336                 std::vector<double> pLstValuePosY;
1337                 std::vector<double> pLstValuePosZ;
1338
1339                 int             resultSize; 
1340                 int             resultGrayRangeCount;
1341                 double  resultMin; 
1342                 double  resultMax;
1343                 double  resultAverage;
1344                 double  resultStandardeviation;
1345
1346                 std::vector<int> tempVector;
1347                 _instantPanel->getInstant( tempVector );
1348
1349                 vtkImageData *imagedata = _theViewPanel->getSceneManager()->GetImageData();
1350                 int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
1351                 int z;
1352                 int ii,sizeLstContourThings;
1353
1354
1355                 int minZ,maxZ;
1356                 double totalZ;
1357                 double porcent; 
1358                 wxString tmpString;
1359
1360
1361                 if (_informationRadiobox->GetSelection()==0 ) // actual slice
1362                 {
1363                         std::vector<int> tempVector;
1364                         _instantPanel->getInstant( tempVector );
1365                         int actualSlice = tempVector[1];
1366                         minZ    = actualSlice;
1367                         maxZ    = actualSlice;
1368                 }
1369                 if (_informationRadiobox->GetSelection()==1 ) // slice range
1370                 {
1371                         minZ    = _mbarrangeSliceInformation->GetStart();
1372                         maxZ    = _mbarrangeSliceInformation->GetEnd();
1373                 }
1374                 if (_informationRadiobox->GetSelection()==2 ) // All slices
1375                 {
1376                         minZ    = 0;
1377                         maxZ    = sizeZ-1;
1378                 }
1379
1380                 totalZ  = maxZ-minZ+1;
1381                 contourextractdata->SetImage( imagedata);
1382
1383         // For each slice..
1384                 for ( z=minZ ; z<=maxZ ; z++ )
1385                 {
1386                         porcent = 100.0* (z-minZ)/totalZ;
1387                         tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
1388                         _staticTextInformation->SetLabel(tmpString);
1389
1390                         //Extraction data from contours of each slice
1391                         contourextractdata->SetZtoBeAnalys( z);
1392
1393                         tempVector[1]=z;
1394                         Instant instant(&tempVector);
1395                         std::vector<ContourThing**> lstContourThings = this->_modelManager->getOutlinesAtInstant( &instant );
1396                         sizeLstContourThings = lstContourThings.size();
1397
1398                         lstManConMod.clear();
1399                         for (ii=0 ; ii<sizeLstContourThings ; ii++)
1400                         {
1401                                 ContourThing **contourthing = lstContourThings[ii];
1402                                 lstManConMod.push_back( (*contourthing)->getModel() );
1403                         }
1404                         lstManConModExp =  ExploseEachModel( lstManConMod );
1405
1406
1407                         wxString tempString;
1408                         tempString.Printf(_T("%d - %d"),z, sizeLstContourThings);
1409                         _grid->SetRowLabelValue(z, tempString );
1410 //EED004
1411                         int iContourGroup,sizeContourGroup;
1412                         if (typeContourGroup==3) // contour separete
1413                         {
1414                                 sizeContourGroup=lstManConModExp.size();
1415                                 if ( maxContourGroup<sizeContourGroup ) 
1416                                 {
1417                                         maxContourGroup=sizeContourGroup;
1418                                 }
1419                         } else {  // contour AND OR XOR
1420                                 sizeContourGroup=1;
1421                                 maxContourGroup=1;
1422                         }
1423
1424                         int tmpIntA;
1425
1426
1427
1428                         for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
1429                                 lstManConModTmp.clear();
1430                                 if (typeContourGroup==3) // contour separete
1431                                 {
1432                                         lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
1433                                 } else {  // contour AND OR XOR
1434                                         lstManConModTmp = lstManConModExp;
1435                                 }
1436
1437                                 contourextractdata->SetLstManualContourModel( lstManConModTmp );
1438
1439                                 pLstValue.clear();
1440                                 pLstValuePosX.clear();
1441                                 pLstValuePosY.clear();
1442                                 pLstValuePosZ.clear();
1443                                 contourextractdata->GetValuesInsideCrown(       &pLstValue,
1444                                                                                                                         &pLstValuePosX,
1445                                                                                                                         &pLstValuePosY,
1446                                                                                                                         &pLstValuePosZ);
1447                                 // Statistics of each slice.
1448                                 contourextractdata->Statistics( &pLstValue,
1449                                                                                                 _mbarrangeRangeInformation->GetStart(),
1450                                                                                                 _mbarrangeRangeInformation->GetEnd(),
1451                                                                                                 &resultGrayRangeCount, 
1452                                                                                                 &resultSize, 
1453                                                                                                 &resultMin, 
1454                                                                                                 &resultMax,
1455                                                                                                 &resultAverage,
1456                                                                                                 &resultStandardeviation);
1457                                 if (_grid->GetNumberCols()<_numberOfVariablesStatistics*(iContourGroup+1)  )
1458                                 {
1459                                         _grid->AppendCols(_numberOfVariablesStatistics);
1460                                 }
1461
1462                                 tmpIntA=_numberOfVariablesStatistics*iContourGroup ;
1463
1464                                 tempString.Printf(_T("%d"),resultSize);
1465                                 _grid->SetCellValue( z, tmpIntA + 0, tempString );
1466                                 tempString.Printf(_T("%d"),resultGrayRangeCount);
1467                                 _grid->SetCellValue( z, tmpIntA + 1, tempString );
1468                                 tempString.Printf(_T("%f"),resultMin);
1469                                 _grid->SetCellValue( z, tmpIntA + 2, tempString );
1470                                 tempString.Printf(_T("%f"),resultMax);
1471                                 _grid->SetCellValue( z, tmpIntA + 3, tempString );
1472                                 tempString.Printf(_T("%f"),resultAverage);
1473                                 _grid->SetCellValue( z, tmpIntA + 4, tempString );
1474                                 tempString.Printf(_T("%f"),resultStandardeviation);
1475                                 _grid->SetCellValue( z, tmpIntA + 5, tempString );
1476
1477                         } // for iContourGroup
1478                 } // for z
1479
1480                 int iTitleGroup;
1481                 wxString tmpTitleString;
1482                 int tmpIntB;
1483                 for ( iTitleGroup=0 ; iTitleGroup<maxContourGroup ; iTitleGroup++ )
1484                 {
1485                         tmpIntB =_numberOfVariablesStatistics*iTitleGroup;
1486                         tmpTitleString.Printf(_T("%d-Size Data"),iTitleGroup);
1487                         _grid->SetColLabelValue( tmpIntB + 0, tmpTitleString );
1488                         _grid->SetColLabelValue( tmpIntB + 1, _T("Size Range") );
1489                         _grid->SetColLabelValue( tmpIntB + 2, _T("Min") );
1490                         _grid->SetColLabelValue( tmpIntB + 3, _T("Max") );
1491                         _grid->SetColLabelValue( tmpIntB + 4, _T("Average") );
1492                         _grid->SetColLabelValue( tmpIntB + 5, _T("St.Dev.") );
1493                         _grid->SetColLabelValue( tmpIntB + 6, _T(" ") );
1494                 }
1495
1496                 _staticTextInformation->SetLabel( _T("") );
1497                 delete contourextractdata;
1498         }
1499
1500
1501         //------------------------------------------------------------------------------------------------------------
1502         void wxContourEventHandler::SaveValuesXYZ(std::string directory,std::string namefile)
1503         {
1504                 wxBusyCursor wait;
1505                 ContourExtractData      *contourextractdata = new ContourExtractData();
1506                 int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
1507                 contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
1508
1509                 std::vector<manualContourModel*> lstManConMod;
1510                 std::vector<manualContourModel*> lstManConModTmp;
1511                 std::vector<manualContourModel*> lstManConModExp;
1512                 std::vector<double> pLstValue;
1513                 std::vector<double> pLstValuePosX;
1514                 std::vector<double> pLstValuePosY;
1515                 std::vector<double> pLstValuePosZ;
1516
1517                 std::vector<int> tempVector;
1518                 _instantPanel->getInstant( tempVector );
1519
1520                 vtkImageData *imagedata = _theViewPanel->getSceneManager()->GetImageData();
1521                 int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
1522                 int z;
1523                 int ii,sizeLstContourThings;
1524
1525
1526                 int minZ,maxZ;
1527                 double totalZ;
1528                 double porcent; 
1529                 wxString tmpString;
1530                 minZ    = 0;// _mbarrange->GetStart();
1531                 maxZ    = sizeZ;//_mbarrange->GetEnd();
1532                 totalZ  = maxZ-minZ+1;
1533
1534                 contourextractdata->SetImage( imagedata);
1535
1536         // For each slice..
1537                 for ( z=0 ; z<sizeZ ; z++)
1538                 {
1539
1540                         porcent = 100.0* (z-minZ)/totalZ;
1541                         
1542                         tmpString.Printf(_T("Saving Values"));
1543                         tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
1544                         _staticTextInformation->SetLabel(tmpString);
1545
1546
1547                         //Extraction data from contours of each slice
1548                         contourextractdata->SetZtoBeAnalys( z);
1549
1550                         tempVector[1]=z;
1551                         Instant instant(&tempVector);
1552                         std::vector<ContourThing**> lstContourThings = this->_modelManager->getOutlinesAtInstant( &instant );
1553                         sizeLstContourThings = lstContourThings.size();
1554
1555                         lstManConMod.clear();
1556                         for (ii=0 ; ii<sizeLstContourThings ; ii++)
1557                         {
1558                                 ContourThing **contourthing = lstContourThings[ii];
1559                                 lstManConMod.push_back( (*contourthing)->getModel() );
1560                         }
1561                         lstManConModExp =  ExploseEachModel( lstManConMod );
1562
1563
1564 //EED004
1565
1566                         int iContourGroup,sizeContourGroup;
1567                         if (typeContourGroup==3) // contour separete
1568                         {
1569                                 sizeContourGroup=lstManConModExp.size();
1570                         } else {  // contour AND OR XOR
1571                                 sizeContourGroup=1;
1572                         }
1573
1574                         for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
1575                                 lstManConModTmp.clear();
1576                                 if (typeContourGroup==3) // contour separete
1577                                 {
1578                                         lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
1579                                 } else {  // contour AND OR XOR
1580                                         lstManConModTmp = lstManConModExp;
1581                                 }
1582
1583                                 contourextractdata->SetLstManualContourModel( lstManConModTmp );
1584
1585                                 pLstValue.clear();
1586                                 pLstValuePosX.clear();
1587                                 pLstValuePosY.clear();
1588                                 pLstValuePosZ.clear();
1589                                 contourextractdata->GetValuesInsideCrown(       &pLstValue,
1590                                                                                                                         &pLstValuePosX,
1591                                                                                                                         &pLstValuePosY,
1592                                                                                                                         &pLstValuePosZ);
1593
1594                                 wxString filename;
1595                                 filename.Printf(_T("%s"),directory.c_str());
1596                                 filename.Printf(_T("\\"));
1597                                 filename.Printf(_T("%s"),namefile.c_str());
1598                                 filename.Printf(_T("-slice"));
1599                                 filename.Printf(_T("%d"),z);
1600                                 filename.Printf(_T("-cont"));
1601                                 filename.Printf(_T("%d"),iContourGroup);
1602                                 filename.Printf(_T(".txt"));
1603                                 FILE *pFile=fopen((const char *)filename.mb_str(),"w+");
1604                                 fprintf(pFile,"value \t x \t y \t z\n"  );
1605                                 int iLstValue,sizeLstValue=pLstValue.size();
1606                                 for (iLstValue=0 ; iLstValue<sizeLstValue ; iLstValue++ )
1607                                 {
1608                                         fprintf(pFile,"%f\t %f\t %f\t %f\n", (float)pLstValue[iLstValue] , (float)pLstValuePosX[iLstValue], (float)pLstValuePosY[iLstValue], (float)z );
1609                                 }
1610                                 fclose(pFile);
1611                         } // for  iContourGroup
1612                 } // for z
1613                 _staticTextInformation->SetLabel( _T("") );
1614                 delete contourextractdata;
1615         }
1616
1617
1618         //------------------------------------------------------------------------------------------------------------
1619         void wxContourEventHandler::SaveImageResult(std::string directory,std::string namefile)
1620         {
1621                 wxBusyCursor wait;
1622                 ContourExtractData      *contourextractdata = new ContourExtractData( true );
1623                 int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
1624                 if (typeContourGroup==3)
1625                 {
1626                         typeContourGroup=1;
1627                 }
1628                 contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
1629
1630                 std::vector<manualContourModel*> lstManConMod;
1631                 std::vector<manualContourModel*> lstManConModTmp;
1632                 std::vector<manualContourModel*> lstManConModExp;
1633
1634                 std::vector<int> tempVector;
1635                 _instantPanel->getInstant( tempVector );
1636
1637                 vtkImageData *imagedata = _theViewPanel->getSceneManager()->GetImageData();
1638                 int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
1639                 int z;
1640                 int ii,sizeLstContourThings;
1641
1642
1643                 int minZ,maxZ;
1644                 double totalZ;
1645                 double porcent; 
1646
1647                 wxString tmpString;
1648
1649                 minZ    = 0;// _mbarrange->GetStart();
1650                 maxZ    = sizeZ;//_mbarrange->GetEnd();
1651                 totalZ  = maxZ-minZ+1;
1652
1653                 contourextractdata->SetImage( imagedata);
1654
1655         // For each slice..
1656                 for ( z=0 ; z<sizeZ ; z++)
1657                 {
1658
1659                         porcent = 100.0* (z-minZ)/totalZ;
1660                         tmpString.Printf(_T("Saving Values"));
1661                         tmpString.Printf(_T("%d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
1662                         _staticTextInformation->SetLabel(tmpString);
1663
1664                         //Extraction data from contours of each slice
1665                         contourextractdata->SetZtoBeAnalys( z);
1666
1667                         tempVector[1]=z;
1668                         Instant instant(&tempVector);
1669                         std::vector<ContourThing**> lstContourThings = this->_modelManager->getOutlinesAtInstant( &instant );
1670                         sizeLstContourThings = lstContourThings.size();
1671
1672                         lstManConMod.clear();
1673                         for (ii=0 ; ii<sizeLstContourThings ; ii++)
1674                         {
1675                                 ContourThing **contourthing = lstContourThings[ii];
1676                                 lstManConMod.push_back( (*contourthing)->getModel() );
1677                         }
1678                         lstManConModExp =  ExploseEachModel( lstManConMod );
1679
1680
1681                         int iContourGroup,sizeContourGroup;
1682                         if (typeContourGroup==3) // contour separete
1683                         {
1684                                 sizeContourGroup=lstManConModExp.size();
1685                         } else {  // contour AND OR XOR
1686                                 sizeContourGroup=1;
1687                         }
1688
1689                         for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
1690                                 lstManConModTmp.clear();
1691                                 if (typeContourGroup==3) // contour separete
1692                                 {
1693                                         lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
1694                                 } else {  // contour AND OR XOR
1695                                         lstManConModTmp = lstManConModExp;
1696                                 }
1697
1698                                 contourextractdata->SetLstManualContourModel( lstManConModTmp );
1699
1700
1701 //                              for (ii=0 ; ii<sizeLstContourThings ; ii++)
1702 //                              {
1703 //                                      ContourThing **contourthing = lstContourThings[ii];
1704 //                                      lstManConMod.push_back( (*contourthing)->getModel() );
1705 //                              }
1706 //                              contourextractdata->SetLstManualContourModel( lstManConMod );
1707
1708                                 contourextractdata->CalculateImageResult(); // with actual Z
1709
1710                         } // for  iContourGroup
1711                 } // for z
1712
1713
1714                 wxString filename;
1715                 //filename.Printf(_T("%s\\%s-Value.mhd",directory.c_str(),namefile.c_str(),z);
1716                 filename.Printf(_T("%s"),directory.c_str());
1717                 filename.Printf(_T("\\"));
1718                 filename.Printf(_T("%s"),namefile.c_str());
1719                 filename.Printf(_T("-Value.mhd"));
1720
1721 // Image Value
1722                 vtkMetaImageWriter *writerValueImage = vtkMetaImageWriter::New( );
1723                 writerValueImage->SetInput( contourextractdata->GetVtkImageValueResult() );
1724                 writerValueImage->SetFileName( (const char *)filename.mb_str() );
1725                 writerValueImage->SetFileDimensionality( 3 );
1726                 writerValueImage->Write( );
1727
1728 // Image Mask
1729                 //              filename.Printf("%s\\%s-Mask.mhd",directory.c_str(),namefile.c_str(),z);
1730                 filename.Printf(_T("%s"),directory.c_str());
1731                 filename.Printf(_T("\\"));
1732                 filename.Printf(_T("%s"),namefile.c_str());
1733                 filename.Printf(_T("-Mask.mhd"));
1734                 vtkMetaImageWriter *writerMaskImage = vtkMetaImageWriter::New( );
1735                 writerMaskImage->SetInput( contourextractdata->GetVtkImageMaskResult() );
1736                 writerMaskImage->SetFileName( (const char *)filename.mb_str() );
1737                 writerMaskImage->SetFileDimensionality( 3 );
1738                 writerMaskImage->Write( );
1739
1740                 _staticTextInformation->SetLabel( _T("") );
1741                 delete contourextractdata;
1742         }
1743
1744
1745         //------------------------------------------------------------------------------------------------------------
1746         void wxContourEventHandler::onInformationContourLabels( wxCommandEvent& event )
1747         {
1748                 wxBusyCursor wait;
1749                 FillGridWithContoursInformation();
1750         }
1751
1752
1753         //------------------------------------------------------------------------------------------------------------
1754         void wxContourEventHandler::onSaveResults( wxCommandEvent& event )
1755         {
1756                 wxFileDialog dialog(_InformationContourFrame, _T("Choose a file"), _T(""), _T(""), _T("*.txt"), wxSAVE );
1757                 if (dialog.ShowModal() == wxID_OK)
1758                 {
1759                         onExtractInformation( event );
1760                         std::string directory=(const char *)(dialog.GetDirectory().mb_str());
1761                         std::string namefile=(const char *)(dialog.GetFilename().mb_str());
1762
1763                         SaveValuesXYZ( directory , namefile );
1764                         SaveImageResult( directory , namefile );
1765
1766                         std::string filename = (const char *)(dialog.GetPath().mb_str() );
1767                         FILE *pFile=fopen(filename.c_str(),"w+");
1768
1769                         int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
1770
1771                         wxString tmpString;
1772                         int i,j,maxX,maxY=sizeZ;
1773                         maxX=this->_grid->GetNumberCols();
1774
1775                         int iTitle,sizeTitle = (maxX / _numberOfVariablesStatistics);
1776                         for ( iTitle=0; iTitle<sizeTitle ; iTitle++)
1777                         {
1778                                 fprintf(pFile,"-- \t %d-Size \t SizeRange \t Min \t Max \t Ave \t StDv \t" , iTitle,tmpString.c_str() );
1779                         }
1780                         fprintf(pFile,"\n" );
1781
1782
1783
1784                         for ( j=0; j<maxY ; j++)
1785                         {
1786                                 fprintf(pFile,"%d\t" , j );
1787                                 for (i=0 ; i<maxX ; i++){
1788                                         tmpString = _grid->GetCellValue( j , i );
1789                                         fprintf(pFile,"%s\t" , (const char *)(tmpString.mb_str()) );
1790                                 } // for i
1791                                 fprintf(pFile,"\n"  );
1792                         } // for j
1793
1794                         fclose(pFile);
1795                 } // if  ShowModal
1796
1797
1798         }
1799
1800
1801         //------------------------------------------------------------------------------------------------------------
1802         void wxContourEventHandler::onInformationContourFrame()
1803         {
1804                 if (_InformationContourFrame==NULL)
1805                 {
1806                         _InformationContourFrame                                                = new wxFrame (_theViewPanel, -1,_T("  Information  "), wxDefaultPosition, wxDefaultSize, wxFRAME_TOOL_WINDOW|wxSYSTEM_MENU | wxCAPTION |  wxCLIP_CHILDREN |wxFRAME_FLOAT_ON_PARENT | wxRESIZE_BORDER  );
1807                         _InformationContourFrame->SetSize( wxSize(500,450) );
1808                         wxSize sizepanel(200,300);
1809                         wxPanel *panel                                                                  = getInformationPanel(_InformationContourFrame);
1810 //JCP 13-10-09  Grouping the panel in a method
1811                         /*new wxPanel(_InformationContourFrame,-1,wxDefaultPosition, wxDefaultSize,wxTAB_TRAVERSAL);
1812
1813                         wxString lstOptions[4];
1814                         lstOptions[0]=_T("Actual Slice");
1815                         lstOptions[1]=_T("Range Slices");
1816                         lstOptions[2]=_T("All Slices");
1817                         _informationRadiobox                                                    = new wxRadioBox(panel, -1, _T("Slice analysis"), wxDefaultPosition, wxSize(270,45), 3 , lstOptions,  3, wxRA_SPECIFY_COLS);
1818
1819                         wxString lstOptContOperation[5];
1820                         lstOptContOperation[0]=_T("AND");
1821                         lstOptContOperation[1]=_T("OR");
1822                         lstOptContOperation[2]=_T("XOR");
1823                         lstOptContOperation[3]=_T("ALL");
1824                         _radiolstboxContourGroup                                                = new wxRadioBox(panel, -1, _T("Contour group"), wxDefaultPosition, wxSize(270,45), 4 , lstOptContOperation,  4, wxRA_SPECIFY_COLS);
1825
1826                         wxButton *informationContourLabelsBtn                   = new wxButton(panel,-1,_T("Contour labels"),wxDefaultPosition, wxSize(140,35) );
1827                         informationContourLabelsBtn->SetEventHandler( this );
1828                         Connect( informationContourLabelsBtn->GetId(),          wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onInformationContourLabels ); 
1829
1830                         wxButton *statisticsContourBtn                                  = new wxButton(panel,-1,_T("Contour statistics"),wxDefaultPosition, wxSize(140,35) );
1831                         statisticsContourBtn->SetEventHandler( this );
1832                         Connect( statisticsContourBtn->GetId(),         wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onExtractInformation ); 
1833
1834                         wxButton *saveResultsBtn                                                = new wxButton(panel,-1,_T("Save statistics results"),wxDefaultPosition, wxSize(140,35) );
1835                         saveResultsBtn->SetEventHandler( this );
1836                         Connect( saveResultsBtn->GetId(),               wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSaveResults ); 
1837
1838
1839                         int sizeZ = this->_theViewPanel->getSceneManager()->GetImageDataSizeZ();                        
1840                         _mbarrangeSliceInformation                                      =  new mBarRange(panel,65,65);
1841                         _mbarrangeSliceInformation->SetMin(0);
1842                         _mbarrangeSliceInformation->SetStart(0);
1843                         _mbarrangeSliceInformation-> SetOrientation( true );
1844                         _mbarrangeSliceInformation-> setActiveStateTo(true);
1845                         _mbarrangeSliceInformation-> setVisibleLabels( true );
1846                         _mbarrangeSliceInformation-> setDeviceEndMargin(10);
1847                         _mbarrangeSliceInformation-> setRepresentedValues( 0 , sizeZ-1 );
1848                         _mbarrangeSliceInformation-> setDeviceBlitStart(10,10); 
1849                         _mbarrangeSliceInformation-> setIfWithActualDrawed( false );
1850                         _mbarrangeSliceInformation-> SetStart( 0 );
1851                         _mbarrangeSliceInformation-> SetEnd( sizeZ-1 );  
1852
1853
1854                         double range[2];
1855                         this->_theViewPanel->getSceneManager()->GetImageDataRange(range);
1856                         _mbarrangeRangeInformation                                      =  new mBarRange(panel,65,65);
1857                         _mbarrangeRangeInformation->SetMin(0);
1858                         _mbarrangeRangeInformation->SetStart(0);
1859                         _mbarrangeRangeInformation-> SetOrientation( true );
1860                         _mbarrangeRangeInformation-> setActiveStateTo(true);
1861                         _mbarrangeRangeInformation-> setVisibleLabels( true );
1862                         _mbarrangeRangeInformation-> setDeviceEndMargin(10);
1863                         _mbarrangeRangeInformation-> setRepresentedValues( range[0] , range[1] );
1864                         _mbarrangeRangeInformation-> setDeviceBlitStart(10,10); 
1865                         _mbarrangeRangeInformation-> setIfWithActualDrawed( false );
1866                         _mbarrangeRangeInformation-> SetStart( range[0] );
1867                         _mbarrangeRangeInformation-> SetEnd( range[1] );  
1868
1869
1870                         _staticTextInformation                                                  = new wxStaticText(panel,-1,_T("    "));
1871
1872
1873 //                      wxButton *XXXXXXXBtn                    = new wxButton(panel,-1,_T("Statistics"),wxDefaultPosition, wxSize(180,35) );
1874 //                      XXXXXXXBtn->SetEventHandler( this );
1875 //                      Connect( XXXXXXXBtn->GetId(),           wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onXXXXX ); 
1876
1877
1878                         _grid = new wxGrid( panel,
1879                        wxID_ANY,
1880                        wxPoint( 0, 0 ),
1881                        wxSize( 100, 100 ) );
1882
1883                         int i,gridCol=10,gridRow=sizeZ;
1884                         _grid->CreateGrid( 0, 0 );
1885                         _grid->AppendRows(gridRow);
1886                         _grid->AppendCols(gridCol);
1887
1888                         for (i=0;i<gridRow;i++)
1889                         {
1890                                 _grid->SetRowLabelValue(i, _T(" ") );
1891                         }
1892 //                      _grid->SetColLabelSize(0);
1893
1894
1895                         FillGridWithContoursInformation();
1896
1897                         wxFlexGridSizer * sizerA                = new wxFlexGridSizer(10);
1898                         sizerA->Add( _informationRadiobox                       , 1, wxALL ,2 );
1899                         sizerA->Add( _radiolstboxContourGroup           , 1, wxALL ,2 );
1900
1901                         wxFlexGridSizer * sizerB                = new wxFlexGridSizer(10);
1902                         sizerB->Add( informationContourLabelsBtn        , 1, wxALL ,2 );
1903                         sizerB->Add( statisticsContourBtn                       , 1, wxALL ,2 );
1904                         sizerB->Add( saveResultsBtn                                     , 1, wxALL ,2 );
1905
1906                         wxFlexGridSizer * sizer         = new wxFlexGridSizer(1);
1907                         sizer->AddGrowableCol(0);
1908                         sizer->AddGrowableRow(7);
1909                         sizer->Add( sizerA                                              , 1, wxALL              , 0 );
1910                         sizer->Add( new wxStaticText(panel              ,-1,_T("Slice Range"))  , 1, wxALL              , 0 );
1911                         sizer->Add( _mbarrangeSliceInformation  , 1, wxALL|wxGROW               , 2 );                  
1912                         sizer->Add( new wxStaticText(panel              ,-1,_T("Gray Range"))   , 1, wxALL              , 0 );
1913                         sizer->Add( _mbarrangeRangeInformation  , 1, wxALL|wxGROW               , 2 );                  
1914                         sizer->Add( sizerB                                              , 1, wxALL              , 0 );
1915                         sizer->Add( _staticTextInformation              , 1, wxALL              , 0 );
1916                         sizer->Add( _grid                                               , 1, wxEXPAND   , 0 );
1917
1918
1919
1920                         panel->SetSizer( sizer );
1921                         panel->SetSize( wxSize(1500,1500) );
1922                         //panel->SetBackgroundColour( wxColour(100,100,100) );
1923                         panel->SetAutoLayout( true );
1924                         panel->Layout();*/
1925
1926                         wxBoxSizer * sizerPanel         = new wxBoxSizer(wxHORIZONTAL);
1927
1928 //                      sizerPanel->AddGrowableCol(0);
1929 //                      sizerPanel->AddGrowableRow(0);
1930
1931 //JCP 14-10-09
1932                         //sizerPanel -> Add( sizer              , 1, wxEXPAND ,0);
1933                         sizerPanel -> Add( panel->GetSizer()            , 1, wxEXPAND ,0);
1934 //JCP 14-10-09
1935
1936
1937
1938                         _InformationContourFrame->SetSizer( sizerPanel );
1939                         _InformationContourFrame->SetAutoLayout( true );
1940                         _InformationContourFrame->Layout();
1941
1942                         _InformationContourFrame->Show();
1943                 } else {
1944                         if (_InformationContourFrame->IsShown()==true)
1945                         {
1946                                 _InformationContourFrame->Show(false);
1947                         } else  {
1948                                 FillGridWithContoursInformation();
1949                                 _InformationContourFrame->Show(true);
1950                         }
1951                 }
1952         }
1953
1954         wxPanel* wxContourEventHandler::getInformationPanel(wxWindow* parent){
1955         wxPanel *panel                                                                  = new wxPanel(parent,-1,wxDefaultPosition, wxDefaultSize,wxTAB_TRAVERSAL);
1956
1957                 wxString lstOptions[4];
1958                 lstOptions[0]=_T("Actual Slice");
1959                 lstOptions[1]=_T("Range Slices");
1960                 lstOptions[2]=_T("All Slices");
1961                 _informationRadiobox                                                    = new wxRadioBox(panel, -1, _T("Slice analysis"), wxDefaultPosition, wxSize(270,45), 3 , lstOptions,  3, wxRA_SPECIFY_COLS);
1962
1963                 wxString lstOptContOperation[5];
1964                 lstOptContOperation[0]=_T("AND");
1965                 lstOptContOperation[1]=_T("OR");
1966                 lstOptContOperation[2]=_T("XOR");
1967                 lstOptContOperation[3]=_T("ALL");
1968                 _radiolstboxContourGroup                                                = new wxRadioBox(panel, -1, _T("Contour group"), wxDefaultPosition, wxSize(270,45), 4 , lstOptContOperation,  4, wxRA_SPECIFY_COLS);
1969
1970                 wxButton *informationContourLabelsBtn                   = new wxButton(panel,-1,_T("Contour labels"),wxDefaultPosition, wxSize(140,35) );
1971                 informationContourLabelsBtn->SetEventHandler( this );
1972                 Connect( informationContourLabelsBtn->GetId(),          wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onInformationContourLabels ); 
1973
1974                 wxButton *statisticsContourBtn                                  = new wxButton(panel,-1,_T("Contour statistics"),wxDefaultPosition, wxSize(140,35) );
1975                 statisticsContourBtn->SetEventHandler( this );
1976                 Connect( statisticsContourBtn->GetId(),         wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onExtractInformation ); 
1977
1978                 wxButton *saveResultsBtn                                                = new wxButton(panel,-1,_T("Save statistics results"),wxDefaultPosition, wxSize(140,35) );
1979                 saveResultsBtn->SetEventHandler( this );
1980                 Connect( saveResultsBtn->GetId(),               wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSaveResults ); 
1981
1982
1983                 int sizeZ = this->_theViewPanel->getSceneManager()->GetImageDataSizeZ();                        
1984                 _mbarrangeSliceInformation                                      =  new mBarRange(panel,65,65);
1985                 _mbarrangeSliceInformation->SetMin(0);
1986                 _mbarrangeSliceInformation->SetStart(0);
1987                 _mbarrangeSliceInformation-> SetOrientation( true );
1988                 _mbarrangeSliceInformation-> setActiveStateTo(true);
1989                 _mbarrangeSliceInformation-> setVisibleLabels( true );
1990                 _mbarrangeSliceInformation-> setDeviceEndMargin(10);
1991                 _mbarrangeSliceInformation-> setRepresentedValues( 0 , sizeZ-1 );
1992                 _mbarrangeSliceInformation-> setDeviceBlitStart(10,10); 
1993                 _mbarrangeSliceInformation-> setIfWithActualDrawed( false );
1994                 _mbarrangeSliceInformation-> SetStart( 0 );
1995                 _mbarrangeSliceInformation-> SetEnd( sizeZ-1 );  
1996
1997
1998                 double range[2];
1999                 this->_theViewPanel->getSceneManager()->GetImageDataRange(range);
2000                 _mbarrangeRangeInformation                                      =  new mBarRange(panel,65,65);
2001                 _mbarrangeRangeInformation->SetMin(0);
2002                 _mbarrangeRangeInformation->SetStart(0);
2003                 _mbarrangeRangeInformation-> SetOrientation( true );
2004                 _mbarrangeRangeInformation-> setActiveStateTo(true);
2005                 _mbarrangeRangeInformation-> setVisibleLabels( true );
2006                 _mbarrangeRangeInformation-> setDeviceEndMargin(10);
2007                 _mbarrangeRangeInformation-> setRepresentedValues( range[0] , range[1] );
2008                 _mbarrangeRangeInformation-> setDeviceBlitStart(10,10); 
2009                 _mbarrangeRangeInformation-> setIfWithActualDrawed( false );
2010                 _mbarrangeRangeInformation-> SetStart( range[0] );
2011                 _mbarrangeRangeInformation-> SetEnd( range[1] );  
2012
2013
2014                 _staticTextInformation                                                  = new wxStaticText(panel,-1,_T("    "));
2015
2016
2017 //                      wxButton *XXXXXXXBtn                    = new wxButton(panel,-1,_T("Statistics"),wxDefaultPosition, wxSize(180,35) );
2018 //                      XXXXXXXBtn->SetEventHandler( this );
2019 //                      Connect( XXXXXXXBtn->GetId(),           wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onXXXXX ); 
2020
2021
2022                 _grid = new wxGrid( panel,
2023                     wxID_ANY,
2024                     wxPoint( 0, 0 ),
2025                     wxSize( 100, 100 ) );
2026
2027                 int i,gridCol=10,gridRow=sizeZ;
2028                 _grid->CreateGrid( 0, 0 );
2029                 _grid->AppendRows(gridRow);
2030                 _grid->AppendCols(gridCol);
2031
2032                 for (i=0;i<gridRow;i++)
2033                 {
2034                         _grid->SetRowLabelValue(i, _T(" ") );
2035                 }
2036 //                      _grid->SetColLabelSize(0);
2037
2038
2039                 FillGridWithContoursInformation();
2040
2041                 wxFlexGridSizer * sizerA                = new wxFlexGridSizer(10);
2042                 sizerA->Add( _informationRadiobox                       , 1, wxALL ,2 );
2043                 sizerA->Add( _radiolstboxContourGroup           , 1, wxALL ,2 );
2044
2045                 wxFlexGridSizer * sizerB                = new wxFlexGridSizer(10);
2046                 sizerB->Add( informationContourLabelsBtn        , 1, wxALL ,2 );
2047                 sizerB->Add( statisticsContourBtn                       , 1, wxALL ,2 );
2048                 sizerB->Add( saveResultsBtn                                     , 1, wxALL ,2 );
2049
2050                 wxFlexGridSizer * sizer         = new wxFlexGridSizer(1);
2051                 sizer->AddGrowableCol(0);
2052                 sizer->AddGrowableRow(7);
2053                 sizer->Add( sizerA                                              , 1, wxALL              , 0 );
2054                 sizer->Add( new wxStaticText(panel              ,-1,_T("Slice Range"))  , 1, wxALL              , 0 );
2055                 sizer->Add( _mbarrangeSliceInformation  , 1, wxALL|wxGROW               , 2 );                  
2056                 sizer->Add( new wxStaticText(panel              ,-1,_T("Gray Range"))   , 1, wxALL              , 0 );
2057                 sizer->Add( _mbarrangeRangeInformation  , 1, wxALL|wxGROW               , 2 );                  
2058                 sizer->Add( sizerB                                              , 1, wxALL              , 0 );
2059                 sizer->Add( _staticTextInformation              , 1, wxALL              , 0 );
2060                 sizer->Add( _grid                                               , 1, wxEXPAND   , 0 );
2061
2062
2063
2064                 panel->SetSizer( sizer );
2065                 panel->SetSize( wxSize(1500,1500) );
2066                 //panel->SetBackgroundColour( wxColour(100,100,100) );
2067                 panel->SetAutoLayout( true );
2068                 panel->Layout();
2069                 return panel;
2070         }
2071         //------------------------------------------------------------------------------------------------------------
2072         void wxContourEventHandler :: onSpreadInDepth( std::vector<std::string> & keyNamesVector )
2073         {
2074                 
2075         }
2076         //------------------------------------------------------------------------------------------------------------
2077         void wxContourEventHandler :: onOutline_Union_Of( std::vector<std::string> & keyNamesVector )
2078         {
2079                 
2080         }
2081         //------------------------------------------------------------------------------------------------------------
2082         void wxContourEventHandler :: onOutline_Intersection_Of( std::vector<std::string> & keyNamesVector )
2083         {
2084                 
2085         }
2086         //------------------------------------------------------------------------------------------------------------
2087         void wxContourEventHandler :: onOutline_Combination_Of( std::vector<std::string> & keyNamesVector )
2088         {
2089                 
2090         }
2091         //------------------------------------------------------------------------------------------------------------
2092         void wxContourEventHandler :: onOutline_Fragmentation_Of( std::vector<std::string> & keyNamesVector )
2093         {
2094                 
2095         }
2096         //------------------------------------------------------------------------------------------------------------
2097         void wxContourEventHandler :: onOutline_Agrupation_Of( std::vector<std::string> & keyNamesVector )
2098         {
2099                 
2100         }
2101         //------------------------------------------------------------------------------------------------------------
2102         void wxContourEventHandler :: onCopyOutlines( std::vector<std::string> & keyNamesVector )
2103         {
2104                 std::vector<int> tempVector;
2105                 _instantPanel->getInstant( tempVector );
2106         _performingOperation->reset();
2107                 _performingOperation->setStartCommand( (char)wxContour_ActionCommandsID::COPY_TOOL );
2108                 _performingOperation->setStartOperationInstantVector( tempVector );
2109                 _performingOperation->setKeyNamesOperationElems( keyNamesVector );
2110
2111         }
2112         //------------------------------------------------------------------------------------------------------------
2113         void wxContourEventHandler :: onPasteOutlines( )
2114         {
2115                 char theStartCommand = _performingOperation->getStartCommand();
2116                 if (  theStartCommand == wxContour_ActionCommandsID::COPY_TOOL )
2117                 {
2118                         //JCP 20-10-08 Undo redo implementation
2119                         saveState();
2120                         //JCP 20-10-08 Undo redo implementation
2121
2122
2123                         std::vector<int> tempVector;
2124                         _instantPanel->getInstant( tempVector );
2125                         _performingOperation->setEndOperationInstantVector ( tempVector );
2126                         std::vector<std::string> elems = _performingOperation->getKeyNamesOperationElems();
2127                         int i,size = elems.size();                      
2128                         for( i=0; i<size; i++ )
2129                         {                               
2130                                 createCopyContourOf( elems[i], tempVector, i>0 );
2131                         }
2132
2133                         
2134                 }
2135                 int fin = 0;
2136         }
2137         //------------------------------------------------------------------------------------------------------------
2138         void wxContourEventHandler :: onShowOutlines( std::vector<std::string> & keyNamesVector )
2139         {
2140                 
2141         }
2142         //------------------------------------------------------------------------------------------------------------
2143         void wxContourEventHandler :: onHideOutlines( std::vector<std::string> & keyNamesVector )
2144         {
2145                 
2146         }
2147         //------------------------------------------------------------------------------------------------------------
2148         void wxContourEventHandler :: onSelectOutlines( std::vector<std::string> & keyNamesVector )
2149         {
2150                 //if( keyNamesVector.empty() )
2151                 {
2152                         _theViewPanel->getSceneManager()->drawSelectionROI( );
2153                 }
2154                 /*else
2155                 {
2156                         int ok = keyNamesVector.size();
2157                         _theViewPanel->getSceneManager()->selectObjects( keyNamesVector );
2158                         std::string name = keyNamesVector[0];                   
2159                 }*/
2160                 /*
2161                 _theViewPanel->getSceneManager()->drawSelectionROI( );
2162                 std::vector<std::string> currentSelection = _theViewPanel->getSceneManager()->getSelectedObjects();
2163                 int ok = currentSelection.size();
2164                 _theViewPanel->getSceneManager()->selectObjects( currentSelection );*/
2165         }
2166         //------------------------------------------------------------------------------------------------------------
2167         void wxContourEventHandler :: onEditOutlines( std::vector<std::string> & keyNamesVector )
2168         {
2169                 
2170         }
2171         //------------------------------------------------------------------------------------------------------------
2172         
2173         //------------------------------------------------------------------------------------------------------------
2174         void wxContourEventHandler :: deleteContour( std::string theKeyName )
2175         {
2176                 manualContourModel                      * cModel;
2177                 manualViewBaseContour           * cViewer;
2178                 manualContourBaseControler      * cControler;
2179
2180                 ContourWrap_ViewControl *conwrapviewControl =  _theViewPanel->getSceneManager()->getContourWrap_ViewControlOf( theKeyName );
2181                 cControler      = conwrapviewControl->getControler();
2182                 int ispartofstaticlst= _modelManager->IsPartOfStaticList(theKeyName);
2183                 if ((cControler!=NULL) && (cControler->IsEditable()==false)  && (ispartofstaticlst==-1) )
2184                 {
2185                         _theViewPanel->getSceneManager()->removeFromScene( theKeyName );
2186                         cModel          = _modelManager->getOutlineByKeyName(theKeyName)->getModel();
2187                         _modelManager->removeOutline( theKeyName );
2188                         cViewer         = conwrapviewControl->getViewer();
2189                         _theViewPanel->getSceneManager()->removeWrap( theKeyName );
2190 //EED Borrame
2191 //FILE *ff = fopen("c:/temp/wxVtkBaseView_SceneManagerStadistics.txt","a+");
2192 //fprintf(ff,"EED wxContourEventHandler::deleteContours() \n" );
2193 //fprintf(ff,"    %s %p\n",keyNamesVector[i].c_str(),  cControler );
2194 //fclose(ff);
2195                         delete cModel;
2196                         delete cViewer;
2197                         delete cControler;
2198                 } // if editable
2199         }
2200
2201         //------------------------------------------------------------------------------------------------------------
2202         void wxContourEventHandler :: deleteContours( std::vector<std::string>  keyNamesVector )
2203         {
2204                 int i,size=keyNamesVector.size();
2205                 for (i=0;i<size;i++)
2206                 {
2207                         deleteContour( keyNamesVector[i] );
2208                 }
2209         }
2210
2211         //------------------------------------------------------------------------------------------------------------
2212         void wxContourEventHandler :: deleteAllContours(  )
2213         {               
2214                 wxBusyCursor wait;
2215                 std::vector<int> tempVector;
2216                 _instantPanel->getInstant( tempVector );
2217
2218 //JCP --08-09-2008 When using a diferent interface the _mbarrangeDeleteAll might not be initialize
2219 //              the values in GetStart and GetEnd will then not be initialize also.
2220 //              We use instead the values given when initializing the _deletepanel.
2221
2222                 //int minZ = _mbarrangeDeleteAll->GetStart();
2223                 //int maxZ = _mbarrangeDeleteAll->GetEnd();
2224                 int minZ, maxZ;
2225                 
2226                 minZ = 0;
2227                 maxZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
2228                 
2229 //JCP --08-09-2008
2230                 
2231                 _theViewPanel->getSceneManager()->removeSceneContours( );
2232                         _modelManager->removeAllOutlines();
2233                         _theViewPanel->getSceneManager()->removeAllOutlines();
2234 //JCP --08-09-2008
2235                 /*
2236                 if ( (minZ==0) && (maxZ==_mbarrangeDeleteAll->GetMax() ))
2237                 {
2238                         _theViewPanel->getSceneManager()->removeSceneContours( );
2239                         _modelManager->removeAllOutlines();
2240                         _theViewPanel->getSceneManager()->removeAllOutlines();
2241
2242                 } else {
2243                         for ( z=minZ ; z<=maxZ ; z++)
2244                         {
2245                                 tempVector[1]=z;
2246                                 Instant instant(&tempVector);
2247                                 std::vector<ContourThing**> lstContourThings = this->_modelManager->getOutlinesAtInstant( &instant );
2248
2249                                 sizeLstContourThings = lstContourThings.size();
2250                                 for (ii=0 ; ii<sizeLstContourThings ; ii++)
2251                                 {
2252                                         ContourThing **contourthing = lstContourThings[ii];
2253                                         deleteContour( (*contourthing)->getName() );
2254                                 } //for ii
2255                         }// for z
2256                 } // if 
2257         JCP --08-09-2008 */
2258         }
2259
2260         //------------------------------------------------------------------------------------------------------------
2261         void wxContourEventHandler::openContours( FILE *pFile, bool staticContour )
2262         {
2263                 char tmp[255];
2264                 fscanf(pFile,"%s",tmp); // NumberOfContours 
2265                 fscanf(pFile,"%s",tmp); // ##
2266                 int numberOfContours = atoi(tmp);  
2267
2268                 std::vector<int> instantVector;
2269                 int typeContourModel;
2270                 manualContourModel *manModelContour;
2271                 int typeView;
2272
2273                 int i;
2274                 for (i=0;i<numberOfContours;i++)
2275                 {
2276                         instantVector.clear();
2277                         fscanf(pFile,"%s",tmp); // Instant
2278
2279                         fscanf(pFile,"%s",tmp); // 1
2280                         instantVector.push_back( atoi(tmp) );
2281                         fscanf(pFile,"%s",tmp); // 2
2282                         instantVector.push_back( atoi(tmp) );
2283                         fscanf(pFile,"%s",tmp); // 3
2284                         instantVector.push_back( atoi(tmp) );
2285                         fscanf(pFile,"%s",tmp); // 4
2286                         instantVector.push_back( atoi(tmp) );
2287                         fscanf(pFile,"%s",tmp); // 5
2288                         instantVector.push_back( atoi(tmp) );
2289                         fscanf(pFile,"%s",tmp); // 6
2290                         instantVector.push_back( atoi(tmp) );
2291
2292
2293                         fscanf(pFile,"%s",tmp); // TypeContourModel
2294                         fscanf(pFile,"%s",tmp); // ##
2295                         typeContourModel = atoi(tmp);
2296
2297                         manModelContour =  factoryManualContourModel(typeContourModel);
2298                         manModelContour->Open(pFile);
2299
2300                         fscanf(pFile,"%s",tmp); // TypeView
2301                         fscanf(pFile,"%s",tmp); // ##
2302                         typeView = atoi(tmp);  
2303
2304
2305 //                      if (typeView==1) 
2306 //                      {
2307 //                      }
2308
2309
2310                         std::string theName;
2311                         theName = _modelManager->createOutline( manModelContour, instantVector );
2312                         bool addedModel = theName.compare("") != 0;
2313                         if( addedModel )
2314                         {
2315                                 double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
2316                                 this->_theViewPanel->getSpacing(spc);                                   
2317                                 //Adding the manualContourControler to interface objects structure
2318                                 //Adding the manualViewContour to interface objects structure           
2319                                 //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
2320                                 _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeView) ;
2321                         }       
2322
2323                         if (staticContour==true)
2324                         {
2325                                 Instant instant(&instantVector);
2326                                 changeContourOfManager( theName , &instant );
2327                         }
2328
2329                 }// for  numberOfContours
2330
2331
2332
2333         }
2334
2335         //------------------------------------------------------------------------------------------------------------
2336         void wxContourEventHandler::openFileWithContours()
2337         {
2338                 char tmp[255];
2339                 wxFileDialog dialog(NULL, _T("Choose a file"), _T(""), _T(""), _T("*.roi"), wxOPEN );
2340                 if (dialog.ShowModal() == wxID_OK)
2341                 {
2342                         fileNameContourROI = (const char *)(dialog.GetPath().mb_str());
2343                         FILE *pFile=fopen(fileNameContourROI.c_str(),"r+");
2344
2345                         fscanf(pFile,"%s",tmp); // --CreaContour--
2346
2347                         fscanf(pFile,"%s",tmp); // Version
2348                         fscanf(pFile,"%s",tmp); // 1.0.1
2349                         std::string version(tmp);
2350
2351                         openContours(pFile,false);
2352                         if (version!="1.0.0"){
2353                                 openContours(pFile,true);
2354                         }
2355 //                        _theViewPanel->getSceneManager()->openFileWithContours(ff);
2356
2357                         fclose(pFile);
2358                 }
2359                 _theViewPanel->getSceneManager()->removeSceneContours();
2360                 changeInstant();
2361                 //updateInstantOutlines();
2362         }
2363
2364
2365         //------------------------------------------------------------------------------------------------------------
2366         void wxContourEventHandler::saveFileWithContours( std::string filename )
2367         {
2368                 FILE *pFile=fopen(filename.c_str(),"w+");
2369                 std::vector< std::string > lstNameThings;
2370                 int i,sizeLstNameThings; 
2371
2372                 fprintf(pFile,"--CreaContour--\n");
2373                 fprintf(pFile,"Version %s\n", "1.0.1" );
2374
2375                 // Normal Contours
2376                 lstNameThings           = _modelManager->GetLstNameThings();
2377                 sizeLstNameThings       = lstNameThings.size(); 
2378                 fprintf(pFile,"NumberOfContours %d\n", sizeLstNameThings );
2379                 for (i=0 ; i<sizeLstNameThings ; i++) 
2380                 {
2381                         _modelManager->SaveThingName( pFile, lstNameThings[i] );
2382                         _theViewPanel->getSceneManager()->SaveThingName( pFile, lstNameThings[i] );
2383                 }// for i
2384
2385                 //-- Contours Statics 
2386                 lstNameThings           = _modelManager->GetLstNameThingsStatic();
2387                 sizeLstNameThings       = lstNameThings.size(); 
2388                 fprintf(pFile,"NumberOfContoursStatic %d\n", sizeLstNameThings );
2389                 for (i=0 ; i<sizeLstNameThings ; i++) 
2390                 {
2391                         _modelManager->SaveThingName( pFile, lstNameThings[i] );
2392                         _theViewPanel->getSceneManager()->SaveThingName( pFile, lstNameThings[i] );
2393                 }// for i
2394                 fclose(pFile);
2395         }
2396
2397
2398         //----------------------------------------------------------
2399
2400         void wxContourEventHandler::saveFileWithContours()
2401         {
2402                 wxFileDialog dialog(NULL, _T("Choose a file"), _T(""), _T(""), _T("*.roi"), wxSAVE );
2403                 if (dialog.ShowModal() == wxID_OK)
2404                 {
2405                         fileNameContourROI = (const char *)(dialog.GetPath().mb_str());
2406                         saveFileWithContours( fileNameContourROI );
2407                 } // if  ShowModal
2408         } 
2409
2410         //------------------------------------------------------------------------------------------------------------
2411         void wxContourEventHandler :: saveFileWithContoursAutomatique()
2412         {
2413                 if (fileNameContourROI=="")
2414                 {
2415                         saveFileWithContours();
2416                 } else {
2417                         saveFileWithContours(fileNameContourROI);
2418                 }
2419         }
2420
2421
2422         //------------------------------------------------------------------------------------------------------------
2423         void wxContourEventHandler :: createCopyContourOf ( std::string anExistingKName, std::vector<int> &instantNoTouchData, bool append )
2424         {
2425                 std::string cloneName = _modelManager->createCopyContourOf( anExistingKName, instantNoTouchData );
2426                 manualContourModel * manualModel = _modelManager->getOutlineByKeyName( cloneName )->getModel();
2427                 _theViewPanel->getSceneManager()->createCopyContourOf( anExistingKName, cloneName, manualModel , append );
2428         }
2429
2430
2431         //------------------------------------------------------------------------------------------------------------
2432         manualContourModel * wxContourEventHandler::factoryManualContourModel(int typeContour)
2433         {       
2434                 manualContourModel *manModelContour=NULL;
2435
2436                 // spline
2437                 if (typeContour==0)
2438                 {
2439                         manModelContour = new manualContourModel();
2440                 }
2441
2442                 // spline
2443                 if (typeContour==1)
2444                 {
2445                         manModelContour = new manualContourModel();
2446                 }
2447
2448                 // rectangle
2449                 if (typeContour==2)
2450                 {
2451                         manModelContour = new manualContourModelRoi();
2452                 }
2453
2454                 // circle
2455                 if (typeContour==3)
2456                 {
2457                         manModelContour = new manualContourModelCircle();
2458                 }
2459
2460                 // BullEye / star
2461                 if (typeContour==4)
2462                 {
2463                         manualContourModelBullEye *manModelContourBullEye = new manualContourModelBullEye();
2464                         manModelContour = manModelContourBullEye;
2465                         if (_panelBullEyeOptions!=NULL){
2466                                 int iCrown,sizeCrowns,iSector,sizeSectors;
2467                                 double radioA,radioB,ang,angDelta ;
2468                                 sizeCrowns = _panelBullEyeOptions->GetNumberOfCrowns();
2469                                 for ( iCrown=0 ; iCrown<sizeCrowns ; iCrown++ )
2470                                 {
2471                                         sizeSectors = _panelBullEyeOptions->GetNumberOfSections(iCrown);
2472                                         radioB  = _panelBullEyeOptions->GetRadioOfCrown(iCrown);
2473                                         if (iCrown==sizeCrowns-1)
2474                                         {
2475                                                 radioA  = 0;
2476                                         } else {
2477                                                 radioA  = _panelBullEyeOptions->GetRadioOfCrown(iCrown+1);
2478                                         }
2479                                         radioA=radioA/100.0;
2480                                         radioB=radioB/100.0;
2481                                         for ( iSector=0 ; iSector<sizeSectors  ; iSector++ )
2482                                         {
2483                                                 ang             = _panelBullEyeOptions->GetAngOfCrownSection(iCrown,iSector);
2484                                                 angDelta= _panelBullEyeOptions->GetAngDeltaOfCrownSection(iCrown);                                      
2485                                                 manModelContourBullEye->AddSector(radioA,radioB,ang,angDelta);
2486                                         } // for iSector
2487                                 } // for iCrown
2488                         } // if _panelBullEyeOptions
2489                 }// if typeContour==4
2490
2491                 return manModelContour;
2492         }
2493
2494         //------------------------------------------------------------------------------------------------------------
2495         void wxContourEventHandler :: createContour( int typeContour )
2496         {
2497                 //Creating the manualContourModel and including in the model
2498                 manualContourModel * manModelContour = factoryManualContourModel(typeContour);
2499                 std::vector<int> instantVector;
2500                 _instantPanel->getInstant( instantVector );
2501                 std::string theName;
2502                 theName= _modelManager->createOutline( manModelContour, instantVector );
2503                 bool addedModel = theName.compare("") != 0;//??
2504                 if( addedModel )
2505                 {
2506                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
2507                         this->_theViewPanel->getSpacing(spc);
2508                         //Adding the manualContourControler to interface objects structure
2509                         //Adding the manualViewContour to interface objects structure           
2510                         //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
2511                         _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , typeContour) ;
2512                 }       
2513
2514 //EED Borrame
2515 //FILE *ff = fopen("c:/temp/wxVtkBaseView_SceneManagerStadistics.txt","a+");
2516 //fprintf(ff,"EED wxContourEventHandler::createContour() \n" );
2517 //fprintf(ff,"    %s\n %p ",theName.c_str() ,  );
2518 //fclose(ff);
2519
2520
2521         }
2522         manualContourModel * wxContourEventHandler::factoryManualContourModel(PanelBullEyeOptions* panel){
2523
2524                 manualContourModelBullEye *manModelContourBullEye = new manualContourModelBullEye();
2525                 manualContourModel *manModelContour=NULL;
2526                 manModelContour = manModelContourBullEye;
2527                 if (panel!=NULL){
2528                         int iCrown,sizeCrowns,iSector,sizeSectors;
2529                         double radioA,radioB,ang,angDelta ;
2530                         sizeCrowns = panel->GetNumberOfCrowns();
2531                         for ( iCrown=0 ; iCrown<sizeCrowns ; iCrown++ )
2532                         {
2533                                 sizeSectors = panel->GetNumberOfSections(iCrown);
2534                                 radioB  = panel->GetRadioOfCrown(iCrown);
2535                                 if (iCrown==sizeCrowns-1)
2536                                 {
2537                                         radioA  = 0;
2538                                 } else {
2539                                         radioA  = panel->GetRadioOfCrown(iCrown+1);
2540                                 }
2541                                 radioA=radioA/100.0;
2542                                 radioB=radioB/100.0;
2543                                 for ( iSector=0 ; iSector<sizeSectors  ; iSector++ )
2544                                 {
2545                                         ang             = panel->GetAngOfCrownSection(iCrown,iSector);
2546                                         angDelta= panel->GetAngDeltaOfCrownSection(iCrown);                                     
2547                                         manModelContourBullEye->AddSector(radioA,radioB,ang,angDelta);
2548                                 } // for iSector
2549                         } // for iCrown
2550                 } // if _panelBullEyeOptions
2551                 
2552                 return manModelContour;
2553         }
2554
2555         void wxContourEventHandler :: createContourBullsEye(PanelBullEyeOptions* panel )
2556         {
2557                 //Creating the manualContourModel and including in the model
2558                 manualContourModel * manModelContour = factoryManualContourModel(panel );
2559                 std::vector<int> instantVector;
2560                 _instantPanel->getInstant( instantVector );
2561                 std::string theName;
2562                 theName= _modelManager->createOutline( manModelContour, instantVector );
2563                 bool addedModel = theName.compare("") != 0;
2564                 if( addedModel )
2565                 {
2566                         double spc[3];//Si no hay imagen pero hay contornos que spacing se pone por default
2567                         this->_theViewPanel->getSpacing(spc);                                   
2568                         //Adding the manualContourControler to interface objects structure
2569                         //Adding the manualViewContour to interface objects structure           
2570                         //_theViewPanel->getSceneManager()->setControlActiveStateOfALL( false );//This call is being done here because if the ROI is created underneath the previously created ROIS will still be active.
2571                         _theViewPanel->getSceneManager()->configureViewControlTo( theName, manModelContour,spc , 4) ;
2572                 }       
2573
2574 //EED Borrame
2575 //FILE *ff = fopen("c:/temp/wxVtkBaseView_SceneManagerStadistics.txt","a+");
2576 //fprintf(ff,"EED wxContourEventHandler::createContour() \n" );
2577 //fprintf(ff,"    %s\n %p ",theName.c_str() ,  );
2578 //fclose(ff);
2579
2580
2581         }
2582
2583         //------------------------------------------------------------------------------------------------------------
2584         //  Attributes getters and setters
2585         //------------------------------------------------------------------------------------------------------------
2586
2587         void wxContourEventHandler :: setModelManager( OutlineModelManager * theModelManager )
2588         {
2589                 _modelManager = theModelManager;
2590                 _workSpace = _modelManager->getContourWorkspace();
2591         }
2592         //------------------------------------------------------------------------------------------------------------  
2593         void wxContourEventHandler :: setViewPanel(  wxContourViewPanel * theViewPanel )
2594         {
2595                 _theViewPanel = theViewPanel;
2596                 //_theViewPanel->setWxEventHandler( this );
2597
2598                 /*double spc[3];
2599                 this->_theViewPanel->getSpacing(spc);
2600                 _sceneManager           = new wxVtkBaseView_SceneManager ( this->_theViewPanel->getWxVtkBaseView(), this, spc  );
2601                 
2602                 Connect( _theViewPanel->GetId(), wxINSTANT_CHANGE, (wxObjectEventFunction) (wxCommandEventFunction)  &wxContourEventHandler::onChangeInstant );
2603         Connect( wxID_ANY, wxEVT_START_CREATE_MULT_ROI, (wxObjectEventFunction) (wxCommandEventFunction)  &wxContourEventHandler::onCreateMultipleROI );
2604                 Connect( wxID_ANY, wxEVT_START_CREATE_ROI, (wxObjectEventFunction) (wxCommandEventFunction)  &wxContourEventHandler::onCreateROI );
2605                 Connect( wxID_ANY, wxEVT_STOP_CREATE_ROI, (wxObjectEventFunction) (wxCommandEventFunction)  &wxContourEventHandler::onStopCreateROI );
2606                 Connect( wxID_ANY, wxEVT_CHANGED_DEEP, (wxObjectEventFunction) (wxCommandEventFunction)  &wxContourEventHandler::onChangedDeep );
2607                 Connect( wxID_ANY,  wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler :: onActionButtonPressed ); */
2608
2609                 
2610         }
2611
2612         //------------------------------------------------------------------------------------------------------------
2613         void wxContourEventHandler :: setInstantChooserPanel(  wxInstantChooserPanel * theInstantChooserPanel )
2614         {
2615                 _instantPanel = theInstantChooserPanel;
2616                 //_instantPanel->setWxEventHandler( this );
2617
2618                 //Connect( _instantPanel->GetId(), wxINSTANT_CHOOSER_CHANGE, (wxObjectEventFunction) (wxCommandEventFunction)  &wxContourEventHandler::onChangeInstant );
2619
2620                 std::vector<int> vect;
2621                 _instantPanel->getInstant( vect );
2622                 _actualInstant = new Instant( &vect );
2623
2624                 if( _modelManager!=NULL )
2625                 {               
2626                         std::vector<std::string> conceptNameVect;
2627                         std::vector<int> conceptSizeVect;
2628                         _modelManager-> getConceptsInformation(conceptNameVect, conceptSizeVect);
2629                         int i=0;
2630                         int max = conceptNameVect.size();                       
2631                         for( ; i<max; i++)
2632                         {
2633                                 if( conceptNameVect[i].compare("Axe Depth") == 0 )
2634                                 {
2635                                         _instantPanel->addConcept( conceptNameVect[i], 0, conceptSizeVect[i], 1);                                       
2636                                 } else {
2637                                         _instantPanel->addConcept( conceptNameVect[i], 1, conceptSizeVect[i], 1);
2638                                 } // if
2639                         } // for                
2640                 } else {
2641                         //Should be configured later, or abort program, because Model -NEEDS- to be added before chooserPanel
2642                 }
2643                 if( _theViewPanel!=NULL )
2644                 {
2645                         double val = _theViewPanel->getCurrentDeep();
2646                         _instantPanel->setConceptValue( "Axe Depth", (int)val );
2647                         //JCP _instantPanel->setConceptValue("time", num de imagenes);
2648                         ConceptDataWrap * data = _instantPanel->getConceptDataOf( "Axe Depth" );
2649                         changeInstant();                        
2650                         _theViewPanel->setVerticalConcept( "Axe Depth", data->getMinValue(), data->getMaxValue(), data->getMinShowedValue(),  data->getMaxShowedValue(), data->getActualValue() );                      
2651                 } else {
2652                         //Should be configured later, or abort program, because ViewPanel -NEEDS- to be added before chooserPanel
2653                 }// if
2654         } 
2655
2656
2657         //------------------------------------------------------------------------------------------------------------
2658         void wxContourEventHandler :: setButtonsBar(  wxContour_ButtonsBar * theButtonsBar )
2659         {
2660                 _buttonsBar = theButtonsBar;
2661                 _buttonsBar->setWxEventHandler( this );
2662                 Connect( _buttonsBar->GetId(),   wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler:: onActionButtonPressed );               
2663         }
2664         //------------------------------------------------------------------------------------------------------------
2665         void wxContourEventHandler :: setGrid(  wxContour_Grid * theGridPanel )
2666         {
2667                 _gridPanel = theGridPanel;
2668         }
2669         //------------------------------------------------------------------------------------------------------------
2670         void wxContourEventHandler :: setDrawToolsPanel(  wxContour_DrawToolsPanel * theDrawToolsPanel )
2671         {
2672                 _drawToolsPanel = theDrawToolsPanel;
2673         }
2674         //------------------------------------------------------------------------------------------------------------
2675         void wxContourEventHandler :: setOperationsToolsPanel(  wxContour_OperationsToolsPanel * theOperationsToolsPanel )
2676         {       
2677                 _operationsToolsPanel = theOperationsToolsPanel;
2678         }
2679         //------------------------------------------------------------------------------------------------------------
2680         void wxContourEventHandler :: setAutomaticFormsPanel(  wxContour_AutomaticFormsToolsPanel * theAutoFormsPanel )
2681         {
2682                 _autoFormsPanel = theAutoFormsPanel;
2683         }
2684
2685         void wxContourEventHandler :: setStandardToolsPanel(  wxContour_StandardToolsPanel * theStandardToolsPanel )
2686         {
2687                 _standardToolsPanel= theStandardToolsPanel;
2688         }
2689         //------------------------------------------------------------------------------------------------------------
2690         void wxContourEventHandler :: setEditionToolsPanel(  wxContour_EdtionToolsPanel * theEditionToolsPanel )
2691         {
2692                 _editionToolsPanel =  theEditionToolsPanel;
2693         }
2694
2695         //------------------------------------------------------------------------------------------------------------
2696         void wxContourEventHandler :: setListViewPanel(  wxContour_ListViewPanel * theListViewPanel )
2697         {
2698                 _listViewPanel = theListViewPanel;
2699         }
2700         //------------------------------------------------------------------------------------------------------------
2701         //  Other functional methods
2702         //------------------------------------------------------------------------------------------------------------
2703
2704
2705         //------------------------------------------------------------------------------------------------------------
2706         void wxContourEventHandler::onDeleteContour( wxCommandEvent& event )
2707         {
2708                 
2709                 //JCP 20-10-08 Undo redo implementation
2710                 saveState();
2711                 //JCP 20-10-08 Undo redo implementation
2712
2713
2714                 int i,size=_theViewPanel->getSceneManager()->getSelectedObjects().size();
2715                 for(i=0;i<size;i++)
2716                 {
2717                         std::string keyName             = _theViewPanel->getSceneManager()->getSelectedObjects()[i];
2718                         int ispartofstaticlist  = this->_modelManager->IsPartOfStaticList( keyName );
2719                         if ( ispartofstaticlist>=0 )
2720                         {
2721                                 std::vector<int> tempVector;
2722                                 _instantPanel->getInstant( tempVector );
2723                                 Instant instant(&tempVector);
2724                                 this->_modelManager->ChangeContourOfList(keyName, &instant);
2725                         }
2726                 }
2727
2728                 std::vector<std::string> lstKeyName;
2729                 std::vector<std::string> lstKeyNameActualSlice;
2730                 std::vector<std::string> lstKeyNameToBeErase;
2731
2732                 lstKeyNameToBeErase             = _theViewPanel->getSceneManager()->getSelectedObjects();
2733                 lstKeyNameActualSlice   = _theViewPanel->getSceneManager()->GetlstContoursNameActualSlice();
2734                 int k,kSize=lstKeyNameToBeErase.size();
2735                 int j,jSize=lstKeyNameActualSlice.size();
2736                 bool ok;
2737                 for (k=0;k<kSize; k++)
2738                 {
2739                         ok=false;
2740                         for (j=0;j<jSize; j++)
2741                         {
2742                                 if (lstKeyNameToBeErase[k]==lstKeyNameActualSlice[j])
2743                                 { 
2744                                         ok=true;
2745                                 }
2746                         } // for j
2747                         if (ok==true)
2748                         {
2749                                 lstKeyName.push_back( lstKeyNameToBeErase[k] );
2750                         } // if ok
2751                 } // for k
2752
2753                 deleteContours( lstKeyName );
2754
2755                 
2756         }
2757
2758         //------------------------------------------------------------------------------------------------------------
2759         void wxContourEventHandler::onDeleteContoursActSlice( wxCommandEvent& event )
2760         {
2761                 //JCP 20-10-08 Undo redo implementation
2762                 saveState();
2763                 //JCP 20-10-08 Undo redo implementation
2764                 deleteContours( (std::vector<std::string>)_theViewPanel->getSceneManager()->GetlstContoursNameActualSlice() );
2765
2766                 
2767         }
2768
2769         //------------------------------------------------------------------------------------------------------------
2770         void wxContourEventHandler::onDeleteAllContours( wxCommandEvent& event )        
2771         {
2772                 //JCP 20-10-08 Undo redo implementation
2773                 saveState();
2774                 //JCP 20-10-08 Undo redo implementation
2775                 deleteAllContours(  );
2776
2777                 
2778         }
2779
2780                 //------------------------------------------------------------------------------------------------------------
2781         void wxContourEventHandler :: onDeleteFrame( )
2782         {
2783                 if (_deleteFrame==NULL)
2784                 {
2785                         _deleteFrame                                            = new wxFrame (_theViewPanel, -1,_T("  Delete Contour "), wxDefaultPosition, wxDefaultSize, wxFRAME_TOOL_WINDOW|wxSYSTEM_MENU | wxCAPTION |  wxCLIP_CHILDREN |wxFRAME_FLOAT_ON_PARENT );
2786                         int width=300;
2787                         wxSize sizepanel(width,230);
2788                         _deleteFrame->SetSize( sizepanel );
2789                         wxPanel *panel                                          = new wxPanel(_deleteFrame,-1);
2790                         wxButton *deleteContourBtn                      = new wxButton(panel,-1,_T("Delete contour selected"),wxDefaultPosition, wxSize(width-10,35) );
2791                         wxButton *deleteContoursActSliceBtn     = new wxButton(panel,-1,_T("Delete contours of actual slice"),wxDefaultPosition, wxSize(width-10,35));
2792                         wxButton *deleteAllContoursBtn          = new wxButton(panel,-1,_T("Delete all contours"),wxDefaultPosition, wxSize(width-10,35));
2793
2794                         int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
2795                         _mbarrangeDeleteAll                                     =  new mBarRange(panel,70, 65);
2796                         _mbarrangeDeleteAll->SetMin(0);
2797                         _mbarrangeDeleteAll->SetStart(0);
2798
2799                         _mbarrangeDeleteAll-> SetOrientation( true );
2800                         _mbarrangeDeleteAll-> setActiveStateTo(true);
2801                         _mbarrangeDeleteAll-> setVisibleLabels( true );
2802                         _mbarrangeDeleteAll-> setDeviceEndMargin(10);
2803                         _mbarrangeDeleteAll-> setRepresentedValues( 0 , sizeZ );
2804                         _mbarrangeDeleteAll-> setDeviceBlitStart(10,10); 
2805                         _mbarrangeDeleteAll-> setIfWithActualDrawed( false );
2806                         _mbarrangeDeleteAll-> SetStart( 0 );
2807                         _mbarrangeDeleteAll-> SetEnd( sizeZ );  
2808
2809
2810                         _deleteFrame->SetEventHandler( this );
2811                         Connect( deleteContourBtn->GetId()                      ,       wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onDeleteContour ); 
2812                         Connect( deleteContoursActSliceBtn->GetId()     ,       wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onDeleteContoursActSlice ); 
2813                         Connect( deleteAllContoursBtn->GetId()          ,       wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onDeleteAllContours ); 
2814
2815                         wxFlexGridSizer * sizer                         = new wxFlexGridSizer(1);
2816                         sizer -> Add( deleteContourBtn                          , 1, wxGROW );
2817                         sizer -> Add( deleteContoursActSliceBtn         , 1, wxGROW );
2818                         sizer -> Add( deleteAllContoursBtn                      , 1, wxGROW );
2819                         sizer -> Add( _mbarrangeDeleteAll                       , 1, wxGROW );
2820
2821                         panel->SetSizer( sizer );
2822                         panel->SetSize( sizepanel );
2823                         panel->SetAutoLayout( true );
2824                         panel->Layout();
2825                         _deleteFrame->Show(true);
2826                 } else {
2827                         if (_deleteFrame->IsShown()==true)
2828                         {
2829                                 _deleteFrame->Show(false);
2830                         } else  {
2831                                 _deleteFrame->Show(true);
2832                         }
2833                 }
2834         }
2835
2836
2837 //------------------------------------------------------------------------------------------------------------
2838 void wxContourEventHandler::onCreateContourSpline( wxCommandEvent& event )
2839 {
2840         
2841         //JCP 20-10-08 Undo redo implementation
2842         saveState();
2843         //JCP 20-10-08 Undo redo implementation
2844         createContour( 1 );
2845
2846         
2847
2848 }
2849
2850 //------------------------------------------------------------------------------------------------------------
2851 void wxContourEventHandler::onCreateContourRectangle( wxCommandEvent& event )
2852 {
2853         
2854         //JCP 20-10-08 Undo redo implementation
2855         saveState();
2856         //JCP 20-10-08 Undo redo implementation 
2857         createContour( 2 );
2858
2859         
2860 }
2861
2862 //------------------------------------------------------------------------------------------------------------
2863 void wxContourEventHandler::onCreateContourCircle( wxCommandEvent& event )
2864 {
2865         //JCP 20-10-08 Undo redo implementation
2866         saveState();
2867         //JCP 20-10-08 Undo redo implementation 
2868         createContour( 3 );
2869
2870         
2871 }
2872 //------------------------------------------------------------------------------------------------------------
2873 void wxContourEventHandler::onCreateContourBullEye( wxCommandEvent& event )
2874 {
2875         //JCP 20-10-08 Undo redo implementation
2876         saveState();
2877         //JCP 20-10-08 Undo redo implementation
2878         createContour( 4 );
2879         
2880 }
2881
2882
2883
2884 //------------------------------------------------------------------------------------------------------------
2885         void wxContourEventHandler :: onCreateContourFrame( )
2886         {
2887                 if (_createContourFrame==NULL)
2888                 {
2889                         _createContourFrame                                             = new wxFrame (_theViewPanel, -1,_T("  New Contour  "), wxDefaultPosition, wxDefaultSize, wxFRAME_TOOL_WINDOW|wxSYSTEM_MENU | wxCAPTION |  wxCLIP_CHILDREN |wxFRAME_FLOAT_ON_PARENT | wxRESIZE_BORDER );
2890                         wxSize sizepanel(490,600);
2891                         _createContourFrame->SetSize( sizepanel );
2892                         wxPanel *panel                                          = new wxPanel(_createContourFrame,-1);
2893                         wxButton *newContourSplineBtn           = new wxButton(panel,-1,_T("Interpolation B-spline (close)"),wxDefaultPosition, wxSize(180,35) );
2894                         newContourSplineBtn->SetToolTip(_T("CTRL-N"));
2895                         wxButton *newContourRectangleBtn        = new wxButton(panel,-1,_T("Rectangle"),wxDefaultPosition, wxSize(180,35));
2896                         wxButton *newContourCircleBtn           = new wxButton(panel,-1,_T("Circle"),wxDefaultPosition, wxSize(180,35));
2897                         wxButton *newContourStarBtn                     = new wxButton(panel,-1,_T("Bull eye"),wxDefaultPosition, wxSize(180,35));
2898
2899                         _panelBullEyeOptions = new PanelBullEyeOptions(panel, wxSize(100,200));
2900
2901                         _createContourFrame->SetEventHandler( this );
2902                         Connect( newContourSplineBtn->GetId()           ,       wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onCreateContourSpline    ); 
2903                         Connect( newContourRectangleBtn->GetId()        ,       wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onCreateContourRectangle ); 
2904                         Connect( newContourCircleBtn->GetId()           ,       wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onCreateContourCircle    ); 
2905                         Connect( newContourStarBtn->GetId()                     ,       wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onCreateContourBullEye   ); 
2906
2907                         wxFlexGridSizer * sizer                         = new wxFlexGridSizer(1);
2908                         sizer -> Add( newContourSplineBtn                       , 1, wxGROW );
2909                         sizer -> Add( newContourRectangleBtn            , 1, wxGROW );
2910                         sizer -> Add( newContourCircleBtn                       , 1, wxGROW );
2911                         sizer -> Add( newContourStarBtn                         , 1, wxGROW );
2912                         sizer -> Add( _panelBullEyeOptions                      , 1, wxGROW );
2913
2914                         panel->SetSizer( sizer );
2915                         panel->SetSize( sizepanel );
2916                         panel->SetAutoLayout( true );
2917                         panel->Layout();
2918                         _createContourFrame->Show(true);
2919                 } else {
2920                         if (_createContourFrame->IsShown()==true)
2921                         {
2922                                 _createContourFrame->Show(false);
2923                         } else  {
2924                                 _createContourFrame->Show(true);
2925                         }
2926                 }
2927         }
2928
2929
2930 //------------------------------------------------------------------------
2931 void wxContourEventHandler::RefreshInterface()
2932 {
2933         changeInstant();
2934         wxVtk2DBaseView *wxvtk2dbaseview = (wxVtk2DBaseView*)this->_theViewPanel->getWxVtkBaseView();
2935         wxvtk2dbaseview->Refresh();
2936 }
2937
2938 //------------------------------------------------------------------------
2939 void wxContourEventHandler::onWidthOfContour(wxScrollEvent& event){
2940         _theViewPanel->getSceneManager()->removeSceneContours();
2941         double width = (double)_withOfContourLine->GetValue() / 2.0;
2942         _theViewPanel->getSceneManager()->SetWidthContour( width );
2943
2944         RefreshInterface();
2945 }
2946
2947 //------------------------------------------------------------------------
2948
2949 void wxContourEventHandler::onBrigthnessColorWindowLevel(wxScrollEvent& event){
2950         int colorwindow                         = _brithtnessColorLevel->GetValue();
2951         int windowlevel                         = _brithtnessWindowLevel->GetValue();
2952         wxVtk2DBaseView *wxvtk2dbaseview = (wxVtk2DBaseView*)this->_theViewPanel->getWxVtkBaseView();
2953         vtkImageViewer2 *imageviewer = wxvtk2dbaseview->_imageViewer2XYZ->GetVtkImageViewer2();
2954         imageviewer->SetColorWindow(colorwindow);
2955         imageviewer->SetColorLevel(windowlevel);        
2956 //      wxvtk2dbaseview->Refresh();
2957         RefreshInterface();
2958 }
2959
2960 void wxContourEventHandler::OnInterpolation(wxCommandEvent& event)
2961 {
2962         wxVtk2DBaseView *wxvtk2dbaseview = (wxVtk2DBaseView*)this->_theViewPanel->getWxVtkBaseView();
2963         vtkImageViewer2 *imageviewer = wxvtk2dbaseview->_imageViewer2XYZ->GetVtkImageViewer2();
2964         if (_interpolationCheckBox->GetValue()==true)
2965         {
2966                 imageviewer->GetImageActor()->InterpolateOn();
2967         } else {
2968                 imageviewer->GetImageActor()->InterpolateOff();
2969         }
2970         RefreshInterface();
2971 }
2972
2973
2974 //------------------------------------------------------------------------------------------------------------
2975         void wxContourEventHandler :: onInterfaceConfigurationFrame( )
2976         {
2977                 if (_interfaceConfigurationFrame==NULL)
2978                 {
2979                         _interfaceConfigurationFrame                    = new wxFrame (_theViewPanel, -1,_T(" Interface Configuration "), wxDefaultPosition, wxDefaultSize, wxFRAME_TOOL_WINDOW|wxSYSTEM_MENU | wxCAPTION |  wxCLIP_CHILDREN |wxFRAME_FLOAT_ON_PARENT );
2980                         wxSize sizepanel(190,400);
2981                         _interfaceConfigurationFrame->SetSize( sizepanel );
2982                         _interfaceConfigurationFrame->SetEventHandler( this );
2983                         wxPanel* panel = getConfigurationPanel(_interfaceConfigurationFrame);
2984                         panel->SetSize(sizepanel);
2985                         _interfaceConfigurationFrame->Show(true);
2986                 } else {
2987                         if (_interfaceConfigurationFrame->IsShown()==true)
2988                         {
2989                                 _interfaceConfigurationFrame->Show(false);
2990                         } else  {
2991                                 _interfaceConfigurationFrame->Show(true);
2992                         }
2993                 }
2994         }
2995
2996
2997         //**JCP 13-10-08
2998
2999         wxPanel* wxContourEventHandler :: getConfigurationPanel(wxWindow* parent){
3000                 
3001                 /*wxPanel *panel                                                        = new wxPanel(parent,-1);
3002                 _withOfContourLine                                              = new wxSlider(panel, -1, 1 , 1, 10, wxDefaultPosition, wxSize(180,40), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
3003
3004                 double range[2];
3005                 this->_theViewPanel->getSceneManager()->GetImageDataRange(range);
3006
3007                 wxVtk2DBaseView *wxvtk2dbaseview = (wxVtk2DBaseView*)this->_theViewPanel->getWxVtkBaseView();
3008                 vtkImageViewer2 *imageviewer = wxvtk2dbaseview->_imageViewer2XYZ->GetVtkImageViewer2();
3009                 int colorwindow = (int)imageviewer->GetWindowLevel()->GetLevel();
3010                 int windowlevel = (int)imageviewer->GetWindowLevel()->GetWindow();      
3011
3012                 _brithtnessWindowLevel                                  = new wxSlider(panel, -1, windowlevel , 1, range[1], wxDefaultPosition, wxSize(180,40), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
3013                 _brithtnessColorLevel                                   = new wxSlider(panel, -1, colorwindow , 1, range[1], wxDefaultPosition, wxSize(180,40), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
3014
3015                 _interpolationCheckBox = new wxCheckBox(panel, -1, _T("Image interpolation") );
3016                 _interpolationCheckBox->SetValue(true);
3017
3018                 _interfaceConfigurationFrame->SetEventHandler( this );
3019
3020                 Connect( _withOfContourLine->GetId()            ,       wxEVT_SCROLL_CHANGED    , (wxObjectEventFunction) &wxContourEventHandler::onWidthOfContour      ); 
3021                 Connect( _withOfContourLine->GetId()            ,       wxEVT_SCROLL_THUMBTRACK , (wxObjectEventFunction) &wxContourEventHandler::onWidthOfContour      ); 
3022
3023                 Connect( _brithtnessWindowLevel->GetId()        ,       wxEVT_SCROLL_CHANGED    , (wxObjectEventFunction) &wxContourEventHandler::onBrigthnessColorWindowLevel  ); 
3024                 Connect( _brithtnessWindowLevel->GetId()        ,       wxEVT_SCROLL_THUMBTRACK , (wxObjectEventFunction) &wxContourEventHandler::onBrigthnessColorWindowLevel  ); 
3025                 Connect( _brithtnessColorLevel->GetId()         ,       wxEVT_SCROLL_CHANGED    , (wxObjectEventFunction) &wxContourEventHandler::onBrigthnessColorWindowLevel  ); 
3026                 Connect( _brithtnessColorLevel->GetId()         ,       wxEVT_SCROLL_THUMBTRACK , (wxObjectEventFunction) &wxContourEventHandler::onBrigthnessColorWindowLevel  ); 
3027                 Connect( _interpolationCheckBox->GetId()        ,       wxEVT_COMMAND_CHECKBOX_CLICKED    , (wxObjectEventFunction) &wxContourEventHandler::OnInterpolation             );
3028
3029                 wxFlexGridSizer * sizer                                 = new wxFlexGridSizer(1);
3030                 sizer -> Add( new wxStaticText(panel,-1,_T("Contour width"))  , 1, wxGROW );
3031                 sizer -> Add( _withOfContourLine                , 1, wxGROW );
3032                 sizer -> Add( new wxStaticText(panel,-1,_T(" "))  , 1, wxGROW );
3033                 sizer -> Add( new wxStaticText(panel,-1,_T(" "))  , 1, wxGROW );
3034                 sizer -> Add( new wxStaticText(panel,-1,_T("Brightness of the image"))  , 1, wxGROW );
3035                 sizer -> Add( new wxStaticText(panel,-1,_T("--Window level--"))  , 1, wxGROW );
3036                 sizer -> Add( _brithtnessWindowLevel            , 1, wxGROW );
3037                 sizer -> Add( new wxStaticText(panel,-1,_T("--Color level--"))  , 1, wxGROW );
3038                 sizer -> Add( _brithtnessColorLevel, 1, wxGROW );
3039                 sizer -> Add( new wxStaticText(panel,-1,_T(" "))  , 1, wxGROW );
3040                 sizer -> Add( new wxStaticText(panel,-1,_T(" "))  , 1, wxGROW );
3041                 sizer -> Add( _interpolationCheckBox            , 1, wxGROW );
3042
3043                 panel->SetSizer( sizer );
3044                 //JCP 13-10-08
3045                 //panel->SetSize( sizepanel );
3046                 //13-10-08
3047                 panel->SetAutoLayout( true );
3048                 panel->Layout();
3049
3050                 return panel;*/
3051
3052                 wxPanel *panel                                                  = new wxPanel(parent,-1,wxDefaultPosition, wxDefaultSize,wxNO_BORDER, wxString(_T("")));
3053                 _withOfContourLine                                              = new wxSlider(panel, -1, 1 , 1, 10, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
3054
3055                 double range[2];
3056                 this->_theViewPanel->getSceneManager()->GetImageDataRange(range);
3057
3058                 wxVtk2DBaseView *wxvtk2dbaseview = (wxVtk2DBaseView*)this->_theViewPanel->getWxVtkBaseView();
3059                 vtkImageViewer2 *imageviewer = wxvtk2dbaseview->_imageViewer2XYZ->GetVtkImageViewer2();
3060                 int colorwindow = (int)imageviewer->GetWindowLevel()->GetLevel();
3061                 int windowlevel = (int)imageviewer->GetWindowLevel()->GetWindow();      
3062
3063                 _brithtnessWindowLevel                                  = new wxSlider(panel, -1, windowlevel , 1, range[1], wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
3064                 _brithtnessColorLevel                                   = new wxSlider(panel, -1, colorwindow , 1, range[1], wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
3065
3066                 _interpolationCheckBox = new wxCheckBox(panel, -1, _T("Image interpolation") );
3067                 _interpolationCheckBox->SetValue(true);         
3068
3069                 Connect( _withOfContourLine->GetId()            ,       wxEVT_SCROLL_CHANGED    , (wxObjectEventFunction) &wxContourEventHandler::onWidthOfContour      ); 
3070                 Connect( _withOfContourLine->GetId()            ,       wxEVT_SCROLL_THUMBTRACK , (wxObjectEventFunction) &wxContourEventHandler::onWidthOfContour      ); 
3071
3072                 Connect( _brithtnessWindowLevel->GetId()        ,       wxEVT_SCROLL_CHANGED    , (wxObjectEventFunction) &wxContourEventHandler::onBrigthnessColorWindowLevel  ); 
3073                 Connect( _brithtnessWindowLevel->GetId()        ,       wxEVT_SCROLL_THUMBTRACK , (wxObjectEventFunction) &wxContourEventHandler::onBrigthnessColorWindowLevel  ); 
3074                 Connect( _brithtnessColorLevel->GetId()         ,       wxEVT_SCROLL_CHANGED    , (wxObjectEventFunction) &wxContourEventHandler::onBrigthnessColorWindowLevel  ); 
3075                 Connect( _brithtnessColorLevel->GetId()         ,       wxEVT_SCROLL_THUMBTRACK , (wxObjectEventFunction) &wxContourEventHandler::onBrigthnessColorWindowLevel  ); 
3076                 Connect( _interpolationCheckBox->GetId()        ,       wxEVT_COMMAND_CHECKBOX_CLICKED    , (wxObjectEventFunction) &wxContourEventHandler::OnInterpolation             );
3077
3078                 wxFlexGridSizer * sizer                                 = new wxFlexGridSizer(1);
3079                 sizer -> Add( new wxStaticText(panel,-1,_T("Contour width"))  , 1, wxGROW );
3080                 sizer -> Add( _withOfContourLine                , 1, wxGROW );
3081                 sizer -> Add( new wxStaticText(panel,-1,_T(" "))  , 1, wxGROW );
3082                 sizer -> Add( new wxStaticText(panel,-1,_T(" "))  , 1, wxGROW );
3083                 sizer -> Add( new wxStaticText(panel,-1,_T("Brightness of the image"))  , 1, wxGROW );
3084                 sizer -> Add( new wxStaticText(panel,-1,_T("--Window level--"))  , 1, wxGROW );
3085                 sizer -> Add( _brithtnessWindowLevel            , 1, wxGROW );
3086                 sizer -> Add( new wxStaticText(panel,-1,_T("--Color level--"))  , 1, wxGROW );
3087                 sizer -> Add( _brithtnessColorLevel, 1, wxGROW );
3088                 sizer -> Add( new wxStaticText(panel,-1,_T(" "))  , 1, wxGROW );
3089                 sizer -> Add( new wxStaticText(panel,-1,_T(" "))  , 1, wxGROW );
3090                 sizer -> Add( _interpolationCheckBox            , 1, wxGROW );
3091
3092                 panel->SetSizer( sizer );
3093                 //JCP 13-10-08
3094                 //panel->SetSize( sizepanel );
3095                 //13-10-08
3096                 panel->SetAutoLayout( true );
3097                 panel->Layout();
3098
3099                 return panel;
3100         }
3101
3102 //**JCP 13-10-08
3103
3104         
3105
3106 //------------------------------------------------------------------
3107         void wxContourEventHandler :: changeContourOfManager(std::string keyName, Instant *instant)
3108         {
3109                 this->_modelManager->ChangeContourOfList(keyName, instant);
3110         }
3111
3112 //------------------------------------------------------------------
3113         void wxContourEventHandler :: changeContoursOfManager(  std::vector<std::string> & keyNamesVector  )
3114         {
3115
3116                 //JCP 20-10-08 Undo redo implementation
3117                 saveState();
3118                 //JCP 20-10-08 Undo redo implementation
3119
3120                 std::vector<int> tempVector;
3121                 _instantPanel->getInstant( tempVector );
3122                 Instant instant(&tempVector);
3123
3124                 int i , size=keyNamesVector.size();
3125                 for ( i=0 ; i<size ; i++ )
3126                 {
3127                         changeContourOfManager(keyNamesVector[i], &instant);
3128                 } // i
3129
3130                 
3131         }
3132
3133
3134 //------------------------------------------------------------------
3135         void wxContourEventHandler :: executeActionCommand( const char  toolCommand )
3136         {
3137                 std::vector<std::string> currentSelection = _theViewPanel->getSceneManager()->getSelectedObjects();
3138                 int elementsSelected = currentSelection.size();
3139                 if( toolCommand == (wxContour_ActionCommandsID::CREATE_TOOL) )
3140                 {
3141                         onCreateContourFrame();
3142                 }
3143                 if( toolCommand == (wxContour_ActionCommandsID::CREATE_CONTOUR_KEY) )
3144                 {
3145                         createContour();
3146                 }
3147                 else if( toolCommand == wxContour_ActionCommandsID::DELETE_TOOL )
3148                 {
3149                         onDeleteFrame( );
3150                 }
3151                 else if( toolCommand == wxContour_ActionCommandsID::DELETE_KEY )
3152                 {
3153                         deleteContours( currentSelection );
3154                 }
3155                 else if( toolCommand == wxContour_ActionCommandsID::SAVE_TOOL )
3156                 {
3157                         saveFileWithContours(  );
3158                 }
3159                 else if( toolCommand == wxContour_ActionCommandsID::SAVE_KEY )
3160                 {
3161                         saveFileWithContoursAutomatique(  );
3162                 }
3163                 else if( toolCommand == wxContour_ActionCommandsID::OPEN_TOOL )
3164                 {
3165                         openFileWithContours(  );
3166                 }
3167                 else if( toolCommand == wxContour_ActionCommandsID::CHANGE_TOOL )
3168                 {
3169                         if ( elementsSelected >= 1 )
3170                         {
3171                                 changeContoursOfManager( currentSelection );
3172                         }
3173
3174                 }
3175                 else if( toolCommand == wxContour_ActionCommandsID::HIDE_TOOL )
3176                 {
3177                         if ( elementsSelected >= 1 )
3178                         {
3179                                 onHideOutlines( currentSelection );
3180                         }                       
3181                 }
3182                 else if( toolCommand == wxContour_ActionCommandsID::SHOW_TOOL )
3183                 {
3184                         if ( elementsSelected >= 1 )
3185                         {
3186                                 onShowOutlines( currentSelection );
3187                         }
3188                 }
3189                 else if( toolCommand == wxContour_ActionCommandsID::COPY_TOOL )
3190                 {
3191                         if ( elementsSelected >= 1 )
3192                         {
3193                                 onCopyOutlines( currentSelection );
3194                         }
3195                 }
3196                 else if( toolCommand == wxContour_ActionCommandsID::PASTE_TOOL )
3197                 {
3198                         onPasteOutlines(  );                    
3199                 }
3200                 else if( toolCommand == wxContour_ActionCommandsID::SPREAD_TOOL )
3201                 {
3202                                 onSpread();
3203                 }
3204                 else if( toolCommand == wxContour_ActionCommandsID::AUTOMATIQUESEGMENTATION_TOOL )
3205                 {
3206                         onAutomatiqueSegmentation(  );                  
3207                 }
3208
3209                 else if( toolCommand == wxContour_ActionCommandsID::SELECT_TOOL )
3210                 {
3211                         onSelectOutlines( currentSelection );
3212                         
3213                 }
3214                 else if( toolCommand == wxContour_ActionCommandsID::EDIT_TOOL )
3215                 {
3216                         if ( elementsSelected >= 1 )
3217                         {
3218                                 onEditOutlines( currentSelection );
3219                         }
3220                 }
3221                 else if( toolCommand == wxContour_ActionCommandsID::UNDO_TOOL )
3222                 {
3223                         onUNDO();
3224                 }
3225                 else if( toolCommand == wxContour_ActionCommandsID::REDO_TOOL )
3226                 {
3227                         onREDO();
3228                 }               
3229                 else if( toolCommand == wxContour_ActionCommandsID::INFORMATIONCONTOUR_TOOL )
3230                 {
3231                         onInformationContourFrame();
3232                 }               
3233                 else if( toolCommand == wxContour_ActionCommandsID::INTERFACECONFIGURATION_TOOL )
3234                 {
3235                         onInterfaceConfigurationFrame();
3236                 }
3237                 else if( toolCommand == wxContour_ActionCommandsID::TEST_TOOL )
3238                 {
3239                         onInterfaceTestFrame();
3240                 }               
3241
3242
3243         }
3244
3245         
3246         //------------------------------------------------------------------------------------------------------------
3247         //  Getting information methods
3248         //------------------------------------------------------------------------------------------------------------
3249
3250
3251
3252         //------------------------------------------------------------------------------------------------------------
3253         //  Private methods
3254         //------------------------------------------------------------------------------------------------------------
3255    
3256         void wxContourEventHandler :: updateInstantOutlines()
3257         {
3258                 std::vector<NameWrapper *> namesWrapping = _modelManager->getActualInstantOutlines();
3259                 int size = namesWrapping.size();
3260                 _theViewPanel->getSceneManager()->removeSceneContours();
3261                 for( int i=0; i<size; i++)
3262                 {                       
3263                         _theViewPanel->getSceneManager()->addToScene(namesWrapping[i]->getKeyName(), true, true, true, false, false );
3264                 }
3265         }
3266         //------------------------------------------------------------------------------------------------------------
3267         void wxContourEventHandler :: updateInstantImageData()
3268         {
3269                 wxContourMainFrame * instance = wxContourMainFrame::getInstance();
3270                 if(instance != NULL){
3271                         int val;
3272                         std::string conceptname;
3273                         val = _instantPanel->getConceptValue(conceptname);
3274
3275                         if(conceptname.compare("time")==0){
3276                                 std::vector<vtkImageData*> imgvect = instance->getVectImages();
3277                                 for(int i = 0; i < imgvect.size(); i++){
3278                                         //_instantPanel->getI
3279                                 }
3280                                 //ImageSourceThing* imgsoth = new ImageSourceThing();
3281                                 //_modelManager->addImageSource(
3282                         }
3283                 }               
3284         }
3285         //------------------------------------------------------------------------------------------------------------
3286
3287         void wxContourEventHandler :: updateInstantAxes()
3288         {
3289                 
3290         }
3291         //------------------------------------------------------------------------------------------------------------  
3292         void wxContourEventHandler :: changeInstant()
3293         {
3294                 std::vector<int> instantVect;
3295                 _instantPanel->getInstant( instantVect );
3296                 Instant * theInstant = new Instant ( &instantVect );
3297                 //if( !theInstant->isEquals( _actualInstant ))
3298                 {       
3299                         //Setting the actual instant
3300                         _actualInstant = theInstant;
3301                         _modelManager->setInstant( _actualInstant );
3302                         
3303                         updateInstantOutlines();
3304                         updateInstantImageData();
3305                         updateInstantAxes();
3306
3307                         
3308                         //Searching the elements at the specified instant
3309
3310                         /*
3311                         std::map<std::string, ContourWrap_ViewControl *> :: iterator iter;
3312                         iter = contours_ViewControl->find("Outline 0");
3313                         (iter->second)->getViewer()->RemoveCompleteContourActor();*/
3314                 }
3315         }
3316
3317         void wxContourEventHandler :: saveState(){
3318                 
3319                         
3320                 inredo = 0;
3321
3322                 //char str[9000];
3323                 //itoa(inundo, str, 10);
3324                 std::string str = intToString(inundo);
3325
3326
3327                 std::string temp = stundoredo + str + ".roi";
3328                 saveFileWithContours(temp);
3329
3330                 inundo++;
3331         }
3332
3333         void wxContourEventHandler ::loadState(std::string filename){
3334
3335                 char tmp[255];
3336                 FILE *pFile=fopen(filename.c_str(),"r+");
3337
3338                 fscanf(pFile,"%s",tmp); // --CreaContour--
3339
3340                 fscanf(pFile,"%s",tmp); // Version
3341                 fscanf(pFile,"%s",tmp); // 1.0.1
3342                 std::string version(tmp);
3343
3344                 deleteAllContours();
3345
3346                 openContours(pFile,false);
3347                 if (version!="1.0.0"){
3348                         openContours(pFile,true);
3349                 }
3350
3351                 fclose(pFile);
3352                 
3353                 //_theViewPanel->getSceneManager()->removeSceneContours();
3354                 //changeInstant();
3355
3356         }
3357 void wxContourEventHandler :: onREDO()
3358         {
3359                 if(inredo > 0){
3360                         inredo--;
3361                         inundo++;
3362
3363                         //char str[9000];
3364                         //itoa(inundo, str, 10);
3365                         std::string str = intToString(inundo);
3366
3367             
3368                         std::string temp = stundoredo + str + ".roi";
3369                 
3370                         loadState(temp);
3371
3372                         
3373                 }
3374
3375         }
3376         //------------------------------------------------------------------------------------------------------------
3377         void wxContourEventHandler :: onUNDO()
3378         {
3379                 if(inundo>0){
3380                         if(inredo==0){
3381
3382                                 //char str[9000];
3383                                 //itoa(inundo, str, 10);
3384                                 std::string str = intToString(inundo);
3385
3386                                 std::string temp = stundoredo + str + ".roi";
3387                                 saveFileWithContours(temp);                             
3388
3389                         }
3390                         inredo++;
3391                         inundo--;
3392
3393                         //char str[9000];
3394                         //itoa(inundo, str, 10);
3395                         std::string str = intToString(inundo);
3396
3397             
3398                         std::string temp = stundoredo + str + ".roi";
3399                 
3400                         loadState(temp);
3401                 }
3402         }
3403 //JCP 21 - 10 - 09
3404         void  wxContourEventHandler :: getValuesXYZ(double **vectx, double **vecty, double **vectz, std::vector<int>* size){
3405
3406
3407                 wxBusyCursor wait;
3408                 ContourExtractData      *contourextractdata = new ContourExtractData();
3409                 int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
3410                 contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
3411
3412                 std::vector<manualContourModel*> lstManConMod;
3413                 std::vector<manualContourModel*> lstManConModTmp;
3414                 std::vector<manualContourModel*> lstManConModExp;
3415                 std::vector<double> pLstValue;
3416                 std::vector<double> pLstValuePosX;
3417                 std::vector<double> pLstValuePosY;
3418                 std::vector<double> pLstValuePosZ;
3419
3420                 std::vector<int> tempVector;
3421                 _instantPanel->getInstant( tempVector );
3422
3423                 vtkImageData *imagedata = _theViewPanel->getSceneManager()->GetImageData();
3424                 int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
3425                 int z;
3426                 int ii,sizeLstContourThings;
3427
3428
3429                 int minZ,maxZ;
3430                 double totalZ;
3431                 double porcent; 
3432                 wxString tmpString;
3433                 minZ    = 0;// _mbarrange->GetStart();
3434                 maxZ    = sizeZ;//_mbarrange->GetEnd();
3435                 totalZ  = maxZ-minZ+1;
3436
3437                 contourextractdata->SetImage( imagedata);
3438
3439         // For each slice..
3440                 vectx = new double *[sizeZ];
3441                 vecty = new double *[sizeZ];
3442                 vectz = new double *[sizeZ];
3443                 for ( z=0 ; z<sizeZ ; z++)
3444                 {
3445
3446                         porcent = 100.0* (z-minZ)/totalZ;
3447                         
3448                         //Extraction data from contours of each slice
3449                         contourextractdata->SetZtoBeAnalys( z);
3450
3451                         tempVector[1]=z;
3452                         Instant instant(&tempVector);
3453                         std::vector<ContourThing**> lstContourThings = this->_modelManager->getOutlinesAtInstant( &instant );
3454                         sizeLstContourThings = lstContourThings.size();
3455
3456                         lstManConMod.clear();
3457                         for (ii=0 ; ii<sizeLstContourThings ; ii++)
3458                         {
3459                                 ContourThing **contourthing = lstContourThings[ii];
3460                                 lstManConMod.push_back( (*contourthing)->getModel() );
3461                         }
3462                         lstManConModExp =  ExploseEachModel( lstManConMod );
3463
3464
3465 //EED004
3466
3467                         int iContourGroup,sizeContourGroup;
3468                         if (typeContourGroup==3) // contour separete
3469                         {
3470                                 sizeContourGroup=lstManConModExp.size();
3471                         } else {  // contour AND OR XOR
3472                                 sizeContourGroup=1;
3473                         }
3474
3475                         for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
3476                                 lstManConModTmp.clear();
3477                                 if (typeContourGroup==3) // contour separete
3478                                 {
3479                                         lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
3480                                 } else {  // contour AND OR XOR
3481                                         lstManConModTmp = lstManConModExp;
3482                                 }
3483
3484                                 contourextractdata->SetLstManualContourModel( lstManConModTmp );
3485
3486                                 pLstValue.clear();
3487                                 pLstValuePosX.clear();
3488                                 pLstValuePosY.clear();
3489                                 pLstValuePosZ.clear();
3490                                 contourextractdata->GetValuesInsideCrown(       &pLstValue,
3491                                                                                                                         &pLstValuePosX,
3492                                                                                                                         &pLstValuePosY,
3493                                                                                                                         &pLstValuePosZ);
3494
3495                                 
3496                                 int iLstValue,sizeLstValue=pLstValue.size();
3497
3498                                 //We initialize the pointers
3499                                 size->push_back(sizeLstValue);
3500                                 vectx[sizeZ] = new double[sizeLstValue];
3501                                 vecty[sizeZ] = new double[sizeLstValue];
3502                                 vectz[sizeZ] = new double[sizeLstValue];
3503                                 
3504                                 for (iLstValue=0 ; iLstValue<sizeLstValue ; iLstValue++ )
3505                                 {
3506                                         
3507                                         vectx[sizeZ][iLstValue] = pLstValuePosX[iLstValue];
3508                                         vecty[sizeZ][iLstValue] = pLstValuePosY[iLstValue];
3509                                         vectz[sizeZ][iLstValue] = pLstValuePosZ[iLstValue];
3510                                         
3511                                 }
3512                                 //The size of the contour is saved
3513                                 
3514                                 
3515                                 
3516                                 //fclose(pFile);
3517                         } // for  iContourGroup
3518                 } // for z
3519                 //_staticTextInformation->SetLabel( _T("") );
3520                 delete contourextractdata;
3521
3522         }
3523
3524
3525         void  wxContourEventHandler :: getMaskValue(vtkImageData* mask, vtkImageData* value){
3526
3527
3528                 wxBusyCursor wait;
3529                 ContourExtractData      *contourextractdata = new ContourExtractData( true );
3530                 int typeContourGroup = this->_radiolstboxContourGroup->GetSelection();
3531                 if (typeContourGroup==3)
3532                 {
3533                         typeContourGroup=1;
3534                 }
3535                 contourextractdata ->SetTypeOperation( typeContourGroup % 3 );
3536
3537                 std::vector<manualContourModel*> lstManConMod;
3538                 std::vector<manualContourModel*> lstManConModTmp;
3539                 std::vector<manualContourModel*> lstManConModExp;
3540
3541                 std::vector<int> tempVector;
3542                 _instantPanel->getInstant( tempVector );
3543
3544                 vtkImageData *imagedata = _theViewPanel->getSceneManager()->GetImageData();
3545                 int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
3546                 int z;
3547                 int ii,sizeLstContourThings;
3548
3549
3550                 int minZ,maxZ;
3551                 double totalZ;
3552                 double porcent; 
3553
3554                 wxString tmpString;
3555
3556                 minZ    = 0;// _mbarrange->GetStart();
3557                 maxZ    = sizeZ;//_mbarrange->GetEnd();
3558                 totalZ  = maxZ-minZ+1;
3559
3560                 contourextractdata->SetImage( imagedata);
3561
3562         // For each slice..
3563                 for ( z=0 ; z<sizeZ ; z++)
3564                 {
3565
3566                         porcent = 100.0* (z-minZ)/totalZ;
3567                         tmpString.Printf(_T("Saving Values"));
3568                         tmpString.Printf(_T("  %d %c            %d/%d             %d"), (int)porcent , 37 , z-minZ+1, (int)totalZ ,z);
3569                         _staticTextInformation->SetLabel(tmpString);
3570
3571                         //Extraction data from contours of each slice
3572                         contourextractdata->SetZtoBeAnalys( z);
3573
3574                         tempVector[1]=z;
3575                         Instant instant(&tempVector);
3576                         std::vector<ContourThing**> lstContourThings = this->_modelManager->getOutlinesAtInstant( &instant );
3577                         sizeLstContourThings = lstContourThings.size();
3578
3579                         lstManConMod.clear();
3580                         for (ii=0 ; ii<sizeLstContourThings ; ii++)
3581                         {
3582                                 ContourThing **contourthing = lstContourThings[ii];
3583                                 lstManConMod.push_back( (*contourthing)->getModel() );
3584                         }
3585                         lstManConModExp =  ExploseEachModel( lstManConMod );
3586
3587
3588                         int iContourGroup,sizeContourGroup;
3589                         if (typeContourGroup==3) // contour separete
3590                         {
3591                                 sizeContourGroup=lstManConModExp.size();
3592                         } else {  // contour AND OR XOR
3593                                 sizeContourGroup=1;
3594                         }
3595
3596                         for( iContourGroup=0 ; iContourGroup<sizeContourGroup ; iContourGroup++ ){
3597                                 lstManConModTmp.clear();
3598                                 if (typeContourGroup==3) // contour separete
3599                                 {
3600                                         lstManConModTmp.push_back( lstManConModExp[iContourGroup]);
3601                                 } else {  // contour AND OR XOR
3602                                         lstManConModTmp = lstManConModExp;
3603                                 }
3604
3605                                 contourextractdata->SetLstManualContourModel( lstManConModTmp );
3606
3607
3608                                 contourextractdata->CalculateImageResult(); // with actual Z
3609
3610                         } // for  iContourGroup
3611                 } // for z
3612
3613
3614
3615 // Image Value
3616                 value = contourextractdata->GetVtkImageValueResult();
3617                 
3618 // Image Mask
3619                 mask = contourextractdata->GetVtkImageMaskResult();
3620                 
3621                 delete contourextractdata;
3622
3623
3624         }
3625         wxPanel* wxContourEventHandler::getSegmentationPanelITK(wxWindow* parent){
3626
3627                 int sizeZ = _theViewPanel->getSceneManager()->GetImageDataSizeZ();
3628                 double range[2];
3629                 _theViewPanel->getSceneManager()->GetImageDataRange(range);
3630
3631                 wxPanel *panel                                          = new wxPanel(parent,-1);
3632                 wxButton *segmentationOneSliceBtn       = new wxButton(panel,-1,_T("Actual slice"), wxDefaultPosition, wxSize(200,35) );
3633                 wxButton *segmentationAllSliceBtn       = new wxButton(panel,-1,_T("All slices") ,wxDefaultPosition, wxSize(200,35) );
3634                 _isovalue                                                       = new wxSlider(panel, -1, 40 , (int)(range[0]), (int)(range[1]), wxDefaultPosition, wxSize(200,35), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
3635                 _sampling                                                       = new wxSlider(panel, -1, 20 , 4, 50, wxDefaultPosition, wxSize(200,35), wxSL_HORIZONTAL|wxSL_LABELS, wxDefaultValidator);
3636                 wxString lstOptions[3];
3637                 lstOptions[0]=_T("A");
3638                 lstOptions[1]=_T("B");
3639                 lstOptions[2]=_T("C");
3640                 methodRadiobox                                          = new wxRadioBox(panel, -1, _T("Method (find ctrl. Points)"), wxDefaultPosition, wxSize(200,45), 3 , lstOptions,  3, wxRA_SPECIFY_COLS);
3641                 methodRadiobox->SetSelection(2);
3642                 _staticTextSegmentation                         = new wxStaticText(panel,-1,_T("    "));
3643
3644
3645                 _mbarrange                                      =  new mBarRange(panel,70, 65);
3646                 _mbarrange->SetMin(0);
3647                 _mbarrange->SetStart(0);
3648
3649                 _mbarrange-> SetOrientation( true );
3650                 _mbarrange-> setActiveStateTo(true);
3651                 _mbarrange-> setVisibleLabels( true );
3652                 _mbarrange-> setDeviceEndMargin(10);
3653                 _mbarrange-> setRepresentedValues( 0 , sizeZ );
3654                 _mbarrange-> setDeviceBlitStart(10,10); 
3655                 _mbarrange-> setIfWithActualDrawed( false );
3656                 _mbarrange-> SetStart( 0 );
3657                 _mbarrange-> SetEnd( sizeZ );  
3658
3659
3660 //                      _segmentationFrame->SetEventHandler( this );
3661                 segmentationOneSliceBtn->SetEventHandler( this );
3662                 segmentationAllSliceBtn->SetEventHandler( this );
3663                 Connect( segmentationOneSliceBtn->GetId(),   wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSegmentationOneSliceITK ); 
3664                 Connect( segmentationAllSliceBtn->GetId(),   wxEVT_COMMAND_BUTTON_CLICKED , (wxObjectEventFunction) &wxContourEventHandler::onSegmentationAllSliceITK ); 
3665
3666                 wxFlexGridSizer * sizer                         = new wxFlexGridSizer(1);
3667                 sizer -> Add( new wxStaticText(panel,-1,_T("Isovalue (Gray level)"))  , 1, wxGROW );
3668                 sizer -> Add( _isovalue , 1, wxGROW );
3669                 sizer -> Add( methodRadiobox , 1, wxGROW );
3670                 sizer -> Add( new wxStaticText(panel,-1,_T("Sampling (%)"))  , 1, wxGROW );
3671                 sizer -> Add( _sampling , 1, wxGROW );
3672                 sizer -> Add( segmentationOneSliceBtn , 1, wxGROW );
3673                 sizer -> Add( new wxStaticText(panel,-1,_T(" "))  , 1, wxGROW );
3674                 sizer -> Add( _staticTextSegmentation  , 1, wxGROW );
3675                 sizer -> Add( segmentationAllSliceBtn , 1, wxGROW );
3676                 sizer -> Add( _mbarrange  , 1, wxGROW );
3677
3678                 panel->SetSizer( sizer );
3679 //              panel->SetSize( sizePanel );
3680                 panel->SetSize( wxDefaultSize );
3681                 panel->SetAutoLayout( true );
3682                 panel->Layout();
3683                 
3684                 return panel;
3685                 
3686         }
3687
3688         void wxContourEventHandler::onSegmentationAllSliceITK( wxCommandEvent& event ){
3689                 //TODO implementar el método para todos los slices ver ayuda en onSegmentationAllSlice
3690         }
3691         void wxContourEventHandler::onSegmentationOneSliceITK( wxCommandEvent& event ){
3692                 //TODO implementar el método de segmentación en ITK ver ayuda en onSegmentationOneSlice y el método
3693                 // SegmentationOneSlice(x, y, z) que es la implementación del método en VTK
3694
3695                 //JCP 20-10-08 Undo redo implementation
3696                 saveState();
3697                 //JCP 20-10-08 Undo redo implementation
3698                 
3699                 wxBusyCursor wait;
3700                 int                                     x                                       = this->_theViewPanel->GetX();
3701                 int                                     y                                       = this->_theViewPanel->GetY();
3702                 int                                     z                                       = this->_theViewPanel->GetZ();
3703                 //SegmentationOneSlice( x,y,z );
3704                 RefreshInterface();
3705         }
3706         void wxContourEventHandler::onSnakePressed(wxWindow* parent){
3707
3708                 std::vector<double> vecX; 
3709                 std::vector<double> vecY; 
3710                 std::vector<double> vecZ; 
3711                 _theViewPanel->getSceneManager()->GetPointsOfActualContour( &vecX , &vecY , &vecZ );    
3712
3713                 if (vecX.size()!=0){
3714                         std::vector<int> tempVector;
3715                         _instantPanel->getInstant( tempVector );
3716                         int i,size=vecZ.size();
3717                         int actualSlice = tempVector[1];
3718                         for ( i=0 ; i<size ; i++ )
3719                         {
3720                                 vecZ[i] = actualSlice;
3721                         } // for
3722
3723                         wxDialog* dialog = new wxDialog(parent, -1, wxString(_T("Snake")));
3724                         wxPanel* panel = new wxPanel(dialog,-1); 
3725                         wxStaticText* sttext = new wxStaticText(panel, -1, wxString(_T("Panel para snake")));
3726                         dialog->ShowModal();
3727                 } // if 
3728
3729         }
3730
3731         void wxContourEventHandler::checkInformationPanel(){
3732                 if (_InformationContourFrame==NULL){
3733                         onInformationContourFrame();
3734                         _InformationContourFrame->Show(false);
3735                 }               
3736         }
3737
3738         std::string wxContourEventHandler::intToString(int num){
3739                 std::string result;
3740                 if(num == 0){
3741                         result = "0";
3742                 }else{
3743                         int k=num;
3744                         while (k > 0){
3745                                 char temp = k % 10 + 48;
3746                                 k = k / 10;
3747                                 result = temp + result; 
3748                         }
3749                 }
3750                 return result;
3751         }
3752 //JCP 21 - 10 - 09
3753
3754