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