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