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