Salome HOME
Fix pb with persistence mechanism for "light" modules: when saving from CORBA API...
[modules/gui.git] / src / SalomeApp / SalomeApp_Engine_i.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SalomeApp_Engine_i : implementation of SalomeApp_Engine.idl
24 //  File   : SalomeApp_Engine_i.cxx
25 //  Author : Alexander SLADKOV
26
27 #include "SalomeApp_Engine_i.h"
28 #include "SalomeApp_Application.h"
29 #include "SalomeApp_Study.h"
30 #include "SUIT_Session.h"
31 #include "CAM_Module.h"
32 #include "LightApp_DataModel.h"
33
34 #include <SALOME_NamingService.hxx>
35 #include <SALOMEDS_Tool.hxx>
36 #include <Utils_ORB_INIT.hxx>
37 #include <Utils_SINGLETON.hxx>
38 #include <Utils_SALOME_Exception.hxx>
39 #include <utilities.h>
40
41 #include <QApplication>
42 #include <QDir>
43 #include <QFile>
44
45 #include <iostream>
46
47 namespace
48 {
49   SalomeApp_Study* getStudyById( int id )
50   {
51     SalomeApp_Study* study = 0;
52     QList<SUIT_Application*> apps = SUIT_Session::session()->applications();
53     for ( int i = 0; i < apps.count() && !study; i++ )
54     {
55       SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( apps[i]->activeStudy() );
56       if ( appStudy && appStudy->id() == id )
57         study = appStudy;
58     }
59     return study;
60   }
61 }
62
63 /*!
64   Constructor
65 */
66 SalomeApp_Engine_i::SalomeApp_Engine_i( const char* theComponentName )
67   : myComponentName( theComponentName )
68 {
69   MESSAGE("SalomeApp_Engine_i::SalomeApp_Engine_i(): myComponentName = " <<
70           qPrintable( myComponentName ) << ", this = " << this);
71 }
72
73 /*!
74   Destructor
75 */
76 SalomeApp_Engine_i::~SalomeApp_Engine_i()
77 {
78   MESSAGE("SalomeApp_Engine_i::~SalomeApp_Engine_i(): myComponentName = " << 
79           qPrintable( myComponentName ) << ", this = " << this);
80 }
81
82 SALOMEDS::TMPFile* SalomeApp_Engine_i::Save (SALOMEDS::SComponent_ptr theComponent,
83                                              const char* theURL,
84                                              bool isMultiFile)
85 {
86   SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile;
87
88   if ( CORBA::is_nil(theComponent) || CORBA::is_nil( theComponent->GetStudy() ) )
89     return aStreamFile._retn();
90
91   // Component type
92   QString componentName = theComponent->ComponentDataType();
93   // Error somewhere outside - Save() called with wrong SComponent instance
94   if ( myComponentName != componentName )
95     return aStreamFile._retn();
96
97   // Get study ID
98   const int studyId = theComponent->GetStudy()->StudyId();
99
100   bool manuallySaved = false;
101
102   if ( !myMap.count( studyId ) ) {
103     // Save was probably called from outside GUI, so SetListOfFiles was not called!
104     // Try to get list of files from directly from data model
105
106     MESSAGE("SalomeApp_Engine_i::Save(): myComponentName = " <<
107             qPrintable( myComponentName ) <<
108             "it seems Save() was called from outside GUI" );
109
110     // - Get study
111     SalomeApp_Study* study = getStudyById( studyId );
112     if ( !study )
113       return aStreamFile._retn();
114     // - Get app
115     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( study->application() );
116     if ( !app )
117       return aStreamFile._retn();
118     // - Get module
119     CAM_Module* module = app->module( SalomeApp_Application::moduleTitle( componentName ) );
120     if ( !module ) // load module???
121       return aStreamFile._retn();
122     // - Get data model
123     LightApp_DataModel* dataModel = dynamic_cast<LightApp_DataModel*>( module->dataModel() );
124     if ( !dataModel )
125       return aStreamFile._retn();
126     // - Save data files
127     QStringList dataFiles;
128     dataModel->saveAs( theURL, study, dataFiles );
129     std::vector<std::string> names;
130     foreach ( QString name, dataFiles ) {
131       if ( !name.isEmpty() )
132         names.push_back(name.toUtf8().data());
133     }
134     SetListOfFiles( names, studyId );
135     manuallySaved = true;
136   }
137
138   // Get a temporary directory to store a file
139   //std::string aTmpDir = isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir();
140
141   if ( myMap.count( studyId ) ) {
142
143     const ListOfFiles& listOfFiles = myMap[studyId];
144
145     // listOfFiles must contain temporary directory name in its first item
146     // and names of files (relatively the temporary directory) in the others
147     const int n = listOfFiles.size() - 1;
148
149     if (n > 0) { // there are some files, containing persistent data of the component
150       std::string aTmpDir = listOfFiles[0];
151
152       // Create a list to store names of created files
153       SALOMEDS::ListOfFileNames_var aSeq = new SALOMEDS::ListOfFileNames;
154       aSeq->length(n);
155       for (int i = 0; i < n; i++)
156         aSeq[i] = CORBA::string_dup(listOfFiles[i + 1].c_str());
157
158       // Convert a file to the byte stream
159       aStreamFile = SALOMEDS_Tool::PutFilesToStream(aTmpDir.c_str(), aSeq.in(), isMultiFile);
160
161       // Remove the files and tmp directory, created by the component storage procedure
162       if (!isMultiFile) SALOMEDS_Tool::RemoveTemporaryFiles(aTmpDir.c_str(), aSeq.in(), true);
163     }
164   }
165
166   if ( manuallySaved )
167     SetListOfFiles( ListOfFiles(), studyId );
168
169   return aStreamFile._retn();
170 }
171
172 CORBA::Boolean SalomeApp_Engine_i::Load (SALOMEDS::SComponent_ptr theComponent,
173                                          const SALOMEDS::TMPFile& theFile,
174                                          const char* theURL,
175                                          bool isMultiFile)
176 {
177   std::cout << "SalomeApp_Engine_i::Load() isMultiFile = " << isMultiFile << std::endl;
178   if (CORBA::is_nil(theComponent) || CORBA::is_nil(theComponent->GetStudy()))
179     return false;
180
181   // Error somewhere outside - Load() called with
182   // wrong SComponent instance
183   QString componentName = theComponent->ComponentDataType();
184   if ( myComponentName != componentName )
185     return false;
186
187   const int studyId = theComponent->GetStudy()->StudyId();
188
189   // Create a temporary directory for the component's data files
190   std::string aTmpDir = isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir();
191
192   // Convert the byte stream theStream to a files and place them in the tmp directory.
193   // The files and temporary directory must be deleted by the component loading procedure.
194   SALOMEDS::ListOfFileNames_var aSeq =
195     SALOMEDS_Tool::PutStreamToFiles(theFile, aTmpDir.c_str(), isMultiFile);
196
197   // Store list of file names to be used by the component loading procedure
198   const int n = aSeq->length() + 1;
199   ListOfFiles listOfFiles (n);
200   listOfFiles[0] = aTmpDir;
201   for (int i = 1; i < n; i++)
202     listOfFiles[i] = std::string(aSeq[i - 1]);
203
204   SetListOfFiles(listOfFiles, studyId);
205
206   return true;
207 }
208
209 SalomeApp_Engine_i::ListOfFiles SalomeApp_Engine_i::GetListOfFiles (const int theStudyId)
210 {
211   ListOfFiles aListOfFiles;
212
213   if (myMap.find(theStudyId) != myMap.end())
214   {
215     aListOfFiles = myMap[theStudyId];
216   }
217
218   return aListOfFiles;
219 }
220
221 void SalomeApp_Engine_i::SetListOfFiles (const ListOfFiles& theListOfFiles,
222                                          const int          theStudyId)
223 {
224   if ( theListOfFiles.empty() )
225     myMap.erase( theStudyId );
226   else
227     myMap[theStudyId] = theListOfFiles;
228 }
229
230 /*! 
231  *  DumpPython implementation for light modules
232  */
233 Engines::TMPFile* SalomeApp_Engine_i::DumpPython(CORBA::Object_ptr theStudy, 
234                                                  CORBA::Boolean isPublished, 
235                                                  CORBA::Boolean isMultiFile, 
236                                                  CORBA::Boolean& isValidScript)
237 {
238   MESSAGE("SalomeApp_Engine_i::DumpPython(): myComponentName = "<<
239           qPrintable( myComponentName ) << ", this = " << this);
240   
241   // Temporary solution: returning a non-empty sequence
242   // even if there's nothing to dump, to avoid crashes in SALOMEDS
243   // TODO: Improve SALOMEDSImpl_Study::DumpStudy() by skipping the components 
244   // with isValidScript == false, and initialize isValidScript by false below.
245   Engines::TMPFile_var aStreamFile = new Engines::TMPFile(1);
246   aStreamFile->length( 1 );
247   aStreamFile[0] = '\0';
248   isValidScript = true;
249
250   if (CORBA::is_nil(theStudy))
251     return aStreamFile._retn();
252
253   SALOMEDS::Study_var studyDS = SALOMEDS::Study::_narrow( theStudy );
254   const int studyId = studyDS->StudyId();
255
256   if (!myMap.count(studyId))
257     return aStreamFile._retn();
258
259   ListOfFiles listOfFiles = myMap[studyId];
260
261   // listOfFiles must contain temporary directory name in its first item
262   // and names of files (relatively the temporary directory) in the others
263   if ( listOfFiles.size() < 2 ) 
264     return aStreamFile._retn();
265
266   // there are some files, containing persistent data of the component
267   QString aTmpPath( listOfFiles.front().c_str() );
268   QDir aTmpDir( aTmpPath );
269   if ( !aTmpDir.exists() )
270     return aStreamFile._retn();    
271
272   // Calculate file sizes
273   QStringList aFilePaths;
274   QList<qint64> aFileSizes;
275   qint64 aBuffSize = 0;
276   ListOfFiles::const_iterator aFIt  = listOfFiles.begin();
277   ListOfFiles::const_iterator aFEnd = listOfFiles.end();
278   aFIt++;
279   for (; aFIt != aFEnd; aFIt++){
280     QString aFileName( (*aFIt).c_str() );
281     if ( !aTmpDir.exists( aFileName ) ){
282       continue;
283     }
284
285     QFile aFile( aTmpDir.filePath( aFileName ) );
286     if ( !aFile.open( QIODevice::ReadOnly ) ){
287       continue;
288     }
289
290     aFilePaths.push_back( aTmpDir.filePath( aFileName ) );
291     aFileSizes.push_back( aFile.size() );
292     aBuffSize += aFileSizes.back();
293
294     aFile.close();
295   }
296
297   if ( !aFilePaths.size() || !aBuffSize )
298     return aStreamFile._retn(); 
299     
300   char* aBuffer = new char[aBuffSize + 1];
301   if ( !aBuffer )
302     return aStreamFile._retn();
303
304   // Convert the file(s) to the byte stream, multiple files are simply
305   // concatenated
306   // TODO: imporve multi-script support if necessary...
307   qint64 aCurrPos = 0;
308   QStringList::const_iterator aFileIt  = aFilePaths.begin();
309   QStringList::const_iterator aFileEnd = aFilePaths.end();
310   QList<qint64>::const_iterator   aSIt = aFileSizes.begin();
311   for ( ; aFileIt != aFileEnd; aFileIt++, aSIt++ ){
312     QFile aFile( aTmpDir.filePath( *aFileIt ) );
313     if ( !aFile.open( QIODevice::ReadOnly ) ){
314       continue;
315     }
316
317     // Incorrect size of file
318     // Do not remove the bad file to have some diagnostic means
319     if ( aFile.read( aBuffer + aCurrPos, *aSIt ) != *aSIt ){
320       aFile.close();      
321       return aStreamFile._retn();
322     }
323
324     aCurrPos += (*aSIt); 
325     aFile.remove();   
326   }
327
328   // Here we should end up with empty aTmpDir
329   // TODO: Handle QDir::rmdir() error status somehow...
330   aTmpDir.rmdir( aTmpPath );
331
332   aBuffer[aBuffSize] = '\0';
333   CORBA::Octet* anOctetBuf =  (CORBA::Octet*)aBuffer;
334   aStreamFile = new Engines::TMPFile(aBuffSize + 1, aBuffSize + 1, anOctetBuf, 1); 
335
336   return aStreamFile._retn();
337 }
338
339 /*!
340   \return Component data type string for this instance of the engine
341 */
342 char* SalomeApp_Engine_i::ComponentDataType()
343 {
344   return CORBA::string_dup( myComponentName.toLatin1().constData() );
345 }
346
347 /*!
348   \return Component version
349 */
350 char* SalomeApp_Engine_i::getVersion()
351 {
352   SalomeApp_Application::ModuleShortInfoList versions = SalomeApp_Application::getVersionInfo();
353   QString version;
354   SalomeApp_Application::ModuleShortInfo version_info;
355   foreach ( version_info, versions ) {
356     if ( SalomeApp_Application::moduleName( version_info.name ) == myComponentName ) {
357       version = version_info.version;
358       break;
359     }
360   }
361   
362   return CORBA::string_dup( version.toLatin1().constData() );
363 }
364
365 /*!
366   \return 
367 */
368 CORBA::ORB_var SalomeApp_Engine_i::orb()
369 {
370   static CORBA::ORB_var _orb;
371
372   if ( CORBA::is_nil( _orb ) ) {
373     Qtx::CmdLineArgs args;
374     ORB_INIT& init = *SINGLETON_<ORB_INIT>::Instance();
375     _orb = init( args.argc(), args.argv() );
376   }
377
378   return _orb;
379 }
380
381 /*!
382   \return 
383 */
384 PortableServer::POA_var SalomeApp_Engine_i::poa()
385 {
386   static PortableServer::POA_var _poa;
387   if ( CORBA::is_nil( _poa ) ){
388     CORBA::Object_var obj = orb()->resolve_initial_references( "RootPOA" );
389     _poa = PortableServer::POA::_narrow( obj );
390   }
391   return _poa;
392 }
393
394 /*!
395   \return 
396 */
397 SALOME_NamingService* SalomeApp_Engine_i::namingService()
398 {
399   static SALOME_NamingService _ns(orb());
400   return &_ns;
401 }
402
403 /*!
404   Internal method, creates a CORBA engine for a light SALOME module
405   with the given "component data type" string,
406   activates it and registers in SALOME naming service with
407   /SalomeAppEngine/comp_data_type path. If the engine is already in the 
408   naming service, simply returns and object reference to it.
409   \param theComponentName - synthetic "component data type" used to identify a given light module
410   \return Object reference to the CORBA engine
411 */
412 CORBA::Object_ptr SalomeApp_Engine_i::EngineForComponent( const char* theComponentName,
413                                                           bool toCreate )
414 {
415   CORBA::Object_var anEngine;
416   if ( !theComponentName || !strlen( theComponentName ) )
417     return anEngine._retn();
418
419   if ( SalomeApp_Application::moduleTitle( theComponentName ).isEmpty() )
420     return anEngine._retn();
421
422   std::string aPath( "/SalomeAppEngine/" );
423   aPath += theComponentName;
424   anEngine = namingService()->Resolve( aPath.c_str() );
425
426   // Activating a new instance of the servant
427   if ( toCreate && CORBA::is_nil( anEngine ) ){
428     try {
429       SalomeApp_Engine_i* aServant    = new SalomeApp_Engine_i( theComponentName );
430       PortableServer::ObjectId_var id = poa()->activate_object( aServant );
431       anEngine = aServant->_this();
432       aServant->_remove_ref();
433       namingService()->Register( anEngine.in(), aPath.c_str() );
434     }
435     catch (CORBA::SystemException&) {
436       INFOS("Caught CORBA::SystemException.");
437     }
438     catch (CORBA::Exception&) {
439       INFOS("Caught CORBA::Exception.");
440     }
441     catch (...) {
442       INFOS("Caught unknown exception.");
443     }
444   }
445
446   return anEngine._retn();
447 }
448
449 /*!
450   \param theComponentName - synthetic "component data type" used to identify a given light module
451   \return IOR string for the CORBA engine for a light SALOME module
452   with the given "component data type" string
453   \sa GetInstance( const char* theComponentName )
454 */
455 std::string SalomeApp_Engine_i::EngineIORForComponent( const char* theComponentName,
456                                                        bool toCreate )
457 {
458   std::string anIOR( "" );
459   CORBA::Object_var anEngine = EngineForComponent( theComponentName, toCreate );
460   if ( !CORBA::is_nil( anEngine ) )
461   {
462     CORBA::String_var objStr = orb()->object_to_string( anEngine.in() );
463     anIOR = std::string( objStr.in() );
464   }
465   return anIOR;
466 }
467
468 /*!
469   \param theComponentName - synthetic "component data type" used to identify a given light module
470   \return A pointer to corresponding C++ engine instance, null means some internal problems.
471   \sa EngineIORForComponent( const char* theComponentName )
472 */
473 SalomeApp_Engine_i* SalomeApp_Engine_i::GetInstance( const char* theComponentName,
474                                                      bool toCreate )
475 {
476   SalomeApp_Engine_i* aServant = 0;
477   CORBA::Object_var anEngine = EngineForComponent( theComponentName, toCreate );
478   if ( !CORBA::is_nil( anEngine ) )
479   {
480     PortableServer::Servant aServantBase = poa()->reference_to_servant( anEngine.in() );
481     aServant = dynamic_cast<SalomeApp_Engine_i*>( aServantBase );
482   } 
483   MESSAGE("SalomeApp_Engine_i::GetInstance(): theComponentName = " <<
484           theComponentName << ", aServant = " << aServant);
485   return aServant;
486 }