Salome HOME
Remove obsolete files
[modules/geom.git] / src / GEOMToolsGUI / GEOMToolsGUI.cxx
1 //  GEOM GEOMGUI : GUI for Geometry component
2 //
3 //  Copyright (C) 2003  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 //
24 //  File   : GEOMBase_Tools.cxx
25 //  Author : Damien COQUERET
26 //  Module : GEOM
27 //  $Header$
28
29 #include "GEOMToolsGUI.h"
30 #include "GEOMToolsGUI_DeleteDlg.h"
31
32 #include "GeometryGUI.h"
33 #include "GEOM_Actor.h"
34 #include "GEOMBase.h"
35
36 #include "GEOM_Operation.h"
37 #include "GEOM_Displayer.h"
38
39 #include <SUIT_Session.h>
40 #include <SUIT_Application.h>
41 #include <SUIT_OverrideCursor.h>
42 #include <SUIT_MessageBox.h>
43 #include <SUIT_Tools.h>
44 #include <SUIT_FileDlg.h>
45 #include <SUIT_Desktop.h>
46 #include <SUIT_ViewModel.h>
47
48 #include <SalomeApp_Application.h>
49 #include <SalomeApp_Study.h>
50 #include <LightApp_SelectionMgr.h>
51 #include <GEOMImpl_Types.hxx>
52
53 #include <SALOME_ListIteratorOfListIO.hxx>
54 #include <SALOME_Prs.h>
55
56 #include "utilities.h"
57
58 // QT Includes
59 #include <qapplication.h>
60 #include <qmap.h>
61 #include <qregexp.h>
62
63 // OCCT Includes
64 #include <TCollection_AsciiString.hxx>
65
66 using namespace std;
67
68 typedef QMap<QString, QString> FilterMap;
69 static QString lastUsedFilter;
70
71 //=======================================================================
72 // function : getFileName
73 // purpose  : Selection of a file name for Import/Export. Returns also
74 //            the selected file type code through <filter> argument.
75 //=======================================================================
76 static QString getFileName( QWidget*           parent,
77                             const QString&     initial,
78                             const FilterMap&   filterMap,
79                             const QStringList  filters,
80                             const QString&     caption,
81                             bool               open,
82                             QString&           format,
83                             bool               showCurrentDirInitially = false)
84 {
85   //QStringList filters;
86   QString aBrepFilter;
87   for ( FilterMap::const_iterator it = filterMap.begin(); it != filterMap.end(); ++it ) {
88     //filters.push_back( it.key() );
89
90     if (it.key().contains("BREP", false)) {
91       aBrepFilter = it.key();
92     }
93   }
94
95   SUIT_FileDlg* fd = new SUIT_FileDlg( parent, open, true, true );
96   if ( !caption.isEmpty() )
97     fd->setCaption( caption );
98
99   if ( !initial.isEmpty() )
100     fd->setSelection( initial );
101   
102   if ( showCurrentDirInitially && SUIT_FileDlg::getLastVisitedPath().isEmpty() )
103     fd->setDir( QDir::currentDirPath() );
104
105   fd->setFilters( filters );
106
107   if ( !lastUsedFilter.isEmpty() && filterMap.contains( lastUsedFilter ) )
108     fd->setSelectedFilter( lastUsedFilter );
109   else {
110     if (!aBrepFilter.isEmpty()) {
111       fd->setSelectedFilter(aBrepFilter);
112     }
113   }
114
115   fd->exec();
116   QString filename = fd->selectedFile();
117   format = filterMap[fd->selectedFilter()];
118   lastUsedFilter = fd->selectedFilter();
119   delete fd;
120   qApp->processEvents();
121   return filename;
122 }
123
124 //=======================================================================
125 // function : getFileNames
126 // purpose  : Select list of files for Import operation. Returns also
127 //            the selected file type code through <format> argument.
128 //=======================================================================
129 static QStringList getFileNames( QWidget*           parent,
130                                  const QString&     initial,
131                                  const FilterMap&   filterMap,
132                                  const QString&     caption,
133                                  QString&           format,
134                                  bool               showCurrentDirInitially = false)
135 {
136   QString aBrepFilter;
137   QStringList allFilters;
138   QStringList filters;
139   QRegExp re( "\\((.*)\\)" );
140   re.setMinimal( true );
141   for ( FilterMap::const_iterator it = filterMap.begin(); it != filterMap.end(); ++it ) {
142     if ( it.data().contains( "BREP", false ) && aBrepFilter.isEmpty() )
143       aBrepFilter = it.key();
144     filters.append( it.key() );
145     int pos = 0;
146     while ( re.search( it.key(), pos ) >= 0 ) {
147       QString f = re.cap(1);
148       pos = re.pos() + f.length() + 2;
149       allFilters.append( f.simplifyWhiteSpace() );
150     }
151   }
152   filters.append( QObject::tr( "GEOM_ALL_IMPORT_FILES" ).arg( allFilters.join( " " ) ) );
153   
154   SUIT_FileDlg fd( parent, true, true, true );
155   fd.setMode( SUIT_FileDlg::ExistingFiles );     
156   if ( !caption.isEmpty() )
157     fd.setCaption( caption );
158   if ( !initial.isEmpty() )
159     fd.setSelection( initial );
160   
161   if ( showCurrentDirInitially && SUIT_FileDlg::getLastVisitedPath().isEmpty() )
162     fd.setDir( QDir::currentDirPath() );
163   
164   fd.setFilters( filters );
165   
166   if ( !lastUsedFilter.isEmpty() && filterMap.contains( lastUsedFilter ) )
167     fd.setSelectedFilter( lastUsedFilter );
168   else if ( !aBrepFilter.isEmpty() )
169     fd.setSelectedFilter( aBrepFilter );
170
171   QStringList filenames;
172   if ( fd.exec() ) {
173     filenames = fd.selectedFiles();
174     format = filterMap.contains( fd.selectedFilter() ) ? filterMap[ fd.selectedFilter() ] : QString();
175     lastUsedFilter = fd.selectedFilter();
176   }
177   qApp->processEvents();
178   return filenames;
179 }
180
181 //=======================================================================
182 // function : getParentComponent
183 // purpose  : Get object's parent component entry
184 //=======================================================================
185 static QString getParentComponent( _PTR( SObject ) obj )
186 {
187   if ( obj ) {
188     _PTR(SComponent) comp = obj->GetFatherComponent();
189     if ( comp )
190       return QString( comp->GetID().c_str() );
191   }
192   return QString();
193 }
194
195 //=====================================================================================
196 // function : inUse
197 // purpose  : check if the object(s) passed as the the second arguments are used
198 //            by the other objects in the study
199 //=====================================================================================
200 static bool inUse( _PTR(Study) study, const QString& component, const QMap<QString,QString>& objects )
201 {
202   _PTR(SObject) comp = study->FindObjectID( component.latin1() );
203   if ( !comp )
204     return false;
205
206   // collect all GEOM objects being deleted
207   QMap<QString, GEOM::GEOM_Object_var> gobjects;
208   QMap<QString, QString>::ConstIterator oit;
209   list<_PTR(SObject)> aSelectedSO;
210   for ( oit = objects.begin(); oit != objects.end(); ++oit ) {
211     _PTR(SObject) so = study->FindObjectID( oit.key().latin1() );
212     if ( !so )
213       continue;
214     aSelectedSO.push_back(so);
215     CORBA::Object_var corbaObj_rem = GeometryGUI::ClientSObjectToObject( so );
216     GEOM::GEOM_Object_var geomObj_rem = GEOM::GEOM_Object::_narrow( corbaObj_rem );
217     if( CORBA::is_nil( geomObj_rem ) ) 
218       continue;
219     gobjects.insert( oit.key(), geomObj_rem );
220   }
221
222   // Search References with other Modules
223   list< _PTR(SObject) >::iterator itSO = aSelectedSO.begin();
224   for ( ; itSO != aSelectedSO.end(); ++itSO ) {
225     std::vector<_PTR(SObject)> aReferences = study->FindDependances( *itSO  );    
226     int aRefLength = aReferences.size();
227     if (aRefLength) {
228       for (int i = 0; i < aRefLength; i++) {
229         _PTR(SObject) firstSO( aReferences[i] );
230         _PTR(SComponent) aComponent = firstSO->GetFatherComponent();
231         QString type = aComponent->ComponentDataType();
232         if ( type == "SMESH" )
233           return true;
234       }
235     }
236   }
237
238   // browse through all GEOM data tree
239   _PTR(ChildIterator) it ( study->NewChildIterator( comp ) );
240   for ( it->InitEx( true ); it->More(); it->Next() ) {
241     _PTR(SObject) child( it->Value() );
242     CORBA::Object_var corbaObj = GeometryGUI::ClientSObjectToObject( child );
243     GEOM::GEOM_Object_var geomObj = GEOM::GEOM_Object::_narrow( corbaObj );
244     if( CORBA::is_nil( geomObj ) ) 
245       continue;
246
247     GEOM::ListOfGO_var list = geomObj->GetDependency();
248     if( list->length() == 0 ) 
249       continue;
250
251     for( int i = 0; i < list->length(); i++ ) {
252       bool depends = false;
253       bool deleted = false;
254       QMap<QString, GEOM::GEOM_Object_var>::Iterator git;
255       for ( git = gobjects.begin(); git != gobjects.end() && ( !depends || !deleted ); ++git ) {
256         depends = depends || list[i]->_is_equivalent( *git );
257         deleted = deleted || git.key() == child->GetID().c_str() ;//geomObj->_is_equivalent( *git );
258       }
259       if ( depends && !deleted )
260         return true;
261     }
262   }
263   return false;
264 }
265
266
267 //=======================================================================
268 // function : GEOMToolsGUI()
269 // purpose  : Constructor
270 //=======================================================================
271 GEOMToolsGUI::GEOMToolsGUI( GeometryGUI* parent )
272 : GEOMGUI( parent )
273 {
274 }
275
276
277 //=======================================================================
278 // function : ~GEOMToolsGUI()
279 // purpose  : Destructor
280 //=======================================================================
281 GEOMToolsGUI::~GEOMToolsGUI()
282 {
283 }
284
285
286 //=======================================================================
287 // function : OnGUIEvent()
288 // purpose  :
289 //=======================================================================
290 bool GEOMToolsGUI::OnGUIEvent(int theCommandID, SUIT_Desktop* parent)
291 {
292   getGeometryGUI()->EmitSignalDeactivateDialog();
293
294   switch (theCommandID)
295     {
296     case 31: // COPY
297       {
298         OnEditCopy();
299         break;
300       }
301     case 33: // DELETE
302       {
303         OnEditDelete();
304         break;
305       }
306     case 111: // IMPORT BREP
307     case 112: // IMPORT IGES
308     case 113: // IMPORT STEP
309       {
310         Import();
311         break;
312       }
313     case 121: // EXPORT BREP
314     case 122: // EXPORT IGES
315     case 123: // EXPORT STEP
316       {
317         Export();
318         break;
319       }
320     case 2171: // POPUP VIEWER - SELECT ONLY - VERTEX
321       {
322         OnSelectOnly( GEOM_POINT );
323         break;
324       }
325     case 2172: // POPUP VIEWER - SELECT ONLY - EDGE
326       {
327         OnSelectOnly( GEOM_EDGE );
328         break;
329       }
330     case 2173: // POPUP VIEWER - SELECT ONLY - WIRE
331       {
332         OnSelectOnly( GEOM_WIRE );
333         break;
334       }
335     case 2174: // POPUP VIEWER - SELECT ONLY - FACE
336       {
337         OnSelectOnly( GEOM_FACE );
338         break;
339       }
340     case 2175: // POPUP VIEWER - SELECT ONLY - SHELL
341       {
342         OnSelectOnly( GEOM_SHELL );
343         break;
344       }
345     case 2176: // POPUP VIEWER - SELECT ONLY - SOLID
346       {
347         OnSelectOnly( GEOM_SOLID );
348         break;
349       }
350     case 2177: // POPUP VIEWER - SELECT ONLY - COMPOUND
351       {
352         OnSelectOnly( GEOM_COMPOUND );
353         break;
354       }
355     case 2178: // POPUP VIEWER - SELECT ONLY - SELECT ALL
356       {
357         OnSelectOnly( GEOM_ALLOBJECTS );
358         break;
359       }    
360     case 411: // SETTINGS - ADD IN STUDY
361       {
362         // SAN -- TO BE REMOVED !!!
363         break;
364       }
365     case 412: // SETTINGS - SHADING COLOR
366       {
367         OnSettingsColor();
368         break;
369       }
370     case 804: // ADD IN STUDY - POPUP VIEWER
371       {
372         // SAN -- TO BE REMOVED !!!!
373         break;
374       }
375     case 901: // RENAME
376       {
377         OnRename();
378         break;
379       }
380     case 5103: // CHECK GEOMETRY
381       {
382         OnCheckGeometry();
383         break;
384       }
385     case 8032: // COLOR - POPUP VIEWER
386       {
387         OnColor();
388         break;
389       }
390     case 8033: // TRANSPARENCY - POPUP VIEWER
391       {
392         OnTransparency();
393         break;
394       }
395     case 8034: // ISOS - POPUP VIEWER
396       {
397         OnNbIsos();
398         break;
399       }
400     case 8035: // AUTO COLOR - POPUP VIEWER
401       {
402         OnAutoColor();
403         break;
404       }
405     case 8036: // DISABLE AUTO COLOR - POPUP VIEWER
406       {
407         OnDisableAutoColor();
408         break;
409       }
410     case 9024 : // OPEN - OBJBROSER POPUP
411       {
412         OnOpen();
413         break;
414       }
415     default:
416       {
417         SUIT_Session::session()->activeApplication()->putInfo(tr("GEOM_PRP_COMMAND").arg(theCommandID));
418         break;
419       }
420     }
421   return true;
422 }
423
424
425 //===============================================================================
426 // function : OnEditDelete()
427 // purpose  :
428 //===============================================================================
429 void GEOMToolsGUI::OnEditDelete()
430 {
431   SALOME_ListIO selected;
432   SalomeApp_Application* app =
433     dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
434   if ( !app )
435     return;
436
437   LightApp_SelectionMgr* aSelMgr = app->selectionMgr();
438   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
439   if ( !aSelMgr || !appStudy )
440     return;
441
442   // get selection
443   aSelMgr->selectedObjects( selected, "ObjectBrowser", false );
444   if ( selected.IsEmpty() )
445     return;
446
447   _PTR(Study) aStudy = appStudy->studyDS();
448   
449   // check if study is locked
450   if ( _PTR(AttributeStudyProperties)( aStudy->GetProperties() )->IsLocked() ) {
451     SUIT_MessageBox::warn1( app->desktop(),
452                             tr("WRN_WARNING"),
453                             tr("WRN_STUDY_LOCKED"),
454                             tr("BUT_OK") );
455     return; // study is locked
456   }
457   
458   // get GEOM component
459   CORBA::String_var geomIOR = app->orb()->object_to_string( GeometryGUI::GetGeomGen() );
460   QString geomComp = getParentComponent( aStudy->FindObjectIOR( geomIOR.in() ) );
461
462   // check each selected object: if belongs to GEOM, if not reference...
463   QMap<QString,QString> toBeDeleted;
464   QMap<QString,QString> allDeleted;
465   bool isComponentSelected = false;
466   for ( SALOME_ListIteratorOfListIO It( selected ); It.More(); It.Next() ) {
467     Handle(SALOME_InteractiveObject) anIObject = It.Value();
468     if ( !anIObject->hasEntry() )
469       continue; // invalid object
470     // ...
471     QString entry = anIObject->getEntry();
472     _PTR(SObject) obj = aStudy->FindObjectID( entry.latin1() );
473     // check parent component
474     QString parentComp = getParentComponent( obj );
475     if ( parentComp != geomComp )  {
476       SUIT_MessageBox::warn1( app->desktop(),
477                               QObject::tr("ERR_ERROR"),
478                               QObject::tr("NON_GEOM_OBJECTS_SELECTED").arg( getGeometryGUI()->moduleName() ),
479                               QObject::tr("BUT_OK") );
480       return; // not GEOM object selected
481     }
482
483     ///////////////////////////////////////////////////////
484     // if GEOM component is selected, so skip other checks
485     if ( isComponentSelected ) continue; 
486     ///////////////////////////////////////////////////////
487         
488     // check if object is reference
489     _PTR(SObject) refobj;
490     if ( obj && obj->ReferencedObject( refobj ) )
491       continue; // skip references
492     // ...
493     QString aName = obj->GetName().c_str();
494     if ( entry == geomComp ) {
495       // GEOM component is selected, skip other checks
496       isComponentSelected = true;
497       continue;
498     }
499     toBeDeleted.insert( entry, aName );
500     allDeleted.insert( entry, aName ); // skip GEOM component
501     // browse through all children recursively
502     _PTR(ChildIterator) it ( aStudy->NewChildIterator( obj ) );
503     for ( it->InitEx( true ); it->More(); it->Next() ) {
504       _PTR(SObject) child( it->Value() );
505       if ( child && child->ReferencedObject( refobj ) )
506         continue; // skip references
507       aName = child->GetName().c_str();
508       if ( !aName.isEmpty() )
509         allDeleted.insert( child->GetID().c_str(), aName );
510     }
511   }
512   
513   // is there is anything to delete?
514   if ( !isComponentSelected && allDeleted.count() <= 0 )
515     return; // nothing to delete
516
517   // show confirmation dialog box
518   GEOMToolsGUI_DeleteDlg dlg( app->desktop(), allDeleted, isComponentSelected );
519   if ( !dlg.exec() )
520     return; // operation is cancelled by user
521   
522   // get currently opened views
523   QPtrList<SALOME_View> views;
524   SALOME_View* view;
525   ViewManagerList vmans = app->viewManagers();
526   SUIT_ViewManager* vman;
527   for ( vman = vmans.first(); vman; vman = vmans.next() ) {
528     SUIT_ViewModel* vmod = vman->getViewModel();
529     view = dynamic_cast<SALOME_View*> ( vmod ); // must work for OCC and VTK views
530     if ( view )
531       views.append( view );
532   }
533   
534   _PTR(StudyBuilder) aStudyBuilder (aStudy->NewBuilder());
535   GEOM_Displayer* disp = new GEOM_Displayer( appStudy );
536   
537   if ( isComponentSelected ) {
538     // GEOM component is selected: delete all objects recursively
539     _PTR(SObject) comp = aStudy->FindObjectID( geomComp.latin1() );
540     if ( !comp )
541       return;
542     _PTR(ChildIterator) it ( aStudy->NewChildIterator( comp ) );
543     // remove top-level objects only
544     for ( it->InitEx( false ); it->More(); it->Next() ) {
545       _PTR(SObject) child( it->Value() );
546       // remove object from GEOM engine
547       removeObjectWithChildren( child, aStudy, views, disp );
548       // remove object from study
549       aStudyBuilder->RemoveObjectWithChildren( child );
550     }
551   }
552   else {
553     // GEOM component is not selected: check if selected objects are in use
554     if ( inUse( aStudy, geomComp, allDeleted ) ) {
555       SUIT_MessageBox::warn1( app->desktop(),
556                               QObject::tr("WRN_WARNING"),
557                               QObject::tr("DEP_OBJECT"),
558                               QObject::tr("BUT_OK") );
559       return; // object(s) in use
560     }
561     // ... and then delete all objects
562     QMap<QString, QString>::Iterator it;
563     for ( it = toBeDeleted.begin(); it != toBeDeleted.end(); ++it ) {
564       _PTR(SObject) obj ( aStudy->FindObjectID( it.key().latin1() ) );
565       // remove object from GEOM engine
566       removeObjectWithChildren( obj, aStudy, views, disp );
567       // remove objects from study
568       aStudyBuilder->RemoveObjectWithChildren( obj );
569     }
570   }
571   
572   selected.Clear();
573   aSelMgr->setSelectedObjects( selected );
574   getGeometryGUI()->updateObjBrowser();
575   app->updateActions(); //SRN: To update a Save button in the toolbar
576 }
577
578
579 //==============================================================================
580 // function : OnEditCopy()
581 // purpose  :
582 //==============================================================================
583 void GEOMToolsGUI::OnEditCopy()
584 {
585 /*
586  SALOME_Selection* Sel = SALOME_Selection::Selection(QAD_Application::getDesktop()->getActiveStudy()->getSelection() );
587   GEOM::string_array_var listIOR = new GEOM::string_array;
588
589   const SALOME_ListIO& List = Sel->StoredIObjects();
590
591   myGeomBase->ConvertListOfIOInListOfIOR(List, listIOR);
592
593   Sel->ClearIObjects();
594
595   SALOMEDS::Study_var aStudy = QAD_Application::getDesktop()->getActiveStudy()->getStudyDocument();
596   int aStudyID = aStudy->StudyId();
597
598   for (unsigned int ind = 0; ind < listIOR->length();ind++) {
599     GEOM::GEOM_Object_var aShapeInit = myGeom->GetIORFromString(listIOR[ind]);
600     try {
601       GEOM::GEOM_IInsertOperations_var IOp =  myGeom->GetIInsertOperations(aStudyID);
602       GEOM::GEOM_Object_var result = IOp->MakeCopy(aShapeInit);
603       myGeomBase->Display(result);
604     }
605     catch  (const SALOME::SALOME_Exception& S_ex) {
606       QtCatchCorbaException(S_ex);
607     }
608   }
609
610   QAD_Application::getDesktop()->putInfo(tr("GEOM_PRP_READY"));
611 */
612 }
613
614
615 //=====================================================================================
616 // function : Import
617 // purpose  : BRep, Iges, Step
618 //=====================================================================================
619 bool GEOMToolsGUI::Import()
620 {
621   SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( getGeometryGUI()->getApp() );
622   if (! app) return false;
623
624   SalomeApp_Study* stud = dynamic_cast<SalomeApp_Study*> ( app->activeStudy() );
625   if ( !stud ) {
626     MESSAGE ( "FAILED to cast active study to SalomeApp_Study" );
627     return false;
628   }
629   _PTR(Study) aStudy = stud->studyDS();
630
631   // check if study is locked
632   bool aLocked = (_PTR(AttributeStudyProperties)(aStudy->GetProperties()))->IsLocked();
633   if ( aLocked ) {
634     SUIT_MessageBox::warn1 ( app->desktop(),
635                              QObject::tr("WRN_WARNING"),
636                              QObject::tr("WRN_STUDY_LOCKED"),
637                              QObject::tr("BUT_OK") );
638     return false;
639   }
640
641   // check if GEOM engine is available
642   GEOM::GEOM_Gen_var eng = GeometryGUI::GetGeomGen();
643   if ( CORBA::is_nil( eng ) ) {
644     SUIT_MessageBox::error1( app->desktop(),
645                              QObject::tr("WRN_WARNING"),
646                              QObject::tr( "GEOM Engine is not started" ),
647                              QObject::tr("BUT_OK") );
648     return false;
649   }
650
651   GEOM::GEOM_IInsertOperations_var aInsOp = eng->GetIInsertOperations( aStudy->StudyId() );
652   if ( aInsOp->_is_nil() )
653     return false;
654
655   // obtain a list of available import formats
656   FilterMap aMap;
657   GEOM::string_array_var aFormats, aPatterns;
658   aInsOp->ImportTranslators( aFormats, aPatterns );
659
660   for ( int i = 0, n = aFormats->length(); i < n; i++ )
661     aMap.insert( (char*)aPatterns[i], (char*)aFormats[i] );
662
663   // select files to be imported
664   QString fileType;
665   QStringList fileNames = getFileNames( app->desktop(), "", aMap,
666                                         tr( "GEOM_MEN_IMPORT" ), fileType, true );
667
668   // set Wait cursor
669   SUIT_OverrideCursor wc;
670
671   if ( fileNames.count() == 0 )
672     return false; // nothing selected, return
673
674   QStringList errors;
675
676   QValueList< GEOM::GEOM_Object_var > objsForDisplay;
677   
678   // iterate through all selected files
679   for ( QStringList::ConstIterator it = fileNames.begin(); it != fileNames.end(); ++it ) {
680     QString fileName = *it;
681
682     if ( fileName.isEmpty() )
683       continue;
684
685     QString aCurrentType;
686     if ( fileType.isEmpty() ) {
687       // file type is not defined, try to detect
688       QString ext = QFileInfo( fileName ).extension( false ).upper();
689       QRegExp re( "\\*\\.(\\w+)" );
690       for ( FilterMap::const_iterator it = aMap.begin(); 
691             it != aMap.end() && aCurrentType.isEmpty(); ++it ) {
692         int pos = 0;
693         while ( re.search( it.key(), pos ) >= 0 ) {
694           QString f = re.cap(1).stripWhiteSpace().upper();
695           if ( ext == f ) { aCurrentType = it.data(); break; }
696           pos = re.pos() + re.cap(1).length() + 2;
697         }
698       }
699     }
700     else {
701       aCurrentType = fileType;
702     }
703
704     if ( aCurrentType.isEmpty() ) {
705       errors.append( QString( "%1 : %2" ).arg( fileName ).arg( tr( "GEOM_UNSUPPORTED_TYPE" ) ) );
706       continue;
707     }
708
709     GEOM_Operation* anOp = new GEOM_Operation( app, aInsOp.in() );
710     try {
711       app->putInfo( tr( "GEOM_PRP_LOADING" ).arg( SUIT_Tools::file( fileName, /*withExten=*/true ) ) );
712       anOp->start();
713
714       CORBA::String_var fileN = fileName.latin1();
715       CORBA::String_var fileT = aCurrentType.latin1();
716       GEOM::GEOM_Object_var anObj = aInsOp->Import( fileN, fileT );
717
718       if ( !anObj->_is_nil() && aInsOp->IsDone() ) {
719         QString aPublishObjName = 
720           GEOMBase::GetDefaultName( SUIT_Tools::file( fileName, /*withExten=*/true ) );
721         
722         SALOMEDS::Study_var aDSStudy = GeometryGUI::ClientStudyToStudy( aStudy );
723         GeometryGUI::GetGeomGen()->PublishInStudy( aDSStudy,
724                                                    SALOMEDS::SObject::_nil(),
725                                                    anObj,
726                                                    aPublishObjName );
727
728         objsForDisplay.append( anObj );
729         
730         anOp->commit();
731       }
732       else {
733         anOp->abort();
734         errors.append( QString( "%1 : %2" ).arg( fileName ).arg( aInsOp->GetErrorCode() ) );
735       }
736     }
737     catch( const SALOME::SALOME_Exception& S_ex ) {
738       anOp->abort();
739       errors.append( QString( "%1 : %2" ).arg( fileName ).arg( tr( "GEOM_UNKNOWN_IMPORT_ERROR" ) ) );
740     }
741   }
742
743   // update object browser
744   getGeometryGUI()->updateObjBrowser( true );
745
746   // display imported model (if only one file is selected)
747   if ( objsForDisplay.count() == 1 )
748     GEOM_Displayer( stud ).Display( objsForDisplay[0].in() );
749
750   if ( errors.count() > 0 ) {
751     SUIT_MessageBox::error1( app->desktop(),
752                              QObject::tr( "GEOM_ERROR" ),
753                              QObject::tr( "GEOM_IMPORT_ERRORS" ) + "\n" + errors.join( "\n" ),
754                              QObject::tr( "BUT_OK" ) );
755   }
756
757   app->updateActions(); //SRN: To update a Save button in the toolbar
758
759   return objsForDisplay.count() > 0;
760 }
761
762
763 //=====================================================================================
764 // function : Export
765 // purpose  : BRep, Iges, Step
766 //=====================================================================================
767 bool GEOMToolsGUI::Export()
768 {
769   SalomeApp_Application* app = getGeometryGUI()->getApp();
770   if (!app) return false;
771
772   SalomeApp_Study* stud = dynamic_cast<SalomeApp_Study*> ( app->activeStudy() );
773   if ( !stud ) {
774     MESSAGE ( "FAILED to cast active study to SalomeApp_Study" );
775     return false;
776   }
777   _PTR(Study) aStudy = stud->studyDS();
778
779   GEOM::GEOM_Gen_var eng = GeometryGUI::GetGeomGen();
780   if ( CORBA::is_nil( eng ) ) {
781     SUIT_MessageBox::error1( app->desktop(),
782                              QObject::tr("WRN_WARNING"),
783                              QObject::tr( "GEOM Engine is not started" ),
784                              QObject::tr("BUT_OK") );
785     return false;
786   }
787
788   GEOM::GEOM_IInsertOperations_var aInsOp = eng->GetIInsertOperations( aStudy->StudyId() );
789   if ( aInsOp->_is_nil() )
790     return false;
791
792   // Obtain a list of available export formats
793   FilterMap aMap;
794   QStringList filters;
795   GEOM::string_array_var aFormats, aPatterns;
796   aInsOp->ExportTranslators( aFormats, aPatterns );
797   for ( int i = 0, n = aFormats->length(); i < n; i++ ) {
798     aMap.insert( (char*)aPatterns[i], (char*)aFormats[i] );
799     filters.push_back( (char*)aPatterns[i] );
800   }
801
802   // Get selected objects
803   LightApp_SelectionMgr* sm = app->selectionMgr();
804   if ( !sm )
805     return false;
806
807   SALOME_ListIO selectedObjects;
808   sm->selectedObjects( selectedObjects );
809
810   SALOME_ListIteratorOfListIO It( selectedObjects );
811   for(;It.More();It.Next()) {
812     Handle(SALOME_InteractiveObject) IObject = It.Value();
813     Standard_Boolean found;
814     GEOM::GEOM_Object_var anObj = GEOMBase::ConvertIOinGEOMObject(IObject, found);
815
816     if ( !found || anObj->_is_nil() )
817       continue;
818
819     QString fileType;
820     QString file = getFileName(app->desktop(), QString( IObject->getName() ), aMap, filters,
821                                tr("GEOM_MEN_EXPORT"), false, fileType, true);
822
823     // User has pressed "Cancel" --> stop the operation
824     if ( file.isEmpty() || fileType.isEmpty() )
825       return false;
826
827     GEOM_Operation* anOp = new GEOM_Operation( app, aInsOp.in() );
828     try {
829       SUIT_OverrideCursor wc;
830
831       app->putInfo( tr("GEOM_PRP_EXPORT").arg(SUIT_Tools::file( file, /*withExten=*/true )) );
832
833       anOp->start();
834
835
836       aInsOp->Export( anObj, file, fileType.latin1() );
837
838       if ( aInsOp->IsDone() )
839         anOp->commit();
840       else
841         {
842           anOp->abort();
843           wc.suspend();
844           SUIT_MessageBox::error1( app->desktop(),
845                                    QObject::tr( "GEOM_ERROR" ),
846                                    QObject::tr("GEOM_PRP_ABORT") + "\n" + QString( aInsOp->GetErrorCode() ),
847                                    QObject::tr("BUT_OK") );
848           return false;
849         }
850     }
851     catch (const SALOME::SALOME_Exception& S_ex) {
852       //QtCatchCorbaException(S_ex);
853       anOp->abort();
854       return false;
855     }
856   }
857
858   return true;
859 }
860
861 //=====================================================================================
862 // function : RemoveObjectWithChildren
863 // purpose  : to be used by OnEditDelete() method
864 //=====================================================================================
865 void GEOMToolsGUI::removeObjectWithChildren(_PTR(SObject) obj,
866                                             _PTR(Study) aStudy,
867                                             QPtrList<SALOME_View> views,
868                                             GEOM_Displayer* disp)
869 {
870   // iterate through all children of obj
871   for (_PTR(ChildIterator) it (aStudy->NewChildIterator(obj)); it->More(); it->Next()) {
872     _PTR(SObject) child (it->Value());
873     removeObjectWithChildren(child, aStudy, views, disp);
874   }
875
876   // erase object and remove it from engine
877   _PTR(GenericAttribute) anAttr;
878   if (obj->FindAttribute(anAttr, "AttributeIOR")) {
879     _PTR(AttributeIOR) anIOR (anAttr);
880
881     // Delete shape in Client
882     const TCollection_AsciiString ASCIor ((char*)anIOR->Value().c_str());
883     getGeometryGUI()->GetShapeReader().RemoveShapeFromBuffer(ASCIor);
884
885     CORBA::Object_var corbaObj = GeometryGUI::ClientSObjectToObject(obj);
886     GEOM::GEOM_Object_var geomObj = GEOM::GEOM_Object::_narrow( corbaObj );
887     if (!CORBA::is_nil(geomObj)) {
888       // Erase graphical object
889       SALOME_View* view = views.first();
890       for (; view; view = views.next()) {
891         disp->Erase(geomObj, true, view);
892       }
893
894       // Remove object from Engine
895       GeometryGUI::GetGeomGen()->RemoveObject( geomObj );
896     }
897   }
898 }
899
900 //=================================================================================
901 // function : deactivate()
902 // purpose  : Called when GEOM component is deactivated
903 //=================================================================================
904 void GEOMToolsGUI::deactivate()
905 {
906   SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
907   if ( app ) {
908     SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
909     GEOM_Displayer aDisp (appStudy);
910     aDisp.GlobalSelection();
911     getGeometryGUI()->setLocalSelectionMode(GEOM_ALLOBJECTS);
912   }
913 }
914
915 //=====================================================================================
916 // EXPORTED METHODS
917 //=====================================================================================
918 extern "C"
919 {
920 GEOMTOOLSGUI_EXPORT
921   GEOMGUI* GetLibGUI( GeometryGUI* parent )
922   {
923     return new GEOMToolsGUI( parent );
924   }
925 }