]> Creatis software - bbtk.git/blob - kernel/src/bbtkConfigurationFile.cxx
fix default_temp_dir trouble
[bbtk.git] / kernel / src / bbtkConfigurationFile.cxx
1 /*=========================================================================                                                                               
2   Program:   bbtk
3   Module:    $RCSfile: bbtkConfigurationFile.cxx,v $
4   Language:  C++
5   Date:      $Date: 2008/11/03 15:53:31 $
6   Version:   $Revision: 1.20 $
7 =========================================================================*/
8
9 /* ---------------------------------------------------------------------
10
11 * Copyright (c) CREATIS-LRMN (Centre de Recherche en Imagerie Medicale)
12 * Authors : Eduardo Davila, Laurent Guigues, Jean-Pierre Roux
13 *
14 *  This software is governed by the CeCILL-B license under French law and 
15 *  abiding by the rules of distribution of free software. You can  use, 
16 *  modify and/ or redistribute the software under the terms of the CeCILL-B 
17 *  license as circulated by CEA, CNRS and INRIA at the following URL 
18 *  http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html 
19 *  or in the file LICENSE.txt.
20 *
21 *  As a counterpart to the access to the source code and  rights to copy,
22 *  modify and redistribute granted by the license, users are provided only
23 *  with a limited warranty  and the software's author,  the holder of the
24 *  economic rights,  and the successive licensors  have only  limited
25 *  liability. 
26 *
27 *  The fact that you are presently reading this means that you have had
28 *  knowledge of the CeCILL-B license and that you accept its terms.
29 * ------------------------------------------------------------------------ */                                                                         
30
31 /**
32  *\file
33  *\brief Class bbtk::ConfigurationFile
34  */
35
36 #include "bbtkConfigurationFile.h"
37 #include "bbtkMessageManager.h"
38 #include "bbtkXML.h"
39 #include "bbtkUtilities.h"
40
41 #if defined(WIN32)
42 #include <direct.h> // for getcwd
43 #endif
44
45
46
47 namespace bbtk
48 {
49
50   //====================================================================
51   /// Constructor
52   ConfigurationFile::ConfigurationFile()
53   {
54
55         mFile_separator = VALID_FILE_SEPARATOR;
56     
57     // ==> Set system paths 
58     mBin_path = GetExecutablePath();
59 //EED    mInstall_path = mBin_path + mFile_separator + "..";
60     mInstall_path = mBin_path + "/..";
61     // The relative path to the doc folder (=BBTK_DOC_REL_PATH)
62     mDoc_rel_path = BBTK_STRINGIFY_SYMBOL(BBTK_DOC_REL_PATH);
63     // The path to the doc folder (=mInstall_path+"/"+mDoc_rel_path)
64 //EED    mDoc_path = mInstall_path + mFile_separator + mDoc_rel_path;
65     mDoc_path = mInstall_path + "/" + mDoc_rel_path;
66     // The relative path to the doc folder (=BBTK_BBS_REL_PATH)
67     mBbs_rel_path = BBTK_STRINGIFY_SYMBOL(BBTK_BBS_REL_PATH);
68     // The path to the bbs folder (=mInstall_path+"/"+mBbs_rel_path)
69 //EED    mBbs_path = mInstall_path + mFile_separator + mBbs_rel_path;
70     mBbs_path = mInstall_path + "/" + mBbs_rel_path;
71     // The relative path to the rsc folder (=BBTK_RSC_REL_PATH)
72     //   mRsc_rel_path = BBTK_STRINGIFY_SYMBOL(BBTK_RSC_REL_PATH);
73     // The path to the rsc folder (=mInstall_path+"/"+mRsc_rel_path)
74     //   mRsc_path = mInstall_path + mFile_separator + mRsc_rel_path;
75     // The path to the bbtk data folder 
76     // Initialized to mInstall_path+"/"+BBTK_DATA_REL_PATH
77     // But can be overriden by value read from bbtk_config.xml
78 //EED    mData_path = mInstall_path + mFile_separator + BBTK_STRINGIFY_SYMBOL(BBTK_DATA_REL_PATH);
79     mData_path = mInstall_path + "/" + BBTK_STRINGIFY_SYMBOL(BBTK_DATA_REL_PATH);
80
81         Utilities::replace( mBin_path           , INVALID_FILE_SEPARATOR , VALID_FILE_SEPARATOR);
82         Utilities::replace( mInstall_path       , INVALID_FILE_SEPARATOR , VALID_FILE_SEPARATOR);
83         Utilities::replace( mDoc_rel_path       , INVALID_FILE_SEPARATOR , VALID_FILE_SEPARATOR);
84         Utilities::replace( mDoc_path           , INVALID_FILE_SEPARATOR , VALID_FILE_SEPARATOR);
85         Utilities::replace( mBbs_path           , INVALID_FILE_SEPARATOR , VALID_FILE_SEPARATOR);
86         Utilities::replace( mData_path          , INVALID_FILE_SEPARATOR , VALID_FILE_SEPARATOR);
87
88     bbtkMessage("Config",1," ==> bin    : '"<<mBin_path<<"'"<<std::endl);
89     bbtkMessage("Config",1," ==> prefix : '"<<mInstall_path<<"'"<<std::endl);
90     bbtkMessage("Config",1," ==> doc    : '"<<mDoc_path<<"'"<<std::endl);
91     bbtkMessage("Config",1," ==> bbs    : '"<<mBbs_path<<"'"<<std::endl);
92     bbtkMessage("Config",1," ==> data   : '"<<mData_path<<"'"<<std::endl);
93
94
95
96     
97     // bbs_paths
98     // always add "." (current working directory) at the begining
99         mBbs_paths.push_back( "." ); 
100     // add system bbs path 
101     mBbs_paths.push_back(mBbs_path);
102     // add toolsbbtk/appli 
103 //EED    std::string toolsappli_rel_path(mFile_separator);
104     std::string toolsappli_rel_path("/");
105 //EED    toolsappli_rel_path +=  "toolsbbtk" + mFile_separator + "appli";
106     toolsappli_rel_path +=  "toolsbbtk/appli";
107     //
108     //-----------------------------------------------------------
109     // LG : REMOVE BUGGY PATH WITH include *:
110     // 
111     //    mBbs_paths.push_back(mBbs_path + toolsappli_rel_path);
112     //-----------------------------------------------------------
113     int iStrVec,sizeStrVec;
114     
115     sizeStrVec = mBbs_paths.size();
116     for (iStrVec=0;iStrVec<sizeStrVec;iStrVec++){
117       Utilities::replace( mBbs_paths[iStrVec] , INVALID_FILE_SEPARATOR , VALID_FILE_SEPARATOR);
118     }
119
120     
121     // always add "." (current working directory) at the begining
122     mPackage_paths.push_back(".");   
123     // add system bin path (for build tree / standalone folder install)
124     mPackage_paths.push_back(mBin_path);
125     // add system lib path (for install tree)
126 //EED    mPackage_paths.push_back(mInstall_path + mFile_separator + "lib");
127     mPackage_paths.push_back(mInstall_path + "/lib");
128 #ifdef WIN32
129     // add bin/Debug bin/Release paths (for build/install tree)
130 //EED    mPackage_paths.push_back(mBin_path + mFile_separator + "Debug");
131     mPackage_paths.push_back(mBin_path + "/Debug");
132 //EED    mPackage_paths.push_back(mBin_path + mFile_separator + "Release");
133     mPackage_paths.push_back(mBin_path + "/Release");
134 #endif
135
136         sizeStrVec = mPackage_paths.size();
137         for (iStrVec=0;iStrVec<sizeStrVec;iStrVec++){
138                 Utilities::replace( mPackage_paths[iStrVec] , INVALID_FILE_SEPARATOR , VALID_FILE_SEPARATOR);
139         }
140
141
142
143     GetHelp(2);
144    
145     // ==> First we look for bbtk_config.xml in "."
146     char buf[2048];
147     const char *currentDir = getcwd(buf, 2048);
148     
149     if( !currentDir )
150       {
151         std::cerr << "Path was too long to fit on 2048 bytes ?!?" << std::endl;
152         // \todo : what else?
153         // How abort a constructor and warn the caller function?
154         // LG : throw an exception 
155       }
156     
157 //    std::string configXmlFullPathName = currentDir + mFile_separator + "bbtk_config.xml";
158     std::string configXmlFullPathName = currentDir ;
159                 configXmlFullPathName += "/bbtk_config.xml";
160         Utilities::replace( configXmlFullPathName , INVALID_FILE_SEPARATOR , VALID_FILE_SEPARATOR);
161
162     if ( Utilities::FileExists( configXmlFullPathName ))
163       {
164         bbtkMessage("Config",1, "ConfigurationFile : [" << configXmlFullPathName << 
165                     "] found in current directory" << std::endl); 
166         //Read(configXmlFullPathName.c_str());
167         // traiter le fichier local     
168       }
169     
170     // ==> Then we look for bbtk_config.xml in ".bbtk"
171     else 
172       {
173         configXmlFullPathName = Utilities::MakeUserSettingsFullFileName("bbtk_config.xml");
174         if (!Utilities::FileExists( configXmlFullPathName ))
175           {         
176             // ==> Nothing found, we create bbtk_config.xml in ".bbtk"
177             InstallPath ();
178           }
179       }
180     
181     // In any case, deal with bbtk_config.xml!
182     Read(configXmlFullPathName.c_str());
183   }
184   //=========================================================================
185
186   //=========================================================================
187   /// Destructor
188   ConfigurationFile::~ConfigurationFile()
189   {
190   }
191   //=========================================================================
192   
193
194
195
196   //=========================================================================
197   void ConfigurationFile::CreateConfigXML( char *rootDirectory )
198   {
199     FILE *fp;
200     char configXml[250];
201     sprintf (configXml , "%s/bbtk_config.xml", rootDirectory);
202     bbtkDebugMessage("Config",1, "in CreateConfigXML[" << configXml << "]" << std::endl);
203     fp = fopen (configXml, "w");
204     fprintf(fp, "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n");
205     fprintf(fp, "<config>\n");
206     fprintf(fp, "   <bbs_path>     </bbs_path>\n");
207     fprintf(fp, "   <package_path> </package_path>\n");
208     fprintf(fp, "   <default_temp_dir> $ </default_temp_dir>\n");    
209     fprintf(fp, "</config>\n");
210     fclose(fp);
211   }
212   //=========================================================================  
213
214
215   //=========================================================================
216   std::string ConfigurationFile::GetExecutablePath()
217   {
218     /// \todo : Think to delete it!
219     char *buf = (char *)malloc(512);
220     char *slash;
221     
222 #if defined(WIN32)
223     GetModuleFileName(NULL, buf, 511);
224     slash = strrchr(buf, '\\');
225     if (slash)
226       {
227         *slash = 0;
228       }
229 #elif defined(__GNUC__)
230     int res;
231     res = readlink("/proc/self/exe", buf, 512);
232     if (res == -1)
233       return "";
234     buf[res] = 0;
235     slash = strrchr(buf, '/');
236     if (slash)
237       {
238         *slash = 0;
239       }
240 #else
241     return "";
242 #endif
243     std::string ret(buf);
244     free(buf);
245     return ret;
246   }
247   //=========================================================================
248
249
250   //=========================================================================
251   void ConfigurationFile::InstallPath ()
252   {
253     
254     /*--------------------------------------------------
255       New policy for bbtk_config.xml :
256       
257       if bbtk_config.xml found in current directory (user is an aware user!)
258       use it!
259       
260       else if bbtk_config.xml found in HOME/.bbtk (user already worked with it)
261       use it!
262       
263       else if bbtk_config.xml.tmp found in /usr/local/bin or c:\\Program Files\\BBTK\\bin
264       copy it as .bbtk/bbtk_config.xml
265       
266       else (nothing installed)
267       create a minimum version in HOME/.bbtk
268       ----------------------------------------------------*/
269     
270     
271     // -----------------------------------------------------------------
272 #if defined(__GNUC__)
273     
274     // ------------------ create some usefull strings ----------------
275     // installed bbtk_path
276     char bbtk_path[100];
277     strcpy(bbtk_path, "/usr/local/bin");
278     
279     // rootDirectory
280     char rootDirectory[200];
281     sprintf( rootDirectory,  "%s/.bbtk", getenv("HOME"));
282     
283     // configPath
284     char configPath[200];
285     sprintf(configPath, "%s/bbtk_config.xml",rootDirectory);
286     
287     // makeDir
288     char makeDir[250];
289     sprintf( makeDir, "mkdir \"%s\" ", rootDirectory);
290     
291     // configXmlTmp
292     char configXmlTmp[250]; 
293     sprintf(configXmlTmp, "%s/bbtk_config.xml.tmp", bbtk_path);
294     
295     // copyFile
296     char copyFile[250];
297     
298     if (!Utilities::FileExists(configXmlTmp)) // bbtk_config.xml.tmp not found (not installed)
299       {  
300         if (!Utilities::FileExists(rootDirectory)) // .bbtk not found
301           {
302             system(makeDir);  // create .bbtk
303           }
304         
305         // if "bbtk_path/bbtk_config.xml.tmp" doesn't exist, hard-create a minimum version in .bbtk
306         CreateConfigXML( rootDirectory );// create .bbtk
307       }
308     else
309       {
310         sprintf(copyFile,"cp %s  %s/bbtk_config.xml ",configXmlTmp,rootDirectory );
311         if (!Utilities::FileExists(rootDirectory))
312           {
313             //std::cout << "makeDir[" << makeDir << "]" << std::endl;
314             system(makeDir);
315           }
316         
317         if (!Utilities::FileExists(configPath))
318           {
319             system(copyFile);
320           }
321       }
322     return;
323     
324     // ------------------------------------------------------------------
325 #elif defined(WIN32)
326     
327     
328     // installed bbtk_path
329     char bbtk_path[100];
330     strcpy(bbtk_path, "\"c:\\Program Files\\BBTK\\bin\"");
331     char bbtk_path2[100];
332     strcpy(bbtk_path2, "c:\\Program Files\\BBTK\\bin");
333     
334     // rootDirectory
335     char rootDirectory[200];  
336     sprintf(rootDirectory, "%s\\.bbtk",getenv("USERPROFILE"));
337     //  std::cout << "[" << rootDirectory << "]" << std::endl;
338     
339     // configPath
340     char configPath[200];
341     sprintf(configPath, "%s\\bbtk_config.xml",rootDirectory);
342     
343     // makeDir
344     char makeDir[250];
345     sprintf( makeDir, "mkdir \"%s\" ", rootDirectory);
346     
347     // configXmlTmp
348     char configXmlTmp[250]; 
349     sprintf(configXmlTmp, "%s\\bbtk_config.xml.tmp", bbtk_path2);
350     
351     // copyFile
352     char copyFile[250];
353     
354     if (!Utilities::FileExists(configXmlTmp)) // bbtk_config.xml.tmp not found
355       {
356         if (!Utilities::FileExists(rootDirectory)) // .bbtk not found
357           {
358             system(makeDir);  // create .bbtk
359           }
360         
361         // if "bbtk_path/bbtk_config.xml.tmp" doesn't exist, hard-create a minimum version in .bbtk
362         CreateConfigXML( rootDirectory );// create .bbtk
363         return;
364       }  
365     
366     sprintf(copyFile,"copy %s\\bbtk_config.xml.tmp \"%s\"\\bbtk_config.xml ",bbtk_path,rootDirectory );
367     
368     int attribs = GetFileAttributes (rootDirectory);
369     bbtkMessage("Config",1,std::hex << attribs << " " << FILE_ATTRIBUTE_DIRECTORY << std::endl);
370     if ( attribs != 0xFFFFFFFF)
371       {
372         if ((attribs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY ) /// \TODO : check !
373           {
374             if ( GetFileAttributes( configPath ) == 0xFFFFFFFF)
375               {
376                 system(copyFile);  
377               } 
378           }
379       } 
380     else 
381       {
382         system(makeDir);
383         system(copyFile); 
384       }    
385     return;  
386     // ------------------------------------------------------------------    
387 #else
388 /// \todo  ConfigurationFile::InstallPath() : exit when for not WIN32 and not__GNUC__
389
390   return;    
391 #endif
392
393 }
394   //=========================================================================
395
396
397
398   //=========================================================================
399   // Gets the list of directories holding bb scripts, packages, dll, ... from the xml file
400   //      bbtk_config.xml
401   
402   void ConfigurationFile::Read(const std::string& filename)
403   {
404     
405     bbtkDebugMessage("Config",1,"ConfigurationFile::Read(" <<filename << ")" << std::endl);
406     
407     mConfig_xml_full_path = filename;
408     XMLResults* res = new XMLResults;
409     XMLNode BB = XMLNode::parseFile((XMLCSTR)filename.c_str(),(XMLCSTR)"config",res);
410     
411     if ( res->error != eXMLErrorNone ) 
412       {
413         std::string mess = GetErrorMessage(res,filename);
414         delete res;
415         bbtkDebugMessage("Config",1,mess<< std::endl);
416         bbtkError(mess);
417       }
418     delete res;
419     
420     bbtkDebugMessage("Config",1,"OK" << std::endl);
421   
422     int i,j;
423     
424     // Description
425     for (i=0,j=0; i<BB.nChildNode((XMLCSTR)"description"); i++) 
426       {
427         std::string val;
428         GetTextOrClear(BB.getChildNode((XMLCSTR)"description",&j),val);
429         mDescription += val;
430       }    
431     
432     // Url
433     if( BB.nChildNode((XMLCSTR)"url") ) 
434       GetTextOrClear(BB.getChildNode((XMLCSTR)"url"),mUrl);
435     
436     // Data_Path
437     if( BB.nChildNode((XMLCSTR)"data_path") ) 
438       GetTextOrClear(BB.getChildNode((XMLCSTR)"data_path"),mData_path);
439     
440     // install_path
441     //  if( BB.nChildNode((XMLCSTR)"install_path") )
442     //   GetTextOrClear(BB.getChildNode((XMLCSTR)"install_path"),mInstall_path);
443     
444     // add user bbs paths
445     for (i=0,j=0; i<BB.nChildNode((XMLCSTR)"bbs_path"); i++) 
446       {
447         std::string val;
448         GetTextOrClear(BB.getChildNode((XMLCSTR)"bbs_path",&j),val);
449         mBbs_paths.push_back(val);
450       }
451     
452     // package_paths
453     
454     // add user package path
455     for (i=0,j=0; i<BB.nChildNode((XMLCSTR)"package_path"); i++) 
456       {
457         std::string val;
458         GetTextOrClear(BB.getChildNode((XMLCSTR)"package_path",&j),val);
459         mPackage_paths.push_back(val);
460       }
461     
462     // default_temp_dir
463     if( BB.nChildNode((XMLCSTR)"default_temp_dir") ) 
464       GetTextOrClear(BB.getChildNode((XMLCSTR)"default_temp_dir"),mDefault_temp_dir);
465     
466     if ( mDefault_temp_dir == "$") // no value found in config_xml
467       {
468         size_t pos = mConfig_xml_full_path.find("bbtk_config.xml");
469         mDefault_temp_dir = mConfig_xml_full_path.substr (0,pos); 
470       }    
471
472     GetHelp(2);
473   }
474   //=========================================================================
475   
476   //=========================================================================
477   bool ConfigurationFile::AddPackagePathsAndWrite( const std::string& path )
478   {
479     bbtkDebugMessageInc("Config",9,
480                         "ConfigurationFile::AddPackagePathsAndWrite("
481                         <<path<<")"<<std::endl);
482     
483      XMLResults* res = new XMLResults;
484     XMLNode BB = 
485       XMLNode::parseFile((XMLCSTR)Get_config_xml_full_path().c_str(),
486                          (XMLCSTR)"config",res);
487     
488     if ( res->error != eXMLErrorNone ) 
489       {
490         std::string mess = GetErrorMessage(res,Get_config_xml_full_path());
491         delete res;
492         bbtkDebugMessage("Config",1,mess<< std::endl);
493         bbtkError(mess);
494       }
495    delete res;
496
497 #ifdef _WIN32
498     std::string bbs_path = path + "/bbs";
499 #else
500     std::string bbs_path = path + "/share/bbtk/bbs" ;
501 #endif
502     XMLNode BBSPATH = BB.addChild((XMLCSTR)"bbs_path");
503     BBSPATH.addText((XMLCSTR)bbs_path.c_str());
504     Utilities::replace(bbs_path, INVALID_FILE_SEPARATOR, VALID_FILE_SEPARATOR);
505     mBbs_paths.push_back(bbs_path);
506  
507 #ifdef _WIN32
508     std::string pack_path = path + "/bin";
509 #else
510     std::string pack_path = path ;
511 #endif
512     XMLNode PACKPATH = BB.addChild((XMLCSTR)"package_path");
513     PACKPATH.addText((XMLCSTR)pack_path.c_str());
514     Utilities::replace(pack_path,INVALID_FILE_SEPARATOR,VALID_FILE_SEPARATOR);
515     mPackage_paths.push_back(pack_path);
516
517 #ifdef _WIN32
518     pack_path = path + "/Debug";
519     PACKPATH = BB.addChild((XMLCSTR)"package_path");
520     PACKPATH.addText((XMLCSTR)pack_path.c_str());
521     Utilities::replace(pack_path,INVALID_FILE_SEPARATOR,VALID_FILE_SEPARATOR);
522     mPackage_paths.push_back(pack_path);
523     pack_path = path + "/Release";
524     PACKPATH = BB.addChild((XMLCSTR)"package_path");
525     PACKPATH.addText((XMLCSTR)pack_path.c_str());
526     Utilities::replace(pack_path,INVALID_FILE_SEPARATOR,VALID_FILE_SEPARATOR);
527     mPackage_paths.push_back(pack_path);
528 #endif
529
530
531     XMLError err = BB.writeToFile((XMLCSTR)Get_config_xml_full_path().c_str());
532     if ( err != eXMLErrorNone ) 
533       {
534         std::string mess = GetErrorMessage(res,Get_config_xml_full_path());
535         bbtkDebugMessage("Config",1,mess<< std::endl);
536         bbtkError(mess);
537       }
538
539     return true;
540   }
541   //=========================================================================
542
543   //=========================================================================
544   void ConfigurationFile::GetHelp(int level) const
545   {
546     bbtkDebugMessageInc("Config",9,"ConfigurationFile::GetHelp("<<level
547                         <<")"<<std::endl);
548     
549     const std::string config_xml_full_path      = Get_config_xml_full_path();    
550     const std::string description               = Get_description();
551     const std::string url                       = Get_doc_path();
552     const std::string data_path                 = Get_data_path();
553     const std::string default_temp_dir          = Get_default_temp_dir();    
554     const std::string file_separator            = Get_file_separator();    
555     const std::vector<std::string>bbs_paths     = Get_bbs_paths();
556     const std::vector<std::string>package_paths = Get_package_paths();
557     
558     bbtkMessage("Help",level, "============="   << std::endl);           
559     bbtkMessage("Help",level, "Configuration"   << std::endl);
560     bbtkMessage("Help",level, "============="   << std::endl);
561     bbtkMessage("Help",level, "bbtk_config.xml    : [" << config_xml_full_path  << "]" << std::endl); 
562     bbtkMessage("Help",level, "Documentation Path : [" << url             << "]" << std::endl);
563     bbtkMessage("Help",level, "Data Path          : [" << data_path       << "]" << std::endl);
564     bbtkMessage("Help",level, "Temp Directory     : [" << default_temp_dir << "]" << std::endl);
565     bbtkMessage("Help",level, "File Separator     : [" << file_separator  << "]" << std::endl);
566
567     std::vector<std::string>::const_iterator i;
568            
569     bbtkMessage("Help",level, "BBS Paths   " << std::endl);     
570     for (i = bbs_paths.begin(); i!=bbs_paths.end(); ++i )
571     {
572       bbtkMessage("Help",level,"--- ["<<*i<<"]"<<std::endl);
573     }    
574     
575     bbtkMessage("Help",level, "PACKAGE Paths : " << std::endl);     
576     for (i = package_paths.begin(); i!=package_paths.end(); ++i )
577     {
578       bbtkMessage("Help",level,"--- ["<<*i<<"]"<<std::endl);
579     }
580
581     bbtkDebugDecTab("Config",9);
582   }
583   //=========================================================================
584
585
586 } // namespace bbtk