Salome HOME
f774f30001ea31ff198cfb2d80409856f6de2818
[modules/geom.git] / src / GEOMToolsGUI / GEOMToolsGUI.cxx
1 // Copyright (C) 2007-2013  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_Tools.cxx
25 // Author : Damien COQUERET, Open CASCADE S.A.S.
26
27 #include "GEOMToolsGUI.h"
28 #include "GEOMToolsGUI_DeleteDlg.h"
29
30 #include <GeometryGUI.h>
31 #include "GeometryGUI_Operations.h"
32 #include <GEOMBase.h>
33 #include <GEOM_Operation.h>
34 #include <GEOM_Displayer.h>
35
36 #include <SUIT_Session.h>
37 #include <SUIT_OverrideCursor.h>
38 #include <SUIT_MessageBox.h>
39 #include <SUIT_Tools.h>
40 #include <SUIT_FileDlg.h>
41 #include <SUIT_Desktop.h>
42 #include <SUIT_ViewModel.h>
43 #include <SUIT_ViewManager.h>
44
45 #include <SalomeApp_Application.h>
46 #include <SalomeApp_Study.h>
47 #include <LightApp_SelectionMgr.h>
48 #include <GEOMImpl_Types.hxx>
49
50 #include <SALOME_ListIO.hxx>
51 #include <SALOME_ListIteratorOfListIO.hxx>
52 #include <SALOME_Prs.h>
53
54 // QT Includes
55 #include <QApplication>
56 #include <QMap>
57 #include <QRegExp>
58
59 // OCCT Includes
60 #include <TCollection_AsciiString.hxx>
61
62 typedef QMap<QString, QString> FilterMap;
63 static QString lastUsedFilter;
64
65 //=======================================================================
66 // function : getFileName
67 // purpose  : Selection of a file name for Import/Export. Returns also
68 //            the selected file type code through <filter> argument.
69 //=======================================================================
70 static QString getFileName( QWidget*           parent,
71                             const QString&     initial,
72                             const FilterMap&   filterMap,
73                             const QStringList& filters,
74                             const QString&     caption,
75                             bool               open,
76                             QString&           format,
77                             bool               showCurrentDirInitially = false )
78 {
79   //QStringList filters;
80   QString aBrepFilter;
81   for (FilterMap::const_iterator it = filterMap.begin(); it != filterMap.end(); ++it) {
82     //filters.push_back( it.key() );
83     if (it.key().contains( "BREP", Qt::CaseInsensitive ))
84       aBrepFilter = it.key();
85   }
86
87   SUIT_FileDlg* fd = new SUIT_FileDlg( parent, open, true, true );
88   if ( !caption.isEmpty() )
89     fd->setWindowTitle( caption );
90
91   if ( !initial.isEmpty() )
92     fd->selectFile( initial );
93
94   if ( showCurrentDirInitially && SUIT_FileDlg::getLastVisitedPath().isEmpty() )
95     fd->setDirectory( QDir::currentPath() );
96
97   fd->setFilters( filters );
98
99   if ( !lastUsedFilter.isEmpty() && filterMap.contains( lastUsedFilter ) ) {
100     fd->selectFilter( lastUsedFilter );
101   }
102   else if ( !aBrepFilter.isEmpty() ) {
103     fd->selectFilter( aBrepFilter );
104   }
105
106   QString filename;
107   if ( fd->exec() == QDialog::Accepted ) {
108     filename = fd->selectedFile();
109     format = filterMap[fd->selectedFilter()];
110     lastUsedFilter = fd->selectedFilter();
111   }
112
113   delete fd;
114   qApp->processEvents();
115   return filename;
116 }
117
118 //=======================================================================
119 // function : getFileNames
120 // purpose  : Select list of files for Import operation. Returns also
121 //            the selected file type code through <format> argument.
122 //=======================================================================
123 static QStringList getFileNames( QWidget*           parent,
124                                  const QString&     initial,
125                                  const FilterMap&   filterMap,
126                                  const QString&     caption,
127                                  QString&           format,
128                                  bool               showCurrentDirInitially = false)
129 {
130   QString aBrepFilter;
131   QStringList allFilters;
132   QStringList filters;
133   QRegExp re( "\\((.*)\\)" );
134   re.setMinimal( true );
135   for ( FilterMap::const_iterator it = filterMap.begin(); it != filterMap.end(); ++it ) {
136     if ( it.value().contains( "BREP", Qt::CaseInsensitive ) && aBrepFilter.isEmpty() )
137       aBrepFilter = it.key();
138     filters.append( it.key() );
139     int pos = 0;
140     while ( re.indexIn( it.key(), pos ) >= 0 ) {
141       QString f = re.cap(1);
142       pos = re.pos() + f.length() + 2;
143       allFilters.append( f.simplified() );
144     }
145   }
146   filters.append( QObject::tr( "GEOM_ALL_IMPORT_FILES" ).arg( allFilters.join( " " ) ) );
147
148   SUIT_FileDlg fd( parent, true, true, true );
149   fd.setFileMode( SUIT_FileDlg::ExistingFiles );
150   if ( !caption.isEmpty() )
151     fd.setWindowTitle( caption );
152   if ( !initial.isEmpty() )
153     fd.selectFile( initial );
154
155   if ( showCurrentDirInitially && SUIT_FileDlg::getLastVisitedPath().isEmpty() )
156     fd.setDirectory( QDir::currentPath() );
157
158   fd.setFilters( filters );
159
160   if ( !lastUsedFilter.isEmpty() && filterMap.contains( lastUsedFilter ) )
161     fd.selectFilter( lastUsedFilter );
162   else if ( !aBrepFilter.isEmpty() )
163     fd.selectFilter( aBrepFilter );
164
165   QStringList filenames;
166   if ( fd.exec() ) {
167     filenames = fd.selectedFiles();
168     format = filterMap.contains( fd.selectedFilter() ) ? filterMap[ fd.selectedFilter() ] : QString();
169     lastUsedFilter = fd.selectedFilter();
170   }
171   qApp->processEvents();
172   return filenames;
173 }
174
175 //=======================================================================
176 // function : getParentComponent
177 // purpose  : Get object's parent component entry
178 //=======================================================================
179 static QString getParentComponent( _PTR( SObject ) obj )
180 {
181   if ( obj ) {
182     _PTR(SComponent) comp = obj->GetFatherComponent();
183     if ( comp )
184       return QString( comp->GetID().c_str() );
185   }
186   return QString();
187 }
188
189 //=====================================================================================
190 // function : inUse
191 // purpose  : check if the object(s) passed as the the second arguments are used
192 //            by the other objects in the study
193 //=====================================================================================
194 static bool inUse( _PTR(Study) study, const QString& component, const QMap<QString,QString>& objects )
195 {
196   _PTR(SObject) comp = study->FindObjectID( component.toLatin1().data() );
197   if ( !comp )
198     return false;
199
200   // collect all GEOM objects being deleted
201   QMap<QString, GEOM::GEOM_BaseObject_var> gobjects;
202   QMap<QString, QString>::ConstIterator oit;
203   std::list<_PTR(SObject)> aSelectedSO;
204   for ( oit = objects.begin(); oit != objects.end(); ++oit ) {
205     _PTR(SObject) so = study->FindObjectID( oit.key().toLatin1().data() );
206     if ( !so )
207       continue;
208     aSelectedSO.push_back(so);
209     CORBA::Object_var corbaObj_rem = GeometryGUI::ClientSObjectToObject( so );
210     GEOM::GEOM_BaseObject_var geomObj_rem = GEOM::GEOM_BaseObject::_narrow( corbaObj_rem );
211     if( CORBA::is_nil( geomObj_rem ) )
212       continue;
213     gobjects.insert( oit.key(), geomObj_rem );
214   }
215
216   // Search References with other Modules
217   std::list< _PTR(SObject) >::iterator itSO = aSelectedSO.begin();
218   for ( ; itSO != aSelectedSO.end(); ++itSO ) {
219     std::vector<_PTR(SObject)> aReferences = study->FindDependances( *itSO  );
220     int aRefLength = aReferences.size();
221     if (aRefLength) {
222       for (int i = 0; i < aRefLength; i++) {
223         _PTR(SObject) firstSO( aReferences[i] );
224         _PTR(SComponent) aComponent = firstSO->GetFatherComponent();
225         QString type = aComponent->ComponentDataType().c_str();
226         if ( type == "SMESH" )
227           return true;
228       }
229     }
230   }
231
232   // browse through all GEOM data tree
233   _PTR(ChildIterator) it ( study->NewChildIterator( comp ) );
234   for ( it->InitEx( true ); it->More(); it->Next() ) {
235     _PTR(SObject) child( it->Value() );
236     CORBA::Object_var corbaObj = GeometryGUI::ClientSObjectToObject( child );
237     GEOM::GEOM_Object_var geomObj = GEOM::GEOM_Object::_narrow( corbaObj );
238     if( CORBA::is_nil( geomObj ) )
239       continue;
240
241     GEOM::ListOfGBO_var list = geomObj->GetDependency();
242     if( list->length() == 0 )
243       continue;
244
245     for( int i = 0; i < list->length(); i++ ) {
246       bool depends = false;
247       bool deleted = false;
248       QMap<QString, GEOM::GEOM_BaseObject_var>::Iterator git;
249       for ( git = gobjects.begin(); git != gobjects.end() && ( !depends || !deleted ); ++git ) {
250         depends = depends || list[i]->_is_equivalent( *git );
251         deleted = deleted || git.key() == child->GetID().c_str() ;//geomObj->_is_equivalent( *git );
252       }
253       if ( depends && !deleted )
254         return true;
255     }
256   }
257   return false;
258 }
259
260 //=======================================================================
261 // function : getGeomChildrenAndFolders
262 // purpose  : Get direct (1-level) GEOM objects under each folder, sub-folder, etc. and these folders itself
263 //=======================================================================
264 static void getGeomChildrenAndFolders( _PTR(SObject) theSO, 
265                                        QMap<QString,QString>& geomObjList, 
266                                        QMap<QString,QString>& folderList ) {
267   if ( !theSO ) return;
268   _PTR(Study) aStudy = theSO->GetStudy();
269   if ( !aStudy ) return;
270   _PTR(UseCaseBuilder) aUseCaseBuilder = aStudy->GetUseCaseBuilder();
271
272   bool isFolder = false;
273   _PTR(GenericAttribute) anAttr;
274   if ( theSO->FindAttribute(anAttr, "AttributeLocalID") ) {
275     _PTR(AttributeLocalID) aLocalID( anAttr );
276     isFolder = aLocalID->Value() == 999;
277   }
278   QString anEntry = theSO->GetID().c_str();
279   QString aName = theSO->GetName().c_str();
280   if ( isFolder ) {
281     folderList.insert( anEntry, aName );
282     _PTR(UseCaseIterator) ucit ( aUseCaseBuilder->GetUseCaseIterator( theSO ) );
283     for ( ucit->Init( false ); ucit->More(); ucit->Next() ) {
284       getGeomChildrenAndFolders( ucit->Value(), geomObjList, folderList );
285     }
286   } else {
287     geomObjList.insert( anEntry, aName );
288   }
289 }
290
291 //=======================================================================
292 // function : GEOMToolsGUI()
293 // purpose  : Constructor
294 //=======================================================================
295 GEOMToolsGUI::GEOMToolsGUI( GeometryGUI* parent )
296 : GEOMGUI( parent )
297 {
298 }
299
300 //=======================================================================
301 // function : ~GEOMToolsGUI()
302 // purpose  : Destructor
303 //=======================================================================
304 GEOMToolsGUI::~GEOMToolsGUI()
305 {
306 }
307
308 //=======================================================================
309 // function : OnGUIEvent()
310 // purpose  :
311 //=======================================================================
312 bool GEOMToolsGUI::OnGUIEvent(int theCommandID, SUIT_Desktop* parent)
313 {
314   getGeometryGUI()->EmitSignalDeactivateDialog();
315
316   switch ( theCommandID ) {
317   case GEOMOp::OpDelete:         // EDIT - DELETE
318     OnEditDelete();
319     break;
320   case GEOMOp::OpImport:         // FILE - IMPORT
321     Import();
322     break;
323   case GEOMOp::OpExport:         // FILE - EXPORT
324     Export();
325     break;
326   case GEOMOp::OpCheckGeom:      // TOOLS - CHECK GEOMETRY
327     OnCheckGeometry();
328     break;
329   case GEOMOp::OpSelectVertex:   // POPUP - SELECT ONLY - VERTEX
330     OnSelectOnly( GEOM_POINT );
331     break;
332   case GEOMOp::OpSelectEdge:     // POPUP - SELECT ONLY - EDGE
333     OnSelectOnly( GEOM_EDGE );
334     break;
335   case GEOMOp::OpSelectWire:     // POPUP - SELECT ONLY - WIRE
336     OnSelectOnly( GEOM_WIRE );
337     break;
338   case GEOMOp::OpSelectFace:     // POPUP - SELECT ONLY - FACE
339     OnSelectOnly( GEOM_FACE );
340     break;
341   case GEOMOp::OpSelectShell:    // POPUP - SELECT ONLY - SHELL
342     OnSelectOnly( GEOM_SHELL );
343     break;
344   case GEOMOp::OpSelectSolid:    // POPUP - SELECT ONLY - SOLID
345     OnSelectOnly( GEOM_SOLID );
346     break;
347   case GEOMOp::OpSelectCompound: // POPUP - SELECT ONLY - COMPOUND
348     OnSelectOnly( GEOM_COMPOUND );
349     break;
350   case GEOMOp::OpSelectAll:      // POPUP - SELECT ONLY - SELECT ALL
351     OnSelectOnly( GEOM_ALLOBJECTS );
352     break;
353   case GEOMOp::OpDeflection:     // POPUP - DEFLECTION ANGLE
354     OnDeflection();
355     break;
356   case GEOMOp::OpColor:          // POPUP - COLOR
357     OnColor();
358     break;
359   case GEOMOp::OpSetTexture:     // POPUP - TEXTURE
360     OnTexture();
361     break;
362   case GEOMOp::OpTransparency:   // POPUP - TRANSPARENCY
363     OnTransparency();
364     break;
365   case GEOMOp::OpIncrTransparency: // SHORTCUT   - INCREASE TRANSPARENCY
366     OnChangeTransparency( true );
367     break;
368   case GEOMOp::OpDecrTransparency: // SHORTCUT   - DECREASE TRANSPARENCY
369     OnChangeTransparency( false );
370     break;
371   case GEOMOp::OpIsos:           // POPUP - ISOS
372     OnNbIsos();
373     break;
374   case GEOMOp::OpIncrNbIsos:     // SHORTCUT   - INCREASE NB ISOLINES
375     OnNbIsos( INCR );
376     break;
377   case GEOMOp::OpDecrNbIsos:     // SHORTCUT   - DECREASE NB ISOLINES
378     OnNbIsos( DECR );
379     break;
380   case GEOMOp::OpMaterialProperties: // POPUP - MATERIAL PROPERTIES
381     OnMaterialProperties();
382     break;
383   case GEOMOp::OpPredefMaterCustom:  // POPUP  - MATERIAL PROPERTIES - CUSTOM...
384     OnMaterialProperties();
385     break;
386   case GEOMOp::OpMaterialsLibrary:    // POPUP MENU - MATERIAL PROPERTIES
387     OnMaterialsLibrary();
388     break;
389   case GEOMOp::OpAutoColor:      // POPUP - AUTO COLOR
390     OnAutoColor();
391     break;
392   case GEOMOp::OpNoAutoColor:    // POPUP - DISABLE AUTO COLOR
393     OnDisableAutoColor();
394     break;
395   case GEOMOp::OpDiscloseChildren:   // POPUP - SHOW CHILDREN
396   case GEOMOp::OpConcealChildren:   // POPUP - HIDE CHILDREN
397     OnDiscloseConcealChildren( theCommandID == GEOMOp::OpDiscloseChildren );
398     break;
399   case GEOMOp::OpPointMarker:    // POPUP - POINT MARKER
400     OnPointMarker();
401     break;
402   case GEOMOp::OpUnpublishObject:// POPUP - UNPUBLISH
403     OnUnpublishObject();
404     break;
405   case GEOMOp::OpPublishObject:// GEOM ROOT OBJECT - POPUP - PUBLISH
406     OnPublishObject();
407     break;
408   case GEOMOp::OpEdgeWidth:
409     OnEdgeWidth();
410     break;
411   case GEOMOp::OpIsosWidth:
412     OnIsosWidth();
413     break;
414   case GEOMOp::OpBringToFront:
415     OnBringToFront();
416     break;
417   case GEOMOp::OpClsBringToFront:
418     OnClsBringToFront();
419      break;
420   case GEOMOp::OpCreateFolder:
421     OnCreateFolder();
422      break;
423   case GEOMOp::OpSortChildren:
424     OnSortChildren();
425      break;
426   default:
427     SUIT_Session::session()->activeApplication()->putInfo(tr("GEOM_PRP_COMMAND").arg(theCommandID));
428     break;
429   }
430   return true;
431 }
432
433 //=======================================================================
434 // function : OnGUIEvent()
435 // purpose  :
436 //=======================================================================
437 bool GEOMToolsGUI::OnGUIEvent(int theCommandID, SUIT_Desktop* parent, const QVariant& theParam )
438 {
439   getGeometryGUI()->EmitSignalDeactivateDialog();
440
441   switch ( theCommandID ) {
442   case GEOMOp::OpPredefMaterial:         // POPUP MENU - MATERIAL PROPERTIES - <SOME MATERIAL>
443     OnSetMaterial( theParam );
444     break;
445   default:
446     SUIT_Session::session()->activeApplication()->putInfo(tr("GEOM_PRP_COMMAND").arg(theCommandID));
447     break;
448   }
449   return true;
450 }
451
452 //===============================================================================
453 // function : OnEditDelete()
454 // purpose  :
455 //===============================================================================
456 void GEOMToolsGUI::OnEditDelete()
457 {
458   SALOME_ListIO selected;
459   SalomeApp_Application* app =
460     dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
461   if ( !app )
462     return;
463
464   LightApp_SelectionMgr* aSelMgr = app->selectionMgr();
465   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
466   if ( !aSelMgr || !appStudy )
467     return;
468
469   // get selection
470   aSelMgr->selectedObjects( selected, "ObjectBrowser", false );
471   if ( selected.IsEmpty() )
472     return;
473
474   _PTR(Study) aStudy = appStudy->studyDS();
475   _PTR(UseCaseBuilder) aUseCaseBuilder = aStudy->GetUseCaseBuilder();
476
477   // check if study is locked
478   if ( _PTR(AttributeStudyProperties)( aStudy->GetProperties() )->IsLocked() ) {
479     SUIT_MessageBox::warning( app->desktop(),
480                               tr("WRN_WARNING"),
481                               tr("WRN_STUDY_LOCKED") );
482     return; // study is locked
483   }
484
485   // get GEOM component
486   CORBA::String_var geomIOR = app->orb()->object_to_string( GeometryGUI::GetGeomGen() );
487   QString geomComp = getParentComponent( aStudy->FindObjectIOR( geomIOR.in() ) );
488
489   // check each selected object: if belongs to GEOM, if not reference...
490   QMap<QString,QString> toBeDeleted;
491   QMap<QString,QString> allDeleted;
492   QMap<QString,QString> toBeDelFolders;
493   bool isComponentSelected = false;
494
495   for ( SALOME_ListIteratorOfListIO It( selected ); It.More(); It.Next() ) {
496     Handle(SALOME_InteractiveObject) anIObject = It.Value();
497     if ( !anIObject->hasEntry() )
498       continue; // invalid object
499     // ...
500     QString entry = anIObject->getEntry();
501     _PTR(SObject) obj = aStudy->FindObjectID( entry.toLatin1().data() );
502     // check parent component
503     QString parentComp = getParentComponent( obj );
504     if ( parentComp != geomComp )  {
505       SUIT_MessageBox::warning( app->desktop(),
506                                 QObject::tr("ERR_ERROR"),
507                                 QObject::tr("NON_GEOM_OBJECTS_SELECTED").arg( getGeometryGUI()->moduleName() ) );
508       return; // not GEOM object selected
509     }
510
511     ///////////////////////////////////////////////////////
512     // if GEOM component is selected, so skip other checks
513     if ( isComponentSelected ) continue;
514     ///////////////////////////////////////////////////////
515
516     // check if object is reference
517     _PTR(SObject) refobj;
518     if ( obj && obj->ReferencedObject( refobj ) ) {
519       // get the main object by reference IPAL 21354
520       obj = refobj;
521       entry = obj->GetID().c_str();
522     }
523     // ...
524     QString aName = obj->GetName().c_str();
525     if ( entry == geomComp ) {
526       // GEOM component is selected, skip other checks
527       isComponentSelected = true;
528       continue;
529     }
530     // all sub-objects of folder have to be deleted
531     getGeomChildrenAndFolders( obj, toBeDeleted, toBeDelFolders );
532     allDeleted.insert( entry, aName ); // skip GEOM component
533     // browse through all children recursively
534     _PTR(UseCaseIterator) it ( aUseCaseBuilder->GetUseCaseIterator( obj ) );
535     for ( it->Init( true ); it->More(); it->Next() ) {
536       _PTR(SObject) child( it->Value() );
537       if ( child && child->ReferencedObject( refobj ) )
538         continue; // skip references
539       aName = child->GetName().c_str();
540       if ( !aName.isEmpty() )
541         allDeleted.insert( child->GetID().c_str(), aName );
542     }
543   }
544
545   // is there is anything to delete?
546   if ( !isComponentSelected && allDeleted.count() <= 0 )
547     return; // nothing to delete
548
549   // show confirmation dialog box
550   GEOMToolsGUI_DeleteDlg dlg( app->desktop(), allDeleted, isComponentSelected );
551   if ( !dlg.exec() )
552     return; // operation is cancelled by user
553
554   // get currently opened views
555   QList<SALOME_View*> views;
556   SALOME_View* view;
557   ViewManagerList vmans = app->viewManagers();
558   SUIT_ViewManager* vman;
559   foreach ( vman, vmans ) {
560     SUIT_ViewModel* vmod = vman->getViewModel();
561     view = dynamic_cast<SALOME_View*> ( vmod ); // must work for OCC and VTK views
562     if ( view )
563       views.append( view );
564   }
565
566   _PTR(StudyBuilder) aStudyBuilder (aStudy->NewBuilder());
567   GEOM_Displayer* disp = new GEOM_Displayer( appStudy );
568
569   if ( isComponentSelected ) {
570     // GEOM component is selected: delete all objects recursively
571     _PTR(SObject) comp = aStudy->FindObjectID( geomComp.toLatin1().data() );
572     if ( !comp )
573       return;
574     _PTR(ChildIterator) it ( aStudy->NewChildIterator( comp ) );
575     // remove top-level objects only
576     for ( it->InitEx( false ); it->More(); it->Next() ) {
577       _PTR(SObject) child( it->Value() );
578       // remove object from GEOM engine
579       removeObjectWithChildren( child, aStudy, views, disp );
580       // remove object from study
581       aStudyBuilder->RemoveObjectWithChildren( child );
582       // remove object from use case tree
583       aUseCaseBuilder->Remove( child );
584     }
585   }
586   else {
587     // GEOM component is not selected: check if selected objects are in use
588     if ( inUse( aStudy, geomComp, allDeleted ) && 
589          SUIT_MessageBox::question( app->desktop(),
590                                     QObject::tr("WRN_WARNING"),
591                                     QObject::tr("DEP_OBJECT"),
592                                     SUIT_MessageBox::Yes | SUIT_MessageBox::No,
593                                     SUIT_MessageBox::No ) != SUIT_MessageBox::Yes ) {
594       return; // object(s) in use
595     }
596     // ... and then delete all objects
597     QMap<QString, QString>::Iterator it;
598     for ( it = toBeDeleted.begin(); it != toBeDeleted.end(); ++it ) {
599       _PTR(SObject) obj ( aStudy->FindObjectID( it.key().toLatin1().data() ) );
600       // remove object from GEOM engine
601       removeObjectWithChildren( obj, aStudy, views, disp );
602       // remove objects from study
603       aStudyBuilder->RemoveObjectWithChildren( obj );
604       // remove object from use case tree
605       aUseCaseBuilder->Remove( obj );
606     }
607     // ... and then delete all folders
608     for ( it = toBeDelFolders.begin(); it != toBeDelFolders.end(); ++it ) {
609       _PTR(SObject) obj ( aStudy->FindObjectID( it.key().toLatin1().data() ) );
610       // remove object from GEOM engine
611       removeObjectWithChildren( obj, aStudy, views, disp );
612       // remove objects from study
613       aStudyBuilder->RemoveObjectWithChildren( obj );
614       // remove object from use case tree
615       aUseCaseBuilder->Remove( obj );
616     }
617   }
618
619   selected.Clear();
620   aSelMgr->setSelectedObjects( selected );
621   getGeometryGUI()->updateObjBrowser();
622   app->updateActions(); //SRN: To update a Save button in the toolbar
623 }
624
625 //=====================================================================================
626 // function : Import
627 // purpose  : BRep, Iges, Step, ...
628 //=====================================================================================
629 bool GEOMToolsGUI::Import()
630 {
631   SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( getGeometryGUI()->getApp() );
632   if ( !app ) return false;
633
634   SalomeApp_Study* stud = dynamic_cast<SalomeApp_Study*> ( app->activeStudy() );
635   if ( !stud ) {
636     MESSAGE ( "FAILED to cast active study to SalomeApp_Study" );
637     return false;
638   }
639   _PTR(Study) aStudy = stud->studyDS();
640
641   // check if study is locked
642   bool aLocked = (_PTR(AttributeStudyProperties)(aStudy->GetProperties()))->IsLocked();
643   if ( aLocked ) {
644     SUIT_MessageBox::warning( app->desktop(),
645                               QObject::tr("WRN_WARNING"),
646                               QObject::tr("WRN_STUDY_LOCKED") );
647     return false;
648   }
649
650   // check if GEOM engine is available
651   GEOM::GEOM_Gen_var eng = GeometryGUI::GetGeomGen();
652   if ( CORBA::is_nil( eng ) ) {
653     SUIT_MessageBox::critical( app->desktop(),
654                                QObject::tr("WRN_WARNING"),
655                                QObject::tr( "GEOM Engine is not started" ) );
656     return false;
657   }
658
659   GEOM::GEOM_IInsertOperations_var aInsOp = eng->GetIInsertOperations( aStudy->StudyId() );
660   if ( aInsOp->_is_nil() )
661     return false;
662
663   // obtain a list of available import formats
664   FilterMap aMap;
665   GEOM::string_array_var aFormats, aPatterns;
666   aInsOp->ImportTranslators( aFormats, aPatterns );
667
668   for ( int i = 0, n = aFormats->length(); i < n; i++ )
669     aMap.insert( (char*)aPatterns[i], (char*)aFormats[i] );
670
671   // select files to be imported
672   QString fileType;
673   QStringList fileNames = getFileNames( app->desktop(), "", aMap,
674                                         tr( "GEOM_MEN_IMPORT" ), fileType, true );
675
676   // set Wait cursor
677   SUIT_OverrideCursor wc;
678
679   if ( fileNames.count() == 0 )
680     return false; // nothing selected, return
681
682   QStringList errors;
683
684   QList< GEOM::GEOM_Object_var > objsForDisplay;
685
686   QStringList anEntryList;
687
688   // iterate through all selected files
689
690   SUIT_MessageBox::StandardButton igesAnswer = SUIT_MessageBox::NoButton;
691   SUIT_MessageBox::StandardButton acisAnswer = SUIT_MessageBox::NoButton;
692
693   for ( int i = 0; i < fileNames.count(); i++ ) {
694     QString fileName = fileNames[i];
695
696     if ( fileName.isEmpty() )
697       continue;
698
699     QString aCurrentType;
700     if ( fileType.isEmpty() ) {
701       // file type is not defined, try to detect
702       QString ext = QFileInfo( fileName ).suffix().toUpper();
703       QRegExp re( "\\*\\.(\\w+)" );
704       for ( FilterMap::const_iterator it = aMap.begin();
705             it != aMap.end() && aCurrentType.isEmpty(); ++it ) {
706         int pos = 0;
707         while ( re.indexIn( it.key(), pos ) >= 0 ) {
708           QString f = re.cap(1).trimmed().toUpper();
709           if ( ext == f ) { aCurrentType = it.value(); break; }
710           pos = re.pos() + re.cap(1).length() + 2;
711         }
712       }
713     }
714     else {
715       aCurrentType = fileType;
716     }
717
718     if ( aCurrentType.isEmpty() ) {
719       errors.append( QString( "%1 : %2" ).arg( fileName ).arg( tr( "GEOM_UNSUPPORTED_TYPE" ) ) );
720       continue;
721     }
722
723     GEOM_Operation* anOp = new GEOM_Operation( app, aInsOp.in() );
724     try {
725       app->putInfo( tr( "GEOM_PRP_LOADING" ).arg( SUIT_Tools::file( fileName, /*withExten=*/true ) ) );
726       anOp->start();
727
728       CORBA::String_var fileN = fileName.toLatin1().constData();
729       CORBA::String_var fileT = aCurrentType.toLatin1().constData();
730
731       // jfa 21.08.2012 for mantis issue 21511 (STEP file units)
732       CORBA::String_var aUnits = aInsOp->ReadValue(fileN, fileT, "LEN_UNITS");
733       QString aUnitsStr (aUnits.in());
734       bool needConvert = true;
735       if (aUnitsStr.isEmpty() || aUnitsStr == "M" || aUnitsStr.toLower() == "metre")
736         needConvert = false;
737
738       if (needConvert) {
739         if (igesAnswer == SUIT_MessageBox::NoToAll) {
740           // converting for all files is already approved
741           fileT = (aCurrentType + "_SCALE").toLatin1().constData();
742         }
743         else if (igesAnswer != SUIT_MessageBox::YesToAll) {
744           SUIT_MessageBox::StandardButtons btns = SUIT_MessageBox::Yes | SUIT_MessageBox::No;
745           if (i < fileNames.count() - 1) btns = btns | SUIT_MessageBox::YesToAll | SUIT_MessageBox::NoToAll;
746           igesAnswer = SUIT_MessageBox::question(app->desktop(),
747                                                  "Question",//tr("WRN_WARNING"),
748                                                  tr("GEOM_SCALE_DIMENSIONS").arg(aUnitsStr),
749                                                  btns | SUIT_MessageBox::Cancel,
750                                                  SUIT_MessageBox::No);
751           switch (igesAnswer) {
752           case SUIT_MessageBox::Cancel:
753             return false;                // cancel (break) import operation
754           case SUIT_MessageBox::Yes:
755           case SUIT_MessageBox::YesToAll:
756             break;                       // scaling is confirmed
757           case SUIT_MessageBox::No:
758           case SUIT_MessageBox::NoAll:
759             fileT = (aCurrentType + "_SCALE").toLatin1().constData();
760           default:
761             break;                       // scaling is rejected
762           } // switch ( igesAnswer )
763         } // if ( igeAnswer != NoToAll )
764       } // if ( needConvert )
765
766       /*
767       // skl 29.05.2009
768       if ( aCurrentType == "IGES" ) {
769         GEOM::GEOM_Object_var anObj = aInsOp->ImportFile( fileN, "IGES_UNIT" );
770         bool needConvert = false;
771         TCollection_AsciiString aUnitName = aInsOp->GetErrorCode();
772         if ( aUnitName.SubString( 1, 4 ) == "UNIT" )
773           needConvert = aUnitName.SubString( 6, aUnitName.Length() ) != "M";
774
775         if ( needConvert ) {
776           if ( igesAnswer == SUIT_MessageBox::NoToAll ) {
777             // converting for all files is already approved
778             fileT = "IGES_SCALE";
779           }
780           else if ( igesAnswer != SUIT_MessageBox::YesToAll ) {
781             SUIT_MessageBox::StandardButtons btns = SUIT_MessageBox::Yes | SUIT_MessageBox::No;
782             if ( i < fileNames.count()-1 ) btns = btns | SUIT_MessageBox::YesToAll | SUIT_MessageBox::NoToAll;
783             igesAnswer = SUIT_MessageBox::question( app->desktop(),
784                                                     "Question",//tr("WRN_WARNING"),
785                                                     tr("GEOM_SCALE_DIMENSIONS"),
786                                                     btns | SUIT_MessageBox::Cancel,
787                                                     SUIT_MessageBox::No );
788             switch ( igesAnswer ) {
789             case SUIT_MessageBox::Cancel:
790               return false;                // cancel (break) import operation
791             case SUIT_MessageBox::Yes:
792             case SUIT_MessageBox::YesToAll:
793               break;                       // scaling is confirmed
794             case SUIT_MessageBox::No:
795             case SUIT_MessageBox::NoAll:
796               fileT = "IGES_SCALE";
797             default:
798               break;                       // scaling is rejected
799             } // switch ( igesAnswer )
800           } // if ( igeAnswer != NoToAll )
801         } // if ( needConvert )
802       } // if ( aCurrentType == "IGES" )
803       else if ( aCurrentType == "ACIS" ) {
804       */
805
806       if ( aCurrentType == "ACIS" ) {
807         if ( acisAnswer != SUIT_MessageBox::YesToAll && acisAnswer != SUIT_MessageBox::NoToAll ) {
808           SUIT_MessageBox::StandardButtons btns = SUIT_MessageBox::Yes | SUIT_MessageBox::No;
809           if ( i < fileNames.count()-1 ) btns = btns | SUIT_MessageBox::YesToAll | SUIT_MessageBox::NoToAll;
810           acisAnswer = SUIT_MessageBox::question( app->desktop(),
811                                                   "Question",//tr("WRN_WARNING"),
812                                                   tr("GEOM_PUBLISH_NAMED_SHAPES"),
813                                                   btns | SUIT_MessageBox::Cancel,
814                                                   SUIT_MessageBox::No );
815           if ( acisAnswer == SUIT_MessageBox::Cancel )
816             return false; // cancel (break) import operation
817         } // if ( acisAnswer != YesToAll && acisAnswer != NoToAll )
818       } // else if ( aCurrentType == "ACIS" )
819
820       // IMPORT
821       GEOM::GEOM_Object_var anObj = aInsOp->ImportFile( fileN, fileT );
822
823       if ( !anObj->_is_nil() && aInsOp->IsDone() ) {
824         QString aPublishObjName =
825           GEOMBase::GetDefaultName( SUIT_Tools::file( fileName, /*withExten=*/true ) );
826
827         SALOMEDS::Study_var aDSStudy = GeometryGUI::ClientStudyToStudy( aStudy );
828         SALOMEDS::SObject_var aSO =
829           GeometryGUI::GetGeomGen()->PublishInStudy( aDSStudy,
830                                                      SALOMEDS::SObject::_nil(),
831                                                      anObj,
832                                                      aPublishObjName.toLatin1().constData() );
833         if ( ( !aSO->_is_nil() ) )
834           anEntryList.append( aSO->GetID() );
835
836         objsForDisplay.append( anObj );
837
838         if ( aCurrentType == "ACIS" ) {
839           if ( acisAnswer == SUIT_MessageBox::Yes || acisAnswer == SUIT_MessageBox::YesToAll )
840             GeometryGUI::GetGeomGen()->PublishNamedShapesInStudy( aDSStudy, anObj );
841         }
842
843         anOp->commit();
844       }
845       else {
846         anOp->abort();
847         errors.append( QString( "%1 : %2" ).arg( fileName ).arg( aInsOp->GetErrorCode() ) );
848       }
849     }
850     catch( const SALOME::SALOME_Exception& S_ex ) {
851       anOp->abort();
852       errors.append( QString( "%1 : %2" ).arg( fileName ).arg( tr( "GEOM_UNKNOWN_IMPORT_ERROR" ) ) );
853     }
854   }
855
856   // update object browser
857   getGeometryGUI()->updateObjBrowser( true );
858
859   // browse published objects
860   app->browseObjects( anEntryList );
861
862   // display imported model (if only one file is selected)
863   if ( objsForDisplay.count() == 1 )
864     GEOM_Displayer( stud ).Display( objsForDisplay[0].in() );
865
866   if ( errors.count() > 0 ) {
867     SUIT_MessageBox::critical( app->desktop(),
868                                QObject::tr( "GEOM_ERROR" ),
869                                QObject::tr( "GEOM_IMPORT_ERRORS" ) + "\n" + errors.join( "\n" ) );
870   }
871
872   app->updateActions(); //SRN: To update a Save button in the toolbar
873
874   return objsForDisplay.count() > 0;
875 }
876
877 //=====================================================================================
878 // function : Export
879 // purpose  : BRep, Iges, Step
880 //=====================================================================================
881 bool GEOMToolsGUI::Export()
882 {
883   SalomeApp_Application* app = getGeometryGUI()->getApp();
884   if (!app) return false;
885
886   SalomeApp_Study* stud = dynamic_cast<SalomeApp_Study*> ( app->activeStudy() );
887   if ( !stud ) {
888     MESSAGE ( "FAILED to cast active study to SalomeApp_Study" );
889     return false;
890   }
891   _PTR(Study) aStudy = stud->studyDS();
892
893   GEOM::GEOM_Gen_var eng = GeometryGUI::GetGeomGen();
894   if ( CORBA::is_nil( eng ) ) {
895     SUIT_MessageBox::critical( app->desktop(),
896                                QObject::tr("WRN_WARNING"),
897                                QObject::tr( "GEOM Engine is not started" ) );
898     return false;
899   }
900
901   GEOM::GEOM_IInsertOperations_var aInsOp = eng->GetIInsertOperations( aStudy->StudyId() );
902   if ( aInsOp->_is_nil() )
903     return false;
904
905   // Obtain a list of available export formats
906   FilterMap aMap;
907   QStringList filters;
908   GEOM::string_array_var aFormats, aPatterns;
909   aInsOp->ExportTranslators( aFormats, aPatterns );
910   for ( int i = 0, n = aFormats->length(); i < n; i++ ) {
911     aMap.insert( (char*)aPatterns[i], (char*)aFormats[i] );
912     filters.push_back( (char*)aPatterns[i] );
913   }
914
915   // Get selected objects
916   LightApp_SelectionMgr* sm = app->selectionMgr();
917   if ( !sm )
918     return false;
919
920   SALOME_ListIO selectedObjects;
921   sm->selectedObjects( selectedObjects );
922   bool appropriateObj = false;
923
924   SALOME_ListIteratorOfListIO It( selectedObjects );
925   for (; It.More(); It.Next()) {
926     Handle(SALOME_InteractiveObject) IObject = It.Value();
927     GEOM::GEOM_Object_var anObj = GEOMBase::ConvertIOinGEOMObject( IObject );
928
929     if ( anObj->_is_nil() )
930       continue;
931
932     QString fileType;
933     QString file = getFileName(app->desktop(), QString( IObject->getName() ), aMap, filters,
934                                tr("GEOM_MEN_EXPORT"), false, fileType, true);
935
936     // User has pressed "Cancel" --> stop the operation
937     if ( file.isEmpty() || fileType.isEmpty() )
938       return false;
939
940     GEOM_Operation* anOp = new GEOM_Operation( app, aInsOp.in() );
941     try {
942       SUIT_OverrideCursor wc;
943
944       app->putInfo( tr("GEOM_PRP_EXPORT").arg(SUIT_Tools::file( file, /*withExten=*/true )) );
945
946       anOp->start();
947
948       aInsOp->Export( anObj, file.toStdString().c_str(), fileType.toLatin1().constData() );
949
950       if (aInsOp->IsDone())
951         anOp->commit();
952       else {
953         anOp->abort();
954         wc.suspend();
955         SUIT_MessageBox::critical(app->desktop(),
956                                   QObject::tr("GEOM_ERROR"),
957                                   QObject::tr("GEOM_PRP_ABORT") + "\n" + QObject::tr(aInsOp->GetErrorCode()));
958         return false;
959       }
960     }
961     catch (const SALOME::SALOME_Exception& S_ex) {
962       //QtCatchCorbaException(S_ex);
963       anOp->abort();
964       return false;
965     }
966     appropriateObj = true;
967   }
968
969   if ( !appropriateObj )
970     SUIT_MessageBox::warning( app->desktop(),
971                               QObject::tr("WRN_WARNING"),
972                               QObject::tr("GEOM_WRN_NO_APPROPRIATE_SELECTION") );
973   return true;
974 }
975
976 //=====================================================================================
977 // function : RemoveObjectWithChildren
978 // purpose  : used by OnEditDelete() method
979 //=====================================================================================
980 void GEOMToolsGUI::removeObjectWithChildren(_PTR(SObject) obj,
981                                             _PTR(Study) aStudy,
982                                             QList<SALOME_View*> views,
983                                             GEOM_Displayer* disp)
984 {
985   // iterate through all children of obj
986   for (_PTR(ChildIterator) it (aStudy->NewChildIterator(obj)); it->More(); it->Next()) {
987   // for (_PTR(UseCaseIterator) it (aStudy->GetUseCaseBuilder()->GetUseCaseIterator(obj)); it->More(); it->Next()) {
988     _PTR(SObject) child (it->Value());
989     removeObjectWithChildren(child, aStudy, views, disp);
990   }
991
992   // erase object and remove it from engine
993   _PTR(GenericAttribute) anAttr;
994   if (obj->FindAttribute(anAttr, "AttributeIOR")) {
995     _PTR(AttributeIOR) anIOR (anAttr);
996
997     SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
998
999     // Delete shape in Client
1000     const TCollection_AsciiString ASCIor ((char*)anIOR->Value().c_str());
1001     getGeometryGUI()->GetShapeReader().RemoveShapeFromBuffer(ASCIor);
1002
1003     CORBA::Object_var corbaObj = GeometryGUI::ClientSObjectToObject(obj);
1004     GEOM::GEOM_Object_var geomObj = GEOM::GEOM_Object::_narrow( corbaObj );
1005     if (!CORBA::is_nil(geomObj)) {
1006
1007       //Remove visual properties of the object
1008       appStudy->removeObjectFromAll(obj->GetID().c_str());
1009
1010       // Erase graphical object
1011       QListIterator<SALOME_View*> it( views );
1012       while ( it.hasNext() )
1013         if ( SALOME_View* view = it.next() )
1014           disp->Erase(geomObj, true, view);
1015
1016       // Remove object from Engine
1017       // We can't directly remove object from engine. All we can do is to unpublish the object
1018       // from the study. Another client could be using the object.
1019       // Unpublishing is done just after in aStudyBuilder->RemoveObjectWithChildren( child );
1020       //GeometryGUI::GetGeomGen()->RemoveObject( geomObj );
1021     }
1022   }
1023 }
1024
1025 //=================================================================================
1026 // function : deactivate()
1027 // purpose  : Called when GEOM component is deactivated
1028 //=================================================================================
1029 void GEOMToolsGUI::deactivate()
1030 {
1031   SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
1032   if ( app ) {
1033     SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
1034     GEOM_Displayer aDisp (appStudy);
1035     aDisp.GlobalSelection();
1036     getGeometryGUI()->setLocalSelectionMode(GEOM_ALLOBJECTS);
1037   }
1038 }
1039
1040 //=====================================================================================
1041 // EXPORTED METHODS
1042 //=====================================================================================
1043 extern "C"
1044 {
1045 #ifdef WIN32
1046   __declspec( dllexport )
1047 #endif
1048   GEOMGUI* GetLibGUI( GeometryGUI* parent )
1049   {
1050     return new GEOMToolsGUI( parent );
1051   }
1052 }