Salome HOME
Porting to Qt4.
[modules/geom.git] / src / GEOMBase / GEOMBase.cxx
1 //  GEOM GEOMGUI : GUI for Geometry component
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //
23 //
24 //  File   : GEOMBase.cxx
25 //  Author : Damien COQUERET
26 //  Module : GEOM
27 //  $Header$
28
29 #include "GEOMBase.h"
30 #include "GeometryGUI.h"
31 #include "GEOMBase_aParameterDlg.h"
32
33 #include "GEOM_Client.hxx"
34
35 ////  SALOME Includes
36 #include "GEOM_Actor.h"
37 #include "SVTK_ViewModel.h"
38 #include "SVTK_ViewWindow.h"
39 #include "OCCViewer_ViewPort3d.h"
40 #include "OCCViewer_ViewModel.h"
41 #include "OCCViewer_ViewWindow.h"
42
43 #include "SALOME_ListIO.hxx"
44 #include "SALOME_ListIteratorOfListIO.hxx"
45
46 #include "SUIT_Desktop.h"
47 #include "SUIT_Session.h"
48 #include "SUIT_ViewManager.h"
49 #include "SUIT_ViewWindow.h"
50 #include "SUIT_MessageBox.h"
51 #include "SalomeApp_Application.h"
52 #include "SalomeApp_Study.h"
53
54 // // Open CASCADE Includes
55 #include <BRep_Tool.hxx>
56 #include <BRepAdaptor_Curve.hxx>
57 #include <BRepAdaptor_Surface.hxx>
58 #include <BRepPrimAPI_MakeCone.hxx>
59
60 #include <AIS_ListIteratorOfListOfInteractive.hxx>
61 #include <AIS_ListOfInteractive.hxx>
62
63 #include <TopAbs.hxx>
64 #include <TopExp.hxx>
65 #include <TopTools_IndexedMapOfShape.hxx>
66
67 #include <Precision.hxx>
68
69 #include <vtkRenderer.h>
70
71 #include <set>
72
73 using namespace std;
74
75
76 //=====================================================================================
77 // function : GetShapeFromIOR()
78 // purpose  : exist also as static method !
79 //=====================================================================================
80 TopoDS_Shape GEOMBase::GetShapeFromIOR(QString IOR)
81 {
82   TopoDS_Shape result;
83   if(IOR.trimmed().isEmpty())
84     return result;
85
86   CORBA::Object_var obj = SalomeApp_Application::orb()->string_to_object(IOR.toLatin1().data());
87   if(CORBA::is_nil(obj))
88     return result;
89   GEOM::GEOM_Object_var GeomObject = GEOM::GEOM_Object::_narrow( obj );
90   if (GeomObject->_is_nil())
91     return result;
92
93   result = GEOM_Client().GetShape(GeometryGUI::GetGeomGen(), GeomObject);
94   return result;
95 }
96
97
98 //=====================================================================================
99 // function : GetIndex()
100 // purpose  : Get the index of a sub shape in a main shape : index start at 1
101 //=====================================================================================
102 int GEOMBase::GetIndex(const TopoDS_Shape& subshape, const TopoDS_Shape& shape, int /*ShapeType*/)
103 {
104   if(shape.IsNull() || subshape.IsNull())
105     return -1;
106
107   TopTools_IndexedMapOfShape anIndices;
108   TopExp::MapShapes(shape, anIndices);
109   if(anIndices.Contains(subshape)) return anIndices.FindIndex(subshape);
110
111   return -1;
112 }
113
114
115 //=======================================================================
116 // function : GetTopoFromSelection()
117 // purpose  : Define tds from a single selection and retuen true
118 //=======================================================================
119 bool GEOMBase::GetTopoFromSelection(const SALOME_ListIO& aList, TopoDS_Shape& tds)
120 {
121   if(aList.Extent() != 1)
122     return false;
123
124   Handle(SALOME_InteractiveObject) IO = aList.First();
125   /* case SObject */
126   if(IO->hasEntry()) {
127     SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
128     if ( !appStudy ) return false;
129     _PTR(Study) aStudy = appStudy->studyDS();
130
131     _PTR(SObject) obj ( aStudy->FindObjectID(IO->getEntry()) );
132     _PTR(GenericAttribute) anAttr;
133     if( obj ) {
134       if(obj->FindAttribute(anAttr, "AttributeIOR")) {
135         _PTR(AttributeIOR) anIOR ( anAttr );
136         tds = GetShapeFromIOR(anIOR->Value().c_str());
137         if(tds.IsNull())
138           return false;
139         else
140           return true;
141       }
142     }
143   }
144
145   return false;
146 }
147
148 //=======================================================================
149 // function : GetNameOfSelectedIObjects()
150 // purpose  : Define the name geom++ or other name of mono or multi sel.
151 //=======================================================================
152 int GEOMBase::GetNameOfSelectedIObjects( const SALOME_ListIO& aList,
153                                          QString&          theName,
154                                          const bool        theShapesOnly )
155 {
156   if ( !theShapesOnly )
157     {
158       int nbSel = aList.Extent();
159       if ( nbSel == 1 )
160         {
161           Handle(SALOME_InteractiveObject) anIObj = aList.First();
162           if(anIObj->hasEntry()) {
163             SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
164             if ( !appStudy ) return nbSel;
165             _PTR(Study) aStudy = appStudy->studyDS();
166
167             _PTR(SObject) obj ( aStudy->FindObjectID(anIObj->getEntry()) );
168
169             _PTR(GenericAttribute) anAttr;
170
171             if ( obj && obj->FindAttribute( anAttr, "AttributeName") )
172               {
173                 _PTR(AttributeName) aNameAttr ( anAttr );
174                 theName = aNameAttr->Value().c_str();
175               }
176           }
177         }
178       else
179         theName = QObject::tr("%1_objects").arg(nbSel);
180
181       return nbSel;
182     }
183   else
184     {
185       GEOM::ListOfGO anObjs;
186       ConvertListOfIOInListOfGO( aList, anObjs, theShapesOnly );
187       if ( anObjs.length() == 1 ) {
188         theName = GetName( anObjs[ 0 ] );
189       }
190       else
191         theName = QString( "%1_objects" ).arg( anObjs.length() );
192
193       return anObjs.length();
194     }
195 }
196
197
198 //=================================================================================
199 // function : GetShapeTypeString()
200 // purpose  : for a single shape
201 //=================================================================================
202 bool GEOMBase::GetShapeTypeString(const TopoDS_Shape& aShape, Standard_CString& aTypeString)
203 {
204   if(aShape.IsNull()) {
205     aTypeString = "aNullShape";
206     return false;
207   }
208   switch(aShape.ShapeType())
209     {
210     case TopAbs_COMPOUND:
211       {
212         aTypeString = CORBA::string_dup(QObject::tr("GEOM_COMPOUND").toLatin1().constData());
213         return true;
214       }
215     case  TopAbs_COMPSOLID:
216       {
217         aTypeString = CORBA::string_dup(QObject::tr("GEOM_COMPOUNDSOLID").toLatin1().constData()) ;
218         return true ;
219       }
220     case TopAbs_SOLID:
221       {
222         aTypeString = CORBA::string_dup(QObject::tr("GEOM_SOLID").toLatin1().constData()) ;
223         return true ;
224       }
225     case TopAbs_SHELL:
226       {
227         aTypeString = CORBA::string_dup(QObject::tr("GEOM_SHELL").toLatin1().constData()) ;
228         return true ;
229       }
230     case TopAbs_FACE:
231       {
232         BRepAdaptor_Surface surf(TopoDS::Face(aShape));
233         if(surf.GetType() == GeomAbs_Plane) {
234           aTypeString = CORBA::string_dup(QObject::tr("GEOM_PLANE").toLatin1().constData());
235           return true;
236         }
237         else if(surf.GetType() == GeomAbs_Cylinder) {
238           aTypeString = CORBA::string_dup(QObject::tr("GEOM_SURFCYLINDER").toLatin1().constData());
239           return true;
240         }
241         else if(surf.GetType() == GeomAbs_Sphere) {
242           aTypeString = CORBA::string_dup(QObject::tr("GEOM_SURFSPHERE").toLatin1().constData());
243           return true ;
244         }
245         else if(surf.GetType() == GeomAbs_Torus) {
246           aTypeString = CORBA::string_dup(QObject::tr("GEOM_SURFTORUS").toLatin1().constData());
247           return true ;
248         }
249         else if(surf.GetType() == GeomAbs_Cone) {
250           aTypeString = CORBA::string_dup(QObject::tr("GEOM_SURFCONE").toLatin1().constData());
251           return true ;
252         }
253         else {
254           aTypeString = CORBA::string_dup(QObject::tr("GEOM_FACE").toLatin1().constData());
255           return true;
256         }
257       }
258     case TopAbs_WIRE:
259       {
260         aTypeString = CORBA::string_dup(QObject::tr("GEOM_WIRE").toLatin1().constData());
261         return true;
262       }
263     case TopAbs_EDGE:
264       {
265         BRepAdaptor_Curve curv(TopoDS::Edge(aShape));
266         if(curv.GetType() == GeomAbs_Line) {
267           if((Abs(curv.FirstParameter()) >= 1E6) || (Abs(curv.LastParameter()) >= 1E6))
268             aTypeString = CORBA::string_dup(QObject::tr("GEOM_LINE").toLatin1().constData());
269           else
270             aTypeString = CORBA::string_dup(QObject::tr("GEOM_EDGE").toLatin1().constData());
271           return true;
272         }
273         else if(curv.GetType() == GeomAbs_Circle) {
274           if(curv.IsClosed())
275             aTypeString = CORBA::string_dup(QObject::tr("GEOM_CIRCLE").toLatin1().constData());
276           else
277             aTypeString = CORBA::string_dup(QObject::tr("GEOM_ARC").toLatin1().constData());
278         return true;
279       }
280         else {
281           aTypeString = CORBA::string_dup(QObject::tr("GEOM_EDGE").toLatin1().constData());
282           return true;
283         }
284       }
285     case TopAbs_VERTEX:
286       {
287         aTypeString = CORBA::string_dup(QObject::tr("GEOM_VERTEX").toLatin1().constData());
288         return true;
289       }
290     case TopAbs_SHAPE:
291       {
292         aTypeString = CORBA::string_dup(QObject::tr("GEOM_SHAPE").toLatin1().constData());
293         return true;
294       }
295     }
296   return false;
297 }
298
299
300 //=======================================================================
301 // function : ConvertIORinGEOMAISShape()
302 // purpose  :
303 //=======================================================================
304 Handle(GEOM_AISShape) GEOMBase::ConvertIORinGEOMAISShape(const char * IOR, Standard_Boolean& testResult, bool onlyInActiveView)
305 {
306   Handle(GEOM_AISShape) resultShape;
307   testResult = false;
308
309   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
310   if ( !appStudy ) return resultShape;
311   _PTR(Study) aStudy = appStudy->studyDS();
312
313   _PTR(SObject) anObj ( aStudy->FindObjectIOR( IOR ) );
314   if ( !anObj )
315     return resultShape;
316
317   QList<SUIT_ViewWindow*> aViewWindowsList = SUIT_Session::session()->activeApplication()->desktop()->windows();
318
319   QListIterator<SUIT_ViewWindow*> it( aViewWindowsList );
320   while ( it.hasNext() ) {
321     SUIT_ViewWindow* aVW = it.next();
322     if (aVW && aVW->getViewManager()->getType() == OCCViewer_Viewer::Type()) {
323       Handle (AIS_InteractiveContext) ic = ((OCCViewer_Viewer*)aVW->getViewManager()->getViewModel())->getAISContext();
324
325       AIS_ListOfInteractive List;
326       ic->DisplayedObjects(List);
327       AIS_ListOfInteractive List1;
328       ic->ObjectsInCollector(List1);
329       List.Append(List1);
330
331       AIS_ListIteratorOfListOfInteractive ite(List);
332       while(ite.More()) {
333         if(ite.Value()->IsInstance(STANDARD_TYPE(GEOM_AISShape))) {
334           Handle(GEOM_AISShape) aSh = Handle(GEOM_AISShape)::DownCast(ite.Value());
335           if(aSh->hasIO()) {
336             Handle(SALOME_InteractiveObject) GIO = Handle(SALOME_InteractiveObject)::DownCast(aSh->getIO());
337             if(GIO->hasEntry() && strcmp(GIO->getEntry(), anObj->GetID().c_str()) == 0) {
338               if(!onlyInActiveView ||
339                  aVW == SUIT_Session::session()->activeApplication()->desktop()->activeWindow()) {
340                 testResult = true;
341                 resultShape = aSh;
342                 return resultShape;
343               }
344             }
345           }
346         }
347         ite.Next();
348       }
349     }
350   }
351   return  resultShape;
352 }
353
354
355 //=======================================================================
356 // function : ConvertIORinGEOMActor()
357 // purpose  :
358 //=======================================================================
359 GEOM_Actor* GEOMBase::ConvertIORinGEOMActor(const char* IOR, Standard_Boolean& testResult, bool onlyInActiveView)
360 {
361   testResult = false;
362
363   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
364   if ( !appStudy ) return GEOM_Actor::New();
365   _PTR(Study) aStudy = appStudy->studyDS();
366
367   _PTR(SObject) anObj ( aStudy->FindObjectIOR( IOR ) );
368   if ( !anObj )
369     return GEOM_Actor::New();
370
371   QList<SUIT_ViewWindow*> aViewWindowsList = SUIT_Session::session()->activeApplication()->desktop()->windows();
372
373   QListIterator<SUIT_ViewWindow*> it( aViewWindowsList );
374   while ( it.hasNext() ) {
375     SUIT_ViewWindow* aVW = it.next();
376     if (aVW && aVW->getViewManager()->getType() == SVTK_Viewer::Type()) {
377       SVTK_ViewWindow* aVTKViewWindow = dynamic_cast<SVTK_ViewWindow*>( aVW );
378       if( !aVTKViewWindow )
379         continue;
380       vtkRenderer* Renderer = aVTKViewWindow->getRenderer();
381       vtkActorCollection* theActors = Renderer->GetActors();
382       theActors->InitTraversal();
383       vtkActor *ac = theActors->GetNextActor();
384       while(!(ac==NULL)) {
385         if( ac->IsA("GEOM_Actor")) {
386           GEOM_Actor* anActor = GEOM_Actor::SafeDownCast(ac);
387           if(anActor->hasIO()) {
388             Handle(SALOME_InteractiveObject) GIO = Handle(SALOME_InteractiveObject)::DownCast(anActor->getIO());
389             if(GIO->hasEntry() && strcmp(GIO->getEntry(), anObj->GetID().c_str()) == 0) {
390               if(!onlyInActiveView ||
391                  aVW == SUIT_Session::session()->activeApplication()->desktop()->activeWindow()) {
392                 testResult = true;
393                 return anActor;
394               }
395             }
396           }
397         }
398         ac = theActors->GetNextActor();
399       }
400     }
401   }
402   testResult = false;
403   return GEOM_Actor::New();
404 }
405
406 //=======================================================================
407 // function : GetAIS()
408 // purpose  :
409 //=======================================================================
410 Handle(AIS_InteractiveObject) GEOMBase::GetAIS( const Handle(SALOME_InteractiveObject)& theIO,
411                                                 const bool                              isOnlyInActiveView )
412 {
413   if ( theIO.IsNull() || !theIO->hasEntry() )
414     return Handle(AIS_InteractiveObject)();
415
416   QList<SUIT_ViewWindow*> aViewWindowsList = SUIT_Session::session()->activeApplication()->desktop()->windows();
417
418   QListIterator<SUIT_ViewWindow*> it( aViewWindowsList );
419   while ( it.hasNext() ) {
420     SUIT_ViewWindow* aVW = it.next();
421     if (!aVW || aVW->getViewManager()->getType() != OCCViewer_Viewer::Type())
422       continue;
423     Handle (AIS_InteractiveContext) anIC = ((OCCViewer_Viewer*)aVW->getViewManager()->getViewModel())->getAISContext();
424
425     AIS_ListOfInteractive aList;
426     anIC->DisplayedObjects( aList );
427     anIC->ObjectsInCollector( aList );
428
429     AIS_ListIteratorOfListOfInteractive anIter( aList );
430     for ( ; anIter.More(); anIter.Next() )
431     {
432       Handle(SALOME_InteractiveObject) anObj =
433         Handle(SALOME_InteractiveObject)::DownCast( anIter.Value()->GetOwner() );
434
435       if( !anObj.IsNull() && strcmp( anObj->getEntry(), theIO->getEntry() ) == 0 )
436       {
437         if( isOnlyInActiveView )
438         {
439           if ( aVW == SUIT_Session::session()->activeApplication()->desktop()->activeWindow() )
440             return anIter.Value();
441         }
442         else
443           return anIter.Value();
444       }
445     }
446   }
447
448   return Handle(AIS_InteractiveObject)();
449 }
450
451
452 //=======================================================================
453 // function : ConvertIOinGEOMAISShape()
454 // purpose  :
455 //=======================================================================
456 Handle(GEOM_AISShape) GEOMBase::ConvertIOinGEOMAISShape(const Handle(SALOME_InteractiveObject)& IO, Standard_Boolean& testResult, bool onlyInActiveView)
457 {
458   Handle(GEOM_AISShape) res;
459
460   if ( !IO->hasEntry() )
461   {
462     testResult = false;
463     return res;
464   }
465
466   QList<SUIT_ViewWindow*> aViewWindowsList = SUIT_Session::session()->activeApplication()->desktop()->windows();
467
468   QListIterator<SUIT_ViewWindow*> it( aViewWindowsList );
469   while ( it.hasNext() ) {
470     SUIT_ViewWindow* aVW = it.next();
471     if (aVW && aVW->getViewManager()->getType() == OCCViewer_Viewer::Type()) {
472       Handle (AIS_InteractiveContext) ic = ((OCCViewer_Viewer*)aVW->getViewManager()->getViewModel())->getAISContext();
473
474       AIS_ListOfInteractive List;
475       ic->DisplayedObjects(List);
476       AIS_ListOfInteractive List1;
477       ic->ObjectsInCollector(List1);
478       List.Append(List1);
479
480       AIS_ListIteratorOfListOfInteractive ite(List);
481       while(ite.More())
482       {
483         if(ite.Value()->IsInstance(STANDARD_TYPE(GEOM_AISShape)))
484         {
485           Handle(GEOM_AISShape) aSh = Handle(GEOM_AISShape)::DownCast(ite.Value());
486           if( aSh->hasIO() )
487           {
488             if( strcmp( aSh->getIO()->getEntry(), IO->getEntry() ) == 0 )
489             {
490               if(onlyInActiveView)
491               {
492                 if(aVW == SUIT_Session::session()->activeApplication()->desktop()->activeWindow())
493                 {
494                   testResult = true;
495                   return aSh;
496                 }
497               }
498               else
499               {
500                 testResult = true;
501                 return aSh;
502               }
503             }
504           }
505         }
506         ite.Next();
507       }
508     }
509   }
510   testResult = false;
511   return res;
512 }
513
514
515 //=======================================================================
516 // function : ConvertIOinGEOMShape()
517 // purpose  :
518 //=======================================================================
519 GEOM::GEOM_Object_ptr GEOMBase::ConvertIOinGEOMShape(const Handle(SALOME_InteractiveObject)& IO, Standard_Boolean& testResult)
520 {
521   GEOM::GEOM_Object_var aShape;
522   testResult = false;
523
524   /* case SObject */
525   if(IO->hasEntry()) {
526     SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
527     if ( !appStudy ) return GEOM::GEOM_Object::_nil();
528     _PTR(Study) aStudy = appStudy->studyDS();
529
530     _PTR(SObject) obj ( aStudy->FindObjectID(IO->getEntry()) );
531     _PTR(GenericAttribute) anAttr;
532     if(obj) {
533       if(obj->FindAttribute(anAttr, "AttributeIOR")) {
534         _PTR(AttributeIOR) anIOR ( anAttr );
535         aShape = GeometryGUI::GetGeomGen()->GetIORFromString(anIOR->Value().c_str());
536         if(!CORBA::is_nil(aShape))
537           testResult = true;
538         return aShape._retn();
539       }
540     }
541   }
542   return GEOM::GEOM_Object::_nil();
543 }
544
545
546 //=======================================================================
547 // function : ConvertListOfIOInListOfIOR()
548 // purpose  :
549 //=======================================================================
550 void GEOMBase::ConvertListOfIOInListOfIOR(const SALOME_ListIO& aList, GEOM::string_array& listIOR)
551 {
552   int nbSel = aList.Extent();
553   listIOR.length(nbSel);
554   int j=0;
555   SALOME_ListIteratorOfListIO It(aList);
556   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>
557     ( SUIT_Session::session()->activeApplication()->activeStudy() );
558   if ( !appStudy ) return;
559   _PTR(Study) aStudy = appStudy->studyDS();
560
561   for (int i=0; It.More(); It.Next(), i++) {
562     Handle(SALOME_InteractiveObject) IObject = It.Value();
563     if (IObject->hasEntry()) {
564       _PTR(SObject) obj ( aStudy->FindObjectID(IObject->getEntry()) );
565       _PTR(GenericAttribute) anAttr;
566       if (obj && obj->FindAttribute(anAttr, "AttributeIOR")) {
567         _PTR(AttributeIOR) anIOR (anAttr);
568         //CORBA::Object_var theObj = dynamic_cast<SALOMEDS_Study*>
569         //  (aStudy.get())->ConvertIORToObject(anIOR->Value());
570         CORBA::Object_var theObj = GeometryGUI::ClientSObjectToObject(obj);
571         if (!CORBA::is_nil(theObj) && theObj->_is_a("IDL:GEOM/GEOM_Object:1.0")) {
572           listIOR[j] = CORBA::string_dup(anIOR->Value().c_str());
573           j++;
574         }
575       }
576     }
577   }
578   listIOR.length(j);
579 }
580
581
582 //=======================================================================
583 // function : ConvertIOinGEOMObject()
584 // purpose  :
585 //=======================================================================
586 GEOM::GEOM_Object_ptr GEOMBase::ConvertIOinGEOMObject( const Handle(SALOME_InteractiveObject)& theIO,
587                                                        Standard_Boolean& theResult )
588 {
589   theResult = Standard_False;
590   GEOM::GEOM_Object_var aReturnObject;
591   if ( !theIO.IsNull() )
592   {
593     const char* anEntry = theIO->getEntry();
594
595     SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>
596       ( SUIT_Session::session()->activeApplication()->activeStudy() );
597     if ( !appStudy ) return  GEOM::GEOM_Object::_nil();
598     _PTR(Study) aStudy = appStudy->studyDS();
599
600     _PTR(SObject) aSObj ( aStudy->FindObjectID( anEntry ) );
601
602     if (aSObj)
603     {
604       aReturnObject = GEOM::GEOM_Object::_narrow(GeometryGUI::ClientSObjectToObject(aSObj));
605       theResult = !CORBA::is_nil( aReturnObject );
606     }
607   }
608   return aReturnObject._retn();
609 }
610
611
612 //=======================================================================
613 // function : ConvertListOfIOInListOfGO()
614 // purpose  :
615 //=======================================================================
616 void GEOMBase::ConvertListOfIOInListOfGO( const SALOME_ListIO& theList,
617                                           GEOM::ListOfGO&      theListGO,
618                                           const bool           theShapesOnly )
619 {
620   int nbSel = theList.Extent();
621   theListGO.length( nbSel );
622   SALOME_ListIteratorOfListIO anIter( theList );
623
624   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
625   if ( !appStudy ) return;
626   _PTR(Study) aStudy = appStudy->studyDS();
627
628   int j = 0;
629   for ( int i=0; anIter.More(); anIter.Next(), i++ )
630   {
631     Handle(SALOME_InteractiveObject) anIObj = anIter.Value();
632     _PTR(SObject) aSObj ( aStudy->FindObjectID( anIObj->getEntry() ) );
633
634     if ( aSObj )
635     {
636       GEOM::GEOM_Object_var aGeomObj =
637         GEOM::GEOM_Object::_narrow(GeometryGUI::ClientSObjectToObject(aSObj));
638       if ( !CORBA::is_nil( aGeomObj ) && ( !theShapesOnly || IsShape( aGeomObj ) ) )
639         theListGO[ j++ ] = aGeomObj;
640     }
641   }
642
643   theListGO.length( j );
644 }
645
646 //=================================================================================
647 // function : CreateArrowForLinearEdge()
648 // purpose  : Create a cone topology to be used to display an arrow in the middle
649 //          : of an edge showing its orientation. (For simulation and Viewer OCC only)
650 //=================================================================================
651 bool GEOMBase::CreateArrowForLinearEdge(const TopoDS_Shape& tds, TopoDS_Shape& ArrowCone)
652 {
653   if(SUIT_Session::session()->activeApplication()->desktop()->activeWindow()->getViewManager()->getType()
654      != OCCViewer_Viewer::Type() || tds.ShapeType() != TopAbs_EDGE)
655     return false;
656
657   OCCViewer_ViewPort3d* vp3d = ((OCCViewer_ViewWindow*)SUIT_Session::session()->activeApplication()->desktop()->activeWindow())->getViewPort();
658   Handle( V3d_View) view3d = vp3d->getView();
659   Standard_Real Width, Height;
660   view3d->Size(Width, Height);
661   const Standard_Real aHeight = (Width + Height) / 50.0;
662
663   try {
664     Standard_Real first, last;
665     Handle(Geom_Curve) curv = BRep_Tool::Curve(TopoDS::Edge(tds), first, last);
666     if(!curv->IsCN(1))
667       return false;
668
669     const Standard_Real param = (first+last) / 2.0;
670     gp_Pnt middleParamPoint;
671     gp_Vec V1;
672     curv->D1( param, middleParamPoint, V1);
673     if(V1.Magnitude() < Precision::Confusion())
674       return false;
675
676     /* Topology orientation not geom orientation */
677     if(tds.Orientation() == TopAbs_REVERSED)
678       V1 *= -1.0;
679
680     gp_Ax2 anAxis( middleParamPoint, gp_Dir(V1));
681     const Standard_Real radius1 = aHeight / 5.0;
682     if(radius1 > 10.0 * Precision::Confusion() && aHeight > 10.0 * Precision::Confusion()) {
683       ArrowCone = BRepPrimAPI_MakeCone( anAxis, radius1, 0.0, aHeight ).Shape();
684       return true;
685     }
686   }
687   catch(Standard_Failure) {
688     // OCC failures are hard to catch in GUI.
689     // This  because of the position for  #include <Standard_ErrorHandler.hxx> that is very critic to find
690     // in SALOME environment : compilation error !
691   }
692   return false;
693 }
694
695
696 //=================================================================================
697 // function : VertexToPoint()
698 // purpose  : If S can be converted in a gp_Pnt returns true and the result is P
699 //=================================================================================
700 bool GEOMBase::VertexToPoint(const TopoDS_Shape& S, gp_Pnt& P)
701 {
702   if(S.IsNull() || S.ShapeType() != TopAbs_VERTEX)
703     return false;
704   P = BRep_Tool::Pnt(TopoDS::Vertex(S));
705   return true;
706 }
707
708
709 //=================================================================================
710 // function : GetBipointDxDyDz()
711 // purpose  :
712 //=================================================================================
713 void GEOMBase::GetBipointDxDyDz(gp_Pnt P1, gp_Pnt P2, double& dx, double& dy, double& dz)
714 {
715   dx = P2.X() - P1.X();
716   dy = P2.Y() - P1.Y();
717   dz = P2.Z() - P1.Z();
718   return;
719 }
720
721
722 //=================================================================================
723 // function : LinearEdgeExtremities()
724 // purpose  : If S can be converted in a linear edge and if initial an final points
725 //          : distance is sufficient, returns true else returns false.
726 //          : Resulting points are respectively P1 and P2
727 //=================================================================================
728 bool GEOMBase::LinearEdgeExtremities(const TopoDS_Shape& S,  gp_Pnt& P1, gp_Pnt& P2)
729 {
730   if(S.IsNull() || S.ShapeType() != TopAbs_EDGE)
731     return false;
732   BRepAdaptor_Curve curv(TopoDS::Edge(S));
733   if(curv.GetType() != GeomAbs_Line)
734     return false;
735
736   curv.D0(curv.FirstParameter(), P1);
737   curv.D0(curv.LastParameter(), P2);
738
739   if(P1.Distance(P2) <= Precision::Confusion())
740     return false;
741
742   return true;
743 }
744
745
746 //=======================================================================
747 // function : Parameter()
748 // purpose  : return a parameter (float) from a dialog box
749 //
750 //  avalue1    : is a float or integer used as a default value displayed
751 //  aTitle1    : is the title for aValue1
752 //  aTitle     : is the main title
753 //  bottom     : maximum value to be entered
754 //  top        : minimum value to be entered
755 //  decimals   : number of decimals
756 //=======================================================================
757 double GEOMBase::Parameter(Standard_Boolean& res, const char* aValue1, const char* aTitle1, const char* aTitle, const double bottom, const double top, const int decimals)
758 {
759   GEOMBase_aParameterDlg * Dialog = new GEOMBase_aParameterDlg(aValue1, aTitle1, SUIT_Session::session()->activeApplication()->desktop(),
760                                                                aTitle, TRUE, 0, bottom, top, decimals);
761   int r = Dialog->exec();
762   float X = 0.0;
763   if(r == QDialog::Accepted) {
764     res = Standard_True;
765     X = Dialog->getValue();
766   }
767   else
768     res = Standard_False;
769   delete Dialog;
770   return X;
771 }
772
773
774 //=======================================================================
775 // function : SelectionByNameInDialogs()
776 // purpose  : Called when user has entered a name of object in a LineEdit.
777 //          : The selection is changed. Dialog box will receive the
778 //          : corresponding signal to manage this event.
779 //=======================================================================
780 bool GEOMBase::SelectionByNameInDialogs(QWidget* aWidget, const QString& objectUserName, const SALOME_ListIO& aList)
781 {
782   /* Find SObject with name in component GEOM */
783   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
784   if ( !appStudy ) return false;
785   _PTR(Study) ST = appStudy->studyDS();
786
787   std::vector<_PTR(SObject)> listSO;
788   listSO = ST->FindObjectByName(objectUserName.toStdString(), "GEOM");
789
790   if(listSO.size() < 1) {
791     const QString caption  = QObject::tr("GEOM_WRN_WARNING");
792     const QString text = QObject::tr("GEOM_NAME_INCORRECT");
793     const QString button0  = QObject::tr("GEOM_BUT_OK");
794     SUIT_MessageBox::critical(aWidget, caption, text, button0);
795     return false;
796   }
797   /* More than one object with same name */
798   if(listSO.size() > 1) {
799     const QString caption  = QObject::tr("GEOM_WRN_WARNING");
800     const QString text = QObject::tr("GEOM_IDENTICAL_NAMES_SELECT_BY_MOUSE");
801     const QString button0  = QObject::tr("GEOM_BUT_OK") ;
802     SUIT_MessageBox::critical(aWidget, caption, text, button0) ;
803     listSO.clear();
804     return false;
805   }
806
807   _PTR(SObject) theObj ( listSO[0] );
808   /* Create a SALOME_InteractiveObject with a SALOME::SObject */
809   char* aCopyobjectUserName = CORBA::string_dup(objectUserName.toLatin1().constData());
810   Handle(SALOME_InteractiveObject) SI = new SALOME_InteractiveObject(theObj->GetID().c_str(), "GEOM", aCopyobjectUserName);
811   delete(aCopyobjectUserName);
812
813   /* Add as a selected object       */
814   /* Clear any previous selection : */
815   /* Warning the LineEdit is purged because of signal currentSelectionChanged ! */
816   // Sel->ClearIObjects(); //mzn
817   // Sel->AddIObject(SI); //mzn
818   return true;
819 }
820
821
822 //=======================================================================
823 // function : DefineDlgPosition()
824 // purpose  : Define x and y the default position for a dialog box
825 //=======================================================================
826 bool GEOMBase::DefineDlgPosition(QWidget* aDlg, int& x, int& y)
827 {
828   /* Here the position is on the bottom right corner - 10 */
829   SUIT_Desktop* PP = SUIT_Session::session()->activeApplication()->desktop();
830   x = abs(PP->x() + PP->size().width() - aDlg->size().width() - 10);
831   y = abs(PP->y() + PP->size().height() - aDlg->size().height() - 10);
832   return true;
833 }
834
835
836 //=======================================================================
837 // function : GetDefaultName()
838 // purpose  : Generates default names
839 //=======================================================================
840 QString GEOMBase::GetDefaultName(const QString& theOperation)
841 {
842   QString aName = "";
843
844   // collect all object names of GEOM component
845   SalomeApp_Study* appStudy =
846     dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
847   if ( !appStudy ) return aName;
848   _PTR(Study) aStudy = appStudy->studyDS();
849
850   std::set<std::string> aSet;
851   _PTR(SComponent) aGeomCompo (aStudy->FindComponent("GEOM"));
852   if (aGeomCompo) {
853     _PTR(ChildIterator) it (aStudy->NewChildIterator(aGeomCompo));
854     _PTR(SObject) obj;
855     for (it->InitEx(true); it->More(); it->Next()) {
856       obj = it->Value();
857       aSet.insert(obj->GetName());
858     }
859   }
860
861   // build a unique name
862   int aNumber = 0;
863   bool isUnique = false;
864   while (!isUnique) {
865     aName = theOperation + "_" + QString::number(++aNumber);
866     isUnique = (aSet.count(aName.toStdString()) == 0);
867   }
868
869   return aName;
870 }
871
872
873 //=======================================================================
874 // function : ShowErrorMessage()
875 // purpose  : Shows message box with error code and comment
876 //=======================================================================
877 void GEOMBase::ShowErrorMessage(const char* theErrorCode, const char* theComment)
878 {
879   QString anErrorCode(theErrorCode);
880   QString aComment(theComment);
881
882   QString aText = "";
883   if (!anErrorCode.isEmpty())
884     aText.append("\n" + QObject::tr(anErrorCode.toLatin1().constData()));
885   if (!aComment.isEmpty())
886     aText.append("\n" + QString(theComment));
887
888   SUIT_MessageBox::critical( SUIT_Session::session()->activeApplication()->desktop(), QObject::tr( "GEOM_ERROR" ),
889                              QObject::tr("GEOM_PRP_ABORT") + aText, "OK" );
890 }
891
892
893 //=======================================================================
894 // function : GetObjectFromIOR()
895 // purpose  : returns a GEOM_Object by given IOR (string)
896 //=======================================================================
897 GEOM::GEOM_Object_ptr GEOMBase::GetObjectFromIOR( const char* theIOR )
898 {
899   GEOM::GEOM_Object_var anObject;
900   if ( theIOR == NULL || strlen( theIOR ) == 0 )
901     return anObject._retn(); // returning nil object
902
903   anObject = GEOM::GEOM_Object::_narrow( SalomeApp_Application::orb()->string_to_object( theIOR ) );
904   return anObject._retn();
905 }
906
907 //=======================================================================
908 // function : GetIORFromObject()
909 // purpose  : returns IOR of a given GEOM_Object
910 //=======================================================================
911 char* GEOMBase::GetIORFromObject( const GEOM::GEOM_Object_ptr& theObject )
912 {
913   if ( CORBA::is_nil( theObject ) )
914     return NULL;
915
916   return SalomeApp_Application::orb()->object_to_string( theObject );
917 }
918
919 //=======================================================================
920 // function : GetShape()
921 // purpose  : returns a TopoDS_Shape stored in GEOM_Object
922 //=======================================================================
923 bool GEOMBase::GetShape( const GEOM::GEOM_Object_ptr& theObject, TopoDS_Shape& theShape, const TopAbs_ShapeEnum theType )
924 {
925   if ( !CORBA::is_nil( theObject ) )
926   {
927     TopoDS_Shape aTopoDSShape = GEOM_Client().GetShape(  GeometryGUI::GetGeomGen(), theObject );
928     if ( !aTopoDSShape.IsNull() && ( theType == TopAbs_SHAPE || theType == aTopoDSShape.ShapeType() ) )
929     {
930        theShape = aTopoDSShape;
931        return true;
932     }
933   }
934   return false;
935 }
936
937 //=======================================================================
938 // function : GetName()
939 // purpose  : Get name of object
940 //=======================================================================
941 QString GEOMBase::GetName( GEOM::GEOM_Object_ptr theObj )
942 {
943   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
944
945   if ( appStudy )
946   {
947     CORBA::String_var anIOR = SalomeApp_Application::orb()->object_to_string( theObj );
948     if ( strcmp(anIOR.in(), "") != 0 )
949     {
950       _PTR(SObject) aSObj ( appStudy->studyDS()->FindObjectIOR( string( anIOR ) ) );
951
952       _PTR(GenericAttribute) anAttr;
953
954       if ( aSObj && aSObj->FindAttribute( anAttr, "AttributeName") )
955       {
956         _PTR(AttributeName) aNameAttr ( anAttr );
957         return QString( aNameAttr->Value().c_str() );
958       }
959     }
960   }
961
962   return QString("");
963 }
964
965 bool GEOMBase::IsShape( GEOM::GEOM_Object_ptr theObj )
966 {
967   return !theObj->_is_nil() && theObj->IsShape();
968 }