]> Creatis software - bbtk.git/blob - kernel/src/bbtkFactory.cxx
Recreated the complete cvs tree because the project architecture deeply changed
[bbtk.git] / kernel / src / bbtkFactory.cxx
1 /*=========================================================================
2                                                                                 
3 Program:   bbtk
4 Module:    $RCSfile: bbtkFactory.cxx,v $
5 Language:  C++
6
7 Date:      $Date: 2008/01/22 15:02:00 $
8 Version:   $Revision: 1.1.1.1 $
9                                                                                 
10
11 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
12 l'Image). All rights reserved. See doc/license.txt or
13 http://www.creatis.insa-lyon.fr/Public/bbtk/License.html for details.
14
15 This software is distributed WITHOUT ANY WARRANTY; without even
16 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
17 PURPOSE.  See the above copyright notices for more information.
18
19 =========================================================================*/
20 /**
21  *\file
22  *\brief  Class bbtk::Factory : can load and unload dynamic libraries containing 
23  *        black boxes packages and create instances of the black boxes registered 
24  *       in the packages loaded.
25  */
26 #include "bbtkFactory.h"
27 #include "bbtkMessageManager.h"
28 #include "bbtkConnection.h"
29 #include "bbtkConfigurationFile.h"
30
31 #include <sys/stat.h> // for struct stat stFileInfo
32
33 #if defined(_WIN32)
34 #include <direct.h> // for getcwd
35 #endif
36
37
38 // was in gdcm ...
39 /*
40 #ifdef _MSC_VER
41 #   define getcwd _getcwd
42 #endif
43
44 #if defined(_MSC_VER) || defined(__BORLANDC__)
45 #   include <direct.h>
46 #else
47 #   include <unistd.h>
48 #endif
49
50 */
51
52
53 namespace bbtk
54 {
55   typedef Package* (*PackageAccessor)();
56   typedef void (*PackageDeleteFunction)();
57
58
59   //===================================================================
60   /// Default ctor
61   Factory::Factory()
62   {
63     bbtkDebugMessage("Core",7,"Factory::Factory()"<<std::endl);
64   }
65   //===================================================================
66
67   //===================================================================
68   /// Dtor
69   Factory::~Factory()
70   {
71     bbtkDebugMessageInc("Core",7,"Factory::~Factory()"<<std::endl);
72     CloseAllPackages();
73     bbtkDebugDecTab("Core",7);
74   }
75   //===================================================================
76
77
78   //===================================================================
79   void Factory::CloseAllPackages()
80   {
81     bbtkDebugMessageInc("Core",7,"Factory::CloseAllPackages()"<<std::endl);
82     while (mPackageMap.begin() != mPackageMap.end())
83       {
84         PackageMapType::iterator i = mPackageMap.begin();
85         ClosePackage(i);
86       }
87     bbtkDebugDecTab("Core",7);
88   }
89   //===================================================================
90
91   //===================================================================
92   void Factory::Reset()
93   {
94     bbtkDebugMessageInc("Core",7,"Factory::Reset()"<<std::endl);
95     CloseAllPackages();
96     bbtkDebugDecTab("Core",7);
97   }
98   //===================================================================
99
100 // --> usefull in many places (at least : ConfigurationFile, Factory, Interpreter)
101 // should be factorized ( "bbtk::Util class ?)
102 /*
103 bool Factory::FileExists(std::string strFilename)
104 bool Factory::IsAtRoot(std::string cwd)
105 std::string Factory::ExtractPackageName(const std::string  &name)
106 std::string Factory::ExpandLibName(const std::string &name, bool verbose)
107 std::string Factory::MakeLibnameFromPath(std::string path, std::string pkgname)
108 bool Factory::CheckIfLibraryContainsPackage(std::string libname,std::string pkgname, bool verbose)
109 */
110
111 // See : http://www.techbytes.ca/techbyte103.html for more O.S.
112 bool Factory::FileExists(std::string strFilename) {
113   struct stat stFileInfo;
114   bool blnReturn;
115   int intStat;
116
117   // Attempt to get the file attributes
118   intStat = stat(strFilename.c_str(),&stFileInfo);
119   if(intStat == 0) {
120     // We were able to get the file attributes
121     // so the file obviously exists.
122     blnReturn = true;
123   } else {
124     // We were not able to get the file attributes.
125     // This may mean that we don't have permission to
126     // access the folder which contains this file. If you
127     // need to do that level of checking, lookup the
128     // return values of stat which will give you
129     // more details on why stat failed.
130     blnReturn = false;
131   }
132
133   return(blnReturn);
134 }
135   
136 // ===================================================================================
137
138   std::string Factory::ExtractPackageName(const std::string  &name, 
139                                           std::string& path)
140   {
141     std::string pkgname;
142     path = "";
143
144     std::string::size_type slash_position = name.find_last_of("/\\");
145     if (slash_position != std::string::npos) 
146       {
147         pkgname = name.substr(slash_position+1,std::string::npos);   
148         path = name.substr(0,slash_position); 
149         //      std::cout << "F:P='"<<path<<"'"<<std::endl;//+1,std::string::npos); 
150       } 
151     else 
152       {
153         pkgname = name;  
154       }      
155           
156     // remove {.so | dll} if any
157     std::string::size_type dot_position = pkgname.find_last_of('.');      
158     if (dot_position != std::string::npos){
159       pkgname = pkgname.substr(0,dot_position);
160     }      
161 #if defined(__GNUC__)
162     
163     // GCC mechanism
164     // shared lib name = libbb<name>.so
165
166       // remove {libbb} if any
167     if (memcmp ( pkgname.c_str(), "libbb", 5) == 0) {
168       pkgname =  pkgname.substr(5, pkgname.length());
169     }
170       /*
171       /// \ \todo     what would happen if (stupid) user names his package 'libbb' ?!?
172       /// \ --> Should be forbidden!
173       */
174 #elif defined(_WIN32)
175
176        // WIN 32 mechanism
177        // shared lib name = <name>.dll
178
179      // remove {bb} if any
180     if (memcmp (pkgname.c_str(), "bb", 2) == 0) {
181        pkgname =  pkgname.substr(2, pkgname.length());  
182     } 
183          
184      /*
185      /// \ \todo     what would happen if (stupid) user names his package 'bb' ?!?
186      /// \ --> Should be forbidden!
187      */
188 #else
189     bbtkError("neither __GNUC__ nor _WIN32 ?!? How did you compile ?");
190 #endif      
191     return pkgname;
192   }
193   
194 // ===================================================================================
195
196   std::string Factory::ExpandLibName(const std::string &name, bool verbose)
197   {
198      // -----   Think of expanding path name ( ./ ../ ../../ )
199
200     char buf[2048]; // for getcwd
201     char * currentDir = getcwd(buf, 2048);
202     std::string cwd(currentDir);
203     std::string libname(name);
204     
205     // tooHigh : true is user supplies a library pathname with too many "../"
206     bool tooHigh = false;
207
208     if ( name[0] == '/' ||  name[0] == '\\' )
209     {
210
211       return(libname);
212     } 
213     else if  (name[0] == '.' && (name[1] == '/' || name[1] == '\\') ) 
214     {
215       libname = cwd  + ConfigurationFile::GetInstance().Get_file_separator () + name.substr(2, name.length());
216       return(libname);  
217     } 
218     else if ( name[0] == '.' &&  name[1] == '.' && (name[2] == '/' || name[2] == '\\') ) 
219     {       
220       if ( IsAtRoot(cwd) )  // hope it gets / (for Linux),  C: D: (for Windows)
221       {  
222      // if we are already at / or c: --> hopeless  
223          if (verbose)
224            std::cout << "   File path [" <<  name << "] doesn't exist" << std::endl;
225          tooHigh = true;
226       }
227       else
228       {
229          // iterate on ../ and go up from the current working dir!
230          std::string a(name); 
231          bool alreadyProcessRoot = false;                
232          for(;;) 
233          { 
234             std::string::size_type slash_position = cwd.find_last_of(ConfigurationFile::GetInstance().Get_file_separator ());
235             if (slash_position != std::string::npos) {
236               if (slash_position == 0)
237                slash_position = 1;  
238               cwd = cwd.substr(0,slash_position/*+1*/);
239               a =  a.substr(3, name.length());  // remove ../  
240               if (a == "" || alreadyProcessRoot)
241               {
242                 if (verbose)
243                   std::cout << "   File path [" <<  name << "] doesn't exist" << std::endl;
244                 tooHigh = true;
245                 break;
246               }
247               libname =  cwd;
248               char c = cwd[cwd.size()-1];
249               if (c != '/' && c != '\\' )
250                 libname += ConfigurationFile::GetInstance().Get_file_separator ();
251               libname += a;
252                           
253               if ( a[0] != '.' ) // if . (probabely ../), loop again
254                 break;
255                
256               if (IsAtRoot(cwd))
257                 alreadyProcessRoot = true;                            
258             }                  
259          } // end iterating on ../
260       }
261       if (tooHigh)
262          libname="";
263 //  std::cout << "=======================================3 libname [" << libname << "]" << std::endl;
264          
265       return (libname);
266       
267     }  // -----   End of expanding path name   ( ./ ../ ../../ )
268     // avoid warnings
269     return(""); // will never get here!
270   } 
271    
272 // ===================================================================================
273
274   std::string Factory::MakeLibnameFromPath(std::string path, std::string pkgname)
275   {
276     std::string libname = path;
277     char c = path[path.size()-1];    
278 #if defined(__GNUC__)
279        if (c != '/')
280           libname += "/libbb";
281        libname += pkgname;
282        libname += ".so";
283          
284 #elif defined(_WIN32)
285        if (c != '\\')
286           libname = path+"\\bb";
287        libname += pkgname;
288        libname += ".dll";
289 #endif
290     return libname;    
291   }
292    
293 // ===================================================================================
294
295
296   bool  Factory::IsAtRoot(std::string cwd)
297   {
298     if ( cwd == "/"                             // hope it gets /     (for Linux)
299         || (cwd.size() <= 3 && cwd[1] == ':') ) // hope it gets C: D: (for Windows)
300       return (true);
301     else
302       return(false);
303 }
304 // ===================================================================================
305
306   bool Factory::DoLoadPackage(std::string libname,
307                               std::string pkgname, 
308                               std::string path, 
309                               bool verbose)
310   {
311
312 #if defined(__GNUC__)
313
314         void *handler;            
315         handler = dlopen(libname.c_str(), 
316                                      BBTK_RTLD_TIME | BBTK_RTLD_SCOPE );
317         if (!handler)
318         {
319           if (verbose) {
320             std::cout <<"[" <<libname<<"] can't be open" << std::endl;
321             std::cout << "   " <<dlerror() << std::endl;
322           }
323           return false; // try next path
324         }
325       
326         if (verbose)
327           std::cout <<"   -->[" <<libname<<"] found" << std::endl;
328
329       // Loads the Package accessor
330
331         std::string getpackname(pkgname);
332         getpackname += "GetPackage";
333         void *getpack = dlsym(handler, getpackname.c_str());
334         if (!getpack)
335         {
336           dlclose(handler);
337           bbtkError("GetPackage : could not load package \""<<pkgname
338                    <<"\" [symbol "<<getpackname<<"] :"<<dlerror());
339         }
340
341         // Verifies that the Package delete function is present
342         std::string delfname(pkgname);
343         delfname += "DeletePackage";
344         void *delf = dlsym(handler, delfname.c_str());
345         if (!delf)
346         {
347           dlclose(handler);
348           bbtkError("DeletePackage : could not load package \""<<pkgname
349                     <<"\" [symbol "<<delfname<<"] :"<<dlerror());
350         } 
351
352 #elif defined(_WIN32)
353
354         HINSTANCE handler;
355      
356         SetErrorMode(0);
357         handler = LoadLibrary(libname.c_str());
358         if (!handler){
359           if (verbose)
360             std::cout <<"   no handler for [" <<libname<<"];" << std::endl;     
361           return false;// Problem with the found library
362         }
363         if (verbose)
364           std::cout <<"   --->[" <<libname<<"] found" << std::endl;
365
366     // Loads the Package accessor
367
368         std::string getpackname(pkgname);
369         getpackname += "GetPackage";
370         void *getpack = GetProcAddress(handler, getpackname.c_str());
371         if (!getpack)
372         {
373           FreeLibrary(handler);
374           bbtkError("[1]could not load package \""<<pkgname
375           <<"\" : "<<getpackname<<" symbol not found (is it a bbtk package lib ?)");
376           // look how to get the error message on win
377               //<<dlerror());
378
379         }
380         // Verifies that the Package delete function is present
381         std::string delfname(pkgname);
382         delfname += "DeletePackage";
383         void *delf = GetProcAddress(handler, delfname.c_str());
384         if (!delf)
385         {
386           FreeLibrary(handler);
387           bbtkError("[2]could not load package \""<<pkgname
388                      <<"\" : "<<delfname<<" symbol not found (is it a bbtk package lib ?)");
389           // look how to get the error message on win
390           //<<dlerror());
391         } 
392 #else
393         bbtkError("neither __GNUC__ nor _WIN32 ?!? How did you compile ?");
394 #endif   
395   
396     // Stores the package
397         PackageInfoType pack;
398         pack.mDynamicLibraryHandler = handler;
399     // Invokes the accessor to the PackageUnit pointer
400         pack.mPackage = ((PackageAccessor)getpack)();
401
402         mPackageMap[pkgname] = pack;
403
404     // Test bbtk build version ok
405         if ( pack.mPackage->GetBBTKVersion() != bbtk::GetVersion() )
406         {
407           std::string v(pack.mPackage->GetBBTKVersion());
408           UnLoadPackage(pkgname);
409           bbtkError(" package build with bbtk version "
410                     << v
411                     << " whereas application build with version "
412                     << bbtk::GetVersion());
413         }
414
415         std::string separator = 
416           ConfigurationFile::GetInstance().Get_file_separator ();
417         //BBTK_STRINGIFY_SYMBOL(BBTK_DOC_REL_PATH)
418         std::string docreldoc = separator + "packages" + separator + pkgname 
419           + separator + "bbdoc" + separator + "index.html";
420         std::string reldoc = ".." + separator + ".." + separator 
421           + ".." + docreldoc;
422         std::string doc = path + separator + ".." + separator
423           + BBTK_STRINGIFY_SYMBOL(BBTK_DOC_REL_PATH) 
424           + docreldoc; 
425         std::cout << "doc='"<<doc<<"'"<<std::endl;
426         
427         pack.mPackage->SetDocURL(doc);
428         pack.mPackage->SetDocRelativeURL(reldoc);
429         
430     //===================================================================
431         bbtkMessage("Output",2,pack.mPackage->GetName()<<" "
432            <<pack.mPackage->GetVersion()
433            <<" (bbtk "
434            <<pack.mPackage->GetBBTKVersion()<<") "
435            <<pack.mPackage->GetAuthor() 
436            <<std::endl);
437         bbtkMessage("Output",2,pack.mPackage->GetDescription()<<std::endl);
438     //===================================================================
439
440         bbtkDebugDecTab("Core",7);
441         return true;
442   }
443
444  //===================================================================
445   /// \brief Loads a package.
446   ///
447   /// The name is the system-independant name of the package (the name of the instance of bbtk::Package).
448   /// Tries to open the dynamic library :
449   /// - "libbb<name>.so" for linux systems,
450   /// - "bb<name>.dll" for windows systems.
451   /// If it succeeds, then tries to load the symbols "<name>GetPackage" and "<name>DeletePackage".
452   /// "<name>GetPackage" is called to get the pointer on the bbtk::Package of the library
453   /// ("<name>DeletePackage" is not used, its presence is just checked before loading the package).
454
455   /// now, filename is only the last name (no longer the full name!)
456   /// it will be searched within *all* the paths given in bbtk_config.xml
457
458   /// verbose = true (set by "config v") displays the loading process
459   void Factory::LoadPackage( const std::string& name,
460                              bool use_configuration_file, bool verbose)
461   {
462   // Note : in the following :
463   // name : the user supplied name 
464   //      - abreviated name    e.g.       pkg   pkg.so   libbpkg   libbbpkg.so 
465   //      - relative full name e.g.       ./libbbpkg.so   ../../libbbpkg.so 
466   //      - absolute full name e.g.       /home/usrname/proj/lib/libbbpkg.so
467   //          same for Windows, with      c:, d: ...
468   //
469     bbtkDebugMessageInc("Core",7,"Factory::LoadPackage(\""<<name<<"\")"<<std::endl);    
470     bbtkMessage("Debug",1,"Factory::LoadPackage(\""<<name<<"\")"<<std::endl);    
471     bbtkMessage("Debug",1,"use_configuration_file [" 
472                 << use_configuration_file << "]" << std::endl);
473   
474     std::vector<std::string> package_paths;
475     std::string libname;  // full path library name
476     std::string pkgname;  // e.g. libbb<pkgname>.so
477     
478     std::string upath;
479     pkgname = ExtractPackageName(name,upath);
480
481     bbtkMessage("Debug",1,"Package name ["<<pkgname<<"]"<<std::endl);
482     bbtkMessage("Debug",1,"Package path ["<<upath<<"]"<<std::endl);
483
484     // no loading package if already loaded
485     PackageMapType::iterator iUnload;
486     iUnload = mPackageMap.find(pkgname);
487     if (iUnload != mPackageMap.end()) 
488     {
489       bbtkMessage("Output",2,"["<<pkgname<<"] already loaded"<<std::endl);
490       return; 
491     }
492     
493    // If path provided by user will be the first scanned : 
494     // push it into vector of paths
495     if (upath.length()>0) package_paths.push_back(upath);
496
497     // Add the path of config file 
498     if (use_configuration_file)
499     {
500       std::vector<std::string>::const_iterator pi;
501       for (pi =ConfigurationFile::GetInstance().Get_package_paths().begin();
502                 pi!=ConfigurationFile::GetInstance().Get_package_paths().end();
503               ++pi)
504              package_paths.push_back(*pi);
505     }
506  
507    
508     bool ok = false; 
509     bool foundFile = false;    
510
511     std::vector<std::string>::iterator i;
512     for (i=package_paths.begin();i!=package_paths.end();++i)
513       {
514         foundFile = false;    
515              std::string path = *i;
516         
517         // we *really* want '.' to be the current working directory
518         if (path == ".") {
519           char buf[2048]; // for getcwd
520           char * currentDir = getcwd(buf, 2048);
521           std::string cwd(currentDir);        
522           path = currentDir;
523         }
524         
525         libname = MakeLibnameFromPath(path, pkgname);
526         
527              bbtkMessage("Debug",2,"-> Trying to load ["<<libname<<"]"<<std::endl);
528
529       // Check if library exists           
530         if ( !FileExists(libname) )
531         {
532         // The following is *NOT* a debug time message :
533         // It's a user intended message.
534         // Please don't remove it.
535               if (verbose)
536                  std::cout <<"   [" <<libname <<"] : doesn't exist" <<std::endl;
537             continue;  // try next path
538         }
539         foundFile = true; 
540
541       // Try to Load the library
542          
543         ok = DoLoadPackage( libname, pkgname, path, verbose);
544         if (ok)
545              {
546                 bbtkMessage("Debug",2,"   OK"<<std::endl);
547                 break; // a package was found; we stop iterating
548              }
549     } //------------------ // end for ( package_paths.begin();i!=package_paths.end() )
550       //  }
551
552     if( !ok )  // nothing was loaded
553     {
554       if (!foundFile)
555       {
556         bbtkError("could not find package ["<<pkgname<< "]");
557       }
558       else
559       {
560 #if defined(__GNUC__)
561         bbtkError("could not load package \""<< pkgname
562                   <<"\" :" << std::endl << "   " <<dlerror());
563 #elif defined(_WIN32)
564         bbtkError("could not load package \""<<pkgname
565                  <<"\" : " << std::endl << "   " <<libname<<" not found");
566
567     // look how to get the error message on win
568     //<<dlerror());
569     // it is the bordel !! (the bloody fucking bordel, you mean?)
570     // look : http://msdn2.microsoft.com/en-us/library/ms680582.aspx
571 #endif
572       }
573     }
574     bbtkMessage("Output",2,"[" << libname << "] loaded" << std::endl);
575
576   }
577     
578   //===================================================================
579   /// \brief UnLoads a package.
580   ///
581   /// The package must have been previously loaded by LoadPackage.
582   /// If the entry is found in the map, calls ClosePackage
583  void Factory::UnLoadPackage( const std::string& userSuppliedName )
584   { 
585     std::string path;
586     std::string name = ExtractPackageName(userSuppliedName,path);
587     bbtkDebugMessageInc("Core",7,"Factory::UnLoadPackage(\""
588                        <<name<<"\")"<<std::endl);
589   
590     PackageMapType::iterator i;
591     i = mPackageMap.find(name);
592     if (i == mPackageMap.end()) 
593     {
594       bbtkError("cannot unload package \""<<name
595                 <<"\" : package not loaded !");
596     }
597     ClosePackage(i);
598     bbtkDebugDecTab("Core",7);
599   }
600   //===================================================================
601
602
603   //===================================================================
604   /// \brief Close the package referenced by the iterator 
605   ///
606   /// If it is a dynamically loaded package 
607   /// - Loads and calls the function "<name>DeletePackage" of the dynamic library (responsible for package desallocation)
608   /// - Closes the dynamic library
609   /// - Erases the package entry in the packages map
610   ///
611   /// Else simply erases the package entry in the packages map
612   void Factory::ClosePackage(PackageMapType::iterator& i) 
613   {   
614      bbtkDebugMessageInc("Core",7,"Factory::ClosePackage(\""
615                          <<i->second.mPackage->GetName()
616                         <<"\")"<<std::endl);
617
618      if (i->second.mDynamicLibraryHandler) 
619      {
620  
621       // If it is a dynamically loaded package
622       // Loads the Package delete function
623
624         std::string delfname(i->second.mPackage->GetName());
625         delfname += "DeletePackage";
626 #if defined(__GNUC__)     
627         void *delf = dlsym(i->second.mDynamicLibraryHandler, delfname.c_str());
628         if (!delf)
629         {
630            bbtkError("could not close package \""
631                      <<i->second.mPackage->GetName()
632                      <<"\" :"<<dlerror());
633         }    
634 #elif defined(_WIN32)
635         void *delf = GetProcAddress(i->second.mDynamicLibraryHandler, 
636                                  delfname.c_str());
637         if (!delf)
638         {  
639            bbtkError("could not close package \""
640                 <<i->second.mPackage->GetName()
641                 <<"\" : "<<delfname
642                 <<" symbol not found (how did you open it ???");
643                //<<"\" :"<<dlerror());
644         }    
645 #endif     
646
647    // deletes the package
648    ((PackageDeleteFunction)delf)();
649
650    // closes the dl handler
651 #if defined(__GNUC__)  
652     dlclose(i->second.mDynamicLibraryHandler);  
653 #elif defined(_WIN32)
654
655     FreeLibrary(i->second.mDynamicLibraryHandler);
656 #endif
657     }
658     else 
659     {  
660        // If it is a manually inserted package 
661        delete i->second.mPackage;
662     }
663
664     // remove the entry in the map
665     mPackageMap.erase(i);
666     bbtkDebugDecTab("Core",7);
667  }
668   //===================================================================
669
670
671
672   //===================================================================  
673   /// Displays the list of packages loaded
674   void Factory::PrintPackages(bool details, bool adaptors) const
675   {
676     bbtkDebugMessageInc("Core",9,"Factory::PrintPackages"<<std::endl);
677
678     PackageMapType::const_iterator i;
679     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
680     {
681       bbtkMessage("Help",1, i->first << std::endl);
682       if (details) {
683          i->second.mPackage->PrintBlackBoxes(false,adaptors);
684       }
685     }
686
687     bbtkDebugDecTab("Core",9);
688   }
689   //===================================================================
690
691   //===================================================================  
692   /// Displays help on a package
693   void Factory::HelpPackage(const std::string& name/* &userSuppliedName */, bool adaptors) const
694   {
695    // std::string name = ExtractPackageName(userSuppliedName);
696     bbtkDebugMessageInc("Core",9,"Factory::HelpPackage(\""<<name<<"\")"
697                         <<std::endl);
698
699     PackageMapType::const_iterator i = mPackageMap.find(name);
700     if ( i != mPackageMap.end() ) 
701       {
702       bbtkMessage("Help",1, "Package "<<i->first<<" ");
703       if (i->second.mPackage->GetVersion().length()>0)
704         bbtkMessageCont("Help",1,"v" <<i->second.mPackage->GetVersion());
705       if (i->second.mPackage->GetAuthor().length()>0)
706         bbtkMessageCont("Help",1,"- "<<i->second.mPackage->GetAuthor());
707       bbtkMessageCont("Help",1,std::endl);
708       bbtkIncTab("Help",1);
709       bbtkMessage("Help",1,i->second.mPackage->GetDescription()<<std::endl);
710       if (i->second.mPackage->GetNumberOfBlackBoxes()>0) 
711         {
712           bbtkMessage("Help",1, "Black boxes : "<<std::endl);
713           i->second.mPackage->PrintBlackBoxes(true,adaptors);
714         }
715       else 
716         {
717           bbtkMessage("Help",1, "No black boxes"<<std::endl);
718         }
719       bbtkDecTab("Help",1);
720       }
721     else 
722       {
723       bbtkDebugDecTab("Core",9);
724       bbtkError("package \""<<name<<"\" unknown");
725       }
726     
727     bbtkDebugDecTab("Core",9);
728   }
729   //===================================================================
730
731   //===================================================================
732   /// Prints help on the black box of type <name>
733   void Factory::HelpBlackBox(const std::string& name, bool full) const
734   {
735     bbtkDebugMessageInc("Core",9,"Factory::HelpBlackBox(\""<<name<<"\")"
736                         <<std::endl);
737
738     bool found = false;
739     PackageMapType::const_iterator i;
740     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
741       {
742       if (i->second.mPackage->ContainsBlackBox(name)) 
743         {
744           i->second.mPackage->HelpBlackBox(name,full);
745           found = true;
746         }
747       }
748     
749     bbtkDebugDecTab("Core",9);
750     if (!found) 
751       {
752       bbtkError("No package of the factory contains any black box <"
753                  <<name<<">");
754       }
755   }  
756   //===================================================================
757
758
759   //=================================================================== 
760   /// Inserts a package in the factory
761   void Factory::InsertPackage( Package* p )
762   {
763     bbtkDebugMessageInc("Core",9,"Factory::InsertPackage(\""<<
764                         p->GetName()<<"\")"<<std::endl);
765
766     PackageInfoType pack;
767     pack.mDynamicLibraryHandler = 0;
768     
769     pack.mPackage = p;
770
771     mPackageMap[p->GetName()] = pack;
772     bbtkDebugDecTab("Core",9);
773   }
774   //===================================================================
775   
776   //=================================================================== 
777   /// Removes a package from the factory (and deletes it)
778   void Factory::RemovePackage( Package* p )
779   {
780     bbtkDebugMessageInc("Core",9,"Factory::RemovePackage(\""<<
781                         p->GetName()<<"\")"<<std::endl);
782
783     PackageMapType::iterator i;
784     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
785       {
786          if (i->second.mPackage == p) break;
787       };
788     
789     if (i!=mPackageMap.end())
790       {
791       ClosePackage(i);
792       }
793     else 
794       {
795       bbtkError("Factory::RemovePackage(\""<<
796                  p->GetName()<<"\") : package absent from factory");
797       }
798
799     bbtkDebugDecTab("Core",9);
800   }
801   //===================================================================
802   
803
804   //===================================================================
805   /// Creates an instance of a black box of type <type> with name <name>
806   BlackBox* Factory::NewBlackBox(const std::string& type, 
807                                  const std::string& name) const
808   {
809     bbtkDebugMessageInc("Core",7,"Factory::NewBlackBox(\""
810                         <<type<<"\",\""<<name<<"\")"<<std::endl);
811
812     BlackBox* b = 0; 
813     PackageMapType::const_iterator i;
814     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
815       {
816       b = i->second.mPackage->NewBlackBox(type,name);
817       if (b) break; 
818       }
819     if (!b) 
820       {
821        bbtkError("black box type \""<<type<<"\" unknown");
822       } 
823
824     bbtkDebugDecTab("Core",7);
825     return b;
826   }
827   //===================================================================
828
829   //===================================================================
830   /// Creates an instance of a black box of type <type> with name <name>
831   BlackBox* Factory::NewAdaptor(TypeInfo typein,
832                      TypeInfo typeout,
833                      const std::string& name) const
834   {
835     bbtkDebugMessageInc("Core",8,"Factory::NewAdaptor(<"
836                         <<TypeName(typein)<<">,<"
837                         <<TypeName(typeout)<<">,\""
838                         <<name<<"\")"<<bbtkendl);
839
840
841     BlackBox* b = 0; 
842     PackageMapType::const_iterator i;
843     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
844       {
845       b = i->second.mPackage->NewAdaptor(typein,typeout,name);
846       if (b) break; 
847       }
848     if (!b) 
849       {
850       bbtkError("no <"
851           <<TypeName(typein)<<"> to <"
852           <<TypeName(typeout)
853           <<"> adaptor available");
854       } 
855     
856     bbtkDebugDecTab("Core",7);
857     return b; 
858   }
859   //===================================================================
860
861   //===================================================================
862   /// Creates an instance of a connection
863   Connection* Factory::NewConnection(BlackBox* from,
864                                      const std::string& output,
865                                      BlackBox* to,
866                                      const std::string& input) const
867   {
868     bbtkDebugMessage("Core",7,"Factory::NewConnection(\""
869                       <<from->bbGetName()<<"\",\""<<output<<"\",\""
870                       <<to->bbGetName()<<"\",\""<<input
871                       <<"\")"<<std::endl);
872     
873     return new Connection(from,output,to,input);
874     /*  
875        Connection* c;
876     // !!! WARNING : WE NEED TO TEST THE TYPE NAME EQUALITY 
877     // BECAUSE IN DIFFERENT DYN LIBS THE type_info EQUALITY CAN 
878     // BE FALSE (DIFFERENT INSTANCES !)
879   
880     std::string t1 ( from->bbGetOutputType(output).name() );
881     std::string t2 ( to->bbGetInputType(input).name() );
882
883
884     if ( t1 == t2 ) 
885        //from->bbGetOutputType(output) ==
886        // to->bbGetInputType(input) )
887       {
888          c = new Connection(from,output,to,input);
889       }
890     else 
891       {
892          //   std::cout << "Adaptive connection "<<std::endl;
893          std::string name;
894          name = from->bbGetName() + "." + output + "-" 
895                                   + to->bbGetName() + "." + input; 
896
897          BlackBox* b = 0; 
898          PackageMapType::const_iterator i;
899          for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
900          {
901              b = i->second.mPackage->NewAdaptor(from->bbGetOutputType(output),
902                                                   to->bbGetInputType(input),
903                                                   name);
904              if (b) break; 
905          } 
906          if (!b)  
907          {  
908             bbtkError("did not find any <"
909                        <<TypeName(from->bbGetOutputType(output))
910                        <<"> to <"
911                        <<TypeName(to->bbGetInputType(input))
912                        <<"> adaptor");
913          } 
914          c = new AdaptiveConnection(from,output,to,input,b);
915       }
916       bbtkDebugDecTab("Core",7);
917     
918       return c;
919     */
920   }
921   //===================================================================
922
923
924
925   //===================================================================
926   const Package* Factory::GetPackage(const std::string& name) const
927   {
928     bbtkDebugMessageInc("Core",9,"Factory::GetPackage(\""<<name<<"\")"
929                          <<std::endl);
930
931     PackageMapType::const_iterator i = mPackageMap.find(name);
932     if ( i != mPackageMap.end() ) 
933     {
934       bbtkDebugDecTab("Core",9); 
935       return i->second.mPackage;
936     }
937     else 
938     {
939        bbtkDebugDecTab("Core",9);
940        bbtkError("package \""<<name<<"\" unknown");
941     }
942     
943     bbtkDebugDecTab("Core",9);  
944   }
945   //===================================================================
946   
947   //===================================================================
948   Package* Factory::GetPackage(const std::string& name) 
949   {
950     bbtkDebugMessageInc("Core",9,"Factory::GetPackage(\""<<name<<"\")"
951                          <<std::endl);
952
953     PackageMapType::const_iterator i = mPackageMap.find(name);
954     if ( i != mPackageMap.end() ) 
955     {
956       bbtkDebugDecTab("Core",9); 
957       return i->second.mPackage;
958     }
959     else 
960     {
961        bbtkDebugDecTab("Core",9);
962        bbtkError("package \""<<name<<"\" unknown");
963     }
964     
965     bbtkDebugDecTab("Core",9);  
966   }
967   //===================================================================
968
969   //===================================================================
970   void Factory::WriteDotFilePackagesList(FILE *ff)
971   {
972     bbtkDebugMessageInc("Core",9,"Factory::WriteDotFilePackagesList()"
973                          <<std::endl);
974
975     fprintf( ff , "\n");
976     fprintf( ff , "subgraph cluster_FACTORY {\n");
977     fprintf( ff , "  label = \"PACKAGES\"%s\n",  ";");
978     fprintf( ff , "  style=filled%s\n",";");
979     fprintf( ff , "  color=lightgrey%s\n",";");
980     fprintf( ff , "  rankdir=TB%s\n",";");
981
982     PackageMapType::const_iterator i;
983     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
984     {
985        std::string url = GetPackage(i->first)->GetDocURL();
986        fprintf(ff,"  %s [shape=ellipse, URL=\"%s\"]%s\n",
987                i->first.c_str(),
988                url.c_str(),";" );
989     }
990     fprintf( ff , "}\n\n");
991     bbtkDebugDecTab("Core",9);
992   }
993   //===================================================================
994
995
996   void Factory::ShowGraphTypes(const std::string& name) const
997   {
998     bool found = false;
999     PackageMapType::const_iterator i;
1000     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
1001       {
1002         if (i->second.mPackage->ContainsBlackBox(name)) 
1003           {
1004             std::string separator = ConfigurationFile::GetInstance().Get_file_separator ();
1005             
1006             // Don't pollute the file store with  "doc_tmp" directories ...    
1007             std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_doc_tmp();
1008             std::string directory = "\"" + default_doc_dir + separator + "doc_tmp"  +separator + "\"";
1009             std::string filename2 =  default_doc_dir + separator + "doc_tmp" + separator + "tmp.html"; 
1010             
1011 #if defined(_WIN32)  
1012             std::string command("start \"Titre\" /D ");
1013 #else 
1014             std::string command("gnome-open ");
1015 #endif
1016             command=command + directory +" tmp.html";
1017             FILE *ff;
1018             ff=fopen(filename2.c_str(),"w");
1019             
1020             fprintf(ff,"<html><head><title>TMP</title> <script type=\"text/javascript\"> <!--\n");
1021             fprintf(ff,"  window.location=\"%s#%s\";\n" , i->second.mPackage->GetDocURL().c_str(),name.c_str() );
1022             fprintf(ff,"//--></script></head><body></body></html>\n");
1023             
1024             
1025             //fprintf(ff, "<a  href=\"%s#%s\">Link</a>\n", i->second.mPackage->GetDocURL().c_str(),name.c_str() );
1026             fclose(ff);
1027             system( command.c_str() );      
1028             found = true;
1029           }
1030       }
1031     
1032     bbtkDebugDecTab("Core",9);
1033     if (!found) 
1034       {
1035         bbtkError("No package of the factory contains any black box <"
1036                   <<name<<">");
1037       }
1038   }
1039
1040 }
1041