0029021: Coding Rules - eliminate GCC warnings in Qt sample
[occt.git] / samples / qt / Interface / src / Translate.cxx
1 #include "Translate.h"
2
3 #include "Application.h"
4
5 #include <QDir>
6 #include <QLayout>
7 #include <QComboBox>
8 #include <QGroupBox>
9 #include <QList>
10 #include <QListView>
11 #include <QFileDialog>
12 #include <QApplication>
13 #include <QWidget>
14 #include <QStyleFactory>
15
16 #include <AIS_Shape.hxx>
17 #include <AIS_InteractiveObject.hxx>
18
19 #include <IGESControl_Reader.hxx>
20 #include <IGESControl_Writer.hxx>
21 #include <IGESControl_Controller.hxx>
22 #include <STEPControl_Reader.hxx>
23 #include <STEPControl_Writer.hxx>
24 #include <STEPControl_StepModelType.hxx>
25 #include <Interface_Static.hxx>
26 //#include <Interface_TraceFile.hxx>
27
28 #include <StlAPI_Writer.hxx>
29 #include <VrmlAPI_Writer.hxx>
30
31 #include <BRepTools.hxx>
32 #include <BRep_Tool.hxx>
33 #include <BRep_Builder.hxx>
34
35 #include <TopoDS.hxx>
36 #include <TopoDS_Shape.hxx>
37 #include <TopoDS_Compound.hxx>
38 #include <TopExp_Explorer.hxx>
39 #include <TopTools_HSequenceOfShape.hxx>
40
41 #include <Geom_Line.hxx>
42 #include <Geom_Curve.hxx>
43 #include <Geom_Plane.hxx>
44 #include <Geom_Surface.hxx>
45
46
47 #include <Standard_ErrorHandler.hxx>
48 #include <Standard_CString.hxx>
49
50 // ---------------------------- TranslateDlg -----------------------------------------
51
52 class TranslateDlg : public QFileDialog
53 {
54 public:
55   TranslateDlg( QWidget* = 0, Qt::WindowFlags flags = 0, bool = true );
56   ~TranslateDlg();
57   int                   getMode() const;
58   void                  setMode( const int );
59   void                  addMode( const int, const QString& );
60   void                  clear();
61
62 protected:
63   void                  showEvent ( QShowEvent* event );
64
65 private:
66   QListView*            findListView( const QObjectList& );
67
68 private:
69   QComboBox*            myBox;
70   QList<int>            myList;
71 };
72
73 TranslateDlg::TranslateDlg( QWidget* parent, Qt::WindowFlags flags, bool modal )
74 : QFileDialog( parent, flags )
75 {
76   setOption( QFileDialog::DontUseNativeDialog );
77   setModal( modal );
78
79   QGridLayout* grid = ::qobject_cast<QGridLayout*>( layout() );
80
81   if( grid )
82   {
83     QVBoxLayout *vbox = new QVBoxLayout;
84  
85     QWidget* paramGroup = new QWidget( this );
86     paramGroup->setLayout( vbox );
87   
88         myBox = new QComboBox( paramGroup );
89     vbox->addWidget( myBox );
90         
91     int row = grid->rowCount();
92     grid->addWidget( paramGroup, row, 1, 1, 3 ); // make combobox occupy 1 row and 3 columns starting from 1
93   }
94 }
95
96 TranslateDlg::~TranslateDlg()
97 {
98 }
99
100 int TranslateDlg::getMode() const
101 {
102   if ( myBox->currentIndex() < 0 || myBox->currentIndex() > (int)myList.count() - 1 )
103     return -1;
104   else
105     return myList.at( myBox->currentIndex() );
106 }
107
108 void TranslateDlg::setMode( const int mode )
109 {
110   int idx = myList.indexOf( mode );
111   if ( idx >= 0 )
112     myBox->setCurrentIndex( idx );
113 }
114
115 void TranslateDlg::addMode( const int mode, const QString& name )
116 {
117   myBox->show();
118         myBox->addItem( name );
119   myList.append( mode );
120   myBox->updateGeometry();
121   updateGeometry();
122 }
123
124 void TranslateDlg::clear()
125 {
126     myList.clear();
127     myBox->clear();
128     myBox->hide();
129     myBox->updateGeometry();
130     updateGeometry();
131 }
132
133 QListView* TranslateDlg::findListView( const QObjectList & childList )
134 {
135   QListView* listView = 0;
136   for ( int i = 0, n = childList.count(); i < n && !listView; i++ )
137   {
138     listView = qobject_cast<QListView*>( childList.at( i ) );
139     if ( !listView && childList.at( i ) )
140     {
141        listView = findListView( childList.at( i )->children() );
142     }
143   }
144   return listView;
145 }
146
147 void TranslateDlg::showEvent ( QShowEvent* event )
148 {
149   QFileDialog::showEvent ( event );
150   QListView* aListView = findListView( children() );
151   aListView->setViewMode( QListView::ListMode );
152 }
153
154
155 // ---------------------------- Translate -----------------------------------------
156
157 Translate::Translate( QObject* parent )
158 : QObject( parent ),
159 myDlg( 0 )
160 {
161 }
162
163 Translate::~Translate()
164 {
165     if ( myDlg )
166         delete myDlg;
167 }
168
169 QString Translate::info() const
170 {
171     return myInfo;
172 }
173
174 bool Translate::importModel( const int format, const Handle(AIS_InteractiveContext)& ic )
175 {
176     myInfo = QString();
177     QString fileName = selectFileName( format, true );
178     if ( fileName.isEmpty() )
179         return true;
180
181     if ( !QFileInfo( fileName ).exists() )
182     {
183         myInfo = QObject::tr( "INF_TRANSLATE_FILENOTFOUND" ).arg( fileName );
184         return false;
185     }
186
187     QApplication::setOverrideCursor( Qt::WaitCursor );
188     Handle(TopTools_HSequenceOfShape) shapes = importModel( format, fileName );
189     QApplication::restoreOverrideCursor();
190
191     return displayShSequence(ic, shapes);
192 }
193
194 bool Translate::displayShSequence(const Handle(AIS_InteractiveContext)& ic,
195                                   const Handle(TopTools_HSequenceOfShape)& shapes )
196 {
197   if ( shapes.IsNull() || !shapes->Length() )
198         return false;
199
200   for ( int i = 1; i <= shapes->Length(); i++ )
201     ic->Display( new AIS_Shape( shapes->Value( i ) ), false );
202   ic->UpdateCurrentViewer();
203   return true;
204 }
205
206 Handle(TopTools_HSequenceOfShape) Translate::importModel( const int format, const QString& file )
207 {
208     Handle(TopTools_HSequenceOfShape) shapes;
209     try {
210         switch ( format )
211         {
212         case FormatBREP:
213             shapes = importBREP( file );
214             break;
215         case FormatIGES:
216             shapes = importIGES( file );
217             break;
218         case FormatSTEP:
219             shapes = importSTEP( file );
220             break;
221         }
222     } catch ( Standard_Failure ) {
223         shapes.Nullify();
224     }
225     return shapes;
226 }
227
228 bool Translate::exportModel( const int format, const Handle(AIS_InteractiveContext)& ic )
229 {
230     myInfo = QString();
231     QString fileName = selectFileName( format, false );
232     if ( fileName.isEmpty() )
233         return true;
234
235     Handle(TopTools_HSequenceOfShape) shapes = getShapes( ic );
236     if ( shapes.IsNull() || !shapes->Length() )
237         return false;
238
239     QApplication::setOverrideCursor( Qt::WaitCursor );
240     bool stat = exportModel( format, fileName, shapes );
241     QApplication::restoreOverrideCursor();
242
243     return stat;
244 }
245
246 bool Translate::exportModel( const int format, const QString& file, const Handle(TopTools_HSequenceOfShape)& shapes )
247 {
248     try {
249         switch ( format )
250         {
251         case FormatBREP: return exportBREP( file, shapes );
252         case FormatIGES: return exportIGES( file, shapes );
253         case FormatSTEP: return exportSTEP( file, shapes );
254         case FormatSTL:  return exportSTL ( file, shapes );
255         case FormatVRML: return exportVRML( file, shapes );
256         }
257     } catch ( Standard_Failure ) {
258         //
259     }
260     return false;
261 }
262
263 Handle(TopTools_HSequenceOfShape) Translate::getShapes( const Handle(AIS_InteractiveContext)& ic )
264 {
265     Handle(TopTools_HSequenceOfShape) aSequence;
266     Handle(AIS_InteractiveObject) picked;
267     for ( ic->InitSelected(); ic->MoreSelected(); ic->NextSelected() )
268     {
269         Handle(AIS_InteractiveObject) obj = ic->SelectedInteractive();
270         if ( obj->IsKind( STANDARD_TYPE( AIS_Shape ) ) )
271         {
272             TopoDS_Shape shape = Handle(AIS_Shape)::DownCast(obj)->Shape();
273             if ( aSequence.IsNull() )
274                 aSequence = new TopTools_HSequenceOfShape();
275             aSequence->Append( shape );
276         }
277     }
278     return aSequence;
279 }
280
281 /*!
282     Selects a file from standard dialog acoording to selection 'filter'
283 */
284 QString Translate::selectFileName( const int format, const bool import )
285 {
286   TranslateDlg* theDlg = getDialog( format, import );
287
288   int ret = theDlg->exec();
289     
290   qApp->processEvents();
291
292   QString file;
293         QStringList fileNames;
294   if ( ret != QDialog::Accepted )
295       return file;
296
297   fileNames = theDlg->selectedFiles();
298         if (!fileNames.isEmpty())
299     file = fileNames[0];
300
301   if ( !QFileInfo( file ).completeSuffix().length() )
302   {
303     QString selFilter = theDlg->selectedNameFilter();
304                 int idx = selFilter.indexOf( "(*." );
305     if ( idx != -1 )
306     {
307       QString tail = selFilter.mid( idx + 3 );
308                         int idx = tail.indexOf( " " );
309       if ( idx == -1 )
310         idx = tail.indexOf( ")" );
311       QString ext = tail.left( idx );
312       if ( ext.length() )
313         file += QString( "." ) + ext;
314     }
315   }
316
317   return file;
318 }
319
320 TranslateDlg* Translate::getDialog( const int format, const bool import )
321 {
322   if ( !myDlg )
323     myDlg = new TranslateDlg( 0, 0, true );
324
325   if ( format < 0 )
326     return myDlg;
327
328   QString formatFilter = QObject::tr( QString( "INF_FILTER_FORMAT_%1" ).arg( format ).toLatin1().constData() );
329   QString allFilter = QObject::tr( "INF_FILTER_FORMAT_ALL" );
330
331   QString filter;
332   filter.append( formatFilter );
333         filter.append( "\t" );
334
335         if ( import ) 
336   {
337     filter.append( allFilter );
338                 filter.append( "\t" );
339         }
340
341   cout << filter.toLatin1().constData() << endl;
342   QStringList filters = filter.split( "\t" );
343   myDlg->setNameFilters ( filters );
344
345         if ( import )
346   {
347           myDlg->setWindowTitle( QObject::tr( "INF_APP_IMPORT" ) );
348     ((QFileDialog*)myDlg)->setFileMode( QFileDialog::ExistingFile );
349   }
350         else
351   {
352           myDlg->setWindowTitle( QObject::tr( "INF_APP_EXPORT" ) );
353     ((QFileDialog*)myDlg)->setFileMode( QFileDialog::AnyFile );
354   }
355
356   myDlg->clear();
357
358   if ( !import )
359   {
360     switch ( format )
361     {
362       case FormatSTEP:
363         myDlg->addMode( STEPControl_ManifoldSolidBrep,      QObject::tr( "INF_BREP_MOIFOLD" ) );
364               myDlg->addMode( STEPControl_FacetedBrep,            QObject::tr( "INF_BREP_FACETED" ) );
365               myDlg->addMode( STEPControl_ShellBasedSurfaceModel, QObject::tr( "INF_BREP_SHELL" ) );
366               myDlg->addMode( STEPControl_GeometricCurveSet,      QObject::tr( "INF_BREP_CURVE" ) );
367         break;
368      }
369   }
370
371   return myDlg;
372 }
373
374 // ----------------------------- Import functionality -----------------------------
375
376 Handle(TopTools_HSequenceOfShape) Translate::importBREP( const QString& file )
377 {
378         Handle(TopTools_HSequenceOfShape) aSequence;
379     TopoDS_Shape aShape;
380         BRep_Builder aBuilder;
381   TCollection_AsciiString  aFilePath = file.toUtf8().data();
382         Standard_Boolean result = BRepTools::Read( aShape, aFilePath.ToCString(), aBuilder );
383         if ( result )
384     {
385             aSequence = new TopTools_HSequenceOfShape();
386                 aSequence->Append( aShape );
387     }
388     return aSequence;
389 }
390
391 Handle(TopTools_HSequenceOfShape) Translate::importIGES( const QString& file )
392 {
393     Handle(TopTools_HSequenceOfShape) aSequence;
394     TCollection_AsciiString  aFilePath = file.toUtf8().data();
395       
396     IGESControl_Reader Reader;
397     int status = Reader.ReadFile(aFilePath.ToCString() );
398
399     if ( status == IFSelect_RetDone )
400     {
401         aSequence = new TopTools_HSequenceOfShape();
402         Reader.TransferRoots();
403         TopoDS_Shape aShape = Reader.OneShape();
404         aSequence->Append( aShape );
405     }
406         return aSequence;
407 }
408
409 Handle(TopTools_HSequenceOfShape) Translate::importSTEP( const QString& file )
410 {
411         Handle(TopTools_HSequenceOfShape) aSequence;
412   TCollection_AsciiString  aFilePath = file.toUtf8().data();
413         STEPControl_Reader aReader;
414         IFSelect_ReturnStatus status = aReader.ReadFile( aFilePath.ToCString() );
415         if ( status == IFSelect_RetDone )
416     {
417             //Interface_TraceFile::SetDefault();
418             bool failsonly = false;
419             aReader.PrintCheckLoad( failsonly, IFSelect_ItemsByEntity );
420
421             int nbr = aReader.NbRootsForTransfer();
422             aReader.PrintCheckTransfer( failsonly, IFSelect_ItemsByEntity );
423             for ( Standard_Integer n = 1; n <= nbr; n++ )
424             {
425                 bool ok = aReader.TransferRoot( n );
426                 int nbs = aReader.NbShapes();
427                 if ( ok == true && nbs > 0 )
428             {
429                     aSequence = new TopTools_HSequenceOfShape();
430                     for ( int i = 1; i <= nbs; i++ )
431                 {
432                             TopoDS_Shape shape = aReader.Shape( i );
433                             aSequence->Append( shape );
434                     }
435             }
436         }
437     }
438         return aSequence;
439 }
440
441 // ----------------------------- Export functionality -----------------------------
442
443 bool Translate::exportBREP( const QString& file, const Handle(TopTools_HSequenceOfShape)& shapes )
444 {
445     if ( shapes.IsNull() || shapes->IsEmpty() )
446         return false;
447
448     TopoDS_Shape shape = shapes->Value( 1 );
449     
450     const TCollection_AsciiString anUtf8Path (file.toUtf8().data());
451     
452     return BRepTools::Write( shape, anUtf8Path.ToCString() ); 
453 }
454
455 bool Translate::exportIGES( const QString& file, const Handle(TopTools_HSequenceOfShape)& shapes )
456 {
457     if ( shapes.IsNull() || shapes->IsEmpty() )
458         return false;
459
460     IGESControl_Controller::Init();
461         IGESControl_Writer writer( Interface_Static::CVal( "XSTEP.iges.unit" ),
462                                Interface_Static::IVal( "XSTEP.iges.writebrep.mode" ) );
463  
464         for ( int i = 1; i <= shapes->Length(); i++ )
465                 writer.AddShape ( shapes->Value( i ) );
466         writer.ComputeModel();
467         
468         const TCollection_AsciiString anUtf8Path (file.toUtf8().data());
469         
470         return writer.Write( anUtf8Path.ToCString() );
471 }
472
473 bool Translate::exportSTEP( const QString& file, const Handle(TopTools_HSequenceOfShape)& shapes )
474 {
475     if ( shapes.IsNull() || shapes->IsEmpty() )
476         return false;
477
478     TranslateDlg* theDlg = getDialog( -1, false );
479     STEPControl_StepModelType type = (STEPControl_StepModelType)theDlg->getMode();
480     if ( type < 0 )
481         return false;
482     
483     IFSelect_ReturnStatus status;
484
485     if ( type == STEPControl_FacetedBrep && !checkFacetedBrep( shapes ) )
486     {
487         myInfo = QObject::tr( "INF_FACET_ERROR" );
488         return false;
489     }
490
491     STEPControl_Writer writer;
492         for ( int i = 1; i <= shapes->Length(); i++ )
493     {
494                 status = writer.Transfer( shapes->Value( i ), type );
495         if ( status != IFSelect_RetDone )
496             return false;
497     }
498     
499     const TCollection_AsciiString anUtf8Path (file.toUtf8().data());
500
501     status = writer.Write( anUtf8Path.ToCString() );
502
503     switch ( status )
504     {
505     case IFSelect_RetError:
506         myInfo = QObject::tr( "INF_DATA_ERROR" );
507         break;
508     case IFSelect_RetFail:
509         myInfo = QObject::tr( "INF_WRITING_ERROR" );
510         break;
511     case IFSelect_RetVoid:
512         myInfo = QObject::tr( "INF_NOTHING_ERROR" );
513         break;
514     case IFSelect_RetStop:
515     case IFSelect_RetDone:
516         break;
517     }
518     return status == IFSelect_RetDone;
519 }
520
521 bool Translate::exportSTL( const QString& file, const Handle(TopTools_HSequenceOfShape)& shapes )
522 {
523     if ( shapes.IsNull() || shapes->IsEmpty() )
524         return false;
525
526         TopoDS_Compound res;
527         BRep_Builder builder;
528         builder.MakeCompound( res );
529
530         for ( int i = 1; i <= shapes->Length(); i++ )
531         {
532                 TopoDS_Shape shape = shapes->Value( i );
533                 if ( shape.IsNull() ) 
534                 {
535                         myInfo = QObject::tr( "INF_TRANSLATE_ERROR_INVALIDSHAPE" );
536                         return false;
537         }
538                 builder.Add( res, shape );
539         }
540
541         StlAPI_Writer writer;
542         
543         const TCollection_AsciiString anUtf8Path (file.toUtf8().data());
544         
545         writer.Write( res, anUtf8Path.ToCString() );
546
547     return true;
548 }
549
550 bool Translate::exportVRML( const QString& file, const Handle(TopTools_HSequenceOfShape)& shapes )
551 {
552     if ( shapes.IsNull() || shapes->IsEmpty() )
553         return false;
554
555         TopoDS_Compound res;
556         BRep_Builder builder;
557         builder.MakeCompound( res );
558
559         for ( int i = 1; i <= shapes->Length(); i++ )
560         {
561                 TopoDS_Shape shape = shapes->Value( i );
562                 if ( shape.IsNull() )
563                 {
564                         myInfo = QObject::tr( "INF_TRANSLATE_ERROR_INVALIDSHAPE" );
565                         return false;
566         }
567                 builder.Add( res, shape );
568         }
569
570         VrmlAPI_Writer writer;
571         
572         const TCollection_AsciiString anUtf8Path (file.toUtf8().data());
573         
574         writer.Write( res, anUtf8Path.ToCString() );
575
576     return true;
577 }
578
579 bool Translate::checkFacetedBrep( const Handle(TopTools_HSequenceOfShape)& shapes )
580 {
581         bool err = false;
582         for ( int i = 1; i <= shapes->Length(); i++ )
583         {
584             TopoDS_Shape shape = shapes->Value( i );
585         for ( TopExp_Explorer fexp( shape, TopAbs_FACE ); fexp.More() && !err; fexp.Next() )
586                 {
587                     Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( fexp.Current() ) );
588                     if ( !surface->IsKind( STANDARD_TYPE( Geom_Plane ) ) )
589                         err = true;
590                 }
591         for ( TopExp_Explorer eexp( shape, TopAbs_EDGE ); eexp.More() && !err; eexp.Next() )
592                 {
593                     Standard_Real fd, ld;
594                     Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eexp.Current() ), fd, ld );
595                     if ( !curve->IsKind( STANDARD_TYPE( Geom_Line ) ) )
596                         err = true;
597                 }
598         }
599         return !err;
600 }
601
602
603