Salome HOME
GDD: Check that the PipeTShape is a block if it is required by user
[modules/geom.git] / src / GEOMToolsGUI / GEOMToolsGUI.cxx
1 //  Copyright (C) 2007-2010  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // GEOM GEOMGUI : GUI for Geometry component
24 // File   : GEOMBase_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_Object_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_Object_var geomObj_rem = GEOM::GEOM_Object::_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::ListOfGO_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_Object_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 //=======================================================================
262 // function : GEOMToolsGUI()
263 // purpose  : Constructor
264 //=======================================================================
265 GEOMToolsGUI::GEOMToolsGUI( GeometryGUI* parent )
266 : GEOMGUI( parent )
267 {
268 }
269
270
271 //=======================================================================
272 // function : ~GEOMToolsGUI()
273 // purpose  : Destructor
274 //=======================================================================
275 GEOMToolsGUI::~GEOMToolsGUI()
276 {
277 }
278
279
280 //=======================================================================
281 // function : OnGUIEvent()
282 // purpose  :
283 //=======================================================================
284 bool GEOMToolsGUI::OnGUIEvent(int theCommandID, SUIT_Desktop* parent)
285 {
286   getGeometryGUI()->EmitSignalDeactivateDialog();
287
288   switch ( theCommandID ) {
289   case GEOMOp::OpDelete:         // EDIT - DELETE
290     OnEditDelete();
291     break;
292   case GEOMOp::OpImport:         // FILE - IMPORT
293     Import();
294     break;
295   case GEOMOp::OpExport:         // FILE - EXPORT
296     Export();
297     break;
298   case GEOMOp::OpCheckGeom:      // TOOLS - CHECK GEOMETRY
299     OnCheckGeometry();
300     break;
301   case GEOMOp::OpSelectVertex:   // POPUP - SELECT ONLY - VERTEX
302     OnSelectOnly( GEOM_POINT );
303     break;
304   case GEOMOp::OpSelectEdge:     // POPUP - SELECT ONLY - EDGE
305     OnSelectOnly( GEOM_EDGE );
306     break;
307   case GEOMOp::OpSelectWire:     // POPUP - SELECT ONLY - WIRE
308     OnSelectOnly( GEOM_WIRE );
309     break;
310   case GEOMOp::OpSelectFace:     // POPUP - SELECT ONLY - FACE
311     OnSelectOnly( GEOM_FACE );
312     break;
313   case GEOMOp::OpSelectShell:    // POPUP - SELECT ONLY - SHELL
314     OnSelectOnly( GEOM_SHELL );
315     break;
316   case GEOMOp::OpSelectSolid:    // POPUP - SELECT ONLY - SOLID
317     OnSelectOnly( GEOM_SOLID );
318     break;
319   case GEOMOp::OpSelectCompound: // POPUP - SELECT ONLY - COMPOUND
320     OnSelectOnly( GEOM_COMPOUND );
321     break;
322   case GEOMOp::OpSelectAll:      // POPUP - SELECT ONLY - SELECT ALL
323     OnSelectOnly( GEOM_ALLOBJECTS );
324     break;
325   case GEOMOp::OpRename:         // POPUP - RENAME
326     OnRename();
327     break;
328   case GEOMOp::OpDeflection:     // POPUP - DEFLECTION ANGLE
329     OnDeflection();
330     break;
331   case GEOMOp::OpColor:          // POPUP - COLOR
332     OnColor();
333     break;
334   case GEOMOp::OpTransparency:   // POPUP - TRANSPARENCY
335     OnTransparency();
336     break;
337   case GEOMOp::OpIncrTransparency: // SHORTCUT   - INCREASE TRANSPARENCY
338     OnChangeTransparency( true );
339     break;
340   case GEOMOp::OpDecrTransparency: // SHORTCUT   - DECREASE TRANSPARENCY
341     OnChangeTransparency( false );
342     break;
343   case GEOMOp::OpIsos:           // POPUP - ISOS
344     OnNbIsos();
345     break;
346   case GEOMOp::OpIncrNbIsos:     // SHORTCUT   - INCREASE NB ISOLINES
347     OnNbIsos( INCR );
348     break;
349   case GEOMOp::OpDecrNbIsos:     // SHORTCUT   - DECREASE NB ISOLINES
350     OnNbIsos( DECR );
351     break;
352   case GEOMOp::OpAutoColor:      // POPUP - AUTO COLOR
353     OnAutoColor();
354     break;
355   case GEOMOp::OpNoAutoColor:    // POPUP - DISABLE AUTO COLOR
356     OnDisableAutoColor();
357     break;
358   case GEOMOp::OpShowChildren:   // POPUP - SHOW CHILDREN
359   case GEOMOp::OpHideChildren:   // POPUP - HIDE CHILDREN
360     OnShowHideChildren( theCommandID == GEOMOp::OpShowChildren );
361     break;
362   case GEOMOp::OpPointMarker:    // POPUP - POINT MARKER
363     OnPointMarker();
364     break;
365   default:
366     SUIT_Session::session()->activeApplication()->putInfo(tr("GEOM_PRP_COMMAND").arg(theCommandID));
367     break;
368   }
369   return true;
370 }
371
372
373 //===============================================================================
374 // function : OnEditDelete()
375 // purpose  :
376 //===============================================================================
377 void GEOMToolsGUI::OnEditDelete()
378 {
379   SALOME_ListIO selected;
380   SalomeApp_Application* app =
381     dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
382   if ( !app )
383     return;
384
385   LightApp_SelectionMgr* aSelMgr = app->selectionMgr();
386   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
387   if ( !aSelMgr || !appStudy )
388     return;
389
390   // get selection
391   aSelMgr->selectedObjects( selected, "ObjectBrowser", false );
392   if ( selected.IsEmpty() )
393     return;
394
395   _PTR(Study) aStudy = appStudy->studyDS();
396   
397   // check if study is locked
398   if ( _PTR(AttributeStudyProperties)( aStudy->GetProperties() )->IsLocked() ) {
399     SUIT_MessageBox::warning( app->desktop(),
400                               tr("WRN_WARNING"),
401                               tr("WRN_STUDY_LOCKED") );
402     return; // study is locked
403   }
404   
405   // get GEOM component
406   CORBA::String_var geomIOR = app->orb()->object_to_string( GeometryGUI::GetGeomGen() );
407   QString geomComp = getParentComponent( aStudy->FindObjectIOR( geomIOR.in() ) );
408
409   // check each selected object: if belongs to GEOM, if not reference...
410   QMap<QString,QString> toBeDeleted;
411   QMap<QString,QString> allDeleted;
412   bool isComponentSelected = false;
413   for ( SALOME_ListIteratorOfListIO It( selected ); It.More(); It.Next() ) {
414     Handle(SALOME_InteractiveObject) anIObject = It.Value();
415     if ( !anIObject->hasEntry() )
416       continue; // invalid object
417     // ...
418     QString entry = anIObject->getEntry();
419     _PTR(SObject) obj = aStudy->FindObjectID( entry.toLatin1().data() );
420     // check parent component
421     QString parentComp = getParentComponent( obj );
422     if ( parentComp != geomComp )  {
423       SUIT_MessageBox::warning( app->desktop(),
424                                 QObject::tr("ERR_ERROR"),
425                                 QObject::tr("NON_GEOM_OBJECTS_SELECTED").arg( getGeometryGUI()->moduleName() ) );
426       return; // not GEOM object selected
427     }
428
429     ///////////////////////////////////////////////////////
430     // if GEOM component is selected, so skip other checks
431     if ( isComponentSelected ) continue; 
432     ///////////////////////////////////////////////////////
433         
434     // check if object is reference
435     _PTR(SObject) refobj;
436     if ( obj && obj->ReferencedObject( refobj ) ) {
437       // get the main object by reference IPAL 21354
438       obj = refobj;
439       entry = obj->GetID().c_str();
440     }
441     // ...
442     QString aName = obj->GetName().c_str();
443     if ( entry == geomComp ) {
444       // GEOM component is selected, skip other checks
445       isComponentSelected = true;
446       continue;
447     }
448     toBeDeleted.insert( entry, aName );
449     allDeleted.insert( entry, aName ); // skip GEOM component
450     // browse through all children recursively
451     _PTR(ChildIterator) it ( aStudy->NewChildIterator( obj ) );
452     for ( it->InitEx( true ); it->More(); it->Next() ) {
453       _PTR(SObject) child( it->Value() );
454       if ( child && child->ReferencedObject( refobj ) )
455         continue; // skip references
456       aName = child->GetName().c_str();
457       if ( !aName.isEmpty() )
458         allDeleted.insert( child->GetID().c_str(), aName );
459     }
460   }
461   
462   // is there is anything to delete?
463   if ( !isComponentSelected && allDeleted.count() <= 0 )
464     return; // nothing to delete
465
466   // show confirmation dialog box
467   GEOMToolsGUI_DeleteDlg dlg( app->desktop(), allDeleted, isComponentSelected );
468   if ( !dlg.exec() )
469     return; // operation is cancelled by user
470   
471   // get currently opened views
472   QList<SALOME_View*> views;
473   SALOME_View* view;
474   ViewManagerList vmans = app->viewManagers();
475   SUIT_ViewManager* vman;
476   foreach ( vman, vmans ) {
477     SUIT_ViewModel* vmod = vman->getViewModel();
478     view = dynamic_cast<SALOME_View*> ( vmod ); // must work for OCC and VTK views
479     if ( view )
480       views.append( view );
481   }
482   
483   _PTR(StudyBuilder) aStudyBuilder (aStudy->NewBuilder());
484   GEOM_Displayer* disp = new GEOM_Displayer( appStudy );
485   
486   if ( isComponentSelected ) {
487     // GEOM component is selected: delete all objects recursively
488     _PTR(SObject) comp = aStudy->FindObjectID( geomComp.toLatin1().data() );
489     if ( !comp )
490       return;
491     _PTR(ChildIterator) it ( aStudy->NewChildIterator( comp ) );
492     // remove top-level objects only
493     for ( it->InitEx( false ); it->More(); it->Next() ) {
494       _PTR(SObject) child( it->Value() );
495       // remove object from GEOM engine
496       removeObjectWithChildren( child, aStudy, views, disp );
497       // remove object from study
498       aStudyBuilder->RemoveObjectWithChildren( child );
499     }
500   }
501   else {
502     // GEOM component is not selected: check if selected objects are in use
503     if ( inUse( aStudy, geomComp, allDeleted ) ) {
504       SUIT_MessageBox::warning( app->desktop(),
505                                 QObject::tr("WRN_WARNING"),
506                                 QObject::tr("DEP_OBJECT") );
507       return; // object(s) in use
508     }
509     // ... and then delete all objects
510     QMap<QString, QString>::Iterator it;
511     for ( it = toBeDeleted.begin(); it != toBeDeleted.end(); ++it ) {
512       _PTR(SObject) obj ( aStudy->FindObjectID( it.key().toLatin1().data() ) );
513       // remove object from GEOM engine
514       removeObjectWithChildren( obj, aStudy, views, disp );
515       // remove objects from study
516       aStudyBuilder->RemoveObjectWithChildren( obj );
517     }
518   }
519   
520   selected.Clear();
521   aSelMgr->setSelectedObjects( selected );
522   getGeometryGUI()->updateObjBrowser();
523   app->updateActions(); //SRN: To update a Save button in the toolbar
524 }
525
526 //=====================================================================================
527 // function : Import
528 // purpose  : BRep, Iges, Step, ...
529 //=====================================================================================
530 bool GEOMToolsGUI::Import()
531 {
532   SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( getGeometryGUI()->getApp() );
533   if ( !app ) return false;
534
535   SalomeApp_Study* stud = dynamic_cast<SalomeApp_Study*> ( app->activeStudy() );
536   if ( !stud ) {
537     MESSAGE ( "FAILED to cast active study to SalomeApp_Study" );
538     return false;
539   }
540   _PTR(Study) aStudy = stud->studyDS();
541
542   // check if study is locked
543   bool aLocked = (_PTR(AttributeStudyProperties)(aStudy->GetProperties()))->IsLocked();
544   if ( aLocked ) {
545     SUIT_MessageBox::warning( app->desktop(),
546                               QObject::tr("WRN_WARNING"),
547                               QObject::tr("WRN_STUDY_LOCKED") );
548     return false;
549   }
550
551   // check if GEOM engine is available
552   GEOM::GEOM_Gen_var eng = GeometryGUI::GetGeomGen();
553   if ( CORBA::is_nil( eng ) ) {
554     SUIT_MessageBox::critical( app->desktop(),
555                                QObject::tr("WRN_WARNING"),
556                                QObject::tr( "GEOM Engine is not started" ) );
557     return false;
558   }
559
560   GEOM::GEOM_IInsertOperations_var aInsOp = eng->GetIInsertOperations( aStudy->StudyId() );
561   if ( aInsOp->_is_nil() )
562     return false;
563
564   // obtain a list of available import formats
565   FilterMap aMap;
566   GEOM::string_array_var aFormats, aPatterns;
567   aInsOp->ImportTranslators( aFormats, aPatterns );
568
569   for ( int i = 0, n = aFormats->length(); i < n; i++ )
570     aMap.insert( (char*)aPatterns[i], (char*)aFormats[i] );
571
572   // select files to be imported
573   QString fileType;
574   QStringList fileNames = getFileNames( app->desktop(), "", aMap,
575                                         tr( "GEOM_MEN_IMPORT" ), fileType, true );
576
577   // set Wait cursor
578   SUIT_OverrideCursor wc;
579
580   if ( fileNames.count() == 0 )
581     return false; // nothing selected, return
582
583   QStringList errors;
584
585   QList< GEOM::GEOM_Object_var > objsForDisplay;
586
587   
588   // iterate through all selected files
589
590   SUIT_MessageBox::StandardButton igesAnswer = SUIT_MessageBox::NoButton;
591   SUIT_MessageBox::StandardButton acisAnswer = SUIT_MessageBox::NoButton;
592
593   for ( int i = 0; i < fileNames.count(); i++ ) {
594     QString fileName = fileNames[i];
595
596     if ( fileName.isEmpty() )
597       continue;
598
599     QString aCurrentType;
600     if ( fileType.isEmpty() ) {
601       // file type is not defined, try to detect
602       QString ext = QFileInfo( fileName ).suffix().toUpper();
603       QRegExp re( "\\*\\.(\\w+)" );
604       for ( FilterMap::const_iterator it = aMap.begin(); 
605             it != aMap.end() && aCurrentType.isEmpty(); ++it ) {
606         int pos = 0;
607         while ( re.indexIn( it.key(), pos ) >= 0 ) {
608           QString f = re.cap(1).trimmed().toUpper();
609           if ( ext == f ) { aCurrentType = it.value(); break; }
610           pos = re.pos() + re.cap(1).length() + 2;
611         }
612       }
613     }
614     else {
615       aCurrentType = fileType;
616     }
617
618     if ( aCurrentType.isEmpty() ) {
619       errors.append( QString( "%1 : %2" ).arg( fileName ).arg( tr( "GEOM_UNSUPPORTED_TYPE" ) ) );
620       continue;
621     }
622
623     GEOM_Operation* anOp = new GEOM_Operation( app, aInsOp.in() );
624     try {
625       app->putInfo( tr( "GEOM_PRP_LOADING" ).arg( SUIT_Tools::file( fileName, /*withExten=*/true ) ) );
626       anOp->start();
627
628       CORBA::String_var fileN = fileName.toLatin1().constData();
629       CORBA::String_var fileT = aCurrentType.toLatin1().constData();
630
631       // skl 29.05.2009
632       if ( aCurrentType == "IGES" ) {
633         GEOM::GEOM_Object_var anObj = aInsOp->Import( fileN, "IGES_UNIT" );
634         bool needConvert = false;
635         TCollection_AsciiString aUnitName = aInsOp->GetErrorCode();
636         if ( aUnitName.SubString( 1, 4 ) == "UNIT" )
637           needConvert = aUnitName.SubString( 6, aUnitName.Length() ) != "M";
638
639         if ( needConvert ) {
640           if ( igesAnswer == SUIT_MessageBox::NoToAll ) {
641             // converting for all files is already approved
642             fileT = "IGES_SCALE";
643           }
644           else if ( igesAnswer != SUIT_MessageBox::YesToAll ) {
645             SUIT_MessageBox::StandardButtons btns = SUIT_MessageBox::Yes | SUIT_MessageBox::No;
646             if ( i < fileNames.count()-1 ) btns = btns | SUIT_MessageBox::YesToAll | SUIT_MessageBox::NoToAll;
647             igesAnswer = SUIT_MessageBox::question( app->desktop(),
648                                                     "Question",//tr("WRN_WARNING"),
649                                                     tr("GEOM_SCALE_DIMENSIONS"),
650                                                     btns | SUIT_MessageBox::Cancel,
651                                                     SUIT_MessageBox::No );
652             switch ( igesAnswer ) {
653             case SUIT_MessageBox::Cancel:
654               return false;                // cancel (break) import operation
655             case SUIT_MessageBox::Yes:
656             case SUIT_MessageBox::YesToAll:
657               break;                       // scaling is confirmed
658             case SUIT_MessageBox::No:
659             case SUIT_MessageBox::NoAll:
660               fileT = "IGES_SCALE";
661             default:
662               break;                       // scaling is rejected
663             } // switch ( igesAnswer )
664           } // if ( igeAnswer != NoToAll )
665         } // if ( needConvert )
666       } // if ( aCurrentType == "IGES" )
667       else if ( aCurrentType == "ACIS" ) {
668         if ( acisAnswer != SUIT_MessageBox::YesToAll && acisAnswer != SUIT_MessageBox::NoToAll ) {
669           SUIT_MessageBox::StandardButtons btns = SUIT_MessageBox::Yes | SUIT_MessageBox::No;
670           if ( i < fileNames.count()-1 ) btns = btns | SUIT_MessageBox::YesToAll | SUIT_MessageBox::NoToAll;
671           acisAnswer = SUIT_MessageBox::question( app->desktop(),
672                                                   "Question",//tr("WRN_WARNING"),
673                                                   tr("GEOM_PUBLISH_NAMED_SHAPES"),
674                                                   btns | SUIT_MessageBox::Cancel,
675                                                   SUIT_MessageBox::No );
676           if ( acisAnswer == SUIT_MessageBox::Cancel )
677             return false; // cancel (break) import operation
678         } // if ( acisAnswer != YesToAll && acisAnswer != NoToAll )
679       } // else if ( aCurrentType == "ACIS" )
680       
681       GEOM::GEOM_Object_var anObj = aInsOp->Import( fileN, fileT );
682
683       if ( !anObj->_is_nil() && aInsOp->IsDone() ) {
684         QString aPublishObjName = 
685           GEOMBase::GetDefaultName( SUIT_Tools::file( fileName, /*withExten=*/true ) );
686         
687         SALOMEDS::Study_var aDSStudy = GeometryGUI::ClientStudyToStudy( aStudy );
688         GeometryGUI::GetGeomGen()->PublishInStudy( aDSStudy,
689                                                    SALOMEDS::SObject::_nil(),
690                                                    anObj,
691                                                    aPublishObjName.toLatin1().constData() );
692         
693         objsForDisplay.append( anObj );
694         
695         if ( aCurrentType == "ACIS" ) {
696           if ( acisAnswer == SUIT_MessageBox::Yes || acisAnswer == SUIT_MessageBox::YesToAll )
697             GeometryGUI::GetGeomGen()->PublishNamedShapesInStudy( aDSStudy, anObj );
698         }
699
700         anOp->commit();
701       }
702       else {
703         anOp->abort();
704         errors.append( QString( "%1 : %2" ).arg( fileName ).arg( aInsOp->GetErrorCode() ) );
705       }
706     }
707     catch( const SALOME::SALOME_Exception& S_ex ) {
708       anOp->abort();
709       errors.append( QString( "%1 : %2" ).arg( fileName ).arg( tr( "GEOM_UNKNOWN_IMPORT_ERROR" ) ) );
710     }
711   }
712
713   // update object browser
714   getGeometryGUI()->updateObjBrowser( true );
715
716   // display imported model (if only one file is selected)
717   if ( objsForDisplay.count() == 1 )
718     GEOM_Displayer( stud ).Display( objsForDisplay[0].in() );
719
720   if ( errors.count() > 0 ) {
721     SUIT_MessageBox::critical( app->desktop(),
722                                QObject::tr( "GEOM_ERROR" ),
723                                QObject::tr( "GEOM_IMPORT_ERRORS" ) + "\n" + errors.join( "\n" ) );
724   }
725
726   app->updateActions(); //SRN: To update a Save button in the toolbar
727
728   return objsForDisplay.count() > 0;
729 }
730
731
732 //=====================================================================================
733 // function : Export
734 // purpose  : BRep, Iges, Step
735 //=====================================================================================
736 bool GEOMToolsGUI::Export()
737 {
738   SalomeApp_Application* app = getGeometryGUI()->getApp();
739   if (!app) return false;
740
741   SalomeApp_Study* stud = dynamic_cast<SalomeApp_Study*> ( app->activeStudy() );
742   if ( !stud ) {
743     MESSAGE ( "FAILED to cast active study to SalomeApp_Study" );
744     return false;
745   }
746   _PTR(Study) aStudy = stud->studyDS();
747
748   GEOM::GEOM_Gen_var eng = GeometryGUI::GetGeomGen();
749   if ( CORBA::is_nil( eng ) ) {
750     SUIT_MessageBox::critical( app->desktop(),
751                                QObject::tr("WRN_WARNING"),
752                                QObject::tr( "GEOM Engine is not started" ) );
753     return false;
754   }
755
756   GEOM::GEOM_IInsertOperations_var aInsOp = eng->GetIInsertOperations( aStudy->StudyId() );
757   if ( aInsOp->_is_nil() )
758     return false;
759
760   // Obtain a list of available export formats
761   FilterMap aMap;
762   QStringList filters;
763   GEOM::string_array_var aFormats, aPatterns;
764   aInsOp->ExportTranslators( aFormats, aPatterns );
765   for ( int i = 0, n = aFormats->length(); i < n; i++ ) {
766     aMap.insert( (char*)aPatterns[i], (char*)aFormats[i] );
767     filters.push_back( (char*)aPatterns[i] );
768   }
769
770   // Get selected objects
771   LightApp_SelectionMgr* sm = app->selectionMgr();
772   if ( !sm )
773     return false;
774
775   SALOME_ListIO selectedObjects;
776   sm->selectedObjects( selectedObjects );
777   bool appropriateObj = false;
778
779   SALOME_ListIteratorOfListIO It( selectedObjects );
780   for(;It.More();It.Next()) {
781     Handle(SALOME_InteractiveObject) IObject = It.Value();
782     Standard_Boolean found;
783     GEOM::GEOM_Object_var anObj = GEOMBase::ConvertIOinGEOMObject(IObject, found);
784
785     if ( !found || anObj->_is_nil() )
786       continue;
787
788     QString fileType;
789     QString file = getFileName(app->desktop(), QString( IObject->getName() ), aMap, filters,
790                                tr("GEOM_MEN_EXPORT"), false, fileType, true);
791
792     // User has pressed "Cancel" --> stop the operation
793     if ( file.isEmpty() || fileType.isEmpty() )
794       return false;
795
796     GEOM_Operation* anOp = new GEOM_Operation( app, aInsOp.in() );
797     try {
798       SUIT_OverrideCursor wc;
799
800       app->putInfo( tr("GEOM_PRP_EXPORT").arg(SUIT_Tools::file( file, /*withExten=*/true )) );
801
802       anOp->start();
803
804
805       aInsOp->Export( anObj, file.toStdString().c_str(), fileType.toLatin1().constData() );
806
807       if ( aInsOp->IsDone() )
808         anOp->commit();
809       else
810         {
811           anOp->abort();
812           wc.suspend();
813           SUIT_MessageBox::critical( app->desktop(),
814                                      QObject::tr( "GEOM_ERROR" ),
815                                      QObject::tr("GEOM_PRP_ABORT") + "\n" + QString( aInsOp->GetErrorCode() ) );
816           return false;
817         }
818     }
819     catch (const SALOME::SALOME_Exception& S_ex) {
820       //QtCatchCorbaException(S_ex);
821       anOp->abort();
822       return false;
823     }
824     appropriateObj = true;
825   }
826
827   if ( !appropriateObj )
828     SUIT_MessageBox::warning( app->desktop(),
829                               QObject::tr("WRN_WARNING"),
830                               QObject::tr("GEOM_WRN_NO_APPROPRIATE_SELECTION") );
831   return true;
832 }
833
834 //=====================================================================================
835 // function : RemoveObjectWithChildren
836 // purpose  : used by OnEditDelete() method
837 //=====================================================================================
838 void GEOMToolsGUI::removeObjectWithChildren(_PTR(SObject) obj,
839                                             _PTR(Study) aStudy,
840                                             QList<SALOME_View*> views,
841                                             GEOM_Displayer* disp)
842 {
843   // iterate through all children of obj
844   for (_PTR(ChildIterator) it (aStudy->NewChildIterator(obj)); it->More(); it->Next()) {
845     _PTR(SObject) child (it->Value());
846     removeObjectWithChildren(child, aStudy, views, disp);
847   }
848
849   // erase object and remove it from engine
850   _PTR(GenericAttribute) anAttr;
851   if (obj->FindAttribute(anAttr, "AttributeIOR")) {
852     _PTR(AttributeIOR) anIOR (anAttr);
853
854     // Delete shape in Client
855     const TCollection_AsciiString ASCIor ((char*)anIOR->Value().c_str());
856     getGeometryGUI()->GetShapeReader().RemoveShapeFromBuffer(ASCIor);
857
858     CORBA::Object_var corbaObj = GeometryGUI::ClientSObjectToObject(obj);
859     GEOM::GEOM_Object_var geomObj = GEOM::GEOM_Object::_narrow( corbaObj );
860     if (!CORBA::is_nil(geomObj)) {
861       // Erase graphical object
862       QListIterator<SALOME_View*> it( views );
863       while ( it.hasNext() )
864         if ( SALOME_View* view = it.next() )
865           disp->Erase(geomObj, true, view);
866       
867       // Remove object from Engine
868       // We can't directly remove object from engine. All we can do is to unpublish the object
869       // from the study. Another client could be using the object.
870       // Unpublishing is done just after in aStudyBuilder->RemoveObjectWithChildren( child );
871       //GeometryGUI::GetGeomGen()->RemoveObject( geomObj );
872     }
873   }
874 }
875
876 //=================================================================================
877 // function : deactivate()
878 // purpose  : Called when GEOM component is deactivated
879 //=================================================================================
880 void GEOMToolsGUI::deactivate()
881 {
882   SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
883   if ( app ) {
884     SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
885     GEOM_Displayer aDisp (appStudy);
886     aDisp.GlobalSelection();
887     getGeometryGUI()->setLocalSelectionMode(GEOM_ALLOBJECTS);
888   }
889 }
890
891 //=====================================================================================
892 // EXPORTED METHODS
893 //=====================================================================================
894 extern "C"
895 {
896 #ifdef WIN32
897   __declspec( dllexport )
898 #endif
899   GEOMGUI* GetLibGUI( GeometryGUI* parent )
900   {
901     return new GEOMToolsGUI( parent );
902   }
903 }