Salome HOME
Synchronize adm files
[modules/geom.git] / src / GEOMToolsGUI / GEOMToolsGUI.cxx
1 // Copyright (C) 2007-2014  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, or (at your option) any later version.
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   case GEOMOp::OpShowDependencyTree:
427     OnShowDependencyTree();
428      break;
429   case GEOMOp::OpReduceStudy:
430     OnReduceStudy();
431     break;
432   default:
433     SUIT_Session::session()->activeApplication()->putInfo(tr("GEOM_PRP_COMMAND").arg(theCommandID));
434     break;
435   }
436   return true;
437 }
438
439 //=======================================================================
440 // function : OnGUIEvent()
441 // purpose  :
442 //=======================================================================
443 bool GEOMToolsGUI::OnGUIEvent(int theCommandID, SUIT_Desktop* parent, const QVariant& theParam )
444 {
445   getGeometryGUI()->EmitSignalDeactivateDialog();
446
447   switch ( theCommandID ) {
448   case GEOMOp::OpPredefMaterial:         // POPUP MENU - MATERIAL PROPERTIES - <SOME MATERIAL>
449     OnSetMaterial( theParam );
450     break;
451   default:
452     SUIT_Session::session()->activeApplication()->putInfo(tr("GEOM_PRP_COMMAND").arg(theCommandID));
453     break;
454   }
455   return true;
456 }
457
458 //===============================================================================
459 // function : OnEditDelete()
460 // purpose  :
461 //===============================================================================
462 void GEOMToolsGUI::OnEditDelete()
463 {
464   SALOME_ListIO selected;
465   SalomeApp_Application* app =
466     dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
467   if ( !app )
468     return;
469
470   LightApp_SelectionMgr* aSelMgr = app->selectionMgr();
471   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
472   if ( !aSelMgr || !appStudy )
473     return;
474
475   // get selection
476   aSelMgr->selectedObjects( selected, "ObjectBrowser", false );
477   if ( selected.IsEmpty() )
478     return;
479
480   _PTR(Study) aStudy = appStudy->studyDS();
481   _PTR(UseCaseBuilder) aUseCaseBuilder = aStudy->GetUseCaseBuilder();
482
483   // check if study is locked
484   if ( _PTR(AttributeStudyProperties)( aStudy->GetProperties() )->IsLocked() ) {
485     SUIT_MessageBox::warning( app->desktop(),
486                               tr("WRN_WARNING"),
487                               tr("WRN_STUDY_LOCKED") );
488     return; // study is locked
489   }
490
491   // get GEOM component
492   CORBA::String_var geomIOR = app->orb()->object_to_string( GeometryGUI::GetGeomGen() );
493   QString geomComp = getParentComponent( aStudy->FindObjectIOR( geomIOR.in() ) );
494
495   // check each selected object: if belongs to GEOM, if not reference...
496   QMap<QString,QString> toBeDeleted;
497   QMap<QString,QString> allDeleted;
498   QMap<QString,QString> toBeDelFolders;
499   bool isComponentSelected = false;
500
501   for ( SALOME_ListIteratorOfListIO It( selected ); It.More(); It.Next() ) {
502     Handle(SALOME_InteractiveObject) anIObject = It.Value();
503     if ( !anIObject->hasEntry() )
504       continue; // invalid object
505     // ...
506     QString entry = anIObject->getEntry();
507     _PTR(SObject) obj = aStudy->FindObjectID( entry.toLatin1().data() );
508     // check parent component
509     QString parentComp = getParentComponent( obj );
510     if ( parentComp != geomComp )  {
511       SUIT_MessageBox::warning( app->desktop(),
512                                 QObject::tr("ERR_ERROR"),
513                                 QObject::tr("NON_GEOM_OBJECTS_SELECTED").arg( getGeometryGUI()->moduleName() ) );
514       return; // not GEOM object selected
515     }
516
517     ///////////////////////////////////////////////////////
518     // if GEOM component is selected, so skip other checks
519     if ( isComponentSelected ) continue;
520     ///////////////////////////////////////////////////////
521
522     // check if object is reference
523     _PTR(SObject) refobj;
524     if ( obj && obj->ReferencedObject( refobj ) ) {
525       // get the main object by reference IPAL 21354
526       obj = refobj;
527       entry = obj->GetID().c_str();
528     }
529     // ...
530     QString aName = obj->GetName().c_str();
531     if ( entry == geomComp ) {
532       // GEOM component is selected, skip other checks
533       isComponentSelected = true;
534       continue;
535     }
536     // all sub-objects of folder have to be deleted
537     getGeomChildrenAndFolders( obj, toBeDeleted, toBeDelFolders );
538     allDeleted.insert( entry, aName ); // skip GEOM component
539     // browse through all children recursively
540     _PTR(UseCaseIterator) it ( aUseCaseBuilder->GetUseCaseIterator( obj ) );
541     for ( it->Init( true ); it->More(); it->Next() ) {
542       _PTR(SObject) child( it->Value() );
543       if ( child && child->ReferencedObject( refobj ) )
544         continue; // skip references
545       aName = child->GetName().c_str();
546       if ( !aName.isEmpty() )
547         allDeleted.insert( child->GetID().c_str(), aName );
548     }
549   }
550
551   // is there is anything to delete?
552   if ( !isComponentSelected && allDeleted.count() <= 0 )
553     return; // nothing to delete
554
555   // show confirmation dialog box
556   GEOMToolsGUI_DeleteDlg dlg( app->desktop(), allDeleted, isComponentSelected );
557   if ( !dlg.exec() )
558     return; // operation is cancelled by user
559
560   // get currently opened views
561   QList<SALOME_View*> views;
562   SALOME_View* view;
563   ViewManagerList vmans = app->viewManagers();
564   SUIT_ViewManager* vman;
565   foreach ( vman, vmans ) {
566     SUIT_ViewModel* vmod = vman->getViewModel();
567     view = dynamic_cast<SALOME_View*> ( vmod ); // must work for OCC and VTK views
568     if ( view )
569       views.append( view );
570   }
571
572   _PTR(StudyBuilder) aStudyBuilder (aStudy->NewBuilder());
573   GEOM_Displayer* disp = new GEOM_Displayer( appStudy );
574
575   if ( isComponentSelected ) {
576     // GEOM component is selected: delete all objects recursively
577     _PTR(SObject) comp = aStudy->FindObjectID( geomComp.toLatin1().data() );
578     if ( !comp )
579       return;
580     _PTR(ChildIterator) it ( aStudy->NewChildIterator( comp ) );
581     // remove top-level objects only
582     for ( it->InitEx( false ); it->More(); it->Next() ) {
583       _PTR(SObject) child( it->Value() );
584       // remove object from GEOM engine
585       removeObjectWithChildren( child, aStudy, views, disp );
586       // remove object from study
587       aStudyBuilder->RemoveObjectWithChildren( child );
588       // remove object from use case tree
589       aUseCaseBuilder->Remove( child );
590     }
591   }
592   else {
593     // GEOM component is not selected: check if selected objects are in use
594     if ( inUse( aStudy, geomComp, allDeleted ) && 
595          SUIT_MessageBox::question( app->desktop(),
596                                     QObject::tr("WRN_WARNING"),
597                                     QObject::tr("DEP_OBJECT"),
598                                     SUIT_MessageBox::Yes | SUIT_MessageBox::No,
599                                     SUIT_MessageBox::No ) != SUIT_MessageBox::Yes ) {
600       return; // object(s) in use
601     }
602     // ... and then delete all objects
603     QMap<QString, QString>::Iterator it;
604     for ( it = toBeDeleted.begin(); it != toBeDeleted.end(); ++it ) {
605       _PTR(SObject) obj ( aStudy->FindObjectID( it.key().toLatin1().data() ) );
606       // remove object from GEOM engine
607       removeObjectWithChildren( obj, aStudy, views, disp );
608       // remove objects from study
609       aStudyBuilder->RemoveObjectWithChildren( obj );
610       // remove object from use case tree
611       aUseCaseBuilder->Remove( obj );
612     }
613     // ... and then delete all folders
614     for ( it = toBeDelFolders.begin(); it != toBeDelFolders.end(); ++it ) {
615       _PTR(SObject) obj ( aStudy->FindObjectID( it.key().toLatin1().data() ) );
616       // remove object from GEOM engine
617       removeObjectWithChildren( obj, aStudy, views, disp );
618       // remove objects from study
619       aStudyBuilder->RemoveObjectWithChildren( obj );
620       // remove object from use case tree
621       aUseCaseBuilder->Remove( obj );
622     }
623   }
624
625   selected.Clear();
626   aSelMgr->setSelectedObjects( selected );
627   getGeometryGUI()->updateObjBrowser();
628   app->updateActions(); //SRN: To update a Save button in the toolbar
629 }
630
631 //=====================================================================================
632 // function : Import
633 // purpose  : BRep, Iges, Step, ...
634 //=====================================================================================
635 bool GEOMToolsGUI::Import()
636 {
637   SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( getGeometryGUI()->getApp() );
638   if ( !app ) return false;
639
640   SalomeApp_Study* stud = dynamic_cast<SalomeApp_Study*> ( app->activeStudy() );
641   if ( !stud ) {
642     MESSAGE ( "FAILED to cast active study to SalomeApp_Study" );
643     return false;
644   }
645   _PTR(Study) aStudy = stud->studyDS();
646
647   // check if study is locked
648   bool aLocked = (_PTR(AttributeStudyProperties)(aStudy->GetProperties()))->IsLocked();
649   if ( aLocked ) {
650     SUIT_MessageBox::warning( app->desktop(),
651                               QObject::tr("WRN_WARNING"),
652                               QObject::tr("WRN_STUDY_LOCKED") );
653     return false;
654   }
655
656   // check if GEOM engine is available
657   GEOM::GEOM_Gen_var eng = GeometryGUI::GetGeomGen();
658   if ( CORBA::is_nil( eng ) ) {
659     SUIT_MessageBox::critical( app->desktop(),
660                                QObject::tr("WRN_WARNING"),
661                                QObject::tr( "GEOM Engine is not started" ) );
662     return false;
663   }
664
665   GEOM::GEOM_IInsertOperations_var aInsOp = eng->GetIInsertOperations( aStudy->StudyId() );
666   if ( aInsOp->_is_nil() )
667     return false;
668
669   // obtain a list of available import formats
670   FilterMap aMap;
671   GEOM::string_array_var aFormats, aPatterns;
672   aInsOp->ImportTranslators( aFormats, aPatterns );
673
674   for ( int i = 0, n = aFormats->length(); i < n; i++ )
675     aMap.insert( (char*)aPatterns[i], (char*)aFormats[i] );
676
677   // select files to be imported
678   QString fileType;
679   QStringList fileNames = getFileNames( app->desktop(), "", aMap,
680                                         tr( "GEOM_MEN_IMPORT" ), fileType, true );
681
682   // set Wait cursor
683   SUIT_OverrideCursor wc;
684
685   if ( fileNames.count() == 0 )
686     return false; // nothing selected, return
687
688   QStringList errors;
689
690   QList< GEOM::GEOM_Object_var > objsForDisplay;
691
692   QStringList anEntryList;
693
694   // iterate through all selected files
695
696   SUIT_MessageBox::StandardButton igesAnswer = SUIT_MessageBox::NoButton;
697   SUIT_MessageBox::StandardButton acisAnswer = SUIT_MessageBox::NoButton;
698
699   for ( int i = 0; i < fileNames.count(); i++ ) {
700     QString fileName = fileNames[i];
701
702     if ( fileName.isEmpty() )
703       continue;
704
705     QString aCurrentType;
706     if ( fileType.isEmpty() ) {
707       // file type is not defined, try to detect
708       QString ext = QFileInfo( fileName ).suffix().toUpper();
709       QRegExp re( "\\*\\.(\\w+)" );
710       for ( FilterMap::const_iterator it = aMap.begin();
711             it != aMap.end() && aCurrentType.isEmpty(); ++it ) {
712         int pos = 0;
713         while ( re.indexIn( it.key(), pos ) >= 0 ) {
714           QString f = re.cap(1).trimmed().toUpper();
715           if ( ext == f ) { aCurrentType = it.value(); break; }
716           pos = re.pos() + re.cap(1).length() + 2;
717         }
718       }
719     }
720     else {
721       aCurrentType = fileType;
722     }
723
724     if ( aCurrentType.isEmpty() ) {
725       errors.append( QString( "%1 : %2" ).arg( fileName ).arg( tr( "GEOM_UNSUPPORTED_TYPE" ) ) );
726       continue;
727     }
728
729     GEOM_Operation* anOp = new GEOM_Operation( app, aInsOp.in() );
730     try {
731       app->putInfo( tr( "GEOM_PRP_LOADING" ).arg( SUIT_Tools::file( fileName, /*withExten=*/true ) ) );
732       anOp->start();
733
734       CORBA::String_var fileN = fileName.toUtf8().constData();
735       CORBA::String_var fileT = aCurrentType.toUtf8().constData();
736
737       // jfa 21.08.2012 for mantis issue 21511 (STEP file units)
738       CORBA::String_var aUnits = aInsOp->ReadValue(fileN, fileT, "LEN_UNITS");
739       QString aUnitsStr (aUnits.in());
740       bool needConvert = true;
741       if (aUnitsStr.isEmpty() || aUnitsStr == "M" || aUnitsStr.toLower() == "metre")
742         needConvert = false;
743
744       if (needConvert) {
745         if (igesAnswer == SUIT_MessageBox::NoToAll) {
746           // converting for all files is already approved
747           fileT = (aCurrentType + "_SCALE").toLatin1().constData();
748         }
749         else if (igesAnswer != SUIT_MessageBox::YesToAll) {
750           SUIT_MessageBox::StandardButtons btns = SUIT_MessageBox::Yes | SUIT_MessageBox::No;
751           if (i < fileNames.count() - 1) btns = btns | SUIT_MessageBox::YesToAll | SUIT_MessageBox::NoToAll;
752           igesAnswer = SUIT_MessageBox::question(app->desktop(),
753                                                  "Question",//tr("WRN_WARNING"),
754                                                  tr("GEOM_SCALE_DIMENSIONS").arg(aUnitsStr),
755                                                  btns | SUIT_MessageBox::Cancel,
756                                                  SUIT_MessageBox::No);
757           switch (igesAnswer) {
758           case SUIT_MessageBox::Cancel:
759             return false;                // cancel (break) import operation
760           case SUIT_MessageBox::Yes:
761           case SUIT_MessageBox::YesToAll:
762             break;                       // scaling is confirmed
763           case SUIT_MessageBox::No:
764           case SUIT_MessageBox::NoAll:
765             fileT = (aCurrentType + "_SCALE").toLatin1().constData();
766           default:
767             break;                       // scaling is rejected
768           } // switch ( igesAnswer )
769         } // if ( igeAnswer != NoToAll )
770       } // if ( needConvert )
771
772       /*
773       // skl 29.05.2009
774       if ( aCurrentType == "IGES" ) {
775         GEOM::GEOM_Object_var anObj = aInsOp->ImportFile( fileN, "IGES_UNIT" );
776         bool needConvert = false;
777         TCollection_AsciiString aUnitName = aInsOp->GetErrorCode();
778         if ( aUnitName.SubString( 1, 4 ) == "UNIT" )
779           needConvert = aUnitName.SubString( 6, aUnitName.Length() ) != "M";
780
781         if ( needConvert ) {
782           if ( igesAnswer == SUIT_MessageBox::NoToAll ) {
783             // converting for all files is already approved
784             fileT = "IGES_SCALE";
785           }
786           else if ( igesAnswer != SUIT_MessageBox::YesToAll ) {
787             SUIT_MessageBox::StandardButtons btns = SUIT_MessageBox::Yes | SUIT_MessageBox::No;
788             if ( i < fileNames.count()-1 ) btns = btns | SUIT_MessageBox::YesToAll | SUIT_MessageBox::NoToAll;
789             igesAnswer = SUIT_MessageBox::question( app->desktop(),
790                                                     "Question",//tr("WRN_WARNING"),
791                                                     tr("GEOM_SCALE_DIMENSIONS"),
792                                                     btns | SUIT_MessageBox::Cancel,
793                                                     SUIT_MessageBox::No );
794             switch ( igesAnswer ) {
795             case SUIT_MessageBox::Cancel:
796               return false;                // cancel (break) import operation
797             case SUIT_MessageBox::Yes:
798             case SUIT_MessageBox::YesToAll:
799               break;                       // scaling is confirmed
800             case SUIT_MessageBox::No:
801             case SUIT_MessageBox::NoAll:
802               fileT = "IGES_SCALE";
803             default:
804               break;                       // scaling is rejected
805             } // switch ( igesAnswer )
806           } // if ( igeAnswer != NoToAll )
807         } // if ( needConvert )
808       } // if ( aCurrentType == "IGES" )
809       else if ( aCurrentType == "ACIS" ) {
810       */
811
812       if ( aCurrentType == "ACIS" ) {
813         if ( acisAnswer != SUIT_MessageBox::YesToAll && acisAnswer != SUIT_MessageBox::NoToAll ) {
814           SUIT_MessageBox::StandardButtons btns = SUIT_MessageBox::Yes | SUIT_MessageBox::No;
815           if ( i < fileNames.count()-1 ) btns = btns | SUIT_MessageBox::YesToAll | SUIT_MessageBox::NoToAll;
816           acisAnswer = SUIT_MessageBox::question( app->desktop(),
817                                                   "Question",//tr("WRN_WARNING"),
818                                                   tr("GEOM_PUBLISH_NAMED_SHAPES"),
819                                                   btns | SUIT_MessageBox::Cancel,
820                                                   SUIT_MessageBox::No );
821           if ( acisAnswer == SUIT_MessageBox::Cancel )
822             return false; // cancel (break) import operation
823         } // if ( acisAnswer != YesToAll && acisAnswer != NoToAll )
824       } // else if ( aCurrentType == "ACIS" )
825
826       // IMPORT
827       GEOM::ListOfGO_var anObj = aInsOp->ImportFile( fileN, fileT );
828
829       if ( anObj->length() > 0 && aInsOp->IsDone() ) {
830         GEOM::GEOM_Object_ptr aFather = anObj[0]._retn();
831         QString aPublishObjName =
832           GEOMBase::GetDefaultName( SUIT_Tools::file( fileName, /*withExten=*/true ) );
833
834         SALOMEDS::Study_var aDSStudy = GeometryGUI::ClientStudyToStudy( aStudy );
835         SALOMEDS::SObject_var aSO =
836           GeometryGUI::GetGeomGen()->PublishInStudy( aDSStudy,
837                                                      SALOMEDS::SObject::_nil(),
838                                                      aFather,
839                                                      aPublishObjName.toLatin1().constData() );
840         if ( ( !aSO->_is_nil() ) )
841           anEntryList.append( aSO->GetID() );
842
843         objsForDisplay.append( aFather );
844
845         if ( aCurrentType == "ACIS" ) {
846           if ( acisAnswer == SUIT_MessageBox::Yes || acisAnswer == SUIT_MessageBox::YesToAll )
847             GeometryGUI::GetGeomGen()->PublishNamedShapesInStudy( aDSStudy, aFather );
848         }
849
850         anOp->commit();
851
852         // Treat group objects.
853         for (int i = 1, n = anObj->length(); i < n; i++) {
854           GEOM::GEOM_Object_ptr anObject = anObj[i]._retn();
855           GeometryGUI::GetGeomGen()->AddInStudy(aDSStudy,
856             anObject, tr(anObject->GetName()).toStdString().c_str(), aFather);
857         }
858       }
859       else {
860         anOp->abort();
861         errors.append( QString( "%1 : %2" ).arg( fileName ).arg( aInsOp->GetErrorCode() ) );
862       }
863     }
864     catch( const SALOME::SALOME_Exception& S_ex ) {
865       anOp->abort();
866       errors.append( QString( "%1 : %2" ).arg( fileName ).arg( tr( "GEOM_UNKNOWN_IMPORT_ERROR" ) ) );
867     }
868   }
869
870   // update object browser
871   getGeometryGUI()->updateObjBrowser( true );
872
873   // browse published objects
874   app->browseObjects( anEntryList );
875
876   // display imported model (if only one file is selected)
877   if ( objsForDisplay.count() == 1 )
878     GEOM_Displayer( stud ).Display( objsForDisplay[0].in() );
879
880   if ( errors.count() > 0 ) {
881     SUIT_MessageBox::critical( app->desktop(),
882                                QObject::tr( "GEOM_ERROR" ),
883                                QObject::tr( "GEOM_IMPORT_ERRORS" ) + "\n" + errors.join( "\n" ) );
884   }
885
886   app->updateActions(); //SRN: To update a Save button in the toolbar
887
888   return objsForDisplay.count() > 0;
889 }
890
891 //=====================================================================================
892 // function : Export
893 // purpose  : BRep, Iges, Step
894 //=====================================================================================
895 bool GEOMToolsGUI::Export()
896 {
897   SalomeApp_Application* app = getGeometryGUI()->getApp();
898   if (!app) return false;
899
900   SalomeApp_Study* stud = dynamic_cast<SalomeApp_Study*> ( app->activeStudy() );
901   if ( !stud ) {
902     MESSAGE ( "FAILED to cast active study to SalomeApp_Study" );
903     return false;
904   }
905   _PTR(Study) aStudy = stud->studyDS();
906
907   GEOM::GEOM_Gen_var eng = GeometryGUI::GetGeomGen();
908   if ( CORBA::is_nil( eng ) ) {
909     SUIT_MessageBox::critical( app->desktop(),
910                                QObject::tr("WRN_WARNING"),
911                                QObject::tr( "GEOM Engine is not started" ) );
912     return false;
913   }
914
915   GEOM::GEOM_IInsertOperations_var aInsOp = eng->GetIInsertOperations( aStudy->StudyId() );
916   if ( aInsOp->_is_nil() )
917     return false;
918
919   // Obtain a list of available export formats
920   FilterMap aMap;
921   QStringList filters;
922   GEOM::string_array_var aFormats, aPatterns;
923   aInsOp->ExportTranslators( aFormats, aPatterns );
924   for ( int i = 0, n = aFormats->length(); i < n; i++ ) {
925     aMap.insert( (char*)aPatterns[i], (char*)aFormats[i] );
926     filters.push_back( (char*)aPatterns[i] );
927   }
928
929   // Get selected objects
930   LightApp_SelectionMgr* sm = app->selectionMgr();
931   if ( !sm )
932     return false;
933
934   SALOME_ListIO selectedObjects;
935   sm->selectedObjects( selectedObjects );
936   bool appropriateObj = false;
937
938   SALOME_ListIteratorOfListIO It( selectedObjects );
939   for (; It.More(); It.Next()) {
940     Handle(SALOME_InteractiveObject) IObject = It.Value();
941     GEOM::GEOM_Object_var anObj = GEOMBase::ConvertIOinGEOMObject( IObject );
942
943     if ( anObj->_is_nil() )
944       continue;
945
946     QString fileType;
947     QString file = getFileName(app->desktop(), QString( IObject->getName() ), aMap, filters,
948                                tr("GEOM_MEN_EXPORT"), false, fileType, true);
949
950     // User has pressed "Cancel" --> stop the operation
951     if ( file.isEmpty() || fileType.isEmpty() )
952       return false;
953
954     GEOM_Operation* anOp = new GEOM_Operation( app, aInsOp.in() );
955     try {
956       SUIT_OverrideCursor wc;
957
958       app->putInfo( tr("GEOM_PRP_EXPORT").arg(SUIT_Tools::file( file, /*withExten=*/true )) );
959
960       anOp->start();
961
962       aInsOp->Export( anObj, file.toUtf8().constData(), fileType.toUtf8().constData() );
963
964       if (aInsOp->IsDone())
965         anOp->commit();
966       else {
967         anOp->abort();
968         wc.suspend();
969         SUIT_MessageBox::critical(app->desktop(),
970                                   QObject::tr("GEOM_ERROR"),
971                                   QObject::tr("GEOM_PRP_ABORT") + "\n" + QObject::tr(aInsOp->GetErrorCode()));
972         return false;
973       }
974     }
975     catch (const SALOME::SALOME_Exception& S_ex) {
976       //QtCatchCorbaException(S_ex);
977       anOp->abort();
978       return false;
979     }
980     appropriateObj = true;
981   }
982
983   if ( !appropriateObj )
984     SUIT_MessageBox::warning( app->desktop(),
985                               QObject::tr("WRN_WARNING"),
986                               QObject::tr("GEOM_WRN_NO_APPROPRIATE_SELECTION") );
987   return true;
988 }
989
990 //=====================================================================================
991 // function : RemoveObjectWithChildren
992 // purpose  : used by OnEditDelete() method
993 //=====================================================================================
994 void GEOMToolsGUI::removeObjectWithChildren(_PTR(SObject) obj,
995                                             _PTR(Study) aStudy,
996                                             QList<SALOME_View*> views,
997                                             GEOM_Displayer* disp)
998 {
999   // iterate through all children of obj
1000   for (_PTR(ChildIterator) it (aStudy->NewChildIterator(obj)); it->More(); it->Next()) {
1001   // for (_PTR(UseCaseIterator) it (aStudy->GetUseCaseBuilder()->GetUseCaseIterator(obj)); it->More(); it->Next()) {
1002     _PTR(SObject) child (it->Value());
1003     removeObjectWithChildren(child, aStudy, views, disp);
1004   }
1005
1006   // erase object and remove it from engine
1007   _PTR(GenericAttribute) anAttr;
1008   if (obj->FindAttribute(anAttr, "AttributeIOR")) {
1009     _PTR(AttributeIOR) anIOR (anAttr);
1010
1011     SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
1012
1013     // Delete shape in Client
1014     const TCollection_AsciiString ASCIor ((char*)anIOR->Value().c_str());
1015     getGeometryGUI()->GetShapeReader().RemoveShapeFromBuffer(ASCIor);
1016
1017     CORBA::Object_var corbaObj = GeometryGUI::ClientSObjectToObject(obj);
1018     GEOM::GEOM_Object_var geomObj = GEOM::GEOM_Object::_narrow( corbaObj );
1019     if (!CORBA::is_nil(geomObj)) {
1020
1021       //Remove visual properties of the object
1022       appStudy->removeObjectFromAll(obj->GetID().c_str());
1023
1024       // Erase graphical object
1025       QListIterator<SALOME_View*> it( views );
1026       while ( it.hasNext() )
1027         if ( SALOME_View* view = it.next() )
1028           disp->Erase(geomObj, true, true, view);
1029
1030       // Remove object from Engine
1031       // We can't directly remove object from engine. All we can do is to unpublish the object
1032       // from the study. Another client could be using the object.
1033       // Unpublishing is done just after in aStudyBuilder->RemoveObjectWithChildren( child );
1034       //GeometryGUI::GetGeomGen()->RemoveObject( geomObj );
1035     }
1036   }
1037 }
1038
1039 //=================================================================================
1040 // function : deactivate()
1041 // purpose  : Called when GEOM component is deactivated
1042 //=================================================================================
1043 void GEOMToolsGUI::deactivate()
1044 {
1045   SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
1046   if ( app ) {
1047     SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
1048     GEOM_Displayer aDisp (appStudy);
1049     aDisp.GlobalSelection();
1050     getGeometryGUI()->setLocalSelectionMode(GEOM_ALLOBJECTS);
1051   }
1052 }
1053
1054 //=====================================================================================
1055 // EXPORTED METHODS
1056 //=====================================================================================
1057 extern "C"
1058 {
1059 #ifdef WIN32
1060   __declspec( dllexport )
1061 #endif
1062   GEOMGUI* GetLibGUI( GeometryGUI* parent )
1063   {
1064     return new GEOMToolsGUI( parent );
1065   }
1066 }