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