Salome HOME
Implementation of the "21187: EDF 1137 GEOM: Performance issue when manipulating...
[modules/geom.git] / src / GEOMBase / GEOMBase_Helper.cxx
1 //  Copyright (C) 2007-2010  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  GEOM GEOMGUI : GUI for Geometry component
24 //  File   : GEOMBase_Helper.cxx
25 //  Author : Sergey ANIKIN, Open CASCADE S.A.S. (sergey.anikin@opencascade.com)
26 //
27 #include "GEOMBase_Helper.h"
28 #include "GEOMBase.h"
29 #include "GEOM_Operation.h"
30
31 #include <GeometryGUI.h>
32
33 #include <SUIT_Desktop.h>
34 #include <SUIT_Session.h>
35 #include <SUIT_ViewManager.h>
36 #include <SUIT_ViewWindow.h>
37 #include <SUIT_ViewModel.h>
38 #include <SUIT_MessageBox.h>
39 #include <SUIT_OverrideCursor.h>
40
41 #include <SalomeApp_Module.h>
42 #include <SalomeApp_Application.h>
43 #include <SalomeApp_Study.h>
44 #include <LightApp_SelectionMgr.h>
45 #include <LightApp_DataOwner.h>
46 #include <SalomeApp_Tools.h>
47 #include <SALOME_ListIteratorOfListIO.hxx>
48
49 #include <SALOME_Prs.h>
50
51 #include <OCCViewer_ViewModel.h>
52 #include <SVTK_ViewModel.h>
53
54 #include <TColStd_MapOfInteger.hxx>
55 #include <TCollection_AsciiString.hxx>
56 #include <TColStd_IndexedMapOfInteger.hxx>
57
58 //To disable automatic genericobj management, the following line should be commented.
59 //Otherwise, it should be uncommented. Refer to KERNEL_SRC/src/SALOMEDSImpl/SALOMEDSImpl_AttributeIOR.cxx
60 #define WITHGENERICOBJ
61
62 //================================================================
63 // Function : getActiveView
64 // Purpose  : Get active view window, returns 0 if no open study frame
65 //================================================================
66 static SUIT_ViewWindow* getActiveView()
67 {
68   SUIT_Study* activeStudy = SUIT_Session::session()->activeApplication()->activeStudy();
69   if ( activeStudy )
70     return SUIT_Session::session()->activeApplication()->desktop()->activeWindow();
71
72   return 0;
73 }
74
75
76 //================================================================
77 // Function : getGeomEngine
78 // Purpose  : Static method
79 //================================================================
80 GEOM::GEOM_Gen_ptr GEOMBase_Helper::getGeomEngine()
81 {
82   return GeometryGUI::GetGeomGen();
83 }
84
85 //================================================================
86 // Function : GEOMBase_Helper
87 // Purpose  :
88 //================================================================
89 GEOMBase_Helper::GEOMBase_Helper( SUIT_Desktop* desktop )
90   : myDesktop( desktop ), myViewWindow( 0 ), myDisplayer( 0 ), myCommand( 0 ), isPreview( false )
91 {
92 }
93
94 //================================================================
95 // Function : ~GEOMBase_Helper
96 // Purpose  :
97 //================================================================
98 GEOMBase_Helper::~GEOMBase_Helper()
99 {
100   //rnv: Fix for the "IPAL21922 : WinTC5.1.4: incorrect quit salome"
101   if ( !SUIT_Session::session()->activeApplication() || !SUIT_Session::session()->activeApplication()->desktop() )
102     return;
103
104   if ( myPreview.size() )
105     erasePreview();
106   if ( hasCommand() )
107     abortCommand();
108   SalomeApp_Application* app = (SalomeApp_Application*)(SUIT_Session::session()->activeApplication());
109   if (app) {
110     GeometryGUI* aGeomGUI = dynamic_cast<GeometryGUI*>( app->module( "Geometry" ) );
111     if(aGeomGUI)
112       globalSelection(aGeomGUI->getLocalSelectionMode() , true );
113   }
114
115   if (myDisplayer)
116     delete myDisplayer;
117   if ( !CORBA::is_nil( myOperation ) )
118     myOperation->UnRegister();
119 }
120
121 //================================================================
122 // Function : display
123 // Purpose  :
124 //================================================================
125 void GEOMBase_Helper::display( const ObjectList& objList, const bool updateView )
126 {
127   ObjectList::const_iterator it;
128   for ( it = objList.begin(); it != objList.end(); it++ ) {
129     display( *it, false );
130   }
131   if ( !objList.empty() && updateView )
132     getDisplayer()->UpdateViewer();
133 }
134
135 //================================================================
136 // Function  : display
137 // Purpose   : Display object.
138 // Important : Object must be already in study
139 //================================================================
140 void GEOMBase_Helper::display( GEOM::GEOM_Object_ptr object, const bool updateView )
141 {
142   // Unset color of shape ( this color may be set during preview displaying )
143   // Default color will be used
144   getDisplayer()->UnsetColor();
145   getDisplayer()->UnsetWidth();
146
147   // Enable activisation of selection
148   getDisplayer()->SetToActivate( true );
149
150   // Display object
151   getDisplayer()->Display( object, updateView );
152 }
153
154 //================================================================
155 // Function : erase
156 // Purpose  :
157 //================================================================
158 void GEOMBase_Helper::erase( const ObjectList& objList, const bool updateView )
159 {
160   ObjectList::const_iterator it = objList.begin();
161   for ( ; it != objList.end(); it++ ) {
162     erase( *it, false );
163   }
164   if ( !objList.empty() && updateView )
165     getDisplayer()->UpdateViewer();
166 }
167
168 //================================================================
169 // Function : erase
170 // Purpose  :
171 //================================================================
172 void GEOMBase_Helper::erase( GEOM::GEOM_Object_ptr object, const bool updateView )
173 {
174   if ( !object->_is_nil() ) {
175     QString entry = getEntry( object );
176     getDisplayer()->Erase( new SALOME_InteractiveObject(
177       entry.toLatin1().constData(), 
178       "GEOM", strdup( GEOMBase::GetName( object ).toLatin1().constData() ) ), true, updateView );
179   }
180 }
181
182 //================================================================
183 // Function : redisplay
184 // Purpose  :
185 //================================================================
186 void GEOMBase_Helper::redisplay( const ObjectList& objList,
187                                  const bool withChildren,
188                                  const bool updateView )
189 {
190   ObjectList::const_iterator it = objList.begin();
191   for ( ; it != objList.end(); it++ ) {
192     redisplay( *it, withChildren, false );
193   }
194   if ( !objList.empty() && updateView )
195     getDisplayer()->UpdateViewer();
196 }
197
198 //================================================================
199 // Function : redisplay
200 // Purpose  :
201 //================================================================
202 void GEOMBase_Helper::redisplay( GEOM::GEOM_Object_ptr object,
203                                  const bool withChildren,
204                                  const bool updateView )
205 {
206   if ( !object->_is_nil() ) {
207     // Unset color of shape ( this color may be set during preview displaying )
208     // Default color will be used
209     getDisplayer()->UnsetColor();
210     getDisplayer()->UnsetWidth();
211
212     // Enable activisation of selection
213     getDisplayer()->SetToActivate( true );
214
215     QString entry = getEntry( object );
216     getDisplayer()->Redisplay(new SALOME_InteractiveObject
217                               (entry.toLatin1().constData(), "GEOM", strdup(GEOMBase::GetName(object).toLatin1().constData())), false);
218   }
219
220   if ( withChildren ) {
221     SalomeApp_Study* aDoc = getStudy();
222     if ( aDoc && aDoc->studyDS() ) {
223       _PTR(Study) aStudy = aDoc->studyDS();
224       CORBA::String_var objStr = SalomeApp_Application::orb()->object_to_string(object);
225       _PTR(SObject) aSObj (aStudy->FindObjectIOR(std::string(objStr.in())));
226       if ( aSObj  ) {
227         _PTR(ChildIterator) anIt ( aStudy->NewChildIterator( aSObj ) );
228         for ( anIt->InitEx( true ); anIt->More(); anIt->Next() ) {
229           GEOM::GEOM_Object_var aChild = GEOM::GEOM_Object::_narrow
230             (GeometryGUI::ClientSObjectToObject(anIt->Value()));
231           if ( !CORBA::is_nil( aChild ) ) {
232             if ( !aChild->_is_nil() ) {
233               QString entry = getEntry( aChild );
234               getDisplayer()->Redisplay( new SALOME_InteractiveObject(
235                 entry.toLatin1().constData(), "GEOM", strdup( GEOMBase::GetName( aChild ).toLatin1().constData() ) ), false );
236             }
237           }
238         }
239       }
240     }
241   }
242
243   if ( updateView )
244     getDisplayer()->UpdateViewer();
245 }
246
247 //================================================================
248 // Function : displayPreview
249 // Purpose  : Method for displaying preview based on execute() results
250 //================================================================
251 void GEOMBase_Helper::displayPreview( const bool   display,
252                                       const bool   activate,
253                                       const bool   update,
254                                       const bool   toRemoveFromEngine,
255                                       const double lineWidth,
256                                       const int    displayMode,
257                                       const int    color )
258 {
259   if(!display) {
260     erasePreview( update );
261     return;
262   }
263   
264   isPreview = true;
265   QString msg;
266   if ( !isValid( msg ) )
267   {
268     erasePreview( update );
269     isPreview = false;
270     return;
271   }
272
273   erasePreview( false );
274
275   try {
276     SUIT_OverrideCursor wc;
277     ObjectList objects;
278     if ( !execute( objects ) || !getOperation()->IsDone() ) {
279       wc.suspend();
280     }
281     else {
282       for ( ObjectList::iterator it = objects.begin(); it != objects.end(); ++it )
283       {
284             GEOM::GEOM_Object_var obj=*it;
285         displayPreview( obj, true, activate, false, lineWidth, displayMode, color );
286         if ( toRemoveFromEngine )
287               obj->UnRegister();
288       }
289     }
290   }
291   catch( const SALOME::SALOME_Exception& e ) {
292     SalomeApp_Tools::QtCatchCorbaException( e );
293   }
294
295   isPreview = false;
296
297   if ( update )
298     updateViewer();
299 }
300
301 //================================================================
302 // Function : displayPreview
303 // Purpose  : Method for displaying preview of resulting shape
304 //================================================================
305 void GEOMBase_Helper::displayPreview( GEOM::GEOM_Object_ptr object,
306                                       const bool            append,
307                                       const bool            activate,
308                                       const bool            update,
309                                       const double          lineWidth,
310                                       const int             displayMode,
311                                       const int             color )
312 {
313   // Set color for preview shape
314   getDisplayer()->SetColor( color == -1 ? Quantity_NOC_VIOLET : color );
315
316   // set width of displayed shape
317   getDisplayer()->SetWidth( lineWidth );
318
319   // set display mode of displayed shape
320   int aPrevDispMode = getDisplayer()->SetDisplayMode( displayMode );
321
322   // Disable activation of selection
323   getDisplayer()->SetToActivate( activate );
324
325   // Make a reference to GEOM_Object
326   CORBA::String_var objStr = SalomeApp_Application::orb()->object_to_string( object );
327   getDisplayer()->SetName( objStr.in() );
328
329   // Build prs
330   SALOME_Prs* aPrs = getDisplayer()->BuildPrs( object );
331   if ( aPrs == 0 || aPrs->IsNull() )
332     return;
333
334   // Display prs
335   displayPreview( aPrs, append, update );
336
337   getDisplayer()->UnsetName();
338   getDisplayer()->UnsetColor();
339   getDisplayer()->SetDisplayMode( aPrevDispMode );
340
341   // Enable activation of displayed objects
342   getDisplayer()->SetToActivate( true );
343 }
344
345 //================================================================
346 // Function : displayPreview
347 // Purpose  : Method for displaying arbitrary preview objects (not limited to shapes)
348 //================================================================
349 void GEOMBase_Helper::displayPreview( const SALOME_Prs* prs,
350                                       const bool        append,
351                                       const bool        update )
352 {
353   if ( !append )
354     erasePreview( false );
355
356   // remember current view frame to make correct erase preview later
357   myViewWindow = getActiveView();
358
359   if ( myViewWindow == 0 )
360     return;
361
362   // Display prs
363   SUIT_ViewManager* aViewManager = myViewWindow->getViewManager();
364   if ( aViewManager->getType() == OCCViewer_Viewer::Type() ||
365        aViewManager->getType() == SVTK_Viewer::Type() )
366     {
367       SUIT_ViewModel* aViewModel = aViewManager->getViewModel();
368       SALOME_View* aView = dynamic_cast<SALOME_View*>(aViewModel);
369       if (aView)
370         aView->Display( prs );
371     }
372
373   // Add prs to the preview list
374   myPreview.push_back( (SALOME_Prs*)prs );
375
376   // Update viewer
377   if ( update )
378     getDisplayer()->UpdateViewer();
379 }
380
381 //================================================================
382 // Function : erasePreview
383 // Purpose  :
384 //================================================================
385 void GEOMBase_Helper::erasePreview( const bool update )
386 {
387   // check view frame where the preview was displayed
388   bool vfOK = checkViewWindow() && myViewWindow;
389   // Iterate through presentations and delete them
390   for ( PrsList::iterator anIter = myPreview.begin(); anIter != myPreview.end(); ++anIter ) {
391     if ( vfOK )
392       {
393          SUIT_ViewManager* aViewManager = myViewWindow->getViewManager();
394          if ( aViewManager->getType() == OCCViewer_Viewer::Type() ||
395               aViewManager->getType() == SVTK_Viewer::Type() )
396            {
397              SUIT_ViewModel* aViewModel = aViewManager->getViewModel();
398              SALOME_View* aView = dynamic_cast<SALOME_View*>(aViewModel);
399              if (aView)
400                aView->Erase( *anIter, true );
401            }
402       }
403     delete *anIter;
404   }
405   myPreview.clear();
406
407   // Update viewer
408   if ( update )
409     updateViewer();
410 }
411
412 //================================================================
413 // Function  : localSelection
414 // Purpose   : Activate selection of objects of a given type
415 // IMPORTANT : Works after localSelection( ... ) method call only
416 //================================================================
417 void GEOMBase_Helper::activate( const int theType )
418 {
419   if (!getStudy()) return;
420   _PTR(Study) aStudy = getStudy()->studyDS();
421   _PTR(SComponent) aGeom ( aStudy->FindComponent( "GEOM" ) );
422   if ( !aGeom )
423     return;
424
425   SALOME_ListIO aList;
426   _PTR(ChildIterator) anIter ( aStudy->NewChildIterator( aGeom ) );
427   for ( ; anIter->More(); anIter->Next() )
428   {
429     _PTR(SObject) aSO ( anIter->Value() );
430     if ( aSO )
431     {
432       _PTR(SObject) aRefSO;
433       if ( !aSO->ReferencedObject( aRefSO ) )
434       {
435         GEOM::GEOM_Object_var anObj = GEOM::GEOM_Object::_narrow
436           (GeometryGUI::ClientSObjectToObject(aSO));
437         if ( !anObj->_is_nil() && anObj->GetType() == theType )
438           aList.Append( new SALOME_InteractiveObject( aSO->GetID().c_str(), "GEOM", aSO->GetName().c_str()) );
439       }
440     }
441   }
442
443   getDisplayer()->LocalSelection( aList, 0 );
444 }
445
446 //================================================================
447 // Function : localSelection
448 // Purpose  : Activate selection of subshapes in accordance with mode
449 //            theMode is from TopAbs_ShapeEnum
450 //================================================================
451 void GEOMBase_Helper::localSelection( const ObjectList& theObjs, const int theMode )
452 {
453   SALOME_ListIO aListOfIO;
454
455   ObjectList::const_iterator anIter = theObjs.begin();
456   for ( ; anIter != theObjs.end(); ++anIter )
457   {
458     GEOM::GEOM_Object_ptr anObj = *anIter;
459     if ( anObj->_is_nil() )
460       continue;
461     QString anEntry = getEntry( anObj );
462     if ( anEntry != "" )
463       aListOfIO.Append( new SALOME_InteractiveObject(
464         anEntry.toLatin1().constData(), "GEOM", strdup( GEOMBase::GetName( anObj ).toLatin1().constData() ) ) );
465   }
466
467   getDisplayer()->LocalSelection( aListOfIO, theMode );
468 }
469
470 //================================================================
471 // Function : localSelection
472 // Purpose  : Activate selection of subshapes in accordance with mode
473 //            theMode is from TopAbs_ShapeEnum
474 //================================================================
475 void GEOMBase_Helper::localSelection( GEOM::GEOM_Object_ptr obj, const int mode )
476 {
477   // If object is null local selection for all objects is activated
478   if ( obj->_is_nil() ) {
479     getDisplayer()->LocalSelection( Handle(SALOME_InteractiveObject)(), mode );
480     return;
481   }
482
483   ObjectList objList;
484   objList.push_back( obj );
485   localSelection( objList, mode );
486 }
487
488
489 //================================================================
490 // Function : globalSelection
491 // Purpose  : Activate selection of subshapes. Set selection filters
492 //            in accordance with mode. theMode is from GEOMImpl_Types
493 //================================================================
494 void GEOMBase_Helper::globalSelection( const int theMode, const bool update )
495 {
496   getDisplayer()->GlobalSelection( theMode, update );
497 }
498
499 //================================================================
500 // Function : globalSelection
501 // Purpose  : Activate selection of subshapes. Set selection filters
502 //            in accordance with mode. theMode is from GEOMImpl_Types
503 //================================================================
504 void GEOMBase_Helper::globalSelection( const TColStd_MapOfInteger& theModes,
505                                        const bool update )
506 {
507   getDisplayer()->GlobalSelection( theModes, update );
508 }
509
510 //================================================================
511 // Function : globalSelection
512 // Purpose  : Activate selection of subshapes. Set selection filters
513 //            in accordance with mode. theMode is from GEOMImpl_Types
514 //================================================================
515 void GEOMBase_Helper::globalSelection( const TColStd_MapOfInteger& theModes,
516                                        const QList<int>& subShapes,
517                                        const bool update )
518 {
519   getDisplayer()->GlobalSelection( theModes, update, &subShapes );
520 }
521
522 //================================================================
523 // Function : addInStudy
524 // Purpose  : Add object in study
525 //================================================================
526 void GEOMBase_Helper::addInStudy( GEOM::GEOM_Object_ptr theObj, const char* theName )
527 {
528   if ( !hasCommand() )
529     return;
530
531   _PTR(Study) aStudy = getStudy()->studyDS();
532   if ( !aStudy || theObj->_is_nil() )
533     return;
534
535   SALOMEDS::Study_var aStudyDS = GeometryGUI::ClientStudyToStudy(aStudy);
536
537   GEOM::GEOM_Object_ptr aFatherObj = getFather( theObj );
538
539   SALOMEDS::SObject_var aSO =
540     getGeomEngine()->AddInStudy(aStudyDS, theObj, theName, aFatherObj);
541
542   // Each dialog is responsible for this method implementation,
543   // default implementation does nothing
544   restoreSubShapes(aStudyDS, aSO);
545   aSO->UnRegister();
546 }
547
548 //================================================================
549 // Function : restoreSubShapes
550 // Purpose  : restore tree of argument's sub-shapes under the resulting shape
551 //================================================================
552 void GEOMBase_Helper::restoreSubShapes (SALOMEDS::Study_ptr   /*theStudy*/,
553                                         SALOMEDS::SObject_ptr /*theSObject*/)
554 {
555   // do nothing by default
556
557   // example of implementation in particular dialog:
558   // GEOM::ListOfGO anArgs;
559   // anArgs.length(0); // empty list means that all arguments should be restored
560   // getGeomEngine()->RestoreSubShapesSO(theStudy, theSObject, anArgs,
561   //                                     /*theFindMethod=*/GEOM::FSM_GetInPlace,
562   //                                     /*theInheritFirstArg=*/false);
563 }
564
565 //================================================================
566 // Function : updateObjBrowser
567 // Purpose  : Update object browser
568 //================================================================
569 void GEOMBase_Helper::updateObjBrowser() const
570 {
571   SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>(SUIT_Session::session()->activeApplication());
572   if (app) {
573     CAM_Module* module = app->module( "Geometry" );
574     SalomeApp_Module* appMod = dynamic_cast<SalomeApp_Module*>( module );
575     if ( appMod ) {
576       appMod->updateObjBrowser( true );
577     }
578   }
579 }
580
581 //================================================================
582 // Function : updateViewer
583 // Purpose  : Update active 3D view
584 //================================================================
585 void GEOMBase_Helper::updateViewer()
586 {
587   getDisplayer()->UpdateViewer();
588 }
589
590 //================================================================
591 // Function : getStudyId
592 // Purpose  : Get study Id
593 //================================================================
594 int GEOMBase_Helper::getStudyId() const
595 {
596   int anId = -1;
597   if ( getStudy() )
598     anId = getStudy()->id();
599   return anId;
600 }
601
602 //================================================================
603 // Function : getStudy
604 // Purpose  : Returns the active study. It is recommended to use
605 //            this method instead of direct desktop->getActiveStudy() calls
606 //================================================================
607 SalomeApp_Study* GEOMBase_Helper::getStudy() const
608 {
609   SUIT_Desktop* aDesktop = getDesktop();
610   if (!aDesktop)
611     return 0;
612
613   QList<SUIT_Application*> anAppList = SUIT_Session::session()->applications();
614
615   SUIT_Application* anApp = 0;
616   QListIterator<SUIT_Application*> it( anAppList );
617   while ( it.hasNext() )
618     {
619       anApp = it.next();
620       if ( anApp && anApp->desktop() == aDesktop )
621         break;
622     }
623
624   return dynamic_cast<SalomeApp_Study*>(anApp->activeStudy());
625 }
626
627 //================================================================
628 // Function : getEntry
629 // Purpose  :
630 //================================================================
631 QString GEOMBase_Helper::getEntry( GEOM::GEOM_Object_ptr object ) const
632 {
633   SalomeApp_Study* study = getStudy();
634   if ( study )  {
635     QString objIOR = GEOMBase::GetIORFromObject( object );
636     if ( objIOR != "" ) {
637       _PTR(SObject) SO ( study->studyDS()->FindObjectIOR( objIOR.toLatin1().constData() ) );
638       if ( SO )
639         return QString::fromStdString(SO->GetID());
640     }
641   }
642   return "";
643 }
644
645 //================================================================
646 // Function : getDisplayer
647 // Purpose  :
648 //================================================================
649 GEOM_Displayer* GEOMBase_Helper::getDisplayer()
650 {
651   if ( !myDisplayer )
652     myDisplayer = new GEOM_Displayer( getStudy() );
653   return myDisplayer;
654 }
655
656 //================================================================
657 // Function : clearShapeBuffer
658 // Purpose  :
659 //================================================================
660 void GEOMBase_Helper::clearShapeBuffer( GEOM::GEOM_Object_ptr theObj )
661 {
662   if ( CORBA::is_nil( theObj ) )
663     return;
664
665   CORBA::String_var IOR = SalomeApp_Application::orb()->object_to_string( theObj );
666   TCollection_AsciiString asciiIOR( (char *)IOR.in() );
667   GEOM_Client::get_client().RemoveShapeFromBuffer( asciiIOR );
668
669   if ( !getStudy() || !getStudy()->studyDS() )
670     return;
671
672   _PTR(Study) aStudy = getStudy()->studyDS();
673   _PTR(SObject) aSObj ( aStudy->FindObjectIOR( std::string( IOR ) ) );
674   if ( !aSObj )
675     return;
676
677   _PTR(ChildIterator) anIt ( aStudy->NewChildIterator( aSObj ) );
678   for ( anIt->InitEx( true ); anIt->More(); anIt->Next() ) {
679     _PTR(GenericAttribute) anAttr;
680     if ( anIt->Value()->FindAttribute(anAttr, "AttributeIOR") ) {
681       _PTR(AttributeIOR) anIOR ( anAttr );
682       TCollection_AsciiString asciiIOR( (char*)anIOR->Value().c_str() );
683       GEOM_Client::get_client().RemoveShapeFromBuffer( asciiIOR );
684     }
685   }
686 }
687
688 //================================================================
689 // Function : openCommand
690 // Purpose  :
691 //================================================================
692 bool GEOMBase_Helper::openCommand()
693 {
694   bool res = false;
695   if ( !getStudy() || hasCommand() )
696     return res;
697
698   GEOM::GEOM_IOperations_var anOp = GEOM::GEOM_IOperations::_narrow( getOperation() );
699   if ( !anOp->_is_nil() ) {
700     myCommand = new GEOM_Operation( SUIT_Session::session()->activeApplication(), anOp.in() );
701     myCommand->start();
702     res = true;
703   }
704
705   return res;
706 }
707
708 //================================================================
709 // Function : abortCommand
710 // Purpose  :
711 //================================================================
712 bool GEOMBase_Helper::abortCommand()
713 {
714   if ( !hasCommand() )
715     return false;
716
717   myCommand->abort();
718   delete myCommand; // I don't know where to delete this object here ?
719   myCommand = 0;
720
721   return true;
722 }
723
724 //================================================================
725 // Function : commitCommand
726 // Purpose  :
727 //================================================================
728 bool GEOMBase_Helper::commitCommand( const char* )
729 {
730   if ( !hasCommand() )
731     return false;
732
733   myCommand->commit();
734   delete myCommand; // I don't know where to delete this object here ?
735   myCommand = 0;
736
737   return true;
738 }
739
740 //================================================================
741 // Function : hasCommand
742 // Purpose  :
743 //================================================================
744 bool GEOMBase_Helper::hasCommand() const
745 {
746   return (bool)myCommand;
747 }
748
749 //================================================================
750 // Function : getOperation
751 // Purpose  :
752 //================================================================
753 GEOM::GEOM_IOperations_ptr GEOMBase_Helper::getOperation()
754 {
755   if ( myOperation->_is_nil() )
756     myOperation = createOperation();
757
758   return myOperation;
759 }
760
761
762
763 //================================================================
764 // Function : checkViewWindow
765 // Purpose  :
766 //================================================================
767 bool GEOMBase_Helper::checkViewWindow()
768 {
769   if ( myViewWindow ){
770     QList<SUIT_ViewWindow*> aViewWindowsList = SUIT_Session::session()->activeApplication()->desktop()->windows();
771     QListIterator<SUIT_ViewWindow*> it( aViewWindowsList );
772     while ( it.hasNext() )
773       {
774         if ( myViewWindow == it.next() )
775           return true;
776       }
777   }
778   myViewWindow = 0;
779   return false;
780 }
781
782 //================================================================
783 // Function : onAccept
784 // Purpose  : This method should be called from dialog's slots onOk() and onApply()
785 //            It perfroms user input validation, then it
786 //            performs a proper operation and manages transactions, etc.
787 //================================================================
788 bool GEOMBase_Helper::onAccept( const bool publish, const bool useTransaction )
789 {
790   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
791   if ( !appStudy ) return false;
792   _PTR(Study) aStudy = appStudy->studyDS();
793
794   bool aLocked = (_PTR(AttributeStudyProperties) (aStudy->GetProperties()))->IsLocked();
795   if ( aLocked ) {
796     MESSAGE("GEOMBase_Helper::onAccept - ActiveStudy is locked");
797     SUIT_MessageBox::warning ( (QWidget*)SUIT_Session::session()->activeApplication()->desktop(),
798                                QObject::tr("WRN_WARNING"),
799                                QObject::tr("WRN_STUDY_LOCKED"),
800                                QObject::tr("BUT_OK") );
801     return false;
802   }
803
804   QString msg;
805   if ( !isValid( msg ) ) {
806     showError( msg );
807     return false;
808   }
809
810   erasePreview( false );
811
812   bool result = false;
813
814   try {
815     if ( ( !publish && !useTransaction ) || openCommand() ) {
816       SUIT_OverrideCursor wc;
817       SUIT_Session::session()->activeApplication()->putInfo( "" );
818       ObjectList objects;
819       if ( !execute( objects ) || !getOperation()->IsDone() ) {
820         wc.suspend();
821         abortCommand();
822         showError();
823       }
824       else {
825         addSubshapesToStudy(); // add Subshapes if local selection
826         const int nbObjs = objects.size();
827         int aNumber = 1;
828         for ( ObjectList::iterator it = objects.begin(); it != objects.end(); ++it ) {
829           GEOM::GEOM_Object_var obj=*it;
830           if ( publish ) {
831             QString aName = getNewObjectName();
832             if ( nbObjs > 1 ) {
833               if (aName.isEmpty())
834                 aName = getPrefix(obj);
835               if (nbObjs <= 30) {
836                 // Try to find a unique name
837                 aName = GEOMBase::GetDefaultName(aName, extractPrefix());
838               } else {
839                 // Don't check name uniqueness in case of numerous objects
840                 aName = aName + "_" + QString::number(aNumber++);
841               }
842             } else {
843               // PAL6521: use a prefix, if some dialog box doesn't reimplement getNewObjectName()
844               if ( aName.isEmpty() )
845                 aName = GEOMBase::GetDefaultName( getPrefix( obj ) );
846             }
847             addInStudy( obj, aName.toLatin1().constData() );
848             // updateView=false
849             display( obj, false );
850 #ifdef WITHGENERICOBJ
851             // obj has been published in study. Its refcount has been incremented.
852             // It is safe to decrement its refcount
853             // so that it will be destroyed when the entry in study will be removed
854             obj->UnRegister();
855 #endif
856           }
857           else {
858             // asv : fix of PAL6454. If publish==false, then the original shape
859             // was modified, and need to be re-cached in GEOM_Client before redisplay
860             clearShapeBuffer( obj );
861             // withChildren=true, updateView=false
862             redisplay( obj, true, false );
863           }
864         }
865
866         if ( nbObjs ) {
867           commitCommand();
868           updateObjBrowser();
869           SUIT_Session::session()->activeApplication()->putInfo( QObject::tr("GEOM_PRP_DONE") );
870           result = true;
871         }
872         else
873           abortCommand();
874       }
875     }
876   }
877   catch( const SALOME::SALOME_Exception& e ) {
878     SalomeApp_Tools::QtCatchCorbaException( e );
879     abortCommand();
880   }
881
882   updateViewer();
883
884   return result;
885 }
886
887
888 //================================================================
889 // Function : showError
890 // Purpose  : Shows a message box with infromation about an error taken from getOperation()->GetErrorCode()
891 //================================================================
892 void GEOMBase_Helper::showError()
893 {
894   QString msg;
895   if ( !getOperation()->_is_nil() )
896     msg = QObject::tr( getOperation()->GetErrorCode() );
897
898   if ( msg.isEmpty() )
899     msg = QObject::tr( "GEOM_PRP_ABORT" );
900
901   SUIT_MessageBox::critical( SUIT_Session::session()->activeApplication()->desktop(),
902                              QObject::tr( "GEOM_ERROR_STATUS" ),
903                              msg,
904                              QObject::tr( "BUT_OK" ) );
905 }
906
907 //================================================================
908 // Function : showError
909 // Purpose  : Shows a error message followed by <msg>
910 //================================================================
911 void GEOMBase_Helper::showError( const QString& msg )
912 {
913   QString str( QObject::tr( "GEOM_INCORRECT_INPUT" ) );
914   if ( !msg.isEmpty() )
915     str += "\n" + msg;
916   SUIT_MessageBox::critical(SUIT_Session::session()->activeApplication()->desktop(), QObject::tr( "GEOM_ERROR" ), str, QObject::tr( "BUT_OK" ) );
917 }
918
919 //////////////////////////////////////////////////////////////////
920 // Virtual methods to be redefined in dialogs
921 //////////////////////////////////////////////////////////////////
922
923 //================================================================
924 // Function : createOperation
925 // Purpose  : Redefine this method to return proper IOperation reference
926 //================================================================
927 GEOM::GEOM_IOperations_ptr GEOMBase_Helper::createOperation()
928 {
929   GEOM::GEOM_IOperations_var aNilOp;
930   return aNilOp._retn();
931 }
932
933 //================================================================
934 // Function : isValid
935 // Purpose  : Called by onAccept(). Redefine this method to check validity of user input in dialog boxes.
936 //================================================================
937 bool GEOMBase_Helper::isValid( QString& )
938 {
939   return true;
940 }
941
942 //================================================================
943 // Function : execute
944 // Purpose  : This method is called by onAccept().
945 //            It should perform the required operation and put all new or modified objects into
946 //            <objects> argument.Should return <false> if some error occurs during its execution.
947 //================================================================
948 bool GEOMBase_Helper::execute( ObjectList& objects )
949 {
950   return false;
951 }
952
953 //================================================================
954 // Function : getFather
955 // Purpose  : This method is called by addInStudy(). It should return a father object
956 //            for <theObj> or a nil reference if <theObj> should be published
957 //            as a top-level object.
958 //================================================================
959 GEOM::GEOM_Object_ptr GEOMBase_Helper::getFather( GEOM::GEOM_Object_ptr theObj )
960 {
961   return GEOM::GEOM_Object::_nil();
962 }
963
964 //================================================================
965 // Function : getNewObjectName
966 // Purpose  : Redefine this method to return proper name for a new object
967 //================================================================
968 QString GEOMBase_Helper::getNewObjectName() const
969 {
970   return QString::null;
971 }
972
973 //================================================================
974 // Function : extractPrefix
975 // Purpose  : Redefine this method to return \c true if necessary
976 //            to extract prefix when generating new name for the
977 //            object(s) being created
978 //================================================================
979 bool GEOMBase_Helper::extractPrefix() const
980 {
981   return false;
982 }
983
984 //================================================================
985 // Function : getPrefix
986 // Purpose  : Get prefix for name of created object
987 //================================================================
988 QString GEOMBase_Helper::getPrefix( GEOM::GEOM_Object_ptr theObj ) const
989 {
990   if ( !myPrefix.isEmpty() || theObj->_is_nil() )
991     return myPrefix;
992
993   GEOM::shape_type aType = theObj->GetShapeType();
994
995   switch ( aType )
996   {
997     case GEOM::VERTEX   : return QObject::tr( "GEOM_VERTEX" );
998     case GEOM::EDGE     : return QObject::tr( "GEOM_EDGE" );
999     case GEOM::WIRE     : return QObject::tr( "GEOM_WIRE" );
1000     case GEOM::FACE     : return QObject::tr( "GEOM_FACE" );
1001     case GEOM::SHELL    : return QObject::tr( "GEOM_SHELL" );
1002     case GEOM::SOLID    : return QObject::tr( "GEOM_SOLID" );
1003     case GEOM::COMPSOLID: return QObject::tr( "GEOM_COMPOUNDSOLID" );
1004     case GEOM::COMPOUND : return QObject::tr( "GEOM_COMPOUND" );
1005     default : return "";
1006   }
1007 }
1008
1009 //================================================================
1010 // Function : getDesktop
1011 // Purpose  : Returns myDesktop field. Initialized in constructor,
1012 //            usually as dynamic_cast<SUIT_Desktop*>(parentWidget())
1013 //================================================================
1014 SUIT_Desktop* GEOMBase_Helper::getDesktop() const
1015 {
1016   return myDesktop;
1017 }
1018
1019 //================================================================
1020 // Function : selectObjects
1021 // Purpose  : Selects list of objects
1022 //================================================================
1023 bool GEOMBase_Helper::selectObjects( ObjectList& objects )
1024 {
1025   SUIT_DataOwnerPtrList aList;
1026   ObjectList::iterator anIter;
1027   for ( anIter = objects.begin(); anIter != objects.end(); ++anIter )
1028   {
1029     QString anEntry = getEntry( *anIter );
1030     LightApp_DataOwner* anOwher = new LightApp_DataOwner( anEntry );
1031     aList.append( anOwher );
1032   }
1033
1034   SUIT_Session* session = SUIT_Session::session();
1035   SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( session->activeApplication() );
1036   if ( !app )
1037     return false;
1038
1039   LightApp_SelectionMgr* aMgr = app->selectionMgr();
1040   if ( !aMgr )
1041     return false;
1042
1043   aMgr->setSelected( aList, false );
1044
1045   return true;
1046 }
1047
1048 //================================================================
1049 // Function : findObjectInFather
1050 // Purpose  : It should return an object if its founded in study or
1051 //            return Null object if the object is not founded
1052 //================================================================
1053 GEOM::GEOM_Object_ptr GEOMBase_Helper::findObjectInFather (GEOM::GEOM_Object_ptr theFather,
1054                                                            const QString& theName)
1055 {
1056   SalomeApp_Application* app =
1057     dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
1058   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
1059   _PTR(Study) aDStudy = appStudy->studyDS();
1060   QString IOR = GEOMBase::GetIORFromObject( theFather );
1061   _PTR(SObject) SObj ( aDStudy->FindObjectIOR( IOR.toLatin1().constData() ) );
1062
1063   bool inStudy = false;
1064   GEOM::GEOM_Object_var aReturnObject;
1065   for (_PTR(ChildIterator) iit (aDStudy->NewChildIterator( SObj )); iit->More() && !inStudy; iit->Next()) {
1066     _PTR(SObject) child (iit->Value());
1067     QString aChildName = child->GetName().c_str();
1068     if (aChildName == theName) {
1069       inStudy = true;
1070       CORBA::Object_var corbaObj = GeometryGUI::ClientSObjectToObject(iit->Value());
1071       aReturnObject = GEOM::GEOM_Object::_narrow( corbaObj );
1072     }
1073   }
1074   if (inStudy)
1075     return aReturnObject._retn();
1076   
1077   return GEOM::GEOM_Object::_nil();
1078 }
1079
1080 //================================================================
1081 // Function : findObjectInFather
1082 // Purpose  : It should return an object if its founded in study or
1083 //            return Null object if the object is not founded
1084 //================================================================
1085 GEOM::GEOM_Object_ptr GEOMBase_Helper::findObjectInFather( GEOM::GEOM_Object_ptr theFather,
1086                                                            int theIndex )
1087 {
1088   GEOM::GEOM_Object_var object;
1089   bool found = false;
1090   
1091   SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
1092   if ( study ) {
1093     _PTR(Study) studyDS = study->studyDS();
1094     QString IOR = GEOMBase::GetIORFromObject( theFather );
1095     _PTR(SObject) sobject( studyDS->FindObjectIOR( IOR.toLatin1().constData() ) );
1096     if ( sobject ) {
1097       _PTR(ChildIterator) it( studyDS->NewChildIterator( sobject ) );
1098       for ( ; it->More() && !found; it->Next() ) {
1099         GEOM::GEOM_Object_var cobject = GEOM::GEOM_Object::_narrow( GeometryGUI::ClientSObjectToObject( it->Value() ) );
1100         if ( !CORBA::is_nil( cobject ) ) {
1101           GEOM::ListOfLong_var indices = cobject->GetSubShapeIndices();
1102           int length = indices->length();
1103           for ( int i = 0; i < length && !found; i++ ) {
1104             if ( indices[i] == theIndex ) {
1105               object = cobject;
1106               found = true;
1107             }
1108           }
1109         }
1110       }
1111     }
1112   }
1113   
1114   return object._retn();
1115 }
1116
1117 //================================================================
1118 // Function : addSubshapesToStudy
1119 // Purpose  : Virtual method to add subshapes if needs
1120 //================================================================
1121 void GEOMBase_Helper::addSubshapesToStudy()
1122 {
1123   //Impemented in Dialogs, called from Accept method
1124 }
1125
1126 //================================================================
1127 // Function : getSelected
1128 // Purpose  : Get selected object by specified type
1129 //
1130 // Returns valid object if only one object of the specified type is selected
1131 // (no matter global or local selection is activated). If \a type is TopAbs_SHAPE,
1132 // geometrical object of any valid type is expected.
1133 // 
1134 // \param type type of the object to be obtained from selection
1135 // \return selected geometrical object or nil object if selection is not satisfactory
1136 //================================================================
1137 GEOM::GeomObjPtr GEOMBase_Helper::getSelected( TopAbs_ShapeEnum type )
1138 {
1139   QList<TopAbs_ShapeEnum> types;
1140   types << type;
1141   return getSelected( types );
1142 }
1143
1144 //================================================================
1145 // Function : getSelected
1146 // Purpose  : Get selected object by specified types
1147 //
1148 // Returns valid object if only one object of the specified type is selected
1149 // (no matter global or local selection is activated). The list of allowed
1150 // shape types is passed via \a types. If \a types includes TopAbs_SHAPE,
1151 // geometrical object of any valid type is expected.
1152 // 
1153 // \param types list of allowed shape types for the objects to be obtained from selection
1154 // \return selected geometrical object or nil object if selection is not satisfactory
1155 //================================================================
1156 GEOM::GeomObjPtr GEOMBase_Helper::getSelected( const QList<TopAbs_ShapeEnum>& types )
1157 {
1158   QList<GEOM::GeomObjPtr> selected = getSelected( types, 1 );
1159   return selected.count() > 0 ? selected[0] : GEOM::GeomObjPtr();
1160 }
1161
1162 //================================================================
1163 // Function : getSelected
1164 // Purpose  : Get selected object(s) by specified type
1165 //
1166 // Returns list of selected objects if selection satisfies specifies selection options.
1167 // (no matter global or local selection is activated). If \a type is TopAbs_SHAPE,
1168 // geometrical objects of any valid type are expected.
1169 //
1170 // The \a type parameter specifies allowed type of the object(s) being selected.
1171 // The \a count parameter specifies exact number of the objects to be retrieved from selection.
1172 // The \a strict parameter specifies policy being applied to the selection. 
1173 // If \a count < 0, then any number of the selected objects is valid (including 0).
1174 // In this case, if \a strict is \c true (default), all selected objects should satisfy
1175 // the specified \a type.
1176 // If \a count > 0, only specified number of the objects is retrieved from the selection.
1177 // In this case, if \a strict is \c true (default), function returns empty list if total number of selected
1178 // objects does not correspond to the \a count parameter. Otherwise (if \a strict is \c false),
1179 // function returns valid list of objects if at least \a count objects satisfy specified \a type.
1180 // 
1181 // \param type type of the object(s) to be obtained from selection
1182 // \param count number of items to be retrieved from selection
1183 // \param strict selection policy
1184 // \return list of selected geometrical objects or empty list if selection is not satisfactory
1185 //================================================================
1186 QList<GEOM::GeomObjPtr> GEOMBase_Helper::getSelected( TopAbs_ShapeEnum type, int count, bool strict )
1187 {
1188   QList<TopAbs_ShapeEnum> types;
1189   types << type;
1190   return getSelected( types, count, strict );
1191 }
1192
1193 static bool typeInList( TopAbs_ShapeEnum type, const QList<TopAbs_ShapeEnum>& types )
1194 {
1195   bool ok = false;
1196   for ( int i = 0; i < types.count() && !ok; i++ )
1197     ok = types[i] == TopAbs_SHAPE || types[i] == type;
1198   return ok;
1199 }
1200
1201 //================================================================
1202 // Function : getSelected
1203 // Purpose  : Get selected objects by specified types
1204 //
1205 // Returns list of selected objects if selection satisfies specifies selection options.
1206 // (no matter global or local selection is activated). If \a types includes TopAbs_SHAPE,
1207 // geometrical objects of any valid type are expected.
1208 //
1209 // The \a types parameter specifies allowed types of the object(s) being selected.
1210 // The \a count parameter specifies exact number of the objects to be retrieved from selection.
1211 // The \a strict parameter specifies policy being applied to the selection. 
1212 // If \a count < 0, then any number of the selected objects is valid (including 0).
1213 // In this case, if \a strict is \c true (default), all selected objects should satisfy
1214 // the specified \a type.
1215 // If \a count > 0, only specified number of the objects is retrieved from the selection.
1216 // In this case, if \a strict is \c true (default), function returns empty list if total number of selected
1217 // objects does not correspond to the \a count parameter. Otherwise (if \a strict is \c false),
1218 // function returns valid list of objects if at least \a count objects satisfy specified \a type.
1219 // 
1220 // \param types list of allowed shape types for the objects to be obtained from selection
1221 // \param count number of items to be retrieved from selection
1222 // \param strict selection policy
1223 // \return list of selected geometrical objects or empty list if selection is not satisfactory
1224 //================================================================
1225 QList<GEOM::GeomObjPtr> GEOMBase_Helper::getSelected( const QList<TopAbs_ShapeEnum>& types, int count, bool strict )
1226 {
1227   SUIT_Session* session = SUIT_Session::session();
1228   QList<GEOM::GeomObjPtr> result;
1229
1230   SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( session->activeApplication() );
1231   if ( app ) {
1232     LightApp_SelectionMgr* selMgr = app->selectionMgr();
1233     if ( selMgr ) {
1234       SALOME_ListIO selected;
1235       selMgr->selectedObjects( selected );
1236       SALOME_ListIteratorOfListIO it( selected );
1237       bool stopped = false;
1238       for ( ; it.More() && !stopped; it.Next() ) {
1239         Handle(SALOME_InteractiveObject) IO = it.Value();
1240         GEOM::GeomObjPtr object = GEOMBase::ConvertIOinGEOMObject( IO );
1241         if ( object ) {
1242           TColStd_IndexedMapOfInteger subShapes;
1243           selMgr->GetIndexes( IO, subShapes );
1244           int nbSubShapes = subShapes.Extent();
1245           if ( nbSubShapes == 0 ) {
1246             // global selection
1247             if ( typeInList( (TopAbs_ShapeEnum)(object->GetShapeType()), types ) ) {
1248               result << object;
1249               if ( count > 0 ) {
1250                 if ( strict && result.count() > count ) {
1251                   result.clear();
1252                   stopped = true;
1253                 }
1254                 else if ( !strict && result.count() == count )
1255                   stopped = true;
1256               }
1257             }
1258             else if ( strict ) {
1259               result.clear();
1260               stopped = true;
1261             }
1262           }
1263           else {
1264             // local selection
1265             for ( int i = 1; i <= nbSubShapes && !stopped; i++ ) {
1266               int idx = subShapes( i );
1267               GEOM::GeomObjPtr subShape = findObjectInFather( object.get(), idx );
1268               if ( !subShape ) {
1269                 // sub-shape is not yet published in the study
1270                 GEOM::ShapesOpPtr shapesOp = getGeomEngine()->GetIShapesOperations( getStudyId() );
1271                 subShape.take( shapesOp->GetSubShape( object.get(), idx ) ); // take ownership!
1272               }
1273               if ( typeInList( (TopAbs_ShapeEnum)(subShape->GetShapeType()), types ) ) {
1274                 result << subShape;
1275                 if ( count > 0 ) {
1276                   if ( strict && result.count() > count ) {
1277                     result.clear();
1278                     stopped = true;
1279                   }
1280                   else if ( !strict && result.count() == count )
1281                     stopped = true;
1282                 }
1283               }
1284               else if ( strict ) {
1285                 result.clear();
1286                 stopped = true;
1287               }
1288             }
1289           }
1290         }
1291       }
1292     }
1293   }
1294   return result;
1295 }