Salome HOME
Join modifications from branch OCC_development_for_3_2_0a2
[modules/visu.git] / src / VISU_I / VISU_Gen_i.cc
1 //  VISU OBJECT : interactive object for VISU entities implementation
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 //  File   : VISU_Gen_i.cc
24 //  Author : Alexey PETROV
25 //  Module : VISU
26
27 #include "VISU_Gen_i.hh"
28 #include "VISU_Result_i.hh"
29 #include "VISU_PrsObject_i.hh"
30 #include "VISU_ViewManager_i.hh"
31
32 #include "VISU_Prs3d_i.hh"
33 #include "VISU_Mesh_i.hh"
34 #include "VISU_ScalarMap_i.hh"
35 #include "VISU_IsoSurfaces_i.hh"
36 #include "VISU_DeformedShape_i.hh"
37 #include "VISU_CutPlanes_i.hh"
38 #include "VISU_CutLines_i.hh"
39 #include "VISU_Vectors_i.hh"
40 #include "VISU_StreamLines_i.hh"
41 #include "VISU_GaussPoints_i.hh"
42 #include "VISU_Plot3D_i.hh"
43 #include "VISU_Table_i.hh"
44 #include "VISU_TimeAnimation.h"
45 #include "VISU_ScalarMapOnDeformedShape_i.hh"
46
47 #include "VISU_Actor.h"
48
49 #include "HDFascii.hxx"
50 #include "SALOMEDS_Tool.hxx"
51
52 #include "SALOMEDSClient_AttributeName.hxx"
53 #include "SALOMEDSClient_AttributePixMap.hxx"
54
55 #include "SUIT_Session.h"
56 #include "SalomeApp_Study.h"
57 #include "SalomeApp_Application.h"
58 #include "LightApp_SelectionMgr.h"
59 #include "SVTK_ViewModel.h"
60 #include "SVTK_ViewWindow.h"
61 #include "SALOME_Event.hxx"
62 #include "SALOME_ListIO.hxx"
63 #include "SALOME_ListIteratorOfListIO.hxx"
64
65 #include "utilities.h"
66
67 // IDL Headers
68 #include <omnithread.h>
69 #include CORBA_SERVER_HEADER(SALOME_Session)
70 #include CORBA_SERVER_HEADER(SALOME_ModuleCatalog)
71
72 // QT Includes
73 #include <qstring.h>
74 #include <qfileinfo.h>
75
76 // VTK Includes
77 #include <vtkRenderer.h>
78 #include <vtkActorCollection.h>
79
80 // OCCT Includes
81 #include <TCollection_AsciiString.hxx>
82 #include <TColStd_SequenceOfAsciiString.hxx>
83
84 // STL Includes
85 #include <strstream>
86
87 #include "Utils_ExceptHandlers.hxx"
88 #include "CASCatch.hxx"
89
90 using namespace std;
91
92 static QFileInfo aFileInfo;
93
94 #ifdef _DEBUG_
95 static int MYDEBUG = 0;
96 //#define _DEXCEPT_
97 #else
98 static int MYDEBUG = 0;
99 #endif
100
101 UNEXPECT_CATCH(SalomeException, SALOME::SALOME_Exception);
102
103 extern "C" VISU::VISU_Gen_ptr GetImpl(CORBA::ORB_ptr theORB,
104                                       PortableServer::POA_ptr thePOA,
105                                       SALOME_NamingService* theNamingService,
106                                       QMutex* theMutex)
107 {
108   if(MYDEBUG) MESSAGE("extern \"C\" GetImpl");
109   VISU::VISU_Gen_i *aVISU_Gen = new VISU::VISU_Gen_i(theORB,thePOA,theNamingService,theMutex);
110   //return VISU::VISU_Gen::_duplicate(aVISU_Gen->_this());
111   return aVISU_Gen->_this();
112 }
113
114 namespace VISU
115 {
116   static string VisuTmpDir;
117
118   static CORBA::Boolean myIsMultiFile;
119   const CORBA::Boolean IsMultifile() { return myIsMultiFile;}
120
121   //===========================================================================
122   _PTR(SComponent) ClientFindOrCreateVisuComponent (_PTR(Study) theStudyDocument)
123   {
124     _PTR(SComponent) aSComponent = theStudyDocument->FindComponent("VISU");
125     if (!aSComponent) {
126       _PTR(StudyBuilder) aStudyBuilder = theStudyDocument->NewBuilder();
127       aStudyBuilder->NewCommand();
128       int aLocked = theStudyDocument->GetProperties()->IsLocked();
129       if (aLocked) theStudyDocument->GetProperties()->SetLocked(false);
130       aSComponent = aStudyBuilder->NewComponent("VISU");
131       _PTR(GenericAttribute) anAttr =
132         aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributeName");
133       _PTR(AttributeName) aName (anAttr);
134
135       CORBA::ORB_var anORB = Base_i::GetORB();
136       SALOME_NamingService *NamingService = new SALOME_NamingService( anORB );
137       CORBA::Object_var objVarN = NamingService->Resolve("/Kernel/ModulCatalog");
138       SALOME_ModuleCatalog::ModuleCatalog_var Catalogue =
139         SALOME_ModuleCatalog::ModuleCatalog::_narrow(objVarN);
140       SALOME_ModuleCatalog::Acomponent_var Comp = Catalogue->GetComponent( "VISU" );
141       if (!Comp->_is_nil()) {
142         aName->SetValue(Comp->componentusername());
143       }
144
145       anAttr = aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributePixMap");
146       _PTR(AttributePixMap) aPixmap (anAttr);
147       aPixmap->SetPixMap( "ICON_OBJBROWSER_Visu" );
148
149       VISU_Gen_var aVisuGen = Base_i::GetVisuGenImpl()->_this();
150       aStudyBuilder->DefineComponentInstance(aSComponent, aVisuGen->GetID());
151       if (aLocked) theStudyDocument->GetProperties()->SetLocked(true);
152       aStudyBuilder->CommitCommand();
153     }
154     return aSComponent;
155   }
156
157   SALOMEDS::SComponent_var FindOrCreateVisuComponent(SALOMEDS::Study_ptr theStudyDocument){
158     SALOMEDS::SComponent_var aSComponent = theStudyDocument->FindComponent("VISU");
159     if (aSComponent->_is_nil()) {
160       SALOMEDS::StudyBuilder_var aStudyBuilder = theStudyDocument->NewBuilder();
161       aStudyBuilder->NewCommand();
162       int aLocked = theStudyDocument->GetProperties()->IsLocked();
163       if (aLocked) theStudyDocument->GetProperties()->SetLocked(false);
164       aSComponent = aStudyBuilder->NewComponent("VISU");
165       SALOMEDS::GenericAttribute_var anAttr = aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributeName");
166       SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(anAttr);
167
168       //NRI      aName->SetValue("Visu");
169       CORBA::ORB_var anORB = Base_i::GetORB();
170       SALOME_NamingService *NamingService = new SALOME_NamingService( anORB );
171       CORBA::Object_var objVarN = NamingService->Resolve("/Kernel/ModulCatalog");
172       SALOME_ModuleCatalog::ModuleCatalog_var Catalogue  = SALOME_ModuleCatalog::ModuleCatalog::_narrow(objVarN);
173       SALOME_ModuleCatalog::Acomponent_var Comp = Catalogue->GetComponent( "VISU" );
174       if ( !Comp->_is_nil() ) {
175         aName->SetValue( Comp->componentusername() );
176       }
177
178       anAttr = aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributePixMap");
179       SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr);
180       aPixmap->SetPixMap( "ICON_OBJBROWSER_Visu" );
181
182       VISU_Gen_var aVisuGen = Base_i::GetVisuGenImpl()->_this();
183       aStudyBuilder->DefineComponentInstance(aSComponent,aVisuGen);
184       if (aLocked) theStudyDocument->GetProperties()->SetLocked(true);
185       aStudyBuilder->CommitCommand();
186     }
187     return aSComponent;
188   }
189
190   void RegistryStorable() {
191     Storable::Registry(Result_i::myComment.c_str(),&(Result_i::Restore));
192     Storable::Registry(Mesh_i::myComment.c_str(),&(Restore<Mesh_i>));
193     Storable::Registry(ScalarMap_i::myComment.c_str(),&(Restore<ScalarMap_i>));
194     Storable::Registry(GaussPoints_i::myComment.c_str(),&(Restore<GaussPoints_i>));
195     Storable::Registry(DeformedShape_i::myComment.c_str(),&(Restore<DeformedShape_i>));
196     Storable::Registry(CutPlanes_i::myComment.c_str(),&(Restore<CutPlanes_i>));
197     Storable::Registry(CutLines_i::myComment.c_str(),&(Restore<CutLines_i>));
198     Storable::Registry(IsoSurfaces_i::myComment.c_str(),&(Restore<IsoSurfaces_i>));
199     Storable::Registry(StreamLines_i::myComment.c_str(),&(Restore<StreamLines_i>));
200     Storable::Registry(Plot3D_i::myComment.c_str(),&(Restore<Plot3D_i>));
201     Storable::Registry(Vectors_i::myComment.c_str(),&(Restore<Vectors_i>));
202     Storable::Registry(Table_i::myComment.c_str(),&(Table_i::Restore));
203     Storable::Registry(Curve_i::myComment.c_str(),&(Curve_i::Restore));
204     Storable::Registry(Container_i::myComment.c_str(),&(Container_i::Restore));
205     Storable::Registry(ScalarMapOnDeformedShape_i::myComment.c_str(),&(Restore<ScalarMapOnDeformedShape_i>));
206   }
207
208
209   //===========================================================================
210   VISU_Gen_i::VISU_Gen_i(CORBA::ORB_ptr theORB, PortableServer::POA_ptr thePOA,
211                          SALOME_NamingService* theNamingService, QMutex* theMutex) :
212     Engines_Component_i()
213   {
214     if(MYDEBUG) MESSAGE("VISU_Gen_i::VISU_Gen_i : "<<theMutex);
215     Base_i::myMutex = theMutex;  //apo
216     Base_i::myOrb = CORBA::ORB::_duplicate(theORB);
217     Base_i::myPoa = PortableServer::POA::_duplicate(thePOA);
218     Base_i::myNamingService = theNamingService;
219     static SALOME_LifeCycleCORBA aEnginesLifeCycle(theNamingService);
220     Base_i::myEnginesLifeCycle = &aEnginesLifeCycle;
221     Base_i::myVisuGenImpl = this;
222     RegistryStorable();
223
224     CORBA::Object_var anObj = myNamingService->Resolve("/myStudyManager");
225     SALOMEDS::StudyManager_var aStudyManager = SALOMEDS::StudyManager::_narrow(anObj);
226     SALOMEDS::ListOfOpenStudies_var aListOfOpenStudies = aStudyManager->GetOpenStudies();
227     if(aListOfOpenStudies->length() > 0) {
228       CORBA::String_var aStudyName = aListOfOpenStudies[0];
229       //aFileInfo.setFile(aStudyName.in());
230       myStudyDocument = aStudyManager->GetStudyByName(aStudyName/*aFileInfo.baseName()*/);
231     }else
232       if(MYDEBUG) MESSAGE("VISU_Gen_i::VISU_Gen_i : there is no opened study in StudyManager !!!");
233   }
234
235   bool
236   CreatColoredPrs3d(ColoredPrs3d_i* theColoredPrs3d,
237                     const char* theMeshName, 
238                     VISU::Entity theEntity,
239                     const char* theFieldName, 
240                     CORBA::Double theIteration)
241   {
242     CASCatch_TRY{       
243 #ifndef _DEXCEPT_
244       try{
245 #endif
246         if(theColoredPrs3d->Create(theMeshName,theEntity,theFieldName,int(theIteration)))
247           return true;
248 #ifndef _DEXCEPT_
249       }catch(std::exception& exc){
250         INFOS("Follow exception was occured :\n"<<exc.what());
251       }catch(...){
252         INFOS("Unknown exception was occured!");
253       }
254 #endif
255     }CASCatch_CATCH(Standard_Failure) {
256       Handle(Standard_Failure) aFail = Standard_Failure::Caught();
257       INFOS("Follow signal was occured :\n"<<aFail->GetMessageString());
258     }
259     return false;
260   }
261
262   VISU_Gen_i::~VISU_Gen_i(){
263     if(MYDEBUG) MESSAGE("VISU_Gen_i::~VISU_Gen_i");
264   }
265   //===========================================================================
266   CORBA::Boolean VISU_Gen_i::Load(SALOMEDS::SComponent_ptr theComponent,
267                                   const SALOMEDS::TMPFile & theStream,
268                                   const char* theURL,
269                                   bool isMultiFile)
270   {
271     Mutex mt(myMutex);
272     SALOMEDS::Study_var aStudy = theComponent->GetStudy();
273     SALOMEDS::StudyBuilder_var  aStudyBuilder = aStudy->NewBuilder();
274     string aDir = isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir();
275     TCollection_AsciiString aTmpDir (const_cast<char*>(aDir.c_str()));
276     VisuTmpDir = aTmpDir.ToCString();
277     SALOMEDS::ListOfFileNames_var aSeq =
278       SALOMEDS_Tool::PutStreamToFiles(theStream, aTmpDir.ToCString(),isMultiFile);
279     myIsMultiFile = isMultiFile;
280     return true;
281   }
282
283   CORBA::Boolean VISU_Gen_i::LoadASCII(SALOMEDS::SComponent_ptr theComponent,
284                                        const SALOMEDS::TMPFile & theStream,
285                                        const char* theURL,
286                                        bool isMultiFile)
287   {
288     return Load(theComponent, theStream, theURL, isMultiFile);
289   }
290
291   char* VISU_Gen_i::LocalPersistentIDToIOR(SALOMEDS::SObject_ptr theSObject,
292                                            const char* aLocalPersistentID,
293                                            CORBA::Boolean isMultiFile,
294                                            CORBA::Boolean isASCII)
295   {
296     CORBA::String_var aString("");
297     if(strcmp(aLocalPersistentID,"") != 0) {
298       Mutex mt(myMutex);
299       Storable* aStorable =
300         Storable::Create(theSObject,VisuTmpDir.c_str(),aLocalPersistentID);
301       if(aStorable != NULL) aString = aStorable->GetID();
302     }
303     return aString._retn();
304   }
305   //===========================================================================
306   SALOMEDS::TMPFile* VISU_Gen_i::Save(SALOMEDS::SComponent_ptr theComponent,
307                                       const char* theURL,
308                                       bool theIsMultiFile)
309   {
310     Mutex mt(myMutex);
311     string aTmpDir = theURL;
312     if(MYDEBUG) MESSAGE("VISU_Gen_i::Save - "<<aTmpDir);
313     
314     typedef std::vector<std::string> TFileNames;
315     TFileNames aFileNames;
316     TFileNames aFiles;
317
318     SALOMEDS::Study_var aStudy = theComponent->GetStudy();
319     SALOMEDS::ChildIterator_var anIter = aStudy->NewChildIterator(theComponent);
320     for (; anIter->More(); anIter->Next()) {
321       SALOMEDS::SObject_var gotBranch = anIter->Value();
322       CORBA::Object_var anObj = SObjectToObject(gotBranch);
323       if(CORBA::is_nil(anObj)) continue;
324       if(Result_i* aResult = dynamic_cast<Result_i*>(GetServant(anObj).in())){
325         switch(aResult->GetCreationId()){
326         case Result_i::eImportFile:
327         case Result_i::eCopyAndImportFile: {
328           const QFileInfo& aFileInfo = aResult->GetFileInfo();
329           const std::string& aName = aResult->GetName();
330           std::string aFileName = std::string("_") + aName;
331           std::string aFile = aFileInfo.filePath().latin1();
332           if(theIsMultiFile){
333             aFileName = SALOMEDS_Tool::GetNameFromPath(aStudy->URL()) + aFileName;
334
335             std::ostringstream aStream;
336             aStream<<"cp "<<aFile<<" "<<aTmpDir<<aFileName;
337             std::string aCommand = aStream.str();
338             if(system(aCommand.c_str()) != 0){
339               INFOS("VISU_Gen_i::Save - Cann't execute the command :"<<aCommand);
340               continue;
341             }
342           }
343           aFileNames.push_back(aFileName);
344           aFiles.push_back(aFile);
345         }}
346       }
347     }
348
349     if(MYDEBUG) MESSAGE("VISU_Gen_i::Save - aFileNames.size() - "<<aFileNames.size());
350
351     SALOMEDS::ListOfFileNames_var aListOfFileNames = new SALOMEDS::ListOfFileNames;
352     if(!aFileNames.empty()){
353       aListOfFileNames->length(aFileNames.size());
354       for(int aCounter = aFileNames.size(); aCounter > 0; aCounter--)
355         aListOfFileNames[aCounter-1] = aFileNames[aCounter-1].c_str();
356     }
357
358     SALOMEDS::ListOfFileNames_var aListOfFiles = new SALOMEDS::ListOfFileNames;
359     aListOfFiles->length(aFiles.size());
360     if(!aFiles.empty()){
361       for(int aCounter = aFileNames.size(); aCounter > 0; aCounter--)
362         aListOfFiles[aCounter-1] = aFiles[aCounter-1].c_str();
363     }
364
365     SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile(0);
366     if(theIsMultiFile)
367       aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir, aListOfFiles.in(), theIsMultiFile);
368     else
369       aStreamFile = SALOMEDS_Tool::PutFilesToStream(aListOfFiles.in(), aListOfFileNames.in());
370
371     return aStreamFile._retn();
372   }
373
374   SALOMEDS::TMPFile* VISU_Gen_i::SaveASCII(SALOMEDS::SComponent_ptr theComponent,
375                                            const char* theURL,
376                                            bool isMultiFile)
377   {
378     Mutex mt(myMutex);
379     string aDir = isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir();
380     TCollection_AsciiString aTmpDir (const_cast<char*>(aDir.c_str()));
381     if(MYDEBUG) MESSAGE("VISU_Gen_i::Save - "<<aTmpDir);
382     int aCounter = 0;
383     TColStd_SequenceOfAsciiString aFileNames;
384     SALOMEDS::Study_var aStudy = theComponent->GetStudy();
385     SALOMEDS::ChildIterator_var itBig = aStudy->NewChildIterator(theComponent);
386     for (; itBig->More(); itBig->Next()) {
387       SALOMEDS::SObject_var gotBranch = itBig->Value();
388       CORBA::Object_var anObj = SObjectToObject(gotBranch);
389       if(CORBA::is_nil(anObj)) continue;
390       if(Result_i* pResult = dynamic_cast<Result_i*>(GetServant(anObj).in())){
391         switch(pResult->GetCreationId()){
392         case Result_i::eImportFile:
393         case Result_i::eCopyAndImportFile: {
394           const QFileInfo& aFileInfo = pResult->GetFileInfo();
395           QString aPrefix("");
396           if (isMultiFile) aPrefix = SALOMEDS_Tool::GetNameFromPath(aStudy->URL()).c_str();
397           QString aFileName = aPrefix + "_" + (pResult->GetName()).c_str();
398           static QString aCommand;
399           aCommand.sprintf("cp %s %s%s",aFileInfo.filePath().latin1(),aTmpDir.ToCString(),aFileName.latin1());
400
401           int aRes = system(aCommand);
402           if(aRes){
403             if(MYDEBUG) MESSAGE("VISU_Gen_i::Save - Can't execute the command :"<<aCommand);
404             continue;
405           }else
406             if(MYDEBUG) MESSAGE("VISU_Gen_i::Save - "<<aCommand);
407
408           TCollection_AsciiString aString(strdup(aFileName.latin1()));
409
410           HDFascii::ConvertFromHDFToASCII(strdup((aTmpDir + aString).ToCString()), true);
411
412           aFileNames.Append(aString);
413         }}
414       }
415     }
416     SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile(0);
417     if(MYDEBUG) MESSAGE("VISU_Gen_i::Save - aFileNames.Length() - "<<aFileNames.Length());
418     if(aFileNames.Length() > 0){
419       SALOMEDS::ListOfFileNames_var aSeq = new SALOMEDS::ListOfFileNames;
420       aSeq->length(aFileNames.Length());
421       for(aCounter = aFileNames.Length(); aCounter > 0; aCounter--)
422         aSeq[aCounter-1] = CORBA::string_dup(aFileNames.Value(aCounter).ToCString());
423       aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir.ToCString(), aSeq.in(), isMultiFile);
424       if(!isMultiFile)
425         SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.ToCString(), aSeq.in(), true);
426     }
427     return aStreamFile._retn();
428   }
429
430   char* VISU_Gen_i::IORToLocalPersistentID(SALOMEDS::SObject_ptr theSObject,
431                                            const char* IORString,
432                                            CORBA::Boolean isMultiFile,
433                                            CORBA::Boolean isASCII)
434   {
435     CORBA::String_var aString(IORString);
436     if(strcmp(IORString,"") != 0){
437       CORBA::ORB_ptr anORB = GetORB();
438       CORBA::Object_var anObj = anORB->string_to_object(aString);
439       if(!CORBA::is_nil(anObj)){
440         if(Storable* pStorable = dynamic_cast<Storable*>(GetServant(anObj).in())){
441           Mutex mt(myMutex);
442           aString = pStorable->ToString().c_str();
443           return aString._retn();
444         }
445       }
446     }
447     return aString._retn();
448   }
449
450   char* VISU_Gen_i::GetID(){
451     return Base_i::GetID();
452   }
453
454   void VISU_Gen_i::SetCurrentStudy (SALOMEDS::Study_ptr theStudy)
455   {
456     class TEvent: public SALOME_Event {
457       std::string myStudyName;
458     public:
459       TEvent(const std::string theStudyName):myStudyName(theStudyName)
460         {}
461       virtual void Execute()
462         {
463           bool isActive = false;
464           SUIT_Session* aSession = SUIT_Session::session();
465           QPtrList<SUIT_Application> anApplications = aSession->applications();
466           QPtrListIterator<SUIT_Application> anIter (anApplications);
467           SUIT_Application* aFirstApp = anIter.current();
468           while (SUIT_Application* anApp = anIter.current()) {
469             ++anIter;
470             if (SUIT_Study* aSStudy = anApp->activeStudy()) {
471               if (SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>(aSStudy)) {
472                 if (_PTR(Study) aCStudy = aStudy->studyDS()) {
473                   if(MYDEBUG) MESSAGE("There is an application with active study : StudyId = "
474                                       << aCStudy->StudyId() << "; Name = '" << aCStudy->Name() << "'");
475                   if (myStudyName == aCStudy->Name()) {
476                     isActive = true;
477                     break;
478                   }
479                 }
480               }
481             }
482           }
483           if (!isActive) {
484             MESSAGE("!!! anApp->onLoadDoc(myStudyName) !!!");
485             // Has to be loaded in an empty or in a new application
486             SalomeApp_Application* anApp = dynamic_cast<SalomeApp_Application*>(aFirstApp);
487             anApp->onLoadDoc(myStudyName.c_str());
488           }
489         }
490     };
491
492     if (!CORBA::is_nil(theStudy))
493     {
494       CORBA::String_var aName = theStudy->Name();
495       std::string aStudyName (aName.in());
496       if(MYDEBUG) MESSAGE("StudyId = " << theStudy->StudyId() << "; Name = '" << aName.in() << "'");
497       myStudyDocument = SALOMEDS::Study::_duplicate(theStudy);
498
499       ProcessVoidEvent(new TEvent(aStudyName));
500     } else {
501       INFOS("CORBA::is_nil(theStudy)");
502     }
503   }
504
505   SALOMEDS::Study_ptr VISU_Gen_i::GetCurrentStudy(){
506     return SALOMEDS::Study::_duplicate(myStudyDocument);
507   }
508
509   ViewManager_ptr VISU_Gen_i::GetViewManager(){
510     Mutex mt(myMutex);
511     ViewManager_i * aViewManager = new ViewManager_i(myStudyDocument);
512     return ViewManager::_duplicate(aViewManager->_this());
513   }
514
515   SALOMEDS::SObject_ptr VISU_Gen_i::ImportTables(const char* theFileName){
516     if(myStudyDocument->GetProperties()->IsLocked())
517       return SALOMEDS::SObject::_nil();
518     Mutex mt(myMutex);
519     SALOMEDS::SObject_var aRes = VISU::ImportTables(theFileName,myStudyDocument);
520     return aRes._retn();
521   }
522
523   CORBA::Boolean VISU_Gen_i::ExportTableToFile(SALOMEDS::SObject_ptr theTable,
524                                                const char* theFileName)
525   {
526     return VISU::ExportTableToFile(theTable, theFileName);
527   }
528
529   Result_ptr VISU_Gen_i::ImportFile(const char* theFileName){
530     if(myStudyDocument->GetProperties()->IsLocked())
531       return Result::_nil();
532     Mutex mt(myMutex);
533     aFileInfo.setFile(theFileName);
534     Result_i* pResult = new Result_i(myStudyDocument,
535                                      Result_i::eFile,
536                                      Result_i::eImportFile);
537     if(pResult->Create(theFileName) != NULL)
538       return pResult->_this();
539     else{
540       pResult->_remove_ref();
541       return VISU::Result::_nil();
542     }
543   }
544
545   Result_ptr VISU_Gen_i::CreateResult(const char* theFileName){
546     if(myStudyDocument->GetProperties()->IsLocked())
547       return Result::_nil();
548     Mutex mt(myMutex);
549     aFileInfo.setFile(theFileName);
550     Result_i* pResult = new Result_i(myStudyDocument,
551                                      Result_i::eFile,
552                                      Result_i::eImportFile,
553                                      false);
554     if(pResult->Create(theFileName) != NULL)
555       return pResult->_this();
556     else{
557       pResult->_remove_ref();
558       return VISU::Result::_nil();
559     }
560   }
561
562   Result_ptr VISU_Gen_i::CopyAndImportFile(const char* theFileName){
563     if(myStudyDocument->GetProperties()->IsLocked())
564       return Result::_nil();
565     Mutex mt(myMutex);
566     VISU::Result_var aResult;
567     aFileInfo.setFile(theFileName);
568     Result_i* pResult = new Result_i(myStudyDocument,
569                                      Result_i::eRestoredFile,
570                                      Result_i::eCopyAndImportFile);
571     if(pResult->Create(theFileName) != NULL)
572       aResult = pResult->_this();
573     return aResult._retn();
574   }
575
576   Result_ptr VISU_Gen_i::ImportMed (SALOMEDS::SObject_ptr theMedSObject)
577   {
578     if (myStudyDocument->GetProperties()->IsLocked())
579       return Result::_nil();
580     Mutex mt(myMutex);
581     Result_i* pResult = new Result_i(myStudyDocument,
582                                      Result_i::eComponent,
583                                      Result_i::eImportMed);
584     if (pResult->Create(theMedSObject) != NULL) {
585       return pResult->_this();
586     } else {
587       pResult->_remove_ref();
588       return VISU::Result::_nil();
589     }
590   }
591
592   Result_ptr VISU_Gen_i::ImportMedField (SALOME_MED::FIELD_ptr theField)
593   {
594     if (myStudyDocument->GetProperties()->IsLocked())
595       return Result::_nil();
596     Mutex mt(myMutex);
597     Result_i* pResult = new Result_i(myStudyDocument,
598                                      Result_i::eComponent,
599                                      Result_i::eImportMedField);
600     if (pResult->Create(theField) != NULL) {
601       return pResult->_this();
602     } else {
603       pResult->_remove_ref();
604       return VISU::Result::_nil();
605     }
606   }
607
608   Mesh_ptr VISU_Gen_i::MeshOnEntity(Result_ptr theResult,
609                                     const char* theMeshName,
610                                     VISU::Entity theEntity)
611   {
612     if(myStudyDocument->GetProperties()->IsLocked())
613       return Mesh::_nil();
614     Mutex mt(myMutex);
615     if(Result_i* pResult = dynamic_cast<Result_i*>(GetServant(theResult).in())){
616       Mesh_i* aPresent = new Mesh_i(pResult);
617       if(aPresent->Create(theMeshName,theEntity) != NULL)
618         return aPresent->_this();
619       else{
620         aPresent->_remove_ref();
621       }
622     }
623     return VISU::Mesh::_nil();
624   }
625
626   Mesh_ptr VISU_Gen_i::FamilyMeshOnEntity(Result_ptr theResult,
627                                           const char* theMeshName,
628                                           VISU::Entity theEntity,
629                                           const char* theFamilyName)
630   {
631     if(myStudyDocument->GetProperties()->IsLocked())
632       return Mesh::_nil();
633     Mutex mt(myMutex);
634     if(Result_i* pResult = dynamic_cast<Result_i*>(GetServant(theResult).in())){
635       Mesh_i* aPresent = new Mesh_i(pResult);
636       if(aPresent->Create(theMeshName,theEntity,theFamilyName) != NULL)
637         return aPresent->_this();
638       else{
639         aPresent->_remove_ref();
640       }
641     }
642     return VISU::Mesh::_nil();
643   }
644
645   Mesh_ptr VISU_Gen_i::GroupMesh(Result_ptr theResult,
646                                  const char* theMeshName,
647                                  const char* theGroupName)
648   {
649     if(myStudyDocument->GetProperties()->IsLocked())
650       return Mesh::_nil();
651     Mutex mt(myMutex);
652     if(Result_i* pResult = dynamic_cast<Result_i*>(GetServant(theResult).in())){
653       Mesh_i* aPresent = new Mesh_i(pResult);
654       if(aPresent->Create(theMeshName,theGroupName) != NULL)
655         return aPresent->_this();
656       else{
657         aPresent->_remove_ref();
658       }
659     }
660     return VISU::Mesh::_nil();
661   }
662
663   ScalarMap_ptr VISU_Gen_i::ScalarMapOnField(Result_ptr theResult,
664                                              const char* theMeshName,
665                                              VISU::Entity theEntity,
666                                              const char* theFieldName,
667                                              CORBA::Double theIteration)
668   {
669     return Prs3dOnField<VISU::ScalarMap_i>(theResult,theMeshName,theEntity,theFieldName,theIteration,true)._retn();
670   }
671
672   GaussPoints_ptr VISU_Gen_i::GaussPointsOnField(Result_ptr theResult,
673                                                  const char* theMeshName,
674                                                  VISU::Entity theEntity,
675                                                  const char* theFieldName,
676                                                  CORBA::Double theIteration)
677   {
678     return Prs3dOnField<VISU::GaussPoints_i>(theResult,theMeshName,theEntity,theFieldName,theIteration,true)._retn();
679   }
680
681   DeformedShape_ptr VISU_Gen_i::DeformedShapeOnField(Result_ptr theResult,
682                                                      const char* theMeshName,
683                                                      VISU::Entity theEntity,
684                                                      const char* theFieldName,
685                                                      CORBA::Double theIteration)
686   {
687     return Prs3dOnField<VISU::DeformedShape_i>(theResult,theMeshName,theEntity,theFieldName,theIteration)._retn();
688   }
689
690   ScalarMapOnDeformedShape_ptr VISU_Gen_i::ScalarMapOnDeformedShapeOnField(Result_ptr theResult,
691                                                                            const char* theMeshName,
692                                                                            VISU::Entity theEntity,
693                                                                            const char* theFieldName,
694                                                                            CORBA::Double theIteration)
695   {
696     return Prs3dOnField<VISU::ScalarMapOnDeformedShape_i>(theResult,theMeshName,theEntity,theFieldName,theIteration)._retn();
697   }
698   
699   Vectors_ptr VISU_Gen_i::VectorsOnField(Result_ptr theResult,
700                                          const char* theMeshName,
701                                          VISU::Entity theEntity,
702                                          const char* theFieldName,
703                                          CORBA::Double theIteration)
704   {
705     return Prs3dOnField<VISU::Vectors_i>(theResult,theMeshName,theEntity,theFieldName,theIteration)._retn();
706   }
707
708   IsoSurfaces_ptr VISU_Gen_i::IsoSurfacesOnField(Result_ptr theResult,
709                                                  const char* theMeshName,
710                                                  VISU::Entity theEntity,
711                                                  const char* theFieldName,
712                                                  CORBA::Double theIteration)
713   {
714     return Prs3dOnField<VISU::IsoSurfaces_i>(theResult,theMeshName,theEntity,theFieldName,theIteration)._retn();
715   }
716
717   StreamLines_ptr VISU_Gen_i::StreamLinesOnField(Result_ptr theResult,
718                                                  const char* theMeshName,
719                                                  VISU::Entity theEntity,
720                                                  const char* theFieldName,
721                                                  CORBA::Double theIteration)
722   {
723     return Prs3dOnField<VISU::StreamLines_i>(theResult,theMeshName,theEntity,theFieldName,theIteration)._retn();
724   }
725
726   Plot3D_ptr VISU_Gen_i::Plot3DOnField(Result_ptr theResult,
727                                        const char* theMeshName,
728                                        VISU::Entity theEntity,
729                                        const char* theFieldName,
730                                        CORBA::Double theIteration)
731   {
732     return Prs3dOnField<VISU::Plot3D_i>(theResult,theMeshName,theEntity,theFieldName,theIteration)._retn();
733   }
734
735   CutPlanes_ptr VISU_Gen_i::CutPlanesOnField(Result_ptr theResult,
736                                              const char* theMeshName,
737                                              VISU::Entity theEntity,
738                                              const char* theFieldName,
739                                              CORBA::Double theIteration)
740   {
741     return Prs3dOnField<VISU::CutPlanes_i>(theResult,theMeshName,theEntity,theFieldName,theIteration)._retn();
742   }
743
744   CutLines_ptr VISU_Gen_i::CutLinesOnField(Result_ptr theResult,
745                                            const char* theMeshName,
746                                            VISU::Entity theEntity,
747                                            const char* theFieldName,
748                                            CORBA::Double theIteration)
749   {
750     return Prs3dOnField<VISU::CutLines_i>(theResult,theMeshName,theEntity,theFieldName,theIteration)._retn();
751   }
752
753   Table_ptr VISU_Gen_i::CreateTable(const char* theTableEntry){
754     if(myStudyDocument->GetProperties()->IsLocked())
755       return Table::_nil();
756     Mutex mt(myMutex);
757     Table_i* pPresent = new Table_i(myStudyDocument,theTableEntry);
758     if(pPresent->Create() != NULL)
759       return pPresent->_this();
760     else{
761       pPresent->_remove_ref();
762       return VISU::Table::_nil();
763     }
764   }
765
766   Curve_ptr VISU_Gen_i::CreateCurve(Table_ptr theTable,
767                                     CORBA::Long theHRow,
768                                     CORBA::Long theVRow)
769   {
770     if(myStudyDocument->GetProperties()->IsLocked())
771       return Curve::_nil();
772     Mutex mt(myMutex);
773     PortableServer::POA_ptr aPOA = GetPOA();
774     Table_i* pTable = dynamic_cast<Table_i*>(aPOA->reference_to_servant(theTable));
775     Curve_i* pPresent = new Curve_i(myStudyDocument,pTable,theHRow,theVRow);
776     if(pPresent->Create() != NULL)
777       return pPresent->_this();
778     else{
779       pPresent->_remove_ref();
780       return VISU::Curve::_nil();
781     }
782   }
783
784   Container_ptr VISU_Gen_i::CreateContainer(){
785     if(myStudyDocument->GetProperties()->IsLocked())
786       return Container::_nil();
787     Mutex mt(myMutex);
788     Container_i* pPresent = new Container_i(myStudyDocument);
789     if(pPresent->Create() != NULL)
790       return pPresent->_this();
791     else{
792       pPresent->_remove_ref();
793       return VISU::Container::_nil();
794     }
795   }
796
797   Animation_ptr VISU_Gen_i::CreateAnimation(View3D_ptr theView3D){
798     if(myStudyDocument->GetProperties()->IsLocked())
799       return Animation::_nil();
800     Mutex mt(myMutex);
801     if(VISU_TimeAnimation_i* anAnim = new VISU_TimeAnimation_i(myStudyDocument,theView3D)){
802       return anAnim->_this();
803     }else
804       return VISU::Animation::_nil();
805   }
806
807   void VISU_Gen_i::DeleteResult (Result_ptr theResult)
808   {
809     theResult->RemoveFromStudy();
810   }
811
812   void VISU_Gen_i::DeletePrs3d (Prs3d_ptr thePrs3d)
813   {
814     thePrs3d->RemoveFromStudy();
815   }
816
817   void VISU_Gen_i::Close(SALOMEDS::SComponent_ptr theComponent){
818   }
819
820   char* VISU_Gen_i::ComponentDataType(){
821     return CORBA::string_dup("VISU");
822   }
823
824   bool VISU_Gen_i::CanPublishInStudy(CORBA::Object_ptr theIOR) {
825     Result_var aResultObj = Result::_narrow(theIOR);
826     return !(aResultObj->_is_nil());
827   }
828
829   SALOMEDS::SObject_ptr VISU_Gen_i::PublishInStudy(SALOMEDS::Study_ptr theStudy,
830                                                    SALOMEDS::SObject_ptr theSObject,
831                                                    CORBA::Object_ptr theObject,
832                                                    const char* theName)
833     throw (SALOME::SALOME_Exception)
834   {
835     Unexpect aCatch(SalomeException);
836     if(MYDEBUG) MESSAGE("VISU_Gen_i::PublishInStudy : "<<myMutex);
837     Mutex mt(myMutex);
838     SALOMEDS::SObject_var aResultSO;
839     Result_i* aResultObj = dynamic_cast<Result_i*>(GetServant(theObject).in());
840     if (!aResultObj) return aResultSO._retn();
841     const QFileInfo& aFileInfo = aResultObj->GetFileInfo();
842     CORBA::String_var anEntry = aResultObj->Create(aFileInfo.filePath().latin1())->GetID();
843     aResultSO = theStudy->FindObjectID(anEntry);
844     return aResultSO._retn();
845   }
846
847   CORBA::Boolean VISU_Gen_i::CanCopy(SALOMEDS::SObject_ptr theObject) {
848     Mutex mt(myMutex);
849     SALOMEDS::GenericAttribute_var anAttr;
850     if (!theObject->FindAttribute(anAttr, "AttributeIOR")) return false;
851     try {
852       SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
853       CORBA::String_var aValue = anIOR->Value();
854       if(strcmp(aValue,"") != 0){
855         CORBA::Object_ptr anObj = GetORB()->string_to_object(aValue);
856         if (!CORBA::is_nil(anObj)){
857           Result_var aResultObj = Result::_narrow(anObj);
858           if(!aResultObj->_is_nil()){
859             if(Result_i* pResult = dynamic_cast<Result_i*>(GetServant(aResultObj).in())){
860               switch(pResult->GetCreationId()){
861               case Result_i::eImportFile:
862               case Result_i::eCopyAndImportFile:
863                 return true;
864               }
865             }
866           }
867         }
868       }
869     }catch(std::exception& exc){
870       INFOS("Follow exception was occured :\n"<<exc.what());
871     }catch (...){
872       INFOS("Unknown exception was occured!");
873     }
874     return false;
875   }
876
877   SALOMEDS::TMPFile* VISU_Gen_i::CopyFrom(SALOMEDS::SObject_ptr theObject, CORBA::Long& theObjectID) {
878     Mutex mt(myMutex);
879     theObjectID = 0;
880     SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile;
881     SALOMEDS::ListOfFileNames_var aSeq = new SALOMEDS::ListOfFileNames;
882
883     PortableServer::POA_ptr aPOA = GetPOA();
884
885     SALOMEDS::GenericAttribute_var anAttr;
886     if (!theObject->FindAttribute(anAttr,"AttributeIOR")) return NULL;
887     SALOMEDS::AttributeIOR_var anIORAttr = SALOMEDS::AttributeIOR::_narrow(anAttr);
888     CORBA::Object_var aCorbaObj;
889     try {
890       aCorbaObj = GetORB()->string_to_object(anIORAttr->Value());
891     } catch(...) {
892       aStreamFile->length(1);
893       aStreamFile[0] = strdup("E")[0];
894       return aStreamFile._retn();
895     }
896     if (CORBA::is_nil(aCorbaObj)) {
897       return NULL;
898     }
899
900     Storable* pStorable = dynamic_cast<Storable*>(GetServant(aCorbaObj).in());
901     if (!pStorable) {
902       return NULL;
903     }
904
905     string aTmpDir = SALOMEDS_Tool::GetTmpDir();
906     string aCopyPersist =  aTmpDir + "copy_persistent";
907
908     ofstream stmOut2(aCopyPersist.c_str(),ios::out);
909     string aStr = pStorable->ToString().c_str();
910     stmOut2<<aStr<<endl;
911     stmOut2.close();
912
913     if (Result_i* aResultObj = dynamic_cast<Result_i*>(aPOA->reference_to_servant(aCorbaObj))) {
914       string aFileName = string(SALOMEDS_Tool::GetNameFromPath(theObject->GetStudy()->URL())) + "_";
915       if(strlen(aFileName.c_str()) == 1) aFileName="";
916       const QFileInfo& aFileInfo = aResultObj->GetFileInfo();
917       aFileName += aFileInfo.fileName().latin1();
918       static QString aCommand;
919       string aFullFileName =  aTmpDir + aFileName;
920       aCommand.sprintf("cp %s %s",
921                        aFileInfo.filePath().latin1(),
922                        aFullFileName.c_str());
923       if(system(aCommand) == -1) {
924         if(MYDEBUG) MESSAGE("VISU_Gen_i::Copy - Cann't execute the command :"<<aCommand);
925         return NULL;
926       }
927       aSeq->length(2);
928       aSeq[0] = "copy_persistent";
929       aSeq[1] = aFileName.c_str();
930     } else {
931       aSeq->length(1);
932       aSeq[0] = "copy_persistent";
933     }
934
935     aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir.c_str(), aSeq.in(), false);
936     SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.c_str(), aSeq.in(), true);
937
938     // Assign an ID = 1 the the type VISU::Result
939     theObjectID = 1;
940
941
942     SALOMEDS::SComponent_var aSComponent = theObject->GetStudy()->FindComponent("VISU");
943     return aStreamFile._retn();
944   }
945
946   CORBA::Boolean VISU_Gen_i::CanPaste(const char* theComponentName, CORBA::Long theObjectID) {
947     // The VISU component can paste only objects copied by VISU component
948     // and with the object type = 1
949     if (strcmp(theComponentName, ComponentDataType()) != 0 || theObjectID != 1)
950       return false;
951     return true;
952   }
953
954   SALOMEDS::SObject_ptr VISU_Gen_i::PasteInto(const SALOMEDS::TMPFile& theStream,
955                                               CORBA::Long theObjectID,
956                                               SALOMEDS::SObject_ptr theObject)
957   {
958     Mutex mt(myMutex);
959     SALOMEDS::SObject_var aResultSO;
960     if (theObjectID != 1)
961       return aResultSO._retn();
962
963     string aTmpDir = SALOMEDS_Tool::GetTmpDir();
964     SALOMEDS::ListOfFileNames_var aSeq = SALOMEDS_Tool::PutStreamToFiles(theStream, aTmpDir.c_str(), false);
965
966     ifstream stmIn((aTmpDir + string("copy_persistent")).c_str());
967     stmIn.seekg(0, ios::end);
968     int aLength = stmIn.tellg();
969     stmIn.seekg(0, ios::beg);
970     char* aString = new char[aLength+1];
971     stmIn.read(aString, aLength);
972     aString[aLength] = 0;
973     myIsMultiFile = false;
974
975     string aFileName(aTmpDir);
976     string aBasicFileName;
977     if(aSeq->length() > 1) {
978       aBasicFileName = aSeq[1].in();
979       aFileName += aBasicFileName;
980     }
981
982     SALOMEDS::SComponent_var aComponent = theObject->GetFatherComponent();
983     SALOMEDS::Study_var aStudy = theObject->GetStudy();
984     SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
985     CORBA::String_var aComponentID(aComponent->GetID()), aSObjID(theObject->GetID());
986
987     if (strcmp(aComponentID, aSObjID) == 0) //create the new result SObject
988       aResultSO = aStudyBuilder->NewObject(aComponent);
989     else
990       aResultSO = SALOMEDS::SObject::_duplicate(theObject);
991
992     //Just for Result::Restore to find the Comment attribute :(
993     SALOMEDS::GenericAttribute_var anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO, "AttributeComment");
994
995     Storable* aStorable = Storable::Create(aResultSO,aFileName,aString);
996
997     SALOMEDS::ListOfFileNames_var aSeqToRm = new SALOMEDS::ListOfFileNames;
998     aSeqToRm->length(1);
999     aSeqToRm[0] = "copy_persistent";
1000
1001     SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.c_str(), aSeqToRm.in(), true);
1002
1003     anAttr = aStudyBuilder->FindOrCreateAttribute(aResultSO, "AttributeIOR");
1004     SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
1005     CORBA::String_var anIORValue(aStorable->GetID());
1006     anIOR->SetValue(anIORValue);
1007     return aResultSO._retn();
1008   }
1009 }