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