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