]> Creatis software - bbtk.git/blob - kernel/src/bbtkConfigurationFile.cxx
BUG HTML in windows + Cast float int
[bbtk.git] / kernel / src / bbtkConfigurationFile.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   bbtk
4   Module:    $RCSfile: bbtkConfigurationFile.cxx,v $
5   Language:  C++
6   Date:      $Date: 2008/02/21 09:37:23 $
7   Version:   $Revision: 1.10 $
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 "bbtkXML.h"
26 #include "bbtkUtilities.h"
27
28 #if defined(WIN32)
29 #include <direct.h> // for getcwd
30 #endif
31
32 namespace bbtk
33 {
34
35   //====================================================================
36   /// Constructor
37   ConfigurationFile::ConfigurationFile()
38   {
39     // file separator
40 #if defined(_WIN32)
41     mFile_separator = "\\";
42 #else
43     mFile_separator = "/";
44 #endif
45     
46     // ==> Set system paths 
47     mBin_path = GetExecutablePath();
48     mInstall_path = mBin_path + mFile_separator + "..";
49     // The relative path to the doc folder (=BBTK_DOC_REL_PATH)
50     mDoc_rel_path = BBTK_STRINGIFY_SYMBOL(BBTK_DOC_REL_PATH);
51     mDoc_rel_path = BBTK_STRINGIFY_SYMBOL(doc);
52     // The path to the doc folder (=mInstall_path+"/"+mDoc_rel_path)
53     mDoc_path = mInstall_path + mFile_separator + mDoc_rel_path;
54     // The relative path to the doc folder (=BBTK_BBS_REL_PATH)
55     mBbs_rel_path = BBTK_STRINGIFY_SYMBOL(BBTK_BBS_REL_PATH);
56     // The path to the bbs folder (=mInstall_path+"/"+mBbs_rel_path)
57     mBbs_path = mInstall_path + mFile_separator + mBbs_rel_path;
58     // The relative path to the rsc folder (=BBTK_RSC_REL_PATH)
59     //   mRsc_rel_path = BBTK_STRINGIFY_SYMBOL(BBTK_RSC_REL_PATH);
60     // The path to the rsc folder (=mInstall_path+"/"+mRsc_rel_path)
61     //   mRsc_path = mInstall_path + mFile_separator + mRsc_rel_path;
62     // The path to the bbtk data folder 
63     // Initialized to mInstall_path+"/"+BBTK_DATA_REL_PATH
64     // But can be overriden by value read from bbtk_config.xml
65     mData_path = mInstall_path + mFile_separator + BBTK_STRINGIFY_SYMBOL(BBTK_DATA_REL_PATH);
66
67     bbtkMessage("Config",1," ==> bin    : '"<<mBin_path<<"'"<<std::endl);
68     bbtkMessage("Config",1," ==> prefix : '"<<mInstall_path<<"'"<<std::endl);
69     bbtkMessage("Config",1," ==> doc    : '"<<mDoc_path<<"'"<<std::endl);
70     bbtkMessage("Config",1," ==> bbs    : '"<<mBbs_path<<"'"<<std::endl);
71     //   bbtkMessage("Config",1," ==> rsc    : '"<<mRsc_path<<"'"<<std::endl);
72     bbtkMessage("Config",1," ==> data   : '"<<mData_path<<"'"<<std::endl);
73     
74     
75     // bbs_paths
76     // always add "." (current working directory) at the begining
77     mBbs_paths.push_back("."); 
78     // add system bbs path 
79 #ifdef WIN32
80 //EED for windows BUILD tree
81     mBbs_paths.push_back(mInstall_path + mFile_separator + ".." + mFile_separator + mBbs_rel_path);
82 #endif
83     mBbs_paths.push_back(mBbs_path);
84
85     
86     // always add "." (current working directory) at the begining
87     mPackage_paths.push_back(".");   
88     // add system bin path (for build tree / standalone folder install)
89     mPackage_paths.push_back(mBin_path);
90     // add system lib path (for install tree)
91     mPackage_paths.push_back(mInstall_path + mFile_separator + "lib");
92 #ifdef WIN32
93     // add bin/Debug bin/Release paths (for build/install tree)
94     mPackage_paths.push_back(mBin_path + mFile_separator + "Debug");
95     mPackage_paths.push_back(mBin_path + mFile_separator + "Release");
96 #endif
97     
98     GetHelp(2);
99    
100     // ==> First we look for bbtk_config.xml in "."
101     char buf[2048];
102     const char *currentDir = getcwd(buf, 2048);
103     
104     if( !currentDir )
105       {
106         std::cerr << "Path was too long to fit on 2048 bytes ?!?" << std::endl;
107         // \todo : what else?
108         // How abort a constructor and warn the caller function?
109         // LG : throw an exception 
110       }
111     
112     std::string configXmlFullPathName = currentDir + mFile_separator + "bbtk_config.xml";
113     
114     if ( Utilities::FileExists( configXmlFullPathName ))
115       {
116         bbtkMessage("Config",1, "ConfigurationFile : [" << configXmlFullPathName << 
117                     "] found in current directory" << std::endl); 
118         //Read(configXmlFullPathName.c_str());
119         // traiter le fichier local     
120       }
121     
122     // ==> Then we look for bbtk_config.xml in ".bbtk"
123     else 
124       {
125 #if defined(__GNUC__)
126         std::string str_home(getenv("HOME"));
127 #elif defined(_WIN32)
128         std::string str_home(getenv("USERPROFILE"));
129 #endif
130         configXmlFullPathName = str_home + mFile_separator + ".bbtk/bbtk_config.xml";
131         if (!Utilities::FileExists( configXmlFullPathName ))
132           {         
133             // ==> Nothing found, we create bbtk_config.xml in ".bbtk"
134             InstallPath ();
135           }
136       }
137     
138     // In any case, deal with bbtk_config.xml!
139     Read(configXmlFullPathName.c_str());
140   }
141   //=========================================================================
142
143   //=========================================================================
144   /// Destructor
145   ConfigurationFile::~ConfigurationFile()
146   {
147   }
148   //=========================================================================
149   
150
151
152
153   //=========================================================================
154   void ConfigurationFile::CreateConfigXML( char *rootDirectory )
155   {
156     FILE *fp;
157     char configXml[250];
158     sprintf (configXml , "%s/bbtk_config.xml", rootDirectory);
159     bbtkMessage("Config",1, "in CreateConfigXML[" << configXml << "]" << std::endl);
160     fp = fopen (configXml, "w");
161     fprintf(fp, "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n");
162     //  fprintf(fp, "<!DOCTYPE config SYSTEM \"/mnt/windows/bbtk/bbtk_config.xml>\n");
163     fprintf(fp, "<config>\n");
164     fprintf(fp, "   <description>  </description>\n");
165     //   fprintf(fp, "   <url>  http://www.creatis.insa-lyon.fr/software/bbtk  </url>\n");
166     //  fprintf(fp, "   <install_path> </install_path>\n");
167     fprintf(fp, "   <bbs_path>     </bbs_path>\n");
168     // fprintf(fp, "   <ext_dll_path> </ext_dll_path>\n");
169     fprintf(fp, "   <package_path> </package_path>\n");
170     fprintf(fp, "   <data_path> </data_path>\n");//, BBTK_DATA_PATH);
171     /// \todo find a decent default value !
172       ///fprintf(fp, "   <default_temp_dir>  %s </default_temp_dir>\n", " ");
173       // when $ will be found, default_temp_dir value will be replaced
174       fprintf(fp, "   <default_temp_dir>$</default_temp_dir>\n");
175       fprintf(fp, "</config>\n");
176       fclose(fp);
177   }
178   //=========================================================================  
179
180
181   //=========================================================================
182   std::string ConfigurationFile::GetExecutablePath()
183   {
184     /// \todo : Think to delete it!
185     char *buf = (char *)malloc(512);
186     char *slash;
187     
188 #if defined(WIN32)
189     GetModuleFileName(NULL, buf, 511);
190     slash = strrchr(buf, '\\');
191     if (slash)
192       {
193         *slash = 0;
194       }
195 #elif defined(__GNUC__)
196     int res;
197     res = readlink("/proc/self/exe", buf, 512);
198     if (res == -1)
199       return "";
200     buf[res] = 0;
201     slash = strrchr(buf, '/');
202     if (slash)
203       {
204         *slash = 0;
205       }
206 #else
207     return "";
208 #endif
209     std::string ret(buf);
210     free(buf);
211     return ret;
212   }
213   //=========================================================================
214
215
216   //=========================================================================
217   void ConfigurationFile::InstallPath ()
218   {
219     
220     /*--------------------------------------------------
221       New policy for bbtk_config.xml :
222       
223       if bbtk_config.xml found in current directory (user is an aware user!)
224       use it!
225       
226       else if bbtk_config.xml found in HOME/.bbtk (user already worked with it)
227       use it!
228       
229       else if bbtk_config.xml.tmp found in /usr/local/bin or c:\\Program Files\\BBTK\\bin
230       copy it as .bbtk/bbtk_config.xml
231       
232       else (nothing installed)
233       create a minimum version in HOME/.bbtk
234       ----------------------------------------------------*/
235     
236     
237     // -----------------------------------------------------------------
238 #if defined(__GNUC__)
239     
240     // ------------------ create some usefull strings ----------------
241     // installed bbtk_path
242     char bbtk_path[100];
243     strcpy(bbtk_path, "/usr/local/bin");
244     
245     // rootDirectory
246     char rootDirectory[200];
247     sprintf( rootDirectory,  "%s/.bbtk", getenv("HOME"));
248     
249     // configPath
250     char configPath[200];
251     sprintf(configPath, "%s/bbtk_config.xml",rootDirectory);
252     
253     // makeDir
254     char makeDir[250];
255     sprintf( makeDir, "mkdir \"%s\" ", rootDirectory);
256     
257     // configXmlTmp
258     char configXmlTmp[250]; 
259     sprintf(configXmlTmp, "%s/bbtk_config.xml.tmp", bbtk_path);
260     
261     // copyFile
262     char copyFile[250];
263     
264     if (!Utilities::FileExists(configXmlTmp)) // bbtk_config.xml.tmp not found (not installed)
265       {  
266         if (!Utilities::FileExists(rootDirectory)) // .bbtk not found
267           {
268             system(makeDir);  // create .bbtk
269           }
270         
271         // if "bbtk_path/bbtk_config.xml.tmp" doesn't exist, hard-create a minimum version in .bbtk
272         CreateConfigXML( rootDirectory );// create .bbtk
273       }
274     else
275       {
276         sprintf(copyFile,"cp %s  %s/bbtk_config.xml ",configXmlTmp,rootDirectory );
277         if (!Utilities::FileExists(rootDirectory))
278           {
279             //std::cout << "makeDir[" << makeDir << "]" << std::endl;
280             system(makeDir);
281           }
282         
283         if (!Utilities::FileExists(configPath))
284           {
285             system(copyFile);
286           }
287       }
288     return;
289     
290     // ------------------------------------------------------------------
291 #elif defined(WIN32)
292     
293     
294     // installed bbtk_path
295     char bbtk_path[100];
296     strcpy(bbtk_path, "\"c:\\Program Files\\BBTK\\bin\"");
297     char bbtk_path2[100];
298     strcpy(bbtk_path2, "c:\\Program Files\\BBTK\\bin");
299     
300     // rootDirectory
301     char rootDirectory[200];  
302     sprintf(rootDirectory, "%s\\.bbtk",getenv("USERPROFILE"));
303     //  std::cout << "[" << rootDirectory << "]" << std::endl;
304     
305     // configPath
306     char configPath[200];
307     sprintf(configPath, "%s\\bbtk_config.xml",rootDirectory);
308     
309     // makeDir
310     char makeDir[250];
311     sprintf( makeDir, "mkdir \"%s\" ", rootDirectory);
312     
313     // configXmlTmp
314     char configXmlTmp[250]; 
315     sprintf(configXmlTmp, "%s\\bbtk_config.xml.tmp", bbtk_path2);
316     
317     // copyFile
318     char copyFile[250];
319     
320     if (!Utilities::FileExists(configXmlTmp)) // bbtk_config.xml.tmp not found
321       {
322         if (!Utilities::FileExists(rootDirectory)) // .bbtk not found
323           {
324             system(makeDir);  // create .bbtk
325           }
326         
327         // if "bbtk_path/bbtk_config.xml.tmp" doesn't exist, hard-create a minimum version in .bbtk
328         CreateConfigXML( rootDirectory );// create .bbtk
329         return;
330       }  
331     
332     sprintf(copyFile,"copy %s\\bbtk_config.xml.tmp \"%s\"\\bbtk_config.xml ",bbtk_path,rootDirectory );
333     
334     int attribs = GetFileAttributes (rootDirectory);
335     bbtkMessage("Config",1,std::hex << attribs << " " << FILE_ATTRIBUTE_DIRECTORY << std::endl);
336     if ( attribs != 0xFFFFFFFF)
337       {
338         if ((attribs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY ) /// \TODO : check !
339           {
340             if ( GetFileAttributes( configPath ) == 0xFFFFFFFF)
341               {
342                 system(copyFile);  
343               } 
344           }
345       } 
346     else 
347       {
348         system(makeDir);
349         system(copyFile); 
350       }    
351     return;  
352     // ------------------------------------------------------------------    
353 #else
354 /// \todo  ConfigurationFile::InstallPath() : exit when for not WIN32 and not__GNUC__
355
356   return;    
357 #endif
358
359 }
360   //=========================================================================
361
362
363
364   //=========================================================================
365   // Gets the list of directories holding bb scripts, packages, dll, ... from the xml file
366   //      bbtk_config.xml
367   
368   void ConfigurationFile::Read(const std::string& filename)
369   {
370     
371     bbtkDebugMessage("Config",1,"ConfigurationFile::Read(" <<filename << ")" << std::endl);
372     
373     mConfig_xml_full_path = filename;
374     XMLResults* res = new XMLResults;
375     XMLNode BB = XMLNode::parseFile((XMLCSTR)filename.c_str(),(XMLCSTR)"config",res);
376     
377     if ( res->error != eXMLErrorNone ) 
378       {
379         std::string mess = GetErrorMessage(res,filename);
380         delete res;
381         bbtkDebugMessage("Config",1,mess<< std::endl);
382         bbtkError(mess);
383       }
384     delete res;
385     
386     bbtkDebugMessage("Config",1,"OK" << std::endl);
387   
388     int i,j;
389     
390     // Description
391     for (i=0,j=0; i<BB.nChildNode((XMLCSTR)"description"); i++) 
392       {
393         std::string val;
394         GetTextOrClear(BB.getChildNode((XMLCSTR)"description",&j),val);
395         mDescription += val;
396       }    
397     
398     // Url
399     if( BB.nChildNode((XMLCSTR)"url") ) 
400       GetTextOrClear(BB.getChildNode((XMLCSTR)"url"),mUrl);
401     
402     // Data_Path
403     if( BB.nChildNode((XMLCSTR)"data_path") ) 
404       GetTextOrClear(BB.getChildNode((XMLCSTR)"data_path"),mData_path);
405     
406     // install_path
407     //  if( BB.nChildNode((XMLCSTR)"install_path") )
408     //   GetTextOrClear(BB.getChildNode((XMLCSTR)"install_path"),mInstall_path);
409     
410     // add user bbs paths
411     for (i=0,j=0; i<BB.nChildNode((XMLCSTR)"bbs_path"); i++) 
412       {
413         std::string val;
414         GetTextOrClear(BB.getChildNode((XMLCSTR)"bbs_path",&j),val);
415         mBbs_paths.push_back(val);
416       }
417     
418     // package_paths
419     
420     // add user package path
421     for (i=0,j=0; i<BB.nChildNode((XMLCSTR)"package_path"); i++) 
422       {
423         std::string val;
424         GetTextOrClear(BB.getChildNode((XMLCSTR)"package_path",&j),val);
425         mPackage_paths.push_back(val);
426       }
427     
428     // default_temp_dir
429     if( BB.nChildNode((XMLCSTR)"default_temp_dir") ) 
430       GetTextOrClear(BB.getChildNode((XMLCSTR)"default_temp_dir"),mDefault_temp_dir);
431     
432     if ( mDefault_temp_dir == "$") // no value found in config_xml
433       {
434         size_t pos = mConfig_xml_full_path.find("bbtk_config.xml");
435         mDefault_temp_dir = mConfig_xml_full_path.substr (0,pos); 
436       }    
437
438     GetHelp(2);
439   }
440   //=========================================================================
441   
442
443   //=========================================================================
444   void ConfigurationFile::GetHelp(int level) const
445   {
446     bbtkDebugMessageInc("Config",9,"ConfigurationFile::GetHelp("<<level
447                         <<")"<<std::endl);
448     
449     const std::string config_xml_full_path      = Get_config_xml_full_path();    
450     const std::string description               = Get_description();
451     const std::string url                       = Get_doc_path();
452     const std::string data_path                 = Get_data_path();
453     const std::string default_temp_dir          = Get_default_temp_dir();    
454     const std::string file_separator            = Get_file_separator();    
455     const std::vector<std::string>bbs_paths     = Get_bbs_paths();
456     const std::vector<std::string>package_paths = Get_package_paths();
457     
458     bbtkMessage("Help",level, "============="   << std::endl);           
459     bbtkMessage("Help",level, "Configuration"   << std::endl);
460     bbtkMessage("Help",level, "============="   << std::endl);
461     bbtkMessage("Help",level, "bbtk_config.xml    : [" << config_xml_full_path  << "]" << std::endl); 
462     bbtkMessage("Help",level, "Documentation Path : [" << url             << "]" << std::endl);
463     bbtkMessage("Help",level, "Data Path          : [" << data_path       << "]" << std::endl);
464     bbtkMessage("Help",level, "Temp Directory     : [" << default_temp_dir << "]" << std::endl);
465     bbtkMessage("Help",level, "File Separator     : [" << file_separator  << "]" << std::endl);
466
467     std::vector<std::string>::const_iterator i;
468            
469     bbtkMessage("Help",level, "BBS Paths   " << std::endl);     
470     for (i = bbs_paths.begin(); i!=bbs_paths.end(); ++i )
471     {
472       bbtkMessage("Help",level,"--- ["<<*i<<"]"<<std::endl);
473     }    
474     
475     bbtkMessage("Help",level, "PACKAGE Paths : " << std::endl);     
476     for (i = package_paths.begin(); i!=package_paths.end(); ++i )
477     {
478       bbtkMessage("Help",level,"--- ["<<*i<<"]"<<std::endl);
479     }
480
481     bbtkDebugDecTab("Config",9);
482   }
483   //=========================================================================
484
485
486 } // namespace bbtk