]> SALOME platform Git repositories - modules/kernel.git/blob - src/TOOLSDS/SALOMEDS_Tool.cxx
Salome HOME
8c292d49376556979e982be82cf15e538150cd7e
[modules/kernel.git] / src / TOOLSDS / SALOMEDS_Tool.cxx
1 //  File      : SALOMEDS_Tool.cxx
2 //  Created   : Mon Oct 21 16:24:34 2002
3 //  Author    : Sergey RUIN
4
5 //  Project   : SALOME
6 //  Module    : SALOMEDS
7 //  Copyright : Open CASCADE
8
9 #include "SALOMEDS_Tool.hxx"
10
11 #include "utilities.h"
12
13 #include <TCollection_AsciiString.hxx> 
14
15 #include <OSD_Path.hxx>
16 #include <OSD_File.hxx>
17 #include <OSD_Directory.hxx>
18 #include <OSD_Process.hxx>
19 #include <OSD_Directory.hxx>
20 #include <OSD_Protection.hxx>
21 #include <OSD_SingleProtection.hxx>
22 #include <OSD_FileIterator.hxx>
23
24 #ifndef WNT
25 #include <stdio.h>
26 #include <iostream.h> 
27 #include <fstream.h>
28 #include <sys/time.h>
29 #else
30 #endif
31 #include <stdlib.h>
32
33 #include CORBA_SERVER_HEADER(SALOMEDS_Attributes)
34
35 using namespace std;
36
37 //============================================================================
38 // function : GetTempDir
39 // purpose  : Return a temp directory to store created files like "/tmp/sub_dir/" 
40 //============================================================================ 
41 std::string SALOMEDS_Tool::GetTmpDir()
42 {
43   //Find a temporary directory to store a file
44
45   TCollection_AsciiString aTmpDir;
46
47   char *Tmp_dir = getenv("SALOME_TMP_DIR");
48   if(Tmp_dir != NULL) {
49     aTmpDir = TCollection_AsciiString(Tmp_dir);
50 #ifdef WIN32
51     if(aTmpDir.Value(aTmpDir.Length()) != '\\') aTmpDir+='\\';
52 #else
53     if(aTmpDir.Value(aTmpDir.Length()) != '/') aTmpDir+='/';
54 #endif      
55   }
56   else {
57 #ifdef WIN32
58     aTmpDir = TCollection_AsciiString("C:\\");
59 #else
60     aTmpDir = TCollection_AsciiString("/tmp/");
61 #endif
62   }
63
64   srand((unsigned int)time(NULL));
65   int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
66   TCollection_AsciiString aSubDir(aRND);
67   if(aSubDir.Length() <= 1) aSubDir = TCollection_AsciiString("123409876");
68
69   aTmpDir += aSubDir; //Get RND sub directory
70
71 #ifdef WIN32
72   if(aTmpDir.Value(aTmpDir.Length()) != '\\') aTmpDir+='\\';
73 #else
74   if(aTmpDir.Value(aTmpDir.Length()) != '/') aTmpDir+='/';
75 #endif
76
77   OSD_Path aPath(aTmpDir);
78   OSD_Directory aDir(aPath);
79
80   for(aRND = 0; aDir.Exists(); aRND++) {
81     aTmpDir.Insert((aTmpDir.Length() - 1), TCollection_AsciiString(aRND));  //Build a unique directory name
82     aPath = OSD_Path(aTmpDir);
83     aDir = OSD_Directory(aPath);
84   }
85
86   MESSAGE("#### TMP" << aTmpDir.ToCString());
87
88   OSD_Protection aProtection(OSD_RW, OSD_RWX, OSD_RX, OSD_RX);
89   aDir.Build(aProtection);
90
91   return aTmpDir.ToCString();
92 }
93
94 //============================================================================
95 // function : RemoveTemporaryFiles
96 // purpose  : Removes files listed in theFileList
97 //============================================================================
98 void SALOMEDS_Tool::RemoveTemporaryFiles(const std::string& theDirectory, 
99                                          const SALOMEDS::ListOfFileNames& theFiles,
100                                          const bool IsDirDeleted)
101 {
102   TCollection_AsciiString aDirName(const_cast<char*>(theDirectory.c_str()));
103
104   int i, aLength = theFiles.length();
105   for(i=0; i<aLength; i++) {
106     TCollection_AsciiString aFile(aDirName);
107 //     aFile += (char*)theFiles[i];
108     aFile += (char*)theFiles[i].in();
109     OSD_Path anOSDPath(aFile);
110     OSD_File anOSDFile(anOSDPath);
111     if(!anOSDFile.Exists()) continue;
112
113     OSD_Protection aProtection = anOSDFile.Protection();
114     aProtection.SetUser(OSD_RW);
115     anOSDFile.SetProtection(aProtection);
116
117     anOSDFile.Remove();
118   }
119
120   if(IsDirDeleted) {
121     OSD_Path aPath(aDirName);
122     OSD_Directory aDir(aPath);
123     OSD_FileIterator anIterator(aPath, '*');
124
125     if(aDir.Exists() && !anIterator.More()) aDir.Remove();
126   }
127
128 }
129
130 //============================================================================
131 // function : PutFilesToStream
132 // purpose  : converts the files from a list 'theFiles' to the stream
133 //============================================================================
134 SALOMEDS::TMPFile* 
135 SALOMEDS_Tool::PutFilesToStream(const std::string& theFromDirectory,
136                                 const SALOMEDS::ListOfFileNames& theFiles,
137                                 const int theNamesOnly)
138 {
139   int i, aLength = theFiles.length();
140   if(aLength == 0)
141 //    return NULL;
142     return (new SALOMEDS::TMPFile);
143
144   //Get a temporary directory for saved a file
145   TCollection_AsciiString aTmpDir(const_cast<char*>(theFromDirectory.c_str()));
146
147   long aBufferSize = 0;
148   long aCurrentPos;
149
150   int aNbFiles = 0;
151   int* aFileNameSize= new int[aLength];
152   long* aFileSize= new long[aLength];
153
154   //Determine the required size of the buffer
155
156   for(i=0; i<aLength; i++) {
157
158     //Check if the file exists
159     
160     if (!theNamesOnly) { // mpv 15.01.2003: if only file names must be stroed, then size of files is zero
161       TCollection_AsciiString aFullPath = aTmpDir + CORBA::string_dup(theFiles[i]);   
162       OSD_Path anOSDPath(aFullPath);
163       OSD_File anOSDFile(anOSDPath);
164       if(!anOSDFile.Exists()) continue;
165 #ifdef WNT
166       ifstream aFile(aFullPath.ToCString(), ios::binary);
167 #else
168       ifstream aFile(aFullPath.ToCString());
169 #endif
170       aFile.seekg(0, ios::end);
171       aFileSize[i] = aFile.tellg();
172       aBufferSize += aFileSize[i];              //Add a space to store the file
173     }
174     aFileNameSize[i] = strlen(theFiles[i])+1;
175     aBufferSize += aFileNameSize[i];          //Add a space to store the file name
176     aBufferSize += (theNamesOnly)?4:12;       //Add 4 bytes: a length of the file name,
177                                               //    8 bytes: length of the file itself
178     aNbFiles++;
179   } 
180
181   aBufferSize += 4;      //4 bytes for a number of the files that will be written to the stream;
182   unsigned char* aBuffer = new unsigned char[aBufferSize];  
183   if(aBuffer == NULL)
184 //    return NULL; 
185     return (new SALOMEDS::TMPFile);
186
187   //Initialize 4 bytes of the buffer by 0
188   memset(aBuffer, 0, 4); 
189   //Copy the number of files that will be written to the stream
190   memcpy(aBuffer, &aNbFiles, ((sizeof(int) > 4) ? 4 : sizeof(int))); 
191
192
193   aCurrentPos = 4;
194
195   for(i=0; i<aLength; i++) {
196     ifstream *aFile;
197     if (!theNamesOnly) { // mpv 15.01.2003: we don't open any file if theNamesOnly = true
198       TCollection_AsciiString aFullPath = aTmpDir + CORBA::string_dup(theFiles[i]);
199       OSD_Path anOSDPath(aFullPath);
200       OSD_File anOSDFile(anOSDPath);
201       if(!anOSDFile.Exists()) continue;
202 #ifdef WNT
203       aFile = new ifstream(aFullPath.ToCString(), ios::binary);
204 #else
205       aFile = new ifstream(aFullPath.ToCString());
206 #endif  
207     }
208     //Initialize 4 bytes of the buffer by 0
209     memset((aBuffer + aCurrentPos), 0, 4); 
210     //Copy the length of the file name to the buffer
211     memcpy((aBuffer + aCurrentPos), (aFileNameSize + i), ((sizeof(int) > 4) ? 4 : sizeof(int))); 
212     aCurrentPos += 4;
213
214     //Copy the file name to the buffer
215     memcpy((aBuffer + aCurrentPos), theFiles[i], aFileNameSize[i]);
216     aCurrentPos += aFileNameSize[i];
217     
218     if (!theNamesOnly) { // mpv 15.01.2003: we don't copy file content to the buffer if !theNamesOnly
219       //Initialize 8 bytes of the buffer by 0
220       memset((aBuffer + aCurrentPos), 0, 8); 
221       //Copy the length of the file to the buffer
222       memcpy((aBuffer + aCurrentPos), (aFileSize + i), ((sizeof(long) > 8) ? 8 : sizeof(long)));
223       aCurrentPos += 8;
224       
225       aFile->seekg(0, ios::beg);
226       aFile->read((char *)(aBuffer + aCurrentPos), aFileSize[i]);
227       aFile->close();
228       delete(aFile);
229       aCurrentPos += aFileSize[i];
230     }
231   }
232
233   delete[] aFileNameSize;
234   delete[] aFileSize;
235   
236   
237   CORBA::Octet* anOctetBuf =  (CORBA::Octet*)aBuffer;
238   
239   return (new SALOMEDS::TMPFile(aBufferSize, aBufferSize, anOctetBuf, 1));
240 }
241
242 //============================================================================
243 // function : PutStreamToFile
244 // purpose  : converts the stream "theStream" to the files
245 //============================================================================
246 SALOMEDS::ListOfFileNames_var 
247 SALOMEDS_Tool::PutStreamToFiles(const SALOMEDS::TMPFile& theStream,
248                                 const std::string& theToDirectory,
249                                 const int theNamesOnly)
250 {
251   if(theStream.length() == 0) 
252     return NULL;
253
254   //Get a temporary directory for saving a file
255   TCollection_AsciiString aTmpDir(const_cast<char*>(theToDirectory.c_str()));
256
257   unsigned char *aBuffer = (unsigned char*)theStream.NP_data();
258
259   if(aBuffer == NULL) return NULL;
260
261   long aFileSize, aCurrentPos = 4;
262   int i, aFileNameSize, aNbFiles = 0;
263
264   //Copy the number of files in the stream
265   memcpy(&aNbFiles, aBuffer, sizeof(int)); 
266
267   SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
268   aFiles->length(aNbFiles);
269
270   for(i=0; i<aNbFiles; i++) {
271
272     //Put a length of the file name to aFileNameSize
273     memcpy(&aFileNameSize, (aBuffer + aCurrentPos), ((sizeof(int) > 4) ? 4 : sizeof(int))); 
274     aCurrentPos += 4;
275
276     char *aFileName = new char[aFileNameSize];
277     //Put a file name to aFileName
278     memcpy(aFileName, (aBuffer + aCurrentPos), aFileNameSize); 
279     aCurrentPos += aFileNameSize;
280  
281     //Put a length of the file to aFileSize
282     if (!theNamesOnly) {
283       memcpy(&aFileSize, (aBuffer + aCurrentPos), ((sizeof(long) > 8) ? 8 : sizeof(long)));
284       aCurrentPos += 8;    
285       
286       TCollection_AsciiString aFullPath = aTmpDir + aFileName;
287       ofstream aFile(aFullPath.ToCString());
288       aFile.write((char *)(aBuffer+aCurrentPos), aFileSize); 
289       aFile.close();  
290       aCurrentPos += aFileSize;
291     }
292     aFiles[i] = CORBA::string_dup(aFileName);
293     delete[] aFileName;
294   }
295
296   return aFiles;
297 }
298
299 //============================================================================
300 // function : GetNameFromPath
301 // purpose  : Returns the name by the path
302 //============================================================================
303 std::string SALOMEDS_Tool::GetNameFromPath(const std::string& thePath) {
304   if(thePath == "") 
305     return "";
306   OSD_Path aPath = OSD_Path(TCollection_AsciiString(const_cast<char*>(thePath.c_str())));
307   TCollection_AsciiString aNameString(aPath.Name());
308   return aNameString.ToCString();
309 }
310
311 //============================================================================
312 // function : GetDirFromPath
313 // purpose  : Returns the dir by the path
314 //============================================================================
315 std::string SALOMEDS_Tool::GetDirFromPath(const std::string& thePath) {
316   if(thePath == "") 
317     return "";
318   OSD_Path aPath = OSD_Path(TCollection_AsciiString(const_cast<char*>(thePath.c_str())));
319   TCollection_AsciiString aDirString(aPath.Trek());
320   aDirString.ChangeAll('|','/');
321   return aDirString.ToCString();
322 }
323
324 //=======================================================================
325 // name    : GetFlag
326 // Purpose : Retrieve specified flaf from "AttributeFlags" attribute
327 //=======================================================================
328 bool SALOMEDS_Tool::GetFlag( const int             theFlag,
329                              SALOMEDS::Study_var   theStudy,
330                              SALOMEDS::SObject_var theObj )
331 {
332   SALOMEDS::GenericAttribute_var anAttr;
333   if ( !theObj->_is_nil() && theObj->FindAttribute( anAttr, "AttributeFlags" ) )
334   {
335     SALOMEDS::AttributeFlags_var aFlags = SALOMEDS::AttributeFlags::_narrow( anAttr );
336     return aFlags->Get( theFlag );
337   }
338
339   return false;
340 }
341
342 //=======================================================================
343 // name    : SetFlag
344 // Purpose : Set/Unset specified flaf from "AttributeFlags" attribute
345 //=======================================================================
346 bool SALOMEDS_Tool::SetFlag( const int           theFlag,
347                              SALOMEDS::Study_var theStudy,
348                              const std::string&  theEntry,
349                              const bool          theValue )
350 {
351   SALOMEDS::SObject_var anObj = theStudy->FindObjectID(theEntry.c_str());
352
353   if ( !anObj->_is_nil() )
354   {
355     SALOMEDS::GenericAttribute_var aGAttr;
356     if ( anObj->FindAttribute( aGAttr, "AttributeFlags" ) )
357     {
358       SALOMEDS::AttributeFlags_var anAttr = SALOMEDS::AttributeFlags::_narrow( aGAttr );
359       anAttr->Set( theFlag, theValue );
360     }
361     else if ( theValue )
362     {
363       SALOMEDS::StudyBuilder_var aBuilder = theStudy->NewBuilder();
364       SALOMEDS::AttributeFlags_var anAttr = SALOMEDS::AttributeFlags::_narrow(
365         aBuilder->FindOrCreateAttribute( anObj, "AttributeFlags" ) );
366       anAttr->Set( theFlag, theValue );
367     }
368     return true;
369   }
370
371   return false;
372 }
373
374 //=======================================================================
375 // name    : getAllChildren
376 // Purpose : Get all children of object.
377 //           If theObj is null all objects of study are returned
378 //=======================================================================
379 void SALOMEDS_Tool::GetAllChildren( SALOMEDS::Study_var               theStudy,
380                                     SALOMEDS::SObject_var             theObj,
381                                     std::list<SALOMEDS::SObject_var>& theList )
382 {
383   if ( theObj->_is_nil() )
384   {
385     SALOMEDS::SComponentIterator_var anIter = theStudy->NewComponentIterator();
386     for ( ; anIter->More(); anIter->Next() )
387     {
388       SALOMEDS::SObject_var anObj = SALOMEDS::SObject::_narrow( anIter->Value() );
389       if ( !anObj->_is_nil() )
390       {
391         theList.push_back( anObj );
392         GetAllChildren( theStudy, anObj, theList );
393       }
394     }
395   }
396   else
397   {
398     SALOMEDS::ChildIterator_var anIter = theStudy->NewChildIterator( theObj );
399     for ( ; anIter->More(); anIter->Next() )
400     {
401       SALOMEDS::SObject_var anObj = anIter->Value();
402       SALOMEDS::SObject_var aRef;
403       if ( !anObj->ReferencedObject( aRef ) )
404       {
405         theList.push_back( anObj );
406         GetAllChildren( theStudy, anObj, theList );
407       }
408     }
409   }
410 }
411
412
413