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