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