]> SALOME platform Git repositories - modules/med.git/blob - src/MED/Med_Gen_i.cxx
Salome HOME
sources v1.2
[modules/med.git] / src / MED / Med_Gen_i.cxx
1 //  MED MED : implemetation of MED idl descriptions
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
6 //  This library is free software; you can redistribute it and/or 
7 //  modify it under the terms of the GNU Lesser General Public 
8 //  License as published by the Free Software Foundation; either 
9 //  version 2.1 of the License. 
10 // 
11 //  This library is distributed in the hope that it will be useful, 
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
14 //  Lesser General Public License for more details. 
15 // 
16 //  You should have received a copy of the GNU Lesser General Public 
17 //  License along with this library; if not, write to the Free Software 
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
19 // 
20 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
21 //
22 //
23 //
24 //  File   : Med_Gen_i.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : MED
27 //  $Header$
28
29 using namespace std;
30 using namespace std;
31 #include "Med_Gen_i.hxx"
32
33 #include "Mesh_i.hxx"
34 #include "Med_i.hxx"
35 #include "FieldInt_i.hxx"
36 #include "FieldDouble_i.hxx"
37 #include "Support_i.hxx"
38
39
40 #include "MEDMEM_Mesh.hxx"
41 #include "MEDMEM_Field.hxx"
42 #include "MEDMEM_Med.hxx"
43 #include "MEDMEM_MedMedDriver.hxx"
44 #include "MEDMEM_MedMeshDriver.hxx"
45 #include "MEDMEM_MedFieldDriver.hxx"
46 #include "MEDMEM_define.hxx"
47 #include "MEDMEM_DriversDef.hxx"
48
49
50 #include "Utils_SINGLETON.hxx"
51 #include "OpUtil.hxx"
52 #include "Utils_CorbaException.hxx"
53 #include "utilities.h"
54
55 #include <string>
56 #include <deque>
57 #include <map>
58
59 #include <TCollection_AsciiString.hxx>
60 #include <TColStd_SequenceOfAsciiString.hxx>
61 #include <HDFascii.hxx>
62 #include "SALOMEDS_Tool.hxx"
63
64 // Initialisation des variables statiques
65  map <string, string> Med_Gen_i::_MedCorbaObj;
66  string Med_Gen_i::_myFileName="";
67  string Med_Gen_i::_saveFileName="";
68
69 //=============================================================================
70 /*!
71  *  default constructor: not for use
72  */
73 //=============================================================================
74
75 Med_Gen_i::Med_Gen_i()
76 {
77   MESSAGE("Med_Gen_i::Med_Gen_i");
78 }
79
80 //=============================================================================
81 /*!
82  *  standard constructor
83  */
84 //=============================================================================
85
86 Med_Gen_i:: Med_Gen_i(CORBA::ORB_ptr orb,
87                                 PortableServer::POA_ptr poa,
88                                 PortableServer::ObjectId * contId, 
89                                 const char *instanceName, 
90                                 const char *interfaceName) :
91   Engines_Component_i(orb, poa, contId, instanceName, interfaceName)
92 {
93   MESSAGE("activate object");
94   _thisObj = this ;
95   _id = _poa->activate_object(_thisObj);
96
97   _duringLoad=false;
98   // get an NamingService interface
99   _NS = SINGLETON_<SALOME_NamingService>::Instance() ;
100   ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting()) ;
101   _NS->init_orb( _orb ) ;
102 }
103 //=============================================================================
104 /*!
105  *  private method : change a study name in SALOMEDS::Study_var
106  */
107 //=============================================================================
108
109 SALOMEDS::Study_var Med_Gen_i::studyName2Study(const char* studyName)
110   throw(SALOME::SALOME_Exception)
111 {
112   string myStudyName(studyName);
113
114   if (myStudyName.size() == 0)
115     THROW_SALOME_CORBA_EXCEPTION("No Study Name given", \
116                                  SALOME::BAD_PARAM);
117
118   // Get StudyManager Reference, current study,
119   
120   CORBA::Object_var obj = _NS->Resolve("/myStudyManager");
121   SALOMEDS::StudyManager_var myStudyManager =
122     SALOMEDS::StudyManager::_narrow(obj);
123   if(CORBA::is_nil(myStudyManager))
124     THROW_SALOME_CORBA_EXCEPTION("No StudyManager Found in NameService", \
125                                  SALOME::BAD_PARAM);
126   
127   SALOMEDS::Study_var myStudy =
128     myStudyManager->GetStudyByName(myStudyName.c_str());
129   if (CORBA::is_nil(myStudy))
130     THROW_SALOME_CORBA_EXCEPTION("Wrong Study Name", \
131                                  SALOME::BAD_PARAM);
132
133   return SALOMEDS::Study::_duplicate(myStudy) ;
134 }
135
136 //=============================================================================
137 /*!
138  *  private method : add Med component in Study (Not MedGen ???)
139  */
140 //=============================================================================
141
142 void Med_Gen_i::addInStudy(SALOMEDS::Study_var myStudy)
143   throw(SALOME::SALOME_Exception)
144 {
145   SALOMEDS::StudyBuilder_var  myBuilder = myStudy->NewBuilder();
146   
147   myBuilder->NewCommand();
148   
149   // Create SComponent labelled 'Med' if it doesn't already exit
150   SALOMEDS::SComponent_var medfather = myStudy->FindComponent("Med");
151   if ( CORBA::is_nil(medfather) )
152     {
153       // mpv: component label must be created in spite of "Locked" study flag state
154       bool aLocked = myStudy->GetProperties()->IsLocked();
155       if (aLocked) myStudy->GetProperties()->SetLocked(false);
156       
157       MESSAGE("Add Component Med");
158       medfather = myBuilder->NewComponent("Med");
159       SALOMEDS::GenericAttribute_var anAttr = myBuilder->FindOrCreateAttribute(medfather, "AttributeName");
160       SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(anAttr);
161       aName->SetValue("Med");
162       //            Utilisation de this  deconseillee par Paul ??
163       //            myBuilder->DefineComponentInstance(medfather,POA_Engines::Med_Gen::_this());
164       CORBA::Object_var myO = _poa->id_to_reference(*_id); // this ior...
165       myBuilder->DefineComponentInstance(medfather,myO);
166       
167       if (aLocked) myStudy->GetProperties()->SetLocked(true);
168     } 
169   
170   myBuilder->CommitCommand();
171    
172 }
173
174 //=============================================================================
175 /*!
176  * Lit tous les objets contenus dans un fichier med et les lit en memoire
177  */
178 //=============================================================================
179 SALOME_MED::MED_ptr Med_Gen_i::readStructFile (const char* fileName,
180                                 const char* studyName)
181   throw(SALOME::SALOME_Exception)
182 {
183         SCRUTE(fileName);
184         SALOMEDS::Study_var myStudy = studyName2Study(studyName) ;
185         if (!_duringLoad) addInStudy(myStudy) ;
186
187         SALOME_MED::MED_ptr myMedIOR ;
188         try 
189         {
190           // we create a new MED_i and add in study
191           MED_i * myMedI = new MED_i();
192           myMedIOR = myMedI->_this() ;
193           if (!_duringLoad) myMedI->addInStudy(myStudy,myMedIOR) ;        
194           // create ::MED object, read all and add in study !
195           myMedI->init(myStudy,MED_DRIVER,fileName) ;
196         }
197         catch (const SALOMEDS::StudyBuilder::LockProtection & lp) {}
198         catch(...)
199         {
200                 MESSAGE("Erreur a la lecture du fichier");
201                 THROW_SALOME_CORBA_EXCEPTION("Unable to open File "\
202                                                 ,SALOME::BAD_PARAM);
203         }
204         return SALOME_MED::MED::_duplicate(myMedIOR) ;
205 }
206
207 //=============================================================================
208 /*!
209  *  Prepare un Maillage sans le lire en memoire avec stokage dans l'etude
210  *  des champs avec leur type
211  */
212 //=============================================================================
213 void Med_Gen_i::readStructFileWithFieldType (const char* fileName,
214                                              const char* studyName)
215 throw (SALOME::SALOME_Exception)
216 {
217   BEGIN_OF("Med_Gen_i::readStructFileWithFieldType (const char* fileName,const char* studyName)");
218
219         SCRUTE(fileName);
220         SALOMEDS::Study_var myStudy = studyName2Study(studyName) ;
221
222         if (!_duringLoad) addInStudy(myStudy) ;
223
224         try 
225         {
226           // we create a new MED_i and add in study
227           MED_i * myMedI = new MED_i();
228           SALOME_MED::MED_ptr myMedIOR = myMedI->_this() ;
229           if (!_duringLoad) myMedI->addInStudy(myStudy,myMedIOR) ;        
230           // create ::MED object, read all and add in study !
231           myMedI->initWithFieldType(myStudy,MED_DRIVER,fileName) ;
232         }
233         catch (const SALOMEDS::StudyBuilder::LockProtection & lp) {}
234         catch(...)
235         {
236                 MESSAGE("Erreur a la lecture du fichier");
237                 THROW_SALOME_CORBA_EXCEPTION("Unable to open File "\
238                                                 ,SALOME::BAD_PARAM);
239         }
240
241         END_OF("Med_Gen_i::readStructFileWithFieldType (const char* fileName,const char* studyName)");
242
243
244 }
245
246 //=============================================================================
247 /*!
248  *  Sert un Maillage
249  */
250 //=============================================================================
251 SALOME_MED::MESH_ptr Med_Gen_i::readMeshInFile(const char* fileName,
252                                                const char* studyName,
253                                                const char* meshName)
254 throw (SALOME::SALOME_Exception)
255 {
256         SCRUTE(fileName);
257         SALOMEDS::Study_var myStudy = studyName2Study(studyName) ;
258
259         if (!_duringLoad) addInStudy(myStudy) ;
260
261 // Creation du maillage
262
263         MESH * myMesh= new MESH() ;
264         myMesh->setName(meshName);
265         MED_MESH_RDONLY_DRIVER myMeshDriver(fileName,myMesh);
266         try
267         {
268                 myMeshDriver.setMeshName(meshName);
269                 myMeshDriver.open();
270         }
271         catch (const exception & ex)
272         {
273                 MESSAGE("Exception Interceptee : ");
274                 SCRUTE(ex.what());
275                 THROW_SALOME_CORBA_EXCEPTION("Unable to find this mesh in this file",SALOME::BAD_PARAM);
276         };
277         try
278         {
279                 myMeshDriver.read();
280                 MESSAGE("apres read");
281                 myMeshDriver.close();
282         }
283         catch (const exception & ex)
284         {
285                 MESSAGE("Exception Interceptee : ");
286                 SCRUTE(ex.what());
287                 THROW_SALOME_CORBA_EXCEPTION("Unable to read this mesh in this file",SALOME::BAD_PARAM);
288         };
289
290         MESH_i * meshi = new MESH_i(myMesh);
291         //SALOME_MED::MESH_var mesh = SALOME_MED::MESH::_narrow(meshi->_this());
292         SALOME_MED::MESH_ptr mesh = meshi->_this();
293         try
294         {
295         // add the mesh object in study
296                 if (!_duringLoad) meshi->addInStudy(myStudy,mesh);
297         }
298         catch (const SALOMEDS::StudyBuilder::LockProtection & lp) {}
299         return SALOME_MED::MESH::_duplicate(mesh);
300 }
301 //=============================================================================
302 /*!
303  *  Sert un Champ
304  */
305 //=============================================================================
306 SALOME_MED::FIELD_ptr Med_Gen_i::readFieldInFile(const char* fileName,
307                                                const char* studyName,
308                                                const char* fieldName,
309                                                CORBA::Long ordre,
310                                                CORBA::Long iter)
311 throw (SALOME::SALOME_Exception)
312 {
313         SCRUTE(fileName);
314         string myStudyName(studyName);
315
316         if (myStudyName.size() == 0)
317                 THROW_SALOME_CORBA_EXCEPTION("No Study Name given", \
318                                  SALOME::BAD_PARAM);
319
320         // Get StudyManager Reference, current study,
321         
322         CORBA::Object_var obj = _NS->Resolve("/myStudyManager");
323         SALOMEDS::StudyManager_var myStudyManager =
324                         SALOMEDS::StudyManager::_narrow(obj);
325         ASSERT(! CORBA::is_nil(myStudyManager));
326         SALOMEDS::Study_var myStudy =
327                 myStudyManager->GetStudyByName(myStudyName.c_str());
328         if (CORBA::is_nil(myStudy))
329         THROW_SALOME_CORBA_EXCEPTION("Wrong Study Name", \
330                                  SALOME::BAD_PARAM);
331
332         SALOMEDS::StudyBuilder_var myBuilder = myStudy->NewBuilder();
333         SALOMEDS::SComponent_var medfather = myStudy->FindComponent("Med");
334         if (CORBA::is_nil(medfather))
335         {
336                 myBuilder->NewCommand();
337                 // mpv: component label must be created in spite of "Locked" study flag state
338                 bool aLocked = myStudy->GetProperties()->IsLocked();
339                 if (aLocked) myStudy->GetProperties()->SetLocked(false);
340
341                 medfather = myBuilder->NewComponent("Med");
342                 SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(
343                       myBuilder->FindOrCreateAttribute(medfather, "AttributeName"));
344                 aName->SetValue("Med");
345                 CORBA::Object_var myO = _poa->id_to_reference(*_id); // this ior...
346                 myBuilder->DefineComponentInstance(medfather,myO);
347
348                 if (aLocked) myStudy->GetProperties()->SetLocked(true);
349                 myBuilder->CommitCommand();
350
351         }
352         else
353                         MESSAGE("MED dejà dans l étude");
354
355         MESSAGE("Lecture du fichier ")
356         SCRUTE(fileName);
357
358 // Creation du champ
359
360         FIELD_ * myField= new FIELD_() ;
361         MED * mymed = new MED(MED_DRIVER,fileName) ;
362         try
363         {
364                 deque<string> fieldsNames = mymed->getFieldNames() ;
365                 int numberOfFields = fieldsNames.size();
366                 int i;
367                 for (i=0; i<numberOfFields; i++)
368                 {
369                         if (fieldsNames[i]== fieldName) break;
370                 }
371                 if (i == numberOfFields)
372                 {
373                         THROW_SALOME_CORBA_EXCEPTION("Unable to find this field ",SALOME::BAD_PARAM);
374                 }
375                 MESSAGE("trouve");
376 /*
377                 deque<DT_IT_> myIteration = mymed->getFieldIteration (fieldName);
378                 if (myIteration.size() != 1)
379                 {
380                         MESSAGE("WARNING : My iteration size is ")
381                         SCRUTE(myIteration.size());
382                 }
383 */
384                 myField = mymed->getField(fieldName,iter,ordre);
385         }
386         catch (const exception & ex)
387         {
388                 MESSAGE("Exception Interceptee : ");
389                 SCRUTE(ex.what());
390                 THROW_SALOME_CORBA_EXCEPTION("Unable to find this field in this file",SALOME::BAD_PARAM);
391         };
392                         
393         SUPPORT * fieldSupport;
394         SALOME_MED::SUPPORT_ptr mySupportIOR;
395         try
396         {
397                 fieldSupport=(SUPPORT *)myField->getSupport() ;
398                 ASSERT(fieldSupport != NULL);
399                 MESH * myMesh=(MESH *)fieldSupport->getMesh();
400                 ASSERT(myMesh != NULL);
401                 myMesh->read();
402                 SCRUTE(myMesh->getName());
403                 fieldSupport->update();
404                 SUPPORT_i * mySupportI = new SUPPORT_i(fieldSupport);
405                 mySupportIOR=mySupportI->_this();
406         }
407         catch (const exception & ex)
408         {
409                 MESSAGE("Exception Interceptee : ");
410                 SCRUTE(ex.what());
411                 THROW_SALOME_CORBA_EXCEPTION("Unable to find associated support",SALOME::BAD_PARAM);
412         };
413
414         med_type_champ type = myField->getValueType() ;
415         switch (type) 
416         {
417          case MED_FR::MED_INT32:        
418          {
419                 try 
420                 {
421                         ((FIELD<int>*)myField)->read() ;
422                         FIELDINT_i * myFieldIntI = new FIELDINT_i(mySupportIOR,(FIELD<int>*)myField);
423                         POA_SALOME_MED::FIELD_tie<FIELD_i> * myFieldTie = new POA_SALOME_MED::FIELD_tie<FIELD_i>(myFieldIntI);
424                         SALOME_MED::FIELD_ptr myFieldIOR = myFieldTie->_this() ;
425                         if (!_duringLoad) myFieldIntI->addInStudy(myStudy,myFieldIOR) ;
426                         return SALOME_MED::FIELD::_duplicate(myFieldIOR);
427                 }
428                 catch (const SALOMEDS::StudyBuilder::LockProtection & lp) {}
429                 catch (const exception & ex)
430                 {
431                         MESSAGE("Exception Interceptee : ");
432                         SCRUTE(ex.what());
433                         THROW_SALOME_CORBA_EXCEPTION("Unable to read int field",SALOME::BAD_PARAM);
434                 };
435                 break;
436          }
437          case MED_FR::MED_REEL64: 
438          {
439                 try 
440                 {
441                         ((FIELD<double>*)myField)->read() ;
442                         FIELDDOUBLE_i * myFieldDoubleI = new FIELDDOUBLE_i(mySupportIOR,(FIELD<double>*)myField);
443                         POA_SALOME_MED::FIELD_tie<FIELD_i> * myFieldTie = new POA_SALOME_MED::FIELD_tie<FIELD_i>(myFieldDoubleI);
444                         SALOME_MED::FIELD_ptr myFieldIOR = myFieldTie->_this() ;
445                         if (!_duringLoad) myFieldDoubleI->addInStudy(myStudy,myFieldIOR) ;
446                         return SALOME_MED::FIELD::_duplicate(myFieldIOR);
447                 }
448                 catch (const SALOMEDS::StudyBuilder::LockProtection & lp) {}
449                 catch (const exception & ex)
450                 {
451                         MESSAGE("Exception Interceptee : ");
452                         SCRUTE(ex.what());
453                         THROW_SALOME_CORBA_EXCEPTION("Unable to read double field",SALOME::BAD_PARAM);
454                 };
455                 break;
456          }
457         }
458
459         
460 }
461
462
463 //=============================================================================
464 /*!
465  *  Destructor
466  */
467 //=============================================================================
468
469 Med_Gen_i::~Med_Gen_i()
470 {
471   MESSAGE("Med_Gen_i::~Med_Gen_i");
472 }
473
474 //=============================================================================
475 /*!
476  *  CORBA: Save Mesh objects (called when a study is saved)
477  */
478 //=============================================================================
479 SALOMEDS::TMPFile* Med_Gen_i::Save(SALOMEDS::SComponent_ptr theComponent,
480                                    const char* theURL,
481                                    bool isMultiFile) {
482   const char* LOC = "Med_Gen_i::Save";
483   BEGIN_OF(LOC);
484
485   SALOMEDS::TMPFile_var aStreamFile;
486   // Get a temporary directory to store a file
487   TCollection_AsciiString aTmpDir = (isMultiFile)?TCollection_AsciiString((char*)theURL):SALOMEDS_Tool::GetTmpDir();
488   // Create a list to store names of created files
489   SALOMEDS::ListOfFileNames_var aSeq = new SALOMEDS::ListOfFileNames;
490   TColStd_SequenceOfAsciiString aFileNames;
491
492   CORBA::String_var aSaveStudyName = strdup(SALOMEDS_Tool::GetNameFromPath(theComponent->GetStudy()->URL()));
493
494   SALOMEDS::SObject_var aMedMeshFather = theComponent->GetStudy()->FindObject("MEDMESH");
495   if (!CORBA::is_nil(aMedMeshFather)) {
496     SALOMEDS::ChildIterator_var anIter = theComponent->GetStudy()->NewChildIterator(aMedMeshFather);
497     for(; anIter->More(); anIter->Next()) {
498       SALOMEDS::SObject_var aSO = anIter->Value();
499       SALOMEDS::GenericAttribute_var anAttr;
500       if (aSO->FindAttribute(anAttr,"AttributeIOR")) {
501         CORBA::Object_var myIOR = _orb->string_to_object(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value());
502         SALOME_MED::MESH_var myMesh = SALOME_MED::MESH::_narrow(myIOR);
503         if (! CORBA::is_nil(myMesh)) {
504           TCollection_AsciiString aName(strdup(aSaveStudyName));
505           aName += "_MEDMESH_";
506           aName += myMesh->getName();
507           aName += ".med";
508           MESSAGE("Save mesh with name "<<aName.ToCString());
509           long driverId = myMesh->addDriver(SALOME_MED::MED_DRIVER,(aTmpDir+aName).ToCString(),myMesh->getName());
510           myMesh->write(driverId,"");
511           aFileNames.Append(aName);
512         }
513       }
514     }
515   }
516
517   SALOMEDS::SObject_var aMedFieldFather = theComponent->GetStudy()->FindObject("MEDFIELD");
518   if (!CORBA::is_nil(aMedFieldFather)) {
519     SALOMEDS::ChildIterator_var anIter = theComponent->GetStudy()->NewChildIterator(aMedFieldFather);
520     for(; anIter->More(); anIter->Next()) {
521       SALOMEDS::SObject_var aSO = anIter->Value();
522       SALOMEDS::GenericAttribute_var anAttr;
523       if (aSO->FindAttribute(anAttr,"AttributeIOR")) {
524         CORBA::Object_var myIOR = _orb->string_to_object(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value());
525         SALOME_MED::FIELD_var myField = SALOME_MED::FIELD::_narrow(myIOR);
526         if (! CORBA::is_nil(myField)) {
527           ostringstream a,b;
528           a<< myField->getOrderNumber();
529           b<< myField->getIterationNumber();
530
531           TCollection_AsciiString aName(strdup(aSaveStudyName));
532           aName += "_MEDFIELD_";
533           aName += myField->getName();
534           aName += "_ORDRE_";
535           aName += strdup(a.str().c_str());
536           aName += "_ITER_";
537           aName += strdup(b.str().c_str());
538           aName += ".med";
539           MESSAGE("Save mesh with name "<<aName.ToCString());
540           long driverId = myField->addDriver(SALOME_MED::MED_DRIVER,(aTmpDir+aName).ToCString(),myField->getName());
541           myField->write(driverId,"");
542           aFileNames.Append(aName);
543         }
544       }
545     }
546   }
547
548   int i;
549   aSeq->length(aFileNames.Length());
550   for(i = aFileNames.Length(); i > 0; i--) aSeq[i-1] = CORBA::string_dup(aFileNames.Value(i).ToCString());
551   // Conver a file to the byte stream
552   aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir.ToCString(), aSeq.in(), isMultiFile);
553   // Remove the created file and tmp directory
554   if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.ToCString(), aSeq.in(), true);
555   // Return the created byte stream
556   return aStreamFile._retn();
557   
558   END_OF(LOC);
559 }
560
561 SALOMEDS::TMPFile* Med_Gen_i::SaveASCII(SALOMEDS::SComponent_ptr theComponent,
562                                         const char* theURL,
563                                         bool isMultiFile) {
564   const char* LOC = "Med_Gen_i::SaveASCII";
565   BEGIN_OF(LOC);
566   
567   SALOMEDS::TMPFile_var aStreamFile;
568   // Get a temporary directory to store a file
569   TCollection_AsciiString aTmpDir = (isMultiFile)?TCollection_AsciiString((char*)theURL):SALOMEDS_Tool::GetTmpDir();
570   // Create a list to store names of created files
571   SALOMEDS::ListOfFileNames_var aSeq = new SALOMEDS::ListOfFileNames;
572   TColStd_SequenceOfAsciiString aFileNames;
573   
574   CORBA::String_var aSaveStudyName = strdup(SALOMEDS_Tool::GetNameFromPath(theComponent->GetStudy()->URL()));
575   
576   SALOMEDS::SObject_var aMedMeshFather = theComponent->GetStudy()->FindObject("MEDMESH");
577   if (!CORBA::is_nil(aMedMeshFather)) {
578     SALOMEDS::ChildIterator_var anIter = theComponent->GetStudy()->NewChildIterator(aMedMeshFather);
579     for(; anIter->More(); anIter->Next()) {
580       SALOMEDS::SObject_var aSO = anIter->Value();
581       SALOMEDS::GenericAttribute_var anAttr;
582       if (aSO->FindAttribute(anAttr,"AttributeIOR")) {
583         CORBA::Object_var myIOR = _orb->string_to_object(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value());
584         SALOME_MED::MESH_var myMesh = SALOME_MED::MESH::_narrow(myIOR);
585         if (! CORBA::is_nil(myMesh)) {
586           TCollection_AsciiString aName(strdup(aSaveStudyName));
587           aName += "_MEDMESH_";
588           aName += myMesh->getName();
589           aName += ".med";
590           MESSAGE("Save mesh with name "<<aName.ToCString());
591           long driverId = myMesh->addDriver(SALOME_MED::MED_DRIVER,(aTmpDir+aName).ToCString(),myMesh->getName());
592           myMesh->write(driverId,"");
593           HDFascii::ConvertFromHDFToASCII(strdup((aTmpDir+aName).ToCString()), true);
594           aFileNames.Append(aName);
595         }
596       }
597     }
598   }
599
600   SALOMEDS::SObject_var aMedFieldFather = theComponent->GetStudy()->FindObject("MEDFIELD");
601   if (!CORBA::is_nil(aMedFieldFather)) {
602     SALOMEDS::ChildIterator_var anIter = theComponent->GetStudy()->NewChildIterator(aMedFieldFather);
603     for(; anIter->More(); anIter->Next()) {
604       SALOMEDS::SObject_var aSO = anIter->Value();
605       SALOMEDS::GenericAttribute_var anAttr;
606       if (aSO->FindAttribute(anAttr,"AttributeIOR")) {
607         CORBA::Object_var myIOR = _orb->string_to_object(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value());
608         SALOME_MED::FIELD_var myField = SALOME_MED::FIELD::_narrow(myIOR);
609         if (! CORBA::is_nil(myField)) {
610           ostringstream a,b;
611           a<< myField->getOrderNumber();
612           b<< myField->getIterationNumber();
613
614           TCollection_AsciiString aName(strdup(aSaveStudyName));
615           aName += "_MEDFIELD_";
616           aName += myField->getName();
617           aName += "_ORDRE_";
618           aName += strdup(a.str().c_str());
619           aName += "_ITER_";
620           aName += strdup(b.str().c_str());
621           aName += ".med";
622           MESSAGE("Save mesh with name "<<aName.ToCString());
623           long driverId = myField->addDriver(SALOME_MED::MED_DRIVER,(aTmpDir+aName).ToCString(),myField->getName());
624           myField->write(driverId,"");
625           HDFascii::ConvertFromHDFToASCII(strdup((aTmpDir+aName).ToCString()), true);
626           aFileNames.Append(aName);
627         }
628       }
629     }
630   }
631
632   int i;
633   aSeq->length(aFileNames.Length());
634   for(i = aFileNames.Length(); i > 0; i--) aSeq[i-1] = CORBA::string_dup(aFileNames.Value(i).ToCString());
635   // Conver a file to the byte stream
636   aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir.ToCString(), aSeq.in(), isMultiFile);
637   // Remove the created file and tmp directory
638   if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.ToCString(), aSeq.in(), true);
639   // Return the created byte stream
640   return aStreamFile._retn();
641   
642   END_OF(LOC);
643 }
644
645 //=============================================================================
646 /*!
647  *  CORBA: Load Mesh objects (called when an existing study is opened)
648  */
649 //=============================================================================
650
651 CORBA::Boolean Med_Gen_i::Load(SALOMEDS::SComponent_ptr theComponent,
652                                const SALOMEDS::TMPFile& theStream,
653                                const char* theURL,
654                                bool isMultiFile) {
655   const char* LOC = "Med_Gen_i::Load";
656   BEGIN_OF(LOC);
657
658   // Get a temporary directory for a file
659   TCollection_AsciiString aTmpDir =
660     (isMultiFile)?TCollection_AsciiString((char*)theURL):SALOMEDS_Tool::GetTmpDir();
661   _saveFileName = CORBA::string_dup(aTmpDir.ToCString());
662   SALOMEDS::ListOfFileNames_var aSeq =
663     SALOMEDS_Tool::PutStreamToFiles(theStream, aTmpDir.ToCString(), isMultiFile);
664   return true;
665
666   END_OF(LOC);
667 }
668
669 CORBA::Boolean Med_Gen_i::LoadASCII(SALOMEDS::SComponent_ptr theComponent,
670                                     const SALOMEDS::TMPFile& theStream,
671                                     const char* theURL,
672                                     bool isMultiFile) {
673   return Load(theComponent, theStream, theURL, isMultiFile);
674 }
675
676 //=============================================================================
677 /*!
678  *  CORBA: 
679  */
680 //=============================================================================
681
682 void Med_Gen_i::Close(SALOMEDS::SComponent_ptr theComponent)
683 {
684   MESSAGE("Med_Gen_i::Close");
685   SALOMEDS::SObject_var aMedMeshFather = theComponent->GetStudy()->FindObject("MEDMESH");
686   if (!CORBA::is_nil(aMedMeshFather)) {
687     SALOMEDS::ChildIterator_var anIter = theComponent->GetStudy()->NewChildIterator(aMedMeshFather);
688     for(; anIter->More(); anIter->Next()) {
689       SALOMEDS::SObject_var aSO = anIter->Value();
690       SALOMEDS::GenericAttribute_var anAttr;
691       if (aSO->FindAttribute(anAttr,"AttributeIOR")) {
692         CORBA::Object_var myIOR = _orb->string_to_object(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value());
693         SALOME_MED::MESH_var myMesh = SALOME_MED::MESH::_narrow(myIOR);
694         // here must call method destroy of myMesh, but it not implented yet
695       }
696     }
697   }
698 }
699
700 //=============================================================================
701 /*!
702  *  CORBA:
703  */
704 //=============================================================================
705
706 char* Med_Gen_i::ComponentDataType()
707 {
708   MESSAGE("Med_Gen_i::ComponentDataType");
709   return strdup("Med") ; /* What is this type ? */
710 }
711     
712 //=============================================================================
713 /*!
714  *  CORBA: give a persistent reference of a transient object (for study save) 
715  */
716 //=============================================================================
717
718 char* Med_Gen_i::IORToLocalPersistentID(SALOMEDS::SObject_ptr theSObject,
719                                         const char* IORString,
720                                         CORBA::Boolean isMultiFile,
721                                         CORBA::Boolean isASCII) {
722   const char * LOC = "Med_Gen_i::IORToLocalPersistentID" ;
723   BEGIN_OF(LOC) ;
724   SCRUTE(IORString);
725
726   string aSaveStudyName(strdup(SALOMEDS_Tool::GetNameFromPath(theSObject->GetStudy()->URL())));
727   
728
729   if (string(IORString).size()==0) return strdup((aSaveStudyName+"_MED").c_str());
730   // Well, we know where put object (_saveFilename) and we know object (IORString)
731   // cast object :
732   CORBA::Object_var myIOR = _orb->string_to_object(IORString);
733
734   // MED
735   SALOME_MED::MED_var myMed = SALOME_MED::MED::_narrow(myIOR);
736   if (! CORBA::is_nil(myMed)) 
737   {
738         // nothing to save : Support will be saved inside the mesh
739         string str_MedName=aSaveStudyName + "_MED Objet Med + /OBJ_MED/";
740         return strdup(str_MedName.c_str()) ; 
741   }
742  
743   // MESH
744   SALOME_MED::MESH_var myMesh = SALOME_MED::MESH::_narrow(myIOR);
745   if (! CORBA::is_nil(myMesh)) 
746   {
747     CORBA::String_var aName((aSaveStudyName+"_MEDMESH_"+ myMesh->getName() + ".med").c_str());
748     return strdup(aName._retn()) ;
749   }
750     
751   // SUPPORT
752   SALOME_MED::SUPPORT_var mySupport = SALOME_MED::SUPPORT::_narrow(myIOR);
753   if (! CORBA::is_nil(mySupport)) 
754   {
755         // nothing to save : Support will be saved inside the mesh
756         string str_SupportName;
757         try
758         {
759                 str_SupportName=string("/FAS/")+string(mySupport->getName());
760                 str_SupportName+=string("/ENS_MAA/")+string(mySupport->getMesh()->getName());
761                 SCRUTE(str_SupportName);
762         }
763         catch(...)
764         {
765                 MESSAGE("Unable to save the support");
766                 THROW_SALOME_CORBA_EXCEPTION("Unable to save Field in Med"\
767                                               ,SALOME::INTERNAL_ERROR);
768         }
769     return strdup((aSaveStudyName+"_MED"+str_SupportName).c_str());
770   }
771     
772   SALOME_MED::FIELD_var myField = SALOME_MED::FIELD::_narrow(myIOR);
773   if (! CORBA::is_nil(myField)) 
774   {
775     string str_FieldName;
776     ostringstream a,b;
777     a<< myField->getOrderNumber();
778     b<< myField->getIterationNumber();
779     CORBA::String_var aName((aSaveStudyName+"_MEDFIELD_"+ myField->getName() +
780                              string("_ORDRE_")+a.str()+
781                              string("_ITER_")+b.str() +
782                              ".med").c_str());
783     return strdup(aName._retn());
784   }
785
786   //THROW_SALOME_CORBA_EXCEPTION("Unable to save IOR",SALOME::BAD_PARAM);
787   return strdup((aSaveStudyName+"_MED").c_str());
788
789   END_OF(LOC) ;
790 }
791
792 //=============================================================================
793 /*!
794  *  CORBA: give a transient reference (when loading an object, opening study)
795  */
796 //=============================================================================
797
798 char* Med_Gen_i::LocalPersistentIDToIOR(SALOMEDS::SObject_ptr theSObject,
799                                         const char* aLocalPersistentID,
800                                         CORBA::Boolean isMultiFile,
801                                         CORBA::Boolean isASCII)
802      throw(SALOME::SALOME_Exception)
803 {
804   const char * LOC = "Med_Gen_i::LocalPersistentIDToIOR" ;
805   BEGIN_OF(LOC) ;
806   TCollection_AsciiString aTmpDir(CORBA::string_dup(_saveFileName.c_str()));
807
808   string aSaveStudyName(strdup(SALOMEDS_Tool::GetNameFromPath(theSObject->GetStudy()->URL())));
809   int aStudyNameLen = strlen(aSaveStudyName.c_str());
810
811   if (strlen(aLocalPersistentID) <= aStudyNameLen) return strdup("");
812   if (strcmp(aLocalPersistentID, "Objet Med + /OBJ_MED/") == 0) return strdup(""); // MED
813
814   if (strncmp(&(aLocalPersistentID[aStudyNameLen]), "_MEDMESH_",9) == 0) {// MESH
815     MESH * myMesh= new MESH() ;
816     int aMeshNameLen = strlen(aLocalPersistentID) - 12 - aStudyNameLen;
817     char* aMeshName = new char[aMeshNameLen];
818     strncpy(aMeshName, &(aLocalPersistentID[aStudyNameLen + 9]), aMeshNameLen-1);
819     aMeshName[aMeshNameLen-1] = 0;
820     myMesh->setName(aMeshName);
821
822     char* aFileName;
823     if (isASCII) {
824       char* aResultPath = HDFascii::ConvertFromASCIIToHDF((aTmpDir + strdup(aLocalPersistentID)).ToCString());
825       aFileName = new char[strlen(aResultPath) + 19];
826       sprintf(aFileName, "%shdf_from_ascii.hdf", aResultPath);
827       delete(aResultPath);
828     } else aFileName = strdup((aTmpDir + strdup(aLocalPersistentID)).ToCString());
829     MED_MESH_RDONLY_DRIVER myMeshDriver(aFileName,myMesh);
830     try
831       {
832         myMeshDriver.setMeshName(aMeshName);
833         myMeshDriver.open();
834       }
835     catch (const exception & ex)
836       {
837         MESSAGE("Exception Interceptee : ");
838         SCRUTE(ex.what());
839         THROW_SALOME_CORBA_EXCEPTION("Unable to find this mesh in this file",SALOME::BAD_PARAM);
840       };
841     try
842       {
843         myMeshDriver.read();
844         MESSAGE("apres read");
845         myMeshDriver.close();
846       }
847     catch (const exception & ex)
848       {
849         MESSAGE("Exception Interceptee : ");
850         SCRUTE(ex.what());
851         THROW_SALOME_CORBA_EXCEPTION("Unable to read this mesh in this file",SALOME::BAD_PARAM);
852       }
853     MESH_i * meshi = new MESH_i(myMesh);
854     //SALOME_MED::MESH_var mesh = SALOME_MED::MESH::_narrow(meshi->_this());
855     SALOME_MED::MESH_ptr mesh = meshi->_this();
856     SALOMEDS::ListOfFileNames_var aSeq = new SALOMEDS::ListOfFileNames;
857     aSeq->length(1);
858     aSeq[0]=CORBA::string_dup(aLocalPersistentID);
859     if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.ToCString(), aSeq.in(), true);
860     if (isASCII) {
861       SALOMEDS::ListOfFileNames_var aFilesToRemove = new SALOMEDS::ListOfFileNames;
862       aFilesToRemove->length(1);
863       aFilesToRemove[0] = strdup(&(aFileName[strlen(SALOMEDS_Tool::GetDirFromPath(aFileName))]));
864       SALOMEDS_Tool::RemoveTemporaryFiles(SALOMEDS_Tool::GetDirFromPath(aFileName), aFilesToRemove, true);
865     }
866     delete(aFileName);
867     return(CORBA::string_dup(_orb->object_to_string(mesh)));
868   } else if (strncmp(&(aLocalPersistentID[aStudyNameLen]), "_MEDFIELD_",14) == 0) { // FIELD
869     return(strdup("")); // not implemented yet
870   }
871
872   return strdup("");
873
874   END_OF(LOC) ;
875 }
876
877 //=============================================================================
878 /*!
879  *  returns true, if can publish object
880  */
881 //=============================================================================
882 bool Med_Gen_i::CanPublishInStudy(CORBA::Object_ptr theIOR) {
883   SALOME_MED::MESH_var aMesh = SALOME_MED::MESH::_narrow(theIOR);
884   return !(aMesh->_is_nil());
885 }
886
887 //=============================================================================
888 /*!
889  *  publish the given object
890  */
891 //=============================================================================
892 SALOMEDS::SObject_ptr Med_Gen_i::PublishInStudy(SALOMEDS::Study_ptr theStudy,
893                                                 SALOMEDS::SObject_ptr theSObject,
894                                                 CORBA::Object_ptr theObject,
895                                                 const char* theName) throw (SALOME::SALOME_Exception)
896 {
897   SALOMEDS::SObject_var aResultSO;
898
899   if(CORBA::is_nil(theObject)) return aResultSO;
900   if(theStudy->_is_nil()) return aResultSO;
901
902   SALOMEDS::StudyBuilder_var aBuilder = theStudy->NewBuilder();
903   SALOMEDS::GenericAttribute_var anAttr;
904   SALOMEDS::AttributeName_var    aName;
905   SALOMEDS::AttributeIOR_var     anIOR;
906   SALOMEDS::SComponent_var aFather = theStudy->FindComponent("Med");
907
908   if (aFather->_is_nil()) {
909     aFather = aBuilder->NewComponent("Med");
910     if (aFather->_is_nil()) return aResultSO;
911     anAttr = aBuilder->FindOrCreateAttribute(aFather, "AttributeName");
912     aName = SALOMEDS::AttributeName::_narrow(anAttr);
913     aName->SetValue("MED");
914     aBuilder->DefineComponentInstance(aFather, Med_Gen::_this());
915   }
916
917   if (CORBA::is_nil(theSObject)) {
918     SALOME_MED::MESH_var aMesh = SALOME_MED::MESH::_narrow(theObject);
919     aMesh->addInStudy(theStudy, aMesh);
920     SALOMEDS::SObject_var aResultSO = theStudy->FindObjectIOR(_orb->object_to_string(theObject));
921   } else {
922     if (!theSObject->ReferencedObject(aResultSO)) 
923       THROW_SALOME_CORBA_EXCEPTION("Publish in study MED object error",SALOME::BAD_PARAM);
924   }
925 //    aBuilder->Addreference(theObject, aResultSO);
926   return aResultSO._retn();
927 }
928
929 //=============================================================================
930 /*!
931  *  returns true, if can copy the object
932  */
933 //=============================================================================
934 CORBA::Boolean Med_Gen_i::CanCopy(SALOMEDS::SObject_ptr theObject) {
935   // Try to retrieve known by MED component mesh by given IOR
936   SALOMEDS::GenericAttribute_var anAttr;
937   if (!theObject->FindAttribute(anAttr, "AttributeIOR")) return false;
938   CORBA::Object_var anObj = _orb->string_to_object(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value());
939   SALOME_MED::MESH_var aMesh = SALOME_MED::MESH::_narrow(anObj);
940   // If the object is null one it can't be copied: return false
941   if (aMesh->_is_nil()) return false;
942   return true;
943 }
944
945 //=============================================================================
946 /*!
947  *  create copy of the object and put it to the stream
948  */
949 //=============================================================================
950 SALOMEDS::TMPFile* Med_Gen_i::CopyFrom(SALOMEDS::SObject_ptr theObject, CORBA::Long& theObjectID) {
951     // Declare a sequence of the byte to store the copied object
952   SALOMEDS::TMPFile_var aStreamFile;
953
954   // Try to get GEOM_Shape object by given SObject
955   SALOMEDS::GenericAttribute_var anAttr;
956   if (!theObject->FindAttribute(anAttr, "AttributeIOR")) return new SALOMEDS::TMPFile(0);
957   CORBA::String_var anIOR = strdup(SALOMEDS::AttributeIOR::_narrow(anAttr)->Value());
958   CORBA::Object_var anObj = _orb->string_to_object(anIOR);
959   SALOME_MED::MESH_var aMesh = SALOME_MED::MESH::_narrow(anObj);
960   if (aMesh->_is_nil()) return new SALOMEDS::TMPFile(0);
961
962   // Get a temporary directory to store a temporary file
963   CORBA::String_var aTmpDir = SALOMEDS_Tool::GetTmpDir();
964   // Create a list to store names of created files
965   SALOMEDS::ListOfFileNames_var aSeq = new SALOMEDS::ListOfFileNames;
966   aSeq->length(1);
967   aSeq[0] = strdup(aMesh->getName());
968   char* aFullName = new char[strlen(aTmpDir)+strlen(aSeq[0])+1];
969   strcpy(aFullName, aTmpDir);
970   strcpy(aFullName+strlen(aTmpDir), aSeq[0]);
971   long driverId = aMesh->addDriver(SALOME_MED::MED_DRIVER,strdup(aFullName) , aMesh->getName());
972   aMesh->write(driverId,"");
973   delete(aFullName);
974   
975   aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir, aSeq.in(), false);
976   SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir, aSeq.in(), true);
977   
978   // Assign an ID = 1 the the type SALOME_MED::MESH
979   theObjectID = 1;
980  
981   return aStreamFile._retn();
982 }
983
984 //=============================================================================
985 /*!
986  *  returns true, if can copy the object
987  */
988 //=============================================================================
989 CORBA::Boolean Med_Gen_i::CanPaste(const char* theComponentName, CORBA::Long theObjectID) {
990   // The MED component can paste only objects copied by MED component
991   // and with the object type = 1 (mesh)
992   if (strcmp(theComponentName, ComponentDataType()) != 0 || theObjectID != 1) return false;
993   return true;
994 }
995
996 //=============================================================================
997 /*!
998  *  returns true, if can copy the object
999  */
1000 //=============================================================================
1001 SALOMEDS::SObject_ptr Med_Gen_i::PasteInto(const SALOMEDS::TMPFile& theStream,
1002                                            CORBA::Long theObjectID,
1003                                            SALOMEDS::SObject_ptr theObject) {
1004   SALOMEDS::SObject_var aResultSO = SALOMEDS::SObject::_duplicate(theObject);
1005   if (theStream.length() == 0) return aResultSO._retn();
1006   
1007   SALOMEDS::Study_var aStudy = theObject->GetStudy();
1008
1009   CORBA::String_var aTmpDir = strdup(SALOMEDS_Tool::GetTmpDir());
1010   SALOMEDS::ListOfFileNames_var aSeq = SALOMEDS_Tool::PutStreamToFiles(theStream, aTmpDir, false);
1011   CORBA::String_var aMeshName = strdup(aSeq[0]);
1012   char* aFullName = new char[strlen(aTmpDir)+strlen(aMeshName)+1];
1013   strcpy(aFullName, aTmpDir);
1014   strcpy(aFullName+strlen(aTmpDir), aMeshName);
1015
1016   MESH * myMesh= new MESH() ;
1017   myMesh->setName((char*)aMeshName);
1018   MED_MESH_RDONLY_DRIVER myMeshDriver(aFullName, myMesh);
1019   try {
1020     myMeshDriver.setMeshName((char*)aMeshName);
1021     myMeshDriver.open();
1022   } catch (const exception & ex) {
1023     MESSAGE("Exception Interceptee : ");
1024     SCRUTE(ex.what());
1025     delete(aFullName);
1026     return aResultSO._retn();
1027   };
1028   try {
1029     myMeshDriver.read();
1030     ("apres read");
1031     myMeshDriver.close();
1032   } catch (const exception & ex) {
1033     MESSAGE("Exception Interceptee : ");
1034     SCRUTE(ex.what());
1035     delete(aFullName);
1036     return aResultSO._retn();
1037   };
1038   // set new mesh name, becouse now there are no possibility to operate meshes with the same names
1039 //    srand((unsigned int)time(NULL));
1040   int aRND = rand(); //Get a random number to present a name of a copied mesh
1041   char aCopiedMeshName[20];
1042   sprintf(aCopiedMeshName,"MESH_COPY_%d",aRND);
1043   myMesh->setName(aCopiedMeshName);
1044   MESH_i * meshi = new MESH_i(myMesh);
1045   SALOME_MED::MESH_ptr mesh = meshi->_this();
1046   // add the mesh object in study
1047   meshi->addInStudy(aStudy,mesh);
1048   // get the IOR attribute of just added mesh
1049   CORBA::String_var anIORString = _orb->object_to_string(mesh);
1050   aResultSO = aStudy->FindObjectIOR(anIORString);
1051
1052   SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir, aSeq.in(), true);
1053   delete(aFullName);
1054   return aResultSO._retn();
1055 }
1056
1057
1058
1059
1060
1061
1062 //=============================================================================
1063 /*! 
1064  * C factory, accessible with dlsym, after dlopen  
1065  */
1066 //=============================================================================
1067
1068 extern "C"
1069 {
1070   PortableServer::ObjectId * MedEngine_factory(
1071                                CORBA::ORB_ptr orb,
1072                                PortableServer::POA_ptr poa, 
1073                                PortableServer::ObjectId * contId,
1074                                const char *instanceName, 
1075                                const char *interfaceName)
1076   {
1077     MESSAGE("PortableServer::ObjectId * MedEngine_factory()");
1078     SCRUTE(interfaceName);
1079     Med_Gen_i * myMed_Gen 
1080       = new Med_Gen_i(orb, poa, contId, instanceName, interfaceName);
1081     return myMed_Gen->getId() ;
1082   }
1083 }