]> Creatis software - bbtk.git/blob - kernel/src/bbtkConfigurationFile.cxx
Recreated the complete cvs tree because the project architecture deeply changed
[bbtk.git] / kernel / src / bbtkConfigurationFile.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   bbtk
4   Module:    $RCSfile: bbtkConfigurationFile.cxx,v $
5   Language:  C++
6   Date:      $Date: 2008/01/22 15:02:00 $
7   Version:   $Revision: 1.1.1.1 $
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  *\file
20  *\brief Class bbtk::ConfigurationFile
21  */
22
23 #include "bbtkConfigurationFile.h"
24 #include "bbtkMessageManager.h"
25 //#include "xmlParser.h"
26 #include <sys/stat.h> // for struct stat stFileInfo
27
28 #if defined(WIN32)
29 #include <direct.h> // for getcwd
30 #endif
31
32 namespace bbtk
33 {
34 /// Constructor
35 ConfigurationFile::ConfigurationFile()
36 {
37    char *execPath = GetExecutablePath();
38
39  #if defined(WIN32)
40    std::string slash("\\");
41  #else
42    std::string slash("/");
43  #endif
44  
45 // ==> First we look for bbtk_config.xml in "."
46
47    char buf[2048];
48    const char *currentDir = getcwd(buf, 2048);
49      
50    if( !currentDir )
51    {
52       std::cerr << "Path was too long to fit on 2048 bytes ?!?" << std::endl;
53       /// \todo : what else?
54       // How abort a constructor and warn the caller function?
55    }
56
57    std::string configXmlFullPathName = currentDir + slash + "bbtk_config.xml";
58
59    if ( FileExists( configXmlFullPathName ))
60    {
61       bbtkMessage("Config",1, "ConfigurationFile : [" << configXmlFullPathName << 
62             "] found in current directory" << std::endl); 
63       //Read(configXmlFullPathName.c_str());
64       // traiter le fichier local     
65    }
66
67 // ==> Then we look for bbtk_config.xml in ".bbtk"
68    else 
69    {
70    #if defined(__GNUC__)
71       std::string str_home(getenv("HOME"));
72    #elif defined(_WIN32)
73       std::string str_home(getenv("USERPROFILE"));
74    #endif
75       configXmlFullPathName = str_home + slash + ".bbtk/bbtk_config.xml";
76       if (!FileExists( configXmlFullPathName ))
77       {         
78          // ==> Nothing found, we create bbtk_config.xml in ".bbtk"
79          InstallPath ();
80       }
81    }
82
83 // In any case, deal with bbtk_config.xml!
84    Read(configXmlFullPathName.c_str());
85 }
86
87 /// Destructor
88 ConfigurationFile::~ConfigurationFile()
89 {
90 }
91
92 // See : http://www.techbytes.ca/techbyte103.html for more O.S.
93 bool ConfigurationFile::FileExists(std::string strFilename) {
94   struct stat stFileInfo;
95   bool blnReturn;
96   int intStat;
97
98   // Attempt to get the file attributes
99   intStat = stat(strFilename.c_str(),&stFileInfo);
100   if(intStat == 0) {
101     // We were able to get the file attributes
102     // so the file obviously exists.
103     blnReturn = true;
104   } else {
105     // We were not able to get the file attributes.
106     // This may mean that we don't have permission to
107     // access the folder which contains this file. If you
108     // need to do that level of checking, lookup the
109     // return values of stat which will give you
110     // more details on why stat failed.
111     blnReturn = false;
112   }
113
114   return(blnReturn);
115 }
116
117
118 void ConfigurationFile::CreateConfigXML( char *rootDirectory )
119 {
120    FILE *fp;
121    char configXml[250];
122    sprintf (configXml , "%s/bbtk_config.xml", rootDirectory);
123    bbtkMessage("Config",1, "in CreateConfigXML[" << configXml << "]" << std::endl);
124    fp = fopen (configXml, "w");
125    fprintf(fp, "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n");
126    fprintf(fp, "<!DOCTYPE config SYSTEM \"/mnt/windows/bbtk/bbtk_config.xml>\n");
127    fprintf(fp, "<config>\n");
128    fprintf(fp, "   <description>  </description>\n");
129    fprintf(fp, "   <url>  http://www.creatis.insa-lyon.fr/software/bbtk  </url>\n");
130    fprintf(fp, "   <install_path> </install_path>\n");
131    fprintf(fp, "   <bbs_path>     </bbs_path>\n");
132   // fprintf(fp, "   <ext_dll_path> </ext_dll_path>\n");
133    fprintf(fp, "   <package_path> </package_path>\n");
134    fprintf(fp, "   <data_path> %s </data_path>\n", BBTK_DATA_PATH);
135    /// \todo find a decent default value !
136    ///fprintf(fp, "   <default_doc_tmp>  %s </default_doc_tmp>\n", " ");
137    // when $ will be found, default_doc_tmp value will be replaced
138    fprintf(fp, "   <default_doc_tmp>$</default_doc_tmp>\n");
139    fprintf(fp, "</config>\n");
140    fclose(fp);
141 }
142
143 char *ConfigurationFile::GetExecutablePath()
144 {
145     /// \todo : Think to delete it!
146     char *buf = (char *)malloc(512);
147     char *slash;
148
149 #if defined(WIN32)
150     GetModuleFileName(NULL, buf, 511);
151     slash = strrchr(buf, '\\');
152     if (slash)
153     {
154         *slash = 0;
155     }
156 #elif defined(__GNUC__)
157     int res;
158     res = readlink("/proc/self/exe", buf, 512);
159     if (res == -1)
160         return "";
161     buf[res] = 0;
162     slash = strrchr(buf, '/');
163     if (slash)
164     {
165         *slash = 0;
166     }
167 #else
168     return "";
169 #endif
170
171     return buf;
172 }
173
174
175
176 void ConfigurationFile::InstallPath ()
177 {
178
179 /*--------------------------------------------------
180 New policy for bbtk_config.xml :
181
182 if bbtk_config.xml found in current directory (user is an aware user!)
183    use it!
184    
185 else if bbtk_config.xml found in HOME/.bbtk (user already worked with it)
186    use it!
187    
188 else if bbtk_config.xml.tmp found in /usr/local/bin or c:\\Program Files\\BBTK\\bin
189    copy it as .bbtk/bbtk_config.xml
190    
191 else (nothing installed)
192    create a minimum version in HOME/.bbtk
193 ----------------------------------------------------*/
194
195
196 // -----------------------------------------------------------------
197 #if defined(__GNUC__)
198
199 // ------------------ create some usefull strings ----------------
200 // installed bbtk_path
201   char bbtk_path[100];
202   strcpy(bbtk_path, "/usr/local/bin");
203        
204 // rootDirectory
205   char rootDirectory[200];
206   sprintf( rootDirectory,  "%s/.bbtk", getenv("HOME"));
207       
208 // configPath
209   char configPath[200];
210   sprintf(configPath, "%s/bbtk_config.xml",rootDirectory);
211   
212 // makeDir
213   char makeDir[250];
214   sprintf( makeDir, "mkdir \"%s\" ", rootDirectory);
215
216 // configXmlTmp
217   char configXmlTmp[250]; 
218   sprintf(configXmlTmp, "%s/bbtk_config.xml.tmp", bbtk_path);
219
220 // copyFile
221   char copyFile[250];
222
223   if (!FileExists(configXmlTmp)) // bbtk_config.xml.tmp not found (not installed)
224   {  
225      if (!FileExists(rootDirectory)) // .bbtk not found
226      {
227        system(makeDir);  // create .bbtk
228      }
229
230      // if "bbtk_path/bbtk_config.xml.tmp" doesn't exist, hard-create a minimum version in .bbtk
231      CreateConfigXML( rootDirectory );// create .bbtk
232   }
233   else
234   {
235      sprintf(copyFile,"cp %s  %s/bbtk_config.xml ",configXmlTmp,rootDirectory );
236      if (!FileExists(rootDirectory))
237      {
238        //std::cout << "makeDir[" << makeDir << "]" << std::endl;
239        system(makeDir);
240      }
241
242      if (!FileExists(configPath))
243      {
244        system(copyFile);
245      }
246   }
247   return;
248    
249 // ------------------------------------------------------------------
250 #elif defined(WIN32)
251
252
253 // installed bbtk_path
254   char bbtk_path[100];
255   strcpy(bbtk_path, "\"c:\\Program Files\\BBTK\\bin\"");
256   char bbtk_path2[100];
257   strcpy(bbtk_path2, "c:\\Program Files\\BBTK\\bin");
258
259 // rootDirectory
260   char rootDirectory[200];  
261   sprintf(rootDirectory, "%s\\.bbtk",getenv("USERPROFILE"));
262   //  std::cout << "[" << rootDirectory << "]" << std::endl;
263     
264 // configPath
265   char configPath[200];
266   sprintf(configPath, "%s\\bbtk_config.xml",rootDirectory);
267     
268 // makeDir
269   char makeDir[250];
270   sprintf( makeDir, "mkdir \"%s\" ", rootDirectory);
271
272 // configXmlTmp
273   char configXmlTmp[250]; 
274   sprintf(configXmlTmp, "%s\\bbtk_config.xml.tmp", bbtk_path2);
275     
276 // copyFile
277   char copyFile[250];
278   
279   if (!FileExists(configXmlTmp)) // bbtk_config.xml.tmp not found
280   {
281      if (!FileExists(rootDirectory)) // .bbtk not found
282      {
283        system(makeDir);  // create .bbtk
284      }
285      
286      // if "bbtk_path/bbtk_config.xml.tmp" doesn't exist, hard-create a minimum version in .bbtk
287      CreateConfigXML( rootDirectory );// create .bbtk
288      return;
289   }  
290   
291   sprintf(copyFile,"copy %s\\bbtk_config.xml.tmp \"%s\"\\bbtk_config.xml ",bbtk_path,rootDirectory );
292     
293   int attribs = GetFileAttributes (rootDirectory);
294   bbtkMessage("Config",1,std::hex << attribs << " " << FILE_ATTRIBUTE_DIRECTORY << std::endl);
295   if ( attribs != 0xFFFFFFFF){
296     if ((attribs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY ) /// \TODO : check !
297     {
298       if ( GetFileAttributes( configPath ) == 0xFFFFFFFF)
299       {
300          system(copyFile);  
301       } 
302     }
303   } else {
304     system(makeDir);
305     system(copyFile); 
306   }    
307   return;  
308 // ------------------------------------------------------------------    
309 #else
310 /// \todo  ConfigurationFile::InstallPath() : exit when for not WIN32 and not__GNUC__
311
312   return;    
313 #endif
314
315 }
316
317 void ConfigurationFile::GetTextOrClear(const XMLNode& node, std::string& var)
318 {
319   if (node.nText()>0) 
320     {
321       var = node.getText();
322     }
323   else if (node.nClear()>0) 
324     {
325       var = node.getClear().lpszValue;
326     }
327   else 
328     {
329       std::string mess("Error : element <");
330       mess += node.getName();
331       mess += "> : no text nor <PRE></PRE> clear tag found";
332     }
333 }
334
335
336 // Gets the list of directories holding bb scripts, packages, dll, ... from the xml file
337 //      bbtk_config.xml
338
339 void ConfigurationFile::Read(const std::string& filename)
340 {
341
342   //std::cout << "=======================in  ConfigurationFile::Read filename [" <<filename << "]" << std::endl;
343   
344   mConfig_xml_full_path = filename;
345   XMLResults* res = new XMLResults;
346   XMLNode BB = XMLNode::parseFile((XMLCSTR)filename.c_str(),(XMLCSTR)"config",res);
347
348   if ( res->error != eXMLErrorNone ) 
349     {
350       std::ostringstream str;
351       str << XMLNode::getError(res->error);
352       str << " [line " << res->nLine << ", col "<<res->nColumn<<"] ";
353       str << " file "<<filename; 
354       delete res;
355       bbtkError(str.str());
356 //      throw ConfigurationException(str.str());
357     }
358   delete res;
359
360   int i,j;
361
362   // Description
363   for (i=0,j=0; i<BB.nChildNode((XMLCSTR)"description"); i++) 
364     {
365       std::string val;
366       GetTextOrClear(BB.getChildNode((XMLCSTR)"description",&j),val);
367       mDescription += val;
368     }    
369
370   // Url
371   if( BB.nChildNode((XMLCSTR)"url") ) 
372      GetTextOrClear(BB.getChildNode((XMLCSTR)"url"),mUrl);
373
374   // Data_Path
375   if( BB.nChildNode((XMLCSTR)"data_path") ) 
376      GetTextOrClear(BB.getChildNode((XMLCSTR)"data_path"),mData_path);
377
378   // install_path
379   if( BB.nChildNode((XMLCSTR)"install_path") )
380      GetTextOrClear(BB.getChildNode((XMLCSTR)"install_path"),mInstall_path);
381
382   // always add "." (current working directory) at the begining
383
384   // bbs_paths
385   mBbs_paths.push_back("."); 
386   for (i=0,j=0; i<BB.nChildNode((XMLCSTR)"bbs_path"); i++) 
387     {
388       std::string val;
389       GetTextOrClear(BB.getChildNode((XMLCSTR)"bbs_path",&j),val);
390       mBbs_paths.push_back(val);
391     }
392
393   // package_paths
394   mPackage_paths.push_back(".");   
395   for (i=0,j=0; i<BB.nChildNode((XMLCSTR)"package_path"); i++) 
396     {
397       std::string val;
398       GetTextOrClear(BB.getChildNode((XMLCSTR)"package_path",&j),val);
399       mPackage_paths.push_back(val);
400     }
401
402   // default_doc_tmp
403   if( BB.nChildNode((XMLCSTR)"default_doc_tmp") ) 
404      GetTextOrClear(BB.getChildNode((XMLCSTR)"default_doc_tmp"),mDefault_doc_tmp);
405
406   if ( mDefault_doc_tmp == "$") // no value found in config_xml
407   {
408      size_t pos = mConfig_xml_full_path.find("bbtk_config.xml");
409      mDefault_doc_tmp = mConfig_xml_full_path.substr (0,pos); 
410   }    
411   // file separator
412   #if defined(_WIN32)
413      mFile_separator = "\\";
414   #else
415      mFile_separator = "/";
416   #endif
417 }
418
419
420 } // namespace bbtk