]> Creatis software - bbtk.git/blob - kernel/src/bbtkUtilities.h
*** empty log message ***
[bbtk.git] / kernel / src / bbtkUtilities.h
1 /*=========================================================================
2                                                                                 
3   Program:   bbtk
4   Module:    $RCSfile: bbtkUtilities.h,v $
5   Language:  C++
6   Date:      $Date: 2008/01/28 15:08:53 $
7   Version:   $Revision: 1.5 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See doc/license.txt or
11   http://www.creatis.insa-lyon.fr/Public/bbtk/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19
20 /**
21  *  \file 
22  *  \brief struct bbtk::Utilities : various usefull methods 
23  */
24
25 /**
26  * \class bbtk::Utilities
27  * \brief various usefull methods 
28  */
29  
30 #ifndef __bbtkUtilities_h_INCLUDED__
31 #define __bbtkUtilities_h_INCLUDED__
32
33 #include "bbtkConfigurationFile.h"
34 #include "bbtkSystem.h"
35 #include <string>
36 #include <sys/stat.h>
37 #ifdef CMAKE_HAVE_TERMIOS_H
38 #include <termios.h>
39 #define BBTK_USE_TERMIOS_BASED_PROMPT
40 #endif
41
42 //#include "bbtkMessageManager.h"
43
44 namespace bbtk
45 {
46   /// Holds various usefull methods 
47   struct BBTK_EXPORT Utilities
48   {
49   
50
51 // ===================================================================================
52  
53    // See : http://www.techbytes.ca/techbyte103.html for more O.S.
54    static inline bool FileExists(std::string strFilename) 
55    {
56      struct stat stFileInfo;
57      bool blnReturn;
58      int intStat;
59
60      // Attempt to get the file attributes
61      intStat = stat(strFilename.c_str(),&stFileInfo);
62      if(intStat == 0) {
63        // We were able to get the file attributes
64        // so the file obviously exists.
65        blnReturn = true;
66      } else {
67        // We were not able to get the file attributes.
68        // This may mean that we don't have permission to
69        // access the folder which contains this file. If you
70        // need to do that level of checking, lookup the
71        // return values of stat which will give you
72        // more details on why stat failed.
73        blnReturn = false;
74      }
75
76      return(blnReturn);
77    }
78
79
80 // ===================================================================================
81
82   static std::string ExtractPackageName(const std::string  &name, 
83                                           std::string& path)
84   {
85     std::string pkgname;
86     path = "";
87
88     std::string::size_type slash_position = name.find_last_of("/\\");
89     if (slash_position != std::string::npos) 
90     {
91            pkgname = name.substr(slash_position+1,std::string::npos);
92            path = name.substr(0,slash_position);
93            //   std::cout << "F:P='"<<path<<"'"<<std::endl;//+1,std::string::npos);
94     }
95     else 
96     {
97            pkgname = name;
98     }
99     
100     // remove {.so | dll} if any
101     std::string::size_type dot_position = pkgname.find_last_of('.');      
102     if (dot_position != std::string::npos){
103       pkgname = pkgname.substr(0,dot_position);
104     }      
105 #if defined(__GNUC__)
106
107     // GCC mechanism
108     // shared lib name = libbb<name>.so
109
110       // remove {libbb} if any
111     if (memcmp ( pkgname.c_str(), "libbb", 5) == 0) {
112       pkgname =  pkgname.substr(5, pkgname.length());
113     }
114       /*
115       /// \ \todo     what would happen if (stupid) user names his package 'libbb' ?!?
116       /// \ --> Should be forbidden!
117       */
118 #elif defined(_WIN32)
119
120        // WIN 32 mechanism
121        // shared lib name = <name>.dll
122
123      // remove {bb} if any
124     if (memcmp (pkgname.c_str(), "bb", 2) == 0) {
125        pkgname =  pkgname.substr(2, pkgname.length());  
126     }
127
128      /*
129      /// \ \todo     what would happen if (stupid) user names his package 'bb' ?!?
130      /// \ --> Should be forbidden!
131      */
132 #else
133     bbtkError("neither __GNUC__ nor _WIN32 ?!? How did you compile ?");
134 #endif      
135     return pkgname;
136   }
137
138 // ===================================================================================
139
140   static std::string ExtractScriptName(const std::string  &name)
141   {
142     std::string pkgname;
143
144     std::string::size_type slash_position = name.find_last_of("/\\");
145     if (slash_position != std::string::npos) {
146       pkgname =name.substr(slash_position+1,std::string::npos);
147     } else {
148       pkgname = name;
149     }
150     // remove {.bbs } if any
151     std::string::size_type dot_position = pkgname.find_last_of('.');
152     if (dot_position != std::string::npos){
153       pkgname = pkgname.substr(0,dot_position);
154     }
155     return pkgname;
156   }
157
158 // ===================================================================================
159
160   static std::string ExpandLibName(const std::string &name, bool verbose)
161   {
162      // -----   Think of expanding path name ( ./ ../ ../../ )
163
164     char buf[2048]; // for getcwd
165     char * currentDir = getcwd(buf, 2048);
166     std::string cwd(currentDir);
167     std::string libname(name);
168     std::string fileSeparator;
169     fileSeparator = ConfigurationFile::GetInstance().Get_file_separator();
170     // tooHigh : true is user supplies a library pathname with too many "../"
171     bool tooHigh = false;
172     
173 //std::cout << "------------------cwd ["  << cwd << "]" << std::endl;
174  
175     if ( name[0] == '/' ||  name[0] == '\\' )
176     {
177       return(libname);
178     }
179     else if  ( name =="." )
180     {
181       libname = cwd  + fileSeparator;
182       return(libname);
183     }
184     else if  (name[0] == '.' && (name[1] == '/' || name[1] == '\\') )
185     {
186       libname = cwd  + fileSeparator + name.substr(2, name.length());
187       return(libname);
188     }
189     else if ( name[0] == '.' &&  name[1] == '.' /*  && (name[2] == '/' || name[2] == '\\') */ ) 
190     {
191       if ( IsAtRoot(cwd) )  // hope it gets / (for Linux),  C: D: (for Windows)
192       {  
193      // if we are already at / or c: --> hopeless  
194          if (verbose)
195            std::cout << "   File path [" <<  name << "] doesn't exist" << std::endl;
196          tooHigh = true;
197       }
198       else
199       {
200          // iterate on ../ and go up from the current working dir!
201          std::string a(name); 
202          bool alreadyProcessRoot = false;
203
204           //if (a[a.size()-1] != fileSeparator[0])
205           //   a.append(fileSeparator);
206 //std::cout << "------------------a ["  << a << "]" << std::endl;
207
208          for(;;)  // wild loop !
209          {
210             std::string::size_type slash_position = cwd.find_last_of(fileSeparator);
211             if (slash_position != std::string::npos) {
212              if (slash_position == 0)
213                 slash_position = 1;
214               cwd = cwd.substr(0,slash_position/*+1*/);
215 //std::cout << "------------------cwd ["  << cwd << "]" << std::endl;
216             //  if (a == "..") {
217             //    a = "";
218             //    break;
219             //   }
220             //   else
221                  a = a.substr(3, /*name.length()*/ a.length());  // remove ../
222 //std::cout << "------------------a ["  << a << "]" << std::endl;  
223               if (a == "" || alreadyProcessRoot)
224               {
225                 if (verbose)
226                   std::cout << "   File path : [" <<  name << "] doesn't exist" << std::endl;
227                 tooHigh = true;
228                 break;
229               }
230              // std::string b = cwd + a;
231               libname =  cwd;
232               char c = cwd[cwd.size()-1];
233               if (c != '/' && c != '\\' )
234                 libname += fileSeparator;
235               libname += a;
236
237               if ( a[0] != '.' ) // if . (probabely ../), loop again
238                 break;
239
240               if (IsAtRoot(cwd))
241                 alreadyProcessRoot = true;
242             }
243          } // end iterating on ../
244       }
245 //std::cout << "------------------out of loop]" << std::endl;        
246       if (tooHigh)
247          libname="";
248       return (libname);
249
250     }  // -----   End of expanding path name   ( ./ ../ ../../ )
251
252     std::cout <<"* ERROR in ExpandLibName : should never get here!" << std::endl;
253     // To avoid warning
254     return(""); // Will never get here!
255   }
256
257 // ===================================================================================
258
259   static std::string MakeLibnameFromPath(std::string path, std::string pkgname)
260   {
261     std::string libname = path;
262     char c = path[path.size()-1];    
263 #if defined(__GNUC__)
264        if (c != '/')
265           libname += "/libbb";
266        else
267           libname += "libbb";
268        libname += pkgname;
269        libname += ".so";
270          
271 #elif defined(_WIN32)
272        if (c != '\\')
273           libname = path+"\\bb";
274        libname += pkgname;
275        libname += ".dll";
276 #endif
277     return libname;    
278   }
279
280 // ===================================================================================
281
282   static inline std::string MakePkgnameFromPath(std::string path, std::string pkgname)
283   {
284     std::string libname = path;
285          char c = path[path.size()-1];
286          if (c != '/' && c != '\\')
287             libname +=  ConfigurationFile::GetInstance().Get_file_separator ();
288          libname += pkgname;
289     int l = libname.size();
290       if (l>4) 
291       {       
292          if (libname.substr(l-4, 4) != ".bbs")
293          {
294             libname = libname + ".bbs";    
295          }
296 }
297     return libname;
298   }
299
300 // ===================================================================================
301
302  static inline  bool IsAtRoot(std::string cwd)
303   {
304     if ( cwd == "/"                             // hope it gets /     (for Linux)
305         || (cwd.size() <= 3 && cwd[1] == ':') ) // hope it gets C: D: (for Windows)
306       return (true);
307     else
308       return(false);
309 }
310
311
312 // ===================================================================================
313
314     static inline void SplitAroundFirstDot( const std::string& in,
315                                             std::string& left,
316                                             std::string& right)
317    {
318       std::string delimiter = ".";
319       std::string::size_type pos = in.find_first_of(delimiter);
320       if (std::string::npos != pos) 
321       {
322         left = in.substr(0,pos);
323         right = in.substr(pos+1,in.size());
324
325       }
326       else
327       {
328              // bbtkError(in<<" : expected 'a.b' format but no dot found");
329              left ="";
330              right = "";
331       }
332     }
333
334 // ===================================================================================
335
336     static inline std::string get_file_name(const std::string& s) 
337     { 
338       std::string::size_type slash_position = s.find_last_of("/\\");
339       if (slash_position != std::string::npos) 
340       {
341         return  s.substr(slash_position+1,std::string::npos);   
342       }
343       else 
344       {
345         return s;
346       }
347     }
348
349
350   //========================================================================
351   // Usefull functions for html generation
352   //========================================================================
353
354     static inline void replace( std::string& str,
355                                 const std::string& from, 
356                                 const std::string& to )
357     {
358       using std::string;
359       string::size_type pos = str.find( from );
360       while ( pos != string::npos )
361       {
362         str.replace( pos, from.size(), to );
363         pos = str.find( from, pos+from.size()-1 );
364       } 
365     }
366     //========================================================================
367
368     static inline void html_format(std::string& str)
369     {
370       replace( str, "&", "&amp;" );
371       replace( str, "<", "&lt;" );
372       replace( str, ">", "&gt;" );
373     }
374     //========================================================================
375
376   };
377
378 } // namespace bbtk
379  
380 #endif //#ifndef __bbtkUtilities_h_INCLUDED__
381 //EOF