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