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