]> Creatis software - bbtk.git/blob - kernel/src/bbtkUtilities.h
Move some general usage methods to Utilities, to avoid dupplicate code :
[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/22 16:55:04 $
7   Version:   $Revision: 1.2 $
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 namespace bbtk
43 {
44   /// Holds various usefull methods 
45   struct BBTK_EXPORT Utilities
46   {
47    // See : http://www.techbytes.ca/techbyte103.html for more O.S.
48    static inline bool FileExists(std::string strFilename) 
49    {
50      struct stat stFileInfo;
51      bool blnReturn;
52      int intStat;
53
54      // Attempt to get the file attributes
55      intStat = stat(strFilename.c_str(),&stFileInfo);
56      if(intStat == 0) {
57        // We were able to get the file attributes
58        // so the file obviously exists.
59        blnReturn = true;
60      } else {
61        // We were not able to get the file attributes.
62        // This may mean that we don't have permission to
63        // access the folder which contains this file. If you
64        // need to do that level of checking, lookup the
65        // return values of stat which will give you
66        // more details on why stat failed.
67        blnReturn = false;
68      }
69
70      return(blnReturn);
71    }
72
73
74 // ===================================================================================
75
76   static std::string ExtractPackageName(const std::string  &name, 
77                                           std::string& path)
78   {
79     std::string pkgname;
80     path = "";
81
82     std::string::size_type slash_position = name.find_last_of("/\\");
83     if (slash_position != std::string::npos) 
84       {
85         pkgname = name.substr(slash_position+1,std::string::npos);   
86         path = name.substr(0,slash_position); 
87         //      std::cout << "F:P='"<<path<<"'"<<std::endl;//+1,std::string::npos); 
88       } 
89     else 
90       {
91         pkgname = name;  
92       }      
93           
94     // remove {.so | dll} if any
95     std::string::size_type dot_position = pkgname.find_last_of('.');      
96     if (dot_position != std::string::npos){
97       pkgname = pkgname.substr(0,dot_position);
98     }      
99 #if defined(__GNUC__)
100     
101     // GCC mechanism
102     // shared lib name = libbb<name>.so
103
104       // remove {libbb} if any
105     if (memcmp ( pkgname.c_str(), "libbb", 5) == 0) {
106       pkgname =  pkgname.substr(5, pkgname.length());
107     }
108       /*
109       /// \ \todo     what would happen if (stupid) user names his package 'libbb' ?!?
110       /// \ --> Should be forbidden!
111       */
112 #elif defined(_WIN32)
113
114        // WIN 32 mechanism
115        // shared lib name = <name>.dll
116
117      // remove {bb} if any
118     if (memcmp (pkgname.c_str(), "bb", 2) == 0) {
119        pkgname =  pkgname.substr(2, pkgname.length());  
120     } 
121          
122      /*
123      /// \ \todo     what would happen if (stupid) user names his package 'bb' ?!?
124      /// \ --> Should be forbidden!
125      */
126 #else
127     bbtkError("neither __GNUC__ nor _WIN32 ?!? How did you compile ?");
128 #endif      
129     return pkgname;
130   }
131
132 // ===================================================================================
133
134   static std::string ExtractScriptName(const std::string  &name)
135   {
136     std::string pkgname;
137
138     std::string::size_type slash_position = name.find_last_of("/\\");
139     if (slash_position != std::string::npos) {
140       pkgname =name.substr(slash_position+1,std::string::npos);
141     } else {
142       pkgname = name;
143     }
144     // remove {.bbs } if any
145     std::string::size_type dot_position = pkgname.find_last_of('.');
146     if (dot_position != std::string::npos){
147       pkgname = pkgname.substr(0,dot_position);
148     }
149     return pkgname;
150   }
151
152 // ===================================================================================
153
154   static std::string ExpandLibName(const std::string &name, bool verbose)
155   {
156      // -----   Think of expanding path name ( ./ ../ ../../ )
157
158     char buf[2048]; // for getcwd
159     char * currentDir = getcwd(buf, 2048);
160     std::string cwd(currentDir);
161     std::string libname(name);
162
163     // tooHigh : true is user supplies a library pathname with too many "../"
164     bool tooHigh = false;
165
166     if ( name[0] == '/' ||  name[0] == '\\' )
167     {
168       return(libname);
169     } 
170     else if  (name[0] == '.' && (name[1] == '/' || name[1] == '\\') ) 
171     {
172       libname = cwd  + ConfigurationFile::GetInstance().Get_file_separator () + name.substr(2, name.length());
173       return(libname);
174     } 
175     else if ( name[0] == '.' &&  name[1] == '.' && (name[2] == '/' || name[2] == '\\') ) 
176     {
177       if ( IsAtRoot(cwd) )  // hope it gets / (for Linux),  C: D: (for Windows)
178       {  
179      // if we are already at / or c: --> hopeless  
180          if (verbose)
181            std::cout << "   File path [" <<  name << "] doesn't exist" << std::endl;
182          tooHigh = true;
183       }
184       else
185       {
186          // iterate on ../ and go up from the current working dir!
187          std::string a(name); 
188          bool alreadyProcessRoot = false;
189          for(;;)
190          {
191             std::string::size_type slash_position = cwd.find_last_of(ConfigurationFile::GetInstance().Get_file_separator ());
192             if (slash_position != std::string::npos) {
193              if (slash_position == 0)
194                 slash_position = 1;
195               cwd = cwd.substr(0,slash_position/*+1*/);
196                  a = a.substr(3, name.length());  // remove ../
197               if (a == "" || alreadyProcessRoot)
198               {
199                 if (verbose)
200                   std::cout << "   File path [" <<  name << "] doesn't exist" << std::endl;
201                 tooHigh = true;
202                 break;
203               }
204              // std::string b = cwd + a;
205               libname =  cwd;
206               char c = cwd[cwd.size()-1];
207               if (c != '/' && c != '\\' )
208                 libname += ConfigurationFile::GetInstance().Get_file_separator ();
209               libname += a;
210
211               if ( a[0] != '.' ) // if . (probabely ../), loop again
212                 break;
213
214               if (IsAtRoot(cwd))
215                 alreadyProcessRoot = true;
216             }
217          } // end iterating on ../
218       }
219       if (tooHigh)
220          libname="";
221       return (libname);
222
223     }  // -----   End of expanding path name   ( ./ ../ ../../ )
224
225     // To avoid warning
226     return(""); // Will never get here!
227   }
228
229 // ===================================================================================
230
231   static std::string MakeLibnameFromPath(std::string path, std::string pkgname)
232   {
233     std::string libname = path;
234     char c = path[path.size()-1];    
235 #if defined(__GNUC__)
236        if (c != '/')
237           libname += "/libbb";
238        libname += pkgname;
239        libname += ".so";
240          
241 #elif defined(_WIN32)
242        if (c != '\\')
243           libname = path+"\\bb";
244        libname += pkgname;
245        libname += ".dll";
246 #endif
247     return libname;    
248   }
249
250 // ===================================================================================
251
252   static inline std::string MakePkgnameFromPath(std::string path, std::string pkgname)
253   {
254     std::string libname = path;
255          char c = path[path.size()-1];
256          if (c != '/' && c != '\\')
257             libname +=  ConfigurationFile::GetInstance().Get_file_separator ();
258          libname += pkgname;
259          libname += ".bbs";
260     return libname;
261   }
262
263 // ===================================================================================
264
265  static inline  bool IsAtRoot(std::string cwd)
266   {
267     if ( cwd == "/"                             // hope it gets /     (for Linux)
268         || (cwd.size() <= 3 && cwd[1] == ':') ) // hope it gets C: D: (for Windows)
269       return (true);
270     else
271       return(false);
272 }
273
274 // ===================================================================================
275
276     static inline void SplitAroundFirstDot( const std::string& in,
277                                             std::string& left,
278                                             std::string& right)
279    {
280       std::string delimiter = ".";
281       std::string::size_type pos = in.find_first_of(delimiter);
282       if (std::string::npos != pos) 
283       {
284         left = in.substr(0,pos);
285         right = in.substr(pos+1,in.size());
286
287       }
288       /*
289       else
290       {
291         bbtkError(in<<" : expected 'a.b' format but no dot found");
292       }
293       */
294       left ="";
295       right = "";
296     }
297
298     static inline std::string get_file_name(const std::string& s) 
299     { 
300       std::string::size_type slash_position = s.find_last_of("/\\");
301       if (slash_position != std::string::npos) 
302       {
303         return  s.substr(slash_position+1,std::string::npos);   
304       }
305       else 
306       {
307         return s;
308       }
309     }
310
311
312   //========================================================================
313     // Usefull functions for html generation
314    
315     //========================================================================
316     static inline void replace( std::string& str,
317                                 const std::string& from, 
318                                 const std::string& to )
319     {
320       using std::string;
321       string::size_type pos = str.find( from );
322       while ( pos != string::npos )
323       {
324         str.replace( pos, from.size(), to );
325         pos = str.find( from, pos+from.size()-1 );
326       } 
327     }
328     //========================================================================
329
330     //========================================================================
331     static inline void html_format(std::string& str)
332     {
333       replace( str, "&", "&amp;" );
334       replace( str, "<", "&lt;" );
335       replace( str, ">", "&gt;" );
336     }
337     //========================================================================
338
339   };
340
341 } // namespace bbtk
342  
343 #endif //#ifndef __bbtkUtilities_h_INCLUDED__
344 //EOF