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