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