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