Salome HOME
IPAL21354 Deleting of referenced father object doesn't work.
[modules/geom.git] / src / GEOMToolsGUI / GEOMToolsGUI.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 // GEOM GEOMGUI : GUI for Geometry component
23 // File   : GEOMBase_Tools.cxx
24 // Author : Damien COQUERET, Open CASCADE S.A.S.
25 //
26 #include "GEOMToolsGUI.h"
27 #include "GEOMToolsGUI_DeleteDlg.h"
28
29 #include <GeometryGUI.h>
30 #include <GEOMBase.h>
31 #include <GEOM_Operation.h>
32 #include <GEOM_Displayer.h>
33
34 #include <SUIT_Session.h>
35 #include <SUIT_OverrideCursor.h>
36 #include <SUIT_MessageBox.h>
37 #include <SUIT_Tools.h>
38 #include <SUIT_FileDlg.h>
39 #include <SUIT_Desktop.h>
40 #include <SUIT_ViewModel.h>
41 #include <SUIT_ViewManager.h>
42
43 #include <SalomeApp_Application.h>
44 #include <SalomeApp_Study.h>
45 #include <LightApp_SelectionMgr.h>
46 #include <GEOMImpl_Types.hxx>
47
48 #include <SALOME_ListIO.hxx>
49 #include <SALOME_ListIteratorOfListIO.hxx>
50 #include <SALOME_Prs.h>
51
52 // QT Includes
53 #include <QApplication>
54 #include <QMap>
55 #include <QRegExp>
56
57 // OCCT Includes
58 #include <TCollection_AsciiString.hxx>
59
60 using namespace std;
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   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   list< _PTR(SObject) >::iterator itSO = aSelectedSO.begin();
218   for ( ; itSO != aSelectedSO.end(); ++itSO ) {
219     std::vector<_PTR(SObject)> aReferences = study->FindDependances( *itSO  );    
220     int aRefLength = aReferences.size();
221     if (aRefLength) {
222       for (int i = 0; i < aRefLength; i++) {
223         _PTR(SObject) firstSO( aReferences[i] );
224         _PTR(SComponent) aComponent = firstSO->GetFatherComponent();
225         QString type = aComponent->ComponentDataType().c_str();
226         if ( type == "SMESH" )
227           return true;
228       }
229     }
230   }
231
232   // browse through all GEOM data tree
233   _PTR(ChildIterator) it ( study->NewChildIterator( comp ) );
234   for ( it->InitEx( true ); it->More(); it->Next() ) {
235     _PTR(SObject) child( it->Value() );
236     CORBA::Object_var corbaObj = GeometryGUI::ClientSObjectToObject( child );
237     GEOM::GEOM_Object_var geomObj = GEOM::GEOM_Object::_narrow( corbaObj );
238     if( CORBA::is_nil( geomObj ) ) 
239       continue;
240
241     GEOM::ListOfGO_var list = geomObj->GetDependency();
242     if( list->length() == 0 ) 
243       continue;
244
245     for( int i = 0; i < list->length(); i++ ) {
246       bool depends = false;
247       bool deleted = false;
248       QMap<QString, GEOM::GEOM_Object_var>::Iterator git;
249       for ( git = gobjects.begin(); git != gobjects.end() && ( !depends || !deleted ); ++git ) {
250         depends = depends || list[i]->_is_equivalent( *git );
251         deleted = deleted || git.key() == child->GetID().c_str() ;//geomObj->_is_equivalent( *git );
252       }
253       if ( depends && !deleted )
254         return true;
255     }
256   }
257   return false;
258 }
259
260
261 //=======================================================================
262 // function : GEOMToolsGUI()
263 // purpose  : Constructor
264 //=======================================================================
265 GEOMToolsGUI::GEOMToolsGUI( GeometryGUI* parent )
266 : GEOMGUI( parent )
267 {
268 }
269
270
271 //=======================================================================
272 // function : ~GEOMToolsGUI()
273 // purpose  : Destructor
274 //=======================================================================
275 GEOMToolsGUI::~GEOMToolsGUI()
276 {
277 }
278
279
280 //=======================================================================
281 // function : OnGUIEvent()
282 // purpose  :
283 //=======================================================================
284 bool GEOMToolsGUI::OnGUIEvent(int theCommandID, SUIT_Desktop* parent)
285 {
286   getGeometryGUI()->EmitSignalDeactivateDialog();
287
288   switch (theCommandID)
289     {
290     case 31: // COPY
291       {
292         OnEditCopy();
293         break;
294       }
295     case 33: // DELETE
296       {
297         OnEditDelete();
298         break;
299       }
300     case 111: // IMPORT BREP
301     case 112: // IMPORT IGES
302     case 113: // IMPORT STEP
303       {
304         Import();
305         break;
306       }
307     case 121: // EXPORT BREP
308     case 122: // EXPORT IGES
309     case 123: // EXPORT STEP
310       {
311         Export();
312         break;
313       }
314     case 2171: // POPUP VIEWER - SELECT ONLY - VERTEX
315       {
316         OnSelectOnly( GEOM_POINT );
317         break;
318       }
319     case 2172: // POPUP VIEWER - SELECT ONLY - EDGE
320       {
321         OnSelectOnly( GEOM_EDGE );
322         break;
323       }
324     case 2173: // POPUP VIEWER - SELECT ONLY - WIRE
325       {
326         OnSelectOnly( GEOM_WIRE );
327         break;
328       }
329     case 2174: // POPUP VIEWER - SELECT ONLY - FACE
330       {
331         OnSelectOnly( GEOM_FACE );
332         break;
333       }
334     case 2175: // POPUP VIEWER - SELECT ONLY - SHELL
335       {
336         OnSelectOnly( GEOM_SHELL );
337         break;
338       }
339     case 2176: // POPUP VIEWER - SELECT ONLY - SOLID
340       {
341         OnSelectOnly( GEOM_SOLID );
342         break;
343       }
344     case 2177: // POPUP VIEWER - SELECT ONLY - COMPOUND
345       {
346         OnSelectOnly( GEOM_COMPOUND );
347         break;
348       }
349     case 2178: // POPUP VIEWER - SELECT ONLY - SELECT ALL
350       {
351         OnSelectOnly( GEOM_ALLOBJECTS );
352         break;
353       }    
354     case 411: // SETTINGS - ADD IN STUDY
355       {
356         // SAN -- TO BE REMOVED !!!
357         break;
358       }
359     case 412: // SETTINGS - SHADING COLOR
360       {
361         OnSettingsColor();
362         break;
363       }
364     case 804: // ADD IN STUDY - POPUP VIEWER
365       {
366         // SAN -- TO BE REMOVED !!!!
367         break;
368       }
369     case 901: // RENAME
370       {
371         OnRename();
372         break;
373       }
374     case 5103: // CHECK GEOMETRY
375       {
376         OnCheckGeometry();
377         break;
378       }
379     case 8032: // COLOR - POPUP VIEWER
380       {
381         OnColor();
382         break;
383       }
384     case 8033: // TRANSPARENCY - POPUP VIEWER
385       {
386         OnTransparency();
387         break;
388       }
389     case 8034: // ISOS - POPUP VIEWER
390       {
391         OnNbIsos();
392         break;
393       }
394     case 8035: // AUTO COLOR - POPUP VIEWER
395       {
396         OnAutoColor();
397         break;
398       }
399     case 8036: // DISABLE AUTO COLOR - POPUP VIEWER
400       {
401         OnDisableAutoColor();
402         break;
403       }
404     case 8037: // SHOW CHILDREN - POPUP VIEWER
405     case 8038: // HIDE CHILDREN - POPUP VIEWER
406       {
407         OnShowHideChildren( theCommandID == 8037 );
408         break;
409       }
410     case 8039: // POINT MARKER
411       {
412         OnPointMarker();
413         break;
414       }
415     case 9024 : // OPEN - OBJBROSER POPUP
416       {
417         OnOpen();
418         break;
419       }
420     default:
421       {
422         SUIT_Session::session()->activeApplication()->putInfo(tr("GEOM_PRP_COMMAND").arg(theCommandID));
423         break;
424       }
425     }
426   return true;
427 }
428
429
430 //===============================================================================
431 // function : OnEditDelete()
432 // purpose  :
433 //===============================================================================
434 void GEOMToolsGUI::OnEditDelete()
435 {
436   SALOME_ListIO selected;
437   SalomeApp_Application* app =
438     dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
439   if ( !app )
440     return;
441
442   LightApp_SelectionMgr* aSelMgr = app->selectionMgr();
443   SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
444   if ( !aSelMgr || !appStudy )
445     return;
446
447   // get selection
448   aSelMgr->selectedObjects( selected, "ObjectBrowser", false );
449   if ( selected.IsEmpty() )
450     return;
451
452   _PTR(Study) aStudy = appStudy->studyDS();
453   
454   // check if study is locked
455   if ( _PTR(AttributeStudyProperties)( aStudy->GetProperties() )->IsLocked() ) {
456     SUIT_MessageBox::warning( app->desktop(),
457                               tr("WRN_WARNING"),
458                               tr("WRN_STUDY_LOCKED") );
459     return; // study is locked
460   }
461   
462   // get GEOM component
463   CORBA::String_var geomIOR = app->orb()->object_to_string( GeometryGUI::GetGeomGen() );
464   QString geomComp = getParentComponent( aStudy->FindObjectIOR( geomIOR.in() ) );
465
466   // check each selected object: if belongs to GEOM, if not reference...
467   QMap<QString,QString> toBeDeleted;
468   QMap<QString,QString> allDeleted;
469   bool isComponentSelected = false;
470   for ( SALOME_ListIteratorOfListIO It( selected ); It.More(); It.Next() ) {
471     Handle(SALOME_InteractiveObject) anIObject = It.Value();
472     if ( !anIObject->hasEntry() )
473       continue; // invalid object
474     // ...
475     QString entry = anIObject->getEntry();
476     _PTR(SObject) obj = aStudy->FindObjectID( entry.toLatin1().data() );
477     // check parent component
478     QString parentComp = getParentComponent( obj );
479     if ( parentComp != geomComp )  {
480       SUIT_MessageBox::warning( app->desktop(),
481                                 QObject::tr("ERR_ERROR"),
482                                 QObject::tr("NON_GEOM_OBJECTS_SELECTED").arg( getGeometryGUI()->moduleName() ) );
483       return; // not GEOM object selected
484     }
485
486     ///////////////////////////////////////////////////////
487     // if GEOM component is selected, so skip other checks
488     if ( isComponentSelected ) continue; 
489     ///////////////////////////////////////////////////////
490         
491     // check if object is reference
492     _PTR(SObject) refobj;
493     if ( obj && obj->ReferencedObject( refobj ) ) {
494       // get the main object by reference IPAL 21354
495       obj = refobj;
496       entry = obj->GetID().c_str();
497     }
498     // ...
499     QString aName = obj->GetName().c_str();
500     if ( entry == geomComp ) {
501       // GEOM component is selected, skip other checks
502       isComponentSelected = true;
503       continue;
504     }
505     toBeDeleted.insert( entry, aName );
506     allDeleted.insert( entry, aName ); // skip GEOM component
507     // browse through all children recursively
508     _PTR(ChildIterator) it ( aStudy->NewChildIterator( obj ) );
509     for ( it->InitEx( true ); it->More(); it->Next() ) {
510       _PTR(SObject) child( it->Value() );
511       if ( child && child->ReferencedObject( refobj ) )
512         continue; // skip references
513       aName = child->GetName().c_str();
514       if ( !aName.isEmpty() )
515         allDeleted.insert( child->GetID().c_str(), aName );
516     }
517   }
518   
519   // is there is anything to delete?
520   if ( !isComponentSelected && allDeleted.count() <= 0 )
521     return; // nothing to delete
522
523   // show confirmation dialog box
524   GEOMToolsGUI_DeleteDlg dlg( app->desktop(), allDeleted, isComponentSelected );
525   if ( !dlg.exec() )
526     return; // operation is cancelled by user
527   
528   // get currently opened views
529   QList<SALOME_View*> views;
530   SALOME_View* view;
531   ViewManagerList vmans = app->viewManagers();
532   SUIT_ViewManager* vman;
533   foreach ( vman, vmans ) {
534     SUIT_ViewModel* vmod = vman->getViewModel();
535     view = dynamic_cast<SALOME_View*> ( vmod ); // must work for OCC and VTK views
536     if ( view )
537       views.append( view );
538   }
539   
540   _PTR(StudyBuilder) aStudyBuilder (aStudy->NewBuilder());
541   GEOM_Displayer* disp = new GEOM_Displayer( appStudy );
542   
543   if ( isComponentSelected ) {
544     // GEOM component is selected: delete all objects recursively
545     _PTR(SObject) comp = aStudy->FindObjectID( geomComp.toLatin1().data() );
546     if ( !comp )
547       return;
548     _PTR(ChildIterator) it ( aStudy->NewChildIterator( comp ) );
549     // remove top-level objects only
550     for ( it->InitEx( false ); it->More(); it->Next() ) {
551       _PTR(SObject) child( it->Value() );
552       // remove object from GEOM engine
553       removeObjectWithChildren( child, aStudy, views, disp );
554       // remove object from study
555       aStudyBuilder->RemoveObjectWithChildren( child );
556     }
557   }
558   else {
559     // GEOM component is not selected: check if selected objects are in use
560     if ( inUse( aStudy, geomComp, allDeleted ) ) {
561       SUIT_MessageBox::warning( app->desktop(),
562                                 QObject::tr("WRN_WARNING"),
563                                 QObject::tr("DEP_OBJECT") );
564       return; // object(s) in use
565     }
566     // ... and then delete all objects
567     QMap<QString, QString>::Iterator it;
568     for ( it = toBeDeleted.begin(); it != toBeDeleted.end(); ++it ) {
569       _PTR(SObject) obj ( aStudy->FindObjectID( it.key().toLatin1().data() ) );
570       // remove object from GEOM engine
571       removeObjectWithChildren( obj, aStudy, views, disp );
572       // remove objects from study
573       aStudyBuilder->RemoveObjectWithChildren( obj );
574     }
575   }
576   
577   selected.Clear();
578   aSelMgr->setSelectedObjects( selected );
579   getGeometryGUI()->updateObjBrowser();
580   app->updateActions(); //SRN: To update a Save button in the toolbar
581 }
582
583
584 //==============================================================================
585 // function : OnEditCopy()
586 // purpose  :
587 //==============================================================================
588 void GEOMToolsGUI::OnEditCopy()
589 {
590 /*
591  SALOME_Selection* Sel = SALOME_Selection::Selection(QAD_Application::getDesktop()->getActiveStudy()->getSelection() );
592   GEOM::string_array_var listIOR = new GEOM::string_array;
593
594   const SALOME_ListIO& List = Sel->StoredIObjects();
595
596   myGeomBase->ConvertListOfIOInListOfIOR(List, listIOR);
597
598   Sel->ClearIObjects();
599
600   SALOMEDS::Study_var aStudy = QAD_Application::getDesktop()->getActiveStudy()->getStudyDocument();
601   int aStudyID = aStudy->StudyId();
602
603   for (unsigned int ind = 0; ind < listIOR->length();ind++) {
604     GEOM::GEOM_Object_var aShapeInit = myGeom->GetIORFromString(listIOR[ind]);
605     try {
606       GEOM::GEOM_IInsertOperations_var IOp =  myGeom->GetIInsertOperations(aStudyID);
607       GEOM::GEOM_Object_var result = IOp->MakeCopy(aShapeInit);
608       myGeomBase->Display(result);
609     }
610     catch  (const SALOME::SALOME_Exception& S_ex) {
611       QtCatchCorbaException(S_ex);
612     }
613   }
614
615   QAD_Application::getDesktop()->putInfo(tr("GEOM_PRP_READY"));
616 */
617 }
618
619 //=====================================================================================
620 // function : Import
621 // purpose  : BRep, Iges, Step
622 //=====================================================================================
623 bool GEOMToolsGUI::Import()
624 {
625   SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( getGeometryGUI()->getApp() );
626   if ( !app ) return false;
627
628   SalomeApp_Study* stud = dynamic_cast<SalomeApp_Study*> ( app->activeStudy() );
629   if ( !stud ) {
630     MESSAGE ( "FAILED to cast active study to SalomeApp_Study" );
631     return false;
632   }
633   _PTR(Study) aStudy = stud->studyDS();
634
635   // check if study is locked
636   bool aLocked = (_PTR(AttributeStudyProperties)(aStudy->GetProperties()))->IsLocked();
637   if ( aLocked ) {
638     SUIT_MessageBox::warning( app->desktop(),
639                               QObject::tr("WRN_WARNING"),
640                               QObject::tr("WRN_STUDY_LOCKED") );
641     return false;
642   }
643
644   // check if GEOM engine is available
645   GEOM::GEOM_Gen_var eng = GeometryGUI::GetGeomGen();
646   if ( CORBA::is_nil( eng ) ) {
647     SUIT_MessageBox::critical( app->desktop(),
648                                QObject::tr("WRN_WARNING"),
649                                QObject::tr( "GEOM Engine is not started" ) );
650     return false;
651   }
652
653   GEOM::GEOM_IInsertOperations_var aInsOp = eng->GetIInsertOperations( aStudy->StudyId() );
654   if ( aInsOp->_is_nil() )
655     return false;
656
657   // obtain a list of available import formats
658   FilterMap aMap;
659   GEOM::string_array_var aFormats, aPatterns;
660   aInsOp->ImportTranslators( aFormats, aPatterns );
661
662   for ( int i = 0, n = aFormats->length(); i < n; i++ )
663     aMap.insert( (char*)aPatterns[i], (char*)aFormats[i] );
664
665   // select files to be imported
666   QString fileType;
667   QStringList fileNames = getFileNames( app->desktop(), "", aMap,
668                                         tr( "GEOM_MEN_IMPORT" ), fileType, true );
669
670   // set Wait cursor
671   SUIT_OverrideCursor wc;
672
673   if ( fileNames.count() == 0 )
674     return false; // nothing selected, return
675
676   QStringList errors;
677
678   QList< GEOM::GEOM_Object_var > objsForDisplay;
679
680   
681   // iterate through all selected files
682
683   SUIT_MessageBox::StandardButton igesAnswer = SUIT_MessageBox::NoButton;
684   SUIT_MessageBox::StandardButton acisAnswer = SUIT_MessageBox::NoButton;
685
686   for ( int i = 0; i < fileNames.count(); i++ ) {
687     QString fileName = fileNames[i];
688
689     if ( fileName.isEmpty() )
690       continue;
691
692     QString aCurrentType;
693     if ( fileType.isEmpty() ) {
694       // file type is not defined, try to detect
695       QString ext = QFileInfo( fileName ).suffix().toUpper();
696       QRegExp re( "\\*\\.(\\w+)" );
697       for ( FilterMap::const_iterator it = aMap.begin(); 
698             it != aMap.end() && aCurrentType.isEmpty(); ++it ) {
699         int pos = 0;
700         while ( re.indexIn( it.key(), pos ) >= 0 ) {
701           QString f = re.cap(1).trimmed().toUpper();
702           if ( ext == f ) { aCurrentType = it.value(); break; }
703           pos = re.pos() + re.cap(1).length() + 2;
704         }
705       }
706     }
707     else {
708       aCurrentType = fileType;
709     }
710
711     if ( aCurrentType.isEmpty() ) {
712       errors.append( QString( "%1 : %2" ).arg( fileName ).arg( tr( "GEOM_UNSUPPORTED_TYPE" ) ) );
713       continue;
714     }
715
716     GEOM_Operation* anOp = new GEOM_Operation( app, aInsOp.in() );
717     try {
718       app->putInfo( tr( "GEOM_PRP_LOADING" ).arg( SUIT_Tools::file( fileName, /*withExten=*/true ) ) );
719       anOp->start();
720
721       CORBA::String_var fileN = fileName.toLatin1().constData();
722       CORBA::String_var fileT = aCurrentType.toLatin1().constData();
723
724       // skl 29.05.2009
725       if ( aCurrentType == "IGES" ) {
726         GEOM::GEOM_Object_var anObj = aInsOp->Import( fileN, "IGES_UNIT" );
727         bool needConvert = false;
728         TCollection_AsciiString aUnitName = aInsOp->GetErrorCode();
729         if ( aUnitName.SubString( 1, 4 ) == "UNIT" )
730           needConvert = aUnitName.SubString( 6, aUnitName.Length() ) != "M";
731
732         if ( needConvert ) {
733           if ( igesAnswer == SUIT_MessageBox::NoToAll ) {
734             // converting for all files is already approved
735             fileT = "IGES_SCALE";
736           }
737           else if ( igesAnswer != SUIT_MessageBox::YesToAll ) {
738             SUIT_MessageBox::StandardButtons btns = SUIT_MessageBox::Yes | SUIT_MessageBox::No;
739             if ( i < fileNames.count()-1 ) btns = btns | SUIT_MessageBox::YesToAll | SUIT_MessageBox::NoToAll;
740             igesAnswer = SUIT_MessageBox::question( app->desktop(),
741                                                     "Question",//tr("WRN_WARNING"),
742                                                     tr("GEOM_SCALE_DIMENSIONS"),
743                                                     btns | SUIT_MessageBox::Cancel,
744                                                     SUIT_MessageBox::No );
745             switch ( igesAnswer ) {
746             case SUIT_MessageBox::Cancel:
747               return false;                // cancel (break) import operation
748             case SUIT_MessageBox::Yes:
749             case SUIT_MessageBox::YesToAll:
750               break;                       // scaling is confirmed
751             case SUIT_MessageBox::No:
752             case SUIT_MessageBox::NoAll:
753               fileT = "IGES_SCALE";
754             default:
755               break;                       // scaling is rejected
756             } // switch ( igesAnswer )
757           } // if ( igeAnswer != NoToAll )
758         } // if ( needConvert )
759       } // if ( aCurrentType == "IGES" )
760       else if ( aCurrentType == "ACIS" ) {
761         if ( acisAnswer != SUIT_MessageBox::YesToAll && acisAnswer != SUIT_MessageBox::NoToAll ) {
762           SUIT_MessageBox::StandardButtons btns = SUIT_MessageBox::Yes | SUIT_MessageBox::No;
763           if ( i < fileNames.count()-1 ) btns = btns | SUIT_MessageBox::YesToAll | SUIT_MessageBox::NoToAll;
764           acisAnswer = SUIT_MessageBox::question( app->desktop(),
765                                                   "Question",//tr("WRN_WARNING"),
766                                                   tr("GEOM_PUBLISH_NAMED_SHAPES"),
767                                                   btns | SUIT_MessageBox::Cancel,
768                                                   SUIT_MessageBox::No );
769           if ( acisAnswer == SUIT_MessageBox::Cancel )
770             return false; // cancel (break) import operation
771         } // if ( acisAnswer != YesToAll && acisAnswer != NoToAll )
772       } // else if ( aCurrentType == "ACIS" )
773       
774       GEOM::GEOM_Object_var anObj = aInsOp->Import( fileN, fileT );
775
776       if ( !anObj->_is_nil() && aInsOp->IsDone() ) {
777         QString aPublishObjName = 
778           GEOMBase::GetDefaultName( SUIT_Tools::file( fileName, /*withExten=*/true ) );
779         
780         SALOMEDS::Study_var aDSStudy = GeometryGUI::ClientStudyToStudy( aStudy );
781         GeometryGUI::GetGeomGen()->PublishInStudy( aDSStudy,
782                                                    SALOMEDS::SObject::_nil(),
783                                                    anObj,
784                                                    aPublishObjName.toLatin1().constData() );
785         
786         objsForDisplay.append( anObj );
787         
788         if ( aCurrentType == "ACIS" ) {
789           if ( acisAnswer == SUIT_MessageBox::Yes || acisAnswer == SUIT_MessageBox::YesToAll )
790             GeometryGUI::GetGeomGen()->PublishNamedShapesInStudy( aDSStudy, anObj );
791         }
792
793         anOp->commit();
794       }
795       else {
796         anOp->abort();
797         errors.append( QString( "%1 : %2" ).arg( fileName ).arg( aInsOp->GetErrorCode() ) );
798       }
799     }
800     catch( const SALOME::SALOME_Exception& S_ex ) {
801       anOp->abort();
802       errors.append( QString( "%1 : %2" ).arg( fileName ).arg( tr( "GEOM_UNKNOWN_IMPORT_ERROR" ) ) );
803     }
804   }
805
806   // update object browser
807   getGeometryGUI()->updateObjBrowser( true );
808
809   // display imported model (if only one file is selected)
810   if ( objsForDisplay.count() == 1 )
811     GEOM_Displayer( stud ).Display( objsForDisplay[0].in() );
812
813   if ( errors.count() > 0 ) {
814     SUIT_MessageBox::critical( app->desktop(),
815                                QObject::tr( "GEOM_ERROR" ),
816                                QObject::tr( "GEOM_IMPORT_ERRORS" ) + "\n" + errors.join( "\n" ) );
817   }
818
819   app->updateActions(); //SRN: To update a Save button in the toolbar
820
821   return objsForDisplay.count() > 0;
822 }
823
824
825 //=====================================================================================
826 // function : Export
827 // purpose  : BRep, Iges, Step
828 //=====================================================================================
829 bool GEOMToolsGUI::Export()
830 {
831   SalomeApp_Application* app = getGeometryGUI()->getApp();
832   if (!app) return false;
833
834   SalomeApp_Study* stud = dynamic_cast<SalomeApp_Study*> ( app->activeStudy() );
835   if ( !stud ) {
836     MESSAGE ( "FAILED to cast active study to SalomeApp_Study" );
837     return false;
838   }
839   _PTR(Study) aStudy = stud->studyDS();
840
841   GEOM::GEOM_Gen_var eng = GeometryGUI::GetGeomGen();
842   if ( CORBA::is_nil( eng ) ) {
843     SUIT_MessageBox::critical( app->desktop(),
844                                QObject::tr("WRN_WARNING"),
845                                QObject::tr( "GEOM Engine is not started" ) );
846     return false;
847   }
848
849   GEOM::GEOM_IInsertOperations_var aInsOp = eng->GetIInsertOperations( aStudy->StudyId() );
850   if ( aInsOp->_is_nil() )
851     return false;
852
853   // Obtain a list of available export formats
854   FilterMap aMap;
855   QStringList filters;
856   GEOM::string_array_var aFormats, aPatterns;
857   aInsOp->ExportTranslators( aFormats, aPatterns );
858   for ( int i = 0, n = aFormats->length(); i < n; i++ ) {
859     aMap.insert( (char*)aPatterns[i], (char*)aFormats[i] );
860     filters.push_back( (char*)aPatterns[i] );
861   }
862
863   // Get selected objects
864   LightApp_SelectionMgr* sm = app->selectionMgr();
865   if ( !sm )
866     return false;
867
868   SALOME_ListIO selectedObjects;
869   sm->selectedObjects( selectedObjects );
870   bool appropriateObj = false;
871
872   SALOME_ListIteratorOfListIO It( selectedObjects );
873   for(;It.More();It.Next()) {
874     Handle(SALOME_InteractiveObject) IObject = It.Value();
875     Standard_Boolean found;
876     GEOM::GEOM_Object_var anObj = GEOMBase::ConvertIOinGEOMObject(IObject, found);
877
878     if ( !found || anObj->_is_nil() )
879       continue;
880
881     QString fileType;
882     QString file = getFileName(app->desktop(), QString( IObject->getName() ), aMap, filters,
883                                tr("GEOM_MEN_EXPORT"), false, fileType, true);
884
885     // User has pressed "Cancel" --> stop the operation
886     if ( file.isEmpty() || fileType.isEmpty() )
887       return false;
888
889     GEOM_Operation* anOp = new GEOM_Operation( app, aInsOp.in() );
890     try {
891       SUIT_OverrideCursor wc;
892
893       app->putInfo( tr("GEOM_PRP_EXPORT").arg(SUIT_Tools::file( file, /*withExten=*/true )) );
894
895       anOp->start();
896
897
898       aInsOp->Export( anObj, file.toStdString().c_str(), fileType.toLatin1().constData() );
899
900       if ( aInsOp->IsDone() )
901         anOp->commit();
902       else
903         {
904           anOp->abort();
905           wc.suspend();
906           SUIT_MessageBox::critical( app->desktop(),
907                                      QObject::tr( "GEOM_ERROR" ),
908                                      QObject::tr("GEOM_PRP_ABORT") + "\n" + QString( aInsOp->GetErrorCode() ) );
909           return false;
910         }
911     }
912     catch (const SALOME::SALOME_Exception& S_ex) {
913       //QtCatchCorbaException(S_ex);
914       anOp->abort();
915       return false;
916     }
917     appropriateObj = true;
918   }
919
920   if ( !appropriateObj )
921     SUIT_MessageBox::warning( app->desktop(),
922                               QObject::tr("WRN_WARNING"),
923                               QObject::tr("GEOM_WRN_NO_APPROPRIATE_SELECTION") );
924   return true;
925 }
926
927 //=====================================================================================
928 // function : RemoveObjectWithChildren
929 // purpose  : to be used by OnEditDelete() method
930 //=====================================================================================
931 void GEOMToolsGUI::removeObjectWithChildren(_PTR(SObject) obj,
932                                             _PTR(Study) aStudy,
933                                             QList<SALOME_View*> views,
934                                             GEOM_Displayer* disp)
935 {
936   // iterate through all children of obj
937   for (_PTR(ChildIterator) it (aStudy->NewChildIterator(obj)); it->More(); it->Next()) {
938     _PTR(SObject) child (it->Value());
939     removeObjectWithChildren(child, aStudy, views, disp);
940   }
941
942   // erase object and remove it from engine
943   _PTR(GenericAttribute) anAttr;
944   if (obj->FindAttribute(anAttr, "AttributeIOR")) {
945     _PTR(AttributeIOR) anIOR (anAttr);
946
947     // Delete shape in Client
948     const TCollection_AsciiString ASCIor ((char*)anIOR->Value().c_str());
949     getGeometryGUI()->GetShapeReader().RemoveShapeFromBuffer(ASCIor);
950
951     CORBA::Object_var corbaObj = GeometryGUI::ClientSObjectToObject(obj);
952     GEOM::GEOM_Object_var geomObj = GEOM::GEOM_Object::_narrow( corbaObj );
953     if (!CORBA::is_nil(geomObj)) {
954       // Erase graphical object
955       QListIterator<SALOME_View*> it( views );
956       while ( it.hasNext() )
957         if ( SALOME_View* view = it.next() )
958           disp->Erase(geomObj, true, view);
959       
960       // Remove object from Engine
961       // We can't directly remove object from engine. All we can do is to unpublish the object
962       // from the study. Another client could be using the object.
963       // Unpublishing is done just after in aStudyBuilder->RemoveObjectWithChildren( child );
964       //GeometryGUI::GetGeomGen()->RemoveObject( geomObj );
965     }
966   }
967 }
968
969 //=================================================================================
970 // function : deactivate()
971 // purpose  : Called when GEOM component is deactivated
972 //=================================================================================
973 void GEOMToolsGUI::deactivate()
974 {
975   SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
976   if ( app ) {
977     SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
978     GEOM_Displayer aDisp (appStudy);
979     aDisp.GlobalSelection();
980     getGeometryGUI()->setLocalSelectionMode(GEOM_ALLOBJECTS);
981   }
982 }
983
984 //=====================================================================================
985 // EXPORTED METHODS
986 //=====================================================================================
987 extern "C"
988 {
989 #ifdef WIN32
990   __declspec( dllexport )
991 #endif
992   GEOMGUI* GetLibGUI( GeometryGUI* parent )
993   {
994     return new GEOMToolsGUI( parent );
995   }
996 }