Salome HOME
bos #18641 [CEA 18636][Windows] SMESH_MeshersList environment variable separator
[modules/smesh.git] / src / SMESHGUI / SMESHGUI_HypothesesUtils.cxx
1 // Copyright (C) 2007-2019  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, or (at your option) any later version.
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 // SMESH SMESHGUI : GUI for SMESH component
24 // File   : SMESHGUI_HypothesesUtils.cxx
25 // Author : Julia DOROVSKIKH, Open CASCADE S.A.S.
26 // SMESH includes
27 //
28 #include "SMESHGUI_HypothesesUtils.h"
29
30 #include "SMESHGUI.h"
31 #include "SMESHGUI_GEOMGenUtils.h"
32 #include "SMESHGUI_Hypotheses.h"
33 #include "SMESHGUI_Utils.h"
34 #include "SMESHGUI_VTKUtils.h"
35 #include "SMESHGUI_XmlHandler.h"
36
37 #include "SMESH_Actor.h"
38
39 // SALOME GUI includes
40 #include <SUIT_Desktop.h>
41 #include <SUIT_MessageBox.h>
42 #include <SUIT_OverrideCursor.h>
43 #include <SUIT_ResourceMgr.h>
44
45 #include <SalomeApp_Study.h>
46 #include <SalomeApp_Tools.h>
47
48 // SALOME KERNEL includes
49 #include <utilities.h>
50
51 // STL includes
52 #include <string>
53
54 // Qt includes
55 #include <QDir>
56
57
58 // Other includes
59 #ifdef WIN32
60 #include <windows.h>
61 #else
62 #include <dlfcn.h>
63 #endif
64
65 #ifdef WIN32
66  #define LibHandle HMODULE
67  #define LoadLib( name ) LoadLibrary( name )
68  #define GetProc GetProcAddress
69  #define UnLoadLib( handle ) FreeLibrary( handle );
70  #define env_sep ";"
71 #else // WIN32
72  #define LibHandle void*
73  #ifdef DYNLOAD_LOCAL
74   #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
75  #else // DYNLOAD_LOCAL
76   #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
77  #endif // DYNLOAD_LOCAL
78  #define GetProc dlsym
79  #define UnLoadLib( handle ) dlclose( handle );
80  #define env_sep ":"
81 #endif // WIN32
82
83 #ifdef _DEBUG_
84 static int MYDEBUG = 0;
85 #else
86 static int MYDEBUG = 0;
87 #endif
88
89 namespace SMESH
90 {
91   typedef IMap<QString,HypothesisData*> THypothesisDataMap;
92   THypothesisDataMap myHypothesesMap;
93   THypothesisDataMap myAlgorithmsMap;
94
95   // BUG 0020378
96   //typedef QMap<QString,SMESHGUI_GenericHypothesisCreator*> THypCreatorMap;
97   //THypCreatorMap myHypCreatorMap;
98
99   QList<HypothesesSet*> myListOfHypothesesSets;
100
101   void processHypothesisStatus(const int                   theHypStatus,
102                                SMESH::SMESH_Hypothesis_ptr theHyp,
103                                const bool                  theIsAddition,
104                                const char*                 theError = 0)
105   {
106     if (theHypStatus > SMESH::HYP_OK) {
107       // get Hyp name
108       QString aHypName ("NULL Hypothesis");
109       if (!CORBA::is_nil(theHyp)) {
110         _PTR(SObject) Shyp = SMESH::FindSObject(theHyp);
111         if (Shyp) {
112           // name in study
113           aHypName = Shyp->GetName().c_str();
114         }
115         else {
116           // label in xml file
117           CORBA::String_var hypType = theHyp->GetName();
118           aHypName = GetHypothesisData( hypType.in() )->Label;
119         }
120       }
121
122       // message
123       bool isFatal = (theHypStatus >= SMESH::HYP_UNKNOWN_FATAL);
124       QString aMsg;
125       if (theIsAddition)
126         aMsg = (isFatal ? "SMESH_CANT_ADD_HYP" : "SMESH_ADD_HYP_WRN");
127       else
128         aMsg = (isFatal ? "SMESH_CANT_RM_HYP"  : "SMESH_RM_HYP_WRN");
129
130       aMsg = QObject::tr(aMsg.toLatin1().data()).arg(aHypName);
131
132       if ( theError && theError[0] )
133       {
134         aMsg += theError;
135       }
136       else
137       {
138         aMsg += QObject::tr(QString("SMESH_HYP_%1").arg(theHypStatus).toLatin1().data());
139
140         if ( theHypStatus == SMESH::HYP_HIDDEN_ALGO ) { // PAL18501
141           CORBA::String_var hypType = theHyp->GetName();
142           if ( HypothesisData* hd = GetHypothesisData( hypType.in() ))
143             aMsg = aMsg.arg( hd->Dim[0] );
144         }
145       }
146       SUIT_MessageBox::warning(SMESHGUI::desktop(),
147                                QObject::tr("SMESH_WRN_WARNING"),
148                                aMsg);
149     }
150   }
151
152   //================================================================================
153   /*!
154    * \brief Prepends dimension and appends '[custom]' to the name of hypothesis set
155    */
156   //================================================================================
157
158   static QString mangledHypoSetName(HypothesesSet* hypSet)
159   {
160     QString name = hypSet->name();
161
162     // prepend 'xD: '
163     int dim = hypSet->maxDim();
164     if ( dim > -1 )
165       name = QString("%1D: %2").arg(dim).arg(name);
166
167     // custom
168     if ( hypSet->getIsCustom() )
169       name = QString("%1 [custom]").arg(name);
170
171     return name;
172   }
173
174   //================================================================================
175   /*!
176    * \brief Removes dimension and '[custom]' from the name of hypothesis set
177    */
178   //================================================================================
179
180   static QString demangledHypoSetName(QString name)
181   {
182     name.remove(QRegExp("[0-3]D: "));
183     name.remove(" [custom]");
184     return name;
185   }
186
187   void InitAvailableHypotheses()
188   {
189     SUIT_OverrideCursor wc;
190     if ( myHypothesesMap.empty() && myAlgorithmsMap.empty() )
191     {
192       // Resource manager
193       SUIT_ResourceMgr* resMgr = SMESHGUI::resourceMgr();
194       if (!resMgr) return;
195
196       // Find name of a resource XML file ("SMESH_Meshers.xml");
197       QString HypsXml;
198       char* cenv = getenv("SMESH_MeshersList");
199       if (cenv)
200         HypsXml.sprintf("%s", cenv);
201
202       QStringList HypsXmlList = HypsXml.split(env_sep, QString::SkipEmptyParts);
203       if (HypsXmlList.count() == 0) {
204         SUIT_MessageBox::critical(SMESHGUI::desktop(),
205                                   QObject::tr("SMESH_WRN_WARNING"),
206                                   QObject::tr("MESHERS_FILE_NO_VARIABLE"));
207         return;
208       }
209       // get full names of xml files from HypsXmlList
210       QStringList xmlFiles;
211       xmlFiles.append( QDir::home().filePath("CustomMeshers.xml")); // may be inexistent
212       for (int i = 0; i < HypsXmlList.count(); i++) {
213         QString HypsXml = HypsXmlList[ i ];
214
215         // Find full path to the resource XML file
216         QString xmlFile = resMgr->path("resources", "SMESH", HypsXml + ".xml");
217         if ( xmlFile.isEmpty() ) // try PLUGIN resources
218           xmlFile = resMgr->path("resources", HypsXml, HypsXml + ".xml");
219         if ( !xmlFile.isEmpty() )
220           xmlFiles.append( xmlFile );
221       }
222
223       // loop on xmlFiles
224       QString aNoAccessFiles;
225       for (int i = 0; i < xmlFiles.count(); i++)
226       {
227         QString xmlFile = xmlFiles[ i ];
228         QFile file (xmlFile);
229         if (file.exists() && file.open(QIODevice::ReadOnly))
230         {
231           file.close();
232
233           SMESHGUI_XmlHandler* aXmlHandler = new SMESHGUI_XmlHandler();
234           ASSERT(aXmlHandler);
235
236           QXmlInputSource source (&file);
237           QXmlSimpleReader reader;
238           reader.setContentHandler(aXmlHandler);
239           reader.setErrorHandler(aXmlHandler);
240           bool ok = reader.parse(source);
241           file.close();
242           if (ok) {
243
244             THypothesisDataMap::ConstIterator it1 = aXmlHandler->myHypothesesMap.begin();
245
246             for( ;it1 != aXmlHandler->myHypothesesMap.end(); it1++)
247               myHypothesesMap.insert( it1.key(), it1.value() );
248
249             it1 = aXmlHandler->myAlgorithmsMap.begin();
250             for( ;it1 != aXmlHandler->myAlgorithmsMap.end(); it1++)
251               myAlgorithmsMap.insert( it1.key(), it1.value() );
252
253             QList<HypothesesSet*>::iterator it;
254             for ( it = aXmlHandler->myListOfHypothesesSets.begin();
255                   it != aXmlHandler->myListOfHypothesesSets.end();
256                   ++it )
257             {
258               (*it)->setIsCustom( i == 0 );
259               myListOfHypothesesSets.append( *it );
260             }
261           }
262           else {
263             SUIT_MessageBox::critical(SMESHGUI::desktop(),
264                                       QObject::tr("INF_PARSE_ERROR"),
265                                       QObject::tr(aXmlHandler->errorProtocol().toLatin1().data()));
266           }
267           delete aXmlHandler;
268         }
269         else if ( i > 0 ) { // 1st is ~/CustomMeshers.xml
270           if (aNoAccessFiles.isEmpty())
271             aNoAccessFiles = xmlFile;
272           else
273             aNoAccessFiles += ", " + xmlFile;
274         }
275       } // end loop on xmlFiles
276
277
278       if (!aNoAccessFiles.isEmpty()) {
279         QString aMess = QObject::tr("MESHERS_FILE_CANT_OPEN") + " " + aNoAccessFiles + "\n";
280         aMess += QObject::tr("MESHERS_FILE_CHECK_VARIABLE");
281         wc.suspend();
282         SUIT_MessageBox::warning(SMESHGUI::desktop(),
283                                  QObject::tr("SMESH_WRN_WARNING"),
284                                  aMess);
285         wc.resume();
286       }
287     }
288   }
289
290
291   QStringList GetAvailableHypotheses( const bool isAlgo,
292                                       const int  theDim,
293                                       const bool isAux,
294                                       const bool hasGeometry,
295                                       const bool isSubMesh)
296   {
297     QStringList aHypList;
298
299     // Init list of available hypotheses, if needed
300     InitAvailableHypotheses();
301     bool checkGeometry = ( isAlgo );
302     const char* context = isSubMesh ? "LOCAL" : "GLOBAL";
303     // fill list of hypotheses/algorithms
304     THypothesisDataMap& pMap = isAlgo ? myAlgorithmsMap : myHypothesesMap;
305     THypothesisDataMap::ConstIterator anIter;
306     for ( anIter = pMap.begin(); anIter != pMap.end(); anIter++ )
307     {
308       HypothesisData* aData = anIter.value();
309       if (( aData && !aData->Label.isEmpty() ) &&
310           ( theDim < 0              || aData->Dim.contains( theDim )) &&
311           ( isAlgo                  || aData->IsAuxOrNeedHyp == isAux ) &&
312           ( aData->Context == "ANY" || aData->Context == context ) &&
313           ( !checkGeometry          || (!aData->IsNeedGeometry  ||
314                                         ( aData->IsNeedGeometry > 0 ) == hasGeometry)))
315       {
316         aHypList.append(anIter.key());
317       }
318     }
319     return aHypList;
320   }
321
322
323   QStringList GetHypothesesSets(int maxDim)
324   {
325     QStringList aSetNameList;
326
327     // Init list of available hypotheses, if needed
328     InitAvailableHypotheses();
329     QList<HypothesesSet*>::iterator hypoSet;
330     for ( hypoSet  = myListOfHypothesesSets.begin();
331         hypoSet != myListOfHypothesesSets.end();
332         ++hypoSet ) {
333       HypothesesSet* aSet = *hypoSet;
334       if ( aSet && 0 <= aSet->maxDim() && aSet->maxDim() <= maxDim )
335       {
336         aSetNameList.append( mangledHypoSetName( aSet ));
337       }
338     }
339     aSetNameList.removeDuplicates();
340     aSetNameList.sort();
341
342     //  reverse order of aSetNameList
343     QStringList reversedNames;
344     for ( int i = 0; i < aSetNameList.count(); ++i )
345       reversedNames.prepend( aSetNameList[i] );
346
347     return reversedNames;
348   }
349
350   HypothesesSet* GetHypothesesSet(const QString& theSetName)
351   {
352     QString name = demangledHypoSetName( theSetName );
353     QList<HypothesesSet*>::iterator hypoSet;
354     for ( hypoSet  = myListOfHypothesesSets.begin();
355           hypoSet != myListOfHypothesesSets.end();
356           ++hypoSet ) {
357       HypothesesSet* aSet = *hypoSet;
358       if ( aSet && aSet->name() == name )
359         return aSet;
360     }
361     return 0;
362   }
363
364   HypothesisData* GetHypothesisData (const QString& aHypType)
365   {
366     HypothesisData* aHypData = 0;
367
368     // Init list of available hypotheses, if needed
369     InitAvailableHypotheses();
370
371     if (myHypothesesMap.contains(aHypType)) {
372       aHypData = myHypothesesMap[aHypType];
373     }
374     else if (myAlgorithmsMap.contains(aHypType)) {
375       aHypData = myAlgorithmsMap[aHypType];
376     }
377     return aHypData;
378   }
379
380   //================================================================================
381   /*!
382    * \brief Return the HypothesisData holding a name of a group of hypotheses
383    *        a given hypothesis belongs to
384    */
385   //================================================================================
386
387   HypothesisData* GetGroupTitle( const HypothesisData* hyp, const bool isAlgo )
388   {
389     static std::vector< std::vector< HypothesisData > > theGroups;
390     if ( theGroups.empty() )
391     {
392       theGroups.resize(14); // 14: isAlgo * 10 + dim
393
394       QString dummyS("GROUP");
395       QList<int> dummyIL; dummyIL << 1;
396       QStringList dummySL;
397       HypothesisData group( dummyS,dummyS,dummyS,dummyS,dummyS,dummyS,dummyS,-1,-1,
398                             dummyIL, 0, dummySL,dummySL,dummySL,dummySL,0,0 );
399       // no group
400       int key = 0;
401       theGroups[ key ].push_back( group );
402
403       // 1D algo
404       key = 11;
405       //        0: Basic
406       group.Label = "GROUP:" + QObject::tr( "SMESH_1D_ALGO_GROUP_BASIC" );
407       theGroups[ key ].push_back( group );
408       //        1: Advanced
409       group.Label = "GROUP:" + QObject::tr( "SMESH_1D_ALGO_GROUP_ADVANCED" );
410       theGroups[ key ].push_back( group );
411
412       // 1D hypotheses
413       key = 01;
414       //        0: Basic
415       group.Label = "GROUP:" + QObject::tr( "SMESH_1D_HYP_GROUP_BASIC" );
416       theGroups[ key ].push_back( group );
417       //        1: Progression
418       group.Label = "GROUP:" + QObject::tr( "SMESH_1D_HYP_GROUP_PROGRESSION" );
419       theGroups[ key ].push_back( group );
420       //        2: Advanced
421       group.Label = "GROUP:" + QObject::tr( "SMESH_1D_HYP_GROUP_ADVANCED" );
422       theGroups[ key ].push_back( group );
423
424       // 2D algo
425       key = 12;
426       //        0: Regular
427       group.Label = "GROUP:" + QObject::tr( "SMESH_2D_ALGO_GROUP_REGULAR" );
428       theGroups[ key ].push_back( group );
429       //        1: Free
430       group.Label = "GROUP:" + QObject::tr( "SMESH_2D_ALGO_GROUP_FREE" );
431       theGroups[ key ].push_back( group );
432       //        2: Advanced
433       group.Label = "GROUP:" + QObject::tr( "SMESH_2D_ALGO_GROUP_ADVANCED" );
434       theGroups[ key ].push_back( group );
435
436       // 3D algo
437       key = 13;
438       //        0: Regular
439       group.Label = "GROUP:" + QObject::tr( "SMESH_3D_ALGO_GROUP_REGULAR" );
440       theGroups[ key ].push_back( group );
441       //        1: Free
442       group.Label = "GROUP:" + QObject::tr( "SMESH_3D_ALGO_GROUP_FREE" );
443       theGroups[ key ].push_back( group );
444       //        2: Advanced
445       group.Label = "GROUP:" + QObject::tr( "SMESH_3D_ALGO_GROUP_ADVANCED" );
446       theGroups[ key ].push_back( group );
447     }
448
449     size_t key = 0, groupID = 0;
450     if ( hyp && !hyp->Dim.isEmpty() )
451     {
452       key     = hyp->Dim[0] + isAlgo * 10;
453       groupID = hyp->GroupID;
454     }
455
456     if ( key < theGroups.size() && !theGroups[ key ].empty() )
457     {
458       std::vector< HypothesisData > & group = theGroups[ key ];
459       return & ( groupID < group.size() ? group[ groupID ] : group.back() );
460     }
461     return & theGroups[ 0 ][ 0 ];
462   }
463
464   bool IsAvailableHypothesis(const HypothesisData* algoData,
465                              const QString&        hypType,
466                              bool&                 isAuxiliary)
467   {
468     isAuxiliary = false;
469     if ( !algoData )
470       return false;
471     if ( algoData->BasicHypos.contains( hypType ))
472       return true;
473     if ( algoData->OptionalHypos.contains( hypType )) {
474       isAuxiliary = true;
475       return true;
476     }
477     return false;
478   }
479
480   bool IsCompatibleAlgorithm(const HypothesisData* algo1Data,
481                              const HypothesisData* algo2Data)
482   {
483     if ( !algo1Data || !algo2Data )
484       return false;
485     const HypothesisData* algoIn = algo1Data, *algoMain = algo2Data;
486     if ( algoIn->Dim.first() > algoMain->Dim.first() ) {
487       algoIn = algo2Data; algoMain = algo1Data;
488     }
489     // look for any output type of algoIn between input types of algoMain
490     QStringList::const_iterator inElemType = algoIn->OutputTypes.begin();
491     for ( ; inElemType != algoIn->OutputTypes.end(); ++inElemType )
492       if ( algoMain->InputTypes.contains( *inElemType ))
493         return true;
494     return false;
495   }
496
497   SMESHGUI_GenericHypothesisCreator* GetHypothesisCreator(const QString& aHypType)
498   {
499     if(MYDEBUG) MESSAGE("Get HypothesisCreator for " << aHypType.toLatin1().data());
500
501     SMESHGUI_GenericHypothesisCreator* aCreator = 0;
502
503     // check, if creator for this hypothesis type already exists
504     // BUG 0020378
505     //if (myHypCreatorMap.find(aHypType) != myHypCreatorMap.end()) {
506     //  aCreator = myHypCreatorMap[aHypType];
507     //}
508     //else
509     {
510       // 1. Init list of available hypotheses, if needed
511       InitAvailableHypotheses();
512
513       // 2. Get names of plugin libraries
514       HypothesisData* aHypData = GetHypothesisData(aHypType);
515       if (!aHypData)
516         return aCreator;
517
518       QString aClientLibName = aHypData->ClientLibName;
519       QString aServerLibName = aHypData->ServerLibName;
520
521       // 3. Load Client Plugin Library
522       try {
523         // load plugin library
524         if(MYDEBUG) MESSAGE("Loading client meshers plugin library ...");
525 #ifdef WIN32
526 #ifdef UNICODE
527         LPTSTR path = new TCHAR[aClientLibName.length() + 1];
528         path[aClientLibName.toWCharArray(path)] = '\0';
529 #else
530         QByteArray baPath = aClientLibName.toUtf8();
531         const char* path = baPath.data();
532 #endif
533 #else
534         QByteArray baPath = aClientLibName.toUtf8();
535         char* path = baPath.data();
536 #endif
537         LibHandle libHandle = LoadLib( path );
538 #if defined(WIN32) && defined(UNICODE)
539       delete path;
540 #endif
541         if (!libHandle) {
542           // report any error, if occurred
543           {
544 #ifdef WIN32
545             const char* anError = "Can't load client meshers plugin library";
546 #else
547             const char* anError = dlerror();
548 #endif
549             INFOS(anError); // always display this kind of error !
550           }
551         }
552         else {
553           // get method, returning hypothesis creator
554           if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
555           typedef SMESHGUI_GenericHypothesisCreator* (*GetHypothesisCreator) \
556             ( const QString& );
557           GetHypothesisCreator procHandle =
558             (GetHypothesisCreator)GetProc(libHandle, "GetHypothesisCreator");
559           if (!procHandle) {
560             if(MYDEBUG) MESSAGE("bad hypothesis client plugin library");
561             UnLoadLib(libHandle);
562           }
563           else {
564             // get hypothesis creator
565             if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << aHypType.toLatin1().data());
566             aCreator = procHandle( aHypType );
567             if (!aCreator) {
568               if(MYDEBUG) MESSAGE("no such a hypothesis in this plugin");
569             }
570             else {
571               // map hypothesis creator to a hypothesis name
572               // BUG 0020378
573               //myHypCreatorMap[aHypType] = aCreator;
574
575               //rnv : This dynamic property of the QObject stores the name of the plugin.
576               //      It is used to obtain plugin root dir environment variable
577               //      in the SMESHGUI_HypothesisDlg class. Plugin root dir environment
578               //      variable is used to display documentation.
579               aCreator->setProperty(SMESH::Plugin_Name(),aHypData->PluginName);
580             }
581           }
582         }
583       }
584       catch (const SALOME::SALOME_Exception& S_ex) {
585         SalomeApp_Tools::QtCatchCorbaException(S_ex);
586       }
587     }
588
589     return aCreator;
590   }
591
592
593   SMESH::SMESH_Hypothesis_ptr CreateHypothesis(const QString& aHypType,
594                                                const QString& aHypName,
595                                                const bool isAlgo)
596   {
597     if(MYDEBUG) MESSAGE("Create " << aHypType.toLatin1().data() <<
598                         " with name " << aHypName.toLatin1().data());
599     HypothesisData* aHypData = GetHypothesisData(aHypType);
600     QString aServLib = aHypData->ServerLibName;
601     try {
602       SMESH::SMESH_Hypothesis_var aHypothesis;
603       aHypothesis = SMESHGUI::GetSMESHGen()->CreateHypothesis(aHypType.toLatin1().data(),
604                                                               aServLib.toUtf8().data());
605       if (!aHypothesis->_is_nil()) {
606         _PTR(SObject) aHypSObject = SMESH::FindSObject(aHypothesis.in());
607         if (aHypSObject) {
608           if (!aHypName.isEmpty())
609             SMESH::SetName(aHypSObject, aHypName);
610           SMESHGUI::Modified();
611           SMESHGUI::GetSMESHGUI()->updateObjBrowser();
612           return aHypothesis._retn();
613         }
614       }
615     } catch (const SALOME::SALOME_Exception & S_ex) {
616       SalomeApp_Tools::QtCatchCorbaException(S_ex);
617     }
618
619     return SMESH::SMESH_Hypothesis::_nil();
620   }
621
622   bool IsApplicable(const QString&        aHypType,
623                     GEOM::GEOM_Object_ptr theGeomObject,
624                     const bool            toCheckAll)
625   {
626     if ( getenv("NO_LIMIT_ALGO_BY_SHAPE")) // allow a workaround for a case if
627       return true;                         // IsApplicable() returns false due to a bug
628
629     HypothesisData* aHypData = GetHypothesisData(aHypType);
630     QString aServLib = aHypData->ServerLibName;
631     return SMESHGUI::GetSMESHGen()->IsApplicable( aHypType.toLatin1().data(),
632                                                   aServLib.toUtf8().data(),
633                                                   theGeomObject,
634                                                   toCheckAll);
635   }
636
637
638   bool AddHypothesisOnMesh (SMESH::SMESH_Mesh_ptr aMesh, SMESH::SMESH_Hypothesis_ptr aHyp)
639   {
640     if(MYDEBUG) MESSAGE ("SMESHGUI::AddHypothesisOnMesh");
641     int res = SMESH::HYP_UNKNOWN_FATAL;
642     SUIT_OverrideCursor wc;
643
644     if (!aMesh->_is_nil()) {
645       _PTR(SObject) SM = SMESH::FindSObject(aMesh);
646       GEOM::GEOM_Object_var aShapeObject = SMESH::GetShapeOnMeshOrSubMesh(SM);
647       try {
648         CORBA::String_var error;
649         res = aMesh->AddHypothesis(aShapeObject, aHyp, error.out());
650         if (res > SMESH::HYP_OK) {
651           wc.suspend();
652           processHypothesisStatus(res, aHyp, true, error.in() );
653           wc.resume();
654         }
655       }
656       catch(const SALOME::SALOME_Exception& S_ex) {
657         wc.suspend();
658         SalomeApp_Tools::QtCatchCorbaException(S_ex);
659         res = SMESH::HYP_UNKNOWN_FATAL;
660       }
661     }
662     return res < SMESH::HYP_UNKNOWN_FATAL;
663   }
664
665
666   bool AddHypothesisOnSubMesh (SMESH::SMESH_subMesh_ptr aSubMesh, SMESH::SMESH_Hypothesis_ptr aHyp)
667   {
668     if(MYDEBUG) MESSAGE("SMESHGUI::AddHypothesisOnSubMesh() ");
669     int res = SMESH::HYP_UNKNOWN_FATAL;
670     SUIT_OverrideCursor wc;
671
672     if ( !aSubMesh->_is_nil() && !aHyp->_is_nil() ) {
673       try {
674         SMESH::SMESH_Mesh_var aMesh = aSubMesh->GetFather();
675         _PTR(SObject) SsubM = SMESH::FindSObject(aSubMesh);
676         GEOM::GEOM_Object_var aShapeObject = SMESH::GetShapeOnMeshOrSubMesh(SsubM);
677         if (!aMesh->_is_nil() && SsubM && !aShapeObject->_is_nil())
678         {
679           CORBA::String_var error;
680           res = aMesh->AddHypothesis( aShapeObject, aHyp, error.out() );
681           if (res > SMESH::HYP_OK) {
682             wc.suspend();
683             processHypothesisStatus( res, aHyp, true, error.in() );
684             wc.resume();
685           }
686         }
687         else {
688           SCRUTE(aHyp->_is_nil());
689           SCRUTE(aMesh->_is_nil());
690           SCRUTE(!SsubM);
691           SCRUTE(aShapeObject->_is_nil());
692         }
693       }
694       catch(const SALOME::SALOME_Exception& S_ex) {
695         wc.suspend();
696         SalomeApp_Tools::QtCatchCorbaException(S_ex);
697         res = SMESH::HYP_UNKNOWN_FATAL;
698       }
699     }
700     else {
701       SCRUTE(aSubMesh->_is_nil());
702       SCRUTE(aHyp->_is_nil());
703     }
704     return res < SMESH::HYP_UNKNOWN_FATAL;
705   }
706
707   bool RemoveHypothesisOrAlgorithmOnMesh (const Handle(SALOME_InteractiveObject)& IObject)
708   {
709     int res = SMESH::HYP_UNKNOWN_FATAL;
710     SUIT_OverrideCursor wc;
711
712     try {
713       _PTR(Study) aStudy = getStudy();
714       _PTR(SObject) aHypObj = aStudy->FindObjectID( IObject->getEntry() );
715       if( aHypObj )
716       {
717         _PTR(SObject) MorSM = SMESH::GetMeshOrSubmesh( aHypObj );
718         _PTR(SObject) aRealHypo;
719         if( aHypObj->ReferencedObject( aRealHypo ) )
720         {
721           SMESH_Hypothesis_var hypo = SMESH_Hypothesis::_narrow( SObjectToObject( aRealHypo ) );
722           RemoveHypothesisOrAlgorithmOnMesh( MorSM, hypo );
723         }
724         else
725         {
726           SMESH_Hypothesis_var hypo = SMESH_Hypothesis::_narrow( SObjectToObject( aHypObj ) );
727           SObjectList meshList = GetMeshesUsingAlgoOrHypothesis( hypo );
728           for( size_t i = 0; i < meshList.size(); i++ )
729             RemoveHypothesisOrAlgorithmOnMesh( meshList[ i ], hypo );
730         }
731       }
732     }
733     catch(const SALOME::SALOME_Exception& S_ex)
734     {
735       wc.suspend();
736       SalomeApp_Tools::QtCatchCorbaException(S_ex);
737       res = SMESH::HYP_UNKNOWN_FATAL;
738     }
739     return res < SMESH::HYP_UNKNOWN_FATAL;
740   }
741
742   bool RemoveHypothesisOrAlgorithmOnMesh (_PTR(SObject)               MorSM,
743                                           SMESH::SMESH_Hypothesis_ptr anHyp)
744   {
745     int res = SMESH::HYP_UNKNOWN_FATAL;
746     SUIT_OverrideCursor wc;
747
748     if (MorSM) {
749       try {
750         GEOM::GEOM_Object_var aShapeObject = SMESH::GetShapeOnMeshOrSubMesh(MorSM);
751         SMESH::SMESH_Mesh_var aMesh        = SMESH::SObjectToInterface<SMESH::SMESH_Mesh>(MorSM);
752         SMESH::SMESH_subMesh_var aSubMesh  = SMESH::SObjectToInterface<SMESH::SMESH_subMesh>(MorSM);
753
754         if (!aSubMesh->_is_nil())
755           aMesh = aSubMesh->GetFather();
756
757         if (!aMesh->_is_nil()) {
758           if (aMesh->HasShapeToMesh() && !aShapeObject->_is_nil()) {
759             res = aMesh->RemoveHypothesis(aShapeObject, anHyp);
760           }
761           else if(!aMesh->HasShapeToMesh()){
762             res = aMesh->RemoveHypothesis(aShapeObject, anHyp);
763           }
764           if (res > SMESH::HYP_OK) {
765             wc.suspend();
766             processHypothesisStatus(res, anHyp, false);
767             wc.resume();
768           }
769           if ( _PTR(SObject) meshSO = SMESH::FindSObject(aMesh) )
770           {
771             if ( SMESH_Actor* actor = SMESH::FindActorByEntry( meshSO->GetID().c_str() ))
772               if( actor->GetVisibility() )
773                 actor->Update();
774           }
775         }
776       } catch(const SALOME::SALOME_Exception& S_ex) {
777         wc.suspend();
778         SalomeApp_Tools::QtCatchCorbaException(S_ex);
779         res = SMESH::HYP_UNKNOWN_FATAL;
780       }
781     }
782     return res < SMESH::HYP_UNKNOWN_FATAL;
783   }
784
785   SObjectList GetMeshesUsingAlgoOrHypothesis(SMESH::SMESH_Hypothesis_ptr AlgoOrHyp)
786   {
787     SObjectList listSOmesh;
788     listSOmesh.resize(0);
789
790     unsigned int index = 0;
791     if (!AlgoOrHyp->_is_nil()) {
792       _PTR(SObject) SO_Hypothesis = SMESH::FindSObject(AlgoOrHyp);
793       if (SO_Hypothesis) {
794         SObjectList listSO = SMESH::getStudy()->FindDependances(SO_Hypothesis);
795
796         if(MYDEBUG) MESSAGE("SMESHGUI::GetMeshesUsingAlgoOrHypothesis(): dependency number ="<<listSO.size());
797         for (unsigned int i = 0; i < listSO.size(); i++) {
798           _PTR(SObject) SO = listSO[i];
799           if (SO) {
800             _PTR(SObject) aFather = SO->GetFather();
801             if (aFather) {
802               _PTR(SObject) SOfatherFather = aFather->GetFather();
803               if (SOfatherFather) {
804                 if(MYDEBUG) MESSAGE("SMESHGUI::GetMeshesUsingAlgoOrHypothesis(): dependency added to list");
805                 index++;
806                 listSOmesh.resize(index);
807                 listSOmesh[index - 1] = SOfatherFather;
808               }
809             }
810           }
811         }
812       }
813     }
814     if (MYDEBUG) MESSAGE("SMESHGUI::GetMeshesUsingAlgoOrHypothesis(): completed");
815     return listSOmesh;
816   }
817
818 #define CASE2MESSAGE(enum) case SMESH::enum: msg = QObject::tr( "STATE_" #enum ); break;
819   QString GetMessageOnAlgoStateErrors(const algo_error_array& errors)
820   {
821     QString resMsg; // PAL14861 = QObject::tr("SMESH_WRN_MISSING_PARAMETERS") + ":\n";
822     for ( size_t i = 0; i < errors.length(); ++i ) {
823       const SMESH::AlgoStateError & error = errors[ i ];
824       const bool hasAlgo = ( strlen( error.algoName ) != 0 );
825       QString msg;
826       if ( !hasAlgo )
827         msg = QObject::tr( "STATE_ALGO_MISSING" );
828       else
829         switch( error.state ) {
830           CASE2MESSAGE( HYP_MISSING );
831           CASE2MESSAGE( HYP_NOTCONFORM );
832           CASE2MESSAGE( HYP_BAD_PARAMETER );
833           CASE2MESSAGE( HYP_BAD_GEOMETRY );
834         default: continue;
835         }
836       // apply args to message:
837       // %1 - algo name
838       if ( hasAlgo )
839         msg = msg.arg( error.algoName.in() );
840       // %2 - dimension
841       msg = msg.arg( error.algoDim );
842       // %3 - global/local
843       msg = msg.arg( QObject::tr( error.isGlobalAlgo ? "GLOBAL_ALGO" : "LOCAL_ALGO" ));
844       // %4 - hypothesis dim == algoDim
845       msg = msg.arg( error.algoDim );
846
847       if ( i ) resMsg += ";\n";
848       resMsg += msg;
849     }
850     return resMsg;
851   }
852 } // end of namespace SMESH