Salome HOME
00830c8d02e222788cb5275f00cc301a55e4cb5c
[modules/smesh.git] / src / SMESHGUI / SMESHGUI_VTKUtils.cxx
1 //  Copyright (C) 2007-2008  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 #include "SMESHGUI_VTKUtils.h"
23 #include "SMESHGUI_Utils.h"
24 #include "SMESHGUI_Filter.h"
25
26 #include "SMESHGUI.h"
27 #include "SMESH_Actor.h"
28 #include "SMESH_ActorUtils.h"
29 #include "SMESH_ObjectDef.h"
30 #include <SMDS_Mesh.hxx>
31
32 #include <SUIT_Desktop.h>
33 #include <SUIT_Session.h>
34 #include <SUIT_Study.h>
35 #include <SUIT_MessageBox.h>
36
37 #include <SALOME_ListIO.hxx>
38 #include <SALOME_ListIteratorOfListIO.hxx>
39
40 #include <SVTK_Selector.h>
41 #include <SVTK_ViewModel.h>
42 #include <SVTK_ViewWindow.h>
43
44 #include <VTKViewer_Algorithm.h>
45
46 #include <LightApp_SelectionMgr.h>
47 #include <SalomeApp_Application.h>
48 #include <SalomeApp_Study.h>
49
50 #include <utilities.h>
51
52 #include <SALOMEconfig.h>
53 #include CORBA_CLIENT_HEADER(SMESH_Gen)
54 #include CORBA_CLIENT_HEADER(SMESH_Mesh)
55 #include CORBA_CLIENT_HEADER(SMESH_Group)
56 #include CORBA_CLIENT_HEADER(SMESH_Hypothesis)
57
58 #include <SALOMEDSClient_Study.hxx>
59 #include <SALOMEDSClient_SObject.hxx>
60
61 // VTK
62 #include <vtkRenderer.h>
63 #include <vtkActorCollection.h>
64 #include <vtkUnstructuredGrid.h>
65
66 // OCCT
67 #include <TColStd_IndexedMapOfInteger.hxx>
68 #include <Standard_ErrorHandler.hxx>
69
70 // STL
71 #include <set>
72 using namespace std;
73
74
75 namespace SMESH {
76
77   typedef map<TKeyOfVisualObj,TVisualObjPtr> TVisualObjCont;
78   static TVisualObjCont VISUAL_OBJ_CONT;
79
80   //=============================================================================
81   /*!
82    * \brief Allocate some memory at construction and release it at destruction.
83    * Is used to be able to continue working after mesh generation or visualization
84    * break due to lack of memory
85    */
86   //=============================================================================
87
88   struct MemoryReserve
89   {
90     char* myBuf;
91     MemoryReserve(): myBuf( new char[1024*1024*1] ){} // 1M
92     void Free() { if (myBuf) { delete [] myBuf; myBuf = 0; }}
93     ~MemoryReserve() { Free(); }
94   };
95   static MemoryReserve* theVISU_MemoryReserve = new MemoryReserve;
96
97   //================================================================================
98   /*!
99    * \brief Remove VisualObj and its actor from all views
100    */
101   //================================================================================
102
103   void RemoveVisualObjectWithActors( const char* theEntry )
104   {
105     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>
106       ( SUIT_Session::session()->activeApplication() );
107     SUIT_ViewManager* aViewManager =
108       app ? app->getViewManager(SVTK_Viewer::Type(), true) : 0;
109     if ( aViewManager ) {
110       QPtrVector<SUIT_ViewWindow> views = aViewManager->getViews();
111       for ( int iV = 0; iV < views.count(); ++iV ) {
112         if ( SMESH_Actor* actor = FindActorByEntry( views[iV], theEntry)) {
113           if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(views[iV]))
114             vtkWnd->RemoveActor(actor);
115           actor->Delete();
116         }
117       }
118       int aStudyId = aViewManager->study()->id();
119       TVisualObjCont::key_type aKey(aStudyId,theEntry);
120       TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.find(aKey);
121       if(anIter != VISUAL_OBJ_CONT.end()) {
122         // for unknown reason, object destructor is not called, so clear object manually
123         anIter->second->GetUnstructuredGrid()->SetCells(0,0,0);
124         anIter->second->GetUnstructuredGrid()->SetPoints(0);
125       }
126       VISUAL_OBJ_CONT.erase(aKey);
127     }
128   }
129   //================================================================================
130   /*!
131    * \brief Remove all VisualObjs and their actors from all views
132    */
133   //================================================================================
134
135   void RemoveAllObjectsWithActors()
136   {
137     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>
138       ( SUIT_Session::session()->activeApplication() );
139     if (!app) return;
140     ViewManagerList viewMgrs = app->viewManagers();
141     for ( int iM = 0; iM < viewMgrs.count(); ++iM ) {
142       SUIT_ViewManager* aViewManager = viewMgrs.at( iM );
143       if ( aViewManager && aViewManager->getType() == SVTK_Viewer::Type()) {
144         QPtrVector<SUIT_ViewWindow> views = aViewManager->getViews();
145         for ( int iV = 0; iV < views.count(); ++iV ) {
146           if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(views[iV])) {
147             vtkRenderer *aRenderer = vtkWnd->getRenderer();
148             VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
149             vtkActorCollection *actors = aCopy.GetActors();
150             for (int i = 0; i < actors->GetNumberOfItems(); ++i ) {
151               // size of actors changes inside the loop
152               while (SMESH_Actor *actor = dynamic_cast<SMESH_Actor*>(actors->GetItemAsObject(i)))
153               {
154                 vtkWnd->RemoveActor(actor);
155                 actor->Delete();
156               }
157             }
158           }
159         }
160       }
161     }
162     TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.begin();
163     for ( ; anIter != VISUAL_OBJ_CONT.end(); ++anIter ) {
164       // for unknown reason, object destructor is not called, so clear object manually
165       anIter->second->GetUnstructuredGrid()->SetCells(0,0,0);
166       anIter->second->GetUnstructuredGrid()->SetPoints(0);
167     }
168     VISUAL_OBJ_CONT.clear();
169   }
170
171   //================================================================================
172   /*!
173    * \brief Remove all VisualObjs of a study
174    */
175   //================================================================================
176
177   void RemoveVisuData(int studyID)
178   {
179     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>
180       ( SUIT_Session::session()->activeApplication() );
181     if (!app) return;
182     ViewManagerList viewMgrs = app->viewManagers();
183     for ( int iM = 0; iM < viewMgrs.count(); ++iM ) {
184       SUIT_ViewManager* aViewManager = viewMgrs.at( iM );
185       if ( aViewManager && aViewManager->getType() == SVTK_Viewer::Type() &&
186            aViewManager->study()->id() == studyID ) {
187         QPtrVector<SUIT_ViewWindow> views = aViewManager->getViews();
188         for ( int iV = 0; iV < views.count(); ++iV ) {
189           if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(views[iV])) {
190             vtkRenderer *aRenderer = vtkWnd->getRenderer();
191             VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
192             vtkActorCollection *actors = aCopy.GetActors();
193             for (int i = 0; i < actors->GetNumberOfItems(); ++i ) {
194               // size of actors changes inside the loop
195               while(SMESH_Actor *actor = dynamic_cast<SMESH_Actor*>(actors->GetItemAsObject(i)))
196               {
197                 vtkWnd->RemoveActor(actor);
198                 actor->Delete();
199               }
200             }
201           }
202         }
203       }
204     }
205     TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.begin();
206     for ( ; anIter != VISUAL_OBJ_CONT.end(); ++anIter ) {
207       int curId = anIter->first.first;
208       if ( curId == studyID ) {
209         // for unknown reason, object destructor is not called, so clear object manually
210         anIter->second->GetUnstructuredGrid()->SetCells(0,0,0);
211         anIter->second->GetUnstructuredGrid()->SetPoints(0);
212         VISUAL_OBJ_CONT.erase( anIter-- );  // dercement occures before erase()
213       }
214     }
215   }
216
217   //================================================================================
218   /*!
219    * \brief Notify the user on problems during visualization
220    */
221   //================================================================================
222
223   void OnVisuException()
224   {
225     try {
226 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
227       OCC_CATCH_SIGNALS;
228 #endif
229       // PAL16774 (Crash after display of many groups). Salome sometimes crashes just
230       // after or at showing this message, so we do an additional check of available memory
231 //       char* buf = new char[100*1024];
232 //       delete [] buf;
233       SUIT_MessageBox::warn1 (SMESHGUI::desktop(), QObject::tr("SMESH_WRN_WARNING"),
234                               QObject::tr("SMESH_VISU_PROBLEM"),
235                               QObject::tr("SMESH_BUT_OK"));
236     } catch (...) {
237       // no more memory at all: last resort
238       MESSAGE_BEGIN ( "SMESHGUI_VTKUtils::OnVisuException(), exception even at showing a message!!!" <<
239                       std::endl << "Try to remove all visual data..." );
240       if (theVISU_MemoryReserve) {
241         delete theVISU_MemoryReserve;
242         theVISU_MemoryReserve = 0;
243       }
244       RemoveAllObjectsWithActors();
245       SUIT_MessageBox::warn1 (SMESHGUI::desktop(), QObject::tr("SMESH_WRN_WARNING"),
246                               QObject::tr("SMESH_VISU_PROBLEM_CLEAR"),
247                               QObject::tr("SMESH_BUT_OK"));
248       MESSAGE_END ( "...done" );
249     }
250   }
251   //================================================================================
252   /*!
253    * \brief Returns an updated visual object
254    */
255   //================================================================================
256
257   TVisualObjPtr GetVisualObj(int theStudyId, const char* theEntry){
258     TVisualObjPtr aVisualObj;
259     TVisualObjCont::key_type aKey(theStudyId,theEntry);
260     try{
261 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
262       OCC_CATCH_SIGNALS;
263 #endif
264       TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.find(aKey);
265       if(anIter != VISUAL_OBJ_CONT.end()){
266         aVisualObj = anIter->second;
267       }else{
268         SalomeApp_Application* app =
269           dynamic_cast<SalomeApp_Application*>( SMESHGUI::activeStudy()->application() );
270         _PTR(Study) aStudy = SMESHGUI::activeStudy()->studyDS();
271         _PTR(SObject) aSObj = aStudy->FindObjectID(theEntry);
272         if(aSObj){
273           _PTR(GenericAttribute) anAttr;
274           if(aSObj->FindAttribute(anAttr,"AttributeIOR")){
275             _PTR(AttributeIOR) anIOR = anAttr;
276             CORBA::String_var aVal = anIOR->Value().c_str();
277             CORBA::Object_var anObj = app->orb()->string_to_object( aVal.in() );
278             if(!CORBA::is_nil(anObj)){
279               //Try narrow to SMESH_Mesh interface
280               SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_narrow(anObj);
281               if(!aMesh->_is_nil()){
282                 aVisualObj.reset(new SMESH_MeshObj(aMesh));
283                 TVisualObjCont::value_type aValue(aKey,aVisualObj);
284                 VISUAL_OBJ_CONT.insert(aValue);
285               }
286               //Try narrow to SMESH_Group interface
287               SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow(anObj);
288               if(!aGroup->_is_nil()){
289                 _PTR(SObject) aFatherSObj = aSObj->GetFather();
290                 if(!aFatherSObj) return aVisualObj;
291                 aFatherSObj = aFatherSObj->GetFather();
292                 if(!aFatherSObj) return aVisualObj;
293                 CORBA::String_var anEntry = aFatherSObj->GetID().c_str();
294                 TVisualObjPtr aVisObj = GetVisualObj(theStudyId,anEntry.in());
295                 if(SMESH_MeshObj* aMeshObj = dynamic_cast<SMESH_MeshObj*>(aVisObj.get())){
296                   aVisualObj.reset(new SMESH_GroupObj(aGroup,aMeshObj));
297                   TVisualObjCont::value_type aValue(aKey,aVisualObj);
298                   VISUAL_OBJ_CONT.insert(aValue);
299                 }
300               }
301               //Try narrow to SMESH_subMesh interface
302               SMESH::SMESH_subMesh_var aSubMesh = SMESH::SMESH_subMesh::_narrow(anObj);
303               if(!aSubMesh->_is_nil()){
304                 _PTR(SObject) aFatherSObj = aSObj->GetFather();
305                 if(!aFatherSObj) return aVisualObj;
306                 aFatherSObj = aFatherSObj->GetFather();
307                 if(!aFatherSObj) return aVisualObj;
308                 CORBA::String_var anEntry = aFatherSObj->GetID().c_str();
309                 TVisualObjPtr aVisObj = GetVisualObj(theStudyId,anEntry.in());
310                 if(SMESH_MeshObj* aMeshObj = dynamic_cast<SMESH_MeshObj*>(aVisObj.get())){
311                   aVisualObj.reset(new SMESH_subMeshObj(aSubMesh,aMeshObj));
312                   TVisualObjCont::value_type aValue(aKey,aVisualObj);
313                   VISUAL_OBJ_CONT.insert(aValue);
314                 }
315               }
316             }
317           }
318         }
319       }
320     }catch(...){
321       INFOS("GetMeshObj - There is no SMESH_Mesh object for the SALOMEDS::Strudy and Entry!!!");
322       return TVisualObjPtr();
323     }
324     // Update object
325     bool objModified = false;
326     if ( aVisualObj ) {
327       try {
328 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
329         OCC_CATCH_SIGNALS;
330 #endif
331         objModified = aVisualObj->Update();
332       }
333       catch (...) {
334 #ifdef _DEBUG_
335         MESSAGE ( "Exception in SMESHGUI_VTKUtils::GetVisualObj()" );
336 #endif
337         RemoveVisualObjectWithActors( theEntry ); // remove this object
338         OnVisuException();
339         aVisualObj.reset();
340       }
341     }
342
343     if ( objModified ) {
344       // PAL16631. Mesurements showed that to show aVisualObj in SHADING(default) mode,
345       // ~10 times more memory is used than it occupies.
346       // Warn the user if there is less free memory than 30 sizes of a grid
347       // TODO: estimate memory usage in other modes and take current mode into account
348       int freeMB = SMDS_Mesh::CheckMemory(true);
349       int usedMB = aVisualObj->GetUnstructuredGrid()->GetActualMemorySize() / 1024;
350       if ( freeMB > 0 && usedMB * 30 > freeMB ) {
351 #ifdef _DEBUG_
352         MESSAGE ( "SMESHGUI_VTKUtils::GetVisualObj(), freeMB=" << freeMB
353                << ", usedMB=" << usedMB );
354 #endif
355         int continu = 0;
356         if ( usedMB * 10 > freeMB )
357           // even dont try to show
358           SUIT_MessageBox::warn1 (SMESHGUI::desktop(), QObject::tr("SMESH_WRN_WARNING"),
359                                   QObject::tr("SMESH_NO_MESH_VISUALIZATION"),
360                                   QObject::tr("SMESH_BUT_OK"));
361         else
362           // there is a chance to succeed
363           continu = SUIT_MessageBox::warn2
364             (SMESHGUI::desktop(),
365              QObject::tr("SMESH_WRN_WARNING"),
366              QObject::tr("SMESH_CONTINUE_MESH_VISUALIZATION"),
367              QObject::tr("SMESH_BUT_YES"),  QObject::tr("SMESH_BUT_NO"),
368              1, 0, 1);
369         if ( !continu ) {
370           // remove the corresponding actors from all views
371           RemoveVisualObjectWithActors( theEntry );
372           aVisualObj.reset();
373         }
374       }
375     }
376
377     return aVisualObj;
378   }
379
380
381   /*! Return active view window, if it instantiates SVTK_ViewWindow class,
382    *  overwise find or create corresponding view window, make it active and return it.
383    *  \note Active VVTK_ViewWindow can be returned, because it inherits SVTK_ViewWindow.
384    */
385   SVTK_ViewWindow* GetViewWindow (const SalomeApp_Module* theModule,
386                                   bool createIfNotFound)
387   {
388     SalomeApp_Application* anApp;
389     if (theModule)
390       anApp = theModule->getApp();
391     else
392       anApp = dynamic_cast<SalomeApp_Application*>
393         (SUIT_Session::session()->activeApplication());
394
395     if (anApp) {
396       if (SVTK_ViewWindow* aView = dynamic_cast<SVTK_ViewWindow*>(anApp->desktop()->activeWindow()))
397         return aView;
398
399       SUIT_ViewManager* aViewManager =
400         anApp->getViewManager(SVTK_Viewer::Type(), createIfNotFound);
401       if (aViewManager) {
402         if (SUIT_ViewWindow* aViewWindow = aViewManager->getActiveView()) {
403           if (SVTK_ViewWindow* aView = dynamic_cast<SVTK_ViewWindow*>(aViewWindow)) {
404             aViewWindow->raise();
405             aViewWindow->setFocus();
406             return aView;
407           }
408         }
409       }
410     }
411     return NULL;
412   }
413
414   SVTK_ViewWindow* FindVtkViewWindow (SUIT_ViewManager* theMgr,
415                                       SUIT_ViewWindow * theWindow)
416   {
417     if( !theMgr )
418       return NULL;
419
420     QPtrVector<SUIT_ViewWindow> views = theMgr->getViews();
421     if( views.containsRef( theWindow ) )
422       return GetVtkViewWindow( theWindow );
423     else
424       return NULL;
425   }
426
427   SVTK_ViewWindow* GetVtkViewWindow(SUIT_ViewWindow* theWindow){
428     return dynamic_cast<SVTK_ViewWindow*>(theWindow);
429   }
430
431 /*  SUIT_ViewWindow* GetActiveWindow()
432   {
433     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
434     if( !app )
435       return NULL;
436     SUIT_ViewManager* mgr = app->activeViewManager();
437     if( mgr )
438       return mgr->getActiveView();
439     else
440       return NULL;
441   }*/
442
443   SVTK_ViewWindow* GetCurrentVtkView(){
444     return GetVtkViewWindow( GetActiveWindow() );
445   }
446
447
448   void RepaintCurrentView()
449   {
450     if (SVTK_ViewWindow* wnd = GetCurrentVtkView())
451     {
452       try {
453 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
454         OCC_CATCH_SIGNALS;
455 #endif
456         wnd->getRenderer()->Render();
457         wnd->Repaint(false);
458       }
459       catch (...) {
460 #ifdef _DEBUG_
461         MESSAGE ( "Exception in SMESHGUI_VTKUtils::RepaintCurrentView()" );
462 #endif
463         OnVisuException();
464       }
465     }
466   }
467
468   void RepaintViewWindow(SVTK_ViewWindow* theWindow)
469   {
470     try {
471 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
472       OCC_CATCH_SIGNALS;
473 #endif
474       theWindow->getRenderer()->Render();
475       theWindow->Repaint();
476     }
477     catch (...) {
478 #ifdef _DEBUG_
479         MESSAGE ( "Exception in SMESHGUI_VTKUtils::RepaintViewWindow(SVTK_ViewWindow)" );
480 #endif
481       OnVisuException();
482     }
483   }
484
485   void RenderViewWindow(SVTK_ViewWindow* theWindow)
486   {
487     try {
488 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
489       OCC_CATCH_SIGNALS;
490 #endif
491       theWindow->getRenderer()->Render();
492       theWindow->Repaint();
493     }
494     catch (...) {
495 #ifdef _DEBUG_
496         MESSAGE ( "Exception in SMESHGUI_VTKUtils::RenderViewWindow(SVTK_ViewWindow)" );
497 #endif
498       OnVisuException();
499     }
500   }
501
502   void FitAll(){
503     if(SVTK_ViewWindow* wnd = GetCurrentVtkView() ){
504       try {
505 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
506         OCC_CATCH_SIGNALS;
507 #endif
508         wnd->onFitAll();
509         wnd->Repaint();
510       }
511       catch (...) {
512 #ifdef _DEBUG_
513         MESSAGE ( "Exception in SMESHGUI_VTKUtils::FitAll()" );
514 #endif
515         OnVisuException();
516       }
517     }
518   }
519
520
521   SMESH_Actor* FindActorByEntry(SUIT_ViewWindow *theWindow,
522                                 const char* theEntry)
523   {
524     if(SVTK_ViewWindow* aViewWindow = GetVtkViewWindow(theWindow)){
525       vtkRenderer *aRenderer = aViewWindow->getRenderer();
526       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
527       vtkActorCollection *aCollection = aCopy.GetActors();
528       aCollection->InitTraversal();
529       while(vtkActor *anAct = aCollection->GetNextActor()){
530         if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
531           if(anActor->hasIO()){
532             Handle(SALOME_InteractiveObject) anIO = anActor->getIO();
533             if(anIO->hasEntry() && strcmp(anIO->getEntry(),theEntry) == 0){
534               return anActor;
535             }
536           }
537         }
538       }
539     }
540     return NULL;
541   }
542
543
544   SMESH_Actor* FindActorByEntry(const char* theEntry){
545     return FindActorByEntry(GetActiveWindow(),theEntry);
546   }
547
548
549   SMESH_Actor* FindActorByObject(CORBA::Object_ptr theObject){
550     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
551     if( !app )
552       return NULL;
553
554     if(!CORBA::is_nil(theObject)){
555       _PTR(Study) aStudy = GetActiveStudyDocument();
556       CORBA::String_var anIOR = app->orb()->object_to_string( theObject );
557       _PTR(SObject) aSObject = aStudy->FindObjectIOR(anIOR.in());
558       if(aSObject){
559         CORBA::String_var anEntry = aSObject->GetID().c_str();
560         return FindActorByEntry(anEntry.in());
561       }
562     }
563     return NULL;
564   }
565
566
567   SMESH_Actor* CreateActor(_PTR(Study) theStudy,
568                            const char* theEntry,
569                            int theIsClear)
570   {
571     SMESH_Actor *anActor = NULL;
572     CORBA::Long anId = theStudy->StudyId();
573     if(TVisualObjPtr aVisualObj = GetVisualObj(anId,theEntry)){
574       _PTR(SObject) aSObj = theStudy->FindObjectID(theEntry);
575       if(aSObj){
576         _PTR(GenericAttribute) anAttr;
577         if(aSObj->FindAttribute(anAttr,"AttributeName")){
578           _PTR(AttributeName) aName = anAttr;
579           std::string aNameVal = aName->Value();
580           anActor = SMESH_Actor::New(aVisualObj,theEntry,aNameVal.c_str(),theIsClear);
581         }
582
583         SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SMESH::SObjectToObject( aSObj ));
584         if(!CORBA::is_nil(aGroup))
585         {
586           SALOMEDS::Color aColor = aGroup->GetColor();
587           if( !( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 ) )
588           {
589             int r = 0, g = 0, b = 0;
590             SMESH::GetColor( "SMESH", "fill_color", r, g, b, QColor( 0, 170, 255 ) );
591             aColor.R = (float)r / 255.0;
592             aColor.G = (float)g / 255.0;
593             aColor.B = (float)b / 255.0;
594             aGroup->SetColor( aColor );
595           }
596           if( aGroup->GetType() == SMESH::NODE )
597             anActor->SetNodeColor( aColor.R, aColor.G, aColor.B );
598           else if( aGroup->GetType() == SMESH::EDGE )
599             anActor->SetEdgeColor( aColor.R, aColor.G, aColor.B );
600           else
601             anActor->SetSufaceColor( aColor.R, aColor.G, aColor.B );
602         }
603       }
604     }
605     return anActor;
606   }
607
608
609   void DisplayActor( SUIT_ViewWindow *theWnd, SMESH_Actor* theActor){
610     if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(theWnd)){
611       try {
612 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
613         OCC_CATCH_SIGNALS;
614 #endif
615         vtkWnd->AddActor(theActor);
616         vtkWnd->Repaint();
617       }
618       catch (...) {
619 #ifdef _DEBUG_
620         MESSAGE ( "Exception in SMESHGUI_VTKUtils::DisplayActor()" );
621 #endif
622         OnVisuException();
623       }
624     }
625   }
626
627
628   void RemoveActor( SUIT_ViewWindow *theWnd, SMESH_Actor* theActor){
629     if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(theWnd)){
630       vtkWnd->RemoveActor(theActor);
631       if(theActor->hasIO()){
632         Handle(SALOME_InteractiveObject) anIO = theActor->getIO();
633         if(anIO->hasEntry()){
634           std::string anEntry = anIO->getEntry();
635           SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>( vtkWnd->getViewManager()->study() );
636           int aStudyId = aStudy->id();
637           TVisualObjCont::key_type aKey(aStudyId,anEntry);
638           VISUAL_OBJ_CONT.erase(aKey);
639         }
640       }
641       theActor->Delete();
642       vtkWnd->Repaint();
643     }
644   }
645
646   //================================================================================
647   /*!
648    * \brief Return true if there are no SMESH actors in a view
649    */
650   //================================================================================
651
652   bool noSmeshActors(SUIT_ViewWindow *theWnd)
653   {
654     if(SVTK_ViewWindow* aViewWindow = GetVtkViewWindow(theWnd)) {
655       vtkRenderer *aRenderer = aViewWindow->getRenderer();
656       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
657       vtkActorCollection *aCollection = aCopy.GetActors();
658       aCollection->InitTraversal();
659       while(vtkActor *anAct = aCollection->GetNextActor())
660         if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct))
661           return false;
662     }
663     return true;
664   }
665
666   bool UpdateView(SUIT_ViewWindow *theWnd, EDisplaing theAction, const char* theEntry)
667   {
668     bool OK = false;
669     SVTK_ViewWindow* aViewWnd = GetVtkViewWindow(theWnd);
670     if (!aViewWnd)
671       return OK;
672
673     {
674       OK = true;
675       vtkRenderer *aRenderer = aViewWnd->getRenderer();
676       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
677       vtkActorCollection *aCollection = aCopy.GetActors();
678       aCollection->InitTraversal();
679
680       switch (theAction) {
681       case eDisplayAll: {
682         while (vtkActor *anAct = aCollection->GetNextActor()) {
683           if (SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)) {
684             anActor->SetVisibility(true);
685           }
686         }
687         break;
688       }
689       case eDisplayOnly:
690       case eEraseAll: {
691         while (vtkActor *anAct = aCollection->GetNextActor()) {
692           if (SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)) {
693             anActor->SetVisibility(false);
694           }
695         }
696       }
697       default: {
698         if (SMESH_Actor *anActor = FindActorByEntry(theWnd,theEntry)) {
699           switch (theAction) {
700             case eDisplay:
701             case eDisplayOnly:
702               anActor->SetVisibility(true);
703               if (theAction == eDisplayOnly) aRenderer->ResetCameraClippingRange();
704               break;
705             case eErase:
706               anActor->SetVisibility(false);
707               break;
708           }
709         } else {
710           switch (theAction) {
711           case eDisplay:
712           case eDisplayOnly:
713             {
714               SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>(theWnd->getViewManager()->study());
715               _PTR(Study) aDocument = aStudy->studyDS();
716               // Pass non-visual objects (hypotheses, etc.), return true in this case
717               CORBA::Long anId = aDocument->StudyId();
718               if (TVisualObjPtr aVisualObj = GetVisualObj(anId,theEntry))
719               {
720                 if ((anActor = CreateActor(aDocument,theEntry,true))) {
721                   bool needFitAll = noSmeshActors(theWnd); // fit for the first object only
722                   DisplayActor(theWnd,anActor);
723                   // FitAll(); - PAL16770(Display of a group performs an automatic fit all)
724                   if (needFitAll) FitAll();
725                 } else {
726                   OK = false;
727                 }
728               }
729               break;
730             }
731           }
732         }
733       }
734       }
735     }
736     return OK;
737   }
738
739
740   bool UpdateView(EDisplaing theAction, const char* theEntry){
741     SalomeApp_Study* aStudy = dynamic_cast< SalomeApp_Study* >( GetActiveStudy() );
742     SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( aStudy->application() );
743     SUIT_ViewWindow *aWnd = app->activeViewManager()->getActiveView();
744     return UpdateView(aWnd,theAction,theEntry);
745   }
746
747   void UpdateView(){
748     if(SVTK_ViewWindow* aWnd = SMESH::GetCurrentVtkView()){
749       LightApp_SelectionMgr* mgr = SMESHGUI::selectionMgr();
750       SALOME_ListIO selected; mgr->selectedObjects( selected );
751
752       if( selected.Extent() == 0){
753         vtkRenderer* aRenderer = aWnd->getRenderer();
754         VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
755         vtkActorCollection *aCollection = aCopy.GetActors();
756         aCollection->InitTraversal();
757         while(vtkActor *anAct = aCollection->GetNextActor()){
758           if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
759             if(anActor->hasIO())
760               if (!Update(anActor->getIO(),anActor->GetVisibility()))
761                 break; // avoid multiple warinings if visu failed
762           }
763         }
764       }else{
765         SALOME_ListIteratorOfListIO anIter( selected );
766         for(; anIter.More(); anIter.Next()){
767           Handle(SALOME_InteractiveObject) anIO = anIter.Value();
768           if ( !Update(anIO,true) )
769             break; // avoid multiple warinings if visu failed
770         }
771       }
772       RepaintCurrentView();
773     }
774   }
775
776
777   bool Update(const Handle(SALOME_InteractiveObject)& theIO, bool theDisplay)
778   {
779     _PTR(Study) aStudy = GetActiveStudyDocument();
780     CORBA::Long anId = aStudy->StudyId();
781     if ( TVisualObjPtr aVisualObj = SMESH::GetVisualObj(anId,theIO->getEntry())) {
782       if ( theDisplay )
783         UpdateView(SMESH::eDisplay,theIO->getEntry());
784       return true;
785     }
786     return false;
787   }
788
789
790   void UpdateSelectionProp( SMESHGUI* theModule ) {
791     if( !theModule )
792       return;
793
794     SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( theModule->application() );
795     if( !app )
796     {
797       MESSAGE( "UpdateSelectionProp: Application is null" );
798       return;
799     }
800
801     SUIT_ViewManager* vm = app->activeViewManager();
802     if( !vm )
803     {
804       MESSAGE( "UpdateSelectionProp: View manager is null" );
805       return;
806     }
807
808     QPtrVector<SUIT_ViewWindow> views = vm->getViews();
809
810     SUIT_ResourceMgr* mgr = SMESH::GetResourceMgr( theModule );
811     if( !mgr )
812     {
813       MESSAGE( "UpdateSelectionProp: Resource manager is null" );
814       return;
815     }
816
817     QColor aHiColor = mgr->colorValue( "SMESH", "selection_object_color", Qt::white ),
818            aSelColor = mgr->colorValue( "SMESH", "selection_element_color", Qt::yellow ),
819            aPreColor = mgr->colorValue( "SMESH", "highlight_color", Qt::cyan );
820
821     int SW = mgr->integerValue( "SMESH", "selection_width", 5 ),
822         PW = mgr->integerValue( "SMESH", "highlight_width", 5 );
823
824     double SP1 = mgr->doubleValue( "SMESH", "selection_precision_node", 0.025 ),
825            SP2 = mgr->doubleValue( "SMESH", "selection_precision_element", 0.001 ),
826            SP3 = mgr->doubleValue( "SMESH", "selection_precision_object", 0.025 );
827
828     for ( int i=0, n=views.count(); i<n; i++ ){
829       // update VTK viewer properties
830       if(SVTK_ViewWindow* aVtkView = GetVtkViewWindow( views[i] )){
831         // mesh element selection
832         aVtkView->SetSelectionProp(aSelColor.red()/255.,
833                                    aSelColor.green()/255.,
834                                    aSelColor.blue()/255.,
835                                    SW );
836         // tolerances
837         aVtkView->SetSelectionTolerance(SP1, SP2, SP3);
838
839         // pre-selection
840         aVtkView->SetPreselectionProp(aPreColor.red()/255.,
841                                       aPreColor.green()/255.,
842                                       aPreColor.blue()/255.,
843                                       PW);
844         // update actors
845         vtkRenderer* aRenderer = aVtkView->getRenderer();
846         VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
847         vtkActorCollection *aCollection = aCopy.GetActors();
848         aCollection->InitTraversal();
849         while(vtkActor *anAct = aCollection->GetNextActor()){
850           if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
851             anActor->SetHighlightColor(aHiColor.red()/255.,
852                                        aHiColor.green()/255.,
853                                        aHiColor.blue()/255.);
854             anActor->SetPreHighlightColor(aPreColor.red()/255.,
855                                           aPreColor.green()/255.,
856                                           aPreColor.blue()/255.);
857           }
858         }
859       }
860     }
861   }
862
863
864   //----------------------------------------------------------------------------
865   SVTK_Selector*
866   GetSelector(SUIT_ViewWindow *theWindow)
867   {
868     if(SVTK_ViewWindow* aWnd = GetVtkViewWindow(theWindow))
869       return aWnd->GetSelector();
870
871     return NULL;
872   }
873
874   void SetFilter(const Handle(VTKViewer_Filter)& theFilter,
875                  SVTK_Selector* theSelector)
876   {
877     if (theSelector)
878       theSelector->SetFilter(theFilter);
879   }
880
881   Handle(VTKViewer_Filter) GetFilter(int theId, SVTK_Selector* theSelector)
882   {
883     return theSelector->GetFilter(theId);
884   }
885
886   bool IsFilterPresent(int theId, SVTK_Selector* theSelector)
887   {
888     return theSelector->IsFilterPresent(theId);
889   }
890
891   void RemoveFilter(int theId, SVTK_Selector* theSelector)
892   {
893     theSelector->RemoveFilter(theId);
894   }
895
896   void RemoveFilters(SVTK_Selector* theSelector)
897   {
898     for ( int id = SMESHGUI_NodeFilter; theSelector && id < SMESHGUI_LastFilter; id++ )
899       theSelector->RemoveFilter( id );
900   }
901
902   bool IsValid(SALOME_Actor* theActor, int theCellId,
903                SVTK_Selector* theSelector)
904   {
905     return theSelector->IsValid(theActor,theCellId);
906   }
907
908
909   //----------------------------------------------------------------------------
910   void SetPointRepresentation(bool theIsVisible){
911     if(SVTK_ViewWindow* aViewWindow = GetCurrentVtkView()){
912       vtkRenderer *aRenderer = aViewWindow->getRenderer();
913       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
914       vtkActorCollection *aCollection = aCopy.GetActors();
915       aCollection->InitTraversal();
916       while(vtkActor *anAct = aCollection->GetNextActor()){
917         if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
918           if(anActor->GetVisibility()){
919             anActor->SetPointRepresentation(theIsVisible);
920           }
921         }
922       }
923       RepaintCurrentView();
924     }
925   }
926
927
928   void SetPickable(SMESH_Actor* theActor){
929     if(SVTK_ViewWindow* aWnd = GetCurrentVtkView()){
930       int anIsAllPickable = (theActor == NULL);
931       vtkRenderer *aRenderer = aWnd->getRenderer();
932       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
933       vtkActorCollection *aCollection = aCopy.GetActors();
934       aCollection->InitTraversal();
935       while(vtkActor *anAct = aCollection->GetNextActor()){
936         if(SALOME_Actor *anActor = dynamic_cast<SALOME_Actor*>(anAct)){
937           if(anActor->GetVisibility()){
938             anActor->SetPickable(anIsAllPickable);
939           }
940         }
941       }
942       if(theActor)
943         theActor->SetPickable(!anIsAllPickable);
944       RepaintCurrentView();
945     }
946   }
947
948
949   //----------------------------------------------------------------------------
950   int GetNameOfSelectedNodes(SVTK_Selector* theSelector,
951                              const Handle(SALOME_InteractiveObject)& theIO,
952                              QString& theName)
953   {
954     theName = "";
955     TColStd_IndexedMapOfInteger aMapIndex;
956     theSelector->GetIndex(theIO,aMapIndex);
957
958     for(int i = 1; i <= aMapIndex.Extent(); i++)
959       theName += QString(" %1").arg(aMapIndex(i));
960
961     return aMapIndex.Extent();
962   }
963
964   int GetNameOfSelectedElements(SVTK_Selector* theSelector,
965                                 const Handle(SALOME_InteractiveObject)& theIO,
966                                 QString& theName)
967   {
968     theName = "";
969     TColStd_IndexedMapOfInteger aMapIndex;
970     theSelector->GetIndex(theIO,aMapIndex);
971
972     typedef std::set<int> TIdContainer;
973     TIdContainer anIdContainer;
974     for( int i = 1; i <= aMapIndex.Extent(); i++)
975       anIdContainer.insert(aMapIndex(i));
976
977     TIdContainer::const_iterator anIter = anIdContainer.begin();
978     for(; anIter != anIdContainer.end(); anIter++)
979       theName += QString(" %1").arg(*anIter);
980
981     return aMapIndex.Extent();
982   }
983
984
985   int GetEdgeNodes(SVTK_Selector* theSelector,
986                    const TVisualObjPtr& theVisualObject,
987                    int& theId1,
988                    int& theId2)
989   {
990     const SALOME_ListIO& selected = theSelector->StoredIObjects();
991
992     if ( selected.Extent() != 1 )
993       return -1;
994
995     Handle(SALOME_InteractiveObject) anIO = selected.First();
996     if ( anIO.IsNull() || !anIO->hasEntry() )
997       return -1;
998
999     TColStd_IndexedMapOfInteger aMapIndex;
1000     theSelector->GetIndex( anIO, aMapIndex );
1001     if ( aMapIndex.Extent() != 2 )
1002       return -1;
1003
1004     int anObjId = -1, anEdgeNum = -1;
1005     for ( int i = 1; i <= aMapIndex.Extent(); i++ ) {
1006       int aVal = aMapIndex( i );
1007       if ( aVal > 0 )
1008         anObjId = aVal;
1009       else
1010         anEdgeNum = abs( aVal ) - 1;
1011     }
1012
1013     if ( anObjId == -1 || anEdgeNum == -1 )
1014       return -1;
1015
1016     return theVisualObject->GetEdgeNodes( anObjId, anEdgeNum, theId1, theId2 ) ? 1 : -1;
1017   }
1018
1019   //----------------------------------------------------------------------------
1020   int GetNameOfSelectedNodes(LightApp_SelectionMgr *theMgr,
1021                              const Handle(SALOME_InteractiveObject)& theIO,
1022                              QString& theName)
1023   {
1024     theName = "";
1025     if(theIO->hasEntry()){
1026       if(FindActorByEntry(theIO->getEntry())){
1027         TColStd_IndexedMapOfInteger aMapIndex;
1028         theMgr->GetIndexes(theIO,aMapIndex);
1029         for(int i = 1; i <= aMapIndex.Extent(); i++){
1030           theName += QString(" %1").arg(aMapIndex(i));
1031         }
1032         return aMapIndex.Extent();
1033       }
1034     }
1035     return -1;
1036   }
1037
1038   int GetNameOfSelectedNodes(LightApp_SelectionMgr *theMgr, QString& theName){
1039     theName = "";
1040     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1041     if(selected.Extent() == 1){
1042       Handle(SALOME_InteractiveObject) anIO = selected.First();
1043       return GetNameOfSelectedNodes(theMgr,anIO,theName);
1044     }
1045     return -1;
1046   }
1047
1048
1049   int GetNameOfSelectedElements(LightApp_SelectionMgr *theMgr,
1050                                 const Handle(SALOME_InteractiveObject)& theIO,
1051                                 QString& theName)
1052   {
1053     theName = "";
1054     if(theIO->hasEntry()){
1055       if(FindActorByEntry(theIO->getEntry())){
1056         TColStd_IndexedMapOfInteger aMapIndex;
1057         theMgr->GetIndexes(theIO,aMapIndex);
1058         typedef set<int> TIdContainer;
1059         TIdContainer anIdContainer;
1060         for( int i = 1; i <= aMapIndex.Extent(); i++)
1061           anIdContainer.insert(aMapIndex(i));
1062         TIdContainer::const_iterator anIter = anIdContainer.begin();
1063         for(; anIter != anIdContainer.end(); anIter++){
1064           theName += QString(" %1").arg(*anIter);
1065         }
1066         return aMapIndex.Extent();
1067       }
1068     }
1069     return -1;
1070   }
1071
1072
1073   int GetNameOfSelectedElements(LightApp_SelectionMgr *theMgr, QString& theName)
1074   {
1075     theName = "";
1076     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1077
1078     if( selected.Extent() == 1){
1079       Handle(SALOME_InteractiveObject) anIO = selected.First();
1080       return GetNameOfSelectedElements(theMgr,anIO,theName);
1081     }
1082     return -1;
1083   }
1084
1085   int GetSelected(LightApp_SelectionMgr*       theMgr,
1086                   TColStd_IndexedMapOfInteger& theMap,
1087                   const bool                   theIsElement)
1088   {
1089     theMap.Clear();
1090     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1091
1092     if ( selected.Extent() == 1 )
1093     {
1094       Handle(SALOME_InteractiveObject) anIO = selected.First();
1095       if ( anIO->hasEntry() ) {
1096         theMgr->GetIndexes( anIO, theMap );
1097       }
1098     }
1099     return theMap.Extent();
1100   }
1101
1102
1103   int GetEdgeNodes( LightApp_SelectionMgr* theMgr, int& theId1, int& theId2 )
1104   {
1105     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1106
1107     if ( selected.Extent() != 1 )
1108       return -1;
1109
1110     Handle(SALOME_InteractiveObject) anIO = selected.First();
1111     if ( anIO.IsNull() || !anIO->hasEntry() )
1112       return -1;
1113
1114     SMESH_Actor *anActor = SMESH::FindActorByEntry( anIO->getEntry() );
1115     if ( anActor == 0 )
1116       return -1;
1117
1118     TColStd_IndexedMapOfInteger aMapIndex;
1119     theMgr->GetIndexes( anIO, aMapIndex );
1120     if ( aMapIndex.Extent() != 2 )
1121       return -1;
1122
1123     int anObjId = -1, anEdgeNum = -1;
1124     for ( int i = 1; i <= aMapIndex.Extent(); i++ ) {
1125       int aVal = aMapIndex( i );
1126       if ( aVal > 0 )
1127         anObjId = aVal;
1128       else
1129         anEdgeNum = abs( aVal );
1130     }
1131
1132     if ( anObjId == -1 || anEdgeNum == -1 )
1133       return -1;
1134
1135     return anActor->GetObject()->GetEdgeNodes( anObjId, anEdgeNum, theId1, theId2 ) ? 1 : -1;
1136   }
1137
1138   void SetControlsPrecision( const long theVal )
1139   {
1140     if( SVTK_ViewWindow* aWnd = SMESH::GetCurrentVtkView() )
1141     {
1142       vtkRenderer *aRenderer = aWnd->getRenderer();
1143       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
1144       vtkActorCollection *aCollection = aCopy.GetActors();
1145       aCollection->InitTraversal();
1146
1147       while ( vtkActor *anAct = aCollection->GetNextActor())
1148       {
1149         if ( SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>( anAct ) )
1150         {
1151           anActor->SetControlsPrecision( theVal );
1152           anActor->SetControlMode( anActor->GetControlMode() );
1153         }
1154       }
1155
1156     }
1157   }
1158 }