Salome HOME
version 5_1_4 HOMARD_SRC
[modules/homard.git] / src / HOMARD_I / HOMARD_Gen_i.cxx
1 #include "HOMARD_Gen_i.hxx"
2 #include "HOMARD_Cas_i.hxx"
3 #include "HOMARD_Hypothesis_i.hxx"
4 #include "HOMARD_Iteration_i.hxx"
5 #include "HOMARD_Boundary_i.hxx"
6 #include "HOMARD_Zone_i.hxx"
7 #include "HomardDriver.hxx"
8 #include "HOMARD_DriverTools.hxx"
9 #include "HomardMedCommun.h"
10
11 #include "utilities.h"
12 #include "Utils_SINGLETON.hxx"
13 #include "Utils_CorbaException.hxx"
14 #include "SALOMEDS_Tool.hxx"
15 #include "SALOME_LifeCycleCORBA.hxx"
16 #include "SALOMEconfig.h"
17 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
18 #include CORBA_CLIENT_HEADER(SMESH_Gen)
19
20 #include <stdlib.h>
21 #include <sys/stat.h>
22 #include <dirent.h>
23 #include <string>
24 #include <iostream>
25 #include <iomanip>
26 #include <sys/stat.h>
27 #include <set>
28 #include <vector>
29 #include <stdio.h>
30
31
32 using  namespace std;
33
34 //=============================================================================
35 /*!
36  *  standard constructor
37  */
38 //=============================================================================
39 HOMARD_Gen_i::HOMARD_Gen_i(CORBA::ORB_ptr orb,
40                            PortableServer::POA_ptr poa,
41                            PortableServer::ObjectId * contId, 
42                            const char *instanceName, 
43                            const char *interfaceName) :
44   Engines_Component_i(orb, poa, contId, instanceName, interfaceName)
45 {
46   MESSAGE("activate object");
47   _thisObj = this;
48   _id = _poa->activate_object(_thisObj);
49
50   myHomard = new ::HOMARD_Gen();
51   _NS = SINGLETON_<SALOME_NamingService>::Instance();
52   ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
53   _NS->init_orb(_orb);
54 }
55
56 //=================================
57 /*!
58  *  standard destructor
59  */
60 //================================
61 HOMARD_Gen_i::~HOMARD_Gen_i()
62 {
63 }
64 //=============================================================================
65 /*!
66  *  Ajoute le composant homard dans l etude si necessaire 
67  */
68 //=============================================================================
69 void HOMARD_Gen_i::addInStudy(SALOMEDS::Study_ptr theStudy)
70 {
71   ASSERT(!CORBA::is_nil(theStudy));
72   MESSAGE("addInStudy: current study ID = " << GetCurrentStudyID());
73   SALOMEDS::StudyBuilder_var myBuilder = theStudy->NewBuilder();
74  
75   // Create SComponent labelled 'homard' if it doesn't already exit
76   SALOMEDS::SComponent_var homardFather = theStudy->FindComponent(ComponentDataType());
77   if (CORBA::is_nil(homardFather))
78   {
79     myBuilder->NewCommand();
80     MESSAGE("Add Component HOMARD");
81
82     bool aLocked = theStudy->GetProperties()->IsLocked();
83     if (aLocked) theStudy->GetProperties()->SetLocked(false);
84     
85     homardFather = myBuilder->NewComponent(ComponentDataType());
86     SALOMEDS::GenericAttribute_var anAttr = myBuilder->FindOrCreateAttribute(homardFather,"AttributeName");
87     SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(anAttr);
88     CORBA::Object_var objVarN = _NS->Resolve("/Kernel/ModulCatalog");
89     SALOME_ModuleCatalog::ModuleCatalog_var Catalogue = 
90                 SALOME_ModuleCatalog::ModuleCatalog::_narrow(objVarN);
91     SALOME_ModuleCatalog::Acomponent_var Comp = Catalogue->GetComponent(ComponentDataType());
92     if (!Comp->_is_nil()) 
93     {
94       aName->SetValue(ComponentDataType());
95     }
96
97     anAttr = myBuilder->FindOrCreateAttribute(homardFather,"AttributePixMap");
98     SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr);
99     aPixmap->SetPixMap("HOMARD_2.png");
100     myBuilder->DefineComponentInstance(homardFather, HOMARD_Gen::_this());
101
102     if (aLocked) theStudy->GetProperties()->SetLocked(true);
103     myBuilder->CommitCommand();
104   }
105 }
106
107 //=============================================================================
108 /*!
109  *
110  *  Set current study
111  */
112 //=============================================================================
113 void HOMARD_Gen_i::SetCurrentStudy(SALOMEDS::Study_ptr theStudy)
114 {
115   MESSAGE("SetCurrentStudy: current study Id = " << GetCurrentStudyID());
116   myCurrentStudy = SALOMEDS::Study::_duplicate(theStudy);
117   this->addInStudy(myCurrentStudy);
118 }
119
120 //=============================================================================
121 SALOMEDS::Study_ptr HOMARD_Gen_i::GetCurrentStudy()
122 //=============================================================================
123 {
124   MESSAGE("GetCurrentStudy: study Id = " << GetCurrentStudyID());
125   return SALOMEDS::Study::_duplicate(myCurrentStudy);
126 }
127
128 //=============================================================================
129 int HOMARD_Gen_i::GetCurrentStudyID()
130 //=============================================================================
131 {
132   return myCurrentStudy->_is_nil() ? -1 : myCurrentStudy->StudyId();
133 }
134
135 //=============================================================================
136 void HOMARD_Gen_i::AssociateCaseIter(const char* nomCas, const char* nomIter, const char* labelIter)
137 {
138   MESSAGE( "AssociateCaseIter " << nomCas << " ," << nomIter << ","  << labelIter );
139   if (CORBA::is_nil(myCurrentStudy))
140   {
141       SALOME::ExceptionStruct es;
142       es.type = SALOME::BAD_PARAM;
143       es.text = "Invalid Study Context ";
144       throw SALOME::SALOME_Exception(es);
145       return ;
146   };
147
148   HOMARD::HOMARD_Cas_var myCase = myContextMap[GetCurrentStudyID()]._mesCas[nomCas];
149   if (CORBA::is_nil(myCase))
150   {
151       SALOME::ExceptionStruct es;
152       es.type = SALOME::BAD_PARAM;
153       es.text = "Invalid Case ";
154       throw SALOME::SALOME_Exception(es);
155       return ;
156   };
157
158   HOMARD::HOMARD_Iteration_var myIteration = myContextMap[GetCurrentStudyID()]._mesIterations[nomIter];
159   if (CORBA::is_nil(myIteration))
160   {
161       SALOME::ExceptionStruct es;
162       es.type = SALOME::BAD_PARAM;
163       es.text = "Invalid Case ";
164       throw SALOME::SALOME_Exception(es);
165       return ;
166   };
167
168   SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
169   SALOMEDS::SObject_var aCasSO = SALOMEDS::SObject::_narrow(myCurrentStudy->FindObjectIOR(_orb->object_to_string(myCase)));
170   if (CORBA::is_nil(aCasSO))
171   {
172       SALOME::ExceptionStruct es;
173       es.type = SALOME::BAD_PARAM;
174       es.text = "Invalid Case ";
175       throw SALOME::SALOME_Exception(es);
176       return ;
177   };
178
179   aStudyBuilder->NewCommand();
180   SALOMEDS::SObject_var newStudyIter = aStudyBuilder->NewObject(aCasSO);
181   PublishInStudyAttr(aStudyBuilder, newStudyIter, nomIter , labelIter, 
182                      "iter_non_calculee.png", _orb->object_to_string(myIteration)) ;
183   aStudyBuilder->CommitCommand();
184
185   myCase->AddIteration(nomIter);
186   myIteration->SetCaseName(nomCas);
187 }
188
189 //=====================================================================================
190 void HOMARD_Gen_i::SetEtatIter(const char* nomIter, const bool EtatCalcul)
191 //=====================================================================================
192 {
193   MESSAGE( "SetEtatIter, nomIter  = " << nomIter << " etat " << EtatCalcul );
194   HOMARD::HOMARD_Iteration_var myIteration = myContextMap[GetCurrentStudyID()]._mesIterations[nomIter];
195   if (CORBA::is_nil(myIteration))
196   {
197       SALOME::ExceptionStruct es;
198       es.type = SALOME::BAD_PARAM;
199       es.text = "Invalid Iteration ";
200       throw SALOME::SALOME_Exception(es);
201       return ;
202   };
203
204   myIteration->SetEtat(EtatCalcul);
205
206   SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
207   SALOMEDS::SObject_var aIterSO = SALOMEDS::SObject::_narrow(myCurrentStudy->FindObjectIOR(_orb->object_to_string(myIteration)));
208   if (CORBA::is_nil(myIteration))
209   {
210       SALOME::ExceptionStruct es;
211       es.type = SALOME::BAD_PARAM;
212       es.text = "Invalid Iteration ";
213       throw SALOME::SALOME_Exception(es);
214       return ;
215   };
216
217   int number = myIteration->GetNumber() ;
218   if ( number == 0 )  
219       PublishInStudyAttr(aStudyBuilder, aIterSO, NULL , NULL, "iter0.png", NULL) ;
220   else if (EtatCalcul) 
221       PublishInStudyAttr(aStudyBuilder, aIterSO, NULL, NULL, "iter_calculee.png", NULL) ;
222   else                 
223       PublishInStudyAttr(aStudyBuilder, aIterSO, NULL, NULL, "iter_non_calculee.png", NULL) ;
224
225   aStudyBuilder->CommitCommand();
226
227 }
228 //=====================================================================================
229 void HOMARD_Gen_i::InvalideZone(const char* ZoneName)
230 //=====================================================================================
231 {
232   MESSAGE( "InvalideZone, ZoneName    = " << ZoneName  );
233   HOMARD::HOMARD_Zone_var myZone = myContextMap[GetCurrentStudyID()]._mesZones[ZoneName];
234   if (CORBA::is_nil(myZone))
235   {
236       SALOME::ExceptionStruct es;
237       es.type = SALOME::BAD_PARAM;
238       es.text = "Invalid Zone ";
239       throw SALOME::SALOME_Exception(es);
240       return ;
241   };
242   HOMARD::listeHypo* maListe = myZone->GetHypo();
243   int numberOfHypo = maListe->length();
244   for (int NumeHypo = 0; NumeHypo< numberOfHypo; NumeHypo++)
245   {
246       std::string nomHypo = std::string((*maListe)[NumeHypo]);
247       InvalideHypo(nomHypo.c_str());
248   }
249 }
250 //=====================================================================================
251 void HOMARD_Gen_i::InvalideHypo(const char* nomHypo)
252 //=====================================================================================
253 {
254   MESSAGE( "InvalideHypo, nomHypo    = " << nomHypo  );
255   HOMARD::HOMARD_Hypothesis_var myHypo = myContextMap[GetCurrentStudyID()]._mesHypotheses[nomHypo];
256   if (CORBA::is_nil(myHypo))
257   {
258       SALOME::ExceptionStruct es;
259       es.type = SALOME::BAD_PARAM;
260       es.text = "Invalid Hypothesis ";
261       throw SALOME::SALOME_Exception(es);
262       return ;
263   };
264
265   HOMARD::listeIters* maListe = myHypo->GetIterations();
266   int numberOfIter = maListe->length();
267   for (int NumeIter = 0; NumeIter< numberOfIter; NumeIter++)
268   {
269       std::string nomIter = std::string((*maListe)[NumeIter]);
270       InvalideIter(nomIter.c_str());
271   }
272 }
273 //
274 //=====================================================================================
275 void HOMARD_Gen_i::InvalideIter(const char* nomIter)
276 //=====================================================================================
277 {
278   MESSAGE("InvalideIter, nomIter    = " << nomIter);
279   SetEtatIter(nomIter,false);
280   HOMARD::HOMARD_Iteration_var myIteration = myContextMap[GetCurrentStudyID()]._mesIterations[nomIter];
281   if (CORBA::is_nil(myIteration))
282   {
283       SALOME::ExceptionStruct es;
284       es.type = SALOME::BAD_PARAM;
285       es.text = "Invalid Iteration ";
286       throw SALOME::SALOME_Exception(es);
287       return ;
288   };
289
290   HOMARD::listeIterFilles* maListe = myIteration->GetIterations();
291   int numberOfIter = maListe->length();
292   for (int NumeIter = 0; NumeIter< numberOfIter; NumeIter++)
293   {
294       std::string nomIterFille = std::string((*maListe)[NumeIter]);
295       InvalideIter(nomIterFille.c_str());
296   }
297
298   SALOMEDS::SObject_var aIterSO = SALOMEDS::SObject::_narrow(myCurrentStudy->FindObjectIOR(_orb->object_to_string(myIteration)));
299   SALOMEDS::ChildIterator_var  aIter = myCurrentStudy->NewChildIterator(aIterSO);
300   for (; aIter->More(); aIter->Next()) 
301   {
302       SALOMEDS::SObject_var so = aIter->Value();
303       SALOMEDS::GenericAttribute_var anAttr;
304       if (!so->FindAttribute(anAttr, "AttributeComment")) continue;
305       SALOMEDS::AttributeComment_var aCommentAttr = SALOMEDS::AttributeComment::_narrow(anAttr);
306       std::string value (aCommentAttr->Value());
307       if(value == std::string("HypoHomard")) continue;
308       SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
309       aStudyBuilder->RemoveObject(so);
310   }
311   const char * nomCas = myIteration->GetCaseName();
312   HOMARD::HOMARD_Cas_var myCase = myContextMap[GetCurrentStudyID()]._mesCas[nomCas];
313   if (CORBA::is_nil(myCase))
314   {
315       SALOME::ExceptionStruct es;
316       es.type = SALOME::BAD_PARAM;
317       es.text = "Invalid Case Context ";
318       throw SALOME::SALOME_Exception(es);
319       return ;
320   };
321   const char* dirParent  = myCase->GetDirName();
322   const char* nomDir     = myIteration->GetDirName();
323   const char* nomFichier = myIteration->GetMeshFile();
324   std::string commande= "rm -rf " + std::string(dirParent) + "/" + std::string(nomDir);
325   commande = commande + ";rm -rf " + std::string(nomFichier);
326   if ((system(commande.c_str())) != 0)
327   {
328         SALOME::ExceptionStruct es;
329         es.type = SALOME::BAD_PARAM;
330         es.text = "Menage du repertoire de calcul impossible" ;
331         throw SALOME::SALOME_Exception(es);
332         return ;
333   }
334 // Suppression du maillage publie dans SMESH
335   const char* MeshName = myIteration->GetMeshName();
336   DeleteResultInSmesh(nomFichier, MeshName) ;
337 }
338 //
339 //=====================================================================================
340 void HOMARD_Gen_i::AssociateHypoZone(const char* ZoneName, const char* nomHypothesis)
341 {
342   MESSAGE ( " AssociateHypoZone, ZoneName= " << ZoneName << ", nomHypo = " << nomHypothesis);
343
344   if (CORBA::is_nil(myCurrentStudy))
345   {
346       SALOME::ExceptionStruct es;
347       es.type = SALOME::BAD_PARAM;
348       es.text = "Invalid Study Context ";
349       throw SALOME::SALOME_Exception(es);
350       return ;
351   };
352
353   HOMARD::HOMARD_Hypothesis_var myHypo = myContextMap[GetCurrentStudyID()]._mesHypotheses[nomHypothesis];
354   ASSERT(!CORBA::is_nil(myHypo));
355   SALOMEDS::SObject_var aHypoSO = SALOMEDS::SObject::_narrow(myCurrentStudy->FindObjectIOR(_orb->object_to_string(myHypo)));
356   ASSERT(!CORBA::is_nil(aHypoSO));
357
358   HOMARD::HOMARD_Zone_var myZone = myContextMap[GetCurrentStudyID()]._mesZones[ZoneName];
359   ASSERT(!CORBA::is_nil(myZone));
360   SALOMEDS::SObject_var aZoneSO = SALOMEDS::SObject::_narrow(myCurrentStudy->FindObjectIOR(_orb->object_to_string(myZone)));
361   ASSERT(!CORBA::is_nil(aZoneSO));
362   SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
363   aStudyBuilder->NewCommand();
364
365   SALOMEDS::SObject_var aSubSO = aStudyBuilder->NewObject(aHypoSO);
366   aStudyBuilder->Addreference(aSubSO, aZoneSO);
367   aStudyBuilder->CommitCommand();
368
369   myZone->AddHypo(nomHypothesis);
370   myHypo->AddZone(ZoneName);
371 };
372
373 //=====================================================================================
374 void HOMARD_Gen_i::DissociateHypoZone(const char* ZoneName, const char* nomHypothesis)
375 {
376   MESSAGE ( " DissociateHypoZone, ZoneName= " << ZoneName << ", nomHypo = " << nomHypothesis);
377
378   if (CORBA::is_nil(myCurrentStudy))
379   {
380       SALOME::ExceptionStruct es;
381       es.type = SALOME::BAD_PARAM;
382       es.text = "Invalid Study Context ";
383       throw SALOME::SALOME_Exception(es);
384       return ;
385   };
386
387   HOMARD::HOMARD_Hypothesis_var myHypo = myContextMap[GetCurrentStudyID()]._mesHypotheses[nomHypothesis];
388   ASSERT(!CORBA::is_nil(myHypo));
389   SALOMEDS::SObject_var aHypoSO = SALOMEDS::SObject::_narrow(myCurrentStudy->FindObjectIOR(_orb->object_to_string(myHypo)));
390   ASSERT(!CORBA::is_nil(aHypoSO));
391
392   HOMARD::HOMARD_Zone_var myZone = myContextMap[GetCurrentStudyID()]._mesZones[ZoneName];
393   ASSERT(!CORBA::is_nil(myZone));
394   SALOMEDS::SObject_var aZoneSO = SALOMEDS::SObject::_narrow(myCurrentStudy->FindObjectIOR(_orb->object_to_string(myZone)));
395   ASSERT(!CORBA::is_nil(aZoneSO));
396
397
398   SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
399
400   SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator(aHypoSO);
401   for (; it->More(); it->Next())
402   {
403     SALOMEDS::SObject_var aHypObj = it->Value();
404     SALOMEDS::SObject_var ptrObj;
405     if (aHypObj->ReferencedObject(ptrObj)) 
406     {
407       if (std::string(ptrObj->GetName()) == std::string(aZoneSO->GetName()))
408       {
409         aStudyBuilder->NewCommand();
410         aStudyBuilder->RemoveObject(aHypObj);
411         aStudyBuilder->CommitCommand();
412         break;
413       }
414     }
415   }
416
417   myZone->SupprHypo(nomHypothesis);
418   myHypo->SupprZone(ZoneName);
419 };
420
421 //=============================================================================
422 void HOMARD_Gen_i::AssociateIterIter(const char* nomIterParent, const char* nomIter)
423 {
424   MESSAGE ( "AssociateIterIter, nomIter       = " << nomIter << " nomIterParent = " << nomIterParent);
425   if (CORBA::is_nil(myCurrentStudy))
426   {
427       SALOME::ExceptionStruct es;
428       es.type = SALOME::BAD_PARAM;
429       es.text = "Invalid Study Context ";
430       throw SALOME::SALOME_Exception(es);
431       return ;
432   };
433
434   HOMARD::HOMARD_Iteration_var myIterationParent = myContextMap[GetCurrentStudyID()]._mesIterations[nomIterParent];
435   ASSERT(!CORBA::is_nil(myIterationParent));
436   HOMARD::HOMARD_Iteration_var myIteration = myContextMap[GetCurrentStudyID()]._mesIterations[nomIter];
437   ASSERT(!CORBA::is_nil(myIteration));
438
439   myIterationParent->AddIteration(nomIter);
440   myIteration->SetIterParent(nomIterParent);
441 }
442
443 //===================================================================================
444 void HOMARD_Gen_i::AssociateIterHypo(const char* nomIter, const char* nomHypo)
445 {
446   MESSAGE("AssociateIterHypo, nomHypo = " << nomHypo << " nomIter = " << nomIter);
447
448   if (CORBA::is_nil(myCurrentStudy))
449   {
450       SALOME::ExceptionStruct es;
451       es.type = SALOME::BAD_PARAM;
452       es.text = "Invalid Study Context ";
453       throw SALOME::SALOME_Exception(es);
454       return ;
455   };
456
457   HOMARD::HOMARD_Hypothesis_var myHypo = myContextMap[GetCurrentStudyID()]._mesHypotheses[nomHypo];
458   ASSERT(!CORBA::is_nil(myHypo));
459   SALOMEDS::SObject_var aHypoSO = SALOMEDS::SObject::_narrow(myCurrentStudy->FindObjectIOR(_orb->object_to_string(myHypo)));
460   ASSERT(!CORBA::is_nil(aHypoSO));
461
462   HOMARD::HOMARD_Iteration_var myIteration = myContextMap[GetCurrentStudyID()]._mesIterations[nomIter];
463   ASSERT(!CORBA::is_nil(myIteration));
464   SALOMEDS::SObject_var aIterSO = SALOMEDS::SObject::_narrow(myCurrentStudy->FindObjectIOR(_orb->object_to_string(myIteration)));
465   ASSERT(!CORBA::is_nil(aIterSO));
466
467   SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
468
469   aStudyBuilder->NewCommand();
470
471   SALOMEDS::SObject_var aSubSO = aStudyBuilder->NewObject(aIterSO);
472   aStudyBuilder->Addreference(aSubSO, aHypoSO);
473
474   aStudyBuilder->CommitCommand();
475   
476   myIteration->SetHypoName(nomHypo);
477   myHypo->AddIteration(nomIter);
478 };
479
480 //=============================================================================
481 CORBA::Boolean HOMARD_Gen_i::VerifieDir(const char* nomDir)
482 {
483   std::map<std::string, HOMARD::HOMARD_Cas_var>::const_iterator it;
484   for (it  = myContextMap[GetCurrentStudyID()]._mesCas.begin();
485         it != myContextMap[GetCurrentStudyID()]._mesCas.end(); it++)
486   {
487    if (std::string(nomDir) == std::string(it->second->GetDirName())) return false;
488   }
489   return true;
490 }
491
492 //=============================================================================
493 HOMARD::HOMARD_Cas_ptr HOMARD_Gen_i::CreateCase(const char* nomCas, const char* MeshName, const char* FileName)
494 {
495   MESSAGE ( "CreateCase, nomCas   = " << nomCas << "MeshName = " << MeshName );
496   if (CORBA::is_nil(myCurrentStudy))
497   {
498       SALOME::ExceptionStruct es;
499       es.type = SALOME::BAD_PARAM;
500       es.text = "Invalid Study Context ";
501       throw SALOME::SALOME_Exception(es);
502       return 0;
503   };
504
505   if ((myContextMap[GetCurrentStudyID()]._mesCas).find(nomCas)!=(myContextMap[GetCurrentStudyID()]._mesCas).end())
506   {
507       SALOME::ExceptionStruct es;
508       es.type = SALOME::BAD_PARAM;
509       es.text = "This case has already been defined";
510       throw SALOME::SALOME_Exception(es);
511       return 0;
512   };
513
514   HOMARD::HOMARD_Cas_var myCase = newCase();
515   myCase->SetName(nomCas);
516   SALOMEDS::SObject_var aSO;
517   PublishInStudy(myCurrentStudy, aSO, myCase, nomCas);
518   myContextMap[GetCurrentStudyID()]._mesCas[nomCas] = myCase;
519
520
521   std::vector<double> LesExtremes =GetBoundingBoxInMedFile(FileName);
522   HOMARD::extrema_var aSeq = new HOMARD::extrema();
523   if (LesExtremes.size()!=10) { return false; } 
524   aSeq->length(10);
525   for (int i =0; i< LesExtremes.size(); i++)
526        aSeq[i]=LesExtremes[i];
527   myCase->SetBoundingBox(aSeq);
528
529   std::set<std::string> LesGroupes  =GetListeGroupesInMedFile(FileName);
530   HOMARD::ListGroupType_var aSeqGroupe = new HOMARD::ListGroupType;
531   aSeqGroupe->length(LesGroupes.size());
532   std::set<std::string>::const_iterator it;
533   int i = 0;
534   for (it=LesGroupes.begin() ; it != LesGroupes.end(); it++)
535      aSeqGroupe[i++]=(*it).c_str();
536   myCase->SetGroups(aSeqGroupe);
537
538 // Recherche d'un nom pour l'iteration 0. Par defaut, on prend le nom
539 // du maillage du cas. Si ce nom existe deja, on incremente avec 0, 1, 2, etc.
540   int monNum=0;
541   std::string nomIter = std::string(MeshName) ;
542   while ((myContextMap[GetCurrentStudyID()]._mesIterations).find(nomIter) != (myContextMap[GetCurrentStudyID()]._mesIterations.end()))
543   {
544      std::ostringstream nom;
545      nom << MeshName << monNum;
546      nomIter=nom.str();
547      monNum = monNum+1;
548   }
549
550   HOMARD::HOMARD_Iteration_var anIter = newIteration();
551   myContextMap[GetCurrentStudyID()]._mesIterations[nomIter] = anIter;
552   std::ostringstream DirName;
553   DirName << "I_00";
554
555   anIter->SetDirName(DirName.str().c_str());
556   anIter->SetName(nomIter.c_str());
557   anIter->SetMeshFile(FileName);
558   anIter->SetMeshName(MeshName);
559   anIter->SetNumber(0);
560
561   AssociateCaseIter (nomCas,nomIter.c_str(),"IterationHomard");
562   SetEtatIter(nomIter.c_str(),true);
563 //
564   PublishResultInSmesh(FileName, 0);
565
566   return HOMARD::HOMARD_Cas::_duplicate(myCase);
567 }
568
569 //=============================================================================
570 HOMARD::HOMARD_Cas_ptr HOMARD_Gen_i::GetCas(const char* nomCas)
571 {
572   if (CORBA::is_nil(myCurrentStudy))
573   {
574       SALOME::ExceptionStruct es;
575       es.type = SALOME::BAD_PARAM;
576       es.text = "Invalid Study Context ";
577       throw SALOME::SALOME_Exception(es);
578       return 0;
579   };
580   HOMARD::HOMARD_Cas_var myCase = myContextMap[GetCurrentStudyID()]._mesCas[nomCas];
581   if (CORBA::is_nil(myCase))
582   {
583       SALOME::ExceptionStruct es;
584       es.type = SALOME::BAD_PARAM;
585       es.text = "Invalid Case";
586       throw SALOME::SALOME_Exception(es);
587       return 0;
588   };
589   return HOMARD::HOMARD_Cas::_duplicate(myCase);
590 }
591
592 //=============================================================================
593 HOMARD::HOMARD_Zone_ptr HOMARD_Gen_i::GetZone(const char* ZoneName)
594 {
595   if (CORBA::is_nil(myCurrentStudy))
596   {
597       SALOME::ExceptionStruct es;
598       es.type = SALOME::BAD_PARAM;
599       es.text = "Invalid Study Context ";
600       throw SALOME::SALOME_Exception(es);
601       return 0;
602   };
603   HOMARD::HOMARD_Zone_var myZone = myContextMap[GetCurrentStudyID()]._mesZones[ZoneName];
604   ASSERT(!CORBA::is_nil(myZone));
605   return HOMARD::HOMARD_Zone::_duplicate(myZone);
606 }
607
608 //=============================================================================
609 HOMARD::HOMARD_Hypothesis_ptr HOMARD_Gen_i::GetHypothesis(const char* nomHypothesis)
610 {
611   if (CORBA::is_nil(myCurrentStudy))
612   {
613       SALOME::ExceptionStruct es;
614       es.type = SALOME::BAD_PARAM;
615       es.text = "Invalid Study Context ";
616       throw SALOME::SALOME_Exception(es);
617       return 0;
618   };
619
620   HOMARD::HOMARD_Hypothesis_var myHypothesis = myContextMap[GetCurrentStudyID()]._mesHypotheses[nomHypothesis];
621   ASSERT(!CORBA::is_nil(myHypothesis));
622   return HOMARD::HOMARD_Hypothesis::_duplicate(myHypothesis);
623 }
624
625 //=============================================================================
626 HOMARD::HOMARD_Iteration_ptr  HOMARD_Gen_i::GetIteration(const char* nomIteration)
627 {
628   if (CORBA::is_nil(myCurrentStudy))
629   {
630       SALOME::ExceptionStruct es;
631       es.type = SALOME::BAD_PARAM;
632       es.text = "Invalid Study Context ";
633       throw SALOME::SALOME_Exception(es);
634       return 0;
635   };
636   HOMARD::HOMARD_Iteration_var myIteration = myContextMap[GetCurrentStudyID()]._mesIterations[nomIteration];
637   ASSERT(!CORBA::is_nil(myIteration));
638   return HOMARD::HOMARD_Iteration::_duplicate(myIteration);
639 }
640 //=============================================================================
641 HOMARD::HOMARD_Boundary_ptr HOMARD_Gen_i::GetBoundary(const char* nomBoundary)
642 {
643   if (CORBA::is_nil(myCurrentStudy))
644   {
645       SALOME::ExceptionStruct es;
646       es.type = SALOME::BAD_PARAM;
647       es.text = "Invalid Study Context ";
648       throw SALOME::SALOME_Exception(es);
649       return 0;
650   };
651
652   HOMARD::HOMARD_Boundary_var myBoundary = myContextMap[GetCurrentStudyID()]._mesBoundarys[nomBoundary];
653   ASSERT(!CORBA::is_nil(myBoundary));
654   return HOMARD::HOMARD_Boundary::_duplicate(myBoundary);
655 }
656
657 //=============================================================================
658 HOMARD::HOMARD_Hypothesis_ptr HOMARD_Gen_i::CreateHypothesis(const char* nomHypothesis)
659 {
660   MESSAGE ( "CreateHypothesis, nomHypothesis  = " << nomHypothesis );
661   if (CORBA::is_nil(myCurrentStudy))
662   {
663       SALOME::ExceptionStruct es;
664       es.type = SALOME::BAD_PARAM;
665       es.text = "Invalid Study Context ";
666       throw SALOME::SALOME_Exception(es);
667       return 0;
668   };
669
670   if ((myContextMap[GetCurrentStudyID()]._mesHypotheses).find(nomHypothesis) != (myContextMap[GetCurrentStudyID()]._mesHypotheses).end())
671   {
672       SALOME::ExceptionStruct es;
673       es.type = SALOME::BAD_PARAM;
674       es.text = "This hypothesis is already defined.";
675       throw SALOME::SALOME_Exception(es);
676       return 0;
677     }
678
679   HOMARD::HOMARD_Hypothesis_var myHypothesis = newHypothesis();
680   myHypothesis->SetName(nomHypothesis);
681   myContextMap[GetCurrentStudyID()]._mesHypotheses[nomHypothesis] = myHypothesis;
682   SALOMEDS::SObject_var aSO;
683   PublishInStudy(myCurrentStudy, aSO, myHypothesis, nomHypothesis);
684
685   return HOMARD::HOMARD_Hypothesis::_duplicate(myHypothesis);
686 }
687
688 //============================================================================================================
689 HOMARD::HOMARD_Iteration_ptr HOMARD_Gen_i::CreateIteration(const char* nomIteration, const char* nomIterParent)
690 //============================================================================================================
691 {
692   MESSAGE ("CreateIteration, nomIteration  = " << nomIteration << "nomIterParent = " << nomIterParent);
693   if (CORBA::is_nil(myCurrentStudy))
694   {
695       SALOME::ExceptionStruct es;
696       es.type = SALOME::BAD_PARAM;
697       es.text = "Invalid Study Context ";
698       throw SALOME::SALOME_Exception(es);
699       return 0;
700   };
701
702   HOMARD::HOMARD_Iteration_var myIterationParent = myContextMap[GetCurrentStudyID()]._mesIterations[nomIterParent];
703   if (CORBA::is_nil(myIterationParent))
704   {
705       SALOME::ExceptionStruct es;
706       es.type = SALOME::BAD_PARAM;
707       es.text = "The parent iteration is not defined.";
708       throw SALOME::SALOME_Exception(es);
709       return 0;
710   };
711
712   const char* nomCas = GetCaseName(nomIterParent);
713   MESSAGE ("CreateIteration, nomCas = " << nomCas);
714   HOMARD::HOMARD_Cas_var myCase = myContextMap[GetCurrentStudyID()]._mesCas[nomCas];
715   if (CORBA::is_nil(myCase))
716   {
717       SALOME::ExceptionStruct es;
718       es.type = SALOME::BAD_PARAM;
719       es.text = "Invalid Case Context ";
720       throw SALOME::SALOME_Exception(es);
721       return 0;
722   };
723
724   if ((myContextMap[GetCurrentStudyID()]._mesIterations).find(nomIteration)!=(myContextMap[GetCurrentStudyID()]._mesIterations).end())
725   {
726       SALOME::ExceptionStruct es;
727       es.type = SALOME::BAD_PARAM;
728       es.text = "This iteration is already defined. ";
729       throw SALOME::SALOME_Exception(es);
730       return 0;
731   };
732
733    HOMARD::HOMARD_Iteration_var myIteration = newIteration();
734    if (CORBA::is_nil(myIteration))
735   {
736       SALOME::ExceptionStruct es;
737       es.type = SALOME::BAD_PARAM;
738       es.text = "Unable to create Iteration ";
739       throw SALOME::SALOME_Exception(es);
740       return 0;
741   };
742    myContextMap[GetCurrentStudyID()]._mesIterations[std::string(nomIteration)] = myIteration;
743    myIteration->SetName(nomIteration);
744    myIteration->SetMeshName(nomIteration);
745
746    int numero = myIterationParent->GetNumber() + 1;
747    myIteration->SetNumber(numero);
748
749 // Nombre d'iterations deja connues pour le cas, permettant
750 // la creation d'un sous-repertoire unique
751    int nbitercase = myCase->GetNumber();
752    std::ostringstream iaux ;
753    iaux << std::setw(2) << std::setfill('0') << nbitercase ;
754    std::stringstream DirName;
755    DirName << "I" << iaux.str();
756    myIteration->SetDirName(DirName.str().c_str());
757
758 // Le nom du fichier du maillage MED est indice par le nombre d'iterations du cas.
759 // Si on a une chaine unique depuis le depart, ce nombre est le meme que le
760 // numero d'iteration dans la sucession : maill.01.med, maill.02.med, etc... C'est le
761 // cas le plus frequent.
762 // Si on a plusieurs branches, donc des iterations a meme niveau d'adaptation, utiliser
763 // le nombre d'iterations du cas permet d'eviter les collisions.
764    std::stringstream FileName;
765    const char* nomDir = myCase->GetDirName();
766    FileName << nomDir << "/maill." << iaux.str() << ".med";
767    myIteration->SetMeshFile(FileName.str().c_str());
768
769 // Association avec le cas et l'iteration precedente
770    std::string label = "IterationHomard_" + std::string(nomIterParent);
771    AssociateCaseIter(nomCas, nomIteration, label.c_str());
772    AssociateIterIter (nomIterParent,nomIteration);
773
774    return HOMARD::HOMARD_Iteration::_duplicate(myIteration);
775 }
776
777
778 //=============================================================================
779 HOMARD::HOMARD_Boundary_ptr HOMARD_Gen_i::CreateBoundary(const char* BoundaryName, CORBA::Long BoundaryType)
780 {
781   MESSAGE ("BoundaryName  = " << BoundaryName << ", BoundaryType = " << BoundaryType);
782   if (CORBA::is_nil(myCurrentStudy))
783   {
784       SALOME::ExceptionStruct es;
785       es.type = SALOME::BAD_PARAM;
786       es.text = "Invalid Study Context ";
787       throw SALOME::SALOME_Exception(es);
788       return 0;
789   };
790
791   if ((myContextMap[GetCurrentStudyID()]._mesBoundarys).find(BoundaryName)!=(myContextMap[GetCurrentStudyID()]._mesBoundarys).end())
792   {
793       SALOME::ExceptionStruct es;
794       es.type = SALOME::BAD_PARAM;
795       es.text = "This boundary has already been defined";
796       throw SALOME::SALOME_Exception(es);
797       return 0;
798   };
799
800   HOMARD::HOMARD_Boundary_var myBoundary = newBoundary();
801   myBoundary->SetName(BoundaryName);
802   myBoundary->SetBoundaryType(BoundaryType);
803
804   myContextMap[GetCurrentStudyID()]._mesBoundarys[BoundaryName] = myBoundary;
805
806   SALOMEDS::SObject_var aSO;
807   SALOMEDS::SObject_var aResultSO=PublishInStudy(myCurrentStudy, aSO, myBoundary, BoundaryName);
808
809 // Limites par defaut pour initialiser en cas de lancement par python
810
811   return HOMARD::HOMARD_Boundary::_duplicate(myBoundary);
812 }
813
814
815 //=============================================================================
816 HOMARD::HOMARD_Zone_ptr HOMARD_Gen_i::CreateZone(const char* ZoneName, CORBA::Long ZoneType)
817 {
818   MESSAGE ("ZoneName  = " << ZoneName << ", ZoneType = " << ZoneType);
819   if (CORBA::is_nil(myCurrentStudy))
820   {
821       SALOME::ExceptionStruct es;
822       es.type = SALOME::BAD_PARAM;
823       es.text = "Invalid Study Context ";
824       throw SALOME::SALOME_Exception(es);
825       return 0;
826   };
827
828   if ((myContextMap[GetCurrentStudyID()]._mesZones).find(ZoneName)!=(myContextMap[GetCurrentStudyID()]._mesZones).end())
829   {
830       SALOME::ExceptionStruct es;
831       es.type = SALOME::BAD_PARAM;
832       es.text = "This zone has already been defined";
833       throw SALOME::SALOME_Exception(es);
834       return 0;
835   };
836
837   HOMARD::HOMARD_Zone_var myZone = newZone();
838   myZone->SetName(ZoneName);
839   myZone->SetZoneType(ZoneType);
840
841   myContextMap[GetCurrentStudyID()]._mesZones[ZoneName] = myZone;
842
843   SALOMEDS::SObject_var aSO;
844   SALOMEDS::SObject_var aResultSO=PublishInStudy(myCurrentStudy, aSO, myZone, ZoneName);
845
846   return HOMARD::HOMARD_Zone::_duplicate(myZone);
847 }
848
849 //=============================================================================
850 CORBA::Boolean HOMARD_Gen_i::Compute(const char* nomIteration, CORBA::Long etatMenage)
851 {
852   MESSAGE ( "Compute, calcul de " << nomIteration );
853   if (CORBA::is_nil(myCurrentStudy))
854   {
855       SALOME::ExceptionStruct es;
856       es.type = SALOME::BAD_PARAM;
857       es.text = "Invalid Study Context ";
858       throw SALOME::SALOME_Exception(es);
859       return 0;
860   };
861
862   HOMARD::HOMARD_Iteration_var myIteration = myContextMap[GetCurrentStudyID()]._mesIterations[nomIteration];
863   ASSERT(!CORBA::is_nil(myIteration));
864
865 // on ne calcule pas l iteration 0 
866   int NumeIter = myIteration->GetNumber();
867   if ( NumeIter == 0 )
868   {
869       SALOME::ExceptionStruct es;
870       es.type = SALOME::BAD_PARAM;
871       es.text = "This iteration is the first of the case and cannot be computed.";
872       throw SALOME::SALOME_Exception(es);
873       return 0;
874   };
875
876 // on verifie qu il y a une hypothese (erreur improbable);
877   const char* nomHypo = myIteration->GetHypoName();
878   if (std::string(nomHypo) == std::string(""))
879   {
880       SALOME::ExceptionStruct es;
881       es.type = SALOME::BAD_PARAM;
882       es.text = "Invalid Study Context ";
883       es.text= "This iteration  has no associated hypothese";
884       throw SALOME::SALOME_Exception(es);
885       return 0;
886   }
887   HOMARD::HOMARD_Hypothesis_var myHypo = myContextMap[GetCurrentStudyID()]._mesHypotheses[nomHypo];
888   ASSERT(!CORBA::is_nil(myHypo));
889
890
891
892   // A.4. L'iteration parent
893   const char* nomIterationParent = myIteration->GetIterParent();
894   HOMARD::HOMARD_Iteration_var myIterationParent = myContextMap[GetCurrentStudyID()]._mesIterations[nomIterationParent];
895   ASSERT(!CORBA::is_nil(myIterationParent));
896   if ( ! myIterationParent->GetEtat() )
897   {
898       /*
899       SALOME::ExceptionStruct es;
900       es.type = SALOME::BAD_PARAM;
901       std::string text = "The iteration cannot be computed because the previous iteration " + std::string(nomIterationParent) + " is not valid.";
902       es.text = CORBA::string_dup(text.c_str());
903       throw SALOME::SALOME_Exception(es);
904       return 0;
905       */
906       Compute(nomIterationParent, etatMenage);
907   };
908
909   const char* nomCas = myIteration->GetCaseName();
910   HOMARD::HOMARD_Cas_var myCase = myContextMap[GetCurrentStudyID()]._mesCas[nomCas];
911   ASSERT(!CORBA::is_nil(myCase));
912
913   int codret = 0;
914   std::stringstream saux0 ;
915   saux0 << NumeIter - 1 ;
916   std::string siter = saux0.str() ;
917   if (NumeIter < 11) { siter = "0" + siter ; }
918 //
919   std::stringstream saux1 ;
920   saux1 << NumeIter ;
921   std::string siterp1 = saux1.str() ;
922   if (NumeIter < 10) { siterp1 = "0" + siterp1 ; }
923
924   // A.3. Hypothese associee
925   // B. Les repertoires
926   // B.1. Le repertoire du cas
927   const char* nomDir = myCase->GetDirName();
928   MESSAGE ( ". nomDir = " << nomDir );
929
930   // B.2. Le sous-repertoire de l'iteration a calculer, puis le repertoire complet a creer
931   // B.2.1. Le nom du sous-repertoire
932    const char* nomDirIt = myIteration->GetDirName();
933
934   // B.2.2. Le nom complet du sous-repertoire
935   std::stringstream DirCompute ;
936   DirCompute << nomDir << "/" << nomDirIt;
937   MESSAGE (". DirCompute = " << DirCompute.str() );
938
939   // B.2.3. Si le sous-repertoire n'existe pas, on le cree
940   //        Si le sous-repertoire existe :
941   //         etatMenage = 0 : on sort en erreur si le repertoire n'est pas vide
942   //         etatMenage = 1 : on fait le menage du repertoire
943   if (chdir(DirCompute.str().c_str()) != 0)
944   {
945 //  Creation du repertoire car il n'existe pas :
946     if (mkdir(DirCompute.str().c_str(), S_IRWXU|S_IRGRP|S_IXGRP) != 0)
947     {
948        // GERALD -- QMESSAGE BOX
949        std::cerr << "Pb Creation du repertoire DirCompute = " << DirCompute.str() << std::endl;
950        ASSERT("Pb a la creation du repertoire" == 0);
951     }
952   }
953   else
954   {
955 //  Le repertoire existe et on fait le menage de son contenu :
956     if (etatMenage != 0)
957     {
958        MESSAGE (". Menage du repertoire DirCompute = " << DirCompute.str());
959        std::string commande= "rm -rf " + DirCompute.str()+"/*" ;
960        int codret = system(commande.c_str());
961        if (codret != 0)
962        {
963          // GERALD -- QMESSAGE BOX
964          std::cerr << ". Menage du repertoire de calcul" << DirCompute.str() << std::endl;
965          ASSERT("Pb au menage du repertoire de calcul" == 0);
966        }
967     }
968     else
969     {
970 //  Le repertoire existe et s'il n'est pas vide, on sort en erreur :
971        DIR *dp;
972        struct dirent *dirp;
973        dp  = opendir(DirCompute.str().c_str());
974        bool result = true;
975        while ((dirp = readdir(dp)) != NULL && result )
976        {
977             std::string file_name(dirp->d_name);
978             result = file_name.empty() || file_name == "." || file_name == ".."; //if any file - break and return false
979        }
980        closedir(dp);
981        if ( result == false)
982        {
983           SALOME::ExceptionStruct es;
984           es.type = SALOME::BAD_PARAM;
985           std::string text = "Directory : " + DirCompute.str() + "is not empty";
986           es.text = CORBA::string_dup(text.c_str());
987           throw SALOME::SALOME_Exception(es);
988           return false;
989        }
990     }
991   }
992
993   // B.3. Le sous-repertoire de l'iteration precedente
994   const char* nomDirItPa ;
995   std::stringstream DirComputePa ;
996   if (NumeIter == 1)
997   {
998     nomDirItPa = nomDirIt;
999     DirComputePa << DirCompute.str();
1000   }
1001   else
1002   {
1003     nomDirItPa = myIterationParent->GetDirName();
1004     DirComputePa << nomDir << "/" << nomDirItPa;
1005   }
1006   MESSAGE( ". nomDirItPa = " << nomDirItPa);
1007   MESSAGE( ". DirComputePa = " << DirComputePa.str() );
1008
1009   // B.4. Le fichier des messages
1010   chdir(DirCompute.str().c_str()) ;
1011   std::string MessFile = DirCompute.str() + "/Liste." + siter + ".vers." + siterp1 ;
1012   MESSAGE (". MessFile = " << MessFile);
1013   myIteration->SetMessFile(MessFile.c_str());
1014
1015    // C. On passe dans le repertoire de l'iteration a calculer
1016   chdir(DirCompute.str().c_str()) ;
1017
1018   // D. Les donnees du calcul HOMARD
1019   // D.1. Le type de conformite
1020   int ConfType = myCase->GetConfType();
1021   MESSAGE ( ". ConfType = " << ConfType );
1022
1023   // D.2. Le maillage n
1024   const char* NomMeshParent = myIterationParent->GetMeshName();
1025   MESSAGE ( ". NomMeshParent = " << NomMeshParent );
1026   const char* MeshFileParent = myIterationParent->GetMeshFile();
1027   MESSAGE ( ". MeshFileParent = " << MeshFileParent );
1028
1029   // D.3. Le maillage n+1
1030   const char* NomMesh = myIteration->GetMeshName();
1031   MESSAGE ( ". NomMesh = " << NomMesh );
1032   const char* MeshFile = myIteration->GetMeshFile();
1033   MESSAGE ( ". MeshFile = " << MeshFile );
1034   FILE *file = fopen(MeshFile,"r");
1035   if (file != NULL)
1036   {
1037      fclose(file);
1038      if (etatMenage == 0)
1039      {
1040           SALOME::ExceptionStruct es;
1041           es.type = SALOME::BAD_PARAM;
1042           std::string text = "MeshFile : " + std::string(MeshFile) + " already exists ";
1043           es.text = CORBA::string_dup(text.c_str());
1044           throw SALOME::SALOME_Exception(es);
1045           return false;
1046      }
1047      else
1048      {
1049          std::string commande = "rm -f " + std::string(MeshFile);
1050          codret = system(commande.c_str());
1051          if (codret != 0)
1052          {
1053           SALOME::ExceptionStruct es;
1054           es.type = SALOME::BAD_PARAM;
1055           std::string text = "PB with meshfile destruction ";
1056           es.text = CORBA::string_dup(text.c_str());
1057           throw SALOME::SALOME_Exception(es);
1058           return false;
1059          }
1060       }
1061   }
1062   else
1063   {
1064      codret = 0 ;
1065   };
1066  
1067
1068   // D.4. Les types de raffinement et de deraffinement
1069   // Les appels corba sont lourds, il vaut mieux les grouper
1070   HOMARD::listeTypes* ListTypes = myHypo->GetAdapRefinUnRef();
1071   ASSERT(ListTypes->length() == 3);
1072   int TypeAdap = (*ListTypes)[0];
1073   int TypeRaff = (*ListTypes)[1];
1074   int TypeDera = (*ListTypes)[2];
1075
1076   // D.6. L'option d'interpolation des champs
1077   int TypeFieldInterp = myHypo->GetTypeFieldInterp();
1078
1079   // E. Texte du fichier de configuration
1080   // E.1. Incontournables du texte
1081   HomardDriver* myDriver = new HomardDriver(siter, siterp1);
1082   myDriver->TexteInit(DirCompute.str(), DirComputePa.str(),MessFile);
1083   myDriver->TexteMaillage(NomMeshParent, MeshFileParent, 0);
1084   myDriver->TexteMaillage(NomMesh, MeshFile, 1);
1085   myDriver->TexteConfRaffDera(ConfType, TypeAdap, TypeRaff, TypeDera);
1086
1087   // E.2. Ajout des informations liees aux zones eventuelles
1088   if (TypeAdap == 0)
1089   {
1090     HOMARD::listeZonesHypo* ListZone = myHypo->GetZones();
1091     int numberOfZones = ListZone->length();
1092
1093     for (int NumZone = 0; NumZone< numberOfZones; NumZone++)
1094     {
1095       std::string ZoneName = std::string((*ListZone)[NumZone]);
1096       MESSAGE ( "... ZoneName = " << ZoneName);
1097       HOMARD::HOMARD_Zone_var myZone = myContextMap[GetCurrentStudyID()]._mesZones[ZoneName];
1098       ASSERT(!CORBA::is_nil(myZone));
1099
1100       int ZoneType = myZone->GetZoneType();
1101       MESSAGE ( "... ZoneType = " << ZoneType);
1102       if (ZoneType == 2) // Cas d un parallelepipede
1103       {
1104         HOMARD::double_array* zone = myZone->GetBox();
1105         myDriver->TexteZone(NumZone+1, ZoneType, (*zone)[0], (*zone)[1], (*zone)[2], (*zone)[3], (*zone)[4], (*zone)[5]);
1106       }
1107       else if (ZoneType == 4) // Cas d une sphere
1108       {
1109         HOMARD::double_array* zone = myZone->GetSphere();
1110         myDriver->TexteZone(NumZone+1, ZoneType, (*zone)[0], (*zone)[1], (*zone)[2], (*zone)[3], 0., 0.);
1111       }
1112     }
1113   }
1114   // E.3. Ajout des informations liees aux champs eventuels
1115   if (TypeAdap == 1)
1116   {
1117 //  Le fichier du champ
1118     char* FieldFile = myIteration->GetFieldFile();
1119     MESSAGE ( ". FieldFile = " << FieldFile );
1120     if (strlen(FieldFile) == 0)
1121     {
1122       // GERALD -- QMESSAGE BOX
1123       std::cerr << "Le fichier du champ n'a pas ete fourni." << std::endl;
1124       ASSERT("The file for the field is not given." == 0);
1125     }
1126 //  Les caracteristiques d'instants
1127     int TimeStep = myIteration->GetTimeStep();
1128     MESSAGE( ". TimeStep = " << TimeStep );
1129     int Rank = myIteration->GetRank();
1130     MESSAGE( ". Rank = " << Rank );
1131 //  Les informations sur les champ
1132     HOMARD::InfosHypo* aInfosHypo = myHypo->GetField();
1133 //  Le nom
1134     const char* FieldName = aInfosHypo->FieldName;
1135 //  Les seuils
1136     int TypeThR = aInfosHypo->TypeThR;
1137     double ThreshR = aInfosHypo->ThreshR;
1138     int TypeThC = aInfosHypo->TypeThC;
1139     double ThreshC = aInfosHypo->ThreshC;
1140 //  L'usage des composantes
1141     int UsCmpI = aInfosHypo->UsCmpI;
1142     MESSAGE( ". UsCmpI = " << UsCmpI );
1143 //
1144     myDriver->TexteField(FieldName, FieldFile, TimeStep, Rank, TypeThR, ThreshR, TypeThC, ThreshC, UsCmpI);
1145 //
1146 //  Les composantes
1147     HOMARD::listeComposantsHypo* mescompo = myHypo->GetListComp();
1148     int numberOfCompos = mescompo->length();
1149     MESSAGE( ". numberOfCompos = " << numberOfCompos );
1150     for (int NumeComp = 0; NumeComp< numberOfCompos; NumeComp++)
1151     {
1152       std::string nomCompo = std::string((*mescompo)[NumeComp]);
1153       MESSAGE( "... nomCompo = " << nomCompo );
1154       myDriver->TexteCompo(NumeComp, nomCompo);
1155     }
1156   }
1157   // E.4. Ajout des informations liees au filtrage eventuel par les groupes
1158   HOMARD::ListGroupType* listeGroupes = myHypo->GetGroups();
1159   int numberOfGroups = listeGroupes->length();
1160   MESSAGE( ". numberOfGroups = " << numberOfGroups );
1161   if (numberOfGroups > 0)
1162   {
1163
1164     for (int NumGroup = 0; NumGroup< numberOfGroups; NumGroup++)
1165     {
1166       std::string GroupName = std::string((*listeGroupes)[NumGroup]);
1167       MESSAGE( "... GroupName = " << GroupName );
1168       myDriver->TexteGroup(GroupName);
1169     }
1170   }
1171
1172   // E.5. Ajout des informations liees a l'eventuel suivi de frontiere
1173   HOMARD::ListBoundaryGroupType* ListBoundaryGroupType = myCase->GetBoundaryGroup();
1174   int numberOfitems = ListBoundaryGroupType->length();
1175   MESSAGE ( "... number of string for Boundary+Group = " << numberOfitems);
1176   int BoundaryOption = 1 ;
1177   int NumBoundaryAnalytical = 0 ;
1178   for (int NumBoundary = 0; NumBoundary< numberOfitems; NumBoundary=NumBoundary+2)
1179   {
1180     std::string BoundaryName = std::string((*ListBoundaryGroupType)[NumBoundary]);
1181     MESSAGE ( "... BoundaryName = " << BoundaryName);
1182     HOMARD::HOMARD_Boundary_var myBoundary = myContextMap[GetCurrentStudyID()]._mesBoundarys[BoundaryName];
1183     ASSERT(!CORBA::is_nil(myBoundary));
1184     std::string GroupName = std::string((*ListBoundaryGroupType)[NumBoundary+1]);
1185     MESSAGE ( "... GroupName = " << GroupName);
1186
1187     int BoundaryType = myBoundary->GetBoundaryType();
1188     MESSAGE ( "... BoundaryType = " << BoundaryType );
1189     if (BoundaryType == 0) // Cas d une frontiere discrete
1190     {
1191       const char* MeshName = myBoundary->GetMeshName() ;
1192       const char* MeshFile = myBoundary->GetMeshFile() ;
1193       myDriver->TexteBoundaryDi( MeshName, MeshFile);
1194       BoundaryOption = BoundaryOption*2 ;
1195     }
1196     else if (BoundaryType == 1) // Cas d un cylindre
1197     {
1198       NumBoundaryAnalytical++ ;
1199       HOMARD::double_array* coor = myBoundary->GetCylinder();
1200       myDriver->TexteBoundaryAn(NumBoundaryAnalytical, BoundaryType, GroupName, (*coor)[0], (*coor)[1], (*coor)[2], (*coor)[3], (*coor)[4], (*coor)[5], (*coor)[6]);
1201       BoundaryOption = BoundaryOption*3 ;
1202     }
1203     else if (BoundaryType == 2) // Cas d une sphere
1204     {
1205       NumBoundaryAnalytical++ ;
1206       HOMARD::double_array* coor = myBoundary->GetSphere();
1207       myDriver->TexteBoundaryAn(NumBoundaryAnalytical, BoundaryType, GroupName, (*coor)[0], (*coor)[1], (*coor)[2], (*coor)[3], 0., 0., 0.);
1208       BoundaryOption = BoundaryOption*3 ;
1209     }
1210   }
1211   myDriver->TexteBoundaryOption(BoundaryOption);
1212
1213   // E.6. Ajout des informations liees a l'eventuelle interpolation des champs
1214   MESSAGE( "... TypeFieldInterp = " << TypeFieldInterp );
1215   if (TypeFieldInterp != 0)
1216   {
1217 //  Le fichier des champs
1218     char* FieldFile = myIteration->GetFieldFile();
1219     MESSAGE ( ". FieldFile = " << FieldFile );
1220     if (strlen(FieldFile) == 0)
1221     {
1222       // GERALD -- QMESSAGE BOX
1223       std::cerr << "Le fichier du champ n'a pas ete fourni." << std::endl;
1224       ASSERT("The file for the field is not given." == 0);
1225     }
1226 //  Les caracteristiques d'instants
1227     int TimeStep = myIteration->GetTimeStep();
1228     MESSAGE( ". TimeStep = " << TimeStep );
1229     int Rank = myIteration->GetRank();
1230     MESSAGE( ". Rank = " << Rank );
1231 //
1232     myDriver->TexteFieldInterp(TypeFieldInterp, FieldFile, MeshFile, TimeStep, Rank);
1233 //  Les champs
1234     if (TypeFieldInterp == 2)
1235     {
1236       HOMARD::listFieldInterpHypo* meschamps = myHypo->GetListFieldInterp();
1237       int numberOfFields = meschamps->length();
1238       MESSAGE( ". numberOfFields = " << numberOfFields );
1239       for (int NumeChamp = 0; NumeChamp< numberOfFields; NumeChamp++)
1240       {
1241         std::string nomChamp = std::string((*meschamps)[NumeChamp]);
1242         MESSAGE( "... nomChamp = " << nomChamp );
1243         myDriver->TexteFieldInterpName(NumeChamp, nomChamp);
1244       }
1245     }
1246   }
1247
1248   // F. Ecriture du texte dans le fichier
1249   if (codret == 0)
1250   {
1251     myDriver->CreeFichier();
1252   }
1253
1254 // G. Execution
1255 //
1256   int codretexec = 1 ;
1257   if (codret == 0)
1258   {
1259     codretexec = myDriver->ExecuteHomard();
1260 //
1261     if (codretexec == 0)
1262     {
1263       SetEtatIter(nomIteration,true);
1264     }
1265     else
1266     {
1267       // GERALD -- QMESSAGE BOX
1268       SetEtatIter(nomIteration,false);
1269     }
1270   }
1271
1272   // H. Gestion des resultats
1273   if (codret == 0)
1274   {
1275     // H.1. Le fichier des messages, dans tous les cas
1276     std::stringstream saux1 ;
1277     saux1 << "Mess " << NumeIter ;
1278     PublishFileUnderIteration(nomIteration, MessFile.c_str(), saux1.str().c_str());
1279
1280     // H.2. Si tout s'est bien passe :
1281     if (codretexec == 0)
1282     {
1283     // H.2.1. Le fichier de bilan
1284       std::stringstream saux2 ;
1285       saux2 << "Summary " << NumeIter ;
1286       std::string SummaryFile = DirCompute.str() + "/apad." + siterp1 + ".bilan" ;
1287       PublishFileUnderIteration(nomIteration, SummaryFile.c_str(), saux2.str().c_str());
1288     // H.2.2. Le fichier de  maillage obtenu
1289       std::stringstream saux0 ;
1290       saux0 <<"Iteration " << NumeIter ;
1291       PublishFileUnderIteration(nomIteration, MeshFile, saux0.str().c_str());
1292       PublishResultInSmesh(MeshFile, 1);
1293     }
1294   // H.3 Message d'erreur en cas de probleme
1295     else
1296     {
1297       SALOME::ExceptionStruct es;
1298       es.type = SALOME::BAD_PARAM;
1299       std::string text = "Error during the adaptation.\n" ;
1300       try 
1301       {
1302           ifstream fichier(MessFile.c_str(), ios::in);
1303           string ligne;
1304           while(getline(fichier, ligne) and (ligne != "===== HOMARD ===== STOP ====="));
1305           while (getline(fichier, ligne)) { text += ligne+ "\n";};
1306       }
1307       catch (...) {
1308         text += "no log file ....";
1309       }
1310       es.text = CORBA::string_dup(text.c_str());
1311       throw SALOME::SALOME_Exception(es);
1312     }
1313   }
1314
1315   // I. Menage
1316   if (codret == 0)
1317   {
1318     delete myDriver;
1319   }
1320   //
1321   if (codret == 0) { return true; }
1322   else { return false; }
1323 }
1324
1325 //===========================================================================
1326 SALOMEDS::SObject_ptr HOMARD_Gen_i::PublishInStudy(SALOMEDS::Study_ptr theStudy,
1327                                                    SALOMEDS::SObject_ptr theSObject,
1328                                                    CORBA::Object_ptr theObject,
1329                                                    const char* theName)
1330 {
1331   MESSAGE("PublishInStudy pour " << theName);
1332   SALOMEDS::SObject_var aResultSO;
1333   if (CORBA::is_nil(theStudy))
1334   {
1335     SALOME::ExceptionStruct es;
1336     es.type = SALOME::BAD_PARAM;
1337     es.text = "Invalid Study Context ";
1338     throw SALOME::SALOME_Exception(es);
1339     return 0;
1340   };
1341
1342 // Recuperation de l'objet correspondant, en essayant chacun des types possibles
1343 // Rq : Iteration est publiee ailleurs
1344   HOMARD::HOMARD_Cas_var        aCase  = HOMARD::HOMARD_Cas::_narrow(theObject);
1345   HOMARD::HOMARD_Hypothesis_var aHypo = HOMARD::HOMARD_Hypothesis::_narrow(theObject);
1346   HOMARD::HOMARD_Zone_var       aZone = HOMARD::HOMARD_Zone::_narrow(theObject);
1347   HOMARD::HOMARD_Boundary_var   aBoundary = HOMARD::HOMARD_Boundary::_narrow(theObject);
1348
1349    addInStudy(theStudy);
1350
1351 // Controle de la non publication d'un objet de meme nom
1352    if ((!aHypo->_is_nil()) or (!aZone->_is_nil()) or (!aBoundary->_is_nil()))
1353     {
1354          SALOMEDS::Study::ListOfSObject_var listSO = theStudy->FindObjectByName(theName, ComponentDataType());
1355          if (listSO->length() >= 1)
1356          {
1357              MESSAGE("This name "<<theName<<" is already used "<<listSO->length()<<" time(s)");
1358              std::cerr <<"This name "<<theName<<" is already used "<<listSO->length()<<" time(s)" << std::endl;
1359              aResultSO = listSO[0];
1360              return aResultSO._retn();
1361          }
1362     }
1363
1364   // Caracteristiques de l'etude
1365     SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
1366     aStudyBuilder->NewCommand();
1367      if(!aCase->_is_nil())
1368         aResultSO = PublishCaseInStudy(theStudy, aStudyBuilder, aCase, theName);
1369      else if(!aHypo->_is_nil())
1370         aResultSO = PublishHypotheseInStudy(theStudy, aStudyBuilder, aHypo, theName);
1371      else if(!aZone->_is_nil())
1372         aResultSO = PublishZoneInStudy(theStudy, aStudyBuilder, aZone, theName);
1373      else if(!aBoundary->_is_nil())
1374         aResultSO = PublishBoundaryInStudy(theStudy, aStudyBuilder, aBoundary, theName);
1375
1376     aStudyBuilder->CommitCommand();
1377   return aResultSO._retn();
1378 };
1379 //=============================================================================
1380 SALOMEDS::SObject_ptr HOMARD_Gen_i::PublishCaseInStudy(SALOMEDS::Study_ptr theStudy, 
1381                                                        SALOMEDS::StudyBuilder_var aStudyBuilder,
1382                                                        HOMARD::HOMARD_Cas_ptr theObject, const char* theName)
1383 {
1384   MESSAGE("PublishCaseInStudy pour "<<theName);
1385   SALOMEDS::SObject_var aResultSO;
1386   SALOMEDS::GenericAttribute_var anAttr;
1387
1388   if (CORBA::is_nil(theObject)) {
1389     MESSAGE("HOMARD_Gen_i.cxx::theObject->_is_nil()");
1390     return aResultSO._retn();
1391   }
1392   if (theStudy->_is_nil()) {
1393     MESSAGE("HOMARD_Gen_i.cxx::theStudy->_is_nil()");
1394     return aResultSO._retn();
1395   }
1396
1397   SALOMEDS::SComponent_var theFatherHomard = theStudy->FindComponent(ComponentDataType());
1398   if (theFatherHomard->_is_nil()) 
1399   {
1400     MESSAGE("theFatherHomard->_is_nil()");      
1401     return aResultSO._retn();
1402   }
1403
1404   aResultSO = aStudyBuilder->NewObject(theFatherHomard);
1405   PublishInStudyAttr(aStudyBuilder, aResultSO, theName, "CasHomard", "cas_calcule.png", 
1406                      _orb->object_to_string(theObject) ) ;
1407   return aResultSO._retn();
1408 }
1409
1410 //=============================================================================
1411 SALOMEDS::SObject_ptr HOMARD_Gen_i::PublishZoneInStudy(SALOMEDS::Study_ptr theStudy, 
1412                     SALOMEDS::StudyBuilder_var aStudyBuilder,
1413                    HOMARD::HOMARD_Zone_ptr theObject, const char* theName)
1414 {
1415   MESSAGE("PublishZoneStudy pour "<<theName);
1416   SALOMEDS::SObject_var aResultSO;
1417   SALOMEDS::GenericAttribute_var anAttr;
1418
1419   if (CORBA::is_nil(theObject)) 
1420   {
1421     MESSAGE("HOMARD_Gen_i.cxx::theObject->_is_nil()");
1422     return aResultSO._retn();
1423   }
1424   if (theStudy->_is_nil()) 
1425   {
1426     MESSAGE("HOMARD_Gen_i.cxx::theStudy->_is_nil()");
1427     return aResultSO._retn();
1428   }
1429   SALOMEDS::SComponent_var theFatherHomard = theStudy->FindComponent(ComponentDataType());
1430   if (theFatherHomard->_is_nil()) 
1431   {
1432     MESSAGE("theFatherHomard->_is_nil()");
1433     return aResultSO._retn();
1434   }
1435
1436   // Caracteristique de la zone
1437   HOMARD::HOMARD_Zone_var myZone = myContextMap[GetCurrentStudyID()]._mesZones[theName];
1438   CORBA::Long ZoneType = myZone->GetZoneType();
1439
1440   // On ajoute la categorie des zones dans l etude si necessaire
1441   SALOMEDS::SObject_var aSOZone;
1442   if (!theFatherHomard->FindSubObject(100, aSOZone))
1443   {
1444     aSOZone = aStudyBuilder->NewObjectToTag(theFatherHomard, 100);
1445     PublishInStudyAttr(aStudyBuilder, aSOZone, "Zones", "ZoneList", "zone_icone_2.png", NULL ) ;
1446   }
1447
1448   aResultSO = aStudyBuilder->NewObject(aSOZone);
1449   switch (ZoneType)
1450   {
1451     case 2 :
1452     { PublishInStudyAttr(aStudyBuilder, aResultSO, theName, "ZoneHomard", 
1453       "boxdxyz_2.png", _orb->object_to_string(theObject) ) ;
1454       break; 
1455     }
1456     case 4 :
1457     { PublishInStudyAttr(aStudyBuilder, aResultSO, theName, "ZoneHomard", 
1458      "spherepoint_2.png", _orb->object_to_string(theObject) ) ;
1459       break; 
1460     }
1461   }
1462   return aResultSO._retn();
1463 }
1464 //=============================================================================
1465 SALOMEDS::SObject_ptr HOMARD_Gen_i::PublishBoundaryInStudy(SALOMEDS::Study_ptr theStudy, 
1466                    SALOMEDS::StudyBuilder_var aStudyBuilder,
1467                    HOMARD::HOMARD_Boundary_ptr theObject, const char* theName)
1468 {
1469   MESSAGE("PublishBoundaryStudy pour "<<theName);
1470   SALOMEDS::SObject_var aResultSO;
1471   SALOMEDS::GenericAttribute_var anAttr;
1472
1473   // Caracteristique de la Boundary
1474   HOMARD::HOMARD_Boundary_var myBoundary = myContextMap[GetCurrentStudyID()]._mesBoundarys[theName];
1475
1476   // On recupere le module pere dans l etude
1477   SALOMEDS::SComponent_var       theFatherHomard = theStudy->FindComponent(ComponentDataType());
1478   if (theFatherHomard->_is_nil())
1479   {
1480     MESSAGE("theFatherHomard->_is_nil()");
1481     return aResultSO._retn();
1482   }
1483
1484   // On ajoute la categorie des boundarys dans l etude si necessaire
1485   SALOMEDS::SObject_var aSOBoundary;
1486   if (!theFatherHomard->FindSubObject(101, aSOBoundary))
1487   {
1488     aSOBoundary = aStudyBuilder->NewObjectToTag(theFatherHomard, 101);
1489     PublishInStudyAttr(aStudyBuilder, aSOBoundary, "Boundaries", "BoundList", "zone_icone_2.png", NULL ) ;
1490   }
1491
1492   aResultSO = aStudyBuilder->NewObject(aSOBoundary);
1493   CORBA::Long BoundaryType = myBoundary->GetBoundaryType();
1494   switch (BoundaryType)
1495   {
1496     case 0 :
1497     { PublishInStudyAttr(aStudyBuilder, aResultSO, theName, "BoundaryDiHomard", "mesh_tree_mesh.png",
1498                           _orb->object_to_string(theObject));
1499       break; 
1500     }
1501     case 1 :
1502     { PublishInStudyAttr(aStudyBuilder, aResultSO, theName, "BoundaryAnHomard", "cylinderpointvector_2.png", 
1503                           _orb->object_to_string(theObject));
1504       break; 
1505     }
1506     case 2 :
1507     { PublishInStudyAttr(aStudyBuilder, aResultSO, theName, "BoundaryAnHomard", "spherepoint_2.png", 
1508                           _orb->object_to_string(theObject));
1509       break; 
1510     }
1511   }
1512   return aResultSO._retn();
1513 }
1514
1515 //=============================================================================
1516 SALOMEDS::SObject_ptr HOMARD_Gen_i::PublishHypotheseInStudy(SALOMEDS::Study_ptr theStudy, 
1517                    SALOMEDS::StudyBuilder_var aStudyBuilder,
1518                    HOMARD::HOMARD_Hypothesis_ptr theObject, const char* theName)
1519 {
1520   MESSAGE("PublishHypotheseInStudy pour "<<theName);
1521   SALOMEDS::SObject_var aResultSO;
1522   SALOMEDS::GenericAttribute_var anAttr;
1523
1524   // On recupere le module pere dans l etude
1525   // On ajoute la categorie des hypotheses dans l etude si necessaire
1526   SALOMEDS::SComponent_var theFatherHomard = theStudy->FindComponent(ComponentDataType());
1527   if (theFatherHomard->_is_nil()) 
1528   {
1529     MESSAGE("theFatherHomard->_is_nil()");
1530     return aResultSO._retn();
1531   }
1532   SALOMEDS::SObject_var aSOHypothese;
1533   if (!theFatherHomard->FindSubObject(0, aSOHypothese))
1534   {
1535     aSOHypothese = aStudyBuilder->NewObjectToTag(theFatherHomard, 0);
1536     PublishInStudyAttr(aStudyBuilder, aSOHypothese, "Hypothesis", "HypoList","hypotheses.png", NULL);
1537   }
1538
1539 // Creation du resultat dans l'etude
1540   aResultSO = aStudyBuilder->NewObject(aSOHypothese);
1541   PublishInStudyAttr(aStudyBuilder, aResultSO, theName, "HypoHomard", NULL, _orb->object_to_string(theObject) ) ;
1542
1543   return aResultSO._retn();
1544 }
1545 //===========================================================================
1546 void HOMARD_Gen_i::PublishInStudyAttr(SALOMEDS::StudyBuilder_var aStudyBuilder,
1547                                       SALOMEDS::SObject_var aResultSO,
1548                                       const char* name, const char* value, const char* icone, const char* ior)
1549 {
1550   SALOMEDS::GenericAttribute_var anAttr ;
1551 //  Ajout du nom
1552   if ( name != NULL )
1553   {
1554     anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO, "AttributeName");
1555     SALOMEDS::AttributeName_var aNameAttrib = SALOMEDS::AttributeName::_narrow(anAttr);
1556     aNameAttrib->SetValue(name);
1557   }
1558
1559 //  Ajout du commentaire
1560   if ( value != NULL )
1561   {
1562     anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO, "AttributeComment");
1563     SALOMEDS::AttributeComment_var aCommentAttrib = SALOMEDS::AttributeComment::_narrow(anAttr);
1564     aCommentAttrib->SetValue(value);
1565   }
1566
1567 //  Ajout de l'icone
1568   if ( icone != NULL  )
1569   {
1570     anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO,"AttributePixMap");
1571     SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr);
1572     aPixmap->SetPixMap(icone);
1573   }
1574
1575 //  Ajout de l ior
1576   if ( ior != NULL  )
1577   {
1578     anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO, "AttributeIOR");
1579     SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
1580     anIOR->SetValue(ior);
1581   }
1582 };
1583
1584 //=============================================================================
1585 HOMARD::listeCases* HOMARD_Gen_i::GetAllCases()
1586 {
1587   if (CORBA::is_nil(myCurrentStudy))
1588   {
1589       SALOME::ExceptionStruct es;
1590       es.type = SALOME::BAD_PARAM;
1591       es.text = "Invalid Study Context ";
1592       throw SALOME::SALOME_Exception(es);
1593       return 0;
1594   };
1595
1596   HOMARD::listeCases_var ret = new HOMARD::listeCases;
1597   ret->length(myContextMap[GetCurrentStudyID()]._mesCas.size());
1598   std::map<std::string, HOMARD::HOMARD_Cas_var>::const_iterator it;
1599   int i = 0;
1600   for (it  = myContextMap[GetCurrentStudyID()]._mesCas.begin();
1601         it != myContextMap[GetCurrentStudyID()]._mesCas.end(); it++)
1602   {
1603     ret[i++] = CORBA::string_dup((*it).first.c_str());
1604   }
1605
1606   return ret._retn();
1607 }
1608
1609 //=============================================================================
1610 HOMARD::listeHypotheses* HOMARD_Gen_i::GetAllHypotheses()
1611 {
1612   if (CORBA::is_nil(myCurrentStudy))
1613   {
1614       SALOME::ExceptionStruct es;
1615       es.type = SALOME::BAD_PARAM;
1616       es.text = "Invalid Study Context ";
1617       throw SALOME::SALOME_Exception(es);
1618       return 0;
1619   };
1620
1621   HOMARD::listeHypotheses_var ret = new HOMARD::listeHypotheses;
1622   ret->length(myContextMap[GetCurrentStudyID()]._mesHypotheses.size());
1623   std::map<std::string, HOMARD::HOMARD_Hypothesis_var>::const_iterator it;
1624   int i = 0;
1625   for (it  = myContextMap[GetCurrentStudyID()]._mesHypotheses.begin();
1626   it != myContextMap[GetCurrentStudyID()]._mesHypotheses.end(); it++)
1627   {
1628     ret[i++] = CORBA::string_dup((*it).first.c_str());
1629   }
1630
1631   return ret._retn();
1632 }
1633
1634 //=============================================================================
1635 HOMARD::listeZones* HOMARD_Gen_i::GetAllZones()
1636 {
1637   if (CORBA::is_nil(myCurrentStudy))
1638   {
1639       SALOME::ExceptionStruct es;
1640       es.type = SALOME::BAD_PARAM;
1641       es.text = "Invalid Study Context ";
1642       throw SALOME::SALOME_Exception(es);
1643       return 0;
1644   };
1645
1646   HOMARD::listeZones_var ret = new HOMARD::listeZones;
1647   ret->length(myContextMap[GetCurrentStudyID()]._mesZones.size());
1648   std::map<std::string, HOMARD::HOMARD_Zone_var>::const_iterator it;
1649   int i = 0;
1650   for (it  = myContextMap[GetCurrentStudyID()]._mesZones.begin();
1651   it != myContextMap[GetCurrentStudyID()]._mesZones.end(); it++)
1652   {
1653     ret[i++] = CORBA::string_dup((*it).first.c_str());
1654   }
1655
1656   return ret._retn();
1657 }
1658
1659 //=============================================================================
1660 HOMARD::listeIterations* HOMARD_Gen_i::GetAllIterations()
1661 {
1662   if (CORBA::is_nil(myCurrentStudy))
1663   {
1664       SALOME::ExceptionStruct es;
1665       es.type = SALOME::BAD_PARAM;
1666       es.text = "Invalid Study Context ";
1667       throw SALOME::SALOME_Exception(es);
1668       return 0;
1669   };
1670
1671   HOMARD::listeIterations_var ret = new HOMARD::listeIterations;
1672   ret->length(myContextMap[GetCurrentStudyID()]._mesIterations.size());
1673   std::map<std::string, HOMARD::HOMARD_Iteration_var>::const_iterator it;
1674   int i = 0;
1675   for (it  = myContextMap[GetCurrentStudyID()]._mesIterations.begin(); 
1676   it != myContextMap[GetCurrentStudyID()]._mesIterations.end(); it++)
1677   {
1678     ret[i++] = CORBA::string_dup((*it).first.c_str());
1679   }
1680
1681   return ret._retn();
1682 }
1683 //=============================================================================
1684 HOMARD::listeBoundarys* HOMARD_Gen_i::GetAllBoundarys()
1685 {
1686   if (CORBA::is_nil(myCurrentStudy))
1687   {
1688       SALOME::ExceptionStruct es;
1689       es.type = SALOME::BAD_PARAM;
1690       es.text = "Invalid Study Context ";
1691       throw SALOME::SALOME_Exception(es);
1692       return 0;
1693   };
1694
1695   HOMARD::listeBoundarys_var ret = new HOMARD::listeBoundarys;
1696   ret->length(myContextMap[GetCurrentStudyID()]._mesBoundarys.size());
1697   std::map<std::string, HOMARD::HOMARD_Boundary_var>::const_iterator it;
1698   int i = 0;
1699   for (it  = myContextMap[GetCurrentStudyID()]._mesBoundarys.begin();
1700   it != myContextMap[GetCurrentStudyID()]._mesBoundarys.end(); it++)
1701   {
1702     ret[i++] = CORBA::string_dup((*it).first.c_str());
1703   }
1704
1705   return ret._retn();
1706 }
1707
1708 //=============================================================================
1709 char* HOMARD_Gen_i::GetCaseName(const char* nomIteration)
1710 {
1711   if (CORBA::is_nil(myCurrentStudy))
1712   {
1713       SALOME::ExceptionStruct es;
1714       es.type = SALOME::BAD_PARAM;
1715       es.text = "Invalid Study Context ";
1716       throw SALOME::SALOME_Exception(es);
1717       return 0;
1718   };
1719
1720   HOMARD::HOMARD_Iteration_var monIter = myContextMap[GetCurrentStudyID()]._mesIterations[nomIteration];
1721   ASSERT(!CORBA::is_nil(monIter));
1722   return CORBA::string_dup(monIter->GetCaseName());
1723 }
1724 //=============================================================================
1725 void HOMARD_Gen_i::PublishResultInSmesh(const char* NomFich, CORBA::Long IconeType)
1726 {
1727   MESSAGE( "PublishResultInSmesh " << NomFich);
1728   if (CORBA::is_nil(myCurrentStudy))
1729   {
1730       SALOME::ExceptionStruct es;
1731       es.type = SALOME::BAD_PARAM;
1732       es.text = "Invalid Study Context ";
1733       throw SALOME::SALOME_Exception(es);
1734       return ;
1735   };
1736
1737 // Le module SMESH est-il actif ?
1738   SALOMEDS::SObject_var aSmeshSO = myCurrentStudy->FindComponent("SMESH");
1739 //
1740   if (!CORBA::is_nil(aSmeshSO))
1741   {
1742 // On verifie que le fichier n est pas deja publie
1743     SALOMEDS::ChildIterator_var aIter = myCurrentStudy->NewChildIterator(aSmeshSO);
1744     for (; aIter->More(); aIter->Next()) 
1745     {
1746        SALOMEDS::SObject_var  aSO = aIter->Value();
1747        SALOMEDS::GenericAttribute_var aGAttr;
1748        if (aSO->FindAttribute(aGAttr,"AttributeExternalFileDef"))
1749        {
1750            SALOMEDS::AttributeExternalFileDef_var anAttr = SALOMEDS::AttributeExternalFileDef::_narrow(aGAttr);
1751            CORBA::String_var value=anAttr->Value();
1752            if (strcmp((const char*)value,NomFich) == 0)
1753            {
1754                 // GERALD -- QMESSAGE BOX
1755                 std::cerr << "fichier : "<< NomFich << " deja publie "<< std::endl;
1756                 return;
1757            }
1758        }
1759      }
1760
1761   }
1762
1763 // On enregistre le fichier
1764   MESSAGE( "Enregistrement du fichier");
1765   SALOME_LifeCycleCORBA* myLCC = new SALOME_LifeCycleCORBA(_NS);
1766   SMESH::SMESH_Gen_var aSmeshEngine = SMESH::SMESH_Gen::_narrow(myLCC->FindOrLoad_Component("FactoryServer","SMESH"));
1767   ASSERT(!CORBA::is_nil(aSmeshEngine));
1768   aSmeshEngine->SetCurrentStudy(myCurrentStudy);
1769   SMESH::DriverMED_ReadStatus theStatus;
1770   //aSmeshEngine->CreateMeshesFromMED(NomFich, theStatus);
1771
1772 // On met a jour les attributs AttributeExternalFileDef et AttributePixMap
1773   SMESH::mesh_array* mesMaillages=aSmeshEngine->CreateMeshesFromMED(NomFich, theStatus);
1774   for (int i = 0; i < mesMaillages->length();  i++) 
1775   {
1776     MESSAGE( ". Mise a jour des attributs");
1777     SMESH::SMESH_Mesh_var monMaillage= (*mesMaillages)[i];
1778     SALOMEDS::SObject_var aSO=SALOMEDS::SObject::_narrow(myCurrentStudy->FindObjectIOR(_orb->object_to_string(monMaillage)));
1779     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1780     SALOMEDS::GenericAttribute_var aGAttr = aStudyBuilder->FindOrCreateAttribute(aSO, "AttributeExternalFileDef");
1781     SALOMEDS::AttributeExternalFileDef_var anAttr = SALOMEDS::AttributeExternalFileDef::_narrow(aGAttr);
1782     anAttr->SetValue(NomFich);
1783     SALOMEDS::GenericAttribute_var aPixMap = aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePixMap" );
1784     SALOMEDS::AttributePixMap_var anAttr2 = SALOMEDS::AttributePixMap::_narrow(aPixMap);
1785 //  IconeType = 0 : fichier issu d'une importation
1786 //  IconeType = 1 : fichier issu d'une execution HOMARD
1787     if ( IconeType == 0 )
1788     { anAttr2->SetPixMap( "mesh_tree_importedmesh.png" ); }
1789     else
1790     { anAttr2->SetPixMap( "mesh_tree_mesh.png" ); }
1791   }
1792
1793 }
1794 //=============================================================================
1795 void HOMARD_Gen_i::DeleteResultInSmesh(const char* NomFich, const char* MeshName)
1796 {
1797   MESSAGE (" DeleteResultInSmesh pour "<< NomFich << "et le maillage "<< MeshName);
1798   if (CORBA::is_nil(myCurrentStudy))
1799   {
1800       SALOME::ExceptionStruct es;
1801       es.type = SALOME::BAD_PARAM;
1802       es.text = "Invalid Study Context ";
1803       throw SALOME::SALOME_Exception(es);
1804       return ;
1805   };
1806
1807 // Le module SMESH est-il actif ?
1808   SALOMEDS::SObject_var aSmeshSO = myCurrentStudy->FindComponent("SMESH");
1809 //
1810   if (CORBA::is_nil(aSmeshSO))
1811   {
1812       return ;
1813   };
1814 // On verifie que le fichier est deja publie
1815   SALOMEDS::StudyBuilder_var myBuilder = myCurrentStudy->NewBuilder();
1816   SALOMEDS::ChildIterator_var aIter = myCurrentStudy->NewChildIterator(aSmeshSO);
1817   for (; aIter->More(); aIter->Next()) 
1818   {
1819      SALOMEDS::SObject_var  aSO = aIter->Value();
1820      SALOMEDS::GenericAttribute_var aGAttr;
1821      if (aSO->FindAttribute(aGAttr,"AttributeExternalFileDef"))
1822      {
1823        SALOMEDS::AttributeExternalFileDef_var anAttr = SALOMEDS::AttributeExternalFileDef::_narrow(aGAttr);
1824        CORBA::String_var value=anAttr->Value();
1825        if (strcmp((const char*)value,NomFich) == 0)
1826        {
1827          if (aSO->FindAttribute(aGAttr,"AttributeName"))
1828          {
1829            SALOMEDS::AttributeName_var anAttr2 = SALOMEDS::AttributeName::_narrow(aGAttr);
1830            CORBA::String_var value2=anAttr2->Value();
1831            if (strcmp((const char*)value2,MeshName) == 0)
1832            {
1833              myBuilder->RemoveObjectWithChildren( aSO ) ;
1834            }
1835          }
1836        }
1837      }
1838   }
1839
1840 }
1841 //=============================================================================
1842 void HOMARD_Gen_i::PublishFileUnderIteration(const char* NomIter, const char* NomFich, const char* Commentaire)
1843 {
1844   if (CORBA::is_nil(myCurrentStudy))
1845   {
1846       SALOME::ExceptionStruct es;
1847       es.type = SALOME::BAD_PARAM;
1848       es.text = "Invalid Study Context ";
1849       throw SALOME::SALOME_Exception(es);
1850       return ;
1851   };
1852
1853   HOMARD::HOMARD_Iteration_var myIteration = myContextMap[GetCurrentStudyID()]._mesIterations[NomIter];
1854   if (CORBA::is_nil(myIteration))
1855   {
1856       SALOME::ExceptionStruct es;
1857       es.type = SALOME::BAD_PARAM;
1858       es.text = "Invalid Iteration ";
1859       throw SALOME::SALOME_Exception(es);
1860       return ;
1861   };
1862   SALOMEDS::SObject_var aIterSO=SALOMEDS::SObject::_narrow(myCurrentStudy->FindObjectIOR(_orb->object_to_string(myIteration)));
1863   if (CORBA::is_nil(myIteration))
1864   {
1865       SALOME::ExceptionStruct es;
1866       es.type = SALOME::BAD_PARAM;
1867       es.text = "Invalid Iteration Study Object";
1868       throw SALOME::SALOME_Exception(es);
1869       return ;
1870   };
1871
1872   SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1873
1874   aStudyBuilder->NewCommand();
1875
1876   SALOMEDS::SObject_var aSubSO = aStudyBuilder->NewObject(aIterSO);
1877 // Pour les fichiers med, on affiche une icone de maillage
1878 // Pour les fichiers qui sont texte, on affiche une icone de fichier texte 'texte'
1879 // Le reperage se fait par la 1ere lettre du commentaire : I pour Iteration n
1880   const char* icone ;
1881   const char* ior = " " ;
1882   if ( Commentaire[0] == 'I' )
1883   { icone = "med.png" ; }
1884   else
1885   { icone = "texte_2.png" ; }
1886   PublishInStudyAttr(aStudyBuilder, aSubSO, NomFich, Commentaire, icone, ior ) ;
1887
1888   aStudyBuilder->CommitCommand();
1889 }
1890
1891
1892 //===========================================================================
1893 //
1894 // Next functions are inherited from SALOMEDS::Driver interface
1895 //
1896 //===========================================================================
1897
1898 //===========================================================================
1899 SALOMEDS::TMPFile* HOMARD_Gen_i::Save(SALOMEDS::SComponent_ptr theComponent,
1900                                        const char* theURL,
1901                                        bool isMultiFile)
1902 {
1903   MESSAGE (" Save pour theURL = "<< theURL);
1904   SALOMEDS::TMPFile_var aStreamFile;
1905
1906   // get temporary directory name
1907   std::string tmpDir = isMultiFile ? std::string(theURL) : SALOMEDS_Tool::GetTmpDir();
1908
1909   SALOMEDS::Study_var aStudy = theComponent->GetStudy();
1910   StudyContext& context = myContextMap[ aStudy->StudyId() ];
1911
1912   // HOMARD data file name
1913   std::string aFileName = "";
1914   if (isMultiFile)
1915     aFileName = SALOMEDS_Tool::GetNameFromPath(aStudy->URL());
1916   aFileName += "_HOMARD.dat";
1917
1918   // initialize sequence of file names
1919   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
1920   aFileSeq->length(1);
1921   aFileSeq[0] = CORBA::string_dup(aFileName.c_str()) ;
1922
1923   // get full path to the data file
1924   aFileName = tmpDir + aFileName;
1925
1926   // save data
1927   // -> create file
1928   std::ofstream f(aFileName.c_str());
1929
1930   // clear temporary id map
1931   context._idmap.clear();
1932
1933   int id = 1;
1934
1935   // -> dump cases
1936   std::map<std::string, HOMARD::HOMARD_Cas_var>::const_iterator it_case;
1937   for (it_case = context._mesCas.begin(); it_case != context._mesCas.end(); ++it_case) {
1938     HOMARD::HOMARD_Cas_var aCas = it_case->second;
1939     PortableServer::ServantBase_var aServant = GetServant(aCas);
1940     HOMARD_Cas_i* aCasServant = dynamic_cast<HOMARD_Cas_i*>(aServant.in());
1941     if (aCasServant) {
1942       f << HOMARD::GetSignature(HOMARD::Case) << aCasServant->Dump() << std::endl;
1943       context._idmap[id++] = dynamic_cast<PortableServer::ServantBase*>(aCasServant);
1944     }
1945   }
1946   // -> dump zones
1947   std::map<std::string, HOMARD::HOMARD_Zone_var>::const_iterator it_zone;
1948   for (it_zone = context._mesZones.begin(); it_zone != context._mesZones.end(); ++it_zone) {
1949     HOMARD::HOMARD_Zone_var aZone = it_zone->second;
1950     PortableServer::ServantBase_var aServant = GetServant(aZone);
1951     HOMARD_Zone_i* aZoneServant = dynamic_cast<HOMARD_Zone_i*>(aServant.in());
1952     if (aZoneServant) {
1953       f << HOMARD::GetSignature(HOMARD::Zone) << aZoneServant->Dump() << std::endl;
1954       context._idmap[id++] = dynamic_cast<PortableServer::ServantBase*>(aZoneServant);
1955     }
1956   }
1957   // -> dump hypotheses
1958   std::map<std::string, HOMARD::HOMARD_Hypothesis_var>::const_iterator it_hypo;
1959   for (it_hypo = context._mesHypotheses.begin(); it_hypo != context._mesHypotheses.end(); ++it_hypo) {
1960     HOMARD::HOMARD_Hypothesis_var aHypo = it_hypo->second;
1961     PortableServer::ServantBase_var aServant = GetServant(aHypo);
1962     HOMARD_Hypothesis_i* aHypoServant = dynamic_cast<HOMARD_Hypothesis_i*>(aServant.in());
1963     if (aHypoServant) {
1964       f << HOMARD::GetSignature(HOMARD::Hypothesis) << aHypoServant->Dump() << std::endl;
1965       context._idmap[id++] = dynamic_cast<PortableServer::ServantBase*>(aHypoServant);
1966     }
1967   }
1968   // -> dump iterations
1969   std::map<std::string, HOMARD::HOMARD_Iteration_var>::const_iterator it_iter;
1970   for (it_iter = context._mesIterations.begin(); it_iter != context._mesIterations.end(); ++it_iter) {
1971     HOMARD::HOMARD_Iteration_var aIter = it_iter->second;
1972     PortableServer::ServantBase_var aServant = GetServant(aIter);
1973     HOMARD_Iteration_i* aIterServant = dynamic_cast<HOMARD_Iteration_i*>(aServant.in());
1974     if (aIterServant) {
1975       f << HOMARD::GetSignature(HOMARD::Iteration) << aIterServant->Dump() << std::endl;
1976       context._idmap[id++] = dynamic_cast<PortableServer::ServantBase*>(aIterServant);
1977     }
1978   }
1979   // -> dump boundaries
1980   std::map<std::string, HOMARD::HOMARD_Boundary_var>::const_iterator it_boundary;
1981   for (it_boundary = context._mesBoundarys.begin(); it_boundary != context._mesBoundarys.end(); ++it_boundary) {
1982     HOMARD::HOMARD_Boundary_var aBoundary = it_boundary->second;
1983     PortableServer::ServantBase_var aServant = GetServant(aBoundary);
1984     HOMARD_Boundary_i* aBoundaryServant = dynamic_cast<HOMARD_Boundary_i*>(aServant.in());
1985     if (aBoundaryServant) {
1986       f << HOMARD::GetSignature(HOMARD::Boundary) << aBoundaryServant->Dump() << std::endl;
1987       context._idmap[id++] = dynamic_cast<PortableServer::ServantBase*>(aBoundaryServant);
1988     }
1989   }
1990   // -> close file
1991   f.close();
1992
1993   // put temporary files  to the stream
1994   aStreamFile = SALOMEDS_Tool::PutFilesToStream(tmpDir.c_str(), aFileSeq.in(), isMultiFile);
1995
1996   // remove temporary files
1997   if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(tmpDir.c_str(), aFileSeq.in(), true);
1998
1999   // return data stream
2000   return aStreamFile._retn();
2001 };
2002
2003 //===========================================================================
2004 SALOMEDS::TMPFile* HOMARD_Gen_i::SaveASCII(SALOMEDS::SComponent_ptr theComponent,
2005                                             const char* theURL,
2006                                             bool isMultiFile)
2007 {
2008   // No specific ASCII persistence
2009   SALOMEDS::TMPFile_var aStreamFile = Save(theComponent, theURL, isMultiFile);
2010   return aStreamFile._retn();
2011 };
2012
2013 //===========================================================================
2014 CORBA::Boolean HOMARD_Gen_i::Load(SALOMEDS::SComponent_ptr theComponent,
2015                                    const SALOMEDS::TMPFile& theStream,
2016                                    const char* theURL,
2017                                    bool isMultiFile)
2018 {
2019   MESSAGE (" Load pour theURL = "<< theURL);
2020   SALOMEDS::Study_var aStudy = theComponent->GetStudy();
2021
2022   // set current study
2023   if (myCurrentStudy->_is_nil() || aStudy->StudyId() != myCurrentStudy->StudyId())
2024     SetCurrentStudy(aStudy);
2025
2026   // get temporary directory name
2027   std::string tmpDir = isMultiFile ? std::string(theURL) : SALOMEDS_Tool::GetTmpDir();
2028
2029   // Convert the stream into sequence of files to process
2030   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles(theStream,
2031                                                                             tmpDir.c_str(),
2032                                                                             isMultiFile);
2033   // HOMARD data file name
2034   std::string aFileName = "";
2035   if (isMultiFile)
2036     aFileName = SALOMEDS_Tool::GetNameFromPath(aStudy->URL());
2037   aFileName = tmpDir + aFileName + "_HOMARD.dat";
2038
2039   StudyContext& context = myContextMap[ aStudy->StudyId() ];
2040
2041   // save data
2042   // -> create file
2043   std::ifstream f(aFileName.c_str());
2044
2045   // clear context
2046   context._mesCas.clear();
2047   context._mesHypotheses.clear();
2048   context._mesIterations.clear();
2049   context._mesZones.clear();
2050   context._mesBoundarys.clear();
2051   context._idmap.clear();
2052
2053   int id = 1;
2054   std::string line;
2055
2056   while (f) {
2057     std::getline(f, line);
2058     std::string caseSignature = HOMARD::GetSignature(HOMARD::Case);
2059     std::string zoneSignature = HOMARD::GetSignature(HOMARD::Zone);
2060     std::string iterSignature = HOMARD::GetSignature(HOMARD::Iteration);
2061     std::string hypoSignature = HOMARD::GetSignature(HOMARD::Hypothesis);
2062     std::string bounSignature = HOMARD::GetSignature(HOMARD::Boundary);
2063     if (line.substr(0, caseSignature.size()) == caseSignature) {
2064       // re-create case
2065       HOMARD::HOMARD_Cas_var aCase = newCase();
2066       PortableServer::ServantBase_var aServant = GetServant(aCase);
2067       HOMARD_Cas_i* aCaseServant = dynamic_cast<HOMARD_Cas_i*>(aServant.in());
2068       if (aCaseServant && aCaseServant->Restore(line.substr(caseSignature.size()))) {
2069         context._mesCas[aCase->GetName()] = aCase;
2070         context._idmap[id] = dynamic_cast<PortableServer::ServantBase*>(aCaseServant);
2071       }
2072     }
2073     else if (line.substr(0, zoneSignature.size()) == zoneSignature) {
2074       // re-create zone
2075       HOMARD::HOMARD_Zone_var aZone = newZone();
2076       PortableServer::ServantBase_var aServant = GetServant(aZone);
2077       HOMARD_Zone_i* aZoneServant = dynamic_cast<HOMARD_Zone_i*>(aServant.in());
2078       if (aZoneServant && aZoneServant->Restore(line.substr(zoneSignature.size()))) {
2079         context._mesZones[aZone->GetName()] = aZone;
2080         context._idmap[id] = dynamic_cast<PortableServer::ServantBase*>(aZoneServant);
2081       }
2082     }
2083     else if (line.substr(0, iterSignature.size()) == iterSignature) {
2084       // re-create iteration
2085       HOMARD::HOMARD_Iteration_var aIter = newIteration();
2086       PortableServer::ServantBase_var aServant = GetServant(aIter);
2087       HOMARD_Iteration_i* aIterServant = dynamic_cast<HOMARD_Iteration_i*>(aServant.in());
2088       if (aIterServant && aIterServant->Restore(line.substr(iterSignature.size()))) {
2089         context._mesIterations[aIter->GetName()] = aIter;
2090         context._idmap[id] = dynamic_cast<PortableServer::ServantBase*>(aIterServant);
2091       }
2092     }
2093     else if (line.substr(0, hypoSignature.size()) == hypoSignature) {
2094       // re-create hypothesis
2095       HOMARD::HOMARD_Hypothesis_var aHypo = newHypothesis();
2096       PortableServer::ServantBase_var aServant = GetServant(aHypo);
2097       HOMARD_Hypothesis_i* aHypoServant = dynamic_cast<HOMARD_Hypothesis_i*>(aServant.in());
2098       if (aHypoServant && aHypoServant->Restore(line.substr(hypoSignature.size()))) {
2099         context._mesHypotheses[aHypo->GetName()] = aHypo;
2100         context._idmap[id] = dynamic_cast<PortableServer::ServantBase*>(aHypoServant);
2101       }
2102     }
2103     else if (line.substr(0, bounSignature.size()) == bounSignature) {
2104       // re-create boundary
2105       HOMARD::HOMARD_Boundary_var aBoundary = newBoundary();
2106       PortableServer::ServantBase_var aServant = GetServant(aBoundary);
2107       HOMARD_Boundary_i* aBoundaryServant = dynamic_cast<HOMARD_Boundary_i*>(aServant.in());
2108       if (aBoundaryServant && aBoundaryServant->Restore(line.substr(bounSignature.size()))) {
2109         context._mesBoundarys[aBoundary->GetName()] = aBoundary;
2110         context._idmap[id] = dynamic_cast<PortableServer::ServantBase*>(aBoundaryServant);
2111       }
2112     }
2113     id++;
2114   }
2115
2116   // -> close file
2117   f.close();
2118
2119   // Remove temporary files created from the stream
2120   if (!isMultiFile) 
2121     SALOMEDS_Tool::RemoveTemporaryFiles(tmpDir.c_str(), aFileSeq.in(), true);
2122
2123   return true;
2124 };
2125
2126 //===========================================================================
2127 CORBA::Boolean HOMARD_Gen_i::LoadASCII(SALOMEDS::SComponent_ptr theComponent,
2128                                         const SALOMEDS::TMPFile& theStream,
2129                                         const char* theURL,
2130                                         bool isMultiFile)
2131 {
2132   // No specific ASCII persistence
2133   return Load(theComponent, theStream, theURL, isMultiFile);
2134 };
2135
2136 //===========================================================================
2137 void HOMARD_Gen_i::Close(SALOMEDS::SComponent_ptr theComponent)
2138 {
2139   if (theComponent->GetStudy()->StudyId() == GetCurrentStudyID()) {
2140     // clearing study context should be done here:
2141     // - destroy all servants and related CORBA objects
2142     // ... (TODO)
2143     // - remove context from myContextMap
2144     myContextMap.erase(theComponent->GetStudy()->StudyId());
2145     // - nullify myCurrentStudy
2146     myCurrentStudy = SALOMEDS::Study::_nil();
2147   }
2148 };
2149
2150 //===========================================================================
2151 char* HOMARD_Gen_i::ComponentDataType()
2152 {
2153   return CORBA::string_dup("HOMARD");
2154 };
2155
2156 //===========================================================================
2157 char* HOMARD_Gen_i::IORToLocalPersistentID(SALOMEDS::SObject_ptr theSObject,
2158                                             const char* IORString,
2159                                             CORBA::Boolean isMultiFile,
2160                                             CORBA::Boolean isASCII)
2161 {
2162   CORBA::String_var aString("");
2163   if (!CORBA::is_nil(theSObject) && strcmp(IORString, "") != 0) {
2164     StudyContext context = myContextMap[ theSObject->GetStudy()->StudyId() ];
2165     CORBA::Object_var anObj = _orb->string_to_object(IORString);
2166     if (!CORBA::is_nil(anObj)) {
2167       PortableServer::ServantBase_var aServant = GetServant(anObj);
2168       PortableServer::ServantBase* aStorable = dynamic_cast<PortableServer::ServantBase*>(aServant.in());
2169       if (aStorable) {
2170         std::map<int, PortableServer::ServantBase*>::const_iterator it;
2171         for (it = context._idmap.begin(); it != context._idmap.end(); ++it) {
2172           if (it->second == aStorable) {
2173             std::stringstream os;
2174             os << it->first;
2175             aString = CORBA::string_dup(os.str().c_str());
2176           }
2177         }
2178       }
2179     }
2180   }
2181   return aString._retn();
2182 };
2183
2184 //===========================================================================
2185 char* HOMARD_Gen_i::LocalPersistentIDToIOR(SALOMEDS::SObject_ptr theSObject,
2186                                             const char* aLocalPersistentID,
2187                                             CORBA::Boolean isMultiFile,
2188                                             CORBA::Boolean isASCII)
2189 {
2190   CORBA::String_var aString("");
2191   if (!CORBA::is_nil(theSObject) && strcmp(aLocalPersistentID, "") != 0) {
2192     StudyContext context = myContextMap[ theSObject->GetStudy()->StudyId() ];
2193     int id = atoi(aLocalPersistentID);
2194     if (id > 0 && context._idmap.find(id) != context._idmap.end()) {
2195       CORBA::Object_var object = _poa->servant_to_reference(context._idmap[ id ]);
2196       if (!CORBA::is_nil(object)) {
2197         aString = _orb->object_to_string(object);
2198       }
2199     }
2200   }
2201   return aString._retn();
2202 };
2203
2204 //===========================================================================
2205 bool HOMARD_Gen_i::CanPublishInStudy(CORBA::Object_ptr theIOR) 
2206 {
2207   if(CORBA::is_nil(myCurrentStudy))
2208     return false;
2209
2210   HOMARD::HOMARD_Cas_var aCas = HOMARD::HOMARD_Cas::_narrow(theIOR);
2211   if(!aCas->_is_nil())
2212     return true;
2213
2214   HOMARD::HOMARD_Hypothesis_var aHypo = HOMARD::HOMARD_Hypothesis::_narrow(theIOR);
2215   if(!aHypo->_is_nil())
2216     return true;
2217
2218   HOMARD::HOMARD_Zone_var aZone = HOMARD::HOMARD_Zone::_narrow(theIOR);
2219   if(!aZone->_is_nil())
2220     return true;
2221
2222   HOMARD::HOMARD_Boundary_var aBoundary = HOMARD::HOMARD_Boundary::_narrow(theIOR);
2223   if(!aBoundary->_is_nil())
2224     return true;
2225
2226   /* Iteration is not published directly
2227   HOMARD::HOMARD_Iteration_var aIter = HOMARD::HOMARD_Iteration::_narrow(theIOR);
2228   if(!aIter->_is_nil())
2229     return true;
2230   */
2231   return false;
2232 };
2233
2234 //===========================================================================
2235 CORBA::Boolean HOMARD_Gen_i::CanCopy(SALOMEDS::SObject_ptr theObject) 
2236 {
2237   // No Copy/Paste support
2238   return false;
2239 };
2240
2241 //===========================================================================
2242 SALOMEDS::TMPFile* HOMARD_Gen_i::CopyFrom(SALOMEDS::SObject_ptr theObject,
2243                                            CORBA::Long& theObjectID)
2244 {
2245   // No Copy/Paste support
2246   SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile(0);
2247   return aStreamFile._retn();
2248 };
2249
2250 //===========================================================================
2251 CORBA::Boolean  HOMARD_Gen_i::CanPaste(const char *theComponentName,
2252                                         CORBA::Long theObjectID)
2253 {
2254   // No Copy/Paste support
2255   return false;
2256 };
2257
2258 //===========================================================================
2259 SALOMEDS::SObject_ptr HOMARD_Gen_i::PasteInto(const SALOMEDS::TMPFile& theStream,
2260                                                CORBA::Long theObjectID,
2261                                                SALOMEDS::SObject_ptr theSObject)
2262 {
2263   // No Copy/Paste support
2264   SALOMEDS::SObject_var aResultSO;
2265   return aResultSO._retn();
2266 };
2267
2268 //===========================================================================
2269 PortableServer::ServantBase_var HOMARD_Gen_i::GetServant(CORBA::Object_ptr theObject)
2270 {
2271   PortableServer::Servant aServant = 0;
2272   if (!CORBA::is_nil(theObject)) {
2273     try {
2274       aServant = _poa->reference_to_servant(theObject);
2275     }
2276     catch (...) {
2277     }
2278   }
2279   return aServant;
2280 }
2281
2282 //===========================================================================
2283 HOMARD::HOMARD_Cas_ptr HOMARD_Gen_i::newCase()
2284 {
2285   HOMARD::HOMARD_Gen_var engine = POA_HOMARD::HOMARD_Gen::_this();
2286   HOMARD_Cas_i* aServant = new HOMARD_Cas_i(_orb, engine);
2287   HOMARD::HOMARD_Cas_var aCase = HOMARD::HOMARD_Cas::_narrow(aServant->_this());
2288   return aCase._retn();
2289 }
2290
2291 //===========================================================================
2292 HOMARD::HOMARD_Hypothesis_ptr HOMARD_Gen_i::newHypothesis()
2293 {
2294   HOMARD::HOMARD_Gen_var engine = POA_HOMARD::HOMARD_Gen::_this();
2295   HOMARD_Hypothesis_i* aServant = new HOMARD_Hypothesis_i(_orb, engine);
2296   HOMARD::HOMARD_Hypothesis_var aHypo = HOMARD::HOMARD_Hypothesis::_narrow(aServant->_this());
2297   return aHypo._retn();
2298 }
2299
2300 //===========================================================================
2301 HOMARD::HOMARD_Iteration_ptr HOMARD_Gen_i::newIteration()
2302 {
2303   HOMARD::HOMARD_Gen_var engine = POA_HOMARD::HOMARD_Gen::_this();
2304   HOMARD_Iteration_i* aServant = new HOMARD_Iteration_i(_orb, engine);
2305   HOMARD::HOMARD_Iteration_var aIter = HOMARD::HOMARD_Iteration::_narrow(aServant->_this());
2306   return aIter._retn();
2307 }
2308
2309 //===========================================================================
2310 HOMARD::HOMARD_Boundary_ptr HOMARD_Gen_i::newBoundary()
2311 {
2312   HOMARD::HOMARD_Gen_var engine = POA_HOMARD::HOMARD_Gen::_this();
2313   HOMARD_Boundary_i* aServant = new HOMARD_Boundary_i(_orb, engine);
2314   HOMARD::HOMARD_Boundary_var aBoundary = HOMARD::HOMARD_Boundary::_narrow(aServant->_this());
2315   return aBoundary._retn();
2316 }
2317 //===========================================================================
2318 HOMARD::HOMARD_Zone_ptr HOMARD_Gen_i::newZone()
2319 {
2320   HOMARD::HOMARD_Gen_var engine = POA_HOMARD::HOMARD_Gen::_this();
2321   HOMARD_Zone_i* aServant = new HOMARD_Zone_i(_orb, engine);
2322   HOMARD::HOMARD_Zone_var aZone = HOMARD::HOMARD_Zone::_narrow(aServant->_this());
2323   return aZone._retn();
2324 }
2325 //==========================================================================
2326 Engines::TMPFile* HOMARD_Gen_i::DumpPython(CORBA::Object_ptr theStudy,
2327                                        CORBA::Boolean isPublished,
2328                                        CORBA::Boolean& isValidScript)
2329 {
2330    MESSAGE ("Entree dans DumpPython");
2331    isValidScript=1;
2332    SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
2333    if(CORBA::is_nil(aStudy))
2334      return new Engines::TMPFile(0);
2335
2336    SALOMEDS::SObject_var aSO = aStudy->FindComponent("HOMARD");
2337    if(CORBA::is_nil(aSO))
2338       return new Engines::TMPFile(0);
2339
2340    std::string aScript = "\"\"\"\n";
2341    aScript += "Python script for HOMARD\n";
2342    aScript += "Copyright EDF-R&D 2010\n";
2343    aScript += "\"\"\"\n";
2344    aScript += "__revision__ = \"V1.2\"\n";
2345    aScript += "import HOMARD\n";
2346    aScript += "import salome\n";
2347    aScript += "homard = salome.lcc.FindOrLoadComponent('FactoryServer','HOMARD')\n";
2348    aScript += "def RebuildData(theStudy):\n";
2349    aScript += "\thomard.SetCurrentStudy(theStudy)\n";
2350
2351
2352    if (myContextMap[GetCurrentStudyID()]._mesBoundarys.size() > 0)
2353    {
2354     aScript += "#\n# Creation of the boundaries";
2355     aScript +=  "\n# ==========================";
2356    }
2357    std::map<std::string, HOMARD::HOMARD_Boundary_var>::const_iterator it_boundary;
2358    for (it_boundary  = myContextMap[GetCurrentStudyID()]._mesBoundarys.begin();
2359         it_boundary != myContextMap[GetCurrentStudyID()]._mesBoundarys.end(); ++it_boundary)
2360    {
2361     HOMARD::HOMARD_Boundary_var maBoundary = (*it_boundary).second;
2362     CORBA::String_var dumpCorbaBoundary = maBoundary->GetDumpPython();
2363     std::string dumpBoundary = dumpCorbaBoundary.in();
2364     aScript+=dumpBoundary;
2365    }
2366
2367
2368    if (myContextMap[GetCurrentStudyID()]._mesZones.size() > 0)
2369    {
2370     aScript += "#\n# Creation of the zones";
2371     aScript +=  "\n# =====================";
2372    }
2373    std::map<std::string, HOMARD::HOMARD_Zone_var>::const_iterator it_zone;
2374    for ( it_zone  = myContextMap[GetCurrentStudyID()]._mesZones.begin(); 
2375          it_zone != myContextMap[GetCurrentStudyID()]._mesZones.end(); ++it_zone) 
2376    {
2377     HOMARD::HOMARD_Zone_var maZone = (*it_zone).second;
2378     CORBA::String_var dumpCorbaZone = maZone->GetDumpPython();
2379     std::string dumpZone = dumpCorbaZone.in();
2380     aScript+=dumpZone;
2381    }
2382
2383
2384    aScript += "#\n# Creation of the hypotheses";
2385    aScript +=  "\n# ==========================";
2386    std::map<std::string, HOMARD::HOMARD_Hypothesis_var>::const_iterator it_hypo;
2387    for ( it_hypo  = myContextMap[GetCurrentStudyID()]._mesHypotheses.begin();
2388          it_hypo != myContextMap[GetCurrentStudyID()]._mesHypotheses.end(); it_hypo++)
2389    {
2390     HOMARD::HOMARD_Hypothesis_var monHypo = (*it_hypo).second;
2391     CORBA::String_var dumpCorbaHypo = monHypo->GetDumpPython();
2392     std::string dumpHypo = dumpCorbaHypo.in();
2393     aScript+=dumpHypo;
2394    }
2395
2396
2397    aScript += "#\n# Creation of the cases";
2398    aScript += "\n# =====================";
2399    std::map<std::string, HOMARD::HOMARD_Cas_var>::const_iterator it_cas;
2400    for (it_cas  = myContextMap[GetCurrentStudyID()]._mesCas.begin();
2401         it_cas != myContextMap[GetCurrentStudyID()]._mesCas.end(); it_cas++)
2402         {
2403            std::string nomCas = (*it_cas).first;
2404            std::string dumpCas = std::string("\n# Creation of the case ") ;
2405            dumpCas +=  nomCas + std::string("\n");
2406            dumpCas += std::string("\t") + nomCas;
2407            dumpCas += std::string(" = homard.CreateCase('") + nomCas + std::string("', '");
2408
2409            HOMARD::HOMARD_Cas_var myCase = (*it_cas).second;
2410            CORBA::String_var cIter0= myCase->GetIter0Name();
2411            std::string iter0 = cIter0.in();
2412
2413            HOMARD::HOMARD_Iteration_var myIteration = myContextMap[GetCurrentStudyID()]._mesIterations[iter0];
2414            CORBA::String_var cMesh0= myIteration->GetMeshFile();
2415            std::string mesh0 = cMesh0.in();
2416            CORBA::String_var cMeshName0= myIteration->GetMeshName();
2417            std::string meshName0 = cMeshName0.in();
2418            dumpCas += meshName0 + std::string("', '")+ mesh0 + std::string("')\n"); 
2419            CORBA::String_var dumpCorbaCase = myCase->GetDumpPython();
2420            std::string dumpCas2= dumpCorbaCase.in();
2421
2422            aScript+=dumpCas + dumpCas2;
2423         };
2424
2425
2426    aScript += "#\n# Creation of the iterations" ;
2427    aScript += "\n# ==========================";
2428    std::map<std::string, HOMARD::HOMARD_Iteration_var>::const_iterator it_iter;
2429    for (it_iter  = myContextMap[GetCurrentStudyID()]._mesIterations.begin(); 
2430         it_iter != myContextMap[GetCurrentStudyID()]._mesIterations.end(); ++it_iter) 
2431    {
2432     HOMARD::HOMARD_Iteration_var aIter = (*it_iter).second;
2433     CORBA::String_var dumpCorbaIter = aIter->GetDumpPython();
2434     std::string dumpIter = dumpCorbaIter.in();
2435     aScript+=dumpIter;
2436    }
2437
2438
2439    const size_t aLen = strlen(aScript.c_str());
2440    char* aBuffer = new char[aLen+1];
2441    strcpy(aBuffer, aScript.c_str());
2442
2443    CORBA::Octet* anOctetBuf =  (CORBA::Octet*)aBuffer;
2444    Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
2445
2446    return aStreamFile._retn();
2447 }
2448
2449 //=============================================================================
2450 extern "C"
2451 {
2452   PortableServer::ObjectId* HOMARDEngine_factory(CORBA::ORB_ptr orb,
2453                                                   PortableServer::POA_ptr poa, 
2454                                                   PortableServer::ObjectId* contId,
2455                                                   const char* instanceName, 
2456                                                   const char* interfaceName)
2457   {
2458     MESSAGE("PortableServer::ObjectId* HOMARDEngine_factory()");
2459     HOMARD_Gen_i* myHOMARD_Gen = new HOMARD_Gen_i(orb, poa, contId, instanceName, interfaceName);
2460     return myHOMARD_Gen->getId();
2461   }
2462 }