Salome HOME
0020632: EDF 1173 GEOM : Extrusion with multiple selection
[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   try {
805     if ( ( !publish && !useTransaction ) || openCommand() ) {
806       SUIT_OverrideCursor wc;
807       SUIT_Session::session()->activeApplication()->putInfo( "" );
808       ObjectList objects;
809       if ( !execute( objects ) || !getOperation()->IsDone() ) {
810         wc.suspend();
811         abortCommand();
812         showError();
813       }
814       else {
815         addSubshapesToStudy(); // add Subshapes if local selection
816         const int nbObjs = objects.size();
817         int aNumber = 1;
818         for ( ObjectList::iterator it = objects.begin(); it != objects.end(); ++it ) {
819           GEOM::GEOM_Object_var obj=*it;
820           if ( publish ) {
821             QString aName = getNewObjectName();
822             if ( nbObjs > 1 ) {
823               if (aName.isEmpty())
824                 aName = getPrefix(obj);
825               if (nbObjs <= 30) {
826                 // Try to find a unique name
827                 aName = GEOMBase::GetDefaultName(aName, extractPrefix());
828               } else {
829                 // Don't check name uniqueness in case of numerous objects
830                 aName = aName + "_" + QString::number(aNumber++);
831               }
832             } else {
833               // PAL6521: use a prefix, if some dialog box doesn't reimplement getNewObjectName()
834               if ( aName.isEmpty() )
835                 aName = GEOMBase::GetDefaultName( getPrefix( obj ) );
836             }
837             addInStudy( obj, aName.toLatin1().constData() );
838             // updateView=false
839             display( obj, false );
840 #ifdef WITHGENERICOBJ
841             // obj has been published in study. Its refcount has been incremented.
842             // It is safe to decrement its refcount
843             // so that it will be destroyed when the entry in study will be removed
844             obj->Destroy();
845 #endif
846           }
847           else {
848             // asv : fix of PAL6454. If publish==false, then the original shape
849             // was modified, and need to be re-cached in GEOM_Client before redisplay
850             clearShapeBuffer( obj );
851             // withChildren=true, updateView=false
852             redisplay( obj, true, false );
853           }
854         }
855
856         if ( nbObjs ) {
857           commitCommand();
858           updateObjBrowser();
859           SUIT_Session::session()->activeApplication()->putInfo( QObject::tr("GEOM_PRP_DONE") );
860         }
861         else
862           abortCommand();
863       }
864     }
865   }
866   catch( const SALOME::SALOME_Exception& e ) {
867     SalomeApp_Tools::QtCatchCorbaException( e );
868     abortCommand();
869   }
870
871   updateViewer();
872
873   return true;
874 }
875
876
877 //================================================================
878 // Function : showError
879 // Purpose  : Shows a message box with infromation about an error taken from getOperation()->GetErrorCode()
880 //================================================================
881 void GEOMBase_Helper::showError()
882 {
883   QString msg;
884   if ( !getOperation()->_is_nil() )
885     msg = QObject::tr( getOperation()->GetErrorCode() );
886
887   if ( msg.isEmpty() )
888     msg = QObject::tr( "GEOM_PRP_ABORT" );
889
890   SUIT_MessageBox::critical( SUIT_Session::session()->activeApplication()->desktop(),
891                              QObject::tr( "GEOM_ERROR_STATUS" ),
892                              msg,
893                              QObject::tr( "BUT_OK" ) );
894 }
895
896 //================================================================
897 // Function : showError
898 // Purpose  : Shows a error message followed by <msg>
899 //================================================================
900 void GEOMBase_Helper::showError( const QString& msg )
901 {
902   QString str( QObject::tr( "GEOM_INCORRECT_INPUT" ) );
903   if ( !msg.isEmpty() )
904     str += "\n" + msg;
905   SUIT_MessageBox::critical(SUIT_Session::session()->activeApplication()->desktop(), QObject::tr( "GEOM_ERROR" ), str, QObject::tr( "BUT_OK" ) );
906 }
907
908 //////////////////////////////////////////////////////////////////
909 // Virtual methods to be redefined in dialogs
910 //////////////////////////////////////////////////////////////////
911
912 //================================================================
913 // Function : createOperation
914 // Purpose  : Redefine this method to return proper IOperation reference
915 //================================================================
916 GEOM::GEOM_IOperations_ptr GEOMBase_Helper::createOperation()
917 {
918   GEOM::GEOM_IOperations_var aNilOp;
919   return aNilOp._retn();
920 }
921
922 //================================================================
923 // Function : isValid
924 // Purpose  : Called by onAccept(). Redefine this method to check validity of user input in dialog boxes.
925 //================================================================
926 bool GEOMBase_Helper::isValid( QString& )
927 {
928   return true;
929 }
930
931 //================================================================
932 // Function : execute
933 // Purpose  : This method is called by onAccept().
934 //            It should perform the required operation and put all new or modified objects into
935 //            <objects> argument.Should return <false> if some error occurs during its execution.
936 //================================================================
937 bool GEOMBase_Helper::execute( ObjectList& objects )
938 {
939   return false;
940 }
941
942 //================================================================
943 // Function : getFather
944 // Purpose  : This method is called by addInStudy(). It should return a father object
945 //            for <theObj> or a nil reference if <theObj> should be published
946 //            as a top-level object.
947 //================================================================
948 GEOM::GEOM_Object_ptr GEOMBase_Helper::getFather( GEOM::GEOM_Object_ptr theObj )
949 {
950   return GEOM::GEOM_Object::_nil();
951 }
952
953 //================================================================
954 // Function : getNewObjectName
955 // Purpose  : Redefine this method to return proper name for a new object
956 //================================================================
957 QString GEOMBase_Helper::getNewObjectName() const
958 {
959   return QString::null;
960 }
961
962 //================================================================
963 // Function : extractPrefix
964 // Purpose  : Redefine this method to return \c true if necessary 
965 //            to extract prefix when generating new name for the
966 //            object(s) being created
967 //================================================================
968 bool GEOMBase_Helper::extractPrefix() const
969 {
970   return false;
971 }
972
973 //================================================================
974 // Function : getPrefix
975 // Purpose  : Get prefix for name of created object
976 //================================================================
977 QString GEOMBase_Helper::getPrefix( GEOM::GEOM_Object_ptr theObj ) const
978 {
979   if ( !myPrefix.isEmpty() || theObj->_is_nil() )
980     return myPrefix;
981
982   //TopoDS_Shape aShape;
983   //if ( !GEOMBase::GetShape( theObj, aShape ) )
984   //  return "";
985   //
986   //long aType = aShape.ShapeType();
987   GEOM::shape_type aType = theObj->GetShapeType();
988
989   switch ( aType )
990   {
991     case GEOM::VERTEX   : return QObject::tr( "GEOM_VERTEX" );
992     case GEOM::EDGE     : return QObject::tr( "GEOM_EDGE" );
993     case GEOM::WIRE     : return QObject::tr( "GEOM_WIRE" );
994     case GEOM::FACE     : return QObject::tr( "GEOM_FACE" );
995     case GEOM::SHELL    : return QObject::tr( "GEOM_SHELL" );
996     case GEOM::SOLID    : return QObject::tr( "GEOM_SOLID" );
997     case GEOM::COMPSOLID: return QObject::tr( "GEOM_COMPOUNDSOLID" );
998     case GEOM::COMPOUND : return QObject::tr( "GEOM_COMPOUND" );
999     default : return "";
1000   }
1001 }
1002
1003 //================================================================
1004 // Function : getDesktop
1005 // Purpose  : Returns myDesktop field. Initialized in constructor,
1006 //            usually as dynamic_cast<SUIT_Desktop*>(parentWidget())
1007 //================================================================
1008 SUIT_Desktop* GEOMBase_Helper::getDesktop() const
1009 {
1010   return myDesktop;
1011 }
1012
1013 //================================================================
1014 // Function : selectObjects
1015 // Purpose  : Selects list of objects 
1016 //================================================================
1017 bool GEOMBase_Helper::selectObjects( ObjectList& objects )
1018 {
1019   SUIT_DataOwnerPtrList aList;
1020   ObjectList::iterator anIter;
1021   for ( anIter = objects.begin(); anIter != objects.end(); ++anIter )
1022   {
1023     std::string entry = getEntry( *anIter );
1024     QString aEntry( entry.c_str() );
1025     LightApp_DataOwner* anOwher = new LightApp_DataOwner( aEntry );
1026     aList.append( anOwher );
1027   }
1028   
1029   SUIT_Session* session = SUIT_Session::session();
1030   SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( session->activeApplication() );
1031   if ( !app )
1032     return false;
1033
1034   LightApp_SelectionMgr* aMgr = app->selectionMgr();
1035   if ( !aMgr )
1036     return false;
1037   
1038   aMgr->setSelected( aList, false );
1039   
1040   return true;
1041 }
1042   
1043 //================================================================
1044 // Function : findObjectInFather
1045 // Purpose  : It should return an object if its founded in study or
1046 //            return Null object if the object is not founded
1047 //================================================================
1048 GEOM::GEOM_Object_ptr GEOMBase_Helper::findObjectInFather (GEOM::GEOM_Object_ptr theFather,
1049                                                            const QString& theName)
1050 {
1051   SalomeApp_Application* app =
1052     dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
1053   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
1054   _PTR(Study) aDStudy = appStudy->studyDS();
1055   std::string IOR = GEOMBase::GetIORFromObject( theFather );
1056   _PTR(SObject) SObj ( aDStudy->FindObjectIOR( IOR ) );
1057
1058   bool inStudy = false;
1059   GEOM::GEOM_Object_var aReturnObject;
1060   for (_PTR(ChildIterator) iit (aDStudy->NewChildIterator( SObj )); iit->More() && !inStudy; iit->Next()) {
1061     _PTR(SObject) child (iit->Value());
1062     QString aChildName = child->GetName().c_str();
1063     if (aChildName == theName) {
1064       inStudy = true;
1065       CORBA::Object_var corbaObj = GeometryGUI::ClientSObjectToObject(iit->Value());
1066       aReturnObject = GEOM::GEOM_Object::_narrow( corbaObj );
1067     }
1068   }
1069   if (inStudy)
1070     return aReturnObject._retn();
1071
1072   return GEOM::GEOM_Object::_nil();
1073 }
1074   
1075 //================================================================
1076 // Function : addSubshapesToStudy
1077 // Purpose  : Virtual method to add subshapes if needs
1078 //================================================================  
1079 void GEOMBase_Helper::addSubshapesToStudy()
1080 {
1081   //Impemented in Dialogs, called from Accept method
1082 }
1083
1084 //================================================================
1085 // Function : addSubshapesToFather
1086 // Purpose  : Method to add Father Subshapes to Study if it`s not exist
1087 //================================================================  
1088 void GEOMBase_Helper::addSubshapesToFather( QMap<QString, GEOM::GEOM_Object_var>& theMap )
1089 {
1090   //GetStudyDS
1091   SalomeApp_Application* app =
1092     dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
1093   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
1094   _PTR(Study) aDStudy = appStudy->studyDS();
1095
1096   GEOM::GEOM_IGroupOperations_var anOp = getGeomEngine()->GetIGroupOperations( getStudyId() );
1097  
1098   for( QMap<QString, GEOM::GEOM_Object_var>::Iterator it = theMap.begin(); it != theMap.end(); it++ ) {
1099     if ( !anOp->_is_nil() ) {
1100       GEOM::GEOM_Object_var aFatherObj = anOp->GetMainShape( it.value() );
1101       if ( !aFatherObj->_is_nil() ) {
1102         std::string aFatherEntry = getEntry( aFatherObj );      
1103         if ( aFatherEntry != "") { // additional checking that object is valid 0020598 EDF 1191
1104           GEOM::GEOM_Object_var aFindedObject = findObjectInFather(aFatherObj, it.key().toLatin1().data() );
1105           //Add Object to study if its not exist
1106           if ( aFindedObject == GEOM::GEOM_Object::_nil() )
1107             GeometryGUI::GetGeomGen()->AddInStudy(GeometryGUI::ClientStudyToStudy(aDStudy),
1108                                                   it.value(), it.key().toLatin1().data(), aFatherObj );
1109         }
1110       }
1111     } else {
1112       //cout << " anOperations is NULL! " << endl;
1113     }
1114   }
1115 }
1116
1117