Salome HOME
Merge from V6_5_BR 05/06/2012
[modules/smesh.git] / src / SMESHGUI / SMESHGUI_VTKUtils.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // SMESH SMESHGUI : GUI for SMESH component
24 // File   : SMESHGUI_VTKUtils.cxx
25 // Author : Open CASCADE S.A.S.
26 // SMESH includes
27 //
28 #include "SMESHGUI_VTKUtils.h"
29
30 #include "SMESHGUI.h"
31 #include "SMESHGUI_Utils.h"
32 #include "SMESHGUI_Filter.h"
33 #include "SMESH_ControlsDef.hxx"
34
35 #include <SMESH_Actor.h>
36 #include <SMESH_ActorUtils.h>
37 #include <SMESH_ObjectDef.h>
38 #include <SMDS_Mesh.hxx>
39
40 // SALOME GUI includes
41 #include <SUIT_Desktop.h>
42 #include <SUIT_Session.h>
43 #include <SUIT_MessageBox.h>
44 #include <SUIT_ViewManager.h>
45 #include <SUIT_ResourceMgr.h>
46
47 #include <SALOME_ListIO.hxx>
48 #include <SALOME_ListIteratorOfListIO.hxx>
49
50 #include <SVTK_Selector.h>
51 #include <SVTK_ViewModel.h>
52 #include <SVTK_ViewWindow.h>
53
54 #include <VTKViewer_Algorithm.h>
55
56 #include <LightApp_SelectionMgr.h>
57 #include <SalomeApp_Application.h>
58 #include <SalomeApp_Study.h>
59
60 // SALOME KERNEL includes
61 #include <utilities.h>
62
63 // IDL includes
64 #include <SALOMEconfig.h>
65 #include CORBA_CLIENT_HEADER(SMESH_Mesh)
66 #include CORBA_CLIENT_HEADER(SMESH_Group)
67
68 // VTK includes
69 #include <vtkMath.h>
70 #include <vtkRenderer.h>
71 #include <vtkActorCollection.h>
72 #include <vtkUnstructuredGrid.h>
73
74 // OCCT includes
75 #include <TColStd_IndexedMapOfInteger.hxx>
76 #include <Standard_ErrorHandler.hxx>
77
78 namespace SMESH
79 {
80   typedef std::map<TKeyOfVisualObj,TVisualObjPtr> TVisualObjCont;
81   static TVisualObjCont VISUAL_OBJ_CONT;
82
83   //=============================================================================
84   /*!
85    * \brief Allocate some memory at construction and release it at destruction.
86    * Is used to be able to continue working after mesh generation or visualization
87    * break due to lack of memory
88    */
89   //=============================================================================
90
91   struct MemoryReserve
92   {
93     char* myBuf;
94     MemoryReserve(): myBuf( new char[1024*1024*1] ){} // 1M
95     void Free() { if (myBuf) { delete [] myBuf; myBuf = 0; }}
96     ~MemoryReserve() { Free(); }
97   };
98   static MemoryReserve* theVISU_MemoryReserve = new MemoryReserve;
99
100   //================================================================================
101   /*!
102    * \brief Remove VisualObj and its actor from all views
103    */
104   //================================================================================
105
106   void RemoveVisualObjectWithActors( const char* theEntry, bool fromAllViews )
107   {
108     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>(SUIT_Session::session()->activeApplication());
109     if(!app)
110       return;
111     SalomeApp_Study* aStudy  = dynamic_cast<SalomeApp_Study*>(app->activeStudy());
112     if(!aStudy)
113       return;
114     ViewManagerList aList;
115
116     if(fromAllViews) {
117       app->viewManagers(SVTK_Viewer::Type() , aList);
118     } else {
119       SUIT_ViewManager* aVM = app->getViewManager(SVTK_Viewer::Type(), true);
120       if(aVM)
121         aList.append(aVM);
122     }    
123     bool actorRemoved = false;
124     ViewManagerList::ConstIterator it = aList.begin();
125     SUIT_ViewManager* aViewManager = 0;
126     for( ; it!=aList.end();it++) {
127       aViewManager = *it;
128       QVector<SUIT_ViewWindow*> views = aViewManager->getViews();
129       for ( int iV = 0; iV < views.count(); ++iV ) {
130         if ( SMESH_Actor* actor = FindActorByEntry( views[iV], theEntry)) {
131           if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(views[iV])) {
132             vtkWnd->RemoveActor(actor);
133             actorRemoved = true;
134           }
135           actor->Delete();
136         }
137       }
138     }
139     
140     if (aViewManager ) {
141       int aStudyId = aViewManager->study()->id();
142       TVisualObjCont::key_type aKey(aStudyId,theEntry);
143       TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.find(aKey);
144       if(anIter != VISUAL_OBJ_CONT.end()) {
145         // for unknown reason, object destructor is not called, so clear object manually
146         anIter->second->GetUnstructuredGrid()->SetCells(0,0,0,0,0);
147         anIter->second->GetUnstructuredGrid()->SetPoints(0);
148       }
149       VISUAL_OBJ_CONT.erase(aKey);
150     }
151
152     if(actorRemoved)
153       aStudy->setVisibilityState(theEntry, Qtx::HiddenState);
154   }
155   //================================================================================
156   /*!
157    * \brief Remove all VisualObjs and their actors from all views
158    */
159   //================================================================================
160
161   void RemoveAllObjectsWithActors()
162   {
163     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>
164       ( SUIT_Session::session()->activeApplication() );
165     if (!app) return;
166     ViewManagerList viewMgrs = app->viewManagers();
167     for ( int iM = 0; iM < viewMgrs.count(); ++iM ) {
168       SUIT_ViewManager* aViewManager = viewMgrs.at( iM );
169       if ( aViewManager && aViewManager->getType() == SVTK_Viewer::Type()) {
170         QVector<SUIT_ViewWindow*> views = aViewManager->getViews();
171         for ( int iV = 0; iV < views.count(); ++iV ) {
172           if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(views[iV])) {
173             vtkRenderer *aRenderer = vtkWnd->getRenderer();
174             VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
175             vtkActorCollection *actors = aCopy.GetActors();
176             for (int i = 0; i < actors->GetNumberOfItems(); ++i ) {
177               // size of actors changes inside the loop
178               if (SMESH_Actor *actor = dynamic_cast<SMESH_Actor*>(actors->GetItemAsObject(i)))
179               {
180                 vtkWnd->RemoveActor(actor);
181                 actor->Delete();
182               }
183             }
184           }
185         }
186       }
187     }
188     TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.begin();
189     for ( ; anIter != VISUAL_OBJ_CONT.end(); ++anIter ) {
190       // for unknown reason, object destructor is not called, so clear object manually
191       anIter->second->GetUnstructuredGrid()->SetCells(0,0,0,0,0);
192       anIter->second->GetUnstructuredGrid()->SetPoints(0);
193     }
194     VISUAL_OBJ_CONT.clear();
195   }
196
197   //================================================================================
198   /*!
199    * \brief Remove all VisualObjs of a study
200    */
201   //================================================================================
202
203   void RemoveVisuData(int studyID)
204   {
205     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>
206       ( SUIT_Session::session()->activeApplication() );
207     if (!app) return;
208     ViewManagerList viewMgrs = app->viewManagers();
209     for ( int iM = 0; iM < viewMgrs.count(); ++iM ) {
210       SUIT_ViewManager* aViewManager = viewMgrs.at( iM );
211       if ( aViewManager && aViewManager->getType() == SVTK_Viewer::Type() &&
212            aViewManager->study()->id() == studyID ) {
213         QVector<SUIT_ViewWindow*> views = aViewManager->getViews();
214         for ( int iV = 0; iV < views.count(); ++iV ) {
215           if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(views[iV])) {
216             vtkRenderer *aRenderer = vtkWnd->getRenderer();
217             VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
218             vtkActorCollection *actors = aCopy.GetActors();
219             for (int i = 0; i < actors->GetNumberOfItems(); ++i ) {
220               // size of actors changes inside the loop
221               if(SMESH_Actor *actor = dynamic_cast<SMESH_Actor*>(actors->GetItemAsObject(i)))
222               {
223                 vtkWnd->RemoveActor(actor);
224                 actor->Delete();
225               }
226             }
227           }
228         }
229       }
230     }
231     TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.begin();
232     for ( ; anIter != VISUAL_OBJ_CONT.end(); ) {
233       int curId = anIter->first.first;
234       if ( curId == studyID ) {
235         // for unknown reason, object destructor is not called, so clear object manually
236         anIter->second->GetUnstructuredGrid()->SetCells(0,0,0,0,0);
237         anIter->second->GetUnstructuredGrid()->SetPoints(0);
238         VISUAL_OBJ_CONT.erase( anIter++ ); // anIter++ returns a copy of self before incrementing
239       }
240       else {
241         anIter++;
242       }
243     }
244   }
245
246   //================================================================================
247   /*!
248    * \brief Notify the user on problems during visualization
249    */
250   //================================================================================
251
252   void OnVisuException()
253   {
254     try {
255 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
256       OCC_CATCH_SIGNALS;
257 #endif
258       // PAL16774 (Crash after display of many groups). Salome sometimes crashes just
259       // after or at showing this message, so we do an additional check of available memory
260 //       char* buf = new char[100*1024];
261 //       delete [] buf;
262       SUIT_MessageBox::warning(SMESHGUI::desktop(), QObject::tr("SMESH_WRN_WARNING"),
263                                QObject::tr("SMESH_VISU_PROBLEM"));
264     } catch (...) {
265       // no more memory at all: last resort
266       MESSAGE_BEGIN ( "SMESHGUI_VTKUtils::OnVisuException(), exception even at showing a message!!!" <<
267                       std::endl << "Try to remove all visual data..." );
268       if (theVISU_MemoryReserve) {
269         delete theVISU_MemoryReserve;
270         theVISU_MemoryReserve = 0;
271       }
272       RemoveAllObjectsWithActors();
273       SUIT_MessageBox::warning(SMESHGUI::desktop(), QObject::tr("SMESH_WRN_WARNING"),
274                                QObject::tr("SMESH_VISU_PROBLEM_CLEAR"));
275       MESSAGE_END ( "...done" );
276     }
277   }
278   //================================================================================
279   /*!
280    * \brief Returns an updated visual object
281    */
282   //================================================================================
283
284   TVisualObjPtr GetVisualObj(int theStudyId, const char* theEntry, bool nulData){
285     TVisualObjPtr aVisualObj;
286     TVisualObjCont::key_type aKey(theStudyId,theEntry);
287     try{
288 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
289       OCC_CATCH_SIGNALS;
290 #endif
291       TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.find(aKey);
292       if(anIter != VISUAL_OBJ_CONT.end()){
293         aVisualObj = anIter->second;
294       }else{
295         SalomeApp_Application* app =
296           dynamic_cast<SalomeApp_Application*>( SMESHGUI::activeStudy()->application() );
297         _PTR(Study) aStudy = SMESHGUI::activeStudy()->studyDS();
298         _PTR(SObject) aSObj = aStudy->FindObjectID(theEntry);
299         if(aSObj){
300           _PTR(GenericAttribute) anAttr;
301           if(aSObj->FindAttribute(anAttr,"AttributeIOR")){
302             _PTR(AttributeIOR) anIOR = anAttr;
303             CORBA::String_var aVal = anIOR->Value().c_str();
304             CORBA::Object_var anObj = app->orb()->string_to_object( aVal.in() );
305             if(!CORBA::is_nil(anObj)){
306               //Try narrow to SMESH_Mesh interface
307               SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_narrow(anObj);
308               if(!aMesh->_is_nil()){
309                 aVisualObj.reset(new SMESH_MeshObj(aMesh));
310                 TVisualObjCont::value_type aValue(aKey,aVisualObj);
311                 VISUAL_OBJ_CONT.insert(aValue);
312               }
313               //Try narrow to SMESH_Group interface
314               SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow(anObj);
315               if(!aGroup->_is_nil()){
316                 _PTR(SObject) aFatherSObj = aSObj->GetFather();
317                 if(!aFatherSObj) return aVisualObj;
318                 aFatherSObj = aFatherSObj->GetFather();
319                 if(!aFatherSObj) return aVisualObj;
320                 CORBA::String_var anEntry = aFatherSObj->GetID().c_str();
321                 TVisualObjPtr aVisObj = GetVisualObj(theStudyId,anEntry.in());
322                 if(SMESH_MeshObj* aMeshObj = dynamic_cast<SMESH_MeshObj*>(aVisObj.get())){
323                   aVisualObj.reset(new SMESH_GroupObj(aGroup,aMeshObj));
324                   TVisualObjCont::value_type aValue(aKey,aVisualObj);
325                   VISUAL_OBJ_CONT.insert(aValue);
326                 }
327               }
328               //Try narrow to SMESH_subMesh interface
329               SMESH::SMESH_subMesh_var aSubMesh = SMESH::SMESH_subMesh::_narrow(anObj);
330               if(!aSubMesh->_is_nil()){
331                 _PTR(SObject) aFatherSObj = aSObj->GetFather();
332                 if(!aFatherSObj) return aVisualObj;
333                 aFatherSObj = aFatherSObj->GetFather();
334                 if(!aFatherSObj) return aVisualObj;
335                 CORBA::String_var anEntry = aFatherSObj->GetID().c_str();
336                 TVisualObjPtr aVisObj = GetVisualObj(theStudyId,anEntry.in());
337                 if(SMESH_MeshObj* aMeshObj = dynamic_cast<SMESH_MeshObj*>(aVisObj.get())){
338                   aVisualObj.reset(new SMESH_subMeshObj(aSubMesh,aMeshObj));
339                   TVisualObjCont::value_type aValue(aKey,aVisualObj);
340                   VISUAL_OBJ_CONT.insert(aValue);
341                 }
342               }
343             }
344           }
345         }
346       }
347     }catch(...){
348       INFOS("GetMeshObj - There is no SMESH_Mesh object for the SALOMEDS::Strudy and Entry!!!");
349       return TVisualObjPtr();
350     }
351     // Update object
352     bool objModified = false;
353     if ( aVisualObj ) {
354       try {
355 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
356         OCC_CATCH_SIGNALS;
357 #endif
358         //MESSAGE("GetVisualObj");
359         if (nulData)
360                 objModified = aVisualObj->NulData();
361         else
362           objModified = aVisualObj->Update();
363       }
364       catch (...) {
365 #ifdef _DEBUG_
366         MESSAGE ( "Exception in SMESHGUI_VTKUtils::GetVisualObj()" );
367 #endif
368         RemoveVisualObjectWithActors( theEntry ); // remove this object
369         OnVisuException();
370         aVisualObj.reset();
371       }
372     }
373
374     if ( objModified ) {
375       // PAL16631. Mesurements showed that to show aVisualObj in SHADING(default) mode,
376       // ~5 times more memory is used than it occupies.
377       // Warn the user if there is less free memory than 30 sizes of a grid
378       // TODO: estimate memory usage in other modes and take current mode into account
379       int freeMB = SMDS_Mesh::CheckMemory(true);
380       int usedMB = aVisualObj->GetUnstructuredGrid()->GetActualMemorySize() / 1024;
381       MESSAGE("SMESHGUI_VTKUtils::GetVisualObj(), freeMB=" << freeMB << ", usedMB=" <<usedMB);
382       if ( freeMB > 0 && usedMB * 5 > freeMB ) {
383        bool continu = false;
384        if ( usedMB * 3 > freeMB )
385          // even dont try to show
386          SUIT_MessageBox::warning(SMESHGUI::desktop(), QObject::tr("SMESH_WRN_WARNING"),
387                                   QObject::tr("SMESH_NO_MESH_VISUALIZATION"));
388        else
389          // there is a chance to succeed
390          continu = SUIT_MessageBox::warning
391            (SMESHGUI::desktop(),
392             QObject::tr("SMESH_WRN_WARNING"),
393             QObject::tr("SMESH_CONTINUE_MESH_VISUALIZATION"),
394             SUIT_MessageBox::Yes | SUIT_MessageBox::No,
395             SUIT_MessageBox::Yes ) == SUIT_MessageBox::Yes;
396        if ( !continu ) {
397          // remove the corresponding actors from all views
398          RemoveVisualObjectWithActors( theEntry );
399          aVisualObj.reset();
400        }
401       }
402     }
403
404     return aVisualObj;
405   }
406
407
408   /*! Return active view window, if it instantiates SVTK_ViewWindow class,
409    *  overwise find or create corresponding view window, make it active and return it.
410    *  \note Active VVTK_ViewWindow can be returned, because it inherits SVTK_ViewWindow.
411    */
412   SVTK_ViewWindow* GetViewWindow (const SalomeApp_Module* theModule,
413                                   bool createIfNotFound)
414   {
415     SalomeApp_Application* anApp;
416     if (theModule)
417       anApp = theModule->getApp();
418     else
419       anApp = dynamic_cast<SalomeApp_Application*>
420         (SUIT_Session::session()->activeApplication());
421
422     if (anApp) {
423       if (SVTK_ViewWindow* aView = dynamic_cast<SVTK_ViewWindow*>(anApp->desktop()->activeWindow()))
424         return aView;
425
426       SUIT_ViewManager* aViewManager =
427         anApp->getViewManager(SVTK_Viewer::Type(), createIfNotFound);
428       if (aViewManager) {
429         if (SUIT_ViewWindow* aViewWindow = aViewManager->getActiveView()) {
430           if (SVTK_ViewWindow* aView = dynamic_cast<SVTK_ViewWindow*>(aViewWindow)) {
431             aViewWindow->raise();
432             aViewWindow->setFocus();
433             return aView;
434           }
435         }
436       }
437     }
438     return NULL;
439   }
440
441   SVTK_ViewWindow* FindVtkViewWindow (SUIT_ViewManager* theMgr,
442                                       SUIT_ViewWindow * theWindow)
443   {
444     if( !theMgr )
445       return NULL;
446
447     QVector<SUIT_ViewWindow*> views = theMgr->getViews();
448     if( views.contains( theWindow ) )
449       return GetVtkViewWindow( theWindow );
450     else
451       return NULL;
452   }
453
454   SVTK_ViewWindow* GetVtkViewWindow(SUIT_ViewWindow* theWindow){
455     return dynamic_cast<SVTK_ViewWindow*>(theWindow);
456   }
457
458 /*  SUIT_ViewWindow* GetActiveWindow()
459   {
460     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
461     if( !app )
462       return NULL;
463     SUIT_ViewManager* mgr = app->activeViewManager();
464     if( mgr )
465       return mgr->getActiveView();
466     else
467       return NULL;
468   }*/
469
470   SVTK_ViewWindow* GetCurrentVtkView(){
471     return GetVtkViewWindow( GetActiveWindow() );
472   }
473
474
475   void RepaintCurrentView()
476   {
477     if (SVTK_ViewWindow* wnd = GetCurrentVtkView())
478     {
479       try {
480 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
481         OCC_CATCH_SIGNALS;
482 #endif
483         wnd->getRenderer()->Render();
484         wnd->Repaint(false);
485       }
486       catch (...) {
487 #ifdef _DEBUG_
488         MESSAGE ( "Exception in SMESHGUI_VTKUtils::RepaintCurrentView()" );
489 #endif
490         OnVisuException();
491       }
492     }
493   }
494
495   void RepaintViewWindow(SVTK_ViewWindow* theWindow)
496   {
497     try {
498 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
499       OCC_CATCH_SIGNALS;
500 #endif
501       theWindow->getRenderer()->Render();
502       theWindow->Repaint();
503     }
504     catch (...) {
505 #ifdef _DEBUG_
506       MESSAGE ( "Exception in SMESHGUI_VTKUtils::RepaintViewWindow(SVTK_ViewWindow*)" );
507 #endif
508       OnVisuException();
509     }
510   }
511
512   void RenderViewWindow(SVTK_ViewWindow* theWindow)
513   {
514     try {
515 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
516       OCC_CATCH_SIGNALS;
517 #endif
518       theWindow->getRenderer()->Render();
519       theWindow->Repaint();
520     }
521     catch (...) {
522 #ifdef _DEBUG_
523       MESSAGE ( "Exception in SMESHGUI_VTKUtils::RenderViewWindow(SVTK_ViewWindow*)" );
524 #endif
525       OnVisuException();
526     }
527   }
528
529   void FitAll(){
530     if(SVTK_ViewWindow* wnd = GetCurrentVtkView() ){
531       try {
532 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
533         OCC_CATCH_SIGNALS;
534 #endif
535         wnd->onFitAll();
536         wnd->Repaint();
537       }
538       catch (...) {
539 #ifdef _DEBUG_
540         MESSAGE ( "Exception in SMESHGUI_VTKUtils::FitAll()" );
541 #endif
542         OnVisuException();
543       }
544     }
545   }
546
547
548   SMESH_Actor* FindActorByEntry(SUIT_ViewWindow *theWindow,
549                                 const char* theEntry)
550   {
551     if(SVTK_ViewWindow* aViewWindow = GetVtkViewWindow(theWindow)){
552       vtkRenderer *aRenderer = aViewWindow->getRenderer();
553       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
554       vtkActorCollection *aCollection = aCopy.GetActors();
555       aCollection->InitTraversal();
556       while(vtkActor *anAct = aCollection->GetNextActor()){
557         if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
558           if(anActor->hasIO()){
559             Handle(SALOME_InteractiveObject) anIO = anActor->getIO();
560             if(anIO->hasEntry() && strcmp(anIO->getEntry(),theEntry) == 0){
561               return anActor;
562             }
563           }
564         }
565       }
566     }
567     return NULL;
568   }
569
570
571   SMESH_Actor* FindActorByEntry(const char* theEntry){
572     return FindActorByEntry(GetActiveWindow(),theEntry);
573   }
574
575
576   SMESH_Actor* FindActorByObject(CORBA::Object_ptr theObject){
577     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
578     if( !app )
579       return NULL;
580
581     if(!CORBA::is_nil(theObject)){
582       _PTR(Study) aStudy = GetActiveStudyDocument();
583       CORBA::String_var anIOR = app->orb()->object_to_string( theObject );
584       _PTR(SObject) aSObject = aStudy->FindObjectIOR(anIOR.in());
585       if(aSObject){
586         CORBA::String_var anEntry = aSObject->GetID().c_str();
587         return FindActorByEntry(anEntry.in());
588       }
589     }
590     return NULL;
591   }
592
593
594   SMESH_Actor* CreateActor(_PTR(Study) theStudy,
595                            const char* theEntry,
596                            int theIsClear)
597   {
598     SMESH_Actor *anActor = NULL;
599     CORBA::Long anId = theStudy->StudyId();
600     if(TVisualObjPtr aVisualObj = GetVisualObj(anId,theEntry)){
601       _PTR(SObject) aSObj = theStudy->FindObjectID(theEntry);
602       if(aSObj){
603         _PTR(GenericAttribute) anAttr;
604         if(aSObj->FindAttribute(anAttr,"AttributeName")){
605           _PTR(AttributeName) aName = anAttr;
606           std::string aNameVal = aName->Value();
607           anActor = SMESH_Actor::New(aVisualObj,theEntry,aNameVal.c_str(),theIsClear);
608         }
609
610         SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SMESH::SObjectToObject( aSObj ));
611         if(!CORBA::is_nil(aGroup) && anActor)
612         {
613           QColor c;int delta;
614           SMESH::GetColor( "SMESH", "fill_color", c, delta, "0,170,255|-100"  );
615           SALOMEDS::Color aColor = aGroup->GetColor();
616           if( !( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 ))
617           {
618             aColor.R = (float)c.red() / 255.0;
619             aColor.G = (float)c.green() / 255.0;
620             aColor.B = (float)c.blue() / 255.0;
621             aGroup->SetColor( aColor );
622           }
623           if( aGroup->GetType() == SMESH::NODE )
624             anActor->SetNodeColor( aColor.R, aColor.G, aColor.B );
625           else if( aGroup->GetType() == SMESH::EDGE )
626             anActor->SetEdgeColor( aColor.R, aColor.G, aColor.B );
627           else if( aGroup->GetType() == SMESH::ELEM0D )
628             anActor->Set0DColor( aColor.R, aColor.G, aColor.B );
629           else
630             anActor->SetSufaceColor( aColor.R, aColor.G, aColor.B, delta );
631         }
632       }
633     }
634     MESSAGE("CreateActor " << anActor);
635     if( anActor )
636       if( SMESHGUI* aSMESHGUI = SMESHGUI::GetSMESHGUI() )
637         aSMESHGUI->addActorAsObserver( anActor );
638     return anActor;
639   }
640
641
642   void DisplayActor( SUIT_ViewWindow *theWnd, SMESH_Actor* theActor){
643     if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(theWnd)){
644       try {
645 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
646         OCC_CATCH_SIGNALS;
647 #endif
648         MESSAGE("DisplayActor " << theActor);
649         vtkWnd->AddActor(theActor);
650         vtkWnd->Repaint();
651       }
652       catch (...) {
653 #ifdef _DEBUG_
654         MESSAGE ( "Exception in SMESHGUI_VTKUtils::DisplayActor()" );
655 #endif
656         OnVisuException();
657       }
658     }
659   }
660
661
662   void RemoveActor( SUIT_ViewWindow *theWnd, SMESH_Actor* theActor){
663     if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(theWnd)){
664         MESSAGE("RemoveActor " << theActor);
665       vtkWnd->RemoveActor(theActor);
666       if(theActor->hasIO()){
667         Handle(SALOME_InteractiveObject) anIO = theActor->getIO();
668         if(anIO->hasEntry()){
669           std::string anEntry = anIO->getEntry();
670           SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>( vtkWnd->getViewManager()->study() );
671           int aStudyId = aStudy->id();
672           TVisualObjCont::key_type aKey(aStudyId,anEntry);
673           VISUAL_OBJ_CONT.erase(aKey);
674         }
675       }
676       theActor->Delete();
677       vtkWnd->Repaint();
678     }
679   }
680
681   //================================================================================
682   /*!
683    * \brief Return true if there are no SMESH actors in a view
684    */
685   //================================================================================
686
687   bool noSmeshActors(SUIT_ViewWindow *theWnd)
688   {
689     if(SVTK_ViewWindow* aViewWindow = GetVtkViewWindow(theWnd)) {
690       vtkRenderer *aRenderer = aViewWindow->getRenderer();
691       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
692       vtkActorCollection *aCollection = aCopy.GetActors();
693       aCollection->InitTraversal();
694       while(vtkActor *anAct = aCollection->GetNextActor())
695         if(dynamic_cast<SMESH_Actor*>(anAct))
696           return false;
697     }
698     return true;
699   }
700
701   bool UpdateView(SUIT_ViewWindow *theWnd, EDisplaing theAction, const char* theEntry)
702   {
703         //MESSAGE("UpdateView");
704     bool OK = false;
705     SVTK_ViewWindow* aViewWnd = GetVtkViewWindow(theWnd);
706     if (!aViewWnd)
707       return OK;
708
709     SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(theWnd);
710     if (!vtkWnd)
711       return OK;
712
713     SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>( vtkWnd->getViewManager()->study() );
714     
715     if (!aStudy)
716       return OK;
717
718     {
719       OK = true;
720       vtkRenderer *aRenderer = aViewWnd->getRenderer();
721       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
722       vtkActorCollection *aCollection = aCopy.GetActors();
723       aCollection->InitTraversal();
724
725       switch (theAction) {
726       case eDisplayAll: {
727         while (vtkActor *anAct = aCollection->GetNextActor()) {
728           if (SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)) {
729                 MESSAGE("--- display " << anActor);
730             anActor->SetVisibility(true);
731
732             if(anActor->hasIO()){
733               Handle(SALOME_InteractiveObject) anIO = anActor->getIO();
734               if(anIO->hasEntry()){
735                 aStudy->setVisibilityState(anIO->getEntry(), Qtx::ShownState);
736               }
737             }
738           }
739         }
740         break;
741       }
742       case eDisplayOnly:
743       case eEraseAll: {
744         //MESSAGE("---case eDisplayOnly");
745         while (vtkActor *anAct = aCollection->GetNextActor()) {
746           if (SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)) {
747                 //MESSAGE("--- erase " << anActor);
748             anActor->SetVisibility(false);
749           }
750         }
751         aStudy->setVisibilityStateForAll(Qtx::HiddenState);
752       }
753       default: {
754         if (SMESH_Actor *anActor = FindActorByEntry(theWnd,theEntry)) {
755           switch (theAction) {
756             case eDisplay:
757             case eDisplayOnly:
758                 //MESSAGE("--- display " << anActor);
759               anActor->Update();
760               anActor->SetVisibility(true);
761               if (theAction == eDisplayOnly) aRenderer->ResetCameraClippingRange();
762               aStudy->setVisibilityState(theEntry, Qtx::ShownState);
763               break;
764             case eErase:
765                 //MESSAGE("--- erase " << anActor);
766               anActor->SetVisibility(false);
767               aStudy->setVisibilityState(theEntry, Qtx::HiddenState);
768               break;
769           }
770         } else {
771           switch (theAction) {
772           case eDisplay:
773           case eDisplayOnly:
774             {
775                 //MESSAGE("---");
776               SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>(theWnd->getViewManager()->study());
777               _PTR(Study) aDocument = aStudy->studyDS();
778               // Pass non-visual objects (hypotheses, etc.), return true in this case
779               CORBA::Long anId = aDocument->StudyId();
780               TVisualObjPtr aVisualObj;
781               if ( (aVisualObj = GetVisualObj(anId,theEntry)) && aVisualObj->IsValid())
782               {
783                 if ((anActor = CreateActor(aDocument,theEntry,true))) {
784                   bool needFitAll = noSmeshActors(theWnd); // fit for the first object only
785                   DisplayActor(theWnd,anActor);
786                   aStudy->setVisibilityState(theEntry, Qtx::ShownState);
787                   // FitAll(); - PAL16770(Display of a group performs an automatic fit all)
788                   if (needFitAll) FitAll();
789                 } else {
790                   OK = false;
791                 }
792               }
793               break;
794             }
795           }
796         }
797       }
798       }
799     }
800     return OK;
801   }
802
803
804   bool UpdateView(EDisplaing theAction, const char* theEntry){
805         //MESSAGE("UpdateView");
806     SalomeApp_Study* aStudy = dynamic_cast< SalomeApp_Study* >( GetActiveStudy() );
807     SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( aStudy->application() );
808     SUIT_ViewWindow *aWnd = app->activeViewManager()->getActiveView();
809     return UpdateView(aWnd,theAction,theEntry);
810   }
811
812   void UpdateView(){
813     if(SVTK_ViewWindow* aWnd = SMESH::GetCurrentVtkView()){
814       LightApp_SelectionMgr* mgr = SMESHGUI::selectionMgr();
815       SALOME_ListIO selected; mgr->selectedObjects( selected );
816
817       if( selected.Extent() == 0){
818         vtkRenderer* aRenderer = aWnd->getRenderer();
819         VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
820         vtkActorCollection *aCollection = aCopy.GetActors();
821         aCollection->InitTraversal();
822         while(vtkActor *anAct = aCollection->GetNextActor()){
823           if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
824             if(anActor->hasIO())
825               if (!Update(anActor->getIO(),anActor->GetVisibility()))
826                 break; // avoid multiple warinings if visu failed
827           }
828         }
829       }else{
830         SALOME_ListIteratorOfListIO anIter( selected );
831         for( ; anIter.More(); anIter.Next()){
832           Handle(SALOME_InteractiveObject) anIO = anIter.Value();
833           if ( !Update(anIO,true) )
834             break; // avoid multiple warinings if visu failed
835         }
836       }
837       RepaintCurrentView();
838     }
839   }
840
841
842   bool Update(const Handle(SALOME_InteractiveObject)& theIO, bool theDisplay)
843   {
844         MESSAGE("Update");
845     _PTR(Study) aStudy = GetActiveStudyDocument();
846     CORBA::Long anId = aStudy->StudyId();
847     if ( TVisualObjPtr aVisualObj = SMESH::GetVisualObj(anId,theIO->getEntry())) {
848       if ( theDisplay )
849         UpdateView(SMESH::eDisplay,theIO->getEntry());
850       return true;
851     }
852     return false;
853   }
854
855   bool UpdateNulData(const Handle(SALOME_InteractiveObject)& theIO, bool theDisplay)
856   {
857         MESSAGE("UpdateNulData");
858     _PTR(Study) aStudy = GetActiveStudyDocument();
859     CORBA::Long anId = aStudy->StudyId();
860     if ( TVisualObjPtr aVisualObj = SMESH::GetVisualObj(anId,theIO->getEntry(), true)) {
861       if ( theDisplay )
862         UpdateView(SMESH::eDisplay,theIO->getEntry());
863       return true;
864     }
865     return false;
866   }
867
868   void UpdateSelectionProp( SMESHGUI* theModule ) {
869     if( !theModule )
870       return;
871
872     SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( theModule->application() );
873     if( !app )
874     {
875       MESSAGE( "UpdateSelectionProp: Application is null" );
876       return;
877     }
878
879     SUIT_ViewManager* vm = app->activeViewManager();
880     if( !vm )
881     {
882       MESSAGE( "UpdateSelectionProp: View manager is null" );
883       return;
884     }
885
886     QVector<SUIT_ViewWindow*> views = vm->getViews();
887
888     SUIT_ResourceMgr* mgr = SMESH::GetResourceMgr( theModule );
889     if( !mgr )
890     {
891       MESSAGE( "UpdateSelectionProp: Resource manager is null" );
892       return;
893     }
894
895     QColor aHiColor = mgr->colorValue( "SMESH", "selection_object_color", Qt::white ),
896            aSelColor = mgr->colorValue( "SMESH", "selection_element_color", Qt::yellow ),
897            aPreColor = mgr->colorValue( "SMESH", "highlight_color", Qt::cyan );
898
899     int aElem0DSize = mgr->integerValue("SMESH", "elem0d_size", 5);
900     int aLineWidth  = mgr->integerValue("SMESH", "element_width", 1);
901     int maxSize = aElem0DSize;
902     if (aElem0DSize > maxSize) maxSize = aElem0DSize;
903     if (aLineWidth > maxSize) maxSize = aLineWidth;
904
905     double SP1 = mgr->doubleValue( "SMESH", "selection_precision_node", 0.025 ),
906            SP2 = mgr->doubleValue( "SMESH", "selection_precision_element", 0.001 ),
907            SP3 = mgr->doubleValue( "SMESH", "selection_precision_object", 0.025 );
908
909     for ( int i=0, n=views.count(); i<n; i++ ){
910       // update VTK viewer properties
911       if(SVTK_ViewWindow* aVtkView = GetVtkViewWindow( views[i] )){
912         // mesh element selection
913         aVtkView->SetSelectionProp(aSelColor.red()/255.,
914                                    aSelColor.green()/255.,
915                                    aSelColor.blue()/255.);
916         // tolerances
917         aVtkView->SetSelectionTolerance(SP1, SP2, SP3);
918
919         // pre-selection
920         aVtkView->SetPreselectionProp(aPreColor.red()/255.,
921                                       aPreColor.green()/255.,
922                                       aPreColor.blue()/255.);
923         // update actors
924         vtkRenderer* aRenderer = aVtkView->getRenderer();
925         VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
926         vtkActorCollection *aCollection = aCopy.GetActors();
927         aCollection->InitTraversal();
928         while(vtkActor *anAct = aCollection->GetNextActor()){
929           if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
930             anActor->SetHighlightColor(aHiColor.red()/255.,
931                                        aHiColor.green()/255.,
932                                        aHiColor.blue()/255.);
933             anActor->SetPreHighlightColor(aPreColor.red()/255.,
934                                           aPreColor.green()/255.,
935                                           aPreColor.blue()/255.);
936           }
937         }
938       }
939     }
940   }
941
942
943   //----------------------------------------------------------------------------
944   SVTK_Selector*
945   GetSelector(SUIT_ViewWindow *theWindow)
946   {
947     if(SVTK_ViewWindow* aWnd = GetVtkViewWindow(theWindow))
948       return aWnd->GetSelector();
949
950     return NULL;
951   }
952
953   void SetFilter(const Handle(VTKViewer_Filter)& theFilter,
954                  SVTK_Selector* theSelector)
955   {
956     if (theSelector)
957       theSelector->SetFilter(theFilter);
958   }
959
960   Handle(VTKViewer_Filter) GetFilter(int theId, SVTK_Selector* theSelector)
961   {
962     return theSelector->GetFilter(theId);
963   }
964
965   bool IsFilterPresent(int theId, SVTK_Selector* theSelector)
966   {
967     return theSelector->IsFilterPresent(theId);
968   }
969
970   void RemoveFilter(int theId, SVTK_Selector* theSelector)
971   {
972     theSelector->RemoveFilter(theId);
973   }
974
975   void RemoveFilters(SVTK_Selector* theSelector)
976   {
977     for ( int id = SMESH::NodeFilter; theSelector && id < SMESH::LastFilter; id++ )
978       theSelector->RemoveFilter( id );
979   }
980
981   bool IsValid(SALOME_Actor* theActor, int theCellId,
982                SVTK_Selector* theSelector)
983   {
984     return theSelector->IsValid(theActor,theCellId);
985   }
986
987
988   //----------------------------------------------------------------------------
989   void SetPointRepresentation(bool theIsVisible){
990     if(SVTK_ViewWindow* aViewWindow = GetCurrentVtkView()){
991       vtkRenderer *aRenderer = aViewWindow->getRenderer();
992       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
993       vtkActorCollection *aCollection = aCopy.GetActors();
994       aCollection->InitTraversal();
995       while(vtkActor *anAct = aCollection->GetNextActor()){
996         if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
997           if(anActor->GetVisibility()){
998             anActor->SetPointRepresentation(theIsVisible);
999           }
1000         }
1001       }
1002       RepaintCurrentView();
1003     }
1004   }
1005
1006
1007   void SetPickable(SMESH_Actor* theActor){
1008     if(SVTK_ViewWindow* aWnd = GetCurrentVtkView()){
1009       int anIsAllPickable = (theActor == NULL);
1010       vtkRenderer *aRenderer = aWnd->getRenderer();
1011       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
1012       vtkActorCollection *aCollection = aCopy.GetActors();
1013       aCollection->InitTraversal();
1014       while(vtkActor *anAct = aCollection->GetNextActor()){
1015         if(SALOME_Actor *anActor = dynamic_cast<SALOME_Actor*>(anAct)){
1016           if(anActor->GetVisibility()){
1017             anActor->SetPickable(anIsAllPickable);
1018           }
1019         }
1020       }
1021       if(theActor)
1022         theActor->SetPickable(!anIsAllPickable);
1023       RepaintCurrentView();
1024     }
1025   }
1026
1027
1028   //----------------------------------------------------------------------------
1029   int GetNameOfSelectedNodes(SVTK_Selector* theSelector,
1030                              const Handle(SALOME_InteractiveObject)& theIO,
1031                              QString& theName)
1032   {
1033     theName = "";
1034     TColStd_IndexedMapOfInteger aMapIndex;
1035     theSelector->GetIndex(theIO,aMapIndex);
1036
1037     for(int i = 1; i <= aMapIndex.Extent(); i++)
1038       theName += QString(" %1").arg(aMapIndex(i));
1039
1040     return aMapIndex.Extent();
1041   }
1042
1043   int GetNameOfSelectedElements(SVTK_Selector* theSelector,
1044                                 const Handle(SALOME_InteractiveObject)& theIO,
1045                                 QString& theName)
1046   {
1047     theName = "";
1048     TColStd_IndexedMapOfInteger aMapIndex;
1049     theSelector->GetIndex(theIO,aMapIndex);
1050
1051     typedef std::set<int> TIdContainer;
1052     TIdContainer anIdContainer;
1053     for( int i = 1; i <= aMapIndex.Extent(); i++)
1054       anIdContainer.insert(aMapIndex(i));
1055
1056     TIdContainer::const_iterator anIter = anIdContainer.begin();
1057     for( ; anIter != anIdContainer.end(); anIter++)
1058       theName += QString(" %1").arg(*anIter);
1059
1060     return aMapIndex.Extent();
1061   }
1062
1063
1064   int GetEdgeNodes(SVTK_Selector* theSelector,
1065                    const TVisualObjPtr& theVisualObject,
1066                    int& theId1,
1067                    int& theId2)
1068   {
1069     const SALOME_ListIO& selected = theSelector->StoredIObjects();
1070
1071     if ( selected.Extent() != 1 )
1072       return -1;
1073
1074     Handle(SALOME_InteractiveObject) anIO = selected.First();
1075     if ( anIO.IsNull() || !anIO->hasEntry() )
1076       return -1;
1077
1078     TColStd_IndexedMapOfInteger aMapIndex;
1079     theSelector->GetIndex( anIO, aMapIndex );
1080     if ( aMapIndex.Extent() != 2 )
1081       return -1;
1082
1083     int anObjId = -1, anEdgeNum = -1;
1084     for ( int i = 1; i <= aMapIndex.Extent(); i++ ) {
1085       int aVal = aMapIndex( i );
1086       if ( aVal > 0 )
1087         anObjId = aVal;
1088       else
1089         anEdgeNum = abs( aVal ) - 1;
1090     }
1091
1092     if ( anObjId == -1 || anEdgeNum == -1 )
1093       return -1;
1094
1095     return theVisualObject->GetEdgeNodes( anObjId, anEdgeNum, theId1, theId2 ) ? 1 : -1;
1096   }
1097
1098   //----------------------------------------------------------------------------
1099   int GetNameOfSelectedNodes(LightApp_SelectionMgr *theMgr,
1100                              const Handle(SALOME_InteractiveObject)& theIO,
1101                              QString& theName)
1102   {
1103     theName = "";
1104     if(theIO->hasEntry()){
1105       if(FindActorByEntry(theIO->getEntry())){
1106         TColStd_IndexedMapOfInteger aMapIndex;
1107         theMgr->GetIndexes(theIO,aMapIndex);
1108         for(int i = 1; i <= aMapIndex.Extent(); i++){
1109           theName += QString(" %1").arg(aMapIndex(i));
1110         }
1111         return aMapIndex.Extent();
1112       }
1113     }
1114     return -1;
1115   }
1116
1117   int GetNameOfSelectedNodes(LightApp_SelectionMgr *theMgr, QString& theName){
1118     theName = "";
1119     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1120     if(selected.Extent() == 1){
1121       Handle(SALOME_InteractiveObject) anIO = selected.First();
1122       return GetNameOfSelectedNodes(theMgr,anIO,theName);
1123     }
1124     return -1;
1125   }
1126
1127
1128   int GetNameOfSelectedElements(LightApp_SelectionMgr *theMgr,
1129                                 const Handle(SALOME_InteractiveObject)& theIO,
1130                                 QString& theName)
1131   {
1132     theName = "";
1133     if(theIO->hasEntry()){
1134       if(FindActorByEntry(theIO->getEntry())){
1135         TColStd_IndexedMapOfInteger aMapIndex;
1136         theMgr->GetIndexes(theIO,aMapIndex);
1137         typedef std::set<int> TIdContainer;
1138         TIdContainer anIdContainer;
1139         for( int i = 1; i <= aMapIndex.Extent(); i++)
1140           anIdContainer.insert(aMapIndex(i));
1141         TIdContainer::const_iterator anIter = anIdContainer.begin();
1142         for( ; anIter != anIdContainer.end(); anIter++){
1143           theName += QString(" %1").arg(*anIter);
1144         }
1145         return aMapIndex.Extent();
1146       }
1147     }
1148     return -1;
1149   }
1150
1151
1152   int GetNameOfSelectedElements(LightApp_SelectionMgr *theMgr, QString& theName)
1153   {
1154     theName = "";
1155     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1156
1157     if( selected.Extent() == 1){
1158       Handle(SALOME_InteractiveObject) anIO = selected.First();
1159       return GetNameOfSelectedElements(theMgr,anIO,theName);
1160     }
1161     return -1;
1162   }
1163
1164   int GetSelected(LightApp_SelectionMgr*       theMgr,
1165                   TColStd_IndexedMapOfInteger& theMap,
1166                   const bool                   theIsElement)
1167   {
1168     theMap.Clear();
1169     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1170
1171     if ( selected.Extent() == 1 )
1172     {
1173       Handle(SALOME_InteractiveObject) anIO = selected.First();
1174       if ( anIO->hasEntry() ) {
1175         theMgr->GetIndexes( anIO, theMap );
1176       }
1177     }
1178     return theMap.Extent();
1179   }
1180
1181
1182   int GetEdgeNodes( LightApp_SelectionMgr* theMgr, int& theId1, int& theId2 )
1183   {
1184     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1185
1186     if ( selected.Extent() != 1 )
1187       return -1;
1188
1189     Handle(SALOME_InteractiveObject) anIO = selected.First();
1190     if ( anIO.IsNull() || !anIO->hasEntry() )
1191       return -1;
1192
1193     SMESH_Actor *anActor = SMESH::FindActorByEntry( anIO->getEntry() );
1194     if ( anActor == 0 )
1195       return -1;
1196
1197     TColStd_IndexedMapOfInteger aMapIndex;
1198     theMgr->GetIndexes( anIO, aMapIndex );
1199     if ( aMapIndex.Extent() != 2 )
1200       return -1;
1201
1202     int anObjId = -1, anEdgeNum = -1;
1203     for ( int i = 1; i <= aMapIndex.Extent(); i++ ) {
1204       int aVal = aMapIndex( i );
1205       if ( aVal > 0 )
1206         anObjId = aVal;
1207       else
1208         anEdgeNum = abs( aVal );
1209     }
1210
1211     if ( anObjId == -1 || anEdgeNum == -1 )
1212       return -1;
1213
1214     return anActor->GetObject()->GetEdgeNodes( anObjId, anEdgeNum, theId1, theId2 ) ? 1 : -1;
1215   }
1216
1217   void SetControlsPrecision( const long theVal )
1218   {
1219     if( SVTK_ViewWindow* aWnd = SMESH::GetCurrentVtkView() )
1220     {
1221       vtkRenderer *aRenderer = aWnd->getRenderer();
1222       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
1223       vtkActorCollection *aCollection = aCopy.GetActors();
1224       aCollection->InitTraversal();
1225
1226       while ( vtkActor *anAct = aCollection->GetNextActor())
1227       {
1228         if ( SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>( anAct ) )
1229         {
1230           anActor->SetControlsPrecision( theVal );
1231           anActor->SetControlMode( anActor->GetControlMode() );
1232         }
1233       }
1234
1235     }
1236   }
1237
1238   //----------------------------------------------------------------------------
1239   // internal function
1240   void ComputeBoundsParam( vtkFloatingPointType theBounds[6],
1241                            vtkFloatingPointType theDirection[3],
1242                            vtkFloatingPointType theMinPnt[3],
1243                            vtkFloatingPointType& theMaxBoundPrj,
1244                            vtkFloatingPointType& theMinBoundPrj )
1245   {
1246     //Enlarge bounds in order to avoid conflicts of precision
1247     for(int i = 0; i < 6; i += 2){
1248       static double EPS = 1.0E-3;
1249       vtkFloatingPointType aDelta = (theBounds[i+1] - theBounds[i])*EPS;
1250       theBounds[i] -= aDelta;
1251       theBounds[i+1] += aDelta;
1252     }
1253
1254     vtkFloatingPointType aBoundPoints[8][3] = { {theBounds[0],theBounds[2],theBounds[4]},
1255                                                 {theBounds[1],theBounds[2],theBounds[4]},
1256                                                 {theBounds[0],theBounds[3],theBounds[4]},
1257                                                 {theBounds[1],theBounds[3],theBounds[4]},
1258                                                 {theBounds[0],theBounds[2],theBounds[5]},
1259                                                 {theBounds[1],theBounds[2],theBounds[5]}, 
1260                                                 {theBounds[0],theBounds[3],theBounds[5]}, 
1261                                                 {theBounds[1],theBounds[3],theBounds[5]}};
1262
1263     int aMaxId = 0;
1264     theMaxBoundPrj = vtkMath::Dot(theDirection,aBoundPoints[aMaxId]);
1265     theMinBoundPrj = theMaxBoundPrj;
1266     for(int i = 1; i < 8; i++){
1267       vtkFloatingPointType aTmp = vtkMath::Dot(theDirection,aBoundPoints[i]);
1268       if(theMaxBoundPrj < aTmp){
1269         theMaxBoundPrj = aTmp;
1270         aMaxId = i;
1271       }
1272       if(theMinBoundPrj > aTmp){
1273         theMinBoundPrj = aTmp;
1274       }
1275     }
1276     vtkFloatingPointType *aMinPnt = aBoundPoints[aMaxId];
1277     theMinPnt[0] = aMinPnt[0];
1278     theMinPnt[1] = aMinPnt[1];
1279     theMinPnt[2] = aMinPnt[2];
1280   }
1281
1282   // internal function
1283   void DistanceToPosition( vtkFloatingPointType theBounds[6],
1284                            vtkFloatingPointType theDirection[3],
1285                            vtkFloatingPointType theDist,
1286                            vtkFloatingPointType thePos[3] )
1287   {
1288     vtkFloatingPointType aMaxBoundPrj, aMinBoundPrj, aMinPnt[3];
1289     ComputeBoundsParam(theBounds,theDirection,aMinPnt,aMaxBoundPrj,aMinBoundPrj);
1290     vtkFloatingPointType aLength = (aMaxBoundPrj-aMinBoundPrj)*theDist;
1291     thePos[0] = aMinPnt[0]-theDirection[0]*aLength;
1292     thePos[1] = aMinPnt[1]-theDirection[1]*aLength;
1293     thePos[2] = aMinPnt[2]-theDirection[2]*aLength;
1294   }
1295
1296   // internal function (currently unused, left just in case)
1297   void PositionToDistance( vtkFloatingPointType theBounds[6],
1298                            vtkFloatingPointType theDirection[3],
1299                            vtkFloatingPointType thePos[3],
1300                            vtkFloatingPointType& theDist )
1301   {
1302     vtkFloatingPointType aMaxBoundPrj, aMinBoundPrj, aMinPnt[3];
1303     ComputeBoundsParam(theBounds,theDirection,aMinPnt,aMaxBoundPrj,aMinBoundPrj);
1304     vtkFloatingPointType aPrj = vtkMath::Dot(theDirection,thePos);
1305     theDist = (aPrj-aMinBoundPrj)/(aMaxBoundPrj-aMinBoundPrj);
1306   }
1307
1308   bool ComputeClippingPlaneParameters( std::list<vtkActor*> theActorList,
1309                                        vtkFloatingPointType theNormal[3],
1310                                        vtkFloatingPointType theDist,
1311                                        vtkFloatingPointType theBounds[6],
1312                                        vtkFloatingPointType theOrigin[3] )
1313   {
1314     bool anIsOk = false;
1315     theBounds[0] = theBounds[2] = theBounds[4] = VTK_DOUBLE_MAX;
1316     theBounds[1] = theBounds[3] = theBounds[5] = -VTK_DOUBLE_MAX;
1317     std::list<vtkActor*>::iterator anIter = theActorList.begin();
1318     for( ; anIter != theActorList.end(); anIter++ ) {
1319       if( vtkActor* aVTKActor = *anIter ) {
1320         if( SMESH_Actor* anActor = SMESH_Actor::SafeDownCast( aVTKActor ) ) {
1321           vtkFloatingPointType aBounds[6];
1322           anActor->GetUnstructuredGrid()->GetBounds( aBounds );
1323           theBounds[0] = std::min( theBounds[0], aBounds[0] );
1324           theBounds[1] = std::max( theBounds[1], aBounds[1] );
1325           theBounds[2] = std::min( theBounds[2], aBounds[2] );
1326           theBounds[3] = std::max( theBounds[3], aBounds[3] );
1327           theBounds[4] = std::min( theBounds[4], aBounds[4] );
1328           theBounds[5] = std::max( theBounds[5], aBounds[5] );
1329           anIsOk = true;
1330         }
1331       }
1332     }
1333
1334     if( !anIsOk )
1335       return false;
1336
1337     DistanceToPosition( theBounds, theNormal, theDist, theOrigin );
1338     return true;
1339   }
1340
1341 #ifndef DISABLE_PLOT2DVIEWER
1342   //================================================================================
1343   /*!
1344    * \brief Find all SMESH_Actor's in the View Window.
1345    * If actor constains Plot2d_Histogram object remove it from each Plot2d Viewer.
1346    */
1347   //================================================================================
1348
1349   void ClearPlot2Viewers( SUIT_ViewWindow* theWindow ) {
1350     if(SVTK_ViewWindow* aViewWindow = GetVtkViewWindow(theWindow)){
1351       vtkRenderer *aRenderer = aViewWindow->getRenderer();
1352       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
1353       vtkActorCollection *aCollection = aCopy.GetActors();
1354       aCollection->InitTraversal();
1355       while(vtkActor *anAct = aCollection->GetNextActor()){
1356         if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
1357           if(anActor->hasIO() && anActor->GetPlot2Histogram() ){
1358             ProcessIn2DViewers(anActor,RemoveFrom2dViewer);
1359           }
1360         }
1361       }
1362     }
1363   }
1364   
1365 #endif
1366
1367 } // end of namespace SMESH